Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

Merge remote-tracking branch 'origin/main' into ENG-3639

Carlos Monastyrskib2b33b4f8b2d
diff --git a/.github/workflows/release-standalone-docker-img-postgres-offical.yml b/.github/workflows/release-standalone-docker-img-postgres-offical.yml
index 5c8809eb46..b17d5e50cc 100644
--- a/.github/workflows/release-standalone-docker-img-postgres-offical.yml
+++ b/.github/workflows/release-standalone-docker-img-postgres-offical.yml
@@ -63,6 +63,8 @@ jobs:
build-args: |
POSTHOG_API_KEY=${{ secrets.PUBLIC_POSTHOG_API_KEY }}
INFISICAL_PLATFORM_VERSION=${{ steps.extract_version.outputs.version }}
+ DD_GIT_REPOSITORY_URL=${{ github.server_url }}/${{ github.repository }}
+ DD_GIT_COMMIT_SHA=${{ github.sha }}
infisical-fips-standalone:
name: Build infisical standalone image postgres
diff --git a/.github/workflows/release_helm_gateway.yaml b/.github/workflows/release_helm_gateway.yaml
index 85f61c4c66..7fd0eb03a9 100644
--- a/.github/workflows/release_helm_gateway.yaml
+++ b/.github/workflows/release_helm_gateway.yaml
@@ -35,7 +35,7 @@ jobs:
run: kubectl create namespace infisical-gateway
- name: Create gateway secret
- run: kubectl create secret generic infisical-gateway-environment --from-literal=TOKEN=my-test-token -n infisical-gateway
+ run: kubectl create secret generic infisical-gateway-environment --from-literal=TOKEN=my-test-token --from-literal=INFISICAL_RELAY_NAME=my-test-relay -n infisical-gateway
- name: Run chart-testing (install)
run: |
diff --git a/Dockerfile.standalone-infisical b/Dockerfile.standalone-infisical
index a4e5c150a6..9ca5e1dea9 100644
--- a/Dockerfile.standalone-infisical
+++ b/Dockerfile.standalone-infisical
@@ -173,6 +173,12 @@ COPY --from=frontend-runner /app ./backend/frontend-build
ARG INFISICAL_PLATFORM_VERSION
ENV INFISICAL_PLATFORM_VERSION $INFISICAL_PLATFORM_VERSION
+ARG DD_GIT_REPOSITORY_URL
+ENV DD_GIT_REPOSITORY_URL $DD_GIT_REPOSITORY_URL
+
+ARG DD_GIT_COMMIT_SHA
+ENV DD_GIT_COMMIT_SHA $DD_GIT_COMMIT_SHA
+
ENV PORT 8080
ENV HOST=0.0.0.0
ENV HTTPS_ENABLED false
diff --git a/backend/e2e-test/routes/v2/secret-folder.spec.ts b/backend/e2e-test/routes/v2/secret-folder.spec.ts
new file mode 100644
index 0000000000..a2bed759a2
--- /dev/null
+++ b/backend/e2e-test/routes/v2/secret-folder.spec.ts
@@ -0,0 +1,165 @@
+import { seedData1 } from "@app/db/seed-data";
+
+const createFolder = async (dto: { path: string; name: string }) => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: `/api/v2/folders`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ projectId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ name: dto.name,
+ path: dto.path
+ }
+ });
+ expect(res.statusCode).toBe(200);
+ return res.json().folder;
+};
+
+const deleteFolder = async (dto: { path: string; id: string }) => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v2/folders/${dto.id}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ projectId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ path: dto.path
+ }
+ });
+ expect(res.statusCode).toBe(200);
+ return res.json().folder;
+};
+
+describe("Secret Folder Router", async () => {
+ test.each([
+ { name: "folder1", path: "/" }, // one in root
+ { name: "folder1", path: "/level1/level2" }, // then create a deep one creating intermediate ones
+ { name: "folder2", path: "/" },
+ { name: "folder1", path: "/level1/level2" } // this should not create folder return same thing
+ ])("Create folder $name in $path", async ({ name, path }) => {
+ const createdFolder = await createFolder({ path, name });
+ // check for default environments
+ expect(createdFolder).toEqual(
+ expect.objectContaining({
+ name,
+ id: expect.any(String)
+ })
+ );
+ await deleteFolder({ path, id: createdFolder.id });
+ });
+
+ test.each([
+ {
+ path: "/",
+ expected: {
+ folders: [{ name: "folder1" }, { name: "level1" }, { name: "folder2" }],
+ length: 3
+ }
+ },
+ { path: "/level1/level2", expected: { folders: [{ name: "folder1" }], length: 1 } }
+ ])("Get folders $path", async ({ path, expected }) => {
+ const newFolders = await Promise.all(expected.folders.map(({ name }) => createFolder({ name, path })));
+
+ const res = await testServer.inject({
+ method: "GET",
+ url: `/api/v2/folders`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ query: {
+ projectId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ path
+ }
+ });
+
+ expect(res.statusCode).toBe(200);
+ const payload = JSON.parse(res.payload);
+ expect(payload).toHaveProperty("folders");
+ expect(payload.folders.length >= expected.folders.length).toBeTruthy();
+ expect(payload).toEqual({
+ folders: expect.arrayContaining(expected.folders.map((el) => expect.objectContaining(el)))
+ });
+
+ await Promise.all(newFolders.map(({ id }) => deleteFolder({ path, id })));
+ });
+
+ test("Update a deep folder", async () => {
+ const newFolder = await createFolder({ name: "folder-updated", path: "/level1/level2" });
+ expect(newFolder).toEqual(
+ expect.objectContaining({
+ id: expect.any(String),
+ name: "folder-updated"
+ })
+ );
+
+ const resUpdatedFolders = await testServer.inject({
+ method: "GET",
+ url: `/api/v2/folders`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ query: {
+ projectId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ path: "/level1/level2"
+ }
+ });
+
+ expect(resUpdatedFolders.statusCode).toBe(200);
+ const updatedFolderList = JSON.parse(resUpdatedFolders.payload);
+ expect(updatedFolderList).toHaveProperty("folders");
+ expect(updatedFolderList.folders[0].name).toEqual("folder-updated");
+
+ await deleteFolder({ path: "/level1/level2", id: newFolder.id });
+ });
+
+ test("Delete a deep folder", async () => {
+ const newFolder = await createFolder({ name: "folder-updated", path: "/level1/level2" });
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v2/folders/${newFolder.id}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ projectId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ path: "/level1/level2"
+ }
+ });
+
+ expect(res.statusCode).toBe(200);
+ const payload = JSON.parse(res.payload);
+ expect(payload).toHaveProperty("folder");
+ expect(payload.folder).toEqual(
+ expect.objectContaining({
+ id: expect.any(String),
+ name: "folder-updated"
+ })
+ );
+
+ const resUpdatedFolders = await testServer.inject({
+ method: "GET",
+ url: `/api/v2/folders`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ query: {
+ projectId: seedData1.project.id,
+ environment: seedData1.environment.slug,
+ path: "/level1/level2"
+ }
+ });
+
+ expect(resUpdatedFolders.statusCode).toBe(200);
+ const updatedFolderList = JSON.parse(resUpdatedFolders.payload);
+ expect(updatedFolderList).toHaveProperty("folders");
+ expect(updatedFolderList.folders.length).toEqual(0);
+ });
+});
diff --git a/backend/e2e-test/routes/v2/service-token.spec.ts b/backend/e2e-test/routes/v2/service-token.spec.ts
index 025d9796f6..4f72987cb0 100644
--- a/backend/e2e-test/routes/v2/service-token.spec.ts
+++ b/backend/e2e-test/routes/v2/service-token.spec.ts
@@ -70,7 +70,7 @@ const createServiceToken = async (
const deleteServiceToken = async () => {
const serviceTokenListRes = await testServer.inject({
method: "GET",
- url: `/api/v1/workspace/${seedData1.project.id}/service-token-data`,
+ url: `/api/v1/projects/${seedData1.project.id}/service-token-data`,
headers: {
authorization: `Bearer ${jwtAuthToken}`
}
diff --git a/backend/e2e-test/routes/v4/secrets.spec.ts b/backend/e2e-test/routes/v4/secrets.spec.ts
new file mode 100644
index 0000000000..979adddf89
--- /dev/null
+++ b/backend/e2e-test/routes/v4/secrets.spec.ts
@@ -0,0 +1,678 @@
+import { SecretType } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+type TRawSecret = {
+ secretKey: string;
+ secretValue: string;
+ secretComment?: string;
+ version: number;
+};
+
+const createSecret = async (dto: { path: string; key: string; value: string; comment: string; type?: SecretType }) => {
+ const createSecretReqBody = {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ type: dto.type || SecretType.Shared,
+ secretPath: dto.path,
+ secretKey: dto.key,
+ secretValue: dto.value,
+ secretComment: dto.comment
+ };
+ const createSecRes = await testServer.inject({
+ method: "POST",
+ url: `/api/v4/secrets/${dto.key}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: createSecretReqBody
+ });
+ expect(createSecRes.statusCode).toBe(200);
+ const createdSecretPayload = JSON.parse(createSecRes.payload);
+ expect(createdSecretPayload).toHaveProperty("secret");
+ return createdSecretPayload.secret as TRawSecret;
+};
+
+const deleteSecret = async (dto: { path: string; key: string }) => {
+ const deleteSecRes = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v4/secrets/${dto.key}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ secretPath: dto.path
+ }
+ });
+ expect(deleteSecRes.statusCode).toBe(200);
+ const updatedSecretPayload = JSON.parse(deleteSecRes.payload);
+ expect(updatedSecretPayload).toHaveProperty("secret");
+ return updatedSecretPayload.secret as TRawSecret;
+};
+
+describe.each([{ auth: AuthMode.JWT }, { auth: AuthMode.IDENTITY_ACCESS_TOKEN }])(
+ "Secret V4 - $auth mode",
+ async ({ auth }) => {
+ let folderId = "";
+ let authToken = "";
+ const secretTestCases = [
+ {
+ path: "/",
+ secret: {
+ key: "SEC1",
+ value: "something-secret",
+ comment: "some comment"
+ }
+ },
+ {
+ path: "/nested1/nested2/folder",
+ secret: {
+ key: "NESTED-SEC1",
+ value: "something-secret",
+ comment: "some comment"
+ }
+ },
+ {
+ path: "/",
+ secret: {
+ key: "secret-key-2",
+ value: `-----BEGIN PRIVATE KEY-----
+ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCa6eeFk+cMVqFn
+ hoVQDYgn2Ptp5Azysr2UPq6P73pCL9BzUtOXKZROqDyGehzzfg3wE2KdYU1Jk5Uq
+ fP0ZOWDIlM2SaVCSI3FW32o5+ZiggjpqcVdLFc/PS0S/ZdSmpPd8h11iO2brtIAI
+ ugTW8fcKlGSNUwx9aFmE7A6JnTRliTxB1l6QaC+YAwTK39VgeVH2gDSWC407aS15
+ QobAkaBKKmFkzB5D7i2ZJwt+uXJV/rbLmyDmtnw0lubciGn7NX9wbYef180fisqT
+ aPNAz0nPKk0fFH2Wd5MZixNGbrrpDA+FCYvI5doThZyT2hpj08qWP07oXXCAqw46
+ IEupNSILAgMBAAECggEBAIJb5KzeaiZS3B3O8G4OBQ5rJB3WfyLYUHnoSWLsBbie
+ nc392/ovThLmtZAAQE6SO85Tsb93+t64Z2TKqv1H8G658UeMgfWIB78v4CcLJ2mi
+ TN/3opqXrzjkQOTDHzBgT7al/mpETHZ6fOdbCemK0fVALGFUioUZg4M8VXtuI4Jw
+ q28jAyoRKrCrzda4BeQ553NZ4G5RvwhX3O2I8B8upTbt5hLcisBKy8MPLYY5LUFj
+ YKAP+raf6QLliP6KYHuVxUlgzxjLTxVG41etcyqqZF+foyiKBO3PU3n8oh++tgQP
+ ExOxiR0JSkBG5b+oOBD0zxcvo3/SjBHn0dJOZCSU2SkCgYEAyCe676XnNyBZMRD7
+ 6trsaoiCWBpA6M8H44+x3w4cQFtqV38RyLy60D+iMKjIaLqeBbnay61VMzo24Bz3
+ EuF2n4+9k/MetLJ0NCw8HmN5k0WSMD2BFsJWG8glVbzaqzehP4tIclwDTYc1jQVt
+ IoV2/iL7HGT+x2daUwbU5kN5hK0CgYEAxiLB+fmjxJW7VY4SHDLqPdpIW0q/kv4K
+ d/yZBrCX799vjmFb9vLh7PkQUfJhMJ/ttJOd7EtT3xh4mfkBeLfHwVU0d/ahbmSH
+ UJu/E9ZGxAW3PP0kxHZtPrLKQwBnfq8AxBauIhR3rPSorQTIOKtwz1jMlHFSUpuL
+ 3KeK2YfDYJcCgYEAkQnJOlNcAuRb/WQzSHIvktssqK8NjiZHryy3Vc0hx7j2jES2
+ HGI2dSVHYD9OSiXA0KFm3OTTsnViwm/60iGzFdjRJV6tR39xGUVcoyCuPnvRfUd0
+ PYvBXgxgkYpyYlPDcwp5CvWGJy3tLi1acgOIwIuUr3S38sL//t4adGk8q1kCgYB8
+ Jbs1Tl53BvrimKpwUNbE+sjrquJu0A7vL68SqgQJoQ7dP9PH4Ff/i+/V6PFM7mib
+ BQOm02wyFbs7fvKVGVJoqWK+6CIucX732x7W5yRgHtS5ukQXdbzt1Ek3wkEW98Cb
+ HTruz7RNAt/NyXlLSODeit1lBbx3Vk9EaxZtRsv88QKBgGn7JwXgez9NOyobsNIo
+ QVO80rpUeenSjuFi+R0VmbLKe/wgAQbYJ0xTAsQ0btqViMzB27D6mJyC+KUIwWNX
+ MN8a+m46v4kqvZkKL2c4gmDibyURNe/vCtCHFuanJS/1mo2tr4XDyEeiuK52eTd9
+ omQDpP86RX/hIIQ+JyLSaWYa
+ -----END PRIVATE KEY-----`,
+ comment:
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation"
+ }
+ },
+ {
+ path: "/nested1/nested2/folder",
+ secret: {
+ key: "secret-key-3",
+ value: `-----BEGIN PRIVATE KEY-----
+ MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCa6eeFk+cMVqFn
+ hoVQDYgn2Ptp5Azysr2UPq6P73pCL9BzUtOXKZROqDyGehzzfg3wE2KdYU1Jk5Uq
+ fP0ZOWDIlM2SaVCSI3FW32o5+ZiggjpqcVdLFc/PS0S/ZdSmpPd8h11iO2brtIAI
+ ugTW8fcKlGSNUwx9aFmE7A6JnTRliTxB1l6QaC+YAwTK39VgeVH2gDSWC407aS15
+ QobAkaBKKmFkzB5D7i2ZJwt+uXJV/rbLmyDmtnw0lubciGn7NX9wbYef180fisqT
+ aPNAz0nPKk0fFH2Wd5MZixNGbrrpDA+FCYvI5doThZyT2hpj08qWP07oXXCAqw46
+ IEupNSILAgMBAAECggEBAIJb5KzeaiZS3B3O8G4OBQ5rJB3WfyLYUHnoSWLsBbie
+ nc392/ovThLmtZAAQE6SO85Tsb93+t64Z2TKqv1H8G658UeMgfWIB78v4CcLJ2mi
+ TN/3opqXrzjkQOTDHzBgT7al/mpETHZ6fOdbCemK0fVALGFUioUZg4M8VXtuI4Jw
+ q28jAyoRKrCrzda4BeQ553NZ4G5RvwhX3O2I8B8upTbt5hLcisBKy8MPLYY5LUFj
+ YKAP+raf6QLliP6KYHuVxUlgzxjLTxVG41etcyqqZF+foyiKBO3PU3n8oh++tgQP
+ ExOxiR0JSkBG5b+oOBD0zxcvo3/SjBHn0dJOZCSU2SkCgYEAyCe676XnNyBZMRD7
+ 6trsaoiCWBpA6M8H44+x3w4cQFtqV38RyLy60D+iMKjIaLqeBbnay61VMzo24Bz3
+ EuF2n4+9k/MetLJ0NCw8HmN5k0WSMD2BFsJWG8glVbzaqzehP4tIclwDTYc1jQVt
+ IoV2/iL7HGT+x2daUwbU5kN5hK0CgYEAxiLB+fmjxJW7VY4SHDLqPdpIW0q/kv4K
+ d/yZBrCX799vjmFb9vLh7PkQUfJhMJ/ttJOd7EtT3xh4mfkBeLfHwVU0d/ahbmSH
+ UJu/E9ZGxAW3PP0kxHZtPrLKQwBnfq8AxBauIhR3rPSorQTIOKtwz1jMlHFSUpuL
+ 3KeK2YfDYJcCgYEAkQnJOlNcAuRb/WQzSHIvktssqK8NjiZHryy3Vc0hx7j2jES2
+ HGI2dSVHYD9OSiXA0KFm3OTTsnViwm/60iGzFdjRJV6tR39xGUVcoyCuPnvRfUd0
+ PYvBXgxgkYpyYlPDcwp5CvWGJy3tLi1acgOIwIuUr3S38sL//t4adGk8q1kCgYB8
+ Jbs1Tl53BvrimKpwUNbE+sjrquJu0A7vL68SqgQJoQ7dP9PH4Ff/i+/V6PFM7mib
+ BQOm02wyFbs7fvKVGVJoqWK+6CIucX732x7W5yRgHtS5ukQXdbzt1Ek3wkEW98Cb
+ HTruz7RNAt/NyXlLSODeit1lBbx3Vk9EaxZtRsv88QKBgGn7JwXgez9NOyobsNIo
+ QVO80rpUeenSjuFi+R0VmbLKe/wgAQbYJ0xTAsQ0btqViMzB27D6mJyC+KUIwWNX
+ MN8a+m46v4kqvZkKL2c4gmDibyURNe/vCtCHFuanJS/1mo2tr4XDyEeiuK52eTd9
+ omQDpP86RX/hIIQ+JyLSaWYa
+ -----END PRIVATE KEY-----`,
+ comment:
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation"
+ }
+ },
+ {
+ path: "/nested1/nested2/folder",
+ secret: {
+ key: "secret-key-3",
+ value:
+ "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gU2VkIGRvIGVpdXNtb2QgdGVtcG9yIGluY2lkaWR1bnQgdXQgbGFib3JlIGV0IGRvbG9yZSBtYWduYSBhbGlxdWEuIFV0IGVuaW0gYWQgbWluaW0gdmVuaWFtLCBxdWlzIG5vc3RydWQgZXhlcmNpdGF0aW9uCg==",
+ comment: ""
+ }
+ }
+ ];
+
+ beforeAll(async () => {
+ if (auth === AuthMode.JWT) {
+ authToken = jwtAuthToken;
+ } else if (auth === AuthMode.IDENTITY_ACCESS_TOKEN) {
+ const identityLogin = await testServer.inject({
+ method: "POST",
+ url: "/api/v1/auth/universal-auth/login",
+ body: {
+ clientSecret: seedData1.machineIdentity.clientCredentials.secret,
+ clientId: seedData1.machineIdentity.clientCredentials.id
+ }
+ });
+ expect(identityLogin.statusCode).toBe(200);
+ authToken = identityLogin.json().accessToken;
+ }
+ // create a deep folder
+ const folderCreate = await testServer.inject({
+ method: "POST",
+ url: `/api/v2/folders`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ name: "folder",
+ path: "/nested1/nested2"
+ }
+ });
+ expect(folderCreate.statusCode).toBe(200);
+ folderId = folderCreate.json().folder.id;
+ });
+
+ afterAll(async () => {
+ const deleteFolder = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v2/folders/${folderId}`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ path: "/nested1/nested2"
+ }
+ });
+ expect(deleteFolder.statusCode).toBe(200);
+ });
+
+ const getSecrets = async (environment: string, secretPath = "/") => {
+ const res = await testServer.inject({
+ method: "GET",
+ url: `/api/v4/secrets`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ query: {
+ secretPath,
+ environment,
+ projectId: seedData1.projectV3.id
+ }
+ });
+ const secrets: TRawSecret[] = JSON.parse(res.payload).secrets || [];
+ return secrets;
+ };
+
+ test.each(secretTestCases)("Create secret in path $path", async ({ secret, path }) => {
+ const createdSecret = await createSecret({ path, ...secret });
+ expect(createdSecret.secretKey).toEqual(secret.key);
+ expect(createdSecret.secretValue).toEqual(secret.value);
+ expect(createdSecret.secretComment || "").toEqual(secret.comment);
+ expect(createdSecret.version).toEqual(1);
+
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ secretKey: secret.key,
+ secretValue: secret.value,
+ type: SecretType.Shared
+ })
+ ])
+ );
+ await deleteSecret({ path, key: secret.key });
+ });
+
+ test.each(secretTestCases)("Get secret by name in path $path", async ({ secret, path }) => {
+ await createSecret({ path, ...secret });
+
+ const getSecByNameRes = await testServer.inject({
+ method: "GET",
+ url: `/api/v4/secrets/${secret.key}`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ query: {
+ secretPath: path,
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug
+ }
+ });
+ expect(getSecByNameRes.statusCode).toBe(200);
+ const getSecretByNamePayload = JSON.parse(getSecByNameRes.payload);
+ expect(getSecretByNamePayload).toHaveProperty("secret");
+ const decryptedSecret = getSecretByNamePayload.secret as TRawSecret;
+ expect(decryptedSecret.secretKey).toEqual(secret.key);
+ expect(decryptedSecret.secretValue).toEqual(secret.value);
+ expect(decryptedSecret.secretComment || "").toEqual(secret.comment);
+
+ await deleteSecret({ path, key: secret.key });
+ });
+
+ if (auth === AuthMode.JWT) {
+ test.each(secretTestCases)(
+ "Creating personal secret without shared throw error in path $path",
+ async ({ secret }) => {
+ const createSecretReqBody = {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ type: SecretType.Personal,
+ secretKey: secret.key,
+ secretValue: secret.value,
+ secretComment: secret.comment
+ };
+ const createSecRes = await testServer.inject({
+ method: "POST",
+ url: `/api/v4/secrets/SEC2`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: createSecretReqBody
+ });
+ const payload = JSON.parse(createSecRes.payload);
+ expect(createSecRes.statusCode).toBe(400);
+ expect(payload.error).toEqual("BadRequest");
+ }
+ );
+
+ test.each(secretTestCases)("Creating personal secret in path $path", async ({ secret, path }) => {
+ await createSecret({ path, ...secret });
+
+ const createSecretReqBody = {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ type: SecretType.Personal,
+ secretPath: path,
+ secretKey: secret.key,
+ secretValue: "personal-value",
+ secretComment: secret.comment
+ };
+ const createSecRes = await testServer.inject({
+ method: "POST",
+ url: `/api/v4/secrets/${secret.key}`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: createSecretReqBody
+ });
+ expect(createSecRes.statusCode).toBe(200);
+
+ // list secrets should contain personal one and shared one
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ secretKey: secret.key,
+ secretValue: secret.value,
+ type: SecretType.Shared
+ }),
+ expect.objectContaining({
+ secretKey: secret.key,
+ secretValue: "personal-value",
+ type: SecretType.Personal
+ })
+ ])
+ );
+
+ await deleteSecret({ path, key: secret.key });
+ });
+
+ test.each(secretTestCases)(
+ "Deleting personal one should not delete shared secret in path $path",
+ async ({ secret, path }) => {
+ await createSecret({ path, ...secret }); // shared one
+ await createSecret({ path, ...secret, type: SecretType.Personal });
+
+ // shared secret deletion should delete personal ones also
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ secretKey: secret.key,
+ type: SecretType.Shared
+ }),
+ expect.not.objectContaining({
+ secretKey: secret.key,
+ type: SecretType.Personal
+ })
+ ])
+ );
+ await deleteSecret({ path, key: secret.key });
+ }
+ );
+ }
+
+ test.each(secretTestCases)("Update secret in path $path", async ({ path, secret }) => {
+ await createSecret({ path, ...secret });
+ const updateSecretReqBody = {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ type: SecretType.Shared,
+ secretPath: path,
+ secretKey: secret.key,
+ secretValue: "new-value",
+ secretComment: secret.comment
+ };
+ const updateSecRes = await testServer.inject({
+ method: "PATCH",
+ url: `/api/v4/secrets/${secret.key}`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: updateSecretReqBody
+ });
+ expect(updateSecRes.statusCode).toBe(200);
+ const updatedSecretPayload = JSON.parse(updateSecRes.payload);
+ expect(updatedSecretPayload).toHaveProperty("secret");
+ const decryptedSecret = updatedSecretPayload.secret;
+ expect(decryptedSecret.secretKey).toEqual(secret.key);
+ expect(decryptedSecret.secretValue).toEqual("new-value");
+ expect(decryptedSecret.secretComment || "").toEqual(secret.comment);
+
+ // list secret should have updated value
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ secretKey: secret.key,
+ secretValue: "new-value",
+ type: SecretType.Shared
+ })
+ ])
+ );
+
+ await deleteSecret({ path, key: secret.key });
+ });
+
+ test.each(secretTestCases)("Delete secret in path $path", async ({ secret, path }) => {
+ await createSecret({ path, ...secret });
+ const deletedSecret = await deleteSecret({ path, key: secret.key });
+ expect(deletedSecret.secretKey).toEqual(secret.key);
+
+ // shared secret deletion should delete personal ones also
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.not.arrayContaining([
+ expect.objectContaining({
+ secretKey: secret.key,
+ type: SecretType.Shared
+ }),
+ expect.objectContaining({
+ secretKey: secret.key,
+ type: SecretType.Personal
+ })
+ ])
+ );
+ });
+
+ test.each(secretTestCases)("Bulk create secrets in path $path", async ({ secret, path }) => {
+ const createSharedSecRes = await testServer.inject({
+ method: "POST",
+ url: `/api/v4/secrets/batch`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ secretPath: path,
+ secrets: Array.from(Array(5)).map((_e, i) => ({
+ secretKey: `BULK-${secret.key}-${i + 1}`,
+ secretValue: secret.value,
+ secretComment: secret.comment
+ }))
+ }
+ });
+ expect(createSharedSecRes.statusCode).toBe(200);
+ const createSharedSecPayload = JSON.parse(createSharedSecRes.payload);
+ expect(createSharedSecPayload).toHaveProperty("secrets");
+
+ // bulk ones should exist
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.arrayContaining(
+ Array.from(Array(5)).map((_e, i) =>
+ expect.objectContaining({
+ secretKey: `BULK-${secret.key}-${i + 1}`,
+ secretValue: secret.value,
+ type: SecretType.Shared
+ })
+ )
+ )
+ );
+
+ await Promise.all(
+ Array.from(Array(5)).map((_e, i) => deleteSecret({ path, key: `BULK-${secret.key}-${i + 1}` }))
+ );
+ });
+
+ test.each(secretTestCases)("Bulk create fail on existing secret in path $path", async ({ secret, path }) => {
+ await createSecret({ ...secret, key: `BULK-${secret.key}-1`, path });
+
+ const createSharedSecRes = await testServer.inject({
+ method: "POST",
+ url: `/api/v4/secrets/batch`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ secretPath: path,
+ secrets: Array.from(Array(5)).map((_e, i) => ({
+ secretKey: `BULK-${secret.key}-${i + 1}`,
+ secretValue: secret.value,
+ secretComment: secret.comment
+ }))
+ }
+ });
+ expect(createSharedSecRes.statusCode).toBe(400);
+
+ await deleteSecret({ path, key: `BULK-${secret.key}-1` });
+ });
+
+ test.each(secretTestCases)("Bulk update secrets in path $path", async ({ secret, path }) => {
+ await Promise.all(
+ Array.from(Array(5)).map((_e, i) => createSecret({ ...secret, key: `BULK-${secret.key}-${i + 1}`, path }))
+ );
+
+ const updateSharedSecRes = await testServer.inject({
+ method: "PATCH",
+ url: `/api/v4/secrets/batch`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ secretPath: path,
+ secrets: Array.from(Array(5)).map((_e, i) => ({
+ secretKey: `BULK-${secret.key}-${i + 1}`,
+ secretValue: "update-value",
+ secretComment: secret.comment
+ }))
+ }
+ });
+ expect(updateSharedSecRes.statusCode).toBe(200);
+ const updateSharedSecPayload = JSON.parse(updateSharedSecRes.payload);
+ expect(updateSharedSecPayload).toHaveProperty("secrets");
+
+ // bulk ones should exist
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.arrayContaining(
+ Array.from(Array(5)).map((_e, i) =>
+ expect.objectContaining({
+ secretKey: `BULK-${secret.key}-${i + 1}`,
+ secretValue: "update-value",
+ type: SecretType.Shared
+ })
+ )
+ )
+ );
+ await Promise.all(
+ Array.from(Array(5)).map((_e, i) => deleteSecret({ path, key: `BULK-${secret.key}-${i + 1}` }))
+ );
+ });
+
+ test.each(secretTestCases)("Bulk upsert secrets in path $path", async ({ secret, path }) => {
+ const updateSharedSecRes = await testServer.inject({
+ method: "PATCH",
+ url: `/api/v4/secrets/batch`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ secretPath: path,
+ mode: "upsert",
+ secrets: Array.from(Array(5)).map((_e, i) => ({
+ secretKey: `BULK-${secret.key}-${i + 1}`,
+ secretValue: "update-value",
+ secretComment: secret.comment
+ }))
+ }
+ });
+ expect(updateSharedSecRes.statusCode).toBe(200);
+ const updateSharedSecPayload = JSON.parse(updateSharedSecRes.payload);
+ expect(updateSharedSecPayload).toHaveProperty("secrets");
+
+ // bulk ones should exist
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.arrayContaining(
+ Array.from(Array(5)).map((_e, i) =>
+ expect.objectContaining({
+ secretKey: `BULK-${secret.key}-${i + 1}`,
+ secretValue: "update-value",
+ type: SecretType.Shared
+ })
+ )
+ )
+ );
+ await Promise.all(
+ Array.from(Array(5)).map((_e, i) => deleteSecret({ path, key: `BULK-${secret.key}-${i + 1}` }))
+ );
+ });
+
+ test("Bulk upsert secrets in path multiple paths", async () => {
+ const firstBatchSecrets = Array.from(Array(5)).map((_e, i) => ({
+ secretKey: `BULK-KEY-${secretTestCases[0].secret.key}-${i + 1}`,
+ secretValue: "update-value",
+ secretComment: "comment",
+ secretPath: secretTestCases[0].path
+ }));
+ const secondBatchSecrets = Array.from(Array(5)).map((_e, i) => ({
+ secretKey: `BULK-KEY-${secretTestCases[1].secret.key}-${i + 1}`,
+ secretValue: "update-value",
+ secretComment: "comment",
+ secretPath: secretTestCases[1].path
+ }));
+ const testSecrets = [...firstBatchSecrets, ...secondBatchSecrets];
+
+ const updateSharedSecRes = await testServer.inject({
+ method: "PATCH",
+ url: `/api/v4/secrets/batch`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ mode: "upsert",
+ secrets: testSecrets
+ }
+ });
+ expect(updateSharedSecRes.statusCode).toBe(200);
+ const updateSharedSecPayload = JSON.parse(updateSharedSecRes.payload);
+ expect(updateSharedSecPayload).toHaveProperty("secrets");
+
+ // bulk ones should exist
+ const firstBatchSecretsOnInfisical = await getSecrets(seedData1.environment.slug, secretTestCases[0].path);
+ expect(firstBatchSecretsOnInfisical).toEqual(
+ expect.arrayContaining(
+ firstBatchSecrets.map((el) =>
+ expect.objectContaining({
+ secretKey: el.secretKey,
+ secretValue: "update-value",
+ type: SecretType.Shared
+ })
+ )
+ )
+ );
+ const secondBatchSecretsOnInfisical = await getSecrets(seedData1.environment.slug, secretTestCases[1].path);
+ expect(secondBatchSecretsOnInfisical).toEqual(
+ expect.arrayContaining(
+ secondBatchSecrets.map((el) =>
+ expect.objectContaining({
+ secretKey: el.secretKey,
+ secretValue: "update-value",
+ type: SecretType.Shared
+ })
+ )
+ )
+ );
+ await Promise.all(testSecrets.map((el) => deleteSecret({ path: el.secretPath, key: el.secretKey })));
+ });
+
+ test.each(secretTestCases)("Bulk delete secrets in path $path", async ({ secret, path }) => {
+ await Promise.all(
+ Array.from(Array(5)).map((_e, i) => createSecret({ ...secret, key: `BULK-${secret.key}-${i + 1}`, path }))
+ );
+
+ const deletedSharedSecRes = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v4/secrets/batch`,
+ headers: {
+ authorization: `Bearer ${authToken}`
+ },
+ body: {
+ projectId: seedData1.projectV3.id,
+ environment: seedData1.environment.slug,
+ secretPath: path,
+ secrets: Array.from(Array(5)).map((_e, i) => ({
+ secretKey: `BULK-${secret.key}-${i + 1}`
+ }))
+ }
+ });
+
+ expect(deletedSharedSecRes.statusCode).toBe(200);
+ const deletedSecretPayload = JSON.parse(deletedSharedSecRes.payload);
+ expect(deletedSecretPayload).toHaveProperty("secrets");
+
+ // bulk ones should exist
+ const secrets = await getSecrets(seedData1.environment.slug, path);
+ expect(secrets).toEqual(
+ expect.not.arrayContaining(
+ Array.from(Array(5)).map((_e, i) =>
+ expect.objectContaining({
+ secretKey: `BULK-${secret.value}-${i + 1}`,
+ type: SecretType.Shared
+ })
+ )
+ )
+ );
+ });
+ }
+);
diff --git a/backend/src/db/migrations/20250204025010_app-connections-and-secret-syncs-unique-constraint.ts b/backend/src/db/migrations/20250204025010_app-connections-and-secret-syncs-unique-constraint.ts
index 348694ae7a..f9b46559d4 100644
--- a/backend/src/db/migrations/20250204025010_app-connections-and-secret-syncs-unique-constraint.ts
+++ b/backend/src/db/migrations/20250204025010_app-connections-and-secret-syncs-unique-constraint.ts
@@ -1,5 +1,6 @@
import { Knex } from "knex";
+import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists";
import { TableName } from "@app/db/schemas";
export async function up(knex: Knex): Promise<void> {
@@ -13,9 +14,7 @@ export async function up(knex: Knex): Promise<void> {
}
export async function down(knex: Knex): Promise<void> {
- await knex.schema.alterTable(TableName.AppConnection, (t) => {
- t.dropUnique(["orgId", "name"]);
- });
+ await dropConstraintIfExists(TableName.AppConnection, "app_connections_orgid_name_unique", knex);
await knex.schema.alterTable(TableName.SecretSync, (t) => {
t.dropUnique(["projectId", "name"]);
diff --git a/backend/src/db/migrations/20250819081226_identity-lockouts-ldap.ts b/backend/src/db/migrations/20250819081226_identity-lockouts-ldap.ts
new file mode 100644
index 0000000000..6cc8513682
--- /dev/null
+++ b/backend/src/db/migrations/20250819081226_identity-lockouts-ldap.ts
@@ -0,0 +1,57 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.IdentityLdapAuth)) {
+ const hasLockoutEnabled = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutEnabled");
+ const hasLockoutThreshold = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutThreshold");
+ const hasLockoutDuration = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutDurationSeconds");
+ const hasLockoutCounterReset = await knex.schema.hasColumn(
+ TableName.IdentityLdapAuth,
+ "lockoutCounterResetSeconds"
+ );
+
+ await knex.schema.alterTable(TableName.IdentityLdapAuth, (t) => {
+ if (!hasLockoutEnabled) {
+ t.boolean("lockoutEnabled").notNullable().defaultTo(true);
+ }
+ if (!hasLockoutThreshold) {
+ t.integer("lockoutThreshold").notNullable().defaultTo(3);
+ }
+ if (!hasLockoutDuration) {
+ t.integer("lockoutDurationSeconds").notNullable().defaultTo(300); // 5 minutes
+ }
+ if (!hasLockoutCounterReset) {
+ t.integer("lockoutCounterResetSeconds").notNullable().defaultTo(30); // 30 seconds
+ }
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.IdentityLdapAuth)) {
+ const hasLockoutEnabled = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutEnabled");
+ const hasLockoutThreshold = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutThreshold");
+ const hasLockoutDuration = await knex.schema.hasColumn(TableName.IdentityLdapAuth, "lockoutDurationSeconds");
+ const hasLockoutCounterReset = await knex.schema.hasColumn(
+ TableName.IdentityLdapAuth,
+ "lockoutCounterResetSeconds"
+ );
+
+ await knex.schema.alterTable(TableName.IdentityLdapAuth, (t) => {
+ if (hasLockoutEnabled) {
+ t.dropColumn("lockoutEnabled");
+ }
+ if (hasLockoutThreshold) {
+ t.dropColumn("lockoutThreshold");
+ }
+ if (hasLockoutDuration) {
+ t.dropColumn("lockoutDurationSeconds");
+ }
+ if (hasLockoutCounterReset) {
+ t.dropColumn("lockoutCounterResetSeconds");
+ }
+ });
+ }
+}
diff --git a/backend/src/db/migrations/20250912011133_app-connection-project-id-col.ts b/backend/src/db/migrations/20250912011133_app-connection-project-id-col.ts
new file mode 100644
index 0000000000..5c846a7395
--- /dev/null
+++ b/backend/src/db/migrations/20250912011133_app-connection-project-id-col.ts
@@ -0,0 +1,41 @@
+import { Knex } from "knex";
+
+import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists";
+import { TableName } from "@app/db/schemas";
+
+const UNIQUE_NAME_ORG_CONNECTION_INDEX = "unique_name_org_app_connection";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.AppConnection)) {
+ // we can't add the constraint back after up since there may be conflicting names so we do if exists
+ await dropConstraintIfExists(TableName.AppConnection, "app_connections_orgid_name_unique", knex);
+
+ if (!(await knex.schema.hasColumn(TableName.AppConnection, "projectId"))) {
+ await knex.schema.alterTable(TableName.AppConnection, (t) => {
+ t.string("projectId").nullable();
+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
+ // unique name for project-level connections
+ t.unique(["name", "projectId", "orgId"]);
+ });
+
+ // unique name for org-level connections
+ await knex.raw(`
+ CREATE UNIQUE INDEX ${UNIQUE_NAME_ORG_CONNECTION_INDEX}
+ ON ${TableName.AppConnection} ("name", "orgId")
+ WHERE "projectId" IS NULL
+ `);
+ }
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.AppConnection)) {
+ if (await knex.schema.hasColumn(TableName.AppConnection, "projectId")) {
+ await knex.schema.alterTable(TableName.AppConnection, (t) => {
+ t.dropUnique(["name", "projectId", "orgId"]);
+ t.dropColumn("projectId");
+ });
+ await dropConstraintIfExists(TableName.AppConnection, UNIQUE_NAME_ORG_CONNECTION_INDEX, knex);
+ }
+ }
+}
diff --git a/backend/src/db/schemas/app-connections.ts b/backend/src/db/schemas/app-connections.ts
index 2218b75ce5..41d1df17fa 100644
--- a/backend/src/db/schemas/app-connections.ts
+++ b/backend/src/db/schemas/app-connections.ts
@@ -21,7 +21,8 @@ export const AppConnectionsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
isPlatformManagedCredentials: z.boolean().default(false).nullable().optional(),
- gatewayId: z.string().uuid().nullable().optional()
+ gatewayId: z.string().uuid().nullable().optional(),
+ projectId: z.string().nullable().optional()
});
export type TAppConnections = z.infer<typeof AppConnectionsSchema>;
diff --git a/backend/src/db/schemas/identity-ldap-auths.ts b/backend/src/db/schemas/identity-ldap-auths.ts
index 3e4d88649c..87c7f1608d 100644
--- a/backend/src/db/schemas/identity-ldap-auths.ts
+++ b/backend/src/db/schemas/identity-ldap-auths.ts
@@ -26,7 +26,11 @@ export const IdentityLdapAuthsSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
accessTokenPeriod: z.coerce.number().default(0),
- templateId: z.string().uuid().nullable().optional()
+ templateId: z.string().uuid().nullable().optional(),
+ lockoutEnabled: z.boolean().default(true),
+ lockoutThreshold: z.number().default(3),
+ lockoutDurationSeconds: z.number().default(300),
+ lockoutCounterResetSeconds: z.number().default(30)
});
export type TIdentityLdapAuths = z.infer<typeof IdentityLdapAuthsSchema>;
diff --git a/backend/src/ee/routes/v1/audit-log-stream-routers/audit-log-stream-router.ts b/backend/src/ee/routes/v1/audit-log-stream-routers/audit-log-stream-router.ts
index e0ac0b6af5..48eed14c9e 100644
--- a/backend/src/ee/routes/v1/audit-log-stream-routers/audit-log-stream-router.ts
+++ b/backend/src/ee/routes/v1/audit-log-stream-routers/audit-log-stream-router.ts
@@ -1,5 +1,9 @@
import { z } from "zod";
+import {
+ AzureProviderListItemSchema,
+ SanitizedAzureProviderSchema
+} from "@app/ee/services/audit-log-stream/azure/azure-provider-schemas";
import {
CriblProviderListItemSchema,
SanitizedCriblProviderSchema
@@ -24,6 +28,7 @@ const SanitizedAuditLogStreamSchema = z.union([
SanitizedCustomProviderSchema,
SanitizedDatadogProviderSchema,
SanitizedSplunkProviderSchema,
+ SanitizedAzureProviderSchema,
SanitizedCriblProviderSchema
]);
@@ -31,6 +36,7 @@ const ProviderOptionsSchema = z.discriminatedUnion("provider", [
CustomProviderListItemSchema,
DatadogProviderListItemSchema,
SplunkProviderListItemSchema,
+ AzureProviderListItemSchema,
CriblProviderListItemSchema
]);
diff --git a/backend/src/ee/routes/v1/audit-log-stream-routers/index.ts b/backend/src/ee/routes/v1/audit-log-stream-routers/index.ts
index f40a82d89e..ad338c8011 100644
--- a/backend/src/ee/routes/v1/audit-log-stream-routers/index.ts
+++ b/backend/src/ee/routes/v1/audit-log-stream-routers/index.ts
@@ -1,4 +1,9 @@
import { LogProvider } from "@app/ee/services/audit-log-stream/audit-log-stream-enums";
+import {
+ CreateAzureProviderLogStreamSchema,
+ SanitizedAzureProviderSchema,
+ UpdateAzureProviderLogStreamSchema
+} from "@app/ee/services/audit-log-stream/azure/azure-provider-schemas";
import {
CreateCriblProviderLogStreamSchema,
SanitizedCriblProviderSchema,
@@ -26,6 +31,15 @@ export * from "./audit-log-stream-router";
export const AUDIT_LOG_STREAM_REGISTER_ROUTER_MAP: Record<LogProvider, (server: FastifyZodProvider) => Promise<void>> =
{
+ [LogProvider.Azure]: async (server: FastifyZodProvider) => {
+ registerAuditLogStreamEndpoints({
+ server,
+ provider: LogProvider.Azure,
+ sanitizedResponseSchema: SanitizedAzureProviderSchema,
+ createSchema: CreateAzureProviderLogStreamSchema,
+ updateSchema: UpdateAzureProviderLogStreamSchema
+ });
+ },
[LogProvider.Custom]: async (server: FastifyZodProvider) => {
registerAuditLogStreamEndpoints({
server,
diff --git a/backend/src/ee/routes/v1/deprecated-project-role-router.ts b/backend/src/ee/routes/v1/deprecated-project-role-router.ts
new file mode 100644
index 0000000000..dc361626d8
--- /dev/null
+++ b/backend/src/ee/routes/v1/deprecated-project-role-router.ts
@@ -0,0 +1,342 @@
+import { packRules } from "@casl/ability/extra";
+import { z } from "zod";
+
+import { ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import {
+ backfillPermissionV1SchemaToV2Schema,
+ ProjectPermissionV1Schema
+} from "@app/ee/services/permission/project-permission";
+import { PROJECT_ROLE } from "@app/lib/api-docs";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { slugSchema } from "@app/server/lib/schemas";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { SanitizedRoleSchemaV1 } from "@app/server/routes/sanitizedSchemas";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
+
+export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/:projectSlug/roles",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ description: "Create a project role",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectSlug: z.string().trim().describe(PROJECT_ROLE.CREATE.projectSlug)
+ }),
+ body: z.object({
+ slug: slugSchema({ max: 64 })
+ .refine(
+ (val) => !Object.values(ProjectMembershipRole).includes(val as ProjectMembershipRole),
+ "Please choose a different slug, the slug you have entered is reserved"
+ )
+ .describe(PROJECT_ROLE.CREATE.slug),
+ name: z.string().min(1).trim().describe(PROJECT_ROLE.CREATE.name),
+ description: z.string().trim().nullish().describe(PROJECT_ROLE.CREATE.description),
+ permissions: ProjectPermissionV1Schema.array().describe(PROJECT_ROLE.CREATE.permissions)
+ }),
+ response: {
+ 200: z.object({
+ role: SanitizedRoleSchemaV1
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const stringifiedPermissions = JSON.stringify(
+ packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true))
+ );
+
+ const role = await server.services.projectRole.createRole({
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actor: req.permission.type,
+ filter: {
+ type: ProjectRoleServiceIdentifierType.SLUG,
+ projectSlug: req.params.projectSlug
+ },
+ data: {
+ ...req.body,
+ permissions: stringifiedPermissions
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.CREATE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: stringifiedPermissions
+ }
+ }
+ });
+
+ return { role };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:projectSlug/roles/:roleId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ description: "Update a project role",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectSlug: z.string().trim().describe(PROJECT_ROLE.UPDATE.projectSlug),
+ roleId: z.string().trim().describe(PROJECT_ROLE.UPDATE.roleId)
+ }),
+ body: z.object({
+ slug: slugSchema({ max: 64 })
+ .refine(
+ (val) => !Object.values(ProjectMembershipRole).includes(val as ProjectMembershipRole),
+ "Please choose a different slug, the slug you have entered is reserved"
+ )
+ .describe(PROJECT_ROLE.UPDATE.slug)
+ .optional(),
+ name: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.name),
+ description: z.string().trim().nullish().describe(PROJECT_ROLE.UPDATE.description),
+ permissions: ProjectPermissionV1Schema.array().describe(PROJECT_ROLE.UPDATE.permissions).optional()
+ }),
+ response: {
+ 200: z.object({
+ role: SanitizedRoleSchemaV1
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const stringifiedPermissions = req.body.permissions
+ ? JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true)))
+ : undefined;
+
+ const role = await server.services.projectRole.updateRole({
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actor: req.permission.type,
+ roleId: req.params.roleId,
+ data: {
+ ...req.body,
+ permissions: stringifiedPermissions
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.UPDATE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: stringifiedPermissions
+ }
+ }
+ });
+
+ return { role };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:projectSlug/roles/:roleId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ description: "Delete a project role",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectSlug: z.string().trim().describe(PROJECT_ROLE.DELETE.projectSlug),
+ roleId: z.string().trim().describe(PROJECT_ROLE.DELETE.roleId)
+ }),
+ response: {
+ 200: z.object({
+ role: SanitizedRoleSchemaV1
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const role = await server.services.projectRole.deleteRole({
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actor: req.permission.type,
+ roleId: req.params.roleId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.DELETE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: role.slug,
+ name: role.name
+ }
+ }
+ });
+
+ return { role };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectSlug/roles",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ description: "List project role",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectSlug: z.string().trim().describe(PROJECT_ROLE.LIST.projectSlug)
+ }),
+ response: {
+ 200: z.object({
+ roles: ProjectRolesSchema.omit({ permissions: true, version: true }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const roles = await server.services.projectRole.listRoles({
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actor: req.permission.type,
+ filter: {
+ type: ProjectRoleServiceIdentifierType.SLUG,
+ projectSlug: req.params.projectSlug
+ }
+ });
+ return { roles };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectSlug/roles/slug/:slug",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ projectSlug: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.projectSlug),
+ slug: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.roleSlug)
+ }),
+ response: {
+ 200: z.object({
+ role: SanitizedRoleSchemaV1.omit({ version: true })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const role = await server.services.projectRole.getRoleBySlug({
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actor: req.permission.type,
+ filter: {
+ type: ProjectRoleServiceIdentifierType.SLUG,
+ projectSlug: req.params.projectSlug
+ },
+ roleSlug: req.params.slug
+ });
+
+ return { role };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/permissions",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ data: z.object({
+ membership: z.object({
+ id: z.string(),
+ roles: z
+ .object({
+ role: z.string()
+ })
+ .array()
+ }),
+ assumedPrivilegeDetails: z
+ .object({
+ actorId: z.string(),
+ actorType: z.string(),
+ actorName: z.string(),
+ actorEmail: z.string().optional()
+ })
+ .optional(),
+ permissions: z.any().array()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { permissions, membership, assumedPrivilegeDetails } = await server.services.projectRole.getUserPermission(
+ req.permission.id,
+ req.params.projectId,
+ req.permission.authMethod,
+ req.permission.orgId
+ );
+
+ return {
+ data: {
+ permissions,
+ membership,
+ assumedPrivilegeDetails
+ }
+ };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/deprecated-project-router.ts b/backend/src/ee/routes/v1/deprecated-project-router.ts
new file mode 100644
index 0000000000..6c4175f840
--- /dev/null
+++ b/backend/src/ee/routes/v1/deprecated-project-router.ts
@@ -0,0 +1,195 @@
+import { z } from "zod";
+
+import { AuditLogsSchema, SecretSnapshotsSchema } from "@app/db/schemas";
+import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, AUDIT_LOGS, PROJECTS } from "@app/lib/api-docs";
+import { getLastMidnightDateISO, removeTrailingSlash } from "@app/lib/fn";
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const registerDeprecatedProjectRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/secret-snapshots",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Projects],
+ description: "Return project secret snapshots ids",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECTS.GET_SNAPSHOTS.projectId)
+ }),
+ querystring: z.object({
+ environment: z.string().trim().describe(PROJECTS.GET_SNAPSHOTS.environment),
+ path: z.string().trim().default("/").transform(removeTrailingSlash).describe(PROJECTS.GET_SNAPSHOTS.path),
+ offset: z.coerce.number().default(0).describe(PROJECTS.GET_SNAPSHOTS.offset),
+ limit: z.coerce.number().default(20).describe(PROJECTS.GET_SNAPSHOTS.limit)
+ }),
+ response: {
+ 200: z.object({
+ secretSnapshots: SecretSnapshotsSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretSnapshots = await server.services.snapshot.listSnapshots({
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ ...req.query
+ });
+ return { secretSnapshots };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/secret-snapshots/count",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ workspaceId: z.string().trim()
+ }),
+ querystring: z.object({
+ environment: z.string().trim(),
+ path: z.string().trim().default("/").transform(removeTrailingSlash)
+ }),
+ response: {
+ 200: z.object({
+ count: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const count = await server.services.snapshot.projectSecretSnapshotCount({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ environment: req.query.environment,
+ path: req.query.path
+ });
+ return { count };
+ }
+ });
+
+ /*
+ * Daniel: This endpoint is no longer is use.
+ * We are keeping it for now because it has been exposed in our public api docs for a while, so by removing it we are likely to break users workflows.
+ *
+ * Please refer to the new endpoint, GET /api/v1/organization/audit-logs, for the same (and more) functionality.
+ */
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/audit-logs",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ description: "Return audit logs",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(AUDIT_LOGS.EXPORT.projectId)
+ }),
+ querystring: z
+ .object({
+ eventType: z.nativeEnum(EventType).optional().describe(AUDIT_LOGS.EXPORT.eventType),
+ userAgentType: z.nativeEnum(UserAgentType).optional().describe(AUDIT_LOGS.EXPORT.userAgentType),
+ startDate: z.string().datetime().optional().describe(AUDIT_LOGS.EXPORT.startDate),
+ endDate: z.string().datetime().optional().describe(AUDIT_LOGS.EXPORT.endDate),
+ offset: z.coerce.number().default(0).describe(AUDIT_LOGS.EXPORT.offset),
+ limit: z.coerce.number().max(1000).default(20).describe(AUDIT_LOGS.EXPORT.limit),
+ actor: z.string().optional().describe(AUDIT_LOGS.EXPORT.actor)
+ })
+ .superRefine((el, ctx) => {
+ if (el.endDate && el.startDate) {
+ const startDate = new Date(el.startDate);
+ const endDate = new Date(el.endDate);
+ const maxAllowedDate = new Date(startDate);
+ maxAllowedDate.setMonth(maxAllowedDate.getMonth() + 3);
+ if (endDate < startDate) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["endDate"],
+ message: "End date cannot be before start date"
+ });
+ }
+ if (endDate > maxAllowedDate) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["endDate"],
+ message: "Dates must be within 3 months"
+ });
+ }
+ }
+ }),
+ response: {
+ 200: z.object({
+ auditLogs: AuditLogsSchema.omit({
+ eventMetadata: true,
+ eventType: true,
+ actor: true,
+ actorMetadata: true
+ })
+ .merge(
+ z.object({
+ project: z
+ .object({
+ name: z.string(),
+ slug: z.string()
+ })
+ .optional(),
+ event: z.object({
+ type: z.string(),
+ metadata: z.any()
+ }),
+ actor: z.object({
+ type: z.string(),
+ metadata: z.any()
+ })
+ })
+ )
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const auditLogs = await server.services.auditLog.listAuditLogs({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+
+ filter: {
+ ...req.query,
+ projectId: req.params.workspaceId,
+ endDate: req.query.endDate || new Date().toISOString(),
+ startDate: req.query.startDate || getLastMidnightDateISO(),
+ auditLogActorId: req.query.actor,
+ eventType: req.query.eventType ? [req.query.eventType] : undefined
+ }
+ });
+ return { auditLogs };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/deprecated-secret-approval-policy-router.ts b/backend/src/ee/routes/v1/deprecated-secret-approval-policy-router.ts
new file mode 100644
index 0000000000..42f6f9c129
--- /dev/null
+++ b/backend/src/ee/routes/v1/deprecated-secret-approval-policy-router.ts
@@ -0,0 +1,293 @@
+import { nanoid } from "nanoid";
+import { z } from "zod";
+
+import { ApproverType, BypasserType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
+import { removeTrailingSlash } from "@app/lib/fn";
+import { EnforcementLevel } from "@app/lib/types";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { sapPubSchema } from "@app/server/routes/sanitizedSchemas";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const registerDeprecatedSecretApprovalPolicyRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ url: "/",
+ method: "POST",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ body: z
+ .object({
+ workspaceId: z.string(),
+ name: z.string().optional(),
+ environment: z.string().optional(),
+ environments: z.string().array().optional(),
+ secretPath: z
+ .string()
+ .min(1, { message: "Secret path cannot be empty" })
+ .transform((val) => removeTrailingSlash(val)),
+ approvers: z
+ .discriminatedUnion("type", [
+ z.object({ type: z.literal(ApproverType.Group), id: z.string() }),
+ z.object({
+ type: z.literal(ApproverType.User),
+ id: z.string().optional(),
+ username: z.string().optional()
+ })
+ ])
+ .array()
+ .min(1, { message: "At least one approver should be provided" })
+ .max(100, "Cannot have more than 100 approvers"),
+ bypassers: z
+ .discriminatedUnion("type", [
+ z.object({ type: z.literal(BypasserType.Group), id: z.string() }),
+ z.object({
+ type: z.literal(BypasserType.User),
+ id: z.string().optional(),
+ username: z.string().optional()
+ })
+ ])
+ .array()
+ .max(100, "Cannot have more than 100 bypassers")
+ .optional(),
+ approvals: z.number().min(1).default(1),
+ enforcementLevel: z.nativeEnum(EnforcementLevel).default(EnforcementLevel.Hard),
+ allowedSelfApprovals: z.boolean().default(true)
+ })
+ .refine((data) => data.environment || data.environments, "At least one environment should be provided"),
+ response: {
+ 200: z.object({
+ approval: sapPubSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const approval = await server.services.secretApprovalPolicy.createSecretApprovalPolicy({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.body.workspaceId,
+ ...req.body,
+ name: req.body.name ?? `${req.body.environment || req.body.environments?.join(",")}-${nanoid(3)}`,
+ enforcementLevel: req.body.enforcementLevel
+ });
+ return { approval };
+ }
+ });
+
+ server.route({
+ url: "/:sapId",
+ method: "PATCH",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ sapId: z.string()
+ }),
+ body: z.object({
+ name: z.string().optional(),
+ approvers: z
+ .discriminatedUnion("type", [
+ z.object({ type: z.literal(ApproverType.Group), id: z.string() }),
+ z.object({ type: z.literal(ApproverType.User), id: z.string().optional(), username: z.string().optional() })
+ ])
+ .array()
+ .min(1, { message: "At least one approver should be provided" })
+ .max(100, "Cannot have more than 100 approvers"),
+ bypassers: z
+ .discriminatedUnion("type", [
+ z.object({ type: z.literal(BypasserType.Group), id: z.string() }),
+ z.object({ type: z.literal(BypasserType.User), id: z.string().optional(), username: z.string().optional() })
+ ])
+ .array()
+ .max(100, "Cannot have more than 100 bypassers")
+ .optional(),
+ approvals: z.number().min(1).default(1),
+ secretPath: z
+ .string()
+ .trim()
+ .min(1, { message: "Secret path cannot be empty" })
+ .optional()
+ .transform((val) => (val ? removeTrailingSlash(val) : undefined)),
+ enforcementLevel: z.nativeEnum(EnforcementLevel).optional(),
+ allowedSelfApprovals: z.boolean().default(true),
+ environments: z.array(z.string()).optional()
+ }),
+ response: {
+ 200: z.object({
+ approval: sapPubSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const approval = await server.services.secretApprovalPolicy.updateSecretApprovalPolicy({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body,
+ secretPolicyId: req.params.sapId
+ });
+ return { approval };
+ }
+ });
+
+ server.route({
+ url: "/:sapId",
+ method: "DELETE",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ sapId: z.string()
+ }),
+ response: {
+ 200: z.object({
+ approval: sapPubSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const approval = await server.services.secretApprovalPolicy.deleteSecretApprovalPolicy({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ secretPolicyId: req.params.sapId
+ });
+ return { approval };
+ }
+ });
+
+ server.route({
+ url: "/",
+ method: "GET",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ querystring: z.object({
+ workspaceId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ approvals: sapPubSchema
+ .extend({
+ approvers: z
+ .object({
+ id: z.string().nullable().optional(),
+ type: z.nativeEnum(ApproverType)
+ })
+ .array(),
+ bypassers: z
+ .object({
+ id: z.string().nullable().optional(),
+ type: z.nativeEnum(BypasserType)
+ })
+ .array()
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const approvals = await server.services.secretApprovalPolicy.getSecretApprovalPolicyByProjectId({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.query.workspaceId
+ });
+ return { approvals };
+ }
+ });
+
+ server.route({
+ url: "/:sapId",
+ method: "GET",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ sapId: z.string()
+ }),
+ response: {
+ 200: z.object({
+ approval: sapPubSchema.extend({
+ approvers: z
+ .object({
+ id: z.string().nullable().optional(),
+ type: z.nativeEnum(ApproverType),
+ username: z.string().nullable().optional()
+ })
+ .array(),
+ bypassers: z
+ .object({
+ id: z.string().nullable().optional(),
+ type: z.nativeEnum(BypasserType),
+ username: z.string().nullable().optional()
+ })
+ .array()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const approval = await server.services.secretApprovalPolicy.getSecretApprovalPolicyById({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.params
+ });
+
+ return { approval };
+ }
+ });
+
+ server.route({
+ url: "/board",
+ method: "GET",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ querystring: z.object({
+ workspaceId: z.string().trim(),
+ environment: z.string().trim(),
+ secretPath: z.string().trim().transform(removeTrailingSlash)
+ }),
+ response: {
+ 200: z.object({
+ policy: sapPubSchema
+ .extend({
+ userApprovers: z.object({ userId: z.string().nullable().optional() }).array()
+ })
+ .optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const policy = await server.services.secretApprovalPolicy.getSecretApprovalPolicyOfFolder({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.query.workspaceId,
+ ...req.query
+ });
+ return { policy };
+ }
+ });
+};
diff --git a/backend/src/ee/routes/v1/index.ts b/backend/src/ee/routes/v1/index.ts
index 5a43de381c..56d450df32 100644
--- a/backend/src/ee/routes/v1/index.ts
+++ b/backend/src/ee/routes/v1/index.ts
@@ -5,6 +5,9 @@ import { registerAccessApprovalRequestRouter } from "./access-approval-request-r
import { registerAssumePrivilegeRouter } from "./assume-privilege-router";
import { AUDIT_LOG_STREAM_REGISTER_ROUTER_MAP, registerAuditLogStreamRouter } from "./audit-log-stream-routers";
import { registerCaCrlRouter } from "./certificate-authority-crl-router";
+import { registerDeprecatedProjectRoleRouter } from "./deprecated-project-role-router";
+import { registerDeprecatedProjectRouter } from "./deprecated-project-router";
+import { registerDeprecatedSecretApprovalPolicyRouter } from "./deprecated-secret-approval-policy-router";
import { registerDynamicSecretLeaseRouter } from "./dynamic-secret-lease-router";
import { registerKubernetesDynamicSecretLeaseRouter } from "./dynamic-secret-lease-routers/kubernetes-lease-router";
import { registerDynamicSecretRouter } from "./dynamic-secret-router";
@@ -27,7 +30,6 @@ import { registerRateLimitRouter } from "./rate-limit-router";
import { registerRelayRouter } from "./relay-router";
import { registerSamlRouter } from "./saml-router";
import { registerScimRouter } from "./scim-router";
-import { registerSecretApprovalPolicyRouter } from "./secret-approval-policy-router";
import { registerSecretApprovalRequestRouter } from "./secret-approval-request-router";
import { registerSecretRotationProviderRouter } from "./secret-rotation-provider-router";
import { registerSecretRotationRouter } from "./secret-rotation-router";
@@ -47,18 +49,29 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
// org role starts with organization
await server.register(registerOrgRoleRouter, { prefix: "/organization" });
await server.register(registerLicenseRouter, { prefix: "/organizations" });
+
+ // depreciated in favour of infisical workspace
+ await server.register(
+ async (projectRouter) => {
+ await projectRouter.register(registerDeprecatedProjectRoleRouter);
+ await projectRouter.register(registerDeprecatedProjectRouter);
+ },
+ { prefix: "/workspace" }
+ );
+
await server.register(
async (projectRouter) => {
await projectRouter.register(registerProjectRoleRouter);
- await projectRouter.register(registerProjectRouter);
await projectRouter.register(registerTrustedIpRouter);
await projectRouter.register(registerAssumePrivilegeRouter);
+ await projectRouter.register(registerProjectRouter);
},
- { prefix: "/workspace" }
+ { prefix: "/projects" }
);
+
await server.register(registerSnapshotRouter, { prefix: "/secret-snapshot" });
await server.register(registerPITRouter, { prefix: "/pit" });
- await server.register(registerSecretApprovalPolicyRouter, { prefix: "/secret-approvals" });
+ await server.register(registerDeprecatedSecretApprovalPolicyRouter, { prefix: "/secret-approvals" });
await server.register(registerSecretApprovalRequestRouter, {
prefix: "/secret-approval-requests"
});
diff --git a/backend/src/ee/routes/v1/org-role-router.ts b/backend/src/ee/routes/v1/org-role-router.ts
index c8ee03a99b..070462d47c 100644
--- a/backend/src/ee/routes/v1/org-role-router.ts
+++ b/backend/src/ee/routes/v1/org-role-router.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { OrgMembershipRole, OrgMembershipsSchema, OrgRolesSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -42,6 +43,22 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
req.permission.authMethod,
req.permission.orgId
);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.CREATE_ORG_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: JSON.stringify(req.body.permissions)
+ }
+ }
+ });
+
return { role };
}
});
@@ -116,6 +133,22 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
req.permission.authMethod,
req.permission.orgId
);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.UPDATE_ORG_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: req.body.permissions ? JSON.stringify(req.body.permissions) : undefined
+ }
+ }
+ });
+
return { role };
}
});
@@ -146,6 +179,16 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
req.permission.authMethod,
req.permission.orgId
);
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.DELETE_ORG_ROLE,
+ metadata: { roleId: role.id, slug: role.slug, name: role.name }
+ }
+ });
+
return { role };
}
});
diff --git a/backend/src/ee/routes/v1/project-role-router.ts b/backend/src/ee/routes/v1/project-role-router.ts
index 949d4cf7ef..5a20ad893d 100644
--- a/backend/src/ee/routes/v1/project-role-router.ts
+++ b/backend/src/ee/routes/v1/project-role-router.ts
@@ -2,26 +2,27 @@ import { packRules } from "@casl/ability/extra";
import { z } from "zod";
import { ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
-import {
- backfillPermissionV1SchemaToV2Schema,
- ProjectPermissionV1Schema
-} from "@app/ee/services/permission/project-permission";
-import { PROJECT_ROLE } from "@app/lib/api-docs";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
+import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
+import { ApiDocsTags, PROJECT_ROLE } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { SanitizedRoleSchemaV1 } from "@app/server/routes/sanitizedSchemas";
+import { SanitizedRoleSchema } from "@app/server/routes/sanitizedSchemas";
import { AuthMode } from "@app/services/auth/auth-type";
import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
- url: "/:projectSlug/roles",
+ url: "/:projectId/roles",
config: {
rateLimit: writeLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectRoles],
description: "Create a project role",
security: [
{
@@ -29,10 +30,10 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- projectSlug: z.string().trim().describe(PROJECT_ROLE.CREATE.projectSlug)
+ projectId: z.string().trim().describe(PROJECT_ROLE.CREATE.projectId)
}),
body: z.object({
- slug: slugSchema({ max: 64 })
+ slug: slugSchema({ min: 1, max: 64 })
.refine(
(val) => !Object.values(ProjectMembershipRole).includes(val as ProjectMembershipRole),
"Please choose a different slug, the slug you have entered is reserved"
@@ -40,28 +41,48 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
.describe(PROJECT_ROLE.CREATE.slug),
name: z.string().min(1).trim().describe(PROJECT_ROLE.CREATE.name),
description: z.string().trim().nullish().describe(PROJECT_ROLE.CREATE.description),
- permissions: ProjectPermissionV1Schema.array().describe(PROJECT_ROLE.CREATE.permissions)
+ permissions: ProjectPermissionV2Schema.array()
+ .describe(PROJECT_ROLE.CREATE.permissions)
+ .refine(checkForInvalidPermissionCombination)
}),
response: {
200: z.object({
- role: SanitizedRoleSchemaV1
+ role: SanitizedRoleSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const stringifiedPermissions = JSON.stringify(packRules(req.body.permissions));
+
const role = await server.services.projectRole.createRole({
actorAuthMethod: req.permission.authMethod,
actorId: req.permission.id,
actorOrgId: req.permission.orgId,
actor: req.permission.type,
filter: {
- type: ProjectRoleServiceIdentifierType.SLUG,
- projectSlug: req.params.projectSlug
+ type: ProjectRoleServiceIdentifierType.ID,
+ projectId: req.params.projectId
},
data: {
...req.body,
- permissions: JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true)))
+ permissions: stringifiedPermissions
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.CREATE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: stringifiedPermissions
+ }
}
});
@@ -71,11 +92,13 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
server.route({
method: "PATCH",
- url: "/:projectSlug/roles/:roleId",
+ url: "/:projectId/roles/:roleId",
config: {
rateLimit: writeLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectRoles],
description: "Update a project role",
security: [
{
@@ -83,29 +106,33 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- projectSlug: z.string().trim().describe(PROJECT_ROLE.UPDATE.projectSlug),
+ projectId: z.string().trim().describe(PROJECT_ROLE.UPDATE.projectId),
roleId: z.string().trim().describe(PROJECT_ROLE.UPDATE.roleId)
}),
body: z.object({
- slug: slugSchema({ max: 64 })
+ slug: slugSchema({ min: 1, max: 64 })
.refine(
(val) => !Object.values(ProjectMembershipRole).includes(val as ProjectMembershipRole),
"Please choose a different slug, the slug you have entered is reserved"
)
- .describe(PROJECT_ROLE.UPDATE.slug)
- .optional(),
+ .optional()
+ .describe(PROJECT_ROLE.UPDATE.slug),
name: z.string().trim().optional().describe(PROJECT_ROLE.UPDATE.name),
description: z.string().trim().nullish().describe(PROJECT_ROLE.UPDATE.description),
- permissions: ProjectPermissionV1Schema.array().describe(PROJECT_ROLE.UPDATE.permissions).optional()
+ permissions: ProjectPermissionV2Schema.array()
+ .describe(PROJECT_ROLE.UPDATE.permissions)
+ .optional()
+ .superRefine(checkForInvalidPermissionCombination)
}),
response: {
200: z.object({
- role: SanitizedRoleSchemaV1
+ role: SanitizedRoleSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const stringifiedPermissions = req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined;
const role = await server.services.projectRole.updateRole({
actorAuthMethod: req.permission.authMethod,
actorId: req.permission.id,
@@ -114,22 +141,39 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
roleId: req.params.roleId,
data: {
...req.body,
- permissions: req.body.permissions
- ? JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true)))
- : undefined
+ permissions: stringifiedPermissions
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.UPDATE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: stringifiedPermissions
+ }
}
});
+
return { role };
}
});
server.route({
method: "DELETE",
- url: "/:projectSlug/roles/:roleId",
+ url: "/:projectId/roles/:roleId",
config: {
rateLimit: writeLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectRoles],
description: "Delete a project role",
security: [
{
@@ -137,12 +181,12 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- projectSlug: z.string().trim().describe(PROJECT_ROLE.DELETE.projectSlug),
+ projectId: z.string().trim().describe(PROJECT_ROLE.DELETE.projectId),
roleId: z.string().trim().describe(PROJECT_ROLE.DELETE.roleId)
}),
response: {
200: z.object({
- role: SanitizedRoleSchemaV1
+ role: SanitizedRoleSchema
})
}
},
@@ -155,17 +199,34 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
roleId: req.params.roleId
});
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.DELETE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: role.slug,
+ name: role.name
+ }
+ }
+ });
+
return { role };
}
});
server.route({
method: "GET",
- url: "/:projectSlug/roles",
+ url: "/:projectId/roles",
config: {
rateLimit: readLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectRoles],
description: "List project role",
security: [
{
@@ -173,7 +234,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- projectSlug: z.string().trim().describe(PROJECT_ROLE.LIST.projectSlug)
+ projectId: z.string().trim().describe(PROJECT_ROLE.LIST.projectId)
}),
response: {
200: z.object({
@@ -189,8 +250,8 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
actorOrgId: req.permission.orgId,
actor: req.permission.type,
filter: {
- type: ProjectRoleServiceIdentifierType.SLUG,
- projectSlug: req.params.projectSlug
+ type: ProjectRoleServiceIdentifierType.ID,
+ projectId: req.params.projectId
}
});
return { roles };
@@ -199,18 +260,20 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:projectSlug/roles/slug/:slug",
+ url: "/:projectId/roles/slug/:roleSlug",
config: {
rateLimit: readLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectRoles],
params: z.object({
- projectSlug: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.projectSlug),
- slug: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.roleSlug)
+ projectId: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.projectId),
+ roleSlug: z.string().trim().describe(PROJECT_ROLE.GET_ROLE_BY_SLUG.roleSlug)
}),
response: {
200: z.object({
- role: SanitizedRoleSchemaV1.omit({ version: true })
+ role: SanitizedRoleSchema.omit({ version: true })
})
}
},
@@ -222,12 +285,11 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
actorOrgId: req.permission.orgId,
actor: req.permission.type,
filter: {
- type: ProjectRoleServiceIdentifierType.SLUG,
- projectSlug: req.params.projectSlug
+ type: ProjectRoleServiceIdentifierType.ID,
+ projectId: req.params.projectId
},
- roleSlug: req.params.slug
+ roleSlug: req.params.roleSlug
});
-
return { role };
}
});
diff --git a/backend/src/ee/routes/v1/project-router.ts b/backend/src/ee/routes/v1/project-router.ts
index 8d8cc4817d..4988565f87 100644
--- a/backend/src/ee/routes/v1/project-router.ts
+++ b/backend/src/ee/routes/v1/project-router.ts
@@ -1,9 +1,9 @@
import { z } from "zod";
-import { AuditLogsSchema, SecretSnapshotsSchema } from "@app/db/schemas";
-import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
-import { ApiDocsTags, AUDIT_LOGS, PROJECTS } from "@app/lib/api-docs";
-import { getLastMidnightDateISO, removeTrailingSlash } from "@app/lib/fn";
+import { SecretSnapshotsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, PROJECTS } from "@app/lib/api-docs";
+import { removeTrailingSlash } from "@app/lib/fn";
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";
@@ -12,7 +12,7 @@ import { KmsType } from "@app/services/kms/kms-types";
export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/secret-snapshots",
+ url: "/:projectId/secret-snapshots",
config: {
rateLimit: readLimit
},
@@ -26,7 +26,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECTS.GET_SNAPSHOTS.workspaceId)
+ projectId: z.string().trim().describe(PROJECTS.GET_SNAPSHOTS.projectId)
}),
querystring: z.object({
environment: z.string().trim().describe(PROJECTS.GET_SNAPSHOTS.environment),
@@ -47,7 +47,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actorId: req.permission.id,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
...req.query
});
return { secretSnapshots };
@@ -56,13 +56,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/secret-snapshots/count",
+ url: "/:projectId/secret-snapshots/count",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
querystring: z.object({
environment: z.string().trim(),
@@ -81,7 +81,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
environment: req.query.environment,
path: req.query.path
});
@@ -89,140 +89,15 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
});
- /*
- * Daniel: This endpoint is no longer is use.
- * We are keeping it for now because it has been exposed in our public api docs for a while, so by removing it we are likely to break users workflows.
- *
- * Please refer to the new endpoint, GET /api/v1/organization/audit-logs, for the same (and more) functionality.
- */
server.route({
method: "GET",
- url: "/:workspaceId/audit-logs",
- config: {
- rateLimit: readLimit
- },
- schema: {
- description: "Return audit logs",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: z.object({
- workspaceId: z.string().trim().describe(AUDIT_LOGS.EXPORT.projectId)
- }),
- querystring: z
- .object({
- eventType: z.nativeEnum(EventType).optional().describe(AUDIT_LOGS.EXPORT.eventType),
- userAgentType: z.nativeEnum(UserAgentType).optional().describe(AUDIT_LOGS.EXPORT.userAgentType),
- startDate: z.string().datetime().optional().describe(AUDIT_LOGS.EXPORT.startDate),
- endDate: z.string().datetime().optional().describe(AUDIT_LOGS.EXPORT.endDate),
- offset: z.coerce.number().default(0).describe(AUDIT_LOGS.EXPORT.offset),
- limit: z.coerce.number().max(1000).default(20).describe(AUDIT_LOGS.EXPORT.limit),
- actor: z.string().optional().describe(AUDIT_LOGS.EXPORT.actor)
- })
- .superRefine((el, ctx) => {
- if (el.endDate && el.startDate) {
- const startDate = new Date(el.startDate);
- const endDate = new Date(el.endDate);
- const maxAllowedDate = new Date(startDate);
- maxAllowedDate.setMonth(maxAllowedDate.getMonth() + 3);
- if (endDate < startDate) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["endDate"],
- message: "End date cannot be before start date"
- });
- }
- if (endDate > maxAllowedDate) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- path: ["endDate"],
- message: "Dates must be within 3 months"
- });
- }
- }
- }),
- response: {
- 200: z.object({
- auditLogs: AuditLogsSchema.omit({
- eventMetadata: true,
- eventType: true,
- actor: true,
- actorMetadata: true
- })
- .merge(
- z.object({
- project: z
- .object({
- name: z.string(),
- slug: z.string()
- })
- .optional(),
- event: z.object({
- type: z.string(),
- metadata: z.any()
- }),
- actor: z.object({
- type: z.string(),
- metadata: z.any()
- })
- })
- )
- .array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const auditLogs = await server.services.auditLog.listAuditLogs({
- actorId: req.permission.id,
- actorOrgId: req.permission.orgId,
- actorAuthMethod: req.permission.authMethod,
- actor: req.permission.type,
-
- filter: {
- ...req.query,
- projectId: req.params.workspaceId,
- endDate: req.query.endDate || new Date().toISOString(),
- startDate: req.query.startDate || getLastMidnightDateISO(),
- auditLogActorId: req.query.actor,
- eventType: req.query.eventType ? [req.query.eventType] : undefined
- }
- });
- return { auditLogs };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:workspaceId/audit-logs/filters/actors",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- workspaceId: z.string().trim()
- }),
- response: {
- 200: z.object({
- actors: z.string().array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async () => ({ actors: [] })
- });
-
- server.route({
- method: "GET",
- url: "/:workspaceId/kms",
+ url: "/:projectId/kms",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.object({
@@ -241,7 +116,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
return kmsKey;
@@ -250,13 +125,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "PATCH",
- url: "/:workspaceId/kms",
+ url: "/:projectId/kms",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
body: z.object({
kms: z.discriminatedUnion("type", [
@@ -281,13 +156,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
...req.body
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
type: EventType.UPDATE_PROJECT_KMS,
metadata: {
@@ -307,13 +182,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/kms/backup",
+ url: "/:projectId/kms/backup",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.object({
@@ -328,12 +203,12 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
type: EventType.GET_PROJECT_KMS_BACKUP,
metadata: {}
@@ -346,13 +221,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
- url: "/:workspaceId/kms/backup",
+ url: "/:projectId/kms/backup",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
body: z.object({
backup: z.string().min(1)
@@ -374,13 +249,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
backup: req.body.backup
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
type: EventType.LOAD_PROJECT_KMS_BACKUP,
metadata: {}
@@ -393,13 +268,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
- url: "/:workspaceId/migrate-v3",
+ url: "/:projectId/migrate-v3",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
@@ -415,7 +290,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
return migration;
diff --git a/backend/src/ee/routes/v1/relay-router.ts b/backend/src/ee/routes/v1/relay-router.ts
index e204800882..f3d006b108 100644
--- a/backend/src/ee/routes/v1/relay-router.ts
+++ b/backend/src/ee/routes/v1/relay-router.ts
@@ -1,9 +1,10 @@
import { z } from "zod";
+import { RelaysSchema } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
-import { writeLimit } from "@app/server/config/rateLimiter";
+import { UnauthorizedError } from "@app/lib/errors";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -89,14 +90,59 @@ export const registerRelayRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- throw new BadRequestError({
- message: "Org relay registration is not yet supported"
- });
-
return server.services.relay.registerRelay({
...req.body,
identityId: req.permission.id,
- orgId: req.permission.orgId
+ orgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod
+ });
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ schema: {
+ response: {
+ 200: RelaysSchema.array()
+ }
+ },
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.relay.getRelays({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:id",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ id: z.string()
+ }),
+ response: {
+ 200: RelaysSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.relay.deleteRelay({
+ id: req.params.id,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
});
}
});
diff --git a/backend/src/ee/routes/v1/secret-approval-request-router.ts b/backend/src/ee/routes/v1/secret-approval-request-router.ts
index bdc9c2dcd2..6a9b59f001 100644
--- a/backend/src/ee/routes/v1/secret-approval-request-router.ts
+++ b/backend/src/ee/routes/v1/secret-approval-request-router.ts
@@ -27,7 +27,7 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
},
schema: {
querystring: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
environment: z.string().trim().optional(),
committer: z.string().trim().optional(),
search: z.string().trim().optional(),
@@ -80,7 +80,7 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.query,
- projectId: req.query.workspaceId
+ projectId: req.query.projectId
});
return { approvals, totalCount };
}
@@ -94,7 +94,7 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
},
schema: {
querystring: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
policyId: z.string().trim().optional()
}),
response: {
@@ -113,7 +113,7 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.query.workspaceId,
+ projectId: req.query.projectId,
policyId: req.query.policyId
});
return { approvals };
diff --git a/backend/src/ee/routes/v1/trusted-ip-router.ts b/backend/src/ee/routes/v1/trusted-ip-router.ts
index b6fc3cc90f..5416e86131 100644
--- a/backend/src/ee/routes/v1/trusted-ip-router.ts
+++ b/backend/src/ee/routes/v1/trusted-ip-router.ts
@@ -9,13 +9,13 @@ import { AuthMode } from "@app/services/auth/auth-type";
export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/trusted-ips",
+ url: "/:projectId/trusted-ips",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.object({
@@ -27,7 +27,7 @@ export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
const trustedIps = await server.services.trustedIp.listIpsByProjectId({
actorAuthMethod: req.permission.authMethod,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
actor: req.permission.type,
actorId: req.permission.id,
actorOrgId: req.permission.orgId
@@ -38,13 +38,13 @@ export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
- url: "/:workspaceId/trusted-ips",
+ url: "/:projectId/trusted-ips",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
body: z.object({
ipAddress: z.string().trim(),
@@ -61,7 +61,7 @@ export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
handler: async (req) => {
const { trustedIp, project } = await server.services.trustedIp.addProjectIp({
actorAuthMethod: req.permission.authMethod,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
actor: req.permission.type,
actorId: req.permission.id,
actorOrgId: req.permission.orgId,
@@ -86,13 +86,13 @@ export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
server.route({
method: "PATCH",
- url: "/:workspaceId/trusted-ips/:trustedIpId",
+ url: "/:projectId/trusted-ips/:trustedIpId",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
trustedIpId: z.string().trim()
}),
body: z.object({
@@ -108,7 +108,7 @@ export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const { trustedIp, project } = await server.services.trustedIp.updateProjectIp({
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -135,13 +135,13 @@ export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
server.route({
method: "DELETE",
- url: "/:workspaceId/trusted-ips/:trustedIpId",
+ url: "/:projectId/trusted-ips/:trustedIpId",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
trustedIpId: z.string().trim()
}),
response: {
@@ -153,7 +153,7 @@ export const registerTrustedIpRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const { trustedIp, project } = await server.services.trustedIp.deleteProjectIp({
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
diff --git a/backend/src/ee/routes/v2/project-role-router.ts b/backend/src/ee/routes/v2/deprecated-project-role-router.ts
similarity index 81%
rename from backend/src/ee/routes/v2/project-role-router.ts
rename to backend/src/ee/routes/v2/deprecated-project-role-router.ts
index 5389293164..326bda06a4 100644
--- a/backend/src/ee/routes/v2/project-role-router.ts
+++ b/backend/src/ee/routes/v2/deprecated-project-role-router.ts
@@ -2,6 +2,7 @@ import { packRules } from "@casl/ability/extra";
import { z } from "zod";
import { ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
import { ApiDocsTags, PROJECT_ROLE } from "@app/lib/api-docs";
@@ -12,7 +13,7 @@ import { SanitizedRoleSchema } from "@app/server/routes/sanitizedSchemas";
import { AuthMode } from "@app/services/auth/auth-type";
import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
-export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
+export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
url: "/:projectId/roles",
@@ -52,6 +53,8 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const stringifiedPermissions = JSON.stringify(packRules(req.body.permissions));
+
const role = await server.services.projectRole.createRole({
actorAuthMethod: req.permission.authMethod,
actorId: req.permission.id,
@@ -63,9 +66,26 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
},
data: {
...req.body,
- permissions: JSON.stringify(packRules(req.body.permissions))
+ permissions: stringifiedPermissions
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.CREATE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: stringifiedPermissions
+ }
}
});
+
return { role };
}
});
@@ -112,6 +132,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const stringifiedPermissions = req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined;
const role = await server.services.projectRole.updateRole({
actorAuthMethod: req.permission.authMethod,
actorId: req.permission.id,
@@ -120,9 +141,26 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
roleId: req.params.roleId,
data: {
...req.body,
- permissions: req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined
+ permissions: stringifiedPermissions
}
});
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.UPDATE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: req.body.slug,
+ name: req.body.name,
+ description: req.body.description,
+ permissions: stringifiedPermissions
+ }
+ }
+ });
+
return { role };
}
});
@@ -161,6 +199,21 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
roleId: req.params.roleId
});
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: role.projectId,
+ event: {
+ type: EventType.DELETE_PROJECT_ROLE,
+ metadata: {
+ roleId: role.id,
+ slug: role.slug,
+ name: role.name
+ }
+ }
+ });
+
return { role };
}
});
diff --git a/backend/src/ee/routes/v2/index.ts b/backend/src/ee/routes/v2/index.ts
index e082773dd6..c402ab00aa 100644
--- a/backend/src/ee/routes/v2/index.ts
+++ b/backend/src/ee/routes/v2/index.ts
@@ -7,15 +7,16 @@ import {
SECRET_SCANNING_REGISTER_ROUTER_MAP
} from "@app/ee/routes/v2/secret-scanning-v2-routers";
+import { registerDeprecatedProjectRoleRouter } from "./deprecated-project-role-router";
import { registerGatewayV2Router } from "./gateway-router";
import { registerIdentityProjectAdditionalPrivilegeRouter } from "./identity-project-additional-privilege-router";
-import { registerProjectRoleRouter } from "./project-role-router";
+import { registerSecretApprovalPolicyRouter } from "./secret-approval-policy-router";
export const registerV2EERoutes = async (server: FastifyZodProvider) => {
- // org role starts with organization
await server.register(
async (projectRouter) => {
- await projectRouter.register(registerProjectRoleRouter);
+ // this has been depreciated and moved to /api/v1/projects
+ await projectRouter.register(registerDeprecatedProjectRoleRouter);
},
{ prefix: "/workspace" }
);
@@ -26,6 +27,8 @@ export const registerV2EERoutes = async (server: FastifyZodProvider) => {
await server.register(registerGatewayV2Router, { prefix: "/gateways" });
+ await server.register(registerSecretApprovalPolicyRouter, { prefix: "/secret-approvals" });
+
await server.register(
async (secretRotationV2Router) => {
// register generic secret rotation endpoints
diff --git a/backend/src/ee/routes/v1/secret-approval-policy-router.ts b/backend/src/ee/routes/v2/secret-approval-policy-router.ts
similarity index 97%
rename from backend/src/ee/routes/v1/secret-approval-policy-router.ts
rename to backend/src/ee/routes/v2/secret-approval-policy-router.ts
index dc87b83f2f..f7f770197d 100644
--- a/backend/src/ee/routes/v1/secret-approval-policy-router.ts
+++ b/backend/src/ee/routes/v2/secret-approval-policy-router.ts
@@ -19,7 +19,7 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
schema: {
body: z
.object({
- workspaceId: z.string(),
+ projectId: z.string(),
name: z.string().optional(),
environment: z.string().optional(),
environments: z.string().array().optional(),
@@ -69,7 +69,6 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.body.workspaceId,
...req.body,
name: req.body.name ?? `${req.body.environment || req.body.environments?.join(",")}-${nanoid(3)}`,
enforcementLevel: req.body.enforcementLevel
@@ -174,7 +173,7 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
},
schema: {
querystring: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.object({
@@ -204,7 +203,7 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.query.workspaceId
+ projectId: req.query.projectId
});
return { approvals };
}
@@ -263,7 +262,7 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
},
schema: {
querystring: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
environment: z.string().trim(),
secretPath: z.string().trim().transform(removeTrailingSlash)
}),
@@ -284,7 +283,6 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.query.workspaceId,
...req.query
});
return { policy };
diff --git a/backend/src/ee/services/access-approval-request/access-approval-request-service.ts b/backend/src/ee/services/access-approval-request/access-approval-request-service.ts
index 008b61919f..da87978fd3 100644
--- a/backend/src/ee/services/access-approval-request/access-approval-request-service.ts
+++ b/backend/src/ee/services/access-approval-request/access-approval-request-service.ts
@@ -777,6 +777,20 @@ export const accessApprovalRequestServiceFactory = ({
.map((appUser) => appUser.email)
.filter((email): email is string => !!email);
+ const approvalPath = `/projects/secret-management/${project.id}/approval`;
+ const approvalUrl = `${cfg.SITE_URL}${approvalPath}`;
+
+ await notificationService.createUserNotifications(
+ approverUsersForEmail.map((approver) => ({
+ userId: approver.id,
+ orgId: actorOrgId,
+ type: NotificationType.ACCESS_POLICY_BYPASSED,
+ title: "Secret Access Policy Bypassed",
+ body: `**${actingUser.firstName} ${actingUser.lastName}** (${actingUser.email}) has accessed a secret in **${policy.secretPath || "/"}** in the **${environment?.name || permissionEnvironment}** environment for project **${project.name}** without obtaining the required approval.`,
+ link: approvalPath
+ }))
+ );
+
if (recipientEmails.length > 0) {
await smtpService.sendMail({
recipients: recipientEmails,
@@ -788,7 +802,7 @@ export const accessApprovalRequestServiceFactory = ({
bypassReason: bypassReason || "No reason provided",
secretPath: policy.secretPath || "/",
environment: environment?.name || permissionEnvironment,
- approvalUrl: `${cfg.SITE_URL}/projects/secret-management/${project.id}/approval`,
+ approvalUrl,
requestType: "access"
},
template: SmtpTemplates.AccessSecretRequestBypassed
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts
index 78233f774d..ebef18574c 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-enums.ts
@@ -1,4 +1,5 @@
export enum LogProvider {
+ Azure = "azure",
Cribl = "cribl",
Custom = "custom",
Datadog = "datadog",
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-factory.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-factory.ts
index 21d629a536..8dde0e0795 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-factory.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-factory.ts
@@ -1,5 +1,6 @@
import { LogProvider } from "./audit-log-stream-enums";
import { TAuditLogStreamCredentials, TLogStreamFactory } from "./audit-log-stream-types";
+import { AzureProviderFactory } from "./azure/azure-provider-factory";
import { CriblProviderFactory } from "./cribl/cribl-provider-factory";
import { CustomProviderFactory } from "./custom/custom-provider-factory";
import { DatadogProviderFactory } from "./datadog/datadog-provider-factory";
@@ -8,6 +9,7 @@ import { SplunkProviderFactory } from "./splunk/splunk-provider-factory";
type TLogStreamFactoryImplementation = TLogStreamFactory<TAuditLogStreamCredentials>;
export const LOG_STREAM_FACTORY_MAP: Record<LogProvider, TLogStreamFactoryImplementation> = {
+ [LogProvider.Azure]: AzureProviderFactory as TLogStreamFactoryImplementation,
[LogProvider.Datadog]: DatadogProviderFactory as TLogStreamFactoryImplementation,
[LogProvider.Splunk]: SplunkProviderFactory as TLogStreamFactoryImplementation,
[LogProvider.Custom]: CustomProviderFactory as TLogStreamFactoryImplementation,
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-fns.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-fns.ts
index d03a5c8a74..07d833030a 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-fns.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-fns.ts
@@ -3,6 +3,7 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TAuditLogStream, TAuditLogStreamCredentials } from "./audit-log-stream-types";
+import { getAzureProviderListItem } from "./azure/azure-provider-fns";
import { getCriblProviderListItem } from "./cribl/cribl-provider-fns";
import { getCustomProviderListItem } from "./custom/custom-provider-fns";
import { getDatadogProviderListItem } from "./datadog/datadog-provider-fns";
@@ -13,6 +14,7 @@ export const listProviderOptions = () => {
getDatadogProviderListItem(),
getSplunkProviderListItem(),
getCustomProviderListItem(),
+ getAzureProviderListItem(),
getCriblProviderListItem()
].sort((a, b) => a.name.localeCompare(b.name));
};
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
index 1ef33befe3..5983e50bf9 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-types.ts
@@ -1,17 +1,19 @@
import { TAuditLogs } from "@app/db/schemas";
import { LogProvider } from "./audit-log-stream-enums";
+import { TAzureProvider, TAzureProviderCredentials } from "./azure/azure-provider-types";
import { TCriblProvider, TCriblProviderCredentials } from "./cribl/cribl-provider-types";
import { TCustomProvider, TCustomProviderCredentials } from "./custom/custom-provider-types";
import { TDatadogProvider, TDatadogProviderCredentials } from "./datadog/datadog-provider-types";
import { TSplunkProvider, TSplunkProviderCredentials } from "./splunk/splunk-provider-types";
-export type TAuditLogStream = TDatadogProvider | TSplunkProvider | TCustomProvider | TCriblProvider;
+export type TAuditLogStream = TDatadogProvider | TSplunkProvider | TCustomProvider | TAzureProvider | TCriblProvider;
export type TAuditLogStreamCredentials =
| TDatadogProviderCredentials
| TSplunkProviderCredentials
| TCustomProviderCredentials
+ | TAzureProviderCredentials
| TCriblProviderCredentials;
export type TCreateAuditLogStreamDTO = {
diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
new file mode 100644
index 0000000000..9a6157666b
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-factory.ts
@@ -0,0 +1,98 @@
+import { RawAxiosRequestHeaders } from "axios";
+
+import { request } from "@app/lib/config/request";
+import { BadRequestError } from "@app/lib/errors";
+import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
+
+import { AUDIT_LOG_STREAM_TIMEOUT } from "../../audit-log/audit-log-queue";
+import { TLogStreamFactoryStreamLog, TLogStreamFactoryValidateCredentials } from "../audit-log-stream-types";
+import { TAzureProviderCredentials } from "./azure-provider-types";
+
+function createPayload(event: { createdAt?: Date | string } & Record<string, unknown>) {
+ return [
+ {
+ ...event,
+ TimeGenerated: (event.createdAt ? new Date(event.createdAt) : new Date()).toISOString()
+ }
+ ];
+}
+
+async function getAzureToken(tenantId: string, clientId: string, clientSecret: string) {
+ const { data } = await request.post<{ access_token: string }>(
+ `https://login.microsoftonline.com/${tenantId}/oauth2/v2.0/token`,
+ new URLSearchParams({
+ grant_type: "client_credentials",
+ client_id: clientId,
+ client_secret: clientSecret,
+ scope: "https://monitor.azure.com/.default"
+ }),
+ {
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded"
+ }
+ }
+ );
+
+ return data.access_token;
+}
+
+export const AzureProviderFactory = () => {
+ const validateCredentials: TLogStreamFactoryValidateCredentials<TAzureProviderCredentials> = async ({
+ credentials
+ }) => {
+ const { tenantId, clientId, clientSecret, dceUrl, dcrId, cltName } = credentials;
+
+ await blockLocalAndPrivateIpAddresses(dceUrl);
+
+ const token = await getAzureToken(tenantId, clientId, clientSecret);
+
+ const streamHeaders: RawAxiosRequestHeaders = {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`
+ };
+
+ await request
+ .post(
+ `${dceUrl}/dataCollectionRules/${dcrId}/streams/Custom-${cltName}_CL?api-version=2023-01-01`,
+ createPayload({ ping: "ok" }),
+ {
+ headers: streamHeaders,
+ timeout: AUDIT_LOG_STREAM_TIMEOUT,
+ signal: AbortSignal.timeout(AUDIT_LOG_STREAM_TIMEOUT)
+ }
+ )
+ .catch((err) => {
+ throw new BadRequestError({ message: `Failed to connect with Azure: ${(err as Error)?.message}` });
+ });
+
+ return credentials;
+ };
+
+ const streamLog: TLogStreamFactoryStreamLog<TAzureProviderCredentials> = async ({ credentials, auditLog }) => {
+ const { tenantId, clientId, clientSecret, dceUrl, dcrId, cltName } = credentials;
+
+ await blockLocalAndPrivateIpAddresses(dceUrl);
+
+ const token = await getAzureToken(tenantId, clientId, clientSecret);
+
+ const streamHeaders: RawAxiosRequestHeaders = {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`
+ };
+
+ await request.post(
+ `${dceUrl}/dataCollectionRules/${dcrId}/streams/Custom-${cltName}_CL?api-version=2023-01-01`,
+ createPayload(auditLog),
+ {
+ headers: streamHeaders,
+ timeout: AUDIT_LOG_STREAM_TIMEOUT,
+ signal: AbortSignal.timeout(AUDIT_LOG_STREAM_TIMEOUT)
+ }
+ );
+ };
+
+ return {
+ validateCredentials,
+ streamLog
+ };
+};
diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-fns.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-fns.ts
new file mode 100644
index 0000000000..e558b69e25
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-fns.ts
@@ -0,0 +1,8 @@
+import { LogProvider } from "../audit-log-stream-enums";
+
+export const getAzureProviderListItem = () => {
+ return {
+ name: "Azure" as const,
+ provider: LogProvider.Azure as const
+ };
+};
diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-schemas.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-schemas.ts
new file mode 100644
index 0000000000..50def1d790
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-schemas.ts
@@ -0,0 +1,52 @@
+import RE2 from "re2";
+import { z } from "zod";
+
+import { LogProvider } from "../audit-log-stream-enums";
+import { BaseProviderSchema } from "../audit-log-stream-schemas";
+
+export const AzureProviderCredentialsSchema = z.object({
+ tenantId: z.string().trim().uuid(),
+ clientId: z.string().trim().uuid(),
+ clientSecret: z.string().trim().length(40),
+
+ // Data Collection Endpoint URL
+ dceUrl: z.string().trim().url().min(1).max(255),
+
+ // Data Collection Rule Immutable ID
+ dcrId: z
+ .string()
+ .trim()
+ .refine((val) => new RE2(/^dcr-[0-9a-f]{32}$/).test(val), "DCR ID must be in dcr-*** format"),
+
+ // Custom Log Table Name
+ cltName: z.string().trim().min(1).max(255)
+});
+
+const BaseAzureProviderSchema = BaseProviderSchema.extend({ provider: z.literal(LogProvider.Azure) });
+
+export const AzureProviderSchema = BaseAzureProviderSchema.extend({
+ credentials: AzureProviderCredentialsSchema
+});
+
+export const SanitizedAzureProviderSchema = BaseAzureProviderSchema.extend({
+ credentials: AzureProviderCredentialsSchema.pick({
+ tenantId: true,
+ clientId: true,
+ dceUrl: true,
+ dcrId: true,
+ cltName: true
+ })
+});
+
+export const AzureProviderListItemSchema = z.object({
+ name: z.literal("Azure"),
+ provider: z.literal(LogProvider.Azure)
+});
+
+export const CreateAzureProviderLogStreamSchema = z.object({
+ credentials: AzureProviderCredentialsSchema
+});
+
+export const UpdateAzureProviderLogStreamSchema = z.object({
+ credentials: AzureProviderCredentialsSchema
+});
diff --git a/backend/src/ee/services/audit-log-stream/azure/azure-provider-types.ts b/backend/src/ee/services/audit-log-stream/azure/azure-provider-types.ts
new file mode 100644
index 0000000000..0ba5f120d9
--- /dev/null
+++ b/backend/src/ee/services/audit-log-stream/azure/azure-provider-types.ts
@@ -0,0 +1,7 @@
+import { z } from "zod";
+
+import { AzureProviderCredentialsSchema, AzureProviderSchema } from "./azure-provider-schemas";
+
+export type TAzureProvider = z.infer<typeof AzureProviderSchema>;
+
+export type TAzureProviderCredentials = z.infer<typeof AzureProviderCredentialsSchema>;
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 10c84cc4a9..e3ba9b72f5 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -146,7 +146,7 @@ export enum EventType {
MOVE_SECRETS = "move-secrets",
DELETE_SECRET = "delete-secret",
DELETE_SECRETS = "delete-secrets",
- GET_WORKSPACE_KEY = "get-workspace-key",
+ GET_PROJECT_KEY = "get-project-key",
AUTHORIZE_INTEGRATION = "authorize-integration",
UPDATE_INTEGRATION_AUTH = "update-integration-auth",
UNAUTHORIZE_INTEGRATION = "unauthorize-integration",
@@ -199,6 +199,7 @@ export enum EventType {
CREATE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET = "create-identity-universal-auth-client-secret",
REVOKE_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET = "revoke-identity-universal-auth-client-secret",
CLEAR_IDENTITY_UNIVERSAL_AUTH_LOCKOUTS = "clear-identity-universal-auth-lockouts",
+ CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS = "clear-identity-ldap-auth-lockouts",
GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRETS = "get-identity-universal-auth-client-secret",
GET_IDENTITY_UNIVERSAL_AUTH_CLIENT_SECRET_BY_ID = "get-identity-universal-auth-client-secret-by-id",
@@ -249,9 +250,9 @@ export enum EventType {
UPDATE_ENVIRONMENT = "update-environment",
DELETE_ENVIRONMENT = "delete-environment",
GET_ENVIRONMENT = "get-environment",
- ADD_WORKSPACE_MEMBER = "add-workspace-member",
- ADD_BATCH_WORKSPACE_MEMBER = "add-workspace-members",
- REMOVE_WORKSPACE_MEMBER = "remove-workspace-member",
+ ADD_PROJECT_MEMBER = "add-project-member",
+ ADD_BATCH_PROJECT_MEMBER = "add-project-members",
+ REMOVE_PROJECT_MEMBER = "remove-project-member",
CREATE_FOLDER = "create-folder",
UPDATE_FOLDER = "update-folder",
DELETE_FOLDER = "delete-folder",
@@ -264,8 +265,8 @@ export enum EventType {
CREATE_SECRET_IMPORT = "create-secret-import",
UPDATE_SECRET_IMPORT = "update-secret-import",
DELETE_SECRET_IMPORT = "delete-secret-import",
- UPDATE_USER_WORKSPACE_ROLE = "update-user-workspace-role",
- UPDATE_USER_WORKSPACE_DENIED_PERMISSIONS = "update-user-workspace-denied-permissions",
+ UPDATE_USER_PROJECT_ROLE = "update-user-project-role",
+ UPDATE_USER_PROJECT_DENIED_PERMISSIONS = "update-user-project-denied-permissions",
SECRET_APPROVAL_MERGED = "secret-approval-merged",
SECRET_APPROVAL_REQUEST = "secret-approval-request",
SECRET_APPROVAL_CLOSED = "secret-approval-closed",
@@ -392,6 +393,8 @@ export enum EventType {
CREATE_APP_CONNECTION = "create-app-connection",
UPDATE_APP_CONNECTION = "update-app-connection",
DELETE_APP_CONNECTION = "delete-app-connection",
+ GET_APP_CONNECTION_USAGE = "get-app-connection-usage",
+ MIGRATE_APP_CONNECTION = "migrate-app-connection",
CREATE_SHARED_SECRET = "create-shared-secret",
CREATE_SECRET_REQUEST = "create-secret-request",
DELETE_SHARED_SECRET = "delete-shared-secret",
@@ -475,9 +478,21 @@ export enum EventType {
UPDATE_PROJECT = "update-project",
DELETE_PROJECT = "delete-project",
+ CREATE_PROJECT_ROLE = "create-project-role",
+ UPDATE_PROJECT_ROLE = "update-project-role",
+ DELETE_PROJECT_ROLE = "delete-project-role",
+
+ CREATE_ORG_ROLE = "create-org-role",
+ UPDATE_ORG_ROLE = "update-org-role",
+ DELETE_ORG_ROLE = "delete-org-role",
+
CREATE_SECRET_REMINDER = "create-secret-reminder",
GET_SECRET_REMINDER = "get-secret-reminder",
- DELETE_SECRET_REMINDER = "delete-secret-reminder"
+ DELETE_SECRET_REMINDER = "delete-secret-reminder",
+
+ DASHBOARD_LIST_SECRETS = "dashboard-list-secrets",
+ DASHBOARD_GET_SECRET_VALUE = "dashboard-get-secret-value",
+ DASHBOARD_GET_SECRET_VERSION_VALUE = "dashboard-get-secret-version-value"
}
export const filterableSecretEvents: EventType[] = [
@@ -588,6 +603,7 @@ interface CreateSecretEvent {
secretKey: string;
secretVersion: number;
secretMetadata?: TSecretMetadata;
+ secretTags?: string[];
};
}
@@ -602,6 +618,7 @@ interface CreateSecretBatchEvent {
secretPath?: string;
secretVersion: number;
secretMetadata?: TSecretMetadata;
+ secretTags?: string[];
}>;
};
}
@@ -615,6 +632,7 @@ interface UpdateSecretEvent {
secretKey: string;
secretVersion: number;
secretMetadata?: TSecretMetadata;
+ secretTags?: string[];
};
}
@@ -629,6 +647,7 @@ interface UpdateSecretBatchEvent {
secretVersion: number;
secretMetadata?: TSecretMetadata;
secretPath?: string;
+ secretTags?: string[];
}>;
};
}
@@ -664,8 +683,8 @@ interface DeleteSecretBatchEvent {
};
}
-interface GetWorkspaceKeyEvent {
- type: EventType.GET_WORKSPACE_KEY;
+interface GetProjectKeyEvent {
+ type: EventType.GET_PROJECT_KEY;
metadata: {
keyId: string;
};
@@ -1370,6 +1389,10 @@ interface AddIdentityLdapAuthEvent {
allowedFields?: TAllowedFields[];
url: string;
templateId?: string | null;
+ lockoutEnabled: boolean;
+ lockoutThreshold: number;
+ lockoutDurationSeconds: number;
+ lockoutCounterResetSeconds: number;
};
}
@@ -1384,6 +1407,10 @@ interface UpdateIdentityLdapAuthEvent {
allowedFields?: TAllowedFields[];
url?: string;
templateId?: string | null;
+ lockoutEnabled?: boolean;
+ lockoutThreshold?: number;
+ lockoutDurationSeconds?: number;
+ lockoutCounterResetSeconds?: number;
};
}
@@ -1401,6 +1428,13 @@ interface RevokeIdentityLdapAuthEvent {
};
}
+interface ClearIdentityLdapAuthLockoutsEvent {
+ type: EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS;
+ metadata: {
+ identityId: string;
+ };
+}
+
interface LoginIdentityOidcAuthEvent {
type: EventType.LOGIN_IDENTITY_OIDC_AUTH;
metadata: {
@@ -1557,24 +1591,24 @@ interface DeleteEnvironmentEvent {
};
}
-interface AddWorkspaceMemberEvent {
- type: EventType.ADD_WORKSPACE_MEMBER;
+interface AddProjectMemberEvent {
+ type: EventType.ADD_PROJECT_MEMBER;
metadata: {
userId: string;
email: string;
};
}
-interface AddBatchWorkspaceMemberEvent {
- type: EventType.ADD_BATCH_WORKSPACE_MEMBER;
+interface AddBatchProjectMemberEvent {
+ type: EventType.ADD_BATCH_PROJECT_MEMBER;
metadata: Array<{
userId: string;
email: string;
}>;
}
-interface RemoveWorkspaceMemberEvent {
- type: EventType.REMOVE_WORKSPACE_MEMBER;
+interface RemoveProjectMemberEvent {
+ type: EventType.REMOVE_PROJECT_MEMBER;
metadata: {
userId: string;
email: string;
@@ -1713,7 +1747,7 @@ interface DeleteSecretImportEvent {
}
interface UpdateUserRole {
- type: EventType.UPDATE_USER_WORKSPACE_ROLE;
+ type: EventType.UPDATE_USER_PROJECT_ROLE;
metadata: {
userId: string;
email: string;
@@ -1723,7 +1757,7 @@ interface UpdateUserRole {
}
interface UpdateUserDeniedPermissions {
- type: EventType.UPDATE_USER_WORKSPACE_DENIED_PERMISSIONS;
+ type: EventType.UPDATE_USER_PROJECT_DENIED_PERMISSIONS;
metadata: {
userId: string;
email: string;
@@ -2781,14 +2815,31 @@ interface GetAppConnectionEvent {
};
}
+interface GetAppConnectionUsageEvent {
+ type: EventType.GET_APP_CONNECTION_USAGE;
+ metadata: {
+ connectionId: string;
+ };
+}
+
+interface MigrateAppConnectionEvent {
+ type: EventType.MIGRATE_APP_CONNECTION;
+ metadata: {
+ connectionId: string;
+ };
+}
+
interface CreateAppConnectionEvent {
type: EventType.CREATE_APP_CONNECTION;
- metadata: Omit<TCreateAppConnectionDTO, "credentials"> & { connectionId: string };
+ metadata: Omit<TCreateAppConnectionDTO, "credentials" | "projectId"> & { connectionId: string };
}
interface UpdateAppConnectionEvent {
type: EventType.UPDATE_APP_CONNECTION;
- metadata: Omit<TUpdateAppConnectionDTO, "credentials"> & { connectionId: string; credentialsUpdated: boolean };
+ metadata: Omit<TUpdateAppConnectionDTO, "credentials" | "projectId"> & {
+ connectionId: string;
+ credentialsUpdated: boolean;
+ };
}
interface DeleteAppConnectionEvent {
@@ -3467,6 +3518,96 @@ interface ProjectDeleteEvent {
};
}
+interface DashboardListSecretsEvent {
+ type: EventType.DASHBOARD_LIST_SECRETS;
+ metadata: {
+ environment: string;
+ secretPath: string;
+ numberOfSecrets: number;
+ secretIds: string[];
+ };
+}
+
+interface DashboardGetSecretValueEvent {
+ type: EventType.DASHBOARD_GET_SECRET_VALUE;
+ metadata: {
+ secretId: string;
+ secretKey: string;
+ environment: string;
+ secretPath: string;
+ };
+}
+
+interface DashboardGetSecretVersionValueEvent {
+ type: EventType.DASHBOARD_GET_SECRET_VERSION_VALUE;
+ metadata: {
+ secretId: string;
+ version: string;
+ };
+}
+
+interface ProjectRoleCreateEvent {
+ type: EventType.CREATE_PROJECT_ROLE;
+ metadata: {
+ roleId: string;
+ slug: string;
+ name: string;
+ description?: string | null;
+ permissions: string;
+ };
+}
+
+interface ProjectRoleUpdateEvent {
+ type: EventType.UPDATE_PROJECT_ROLE;
+ metadata: {
+ roleId: string;
+ slug?: string;
+ name?: string;
+ description?: string | null;
+ permissions?: string;
+ };
+}
+
+interface ProjectRoleDeleteEvent {
+ type: EventType.DELETE_PROJECT_ROLE;
+ metadata: {
+ roleId: string;
+ slug: string;
+ name: string;
+ };
+}
+
+interface OrgRoleCreateEvent {
+ type: EventType.CREATE_ORG_ROLE;
+ metadata: {
+ roleId: string;
+ slug: string;
+ name: string;
+ description?: string | null;
+ permissions: string;
+ };
+}
+
+interface OrgRoleUpdateEvent {
+ type: EventType.UPDATE_ORG_ROLE;
+ metadata: {
+ roleId: string;
+ slug?: string;
+ name?: string;
+ description?: string | null;
+ permissions?: string;
+ };
+}
+
+interface OrgRoleDeleteEvent {
+ type: EventType.DELETE_ORG_ROLE;
+ metadata: {
+ roleId: string;
+ slug: string;
+ name: string;
+ };
+}
+
export type Event =
| GetSecretsEvent
| GetSecretEvent
@@ -3477,7 +3618,7 @@ export type Event =
| MoveSecretsEvent
| DeleteSecretEvent
| DeleteSecretBatchEvent
- | GetWorkspaceKeyEvent
+ | GetProjectKeyEvent
| AuthorizeIntegrationEvent
| UpdateIntegrationAuthEvent
| UnauthorizeIntegrationEvent
@@ -3562,13 +3703,14 @@ export type Event =
| UpdateIdentityLdapAuthEvent
| GetIdentityLdapAuthEvent
| RevokeIdentityLdapAuthEvent
+ | ClearIdentityLdapAuthLockoutsEvent
| CreateEnvironmentEvent
| GetEnvironmentEvent
| UpdateEnvironmentEvent
| DeleteEnvironmentEvent
- | AddWorkspaceMemberEvent
- | AddBatchWorkspaceMemberEvent
- | RemoveWorkspaceMemberEvent
+ | AddProjectMemberEvent
+ | AddBatchProjectMemberEvent
+ | RemoveProjectMemberEvent
| CreateFolderEvent
| UpdateFolderEvent
| DeleteFolderEvent
@@ -3697,6 +3839,8 @@ export type Event =
| CreateAppConnectionEvent
| UpdateAppConnectionEvent
| DeleteAppConnectionEvent
+ | GetAppConnectionUsageEvent
+ | MigrateAppConnectionEvent
| GetSshHostGroupEvent
| CreateSshHostGroupEvent
| UpdateSshHostGroupEvent
@@ -3780,4 +3924,13 @@ export type Event =
| ProjectDeleteEvent
| SecretReminderCreateEvent
| SecretReminderGetEvent
- | SecretReminderDeleteEvent;
+ | SecretReminderDeleteEvent
+ | DashboardListSecretsEvent
+ | DashboardGetSecretValueEvent
+ | DashboardGetSecretVersionValueEvent
+ | ProjectRoleCreateEvent
+ | ProjectRoleUpdateEvent
+ | ProjectRoleDeleteEvent
+ | OrgRoleCreateEvent
+ | OrgRoleUpdateEvent
+ | OrgRoleDeleteEvent;
diff --git a/backend/src/ee/services/dynamic-secret/providers/aws-iam.ts b/backend/src/ee/services/dynamic-secret/providers/aws-iam.ts
index d4fceb6742..08686ffc4b 100644
--- a/backend/src/ee/services/dynamic-secret/providers/aws-iam.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/aws-iam.ts
@@ -16,7 +16,7 @@ import {
PutUserPolicyCommand,
RemoveUserFromGroupCommand
} from "@aws-sdk/client-iam";
-import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
+import { AssumeRoleCommand, GetSessionTokenCommand, STSClient } from "@aws-sdk/client-sts";
import { z } from "zod";
import { CustomAWSHasher } from "@app/lib/aws/hashing";
@@ -26,9 +26,12 @@ import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
import { sanitizeString } from "@app/lib/fn";
import { alphaNumericNanoId } from "@app/lib/nanoid";
-import { AwsIamAuthType, DynamicSecretAwsIamSchema, TDynamicProviderFns } from "./models";
+import { AwsIamAuthType, AwsIamCredentialType, DynamicSecretAwsIamSchema, TDynamicProviderFns } from "./models";
import { compileUsernameTemplate } from "./templateUtils";
+// AWS STS duration constants (in seconds)
+const AWS_STS_MIN_DURATION = 900;
+
const generateUsername = (usernameTemplate?: string | null, identity?: { name: string }) => {
const randomUsername = alphaNumericNanoId(32);
if (!usernameTemplate) return randomUsername;
@@ -120,6 +123,58 @@ export const AwsIamProvider = (): TDynamicProviderFns => {
const validateConnection = async (inputs: unknown, { projectId }: { projectId: string }) => {
const providerInputs = await validateProviderInputs(inputs);
try {
+ if (providerInputs.credentialType === AwsIamCredentialType.TemporaryCredentials) {
+ if (providerInputs.method === AwsIamAuthType.AccessKey) {
+ const stsClient = new STSClient({
+ region: providerInputs.region,
+ useFipsEndpoint: crypto.isFipsModeEnabled(),
+ sha256: CustomAWSHasher,
+ credentials: {
+ accessKeyId: providerInputs.accessKey,
+ secretAccessKey: providerInputs.secretAccessKey
+ }
+ });
+
+ await stsClient.send(new GetSessionTokenCommand({ DurationSeconds: AWS_STS_MIN_DURATION }));
+ return true;
+ }
+ if (providerInputs.method === AwsIamAuthType.AssumeRole) {
+ const appCfg = getConfig();
+ const stsClient = new STSClient({
+ region: providerInputs.region,
+ useFipsEndpoint: crypto.isFipsModeEnabled(),
+ sha256: CustomAWSHasher,
+ credentials:
+ appCfg.DYNAMIC_SECRET_AWS_ACCESS_KEY_ID && appCfg.DYNAMIC_SECRET_AWS_SECRET_ACCESS_KEY
+ ? {
+ accessKeyId: appCfg.DYNAMIC_SECRET_AWS_ACCESS_KEY_ID,
+ secretAccessKey: appCfg.DYNAMIC_SECRET_AWS_SECRET_ACCESS_KEY
+ }
+ : undefined
+ });
+
+ await stsClient.send(
+ new AssumeRoleCommand({
+ RoleArn: providerInputs.roleArn,
+ RoleSessionName: `infisical-validation-${crypto.nativeCrypto.randomUUID()}`,
+ DurationSeconds: AWS_STS_MIN_DURATION,
+ ExternalId: projectId
+ })
+ );
+ return true;
+ }
+ if (providerInputs.method === AwsIamAuthType.IRSA) {
+ const stsClient = new STSClient({
+ region: providerInputs.region,
+ useFipsEndpoint: crypto.isFipsModeEnabled(),
+ sha256: CustomAWSHasher
+ });
+
+ await stsClient.send(new GetSessionTokenCommand({ DurationSeconds: AWS_STS_MIN_DURATION }));
+ return true;
+ }
+ }
+
const client = await $getClient(providerInputs, projectId);
const isConnected = await client
.send(new GetUserCommand({}))
@@ -137,7 +192,7 @@ export const AwsIamProvider = (): TDynamicProviderFns => {
});
return isConnected;
} catch (err) {
- const sensitiveTokens = [];
+ const sensitiveTokens: string[] = [];
if (providerInputs.method === AwsIamAuthType.AccessKey) {
sensitiveTokens.push(providerInputs.accessKey, providerInputs.secretAccessKey);
}
@@ -163,102 +218,269 @@ export const AwsIamProvider = (): TDynamicProviderFns => {
};
metadata: { projectId: string };
}) => {
- const { inputs, usernameTemplate, metadata, identity } = data;
+ const { inputs, usernameTemplate, metadata, identity, expireAt } = data;
const providerInputs = await validateProviderInputs(inputs);
- const client = await $getClient(providerInputs, metadata.projectId);
- const username = generateUsername(usernameTemplate, identity);
- const { policyArns, userGroups, policyDocument, awsPath, permissionBoundaryPolicyArn } = providerInputs;
- const awsTags = [{ Key: "createdBy", Value: "infisical-dynamic-secret" }];
+ if (providerInputs.credentialType === AwsIamCredentialType.TemporaryCredentials) {
+ try {
+ let stsClient: STSClient;
+ let entityId: string;
+
+ const currentTime = Date.now();
+ const requestedDuration = Math.floor((expireAt - currentTime) / 1000);
+
+ if (requestedDuration <= 0) {
+ throw new BadRequestError({ message: "Expiration time must be in the future" });
+ }
+
+ let durationSeconds: number;
+
+ if (providerInputs.method === AwsIamAuthType.AssumeRole) {
+ durationSeconds = requestedDuration;
+ const appCfg = getConfig();
+ stsClient = new STSClient({
+ region: providerInputs.region,
+ useFipsEndpoint: crypto.isFipsModeEnabled(),
+ sha256: CustomAWSHasher,
+ credentials:
+ appCfg.DYNAMIC_SECRET_AWS_ACCESS_KEY_ID && appCfg.DYNAMIC_SECRET_AWS_SECRET_ACCESS_KEY
+ ? {
+ accessKeyId: appCfg.DYNAMIC_SECRET_AWS_ACCESS_KEY_ID,
+ secretAccessKey: appCfg.DYNAMIC_SECRET_AWS_SECRET_ACCESS_KEY
+ }
+ : undefined
+ });
+
+ const assumeRoleRes = await stsClient.send(
+ new AssumeRoleCommand({
+ RoleArn: providerInputs.roleArn,
+ RoleSessionName: `infisical-temp-cred-${crypto.nativeCrypto.randomUUID()}`,
+ DurationSeconds: durationSeconds,
+ ExternalId: metadata.projectId
+ })
+ );
+
+ if (
+ !assumeRoleRes.Credentials?.AccessKeyId ||
+ !assumeRoleRes.Credentials?.SecretAccessKey ||
+ !assumeRoleRes.Credentials?.SessionToken
+ ) {
+ throw new BadRequestError({ message: "Failed to assume role - verify credentials and role configuration" });
+ }
+
+ entityId = `assume-role-${alphaNumericNanoId(8)}`;
+ return {
+ entityId,
+ data: {
+ ACCESS_KEY: assumeRoleRes.Credentials.AccessKeyId,
+ SECRET_ACCESS_KEY: assumeRoleRes.Credentials.SecretAccessKey,
+ SESSION_TOKEN: assumeRoleRes.Credentials.SessionToken
+ }
+ };
+ }
+ if (providerInputs.method === AwsIamAuthType.AccessKey) {
+ durationSeconds = requestedDuration;
+ stsClient = new STSClient({
+ region: providerInputs.region,
+ useFipsEndpoint: crypto.isFipsModeEnabled(),
+ sha256: CustomAWSHasher,
+ credentials: {
+ accessKeyId: providerInputs.accessKey,
+ secretAccessKey: providerInputs.secretAccessKey
+ }
+ });
+
+ const sessionTokenRes = await stsClient.send(
+ new GetSessionTokenCommand({
+ DurationSeconds: durationSeconds
+ })
+ );
+
+ if (
+ !sessionTokenRes.Credentials?.AccessKeyId ||
+ !sessionTokenRes.Credentials?.SecretAccessKey ||
+ !sessionTokenRes.Credentials?.SessionToken
+ ) {
+ throw new BadRequestError({ message: "Failed to get session token - verify credentials and permissions" });
+ }
+
+ entityId = `session-token-${alphaNumericNanoId(8)}`;
+ return {
+ entityId,
+ data: {
+ ACCESS_KEY: sessionTokenRes.Credentials.AccessKeyId,
+ SECRET_ACCESS_KEY: sessionTokenRes.Credentials.SecretAccessKey,
+ SESSION_TOKEN: sessionTokenRes.Credentials.SessionToken
+ }
+ };
+ }
+ if (providerInputs.method === AwsIamAuthType.IRSA) {
+ durationSeconds = requestedDuration;
+ stsClient = new STSClient({
+ region: providerInputs.region,
+ useFipsEndpoint: crypto.isFipsModeEnabled(),
+ sha256: CustomAWSHasher
+ });
+
+ const sessionTokenRes = await stsClient.send(
+ new GetSessionTokenCommand({
+ DurationSeconds: durationSeconds
+ })
+ );
+
+ if (
+ !sessionTokenRes.Credentials?.AccessKeyId ||
+ !sessionTokenRes.Credentials?.SecretAccessKey ||
+ !sessionTokenRes.Credentials?.SessionToken
+ ) {
+ throw new BadRequestError({
+ message: "Failed to get session token - verify IRSA credentials and permissions"
+ });
+ }
+
+ entityId = `irsa-session-${alphaNumericNanoId(8)}`;
+ return {
+ entityId,
+ data: {
+ ACCESS_KEY: sessionTokenRes.Credentials.AccessKeyId,
+ SECRET_ACCESS_KEY: sessionTokenRes.Credentials.SecretAccessKey,
+ SESSION_TOKEN: sessionTokenRes.Credentials.SessionToken
+ }
+ };
+ }
+
+ throw new BadRequestError({ message: "Unsupported authentication method for temporary credentials" });
+ } catch (err) {
+ const sensitiveTokens: string[] = [];
+ if (providerInputs.method === AwsIamAuthType.AccessKey) {
+ sensitiveTokens.push(providerInputs.accessKey, providerInputs.secretAccessKey);
+ }
+ if (providerInputs.method === AwsIamAuthType.AssumeRole) {
+ sensitiveTokens.push(providerInputs.roleArn);
+ }
+
+ let errorMessage = (err as Error)?.message || "Unknown error";
+
+ if (err && typeof err === "object" && "name" in err && "$metadata" in err) {
+ const awsError = err as { name?: string; message?: string; $metadata?: object };
+ if (awsError.name) {
+ errorMessage = `${awsError.name}: ${errorMessage}`;
+ }
+ }
- if (providerInputs.tags && Array.isArray(providerInputs.tags)) {
- const additionalTags = providerInputs.tags.map((tag) => ({
- Key: tag.key,
- Value: tag.value
- }));
- awsTags.push(...additionalTags);
+ const sanitizedErrorMessage = sanitizeString({
+ unsanitizedString: errorMessage,
+ tokens: sensitiveTokens
+ });
+ throw new BadRequestError({
+ message: `Failed to create temporary credentials: ${sanitizedErrorMessage}`
+ });
+ }
}
- try {
- const createUserRes = await client.send(
- new CreateUserCommand({
- Path: awsPath,
- PermissionsBoundary: permissionBoundaryPolicyArn || undefined,
- Tags: awsTags,
- UserName: username
- })
- );
-
- if (!createUserRes.User) throw new BadRequestError({ message: "Failed to create AWS IAM User" });
- if (userGroups) {
- await Promise.all(
- userGroups
- .split(",")
- .filter(Boolean)
- .map((group) =>
- client.send(new AddUserToGroupCommand({ UserName: createUserRes?.User?.UserName, GroupName: group }))
- )
- );
+ if (providerInputs.credentialType === AwsIamCredentialType.IamUser) {
+ const client = await $getClient(providerInputs, metadata.projectId);
+
+ const username = generateUsername(usernameTemplate, identity);
+ const { policyArns, userGroups, policyDocument, awsPath, permissionBoundaryPolicyArn } = providerInputs;
+ const awsTags = [{ Key: "createdBy", Value: "infisical-dynamic-secret" }];
+
+ if (providerInputs.tags && Array.isArray(providerInputs.tags)) {
+ const additionalTags = providerInputs.tags.map((tag) => ({
+ Key: tag.key,
+ Value: tag.value
+ }));
+ awsTags.push(...additionalTags);
}
- if (policyArns) {
- await Promise.all(
- policyArns
- .split(",")
- .filter(Boolean)
- .map((policyArn) =>
- client.send(
- new AttachUserPolicyCommand({ UserName: createUserRes?.User?.UserName, PolicyArn: policyArn })
- )
- )
+
+ try {
+ const createUserRes = await client.send(
+ new CreateUserCommand({
+ Path: awsPath,
+ PermissionsBoundary: permissionBoundaryPolicyArn || undefined,
+ Tags: awsTags,
+ UserName: username
+ })
);
- }
- if (policyDocument) {
- await client.send(
- new PutUserPolicyCommand({
- UserName: createUserRes.User.UserName,
- PolicyName: `infisical-dynamic-policy-${alphaNumericNanoId(4)}`,
- PolicyDocument: policyDocument
+
+ if (!createUserRes.User) throw new BadRequestError({ message: "Failed to create AWS IAM User" });
+ if (userGroups) {
+ await Promise.all(
+ userGroups
+ .split(",")
+ .filter(Boolean)
+ .map((group) =>
+ client.send(new AddUserToGroupCommand({ UserName: createUserRes?.User?.UserName, GroupName: group }))
+ )
+ );
+ }
+ if (policyArns) {
+ await Promise.all(
+ policyArns
+ .split(",")
+ .filter(Boolean)
+ .map((policyArn) =>
+ client.send(
+ new AttachUserPolicyCommand({ UserName: createUserRes?.User?.UserName, PolicyArn: policyArn })
+ )
+ )
+ );
+ }
+ if (policyDocument) {
+ await client.send(
+ new PutUserPolicyCommand({
+ UserName: createUserRes.User.UserName,
+ PolicyName: `infisical-dynamic-policy-${alphaNumericNanoId(4)}`,
+ PolicyDocument: policyDocument
+ })
+ );
+ }
+
+ const createAccessKeyRes = await client.send(
+ new CreateAccessKeyCommand({
+ UserName: createUserRes.User.UserName
})
);
- }
+ if (!createAccessKeyRes.AccessKey)
+ throw new BadRequestError({ message: "Failed to create AWS IAM User access key" });
- const createAccessKeyRes = await client.send(
- new CreateAccessKeyCommand({
- UserName: createUserRes.User.UserName
- })
- );
- if (!createAccessKeyRes.AccessKey)
- throw new BadRequestError({ message: "Failed to create AWS IAM User access key" });
-
- return {
- entityId: username,
- data: {
- ACCESS_KEY: createAccessKeyRes.AccessKey.AccessKeyId,
- SECRET_ACCESS_KEY: createAccessKeyRes.AccessKey.SecretAccessKey,
- USERNAME: username
+ return {
+ entityId: username,
+ data: {
+ ACCESS_KEY: createAccessKeyRes.AccessKey.AccessKeyId,
+ SECRET_ACCESS_KEY: createAccessKeyRes.AccessKey.SecretAccessKey,
+ USERNAME: username
+ }
+ };
+ } catch (err) {
+ const sensitiveTokens = [username];
+ if (providerInputs.method === AwsIamAuthType.AccessKey) {
+ sensitiveTokens.push(providerInputs.accessKey, providerInputs.secretAccessKey);
}
- };
- } catch (err) {
- const sensitiveTokens = [username];
- if (providerInputs.method === AwsIamAuthType.AccessKey) {
- sensitiveTokens.push(providerInputs.accessKey, providerInputs.secretAccessKey);
- }
- if (providerInputs.method === AwsIamAuthType.AssumeRole) {
- sensitiveTokens.push(providerInputs.roleArn);
+ if (providerInputs.method === AwsIamAuthType.AssumeRole) {
+ sensitiveTokens.push(providerInputs.roleArn);
+ }
+ const sanitizedErrorMessage = sanitizeString({
+ unsanitizedString: (err as Error)?.message,
+ tokens: sensitiveTokens
+ });
+ throw new BadRequestError({
+ message: `Failed to create lease from provider: ${sanitizedErrorMessage}`
+ });
}
- const sanitizedErrorMessage = sanitizeString({
- unsanitizedString: (err as Error)?.message,
- tokens: sensitiveTokens
- });
- throw new BadRequestError({
- message: `Failed to create lease from provider: ${sanitizedErrorMessage}`
- });
}
+
+ throw new BadRequestError({ message: "Invalid credential type specified" });
};
const revoke = async (inputs: unknown, entityId: string, metadata: { projectId: string }) => {
const providerInputs = await validateProviderInputs(inputs);
+
+ if (providerInputs.credentialType === AwsIamCredentialType.TemporaryCredentials) {
+ return { entityId };
+ }
+
const client = await $getClient(providerInputs, metadata.projectId);
const username = entityId;
diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.ts
index f076bf8836..3586fa0d93 100644
--- a/backend/src/ee/services/dynamic-secret/providers/models.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/models.ts
@@ -32,6 +32,11 @@ export enum AwsIamAuthType {
IRSA = "irsa"
}
+export enum AwsIamCredentialType {
+ IamUser = "iam-user",
+ TemporaryCredentials = "temporary-credentials"
+}
+
export enum ElasticSearchAuthTypes {
User = "user",
ApiKey = "api-key"
@@ -203,6 +208,7 @@ export const DynamicSecretAwsIamSchema = z.preprocess(
z.discriminatedUnion("method", [
z.object({
method: z.literal(AwsIamAuthType.AccessKey),
+ credentialType: z.nativeEnum(AwsIamCredentialType).default(AwsIamCredentialType.IamUser),
accessKey: z.string().trim().min(1),
secretAccessKey: z.string().trim().min(1),
region: z.string().trim().min(1),
@@ -215,6 +221,7 @@ export const DynamicSecretAwsIamSchema = z.preprocess(
}),
z.object({
method: z.literal(AwsIamAuthType.AssumeRole),
+ credentialType: z.nativeEnum(AwsIamCredentialType).default(AwsIamCredentialType.IamUser),
roleArn: z.string().trim().min(1, "Role ARN required"),
region: z.string().trim().min(1),
awsPath: z.string().trim().optional(),
@@ -226,6 +233,7 @@ export const DynamicSecretAwsIamSchema = z.preprocess(
}),
z.object({
method: z.literal(AwsIamAuthType.IRSA),
+ credentialType: z.nativeEnum(AwsIamCredentialType).default(AwsIamCredentialType.IamUser),
region: z.string().trim().min(1),
awsPath: z.string().trim().optional(),
permissionBoundaryPolicyArn: z.string().trim().optional(),
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index 317e5da6d2..e8ccc8a5ea 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -395,7 +395,8 @@ export const gatewayV2ServiceFactory = ({
relayId: gateway.relayId,
orgId: gateway.orgId,
orgName: gateway.orgName,
- gatewayId
+ gatewayId,
+ gatewayName: gateway.name
});
return {
@@ -508,7 +509,8 @@ export const gatewayV2ServiceFactory = ({
const relayCredentials = await relayService.getCredentialsForGateway({
relayName,
orgId,
- gatewayId: gateway.id
+ gatewayId: gateway.id,
+ gatewayName: gateway.name
});
return {
diff --git a/backend/src/ee/services/license/license-service.ts b/backend/src/ee/services/license/license-service.ts
index a5353b7e5b..0fdd07396f 100644
--- a/backend/src/ee/services/license/license-service.ts
+++ b/backend/src/ee/services/license/license-service.ts
@@ -160,7 +160,10 @@ export const licenseServiceFactory = ({
}
if (isValidOfflineLicense) {
- onPremFeatures = contents.license.features;
+ onPremFeatures = {
+ ...contents.license.features,
+ slug: "enterprise"
+ };
instanceType = InstanceType.EnterpriseOnPremOffline;
logger.info(`Instance type: ${InstanceType.EnterpriseOnPremOffline}`);
isValidLicense = true;
diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.ts
index 2ccd3ac8fc..cf86d9ac19 100644
--- a/backend/src/ee/services/license/license-types.ts
+++ b/backend/src/ee/services/license/license-types.ts
@@ -24,7 +24,7 @@ export type TOfflineLicense = {
export type TFeatureSet = {
_id: null;
- slug: null;
+ slug: string | null;
tier: -1;
workspaceLimit: null;
workspacesUsed: number;
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 9329c3c7f8..953d0195ec 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -2,6 +2,7 @@ import { AbilityBuilder, createMongoAbility, MongoAbility } from "@casl/ability"
import {
ProjectPermissionActions,
+ ProjectPermissionAppConnectionActions,
ProjectPermissionAuditLogsActions,
ProjectPermissionCertificateActions,
ProjectPermissionCmekActions,
@@ -264,6 +265,17 @@ const buildAdminPermissionRules = () => {
ProjectPermissionSub.SecretEvents
);
+ can(
+ [
+ ProjectPermissionAppConnectionActions.Create,
+ ProjectPermissionAppConnectionActions.Edit,
+ ProjectPermissionAppConnectionActions.Delete,
+ ProjectPermissionAppConnectionActions.Read,
+ ProjectPermissionAppConnectionActions.Connect
+ ],
+ ProjectPermissionSub.AppConnections
+ );
+
return rules;
};
@@ -477,6 +489,8 @@ const buildMemberPermissionRules = () => {
ProjectPermissionSub.SecretEvents
);
+ can(ProjectPermissionAppConnectionActions.Connect, ProjectPermissionSub.AppConnections);
+
return rules;
};
diff --git a/backend/src/ee/services/permission/org-permission.ts b/backend/src/ee/services/permission/org-permission.ts
index d4155d02cd..0548911e8c 100644
--- a/backend/src/ee/services/permission/org-permission.ts
+++ b/backend/src/ee/services/permission/org-permission.ts
@@ -58,6 +58,13 @@ export enum OrgPermissionGatewayActions {
AttachGateways = "attach-gateways"
}
+export enum OrgPermissionRelayActions {
+ CreateRelays = "create-relays",
+ ListRelays = "list-relays",
+ EditRelays = "edit-relays",
+ DeleteRelays = "delete-relays"
+}
+
export enum OrgPermissionIdentityActions {
Read = "read",
Create = "create",
@@ -87,6 +94,7 @@ export enum OrgPermissionBillingActions {
export enum OrgPermissionSubjects {
Workspace = "workspace",
+ Project = "project",
Role = "role",
Member = "member",
Settings = "settings",
@@ -108,6 +116,7 @@ export enum OrgPermissionSubjects {
AppConnections = "app-connections",
Kmip = "kmip",
Gateway = "gateway",
+ Relay = "relay",
SecretShare = "secret-share"
}
@@ -117,6 +126,7 @@ export type AppConnectionSubjectFields = {
export type OrgPermissionSet =
| [OrgPermissionActions.Create, OrgPermissionSubjects.Workspace]
+ | [OrgPermissionActions.Create, OrgPermissionSubjects.Project]
| [OrgPermissionActions, OrgPermissionSubjects.Role]
| [OrgPermissionActions, OrgPermissionSubjects.Member]
| [OrgPermissionActions, OrgPermissionSubjects.Settings]
@@ -134,6 +144,7 @@ export type OrgPermissionSet =
| [OrgPermissionAuditLogsActions, OrgPermissionSubjects.AuditLogs]
| [OrgPermissionActions, OrgPermissionSubjects.ProjectTemplates]
| [OrgPermissionGatewayActions, OrgPermissionSubjects.Gateway]
+ | [OrgPermissionRelayActions, OrgPermissionSubjects.Relay]
| [
OrgPermissionAppConnectionActions,
(
@@ -166,6 +177,10 @@ export const OrgPermissionSchema = z.discriminatedUnion("subject", [
subject: z.literal(OrgPermissionSubjects.Workspace).describe("The entity this permission pertains to."),
action: CASL_ACTION_SCHEMA_ENUM([OrgPermissionActions.Create]).describe("Describe what action an entity can take.")
}),
+ z.object({
+ subject: z.literal(OrgPermissionSubjects.Project).describe("The entity this permission pertains to."),
+ action: CASL_ACTION_SCHEMA_ENUM([OrgPermissionActions.Create]).describe("Describe what action an entity can take.")
+ }),
z.object({
subject: z.literal(OrgPermissionSubjects.Role).describe("The entity this permission pertains to."),
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionActions).describe("Describe what action an entity can take.")
@@ -273,6 +288,12 @@ export const OrgPermissionSchema = z.discriminatedUnion("subject", [
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionGatewayActions).describe(
"Describe what action an entity can take."
)
+ }),
+ z.object({
+ subject: z.literal(OrgPermissionSubjects.Relay).describe("The entity this permission pertains to."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(OrgPermissionRelayActions).describe(
+ "Describe what action an entity can take."
+ )
})
]);
@@ -280,6 +301,7 @@ const buildAdminPermission = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<OrgPermissionSet>>(createMongoAbility);
// ws permissions
can(OrgPermissionActions.Create, OrgPermissionSubjects.Workspace);
+ can(OrgPermissionActions.Create, OrgPermissionSubjects.Project);
// role permission
can(OrgPermissionActions.Read, OrgPermissionSubjects.Role);
can(OrgPermissionActions.Create, OrgPermissionSubjects.Role);
@@ -376,6 +398,11 @@ const buildAdminPermission = () => {
can(OrgPermissionGatewayActions.DeleteGateways, OrgPermissionSubjects.Gateway);
can(OrgPermissionGatewayActions.AttachGateways, OrgPermissionSubjects.Gateway);
+ can(OrgPermissionRelayActions.ListRelays, OrgPermissionSubjects.Relay);
+ can(OrgPermissionRelayActions.CreateRelays, OrgPermissionSubjects.Relay);
+ can(OrgPermissionRelayActions.EditRelays, OrgPermissionSubjects.Relay);
+ can(OrgPermissionRelayActions.DeleteRelays, OrgPermissionSubjects.Relay);
+
can(OrgPermissionAdminConsoleAction.AccessAllProjects, OrgPermissionSubjects.AdminConsole);
can(OrgPermissionKmipActions.Setup, OrgPermissionSubjects.Kmip);
@@ -413,6 +440,7 @@ const buildMemberPermission = () => {
const { can, rules } = new AbilityBuilder<MongoAbility<OrgPermissionSet>>(createMongoAbility);
can(OrgPermissionActions.Create, OrgPermissionSubjects.Workspace);
+ can(OrgPermissionActions.Create, OrgPermissionSubjects.Project);
can(OrgPermissionActions.Read, OrgPermissionSubjects.Member);
can(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups);
can(OrgPermissionActions.Read, OrgPermissionSubjects.Role);
@@ -437,6 +465,10 @@ const buildMemberPermission = () => {
can(OrgPermissionGatewayActions.CreateGateways, OrgPermissionSubjects.Gateway);
can(OrgPermissionGatewayActions.AttachGateways, OrgPermissionSubjects.Gateway);
+ can(OrgPermissionRelayActions.ListRelays, OrgPermissionSubjects.Relay);
+ can(OrgPermissionRelayActions.CreateRelays, OrgPermissionSubjects.Relay);
+ can(OrgPermissionRelayActions.EditRelays, OrgPermissionSubjects.Relay);
+
can(OrgPermissionMachineIdentityAuthTemplateActions.ListTemplates, OrgPermissionSubjects.MachineIdentityAuthTemplate);
can(
OrgPermissionMachineIdentityAuthTemplateActions.UnlinkTemplates,
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 20b4344d31..099461f7fd 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -147,6 +147,14 @@ export enum ProjectPermissionSecretScanningDataSourceActions {
ReadResources = "read-data-source-resources"
}
+export enum ProjectPermissionAppConnectionActions {
+ Read = "read-app-connections",
+ Create = "create-app-connections",
+ Edit = "edit-app-connections",
+ Delete = "delete-app-connections",
+ Connect = "connect-app-connections"
+}
+
export enum ProjectPermissionSecretScanningFindingActions {
Read = "read-findings",
Update = "update-findings"
@@ -208,7 +216,8 @@ export enum ProjectPermissionSub {
SecretScanningDataSources = "secret-scanning-data-sources",
SecretScanningFindings = "secret-scanning-findings",
SecretScanningConfigs = "secret-scanning-configs",
- SecretEvents = "secret-events"
+ SecretEvents = "secret-events",
+ AppConnections = "app-connections"
}
export type SecretSubjectFields = {
@@ -272,6 +281,10 @@ export type PkiSubscriberSubjectFields = {
// (dangtony98): consider adding [commonName] as a subject field in the future
};
+export type AppConnectionSubjectFields = {
+ connectionId: string;
+};
+
export type ProjectPermissionSet =
| [
ProjectPermissionSecretActions,
@@ -365,6 +378,13 @@ export type ProjectPermissionSet =
| [
ProjectPermissionSecretEventActions,
ProjectPermissionSub.SecretEvents | (ForcedSubject<ProjectPermissionSub.SecretEvents> & SecretEventSubjectFields)
+ ]
+ | [
+ ProjectPermissionAppConnectionActions,
+ (
+ | ProjectPermissionSub.AppConnections
+ | (ForcedSubject<ProjectPermissionSub.AppConnections> & AppConnectionSubjectFields)
+ )
];
const SECRET_PATH_MISSING_SLASH_ERR_MSG = "Invalid Secret Path; it must start with a '/'";
@@ -580,6 +600,21 @@ const PkiTemplateConditionSchema = z
})
.partial();
+const AppConnectionConditionSchema = z
+ .object({
+ connectionId: z.union([
+ z.string(),
+ z
+ .object({
+ [PermissionConditionOperators.$EQ]: PermissionConditionSchema[PermissionConditionOperators.$EQ],
+ [PermissionConditionOperators.$NEQ]: PermissionConditionSchema[PermissionConditionOperators.$NEQ],
+ [PermissionConditionOperators.$IN]: PermissionConditionSchema[PermissionConditionOperators.$IN]
+ })
+ .partial()
+ ])
+ })
+ .partial();
+
const GeneralPermissionSchema = [
z.object({
subject: z.literal(ProjectPermissionSub.SecretApproval).describe("The entity this permission pertains to."),
@@ -760,6 +795,16 @@ const GeneralPermissionSchema = [
action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionSecretScanningConfigActions).describe(
"Describe what action an entity can take."
)
+ }),
+ z.object({
+ subject: z.literal(ProjectPermissionSub.AppConnections).describe("The entity this permission pertains to."),
+ inverted: z.boolean().optional().describe("Whether rule allows or forbids."),
+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionAppConnectionActions).describe(
+ "Describe what action an entity can take."
+ ),
+ conditions: AppConnectionConditionSchema.describe(
+ "When specified, only matching conditions will be allowed to access given resource."
+ ).optional()
})
];
diff --git a/backend/src/ee/services/pit/pit-service.ts b/backend/src/ee/services/pit/pit-service.ts
index ef7f9b5a37..d561064a67 100644
--- a/backend/src/ee/services/pit/pit-service.ts
+++ b/backend/src/ee/services/pit/pit-service.ts
@@ -754,7 +754,8 @@ export const pitServiceFactory = ({
secrets: newSecrets.map((secret) => ({
secretId: secret.id,
secretKey: secret.secretKey,
- secretVersion: secret.version
+ secretVersion: secret.version,
+ secretTags: secret.tags?.map((tag) => tag.name)
}))
}
});
@@ -781,7 +782,8 @@ export const pitServiceFactory = ({
secrets: updatedSecrets.map((secret) => ({
secretId: secret.id,
secretKey: secret.secretKey,
- secretVersion: secret.version
+ secretVersion: secret.version,
+ secretTags: secret.tags?.map((tag) => tag.name)
}))
}
});
diff --git a/backend/src/ee/services/relay/relay-constants.ts b/backend/src/ee/services/relay/relay-constants.ts
new file mode 100644
index 0000000000..d7f00f0360
--- /dev/null
+++ b/backend/src/ee/services/relay/relay-constants.ts
@@ -0,0 +1 @@
+export const RELAY_CONNECTING_GATEWAY_INFO = "1.3.6.1.4.1.12345.100.3";
diff --git a/backend/src/ee/services/relay/relay-service.ts b/backend/src/ee/services/relay/relay-service.ts
index 92401faafd..2fef712596 100644
--- a/backend/src/ee/services/relay/relay-service.ts
+++ b/backend/src/ee/services/relay/relay-service.ts
@@ -1,9 +1,13 @@
+import { isIP } from "node:net";
+
+import { ForbiddenError } from "@casl/ability";
import * as x509 from "@peculiar/x509";
import { TRelays } from "@app/db/schemas";
import { PgSqlLock } from "@app/keystore/keystore";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
import { constructPemChainFromCerts, prependCertToPemChain } from "@app/services/certificate/certificate-fns";
import { CertExtendedKeyUsage, CertKeyAlgorithm, CertKeyUsage } from "@app/services/certificate/certificate-types";
import {
@@ -14,11 +18,15 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { verifyHostInputValidity } from "../dynamic-secret/dynamic-secret-fns";
+import { TLicenseServiceFactory } from "../license/license-service";
+import { OrgPermissionRelayActions, OrgPermissionSubjects } from "../permission/org-permission";
+import { TPermissionServiceFactory } from "../permission/permission-service-types";
import { createSshCert, createSshKeyPair } from "../ssh/ssh-certificate-authority-fns";
import { SshCertType } from "../ssh/ssh-certificate-authority-types";
import { SshCertKeyAlgorithm } from "../ssh-certificate/ssh-certificate-types";
import { TInstanceRelayConfigDALFactory } from "./instance-relay-config-dal";
import { TOrgRelayConfigDALFactory } from "./org-relay-config-dal";
+import { RELAY_CONNECTING_GATEWAY_INFO } from "./relay-constants";
import { TRelayDALFactory } from "./relay-dal";
export type TRelayServiceFactory = ReturnType<typeof relayServiceFactory>;
@@ -29,12 +37,16 @@ export const relayServiceFactory = ({
instanceRelayConfigDAL,
orgRelayConfigDAL,
relayDAL,
- kmsService
+ kmsService,
+ licenseService,
+ permissionService
}: {
instanceRelayConfigDAL: TInstanceRelayConfigDALFactory;
orgRelayConfigDAL: TOrgRelayConfigDALFactory;
relayDAL: TRelayDALFactory;
kmsService: TKmsServiceFactory;
+ licenseService: TLicenseServiceFactory;
+ permissionService: TPermissionServiceFactory;
}) => {
const $getInstanceCAs = async () => {
const instanceConfig = await instanceRelayConfigDAL.transaction(async (tx) => {
@@ -639,8 +651,9 @@ export const relayServiceFactory = ({
true
),
new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.SERVER_AUTH]], true),
+
// san
- new x509.SubjectAlternativeNameExtension([{ type: "ip", value: host }], false)
+ new x509.SubjectAlternativeNameExtension([{ type: isIP(host) ? "ip" : "dns", value: host }], false)
];
const relayServerSerialNumber = createSerialNumber();
@@ -689,6 +702,7 @@ export const relayServiceFactory = ({
const $generateRelayClientCredentials = async ({
gatewayId,
+ gatewayName,
orgId,
orgName,
relayPkiClientCaCertificate,
@@ -697,6 +711,7 @@ export const relayServiceFactory = ({
relayPkiServerCaCertificateChain
}: {
gatewayId: string;
+ gatewayName: string;
orgId: string;
orgName: string;
relayPkiClientCaCertificate: Buffer;
@@ -727,6 +742,16 @@ export const relayServiceFactory = ({
const clientCertPrivateKey = crypto.nativeCrypto.KeyObject.from(clientKeys.privateKey);
const clientCertSerialNumber = createSerialNumber();
+ const connectingGatewayInfoExtension = new x509.Extension(
+ RELAY_CONNECTING_GATEWAY_INFO,
+ false,
+ Buffer.from(
+ JSON.stringify({
+ name: gatewayName
+ })
+ )
+ );
+
// Build standard extensions
const extensions: x509.Extension[] = [
new x509.BasicConstraintsExtension(false),
@@ -740,7 +765,8 @@ export const relayServiceFactory = ({
x509.KeyUsageFlags[CertKeyUsage.KEY_AGREEMENT],
true
),
- new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.CLIENT_AUTH]], true)
+ new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.CLIENT_AUTH]], true),
+ connectingGatewayInfoExtension
];
const clientCert = await x509.X509CertificateGenerator.create({
@@ -768,11 +794,13 @@ export const relayServiceFactory = ({
const getCredentialsForGateway = async ({
relayName,
orgId,
- gatewayId
+ gatewayId,
+ gatewayName
}: {
relayName: string;
orgId: string;
gatewayId: string;
+ gatewayName: string;
}) => {
let relay: TRelays | null = await relayDAL.findOne({
orgId,
@@ -819,10 +847,10 @@ export const relayServiceFactory = ({
const relayClientSshCert = await createSshCert({
caPrivateKey: orgCAs.relaySshClientCaPrivateKey.toString("utf8"),
clientPublicKey: relayClientSshPublicKey,
- keyId: `relay-client-${relay.id}`,
- principals: [gatewayId],
+ keyId: `client-${relayName}`,
+ principals: [gatewayId, gatewayName],
certType: SshCertType.USER,
- requestedTtl: "30d"
+ requestedTtl: "1d"
});
return {
@@ -837,12 +865,14 @@ export const relayServiceFactory = ({
relayId,
orgId,
orgName,
- gatewayId
+ gatewayId,
+ gatewayName
}: {
relayId: string;
orgId: string;
orgName: string;
gatewayId: string;
+ gatewayName: string;
}) => {
const relay = await relayDAL.findOne({
id: relayId
@@ -860,6 +890,7 @@ export const relayServiceFactory = ({
const instanceCAs = await $getInstanceCAs();
const relayCertificateCredentials = await $generateRelayClientCredentials({
gatewayId,
+ gatewayName,
orgId,
orgName,
relayPkiClientCaCertificate: instanceCAs.instanceRelayPkiClientCaCertificate,
@@ -877,6 +908,7 @@ export const relayServiceFactory = ({
const orgCAs = await $getOrgCAs(orgId);
const relayCertificateCredentials = await $generateRelayClientCredentials({
gatewayId,
+ gatewayName,
orgId,
orgName,
relayPkiClientCaCertificate: orgCAs.relayPkiClientCaCertificate,
@@ -895,11 +927,13 @@ export const relayServiceFactory = ({
host,
name,
identityId,
+ actorAuthMethod,
orgId
}: {
host: string;
name: string;
identityId?: string;
+ actorAuthMethod?: ActorAuthMethod;
orgId?: string;
}) => {
let relay: TRelays;
@@ -908,6 +942,27 @@ export const relayServiceFactory = ({
await verifyHostInputValidity(host);
if (isOrgRelay) {
+ const orgLicensePlan = await licenseService.getPlan(orgId);
+ if (!orgLicensePlan.gateway) {
+ throw new BadRequestError({
+ message:
+ "Relay registration failed due to organization plan restrictions. Please upgrade your instance to Infisical's Enterprise plan."
+ });
+ }
+
+ const { permission } = await permissionService.getOrgPermission(
+ ActorType.IDENTITY,
+ identityId,
+ orgId,
+ actorAuthMethod!,
+ orgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionRelayActions.CreateRelays,
+ OrgPermissionSubjects.Relay
+ );
+
relay = await relayDAL.transaction(async (tx) => {
const existingRelay = await relayDAL.findOne(
{
@@ -995,9 +1050,75 @@ export const relayServiceFactory = ({
});
};
+ const getRelays = async ({
+ actorId,
+ actor,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ actorId: string;
+ actor: ActorType;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const { permission } = await permissionService.getOrgPermission(
+ actor,
+ actorId,
+ actorOrgId,
+ actorAuthMethod,
+ actorOrgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionRelayActions.ListRelays, OrgPermissionSubjects.Relay);
+
+ const instanceRelays = await relayDAL.find({
+ orgId: null
+ });
+
+ const orgRelays = await relayDAL.find({
+ orgId: actorOrgId
+ });
+
+ return [...instanceRelays, ...orgRelays];
+ };
+
+ const deleteRelay = async ({
+ id,
+ actorId,
+ actor,
+ actorAuthMethod,
+ actorOrgId
+ }: {
+ id: string;
+ actorId: string;
+ actor: ActorType;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+ }) => {
+ const { permission } = await permissionService.getOrgPermission(
+ actor,
+ actorId,
+ actorOrgId,
+ actorAuthMethod,
+ actorOrgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionRelayActions.DeleteRelays, OrgPermissionSubjects.Relay);
+
+ const relay = await relayDAL.findById(id);
+ if (!relay || relay.orgId !== actorOrgId || relay.orgId === null) {
+ throw new NotFoundError({ message: "Relay not found" });
+ }
+
+ const deletedRelay = await relayDAL.deleteById(id);
+ return deletedRelay;
+ };
+
return {
registerRelay,
getCredentialsForGateway,
- getCredentialsForClient
+ getCredentialsForClient,
+ getRelays,
+ deleteRelay
};
};
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts
index dfe425b8e2..d96fb2e53e 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts
@@ -1,5 +1,7 @@
import { TSecretApprovalRequests } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
@@ -11,6 +13,7 @@ type TSendApprovalEmails = {
smtpService: Pick<TSmtpService, "sendMail">;
projectId: string;
secretApprovalRequest: TSecretApprovalRequests;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export const sendApprovalEmailsFn = async ({
@@ -18,7 +21,8 @@ export const sendApprovalEmailsFn = async ({
projectDAL,
smtpService,
projectId,
- secretApprovalRequest
+ secretApprovalRequest,
+ notificationService
}: TSendApprovalEmails) => {
const cfg = getConfig();
@@ -26,6 +30,17 @@ export const sendApprovalEmailsFn = async ({
const project = await projectDAL.findProjectWithOrg(projectId);
+ await notificationService.createUserNotifications(
+ policy.userApprovers.map((approver) => ({
+ userId: approver.userId,
+ orgId: project.orgId,
+ type: NotificationType.SECRET_CHANGE_REQUEST,
+ title: "Secret Change Request",
+ body: `You have a new secret change request pending your review for the project **${project.name}** in the organization **${project.organization.name}**.`,
+ link: `/projects/secret-management/${project.id}/approval?requestId=${secretApprovalRequest.id}`
+ }))
+ );
+
// now we need to go through each of the reviewers and print out all the commits that they need to approve
for await (const reviewerUser of policy.userApprovers) {
await smtpService.sendMail({
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
index 17b7d83472..80fbf546f0 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
@@ -28,6 +28,8 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
import { TMicrosoftTeamsServiceFactory } from "@app/services/microsoft-teams/microsoft-teams-service";
import { TProjectMicrosoftTeamsConfigDALFactory } from "@app/services/microsoft-teams/project-microsoft-teams-config-dal";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
@@ -140,6 +142,7 @@ type TSecretApprovalRequestServiceFactoryDep = {
projectMicrosoftTeamsConfigDAL: Pick<TProjectMicrosoftTeamsConfigDALFactory, "getIntegrationDetailsByProject">;
microsoftTeamsService: Pick<TMicrosoftTeamsServiceFactory, "sendNotification">;
folderCommitService: Pick<TFolderCommitServiceFactory, "createCommit">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export type TSecretApprovalRequestServiceFactory = ReturnType<typeof secretApprovalRequestServiceFactory>;
@@ -172,7 +175,8 @@ export const secretApprovalRequestServiceFactory = ({
resourceMetadataDAL,
projectMicrosoftTeamsConfigDAL,
microsoftTeamsService,
- folderCommitService
+ folderCommitService,
+ notificationService
}: TSecretApprovalRequestServiceFactoryDep) => {
const requestCount = async ({
projectId,
@@ -1035,6 +1039,17 @@ export const secretApprovalRequestServiceFactory = ({
}
});
+ await notificationService.createUserNotifications(
+ approverUsers.map((approver) => ({
+ userId: approver.id,
+ orgId: project.orgId,
+ type: NotificationType.SECRET_CHANGE_POLICY_BYPASSED,
+ title: "Secret Change Policy Bypassed",
+ body: `**${requestedByUser.firstName} ${requestedByUser.lastName}** (${requestedByUser.email}) has merged a secret to **${policy.secretPath}** in the **${env.name}** environment for project **${project.name}** without obtaining the required approval.`,
+ link: `/projects/secret-management/${project.id}/approval`
+ }))
+ );
+
await smtpService.sendMail({
recipients: approverUsers.filter((approver) => approver.email).map((approver) => approver.email!),
subjectLine: "Infisical Secret Change Policy Bypassed",
@@ -1069,7 +1084,9 @@ export const secretApprovalRequestServiceFactory = ({
// @ts-expect-error not present on v1 secrets
secretKey: secret.key as string,
// @ts-expect-error not present on v1 secrets
- secretMetadata: secret.secretMetadata as ResourceMetadataDTO
+ secretMetadata: secret.secretMetadata as ResourceMetadataDTO,
+ // @ts-expect-error not present on v1 secrets
+ secretTags: (secret.tags as { name: string }[])?.map((tag) => tag.name)
}))
}
});
@@ -1085,7 +1102,9 @@ export const secretApprovalRequestServiceFactory = ({
// @ts-expect-error not present on v1 secrets
secretKey: secret.key as string,
// @ts-expect-error not present on v1 secrets
- secretMetadata: secret.secretMetadata as ResourceMetadataDTO
+ secretMetadata: secret.secretMetadata as ResourceMetadataDTO,
+ // @ts-expect-error not present on v1 secrets
+ secretTags: (secret.tags as { name: string }[])?.map((tag) => tag.name)
}
});
}
@@ -1104,7 +1123,9 @@ export const secretApprovalRequestServiceFactory = ({
// @ts-expect-error not present on v1 secrets
secretKey: secret.key as string,
// @ts-expect-error not present on v1 secrets
- secretMetadata: secret.secretMetadata as ResourceMetadataDTO
+ secretMetadata: secret.secretMetadata as ResourceMetadataDTO,
+ // @ts-expect-error not present on v1 secrets
+ secretTags: (secret.tags as { name: string }[])?.map((tag) => tag.name)
}))
}
});
@@ -1120,7 +1141,9 @@ export const secretApprovalRequestServiceFactory = ({
// @ts-expect-error not present on v1 secrets
secretKey: secret.key as string,
// @ts-expect-error not present on v1 secrets
- secretMetadata: secret.secretMetadata as ResourceMetadataDTO
+ secretMetadata: secret.secretMetadata as ResourceMetadataDTO,
+ // @ts-expect-error not present on v1 secrets
+ secretTags: (secret.tags as { name: string }[])?.map((tag) => tag.name)
}
});
}
@@ -1446,7 +1469,8 @@ export const secretApprovalRequestServiceFactory = ({
secretApprovalPolicyDAL,
secretApprovalRequest,
smtpService,
- projectId
+ projectId,
+ notificationService
});
return secretApprovalRequest;
@@ -1813,7 +1837,8 @@ export const secretApprovalRequestServiceFactory = ({
secretApprovalPolicyDAL,
secretApprovalRequest,
smtpService,
- projectId
+ projectId,
+ notificationService
});
return secretApprovalRequest;
};
diff --git a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts
index 07cf97a7ee..9b1fd14a02 100644
--- a/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts
+++ b/backend/src/ee/services/secret-rotation-v2/ldap-password/ldap-password-rotation-fns.ts
@@ -175,7 +175,8 @@ export const ldapPasswordRotationFactory: TRotationFactory<
const encryptedCredentials = await encryptAppConnectionCredentials({
credentials: updatedCredentials,
orgId,
- kmsService
+ kmsService,
+ projectId: connection.projectId
});
await appConnectionDAL.updateById(connection.id, { encryptedCredentials });
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts
index 787c07baeb..cf236b56f5 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-dal.ts
@@ -52,6 +52,7 @@ const baseSecretRotationV2Query = ({
db.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),
db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),
db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),
+ db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),
db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),
db.ref("updatedAt").withSchema(TableName.AppConnection).as("connectionUpdatedAt"),
db
@@ -106,6 +107,7 @@ const expandSecretRotation = <T extends Awaited<ReturnType<typeof baseSecretRota
connectionUpdatedAt,
connectionVersion,
connectionGatewayId,
+ connectionProjectId,
connectionIsPlatformManagedCredentials,
...el
} = secretRotation;
@@ -126,6 +128,7 @@ const expandSecretRotation = <T extends Awaited<ReturnType<typeof baseSecretRota
updatedAt: connectionUpdatedAt,
version: connectionVersion,
gatewayId: connectionGatewayId,
+ projectId: connectionProjectId,
isPlatformManagedCredentials: connectionIsPlatformManagedCredentials
},
folder: {
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts
index 50c81f444e..f653802b68 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-queue.ts
@@ -17,6 +17,8 @@ import {
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
@@ -28,6 +30,7 @@ type TSecretRotationV2QueueServiceFactoryDep = {
smtpService: Pick<TSmtpService, "sendMail">;
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
projectDAL: Pick<TProjectDALFactory, "findById">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export const secretRotationV2QueueServiceFactory = async ({
@@ -36,7 +39,8 @@ export const secretRotationV2QueueServiceFactory = async ({
secretRotationV2Service,
projectMembershipDAL,
projectDAL,
- smtpService
+ smtpService,
+ notificationService
}: TSecretRotationV2QueueServiceFactoryDep) => {
const appCfg = getConfig();
@@ -152,6 +156,19 @@ export const secretRotationV2QueueServiceFactory = async ({
const rotationType = SECRET_ROTATION_NAME_MAP[type as SecretRotation];
+ const rotationPath = `/projects/secret-management/${projectId}/secrets/${environment.slug}`;
+
+ await notificationService.createUserNotifications(
+ projectAdmins.map((admin) => ({
+ userId: admin.userId,
+ orgId: project.orgId,
+ type: NotificationType.SECRET_ROTATION_FAILED,
+ title: "Secret Rotation Failed",
+ body: `Your **${rotationType}** rotation **${rotationName}** failed to rotate.`,
+ link: rotationPath
+ }))
+ );
+
await smtpService.sendMail({
recipients: projectAdmins.map((member) => member.user.email!).filter(Boolean),
template: SmtpTemplates.SecretRotationFailed,
@@ -165,9 +182,7 @@ export const secretRotationV2QueueServiceFactory = async ({
secretPath: folder.path,
environment: environment.name,
projectName: project.name,
- rotationUrl: encodeURI(
- `${appCfg.SITE_URL}/projects/secret-management/${projectId}/secrets/${environment.slug}`
- )
+ rotationUrl: encodeURI(`${appCfg.SITE_URL}${rotationPath}`)
}
});
} catch (error) {
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
index 97a0f57006..80bb7ebab3 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
@@ -89,7 +89,7 @@ import { TSecretRotationV2DALFactory } from "./secret-rotation-v2-dal";
export type TSecretRotationV2ServiceFactoryDep = {
secretRotationV2DAL: TSecretRotationV2DALFactory;
- appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
@@ -459,7 +459,11 @@ export const secretRotationV2ServiceFactory = ({
const typeApp = SECRET_ROTATION_CONNECTION_MAP[payload.type];
// validates permission to connect and app is valid for rotation type
- const connection = await appConnectionService.connectAppConnectionById(typeApp, payload.connectionId, actor);
+ const connection = await appConnectionService.validateAppConnectionUsageById(
+ typeApp,
+ { connectionId: payload.connectionId, projectId },
+ actor
+ );
const rotationFactory = SECRET_ROTATION_FACTORY_MAP[payload.type](
{
diff --git a/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.ts b/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.ts
index 557e71e6c4..eefe6b63af 100644
--- a/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.ts
+++ b/backend/src/ee/services/secret-rotation/secret-rotation-queue/secret-rotation-queue.ts
@@ -431,7 +431,7 @@ export const secretRotationQueueFactory = ({
numberOfSecrets: numberOfSecretsRotated,
environment: secretRotation.environment.slug,
secretPath: secretRotation.secretPath,
- workspaceId: secretRotation.projectId
+ projectId: secretRotation.projectId
}
});
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts
index c6ca50c5e0..405e601591 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-dal.ts
@@ -50,6 +50,7 @@ const baseSecretScanningDataSourceQuery = ({
db.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),
db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),
db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),
+ db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),
db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),
db.ref("updatedAt").withSchema(TableName.AppConnection).as("connectionUpdatedAt"),
db
@@ -84,6 +85,7 @@ const expandSecretScanningDataSource = <
connectionVersion,
connectionIsPlatformManagedCredentials,
connectionGatewayId,
+ connectionProjectId,
...el
} = dataSource;
@@ -103,7 +105,8 @@ const expandSecretScanningDataSource = <
updatedAt: connectionUpdatedAt,
version: connectionVersion,
isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,
- gatewayId: connectionGatewayId
+ gatewayId: connectionGatewayId,
+ projectId: connectionProjectId
}
: undefined
};
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
index 8621b039b7..406c25e037 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-queue.ts
@@ -21,6 +21,8 @@ import { decryptAppConnection } from "@app/services/app-connection/app-connectio
import { TAppConnection } from "@app/services/app-connection/app-connection-types";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
+import { NotificationType } from "@app/services/notification/notification-types";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
@@ -52,6 +54,7 @@ type TSecretRotationV2QueueServiceFactoryDep = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "updateById">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "getItem">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export type TSecretScanningV2QueueServiceFactory = Awaited<ReturnType<typeof secretScanningV2QueueServiceFactory>>;
@@ -65,7 +68,8 @@ export const secretScanningV2QueueServiceFactory = async ({
kmsService,
auditLogService,
keyStore,
- appConnectionDAL
+ appConnectionDAL,
+ notificationService
}: TSecretRotationV2QueueServiceFactoryDep) => {
const queueDataSourceFullScan = async (
dataSource: TSecretScanningDataSourceWithConnection,
@@ -592,16 +596,38 @@ export const secretScanningV2QueueServiceFactory = async ({
const timestamp = new Date().toISOString();
+ const subjectLine =
+ payload.status === SecretScanningScanStatus.Completed
+ ? "Incident Alert: Secret(s) Leaked"
+ : `Secret Scanning Failed`;
+
+ await notificationService.createUserNotifications(
+ recipients.map((member) => ({
+ userId: member.userId,
+ orgId: project.orgId,
+ type:
+ payload.status === SecretScanningScanStatus.Completed
+ ? NotificationType.SECRET_SCANNING_SECRETS_DETECTED
+ : NotificationType.SECRET_SCANNING_SCAN_FAILED,
+ title: subjectLine,
+ body:
+ payload.status === SecretScanningScanStatus.Completed
+ ? `Uncovered **${payload.numberOfSecrets}** secret(s) ${payload.isDiffScan ? " from a recent commit to" : " in"} **${resourceName}**.`
+ : `Encountered an error while attempting to scan the resource **${resourceName}**: ${payload.errorMessage}`,
+ link:
+ payload.status === SecretScanningScanStatus.Completed
+ ? `/projects/secret-scanning/${projectId}/findings?search=scanId:${payload.scanId}`
+ : `/projects/secret-scanning/${projectId}/data-sources/${dataSource.type}/${dataSource.id}`
+ }))
+ );
+
await smtpService.sendMail({
recipients: recipients.map((member) => member.user.email!).filter(Boolean),
template:
payload.status === SecretScanningScanStatus.Completed
? SmtpTemplates.SecretScanningV2SecretsDetected
: SmtpTemplates.SecretScanningV2ScanFailed,
- subjectLine:
- payload.status === SecretScanningScanStatus.Completed
- ? "Incident Alert: Secret(s) Leaked"
- : `Secret Scanning Failed`,
+ subjectLine,
substitutions:
payload.status === SecretScanningScanStatus.Completed
? {
diff --git a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts
index 6bef41e109..c48139e17a 100644
--- a/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts
+++ b/backend/src/ee/services/secret-scanning-v2/secret-scanning-v2-service.ts
@@ -60,7 +60,7 @@ import { TSecretScanningV2QueueServiceFactory } from "./secret-scanning-v2-queue
export type TSecretScanningV2ServiceFactoryDep = {
secretScanningV2DAL: TSecretScanningV2DALFactory;
- appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "updateById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
@@ -252,9 +252,9 @@ export const secretScanningV2ServiceFactory = ({
let connection: TAppConnection | null = null;
if (payload.connectionId) {
// validates permission to connect and app is valid for data source
- connection = await appConnectionService.connectAppConnectionById(
+ connection = await appConnectionService.validateAppConnectionUsageById(
SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP[payload.type],
- payload.connectionId,
+ { connectionId: payload.connectionId, projectId: payload.projectId },
actor
);
}
@@ -373,9 +373,9 @@ export const secretScanningV2ServiceFactory = ({
let connection: TAppConnection | null = null;
if (dataSource.connectionId) {
// validates permission to connect and app is valid for data source
- connection = await appConnectionService.connectAppConnectionById(
+ connection = await appConnectionService.validateAppConnectionUsageById(
SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP[dataSource.type],
- dataSource.connectionId,
+ { connectionId: dataSource.connectionId, projectId: dataSource.projectId },
actor
);
}
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index d61694d8fd..53a2ca993c 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -242,7 +242,12 @@ export const LDAP_AUTH = {
accessTokenTTL: "The lifetime for an access token in seconds.",
accessTokenMaxTTL: "The maximum lifetime for an access token in seconds.",
accessTokenNumUsesLimit: "The maximum number of times that an access token can be used.",
- accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from."
+ accessTokenTrustedIps: "The IPs or CIDR ranges that access tokens can be used from.",
+ lockoutEnabled: "Whether the lockout feature is enabled.",
+ lockoutThreshold: "The amount of times login must fail before locking the identity auth method.",
+ lockoutDurationSeconds: "How long an identity auth method lockout lasts.",
+ lockoutCounterResetSeconds:
+ "How long to wait from the most recent failed login until resetting the lockout counter."
},
UPDATE: {
identityId: "The ID of the identity to update the configuration for.",
@@ -257,13 +262,21 @@ export const LDAP_AUTH = {
accessTokenMaxTTL: "The new maximum lifetime for an access token in seconds.",
accessTokenNumUsesLimit: "The new maximum number of times that an access token can be used.",
accessTokenTrustedIps: "The new IPs or CIDR ranges that access tokens can be used from.",
- templateId: "The ID of the identity auth template to update the configuration to."
+ templateId: "The ID of the identity auth template to update the configuration to.",
+ lockoutEnabled: "Whether the lockout feature is enabled.",
+ lockoutThreshold: "The amount of times login must fail before locking the identity auth method.",
+ lockoutDurationSeconds: "How long an identity auth method lockout lasts.",
+ lockoutCounterResetSeconds:
+ "How long to wait from the most recent failed login until resetting the lockout counter."
},
RETRIEVE: {
identityId: "The ID of the identity to retrieve the configuration for."
},
REVOKE: {
identityId: "The ID of the identity to revoke the configuration for."
+ },
+ CLEAR_CLIENT_LOCKOUTS: {
+ identityId: "The ID of the identity to clear the client lockouts from."
}
} as const;
@@ -711,13 +724,13 @@ export const PROJECTS = {
template: "The name of the project template, if specified, to apply to this project."
},
DELETE: {
- workspaceId: "The ID of the project to delete."
+ projectId: "The ID of the project to delete."
},
GET: {
- workspaceId: "The ID of the project."
+ projectId: "The ID of the project."
},
UPDATE: {
- workspaceId: "The ID of the project to update.",
+ projectId: "The ID of the project to update.",
name: "The new name of the project.",
projectDescription: "An optional description label for the project.",
autoCapitalization: "Disable or enable auto-capitalization for the project.",
@@ -729,10 +742,10 @@ export const PROJECTS = {
secretDetectionIgnoreValues: "The list of secret values to ignore for secret detection."
},
GET_KEY: {
- workspaceId: "The ID of the project to get the key from."
+ projectId: "The ID of the project to get the key from."
},
GET_SNAPSHOTS: {
- workspaceId: "The ID of the project to get snapshots from.",
+ projectId: "The ID of the project to get snapshots from.",
environment: "The environment to get snapshots from.",
path: "The secret path to get snapshots from.",
offset: "The offset to start from. If you enter 10, it will start from the 10th snapshot.",
@@ -759,10 +772,10 @@ export const PROJECTS = {
projectId: "The ID of the project to list groups for."
},
LIST_INTEGRATION: {
- workspaceId: "The ID of the project to list integrations for."
+ projectId: "The ID of the project to list integrations for."
},
LIST_INTEGRATION_AUTHORIZATION: {
- workspaceId: "The ID of the project to list integration auths for."
+ projectId: "The ID of the project to list integration auths for."
},
LIST_SSH_CAS: {
projectId: "The ID of the project to list SSH CAs for."
@@ -815,15 +828,15 @@ export const PROJECT_USERS = {
usernames: "A list of usernames to remove from the project."
},
GET_USER_MEMBERSHIPS: {
- workspaceId: "The ID of the project to get memberships from."
+ projectId: "The ID of the project to get memberships from."
},
GET_USER_MEMBERSHIP: {
- workspaceId: "The ID of the project to get memberships from.",
+ projectId: "The ID of the project to get memberships from.",
membershipId: "The ID of the user's project membership.",
username: "The username to get project membership of. Email is the default username."
},
UPDATE_USER_MEMBERSHIP: {
- workspaceId: "The ID of the project to update the membership for.",
+ projectId: "The ID of the project to update the membership for.",
membershipId: "The ID of the membership to update.",
roles: "A list of roles to update the membership to."
}
@@ -877,31 +890,31 @@ export const PROJECT_IDENTITIES = {
export const ENVIRONMENTS = {
CREATE: {
- workspaceId: "The ID of the project to create the environment in.",
+ projectId: "The ID of the project to create the environment in.",
name: "The name of the environment to create.",
slug: "The slug of the environment to create.",
position: "The position of the environment. The lowest number will be displayed as the first environment."
},
UPDATE: {
- workspaceId: "The ID of the project to update the environment in.",
+ projectId: "The ID of the project to update the environment in.",
id: "The ID of the environment to update.",
name: "The new name of the environment.",
slug: "The new slug of the environment.",
position: "The new position of the environment. The lowest number will be displayed as the first environment."
},
DELETE: {
- workspaceId: "The ID of the project to delete the environment from.",
+ projectId: "The ID of the project to delete the environment from.",
id: "The ID of the environment to delete."
},
GET: {
- workspaceId: "The ID of the project the environment belongs to.",
+ projectId: "The ID of the project the environment belongs to.",
id: "The ID of the environment to fetch."
}
} as const;
export const FOLDERS = {
LIST: {
- workspaceId: "The ID of the project to list folders from.",
+ projectId: "The ID of the project to list folders from.",
environment: "The slug of the environment to list folders from.",
path: "The path to list folders from.",
directory: "The directory to list folders from. (Deprecated in favor of path)",
@@ -913,7 +926,7 @@ export const FOLDERS = {
folderId: "The ID of the folder to get details."
},
CREATE: {
- workspaceId: "The ID of the project to create the folder in.",
+ projectId: "The ID of the project to create the folder in.",
environment: "The slug of the environment to create the folder in.",
name: "The name of the folder to create.",
path: "The path of the folder to create.",
@@ -927,12 +940,12 @@ export const FOLDERS = {
path: "The path of the folder to update.",
directory: "The new directory of the folder to update. (Deprecated in favor of path)",
projectSlug: "The slug of the project where the folder is located.",
- workspaceId: "The ID of the project where the folder is located.",
+ projectId: "The ID of the project where the folder is located.",
description: "An optional description label for the folder."
},
DELETE: {
folderIdOrName: "The ID or name of the folder to delete.",
- workspaceId: "The ID of the project to delete the folder from.",
+ projectId: "The ID of the project to delete the folder from.",
environment: "The slug of the environment where the folder is located.",
directory: "The directory of the folder to delete. (Deprecated in favor of path)",
path: "The path of the folder to delete."
@@ -964,7 +977,7 @@ export const RAW_SECRETS = {
expand: "Whether or not to expand secret references.",
recursive:
"Whether or not to fetch all secrets from the specified base path, and all of its subdirectories. Note, the max depth is 20 deep.",
- workspaceId: "The ID of the project to list secrets from.",
+ projectId: "The ID of the project to list secrets from.",
workspaceSlug:
"The slug of the project to list secrets from. This parameter is only applicable by machine identities.",
environment: "The slug of the environment to list secrets from.",
@@ -984,7 +997,7 @@ export const RAW_SECRETS = {
secretValue: "The value of the secret to create.",
skipMultilineEncoding: "Skip multiline encoding for the secret value.",
type: "The type of the secret to create.",
- workspaceId: "The ID of the project to create the secret in.",
+ projectId: "The ID of the project to create the secret in.",
tagIds: "The ID of the tags to be attached to the created secret.",
secretReminderRepeatDays: "Interval for secret rotation notifications, measured in days.",
secretReminderNote: "Note to be attached in notification email."
@@ -992,7 +1005,7 @@ export const RAW_SECRETS = {
GET: {
expand: "Whether or not to expand secret references.",
secretName: "The name of the secret to get.",
- workspaceId: "The ID of the project to get the secret from.",
+ projectId: "The ID of the project to get the secret from.",
workspaceSlug: "The slug of the project to get the secret from.",
environment: "The slug of the environment to get the secret from.",
secretPath: "The path of the secret to get.",
@@ -1011,7 +1024,7 @@ export const RAW_SECRETS = {
skipMultilineEncoding: "Skip multiline encoding for the secret value.",
type: "The type of the secret to update.",
projectSlug: "The slug of the project to update the secret in.",
- workspaceId: "The ID of the project to update the secret in.",
+ projectId: "The ID of the project to update the secret in.",
tagIds: "The ID of the tags to be attached to the updated secret.",
secretReminderRepeatDays: "Interval for secret rotation notifications, measured in days.",
secretReminderNote: "Note to be attached in notification email.",
@@ -1025,11 +1038,11 @@ export const RAW_SECRETS = {
secretPath: "The path of the secret.",
type: "The type of the secret to delete.",
projectSlug: "The slug of the project to delete the secret in.",
- workspaceId: "The ID of the project where the secret is located."
+ projectId: "The ID of the project where the secret is located."
},
GET_REFERENCE_TREE: {
secretName: "The name of the secret to get the reference tree for.",
- workspaceId: "The ID of the project where the secret is located.",
+ projectId: "The ID of the project where the secret is located.",
environment: "The slug of the environment where the the secret is located.",
secretPath: "The folder path where the secret is located."
},
@@ -1043,7 +1056,7 @@ export const RAW_SECRETS = {
export const SECRET_IMPORTS = {
LIST: {
- workspaceId: "The ID of the project to list secret imports from.",
+ projectId: "The ID of the project to list secret imports from.",
environment: "The slug of the environment to list secret imports from.",
path: "The path to list secret imports from."
},
@@ -1053,7 +1066,7 @@ export const SECRET_IMPORTS = {
CREATE: {
environment: "The slug of the environment to import into.",
path: "The path to import into.",
- workspaceId: "The ID of the project you are working in.",
+ projectId: "The ID of the project you are working in.",
isReplication:
"When true, secrets from the source will be automatically sent to the destination. If approval policies exist at the destination, the secrets will be sent as approval requests instead of being applied immediately.",
import: {
@@ -1070,10 +1083,10 @@ export const SECRET_IMPORTS = {
position: "The new position of the secret import. The lowest number will be displayed as the first import."
},
path: "The path of the secret import to update.",
- workspaceId: "The ID of the project where the secret import is located."
+ projectId: "The ID of the project where the secret import is located."
},
DELETE: {
- workspaceId: "The ID of the project to delete the secret import from.",
+ projectId: "The ID of the project to delete the secret import from.",
secretImportId: "The ID of the secret import to delete.",
environment: "The slug of the environment where the secret import is located.",
path: "The path of the secret import to delete."
@@ -2185,11 +2198,15 @@ export const CertificateAuthorities = {
};
export const AppConnections = {
+ LIST: (app?: AppConnection) => ({
+ projectId: `The ID of the project to list ${app ? APP_CONNECTION_NAME_MAP[app] : "App"} Connections from.`
+ }),
GET_BY_ID: (app: AppConnection) => ({
connectionId: `The ID of the ${APP_CONNECTION_NAME_MAP[app]} Connection to retrieve.`
}),
GET_BY_NAME: (app: AppConnection) => ({
- connectionName: `The name of the ${APP_CONNECTION_NAME_MAP[app]} Connection to retrieve.`
+ connectionName: `The name of the ${APP_CONNECTION_NAME_MAP[app]} Connection to retrieve.`,
+ projectId: `The project ID of the ${APP_CONNECTION_NAME_MAP[app]} Connection is associated with. Leave unspecified to get organization-level connections.`
}),
CREATE: (app: AppConnection) => {
const appName = APP_CONNECTION_NAME_MAP[app];
@@ -2198,7 +2215,8 @@ export const AppConnections = {
description: `An optional description for the ${appName} Connection.`,
credentials: `The credentials used to connect with ${appName}.`,
method: `The method used to authenticate with ${appName}.`,
- isPlatformManagedCredentials: `Whether or not the ${appName} Connection credentials should be managed by Infisical. Once enabled this cannot be reversed.`
+ isPlatformManagedCredentials: `Whether or not the ${appName} Connection credentials should be managed by Infisical. Once enabled this cannot be reversed.`,
+ projectId: `The ID of the project to create the ${appName} Connection in.`
};
},
UPDATE: (app: AppConnection) => {
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 5a7c92f22b..f2f63f57a8 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -231,6 +231,8 @@ export type TQueueJobTypes = {
[QueueName.ImportSecretsFromExternalSource]: {
name: QueueJobs.ImportSecretsFromExternalSource;
payload: {
+ orgId: string;
+ actorId: string;
actorEmail: string;
importType: ExternalPlatforms;
data: {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index eccad29565..8444e87657 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -328,6 +328,7 @@ import { registerV1Routes } from "./v1";
import { initializeOauthConfigSync } from "./v1/sso-router";
import { registerV2Routes } from "./v2";
import { registerV3Routes } from "./v3";
+import { registerV4Routes } from "./v4";
const histogram = monitorEventLoopDelay({ resolution: 20 });
histogram.enable();
@@ -772,7 +773,8 @@ export const registerRoutes = async (
orgDAL,
totpService,
orgMembershipDAL,
- auditLogService
+ auditLogService,
+ notificationService
});
const passwordService = authPaswordServiceFactory({
tokenService,
@@ -886,7 +888,8 @@ export const registerRoutes = async (
projectDAL,
permissionService,
projectUserMembershipRoleDAL,
- projectMembershipDAL
+ projectMembershipDAL,
+ notificationService
});
const rateLimitService = rateLimitServiceFactory({
@@ -925,7 +928,8 @@ export const registerRoutes = async (
projectRoleDAL,
groupProjectDAL,
secretReminderRecipientsDAL,
- licenseService
+ licenseService,
+ notificationService
});
const projectUserAdditionalPrivilegeService = projectUserAdditionalPrivilegeServiceFactory({
permissionService,
@@ -1106,7 +1110,9 @@ export const registerRoutes = async (
instanceRelayConfigDAL,
orgRelayConfigDAL,
relayDAL,
- kmsService
+ kmsService,
+ licenseService,
+ permissionService
});
const gatewayV2Service = gatewayV2ServiceFactory({
@@ -1144,7 +1150,8 @@ export const registerRoutes = async (
appConnectionDAL,
licenseService,
gatewayService,
- gatewayV2Service
+ gatewayV2Service,
+ notificationService
});
const secretQueueService = secretQueueFactory({
@@ -1228,7 +1235,8 @@ export const registerRoutes = async (
projectTemplateService,
groupProjectDAL,
smtpService,
- reminderService
+ reminderService,
+ notificationService
});
const projectEnvService = projectEnvServiceFactory({
@@ -1362,7 +1370,8 @@ export const registerRoutes = async (
resourceMetadataDAL,
projectMicrosoftTeamsConfigDAL,
microsoftTeamsService,
- folderCommitService
+ folderCommitService,
+ notificationService
});
const secretService = secretServiceFactory({
@@ -1680,7 +1689,8 @@ export const registerRoutes = async (
identityOrgMembershipDAL,
licenseService,
identityDAL,
- identityAuthTemplateDAL
+ identityAuthTemplateDAL,
+ keyStore
});
const dynamicSecretProviders = buildDynamicSecretProviders({
@@ -1812,7 +1822,8 @@ export const registerRoutes = async (
secretV2BridgeService,
resourceMetadataDAL,
folderCommitService,
- folderVersionDAL
+ folderVersionDAL,
+ notificationService
});
const migrationService = externalMigrationServiceFactory({
@@ -1837,7 +1848,8 @@ export const registerRoutes = async (
gatewayService,
gatewayV2Service,
gatewayDAL,
- gatewayV2DAL
+ gatewayV2DAL,
+ projectDAL
});
const secretSyncService = secretSyncServiceFactory({
@@ -2014,7 +2026,8 @@ export const registerRoutes = async (
queueService,
projectDAL,
projectMembershipDAL,
- smtpService
+ smtpService,
+ notificationService
});
const secretScanningV2Queue = await secretScanningV2QueueServiceFactory({
@@ -2026,7 +2039,8 @@ export const registerRoutes = async (
smtpService,
kmsService,
keyStore,
- appConnectionDAL
+ appConnectionDAL,
+ notificationService
});
const secretScanningV2Service = secretScanningV2ServiceFactory({
@@ -2294,6 +2308,7 @@ export const registerRoutes = async (
{ prefix: "/api/v2" }
);
await server.register(registerV3Routes, { prefix: "/api/v3" });
+ await server.register(registerV4Routes, { prefix: "/api/v4" });
server.addHook("onClose", async () => {
cronJobs.forEach((job) => job.stop());
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
index 50111b1090..720726c340 100644
--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
@@ -26,6 +26,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
description?: string | null;
isPlatformManagedCredentials?: boolean;
gatewayId?: string | null;
+ projectId?: string;
}>;
updateSchema: z.ZodType<{
name?: string;
@@ -47,18 +48,27 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
schema: {
hide: false,
tags: [ApiDocsTags.AppConnections],
- description: `List the ${appName} Connections for the current organization.`,
+ description: `List the ${appName} Connections for the current organization or project.`,
+ querystring: z.object({
+ projectId: z.string().optional().describe(AppConnections.LIST(app).projectId)
+ }),
response: {
200: z.object({ appConnections: sanitizedResponseSchema.array() })
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const appConnections = (await server.services.appConnection.listAppConnectionsByOrg(req.permission, app)) as T[];
+ const { projectId } = req.query;
+ const appConnections = (await server.services.appConnection.listAppConnections(
+ req.permission,
+ app,
+ projectId
+ )) as T[];
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId,
event: {
type: EventType.GET_APP_CONNECTIONS,
metadata: {
@@ -82,14 +92,19 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
schema: {
hide: false,
tags: [ApiDocsTags.AppConnections],
- description: `List the ${appName} Connections the current user has permission to establish connections with.`,
+ description: `List the ${appName} Connections the current user has permission to establish connections within this project.`,
+ querystring: z.object({
+ projectId: z.string().optional().describe(AppConnections.LIST(app).projectId)
+ }),
response: {
200: z.object({
appConnections: z
.object({
app: z.literal(app),
name: z.string(),
- id: z.string().uuid()
+ id: z.string().uuid(),
+ projectId: z.string().nullish(),
+ orgId: z.string()
})
.array()
})
@@ -97,14 +112,17 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ const { projectId } = req.query;
const appConnections = await server.services.appConnection.listAvailableAppConnectionsForUser(
app,
- req.permission
+ req.permission,
+ projectId
);
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId,
event: {
type: EventType.GET_AVAILABLE_APP_CONNECTIONS_DETAILS,
metadata: {
@@ -149,6 +167,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId: appConnection.projectId ?? undefined,
event: {
type: EventType.GET_APP_CONNECTION,
metadata: {
@@ -178,6 +197,9 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
.min(1, "Connection name required")
.describe(AppConnections.GET_BY_NAME(app).connectionName)
}),
+ querystring: z.object({
+ projectId: z.string().trim().optional().describe(AppConnections.GET_BY_NAME(app).projectId)
+ }),
response: {
200: z.object({ appConnection: sanitizedResponseSchema })
}
@@ -185,16 +207,21 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const { connectionName } = req.params;
+ const { projectId } = req.query;
const appConnection = (await server.services.appConnection.findAppConnectionByName(
app,
- connectionName,
+ {
+ connectionName,
+ projectId
+ },
req.permission
)) as T;
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId: appConnection.projectId ?? undefined,
event: {
type: EventType.GET_APP_CONNECTION,
metadata: {
@@ -216,9 +243,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
schema: {
hide: false,
tags: [ApiDocsTags.AppConnections],
- description: `Create ${
- startsWithVowel(appName) ? "an" : "a"
- } ${appName} Connection for the current organization.`,
+ description: `Create ${startsWithVowel(appName) ? "an" : "a"} ${appName} Connection.`,
body: createSchema,
response: {
200: z.object({ appConnection: sanitizedResponseSchema })
@@ -226,16 +251,17 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const { name, method, credentials, description, isPlatformManagedCredentials, gatewayId } = req.body;
+ const { name, method, credentials, description, isPlatformManagedCredentials, gatewayId, projectId } = req.body;
const appConnection = (await server.services.appConnection.createAppConnection(
- { name, method, app, credentials, description, isPlatformManagedCredentials, gatewayId },
+ { name, method, app, credentials, description, isPlatformManagedCredentials, gatewayId, projectId },
req.permission
)) as T;
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId,
event: {
type: EventType.CREATE_APP_CONNECTION,
metadata: {
@@ -283,6 +309,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId: appConnection.projectId ?? undefined,
event: {
type: EventType.UPDATE_APP_CONNECTION,
metadata: {
@@ -329,6 +356,7 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId: appConnection.projectId ?? undefined,
event: {
type: EventType.DELETE_APP_CONNECTION,
metadata: {
@@ -340,4 +368,81 @@ export const registerAppConnectionEndpoints = <T extends TAppConnection, I exten
return { appConnection };
}
});
+
+ // scott: we will need this once we have individual app connection page and may want to expose to API
+ // server.route({
+ // method: "GET",
+ // url: `/:connectionId/usage`,
+ // config: {
+ // rateLimit: readLimit
+ // },
+ // schema: {
+ // hide: true, // scott: we could expose this in the future but just for UI right now
+ // tags: [ApiDocsTags.AppConnections],
+ // params: z.object({
+ // connectionId: z.string().uuid()
+ // }),
+ // response: {
+ // 200: z.object({
+ // projects: z
+ // .object({
+ // id: z.string(),
+ // name: z.string(),
+ // type: z.nativeEnum(ProjectType),
+ // slug: z.string(),
+ // resources: z.object({
+ // secretSyncs: z
+ // .object({
+ // id: z.string(),
+ // name: z.string()
+ // })
+ // .array(),
+ // secretRotations: z
+ // .object({
+ // id: z.string(),
+ // name: z.string()
+ // })
+ // .array(),
+ // externalCas: z
+ // .object({
+ // id: z.string(),
+ // name: z.string()
+ // })
+ // .array(),
+ // dataSources: z
+ // .object({
+ // id: z.string(),
+ // name: z.string()
+ // })
+ // .array()
+ // })
+ // })
+ // .array()
+ // })
+ // }
+ // },
+ // onRequest: verifyAuth([AuthMode.JWT]),
+ // handler: async (req) => {
+ // const { connectionId } = req.params;
+ //
+ // const projects = await server.services.appConnection.findAppConnectionUsageById(
+ // app,
+ // connectionId,
+ // req.permission
+ // );
+ //
+ // await server.services.auditLog.createAuditLog({
+ // ...req.auditLogInfo,
+ // orgId: req.permission.orgId,
+ // event: {
+ // type: EventType.GET_APP_CONNECTION_USAGE,
+ // metadata: {
+ // connectionId
+ // }
+ // }
+ // });
+ //
+ // return { projects };
+ // }
+ // });
};
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
index c2033f4b49..37558b817d 100644
--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
@@ -1,12 +1,13 @@
import { z } from "zod";
+import { ProjectType } from "@app/db/schemas";
import { OCIConnectionListItemSchema, SanitizedOCIConnectionSchema } from "@app/ee/services/app-connections/oci";
import {
OracleDBConnectionListItemSchema,
SanitizedOracleDBConnectionSchema
} from "@app/ee/services/app-connections/oracledb";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { ApiDocsTags } from "@app/lib/api-docs";
+import { ApiDocsTags, AppConnections } from "@app/lib/api-docs";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import {
@@ -210,6 +211,9 @@ export const registerAppConnectionRouter = async (server: FastifyZodProvider) =>
hide: false,
tags: [ApiDocsTags.AppConnections],
description: "List the available App Connection Options.",
+ querystring: z.object({
+ projectType: z.nativeEnum(ProjectType).optional()
+ }),
response: {
200: z.object({
appConnectionOptions: AppConnectionOptionsSchema.array()
@@ -217,8 +221,8 @@ export const registerAppConnectionRouter = async (server: FastifyZodProvider) =>
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: () => {
- const appConnectionOptions = server.services.appConnection.listAppConnectionOptions();
+ handler: (req) => {
+ const appConnectionOptions = server.services.appConnection.listAppConnectionOptions(req.query.projectType);
return { appConnectionOptions };
}
});
@@ -232,18 +236,27 @@ export const registerAppConnectionRouter = async (server: FastifyZodProvider) =>
schema: {
hide: false,
tags: [ApiDocsTags.AppConnections],
- description: "List all the App Connections for the current organization.",
+ description: "List all the App Connections for the current organization or project.",
+ querystring: z.object({
+ projectId: z.string().optional().describe(AppConnections.LIST().projectId)
+ }),
response: {
200: z.object({ appConnections: SanitizedAppConnectionSchema.array() })
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const appConnections = await server.services.appConnection.listAppConnectionsByOrg(req.permission);
+ const { projectId } = req.query;
+ const appConnections = await server.services.appConnection.listAppConnections(
+ req.permission,
+ undefined,
+ projectId
+ );
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
+ projectId,
event: {
type: EventType.GET_APP_CONNECTIONS,
metadata: {
diff --git a/backend/src/server/routes/v1/dashboard-router.ts b/backend/src/server/routes/v1/dashboard-router.ts
index a54bd5ccfe..8cf9604a43 100644
--- a/backend/src/server/routes/v1/dashboard-router.ts
+++ b/backend/src/server/routes/v1/dashboard-router.ts
@@ -1,16 +1,16 @@
import { ForbiddenError } from "@casl/ability";
import { z } from "zod";
-import { SecretFoldersSchema, SecretImportsSchema, UsersSchema } from "@app/db/schemas";
+import { SecretFoldersSchema, SecretImportsSchema, SecretType, UsersSchema } from "@app/db/schemas";
import { RemindersSchema } from "@app/db/schemas/reminders";
import { EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { ProjectPermissionSecretActions } from "@app/ee/services/permission/project-permission";
import { SecretRotationV2Schema } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-union-schema";
import { DASHBOARD } from "@app/lib/api-docs";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { removeTrailingSlash } from "@app/lib/fn";
import { OrderByDirection } from "@app/lib/types";
-import { secretsLimit } from "@app/server/config/rateLimiter";
+import { readLimit, secretsLimit } from "@app/server/config/rateLimiter";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { getUserAgentType } from "@app/server/plugins/audit-log";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -111,6 +111,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
SecretRotationV2Schema,
z.object({
secrets: secretRawSchema
+ .omit({ secretValue: true })
.extend({
secretValueHidden: z.boolean(),
secretPath: z.string().optional(),
@@ -124,7 +125,9 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
.array()
.optional(),
secrets: secretRawSchema
+ .omit({ secretValue: true })
.extend({
+ isEmpty: z.boolean(),
secretValueHidden: z.boolean(),
secretPath: z.string().optional(),
secretMetadata: ResourceMetadataSchema.optional(),
@@ -207,7 +210,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
const environments = req.query.environments.split(",");
if (!projectId || environments.length === 0)
- throw new BadRequestError({ message: "Missing workspace id or environment(s)" });
+ throw new BadRequestError({ message: "Missing project id or environment(s)" });
const { shouldUseSecretV2Bridge } = await server.services.projectBot.getBotKey(projectId);
@@ -219,7 +222,9 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
let imports: Awaited<ReturnType<typeof server.services.secretImport.getImportsMultiEnv>> | undefined;
let folders: Awaited<ReturnType<typeof server.services.folder.getFoldersMultiEnv>> | undefined;
- let secrets: Awaited<ReturnType<typeof server.services.secret.getSecretsRawMultiEnv>> | undefined;
+ let secrets:
+ | (Awaited<ReturnType<typeof server.services.secret.getSecretsRawMultiEnv>>[number] & { isEmpty: boolean })[]
+ | undefined;
let dynamicSecrets:
| Awaited<ReturnType<typeof server.services.dynamicSecret.listDynamicSecretsByEnvs>>
| undefined;
@@ -426,43 +431,51 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
});
if (remainingLimit > 0 && totalSecretCount > adjustedOffset) {
- secrets = await server.services.secret.getSecretsRawMultiEnv({
- viewSecretValue: true,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId,
- environments,
- actorAuthMethod: req.permission.authMethod,
- projectId,
- path: secretPath,
- orderBy,
- orderDirection,
- search,
- limit: remainingLimit,
- offset: adjustedOffset,
- isInternal: true
- });
+ secrets = (
+ await server.services.secret.getSecretsRawMultiEnv({
+ viewSecretValue: true,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ environments,
+ actorAuthMethod: req.permission.authMethod,
+ projectId,
+ path: secretPath,
+ orderBy,
+ orderDirection,
+ search,
+ limit: remainingLimit,
+ offset: adjustedOffset,
+ isInternal: true
+ })
+ ).map((secret) => ({ ...secret, isEmpty: !secret.secretValue }));
}
}
if (secrets?.length || secretRotations?.length) {
for await (const environment of environments) {
- const secretCountFromEnv =
- (secrets?.filter((secret) => secret.environment === environment).length ?? 0) +
- (secretRotations
- ?.filter((rotation) => rotation.environment.slug === environment)
- .flatMap((rotation) => rotation.secrets.filter((secret) => Boolean(secret))).length ?? 0);
+ const secretIds = [
+ ...new Set(
+ [
+ ...(secrets?.filter((secret) => secret.environment === environment) ?? []),
+ ...(secretRotations
+ ?.filter((rotation) => rotation.environment.slug === environment)
+ .flatMap((rotation) => rotation.secrets.filter((secret) => Boolean(secret))) ?? [])
+ ].map((secret) => secret.id)
+ )
+ ];
- if (secretCountFromEnv) {
+ if (secretIds) {
await server.services.auditLog.createAuditLog({
projectId,
...req.auditLogInfo,
event: {
- type: EventType.GET_SECRETS,
+ type: EventType.DASHBOARD_LIST_SECRETS,
metadata: {
environment,
secretPath,
- numberOfSecrets: secretCountFromEnv
+ numberOfSecrets: secretIds.length,
+ secretIds
}
}
});
@@ -473,8 +486,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
distinctId: getTelemetryDistinctId(req),
organizationId: req.permission.orgId,
properties: {
- numberOfSecrets: secretCountFromEnv,
- workspaceId: projectId,
+ numberOfSecrets: secretIds.length,
+ projectId,
environment,
secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -584,7 +597,6 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
.optional(),
search: z.string().trim().describe(DASHBOARD.SECRET_DETAILS_LIST.search).optional(),
tags: z.string().trim().transform(decodeURIComponent).describe(DASHBOARD.SECRET_DETAILS_LIST.tags).optional(),
- viewSecretValue: booleanSchema.default(true),
includeSecrets: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeSecrets),
includeFolders: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeFolders),
includeDynamicSecrets: booleanSchema.describe(DASHBOARD.SECRET_DETAILS_LIST.includeDynamicSecrets),
@@ -606,7 +618,9 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
SecretRotationV2Schema,
z.object({
secrets: secretRawSchema
+ .omit({ secretValue: true })
.extend({
+ isEmpty: z.boolean(),
secretValueHidden: z.boolean(),
secretPath: z.string().optional(),
secretMetadata: ResourceMetadataSchema.optional(),
@@ -619,7 +633,9 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
.array()
.optional(),
secrets: secretRawSchema
+ .omit({ secretValue: true })
.extend({
+ isEmpty: z.boolean(),
secretReminderRecipients: z
.object({
user: UsersSchema.pick({ id: true, email: true, username: true }),
@@ -696,7 +712,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
includeSecretRotations
} = req.query;
- if (!projectId || !environment) throw new BadRequestError({ message: "Missing workspace id or environment" });
+ if (!projectId || !environment) throw new BadRequestError({ message: "Missing project id or environment" });
const { shouldUseSecretV2Bridge } = await server.services.projectBot.getBotKey(projectId);
@@ -715,12 +731,21 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
let folders: Awaited<ReturnType<typeof server.services.folder.getFolders>> | undefined;
let secrets:
| (Awaited<ReturnType<typeof server.services.secret.getSecretsRaw>>["secrets"][number] & {
+ isEmpty: boolean;
reminder: Awaited<ReturnType<typeof server.services.reminder.getRemindersForDashboard>>[string] | null;
})[]
| undefined;
let dynamicSecrets: Awaited<ReturnType<typeof server.services.dynamicSecret.listDynamicSecretsByEnv>> | undefined;
let secretRotations:
- | Awaited<ReturnType<typeof server.services.secretRotationV2.getDashboardSecretRotations>>
+ | (Awaited<ReturnType<typeof server.services.secretRotationV2.getDashboardSecretRotations>>[number] & {
+ secrets: (NonNullable<
+ Awaited<
+ ReturnType<typeof server.services.secretRotationV2.getDashboardSecretRotations>
+ >[number]["secrets"][number] & {
+ isEmpty: boolean;
+ }
+ > | null)[];
+ })[]
| undefined;
let totalImportCount: number | undefined;
@@ -822,19 +847,31 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
);
if (remainingLimit > 0 && totalSecretRotationCount > adjustedOffset) {
- secretRotations = await server.services.secretRotationV2.getDashboardSecretRotations(
- {
- projectId,
- search,
- orderBy,
- orderDirection,
- environments: [environment],
- secretPath,
- limit: remainingLimit,
- offset: adjustedOffset
- },
- req.permission
- );
+ secretRotations = (
+ await server.services.secretRotationV2.getDashboardSecretRotations(
+ {
+ projectId,
+ search,
+ orderBy,
+ orderDirection,
+ environments: [environment],
+ secretPath,
+ limit: remainingLimit,
+ offset: adjustedOffset
+ },
+ req.permission
+ )
+ ).map((rotation) => ({
+ ...rotation,
+ secrets: rotation.secrets.map((secret) =>
+ secret
+ ? {
+ ...secret,
+ isEmpty: !secret.secretValue
+ }
+ : secret
+ )
+ }));
await server.services.auditLog.createAuditLog({
projectId,
@@ -919,7 +956,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
await server.services.secret.getSecretsRaw({
actorId: req.permission.id,
actor: req.permission.type,
- viewSecretValue: req.query.viewSecretValue,
+ viewSecretValue: true,
throwOnMissingReadValuePermission: false,
actorOrgId: req.permission.orgId,
environment,
@@ -943,6 +980,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
secrets = rawSecrets.map((secret) => ({
...secret,
+ isEmpty: !secret.secretValue,
reminder: reminders[secret.id] ?? null
}));
}
@@ -977,19 +1015,25 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
}));
if (secrets?.length || secretRotations?.length) {
- const secretCount =
- (secrets?.length ?? 0) +
- (secretRotations?.flatMap((rotation) => rotation.secrets.filter((secret) => Boolean(secret))).length ?? 0);
+ const secretIds = [
+ ...new Set(
+ [
+ ...(secrets ?? []),
+ ...(secretRotations?.flatMap((rotation) => rotation.secrets.filter((secret) => Boolean(secret))) ?? [])
+ ].map((secret) => secret.id)
+ )
+ ];
await server.services.auditLog.createAuditLog({
projectId,
...req.auditLogInfo,
event: {
- type: EventType.GET_SECRETS,
+ type: EventType.DASHBOARD_LIST_SECRETS,
metadata: {
environment,
secretPath,
- numberOfSecrets: secretCount
+ numberOfSecrets: secretIds.length,
+ secretIds
}
}
});
@@ -1000,8 +1044,8 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
distinctId: getTelemetryDistinctId(req),
organizationId: req.permission.orgId,
properties: {
- numberOfSecrets: secretCount,
- workspaceId: projectId,
+ numberOfSecrets: secretIds.length,
+ projectId,
environment,
secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1060,6 +1104,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
.array()
.optional(),
secrets: secretRawSchema
+ .omit({ secretValue: true })
.extend({
secretValueHidden: z.boolean(),
secretPath: z.string().optional(),
@@ -1145,18 +1190,20 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
);
for await (const environment of environments) {
- const secretCountForEnv = secrets.filter((secret) => secret.environment === environment).length;
+ const envSecrets = secrets.filter((secret) => secret.environment === environment);
+ const secretCountForEnv = envSecrets.length;
if (secretCountForEnv) {
await server.services.auditLog.createAuditLog({
projectId,
...req.auditLogInfo,
event: {
- type: EventType.GET_SECRETS,
+ type: EventType.DASHBOARD_LIST_SECRETS,
metadata: {
environment,
secretPath,
- numberOfSecrets: secretCountForEnv
+ numberOfSecrets: secretCountForEnv,
+ secretIds: envSecrets.map((secret) => secret.id)
}
}
});
@@ -1168,7 +1215,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secretCountForEnv,
- workspaceId: projectId,
+ projectId,
environment,
secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1259,6 +1306,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
+ // TODO(scott): omit secretValue here, but requires refactor of uploading env/copy from board
secrets: secretRawSchema
.extend({
secretPath: z.string().optional(),
@@ -1310,6 +1358,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
+ // TODO(scott): omit secretValue here, but requires refactor of uploading env/copy from board
secrets: secretRawSchema
.extend({
secretValueHidden: z.boolean(),
@@ -1345,11 +1394,12 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
projectId,
...req.auditLogInfo,
event: {
- type: EventType.GET_SECRETS,
+ type: EventType.DASHBOARD_LIST_SECRETS,
metadata: {
environment,
secretPath,
- numberOfSecrets: secrets.length
+ numberOfSecrets: secrets.length,
+ secretIds: secrets.map((secret) => secret.id)
}
}
});
@@ -1361,7 +1411,7 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: projectId,
+ projectId,
environment,
secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1373,4 +1423,256 @@ export const registerDashboardRouter = async (server: FastifyZodProvider) => {
return { secrets };
}
});
+
+ server.route({
+ method: "GET",
+ url: "/secret-value",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ querystring: z.object({
+ projectId: z.string().trim(),
+ environment: z.string().trim(),
+ secretPath: z.string().trim().default("/").transform(removeTrailingSlash),
+ secretKey: z.string().trim(),
+ isOverride: z
+ .enum(["true", "false"])
+ .transform((value) => value === "true")
+ .optional()
+ }),
+ response: {
+ 200: z.object({
+ valueOverride: z.string().optional(),
+ value: z.string().optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { secretPath, projectId, environment, secretKey, isOverride } = req.query;
+
+ // TODO (scott): just get the secret instead of searching for it in list
+ const { secrets } = await server.services.secret.getSecretsRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ viewSecretValue: true,
+ throwOnMissingReadValuePermission: false,
+ actorOrgId: req.permission.orgId,
+ environment,
+ actorAuthMethod: req.permission.authMethod,
+ projectId,
+ path: secretPath,
+ search: secretKey,
+ includeTagsInSearch: true,
+ includeMetadataInSearch: true
+ });
+
+ if (isOverride) {
+ const personalSecret = secrets.find(
+ (secret) => secret.type === SecretType.Personal && secret.secretKey === secretKey
+ );
+
+ if (!personalSecret)
+ throw new BadRequestError({
+ message: `Could not find personal secret with key "${secretKey}" at secret path "${secretPath}" in environment "${environment}" for project with ID "${projectId}"`
+ });
+
+ if (personalSecret)
+ return {
+ valueOverride: personalSecret.secretValue
+ };
+ }
+
+ const sharedSecret = secrets.find(
+ (secret) => secret.type === SecretType.Shared && secret.secretKey === secretKey
+ );
+
+ if (!sharedSecret)
+ throw new BadRequestError({
+ message: `Could not find secret with key "${secretKey}" at secret path "${secretPath}" in environment "${environment}" for project with ID "${projectId}"`
+ });
+
+ // only audit if not personal
+ await server.services.auditLog.createAuditLog({
+ projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.DASHBOARD_GET_SECRET_VALUE,
+ metadata: {
+ environment: req.query.environment,
+ secretPath: req.query.secretPath,
+ secretKey,
+ secretId: sharedSecret.id
+ }
+ }
+ });
+
+ return { value: sharedSecret.secretValue };
+ }
+ });
+
+ server.route({
+ url: "/secret-imports",
+ method: "GET",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ querystring: z.object({
+ projectId: z.string().trim(),
+ environment: z.string().trim(),
+ path: z.string().trim().default("/").transform(removeTrailingSlash)
+ }),
+ response: {
+ 200: z.object({
+ secrets: z
+ .object({
+ secretPath: z.string(),
+ environment: z.string(),
+ environmentInfo: z.object({
+ id: z.string(),
+ name: z.string(),
+ slug: z.string()
+ }),
+ folderId: z.string().optional(),
+ secrets: secretRawSchema.omit({ secretValue: true }).extend({ isEmpty: z.boolean() }).array()
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const importedSecrets = await server.services.secretImport.getRawSecretsFromImports({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.query
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId: req.query.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.DASHBOARD_LIST_SECRETS,
+ metadata: {
+ environment: req.query.environment,
+ secretPath: req.query.path,
+ numberOfSecrets: importedSecrets.length,
+ secretIds: importedSecrets.map((secret) => secret.id)
+ }
+ }
+ });
+
+ return {
+ secrets: importedSecrets.map((importData) => ({
+ ...importData,
+ secrets: importData.secrets.map((secret) => ({
+ ...secret,
+ isEmpty: !secret.secretValue
+ }))
+ }))
+ };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/secret-versions/:secretId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ secretId: z.string()
+ }),
+ querystring: z.object({
+ offset: z.coerce.number(),
+ limit: z.coerce.number()
+ }),
+ response: {
+ 200: z.object({
+ secretVersions: secretRawSchema
+ .omit({ secretValue: true })
+ .extend({
+ secretValueHidden: z.boolean()
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const secretVersions = await server.services.secret.getSecretVersions({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ limit: req.query.limit,
+ offset: req.query.offset,
+ secretId: req.params.secretId
+ });
+
+ return { secretVersions };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/secret-versions/:secretId/value/:version",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ secretId: z.string(),
+ version: z.string()
+ }),
+
+ response: {
+ 200: z.object({
+ value: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { version, secretId } = req.params;
+
+ const [secretVersion] = await server.services.secret.getSecretVersions({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ secretId,
+ secretVersions: [version]
+ });
+
+ if (!secretVersion)
+ throw new NotFoundError({
+ message: `Could not find secret version "${version}" for secret with ID "${secretId}`
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId: secretVersion.workspace,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.DASHBOARD_GET_SECRET_VERSION_VALUE,
+ metadata: {
+ secretId,
+ version
+ }
+ }
+ });
+
+ return { value: secretVersion.secretValue };
+ }
+ });
};
diff --git a/backend/src/server/routes/v1/deprecated-project-env-router.ts b/backend/src/server/routes/v1/deprecated-project-env-router.ts
new file mode 100644
index 0000000000..1a187e2b16
--- /dev/null
+++ b/backend/src/server/routes/v1/deprecated-project-env-router.ts
@@ -0,0 +1,298 @@
+import { z } from "zod";
+
+import { ProjectEnvironmentsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, ENVIRONMENTS } from "@app/lib/api-docs";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { slugSchema } from "@app/server/lib/schemas";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const registerDeprecatedProjectEnvRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/environments/:envId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Environments],
+ description: "Get Environment",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ // NOTE(daniel): workspaceId isn't used, but we need to keep it for backwards compatibility. The endpoint defined below, uses no project ID, and is takes a pure environment ID.
+ workspaceId: z.string().trim().describe(ENVIRONMENTS.GET.projectId),
+ 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,
+ 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({
+ method: "GET",
+ url: "/environments/:envId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Environments],
+ description: "Get Environment by ID",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ 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,
+ 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({
+ method: "POST",
+ url: "/:workspaceId/environments",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Environments],
+ description: "Create environment",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(ENVIRONMENTS.CREATE.projectId)
+ }),
+ body: z.object({
+ name: z.string().trim().describe(ENVIRONMENTS.CREATE.name),
+ position: z.number().min(1).optional().describe(ENVIRONMENTS.CREATE.position),
+ slug: slugSchema({ max: 64 }).describe(ENVIRONMENTS.CREATE.slug)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ workspace: z.string(),
+ environment: ProjectEnvironmentsSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const environment = await server.services.projectEnv.createEnvironment({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ projectId: req.params.workspaceId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: environment.projectId,
+ event: {
+ type: EventType.CREATE_ENVIRONMENT,
+ metadata: {
+ name: environment.name,
+ slug: environment.slug
+ }
+ }
+ });
+ return {
+ message: "Successfully created new environment",
+ workspace: req.params.workspaceId,
+ environment
+ };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:workspaceId/environments/:id",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Environments],
+ description: "Update environment",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(ENVIRONMENTS.UPDATE.projectId),
+ id: z.string().trim().describe(ENVIRONMENTS.UPDATE.id)
+ }),
+ body: z.object({
+ slug: slugSchema({ max: 64 }).optional().describe(ENVIRONMENTS.UPDATE.slug),
+ name: z.string().trim().optional().describe(ENVIRONMENTS.UPDATE.name),
+ position: z.number().optional().describe(ENVIRONMENTS.UPDATE.position)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ workspace: z.string(),
+ environment: ProjectEnvironmentsSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { environment, old } = await server.services.projectEnv.updateEnvironment({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ id: req.params.id,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: environment.projectId,
+ event: {
+ type: EventType.UPDATE_ENVIRONMENT,
+ metadata: {
+ oldName: old.name,
+ oldSlug: old.slug,
+ oldPos: old.position,
+ newName: environment.name,
+ newSlug: environment.slug,
+ newPos: environment.position
+ }
+ }
+ });
+
+ return {
+ message: "Successfully updated environment",
+ workspace: req.params.workspaceId,
+ environment
+ };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:workspaceId/environments/:id",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Environments],
+ description: "Delete environment",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(ENVIRONMENTS.DELETE.projectId),
+ id: z.string().trim().describe(ENVIRONMENTS.DELETE.id)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ workspace: z.string(),
+ environment: ProjectEnvironmentsSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const environment = await server.services.projectEnv.deleteEnvironment({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ id: req.params.id
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: environment.projectId,
+ event: {
+ type: EventType.DELETE_ENVIRONMENT,
+ metadata: {
+ slug: environment.slug,
+ name: environment.name
+ }
+ }
+ });
+
+ return {
+ message: "Successfully deleted environment",
+ workspace: req.params.workspaceId,
+ environment
+ };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/deprecated-project-membership-router.ts b/backend/src/server/routes/v1/deprecated-project-membership-router.ts
new file mode 100644
index 0000000000..ab225929f5
--- /dev/null
+++ b/backend/src/server/routes/v1/deprecated-project-membership-router.ts
@@ -0,0 +1,378 @@
+import { z } from "zod";
+
+import {
+ OrgMembershipsSchema,
+ ProjectMembershipsSchema,
+ ProjectUserMembershipRolesSchema,
+ UserEncryptionKeysSchema,
+ UsersSchema
+} from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, PROJECT_USERS } from "@app/lib/api-docs";
+import { ms } from "@app/lib/ms";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { ProjectUserMembershipTemporaryMode } from "@app/services/project-membership/project-membership-types";
+
+export const registerDeprecatedProjectMembershipRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/memberships",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectUsers],
+ description: "Return project user memberships",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIPS.projectId)
+ }),
+ response: {
+ 200: z.object({
+ memberships: ProjectMembershipsSchema.extend({
+ user: UsersSchema.pick({
+ email: true,
+ firstName: true,
+ lastName: true,
+ id: true,
+ username: true
+ }).merge(UserEncryptionKeysSchema.pick({ publicKey: 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({ updatedAt: true })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const memberships = await server.services.projectMembership.getProjectMemberships({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId
+ });
+ return { memberships };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/memberships/:membershipId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ description: "Return project user membership",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.projectId),
+ membershipId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.membershipId)
+ }),
+ response: {
+ 200: z.object({
+ membership: ProjectMembershipsSchema.extend({
+ user: UsersSchema.pick({
+ email: true,
+ firstName: true,
+ lastName: true,
+ id: true,
+ username: true
+ }).merge(UserEncryptionKeysSchema.pick({ publicKey: 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({ updatedAt: true })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.projectMembership.getProjectMembershipById({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ id: req.params.membershipId
+ });
+ return { membership };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:workspaceId/memberships/details",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectUsers],
+ description: "Return project user memberships",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.projectId)
+ }),
+ body: z.object({
+ username: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.username)
+ }),
+ response: {
+ 200: z.object({
+ membership: ProjectMembershipsSchema.extend({
+ user: UsersSchema.pick({
+ email: true,
+ firstName: true,
+ lastName: true,
+ id: true
+ }).merge(UserEncryptionKeysSchema.pick({ publicKey: 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 })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.projectMembership.getProjectMembershipByUsername({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ username: req.body.username
+ });
+ return { membership };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:workspaceId/memberships",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ workspaceId: z.string().trim()
+ }),
+ body: z.object({
+ members: z
+ .object({
+ orgMembershipId: z.string().trim(),
+ workspaceEncryptedKey: z.string().trim(),
+ workspaceEncryptedNonce: z.string().trim()
+ })
+ .array()
+ .min(1)
+ }),
+ response: {
+ 200: z.object({
+ success: z.boolean(),
+ data: OrgMembershipsSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const data = await server.services.projectMembership.addUsersToProject({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ members: req.body.members
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId: req.params.workspaceId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.ADD_BATCH_PROJECT_MEMBER,
+ metadata: data.map(({ userId }) => ({
+ userId: userId || "",
+ email: ""
+ }))
+ }
+ });
+
+ return { data, success: true };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:workspaceId/memberships/:membershipId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectUsers],
+ description: "Update project user membership",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECT_USERS.UPDATE_USER_MEMBERSHIP.projectId),
+ membershipId: z.string().trim().describe(PROJECT_USERS.UPDATE_USER_MEMBERSHIP.membershipId)
+ }),
+ body: z.object({
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(false).default(false)
+ }),
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(true),
+ temporaryMode: z.nativeEnum(ProjectUserMembershipTemporaryMode),
+ temporaryRange: z.string().refine((val) => ms(val) > 0, "Temporary range must be a positive number"),
+ temporaryAccessStartTime: z.string().datetime()
+ })
+ ])
+ )
+ .min(1)
+ .refine((data) => data.some(({ isTemporary }) => !isTemporary), "At least one long lived role is required")
+ .describe(PROJECT_USERS.UPDATE_USER_MEMBERSHIP.roles)
+ }),
+ response: {
+ 200: z.object({
+ roles: ProjectUserMembershipRolesSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const roles = await server.services.projectMembership.updateProjectMembership({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ membershipId: req.params.membershipId,
+ roles: req.body.roles
+ });
+
+ // await server.services.auditLog.createAuditLog({
+ // ...req.auditLogInfo,
+ // projectId: req.params.workspaceId,
+ // event: {
+ // type: EventType.UPDATE_USER_WORKSPACE_ROLE,
+ // metadata: {
+ // userId: membership.userId,
+ // newRole: req.body.role,
+ // oldRole: membership.role,
+ // email: ""
+ // }
+ // }
+ // });
+ return { roles };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:workspaceId/memberships/:membershipId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ description: "Delete project user membership",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim(),
+ membershipId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ membership: ProjectMembershipsSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const membership = await server.services.projectMembership.deleteProjectMembership({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ membershipId: req.params.membershipId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.params.workspaceId,
+ event: {
+ type: EventType.REMOVE_PROJECT_MEMBER,
+ metadata: {
+ userId: membership.userId,
+ email: ""
+ }
+ }
+ });
+ return { membership };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/deprecated-project-router.ts b/backend/src/server/routes/v1/deprecated-project-router.ts
new file mode 100644
index 0000000000..687d95b9b2
--- /dev/null
+++ b/backend/src/server/routes/v1/deprecated-project-router.ts
@@ -0,0 +1,728 @@
+import { z } from "zod";
+
+import {
+ IntegrationsSchema,
+ ProjectRolesSchema,
+ ProjectSlackConfigsSchema,
+ ProjectSshConfigsSchema,
+ ProjectType,
+ SortDirection
+} from "@app/db/schemas";
+import { ProjectMicrosoftTeamsConfigsSchema } from "@app/db/schemas/project-microsoft-teams-configs";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, PROJECTS } from "@app/lib/api-docs";
+import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
+import { re2Validator } from "@app/lib/zod";
+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";
+import { validateMicrosoftTeamsChannelsSchema } from "@app/services/microsoft-teams/microsoft-teams-fns";
+import { ProjectFilterType, SearchProjectSortBy } from "@app/services/project/project-types";
+import { validateSlackChannelsField } from "@app/services/slack/slack-auth-validators";
+import { WorkflowIntegration } from "@app/services/workflow-integration/workflow-integration-types";
+
+import { integrationAuthPubSchema, SanitizedProjectSchema } from "../sanitizedSchemas";
+
+const projectWithEnv = SanitizedProjectSchema.merge(
+ z.object({
+ _id: z.string(),
+ environments: z.object({ name: z.string(), slug: z.string(), id: z.string() }).array()
+ })
+);
+
+export const registerDeprecatedProjectRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ querystring: z.object({
+ includeRoles: z
+ .enum(["true", "false"])
+ .default("false")
+ .transform((value) => value === "true"),
+ type: z.nativeEnum(ProjectType).optional()
+ }),
+ response: {
+ 200: z.object({
+ workspaces: projectWithEnv
+ .extend({
+ roles: ProjectRolesSchema.array().optional()
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspaces = await server.services.project.getProjects({
+ includeRoles: req.query.includeRoles,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ type: req.query.type
+ });
+ return { workspaces };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:workspaceId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Projects],
+ description: "Get project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECTS.GET.projectId)
+ }),
+ response: {
+ 200: z.object({
+ workspace: projectWithEnv.optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspace = await server.services.project.getAProject({
+ filter: {
+ type: ProjectFilterType.ID,
+ projectId: req.params.workspaceId
+ },
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId
+ });
+ return { workspace };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:workspaceId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Projects],
+ description: "Delete project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECTS.DELETE.projectId)
+ }),
+ response: {
+ 200: z.object({
+ workspace: SanitizedProjectSchema.optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspace = await server.services.project.deleteProject({
+ filter: {
+ type: ProjectFilterType.ID,
+ projectId: req.params.workspaceId
+ },
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ event: {
+ type: EventType.DELETE_PROJECT,
+ metadata: workspace
+ }
+ });
+
+ return { workspace };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:workspaceId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Projects],
+ description: "Update project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECTS.UPDATE.projectId)
+ }),
+ body: z.object({
+ name: z
+ .string()
+ .trim()
+ .max(64, { message: "Name must be 64 or fewer characters" })
+ .optional()
+ .describe(PROJECTS.UPDATE.name),
+ description: z
+ .string()
+ .trim()
+ .max(256, { message: "Description must be 256 or fewer characters" })
+ .optional()
+ .describe(PROJECTS.UPDATE.projectDescription),
+ autoCapitalization: z.boolean().optional().describe(PROJECTS.UPDATE.autoCapitalization),
+ hasDeleteProtection: z.boolean().optional().describe(PROJECTS.UPDATE.hasDeleteProtection),
+ slug: z
+ .string()
+ .trim()
+ .max(64, { message: "Slug must be 64 characters or fewer" })
+ .refine(re2Validator(/^[a-z0-9]+(?:[_-][a-z0-9]+)*$/), {
+ message:
+ "Project slug can only contain lowercase letters and numbers, with optional single hyphens (-) or underscores (_) between words. Cannot start or end with a hyphen or underscore."
+ })
+ .optional()
+ .describe(PROJECTS.UPDATE.slug),
+ secretSharing: z.boolean().optional().describe(PROJECTS.UPDATE.secretSharing),
+ showSnapshotsLegacy: z.boolean().optional().describe(PROJECTS.UPDATE.showSnapshotsLegacy),
+ defaultProduct: z.nativeEnum(ProjectType).optional().describe(PROJECTS.UPDATE.defaultProduct),
+ secretDetectionIgnoreValues: z
+ .array(z.string())
+ .optional()
+ .describe(PROJECTS.UPDATE.secretDetectionIgnoreValues)
+ }),
+ response: {
+ 200: z.object({
+ workspace: SanitizedProjectSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspace = await server.services.project.updateProject({
+ filter: {
+ type: ProjectFilterType.ID,
+ projectId: req.params.workspaceId
+ },
+ update: {
+ name: req.body.name,
+ description: req.body.description,
+ autoCapitalization: req.body.autoCapitalization,
+ defaultProduct: req.body.defaultProduct,
+ hasDeleteProtection: req.body.hasDeleteProtection,
+ slug: req.body.slug,
+ secretSharing: req.body.secretSharing,
+ showSnapshotsLegacy: req.body.showSnapshotsLegacy,
+ secretDetectionIgnoreValues: req.body.secretDetectionIgnoreValues
+ },
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ event: {
+ type: EventType.UPDATE_PROJECT,
+ metadata: req.body
+ }
+ });
+
+ return {
+ workspace
+ };
+ }
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/:workspaceSlug/audit-logs-retention",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ workspaceSlug: z.string().trim()
+ }),
+ body: z.object({
+ auditLogsRetentionDays: z.number().min(0)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ workspace: SanitizedProjectSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspace = await server.services.project.updateAuditLogsRetention({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ filter: {
+ type: ProjectFilterType.SLUG,
+ slug: req.params.workspaceSlug,
+ orgId: req.permission.orgId
+ },
+ auditLogsRetentionDays: req.body.auditLogsRetentionDays
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: workspace.id,
+ event: {
+ type: EventType.UPDATE_PROJECT,
+ metadata: req.body
+ }
+ });
+
+ return {
+ message: "Successfully updated project's audit logs retention period",
+ workspace
+ };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/integrations",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Integrations],
+ description: "List integrations for a project.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECTS.LIST_INTEGRATION.projectId)
+ }),
+ response: {
+ 200: z.object({
+ integrations: IntegrationsSchema.merge(
+ z.object({
+ environment: z.object({
+ id: z.string(),
+ name: z.string(),
+ slug: z.string()
+ })
+ })
+ ).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const integrations = await server.services.integration.listIntegrationByProject({
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId
+ });
+ return { integrations };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/authorizations",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Integrations],
+ description: "List integration auth objects for a workspace.",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ workspaceId: z.string().trim().describe(PROJECTS.LIST_INTEGRATION_AUTHORIZATION.projectId)
+ }),
+ response: {
+ 200: z.object({
+ authorizations: integrationAuthPubSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const authorizations = await server.services.integrationAuth.listIntegrationAuthByProjectId({
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId
+ });
+ return { authorizations };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/ssh-config",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ workspaceId: z.string().trim()
+ }),
+ response: {
+ 200: ProjectSshConfigsSchema.pick({
+ id: true,
+ createdAt: true,
+ updatedAt: true,
+ projectId: true,
+ defaultUserSshCaId: true,
+ defaultHostSshCaId: true
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const sshConfig = await server.services.project.getProjectSshConfig({
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: sshConfig.projectId,
+ event: {
+ type: EventType.GET_PROJECT_SSH_CONFIG,
+ metadata: {
+ id: sshConfig.id,
+ projectId: sshConfig.projectId
+ }
+ }
+ });
+
+ return sshConfig;
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:workspaceId/ssh-config",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ workspaceId: z.string().trim()
+ }),
+ body: z.object({
+ defaultUserSshCaId: z.string().optional(),
+ defaultHostSshCaId: z.string().optional()
+ }),
+ response: {
+ 200: ProjectSshConfigsSchema.pick({
+ id: true,
+ createdAt: true,
+ updatedAt: true,
+ projectId: true,
+ defaultUserSshCaId: true,
+ defaultHostSshCaId: true
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const sshConfig = await server.services.project.updateProjectSshConfig({
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: sshConfig.projectId,
+ event: {
+ type: EventType.UPDATE_PROJECT_SSH_CONFIG,
+ metadata: {
+ id: sshConfig.id,
+ projectId: sshConfig.projectId,
+ defaultUserSshCaId: sshConfig.defaultUserSshCaId,
+ defaultHostSshCaId: sshConfig.defaultHostSshCaId
+ }
+ }
+ });
+
+ return sshConfig;
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:workspaceId/workflow-integration-config/:integration",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ workspaceId: z.string().trim(),
+ integration: z.nativeEnum(WorkflowIntegration)
+ }),
+ response: {
+ 200: z.discriminatedUnion("integration", [
+ ProjectSlackConfigsSchema.pick({
+ id: true,
+ isAccessRequestNotificationEnabled: true,
+ accessRequestChannels: true,
+ isSecretRequestNotificationEnabled: true,
+ secretRequestChannels: true
+ }).merge(
+ z.object({
+ integration: z.literal(WorkflowIntegration.SLACK),
+ integrationId: z.string()
+ })
+ ),
+ ProjectMicrosoftTeamsConfigsSchema.pick({
+ id: true,
+ isAccessRequestNotificationEnabled: true,
+ accessRequestChannels: true,
+ isSecretRequestNotificationEnabled: true,
+ secretRequestChannels: true
+ }).merge(
+ z.object({
+ integration: z.literal(WorkflowIntegration.MICROSOFT_TEAMS),
+ integrationId: z.string()
+ })
+ )
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const config = await server.services.project.getProjectWorkflowIntegrationConfig({
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ integration: req.params.integration
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.params.workspaceId,
+ event: {
+ type: EventType.GET_PROJECT_WORKFLOW_INTEGRATION_CONFIG,
+ metadata: {
+ id: config.id,
+ integration: config.integration
+ }
+ }
+ });
+
+ return config;
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:projectId/workflow-integration/:integration/:integrationId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ projectId: z.string().trim(),
+ integration: z.nativeEnum(WorkflowIntegration),
+ integrationId: z.string()
+ }),
+ response: {
+ 200: z.object({
+ integrationConfig: z.object({
+ id: z.string()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const deletedIntegration = await server.services.project.deleteProjectWorkflowIntegration({
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ integration: req.params.integration,
+ integrationId: req.params.integrationId
+ });
+
+ return {
+ integrationConfig: deletedIntegration
+ };
+ }
+ });
+
+ server.route({
+ method: "PUT",
+ url: "/:workspaceId/workflow-integration",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ workspaceId: z.string().trim()
+ }),
+
+ body: z.discriminatedUnion("integration", [
+ z.object({
+ integration: z.literal(WorkflowIntegration.SLACK),
+ integrationId: z.string(),
+ accessRequestChannels: validateSlackChannelsField,
+ secretRequestChannels: validateSlackChannelsField,
+ isAccessRequestNotificationEnabled: z.boolean(),
+ isSecretRequestNotificationEnabled: z.boolean()
+ }),
+ z.object({
+ integration: z.literal(WorkflowIntegration.MICROSOFT_TEAMS),
+ integrationId: z.string(),
+ accessRequestChannels: validateMicrosoftTeamsChannelsSchema,
+ secretRequestChannels: validateMicrosoftTeamsChannelsSchema,
+ isAccessRequestNotificationEnabled: z.boolean(),
+ isSecretRequestNotificationEnabled: z.boolean()
+ })
+ ]),
+ response: {
+ 200: z.discriminatedUnion("integration", [
+ ProjectSlackConfigsSchema.pick({
+ id: true,
+ isAccessRequestNotificationEnabled: true,
+ accessRequestChannels: true,
+ isSecretRequestNotificationEnabled: true,
+ secretRequestChannels: true
+ }).merge(
+ z.object({
+ integration: z.literal(WorkflowIntegration.SLACK),
+ integrationId: z.string()
+ })
+ ),
+ ProjectMicrosoftTeamsConfigsSchema.pick({
+ id: true,
+ isAccessRequestNotificationEnabled: true,
+ isSecretRequestNotificationEnabled: true
+ }).merge(
+ z.object({
+ integration: z.literal(WorkflowIntegration.MICROSOFT_TEAMS),
+ integrationId: z.string(),
+ accessRequestChannels: validateMicrosoftTeamsChannelsSchema,
+ secretRequestChannels: validateMicrosoftTeamsChannelsSchema
+ })
+ )
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workflowIntegrationConfig = await server.services.project.updateProjectWorkflowIntegration({
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.workspaceId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.params.workspaceId,
+ event: {
+ type: EventType.UPDATE_PROJECT_WORKFLOW_INTEGRATION_CONFIG,
+ metadata: {
+ id: workflowIntegrationConfig.id,
+ integrationId: workflowIntegrationConfig.integrationId,
+ integration: workflowIntegrationConfig.integration,
+ isAccessRequestNotificationEnabled: workflowIntegrationConfig.isAccessRequestNotificationEnabled,
+ accessRequestChannels: workflowIntegrationConfig.accessRequestChannels,
+ isSecretRequestNotificationEnabled: workflowIntegrationConfig.isSecretRequestNotificationEnabled,
+ secretRequestChannels: workflowIntegrationConfig.secretRequestChannels
+ }
+ }
+ });
+
+ return workflowIntegrationConfig;
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/search",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ body: z.object({
+ limit: z.number().default(100),
+ offset: z.number().default(0),
+ type: z.nativeEnum(ProjectType).optional(),
+ orderBy: z.nativeEnum(SearchProjectSortBy).optional().default(SearchProjectSortBy.NAME),
+ orderDirection: z.nativeEnum(SortDirection).optional().default(SortDirection.ASC),
+ name: z
+ .string()
+ .trim()
+ .refine((val) => characterValidator([CharacterType.AlphaNumeric, CharacterType.Hyphen])(val), {
+ message: "Invalid pattern: only alphanumeric characters, - are allowed."
+ })
+ .optional()
+ }),
+ response: {
+ 200: z.object({
+ projects: SanitizedProjectSchema.extend({ isMember: z.boolean() }).array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { docs: projects, totalCount } = await server.services.project.searchProjects({
+ permission: req.permission,
+ ...req.body
+ });
+
+ return { projects, totalCount };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/deprecated-secret-folder-router.ts b/backend/src/server/routes/v1/deprecated-secret-folder-router.ts
new file mode 100644
index 0000000000..ecb955025c
--- /dev/null
+++ b/backend/src/server/routes/v1/deprecated-secret-folder-router.ts
@@ -0,0 +1,444 @@
+import { z } from "zod";
+
+import { SecretFoldersSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, FOLDERS } from "@app/lib/api-docs";
+import { prefixWithSlash, removeTrailingSlash } from "@app/lib/fn";
+import { isValidFolderName } from "@app/lib/validator";
+import { readLimit, secretsLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { booleanSchema } from "../sanitizedSchemas";
+
+export const registerDeprecatedSecretFolderRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ url: "/",
+ method: "POST",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ description: "Create folders",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ workspaceId: z.string().trim().describe(FOLDERS.CREATE.projectId),
+ environment: z.string().trim().describe(FOLDERS.CREATE.environment),
+ name: z
+ .string()
+ .trim()
+ .describe(FOLDERS.CREATE.name)
+ .refine((name) => isValidFolderName(name), {
+ message: "Invalid folder name. Only alphanumeric characters, dashes, and underscores are allowed."
+ }),
+ path: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(prefixWithSlash) // Transformations get skipped if path is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.CREATE.path)
+ .optional(),
+ // backward compatibility with cli
+ directory: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.CREATE.directory)
+ .optional(),
+ description: z.string().optional().nullable().describe(FOLDERS.CREATE.description)
+ }),
+ response: {
+ 200: z.object({
+ folder: SecretFoldersSchema.extend({
+ path: z.string()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const path = req.body.path || req.body.directory || "/";
+ const folder = await server.services.folder.createFolder({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body,
+ projectId: req.body.workspaceId,
+ path,
+ description: req.body.description
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.workspaceId,
+ event: {
+ type: EventType.CREATE_FOLDER,
+ metadata: {
+ environment: req.body.environment,
+ folderId: folder.id,
+ folderName: folder.name,
+ folderPath: path,
+ ...(req.body.description ? { description: req.body.description } : {})
+ }
+ }
+ });
+ return { folder };
+ }
+ });
+
+ server.route({
+ url: "/:folderId",
+ method: "PATCH",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ description: "Update folder",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ // old way this was name
+ folderId: z.string().describe(FOLDERS.UPDATE.folderId)
+ }),
+ body: z.object({
+ workspaceId: z.string().trim().describe(FOLDERS.UPDATE.projectId),
+ environment: z.string().trim().describe(FOLDERS.UPDATE.environment),
+ name: z
+ .string()
+ .trim()
+ .describe(FOLDERS.UPDATE.name)
+ .refine((name) => isValidFolderName(name), {
+ message: "Invalid folder name. Only alphanumeric characters, dashes, and underscores are allowed."
+ }),
+ path: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(prefixWithSlash) // Transformations get skipped if path is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.UPDATE.path)
+ .optional(),
+ // backward compatibility with cli
+ directory: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.UPDATE.directory)
+ .optional(),
+ description: z.string().optional().nullable().describe(FOLDERS.UPDATE.description)
+ }),
+ response: {
+ 200: z.object({
+ folder: SecretFoldersSchema.extend({
+ path: z.string()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const path = req.body.path || req.body.directory || "/";
+ const { folder, old } = await server.services.folder.updateFolder({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body,
+ projectId: req.body.workspaceId,
+ id: req.params.folderId,
+ path
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.workspaceId,
+ event: {
+ type: EventType.UPDATE_FOLDER,
+ metadata: {
+ environment: req.body.environment,
+ folderId: folder.id,
+ folderPath: path,
+ newFolderName: folder.name,
+ oldFolderName: old.name
+ }
+ }
+ });
+ return { folder };
+ }
+ });
+
+ server.route({
+ url: "/batch",
+ method: "PATCH",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ description: "Update folders by batch",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectSlug: z.string().trim().describe(FOLDERS.UPDATE.projectSlug),
+ folders: z
+ .object({
+ id: z.string().describe(FOLDERS.UPDATE.folderId),
+ environment: z.string().trim().describe(FOLDERS.UPDATE.environment),
+ name: z
+ .string()
+ .trim()
+ .describe(FOLDERS.UPDATE.name)
+ .refine((name) => isValidFolderName(name), {
+ message: "Invalid folder name. Only alphanumeric characters, dashes, and underscores are allowed."
+ }),
+ path: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(prefixWithSlash)
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.UPDATE.path),
+ description: z.string().optional().nullable().describe(FOLDERS.UPDATE.description)
+ })
+ .array()
+ .min(1)
+ }),
+ response: {
+ 200: z.object({
+ folders: SecretFoldersSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { newFolders, oldFolders, projectId } = await server.services.folder.updateManyFolders({
+ ...req.body,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await Promise.all(
+ req.body.folders.map(async (folder, index) => {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId,
+ event: {
+ type: EventType.UPDATE_FOLDER,
+ metadata: {
+ environment: oldFolders[index].envId,
+ folderId: oldFolders[index].id,
+ folderPath: folder.path,
+ newFolderName: newFolders[index].name,
+ oldFolderName: oldFolders[index].name
+ }
+ }
+ });
+ })
+ );
+
+ return { folders: newFolders };
+ }
+ });
+
+ // TODO(daniel): Expose this route in api reference and write docs for it.
+ server.route({
+ method: "DELETE",
+ url: "/:folderIdOrName",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ description: "Delete a folder",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ folderIdOrName: z.string().describe(FOLDERS.DELETE.folderIdOrName)
+ }),
+ body: z.object({
+ workspaceId: z.string().trim().describe(FOLDERS.DELETE.projectId),
+ environment: z.string().trim().describe(FOLDERS.DELETE.environment),
+ path: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(prefixWithSlash) // Transformations get skipped if path is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.DELETE.path)
+ .optional(),
+ // keep this here as cli need directory
+ directory: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.DELETE.directory)
+ .optional()
+ }),
+ response: {
+ 200: z.object({
+ folder: SecretFoldersSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const path = req.body.path || req.body.directory || "/";
+ const folder = await server.services.folder.deleteFolder({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body,
+ projectId: req.body.workspaceId,
+ idOrName: req.params.folderIdOrName,
+ path
+ });
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.workspaceId,
+ event: {
+ type: EventType.DELETE_FOLDER,
+ metadata: {
+ environment: req.body.environment,
+ folderId: folder.id,
+ folderPath: path,
+ folderName: folder.name
+ }
+ }
+ });
+ return { folder };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ description: "Get folders",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ querystring: z.object({
+ workspaceId: z.string().trim().describe(FOLDERS.LIST.projectId),
+ environment: z.string().trim().describe(FOLDERS.LIST.environment),
+ lastSecretModified: z.string().datetime().trim().optional().describe(FOLDERS.LIST.lastSecretModified),
+ path: z
+ .string()
+ .trim()
+ .transform(prefixWithSlash) // Transformations get skipped if path is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.LIST.path)
+ .optional(),
+ // backward compatibility with cli
+ directory: z
+ .string()
+ .trim()
+ .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
+ .transform(removeTrailingSlash)
+ .describe(FOLDERS.LIST.directory)
+ .optional(),
+ recursive: booleanSchema.default(false).describe(FOLDERS.LIST.recursive)
+ }),
+ response: {
+ 200: z.object({
+ folders: SecretFoldersSchema.extend({
+ relativePath: z.string().optional()
+ }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const path = req.query.path || req.query.directory || "/";
+ const folders = await server.services.folder.getFolders({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.query,
+ projectId: req.query.workspaceId,
+ path
+ });
+ return { folders };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:id",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ 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.extend({
+ environment: z.object({
+ envId: z.string(),
+ envName: z.string(),
+ envSlug: z.string()
+ }),
+ path: z.string(),
+ projectId: z.string()
+ })
+ })
+ }
+ },
+ 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 };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/deprecated-secret-import-router.ts b/backend/src/server/routes/v1/deprecated-secret-import-router.ts
new file mode 100644
index 0000000000..2fdbe42163
--- /dev/null
+++ b/backend/src/server/routes/v1/deprecated-secret-import-router.ts
@@ -0,0 +1,472 @@
+import { z } from "zod";
+
+import { SecretImportsSchema, SecretsSchema } from "@app/db/schemas";
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, SECRET_IMPORTS } from "@app/lib/api-docs";
+import { removeTrailingSlash } from "@app/lib/fn";
+import { readLimit, secretsLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+import { secretRawSchema } from "../sanitizedSchemas";
+
+export const registerDeprecatedSecretImportRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SecretImports],
+ description: "Create secret imports",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ workspaceId: z.string().trim().describe(SECRET_IMPORTS.CREATE.projectId),
+ environment: z.string().trim().describe(SECRET_IMPORTS.CREATE.environment),
+ path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.CREATE.path),
+ import: z.object({
+ environment: z.string().trim().describe(SECRET_IMPORTS.CREATE.import.environment),
+ path: z.string().trim().transform(removeTrailingSlash).describe(SECRET_IMPORTS.CREATE.import.path)
+ }),
+ isReplication: z.boolean().default(false).describe(SECRET_IMPORTS.CREATE.isReplication)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ secretImport: SecretImportsSchema.omit({ importEnv: true }).merge(
+ z.object({
+ importEnv: z.object({ name: z.string(), slug: z.string(), id: z.string() })
+ })
+ )
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretImport = await server.services.secretImport.createImport({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body,
+ projectId: req.body.workspaceId,
+ data: req.body.import
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.workspaceId,
+ event: {
+ type: EventType.CREATE_SECRET_IMPORT,
+ metadata: {
+ secretImportId: secretImport.id,
+ folderId: secretImport.folderId,
+ importFromSecretPath: secretImport.importPath,
+ importFromEnvironment: secretImport.importEnv.slug,
+ importToEnvironment: req.body.environment,
+ importToSecretPath: req.body.path
+ }
+ }
+ });
+ return { message: "Successfully created secret import", secretImport };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:secretImportId",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SecretImports],
+ description: "Update secret imports",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretImportId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.secretImportId)
+ }),
+ body: z.object({
+ workspaceId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.projectId),
+ environment: z.string().trim().describe(SECRET_IMPORTS.UPDATE.environment),
+ path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.UPDATE.path),
+ import: z.object({
+ environment: z.string().trim().optional().describe(SECRET_IMPORTS.UPDATE.import.environment),
+ path: z
+ .string()
+ .trim()
+ .optional()
+ .transform((val) => (val ? removeTrailingSlash(val) : val))
+ .describe(SECRET_IMPORTS.UPDATE.import.path),
+ position: z.number().optional().describe(SECRET_IMPORTS.UPDATE.import.position)
+ })
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ secretImport: SecretImportsSchema.omit({ importEnv: true }).merge(
+ z.object({
+ importEnv: z.object({ name: z.string(), slug: z.string(), id: z.string() })
+ })
+ )
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretImport = await server.services.secretImport.updateImport({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ id: req.params.secretImportId,
+ ...req.body,
+ projectId: req.body.workspaceId,
+ data: req.body.import
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.workspaceId,
+ event: {
+ type: EventType.UPDATE_SECRET_IMPORT,
+ metadata: {
+ secretImportId: secretImport.id,
+ folderId: secretImport.folderId,
+ position: secretImport.position,
+ importToEnvironment: req.body.environment,
+ importToSecretPath: req.body.path
+ }
+ }
+ });
+
+ return { message: "Successfully updated secret import", secretImport };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:secretImportId",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SecretImports],
+ description: "Delete secret imports",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretImportId: z.string().trim().describe(SECRET_IMPORTS.DELETE.secretImportId)
+ }),
+ body: z.object({
+ workspaceId: z.string().trim().describe(SECRET_IMPORTS.DELETE.projectId),
+ environment: z.string().trim().describe(SECRET_IMPORTS.DELETE.environment),
+ path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.DELETE.path)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ secretImport: SecretImportsSchema.omit({ importEnv: true }).merge(
+ z.object({
+ importEnv: z.object({ name: z.string(), slug: z.string(), id: z.string() })
+ })
+ )
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretImport = await server.services.secretImport.deleteImport({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ id: req.params.secretImportId,
+ ...req.body,
+ projectId: req.body.workspaceId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.body.workspaceId,
+ event: {
+ type: EventType.DELETE_SECRET_IMPORT,
+ metadata: {
+ secretImportId: secretImport.id,
+ folderId: secretImport.folderId,
+ importFromEnvironment: secretImport.importEnv.slug,
+ importFromSecretPath: secretImport.importPath,
+ importToEnvironment: req.body.environment,
+ importToSecretPath: req.body.path
+ }
+ }
+ });
+ return { message: "Successfully deleted secret import", secretImport };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:secretImportId/replication-resync",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ description: "Resync secret replication of secret imports",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretImportId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.secretImportId)
+ }),
+ body: z.object({
+ workspaceId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.projectId),
+ environment: z.string().trim().describe(SECRET_IMPORTS.UPDATE.environment),
+ path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.UPDATE.path)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { message } = await server.services.secretImport.resyncSecretImportReplication({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ id: req.params.secretImportId,
+ ...req.body,
+ projectId: req.body.workspaceId
+ });
+
+ return { message };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SecretImports],
+ description: "Get secret imports",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ querystring: z.object({
+ workspaceId: z.string().trim().describe(SECRET_IMPORTS.LIST.projectId),
+ environment: z.string().trim().describe(SECRET_IMPORTS.LIST.environment),
+ path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.LIST.path)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string(),
+ secretImports: SecretImportsSchema.omit({ importEnv: true })
+ .extend({
+ importEnv: z.object({ name: z.string(), slug: z.string(), id: z.string() })
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretImports = await server.services.secretImport.getImports({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.query,
+ projectId: req.query.workspaceId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.query.workspaceId,
+ event: {
+ type: EventType.GET_SECRET_IMPORTS,
+ metadata: {
+ environment: req.query.environment,
+ folderId: secretImports?.[0]?.folderId,
+ numberOfImports: secretImports.length
+ }
+ }
+ });
+ return { message: "Successfully fetched secret imports", secretImports };
+ }
+ });
+
+ server.route({
+ url: "/:secretImportId",
+ method: "GET",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SecretImports],
+ description: "Get single secret import",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretImportId: z.string().trim().describe(SECRET_IMPORTS.GET.secretImportId)
+ }),
+ response: {
+ 200: z.object({
+ secretImport: SecretImportsSchema.omit({ importEnv: true }).extend({
+ environment: z.object({
+ id: z.string(),
+ name: z.string(),
+ slug: z.string()
+ }),
+ projectId: z.string(),
+ importEnv: z.object({ name: z.string(), slug: z.string(), id: z.string() }),
+ secretPath: z.string()
+ })
+ })
+ }
+ },
+
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretImport = await server.services.secretImport.getImportById({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ id: req.params.secretImportId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: secretImport.projectId,
+ event: {
+ type: EventType.GET_SECRET_IMPORT,
+ metadata: {
+ secretImportId: secretImport.id,
+ folderId: secretImport.folderId
+ }
+ }
+ });
+
+ return { secretImport };
+ }
+ });
+
+ server.route({
+ url: "/secrets",
+ method: "GET",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ querystring: z.object({
+ workspaceId: z.string().trim(),
+ environment: z.string().trim(),
+ path: z.string().trim().default("/").transform(removeTrailingSlash)
+ }),
+ response: {
+ 200: z.object({
+ secrets: z
+ .object({
+ secretPath: z.string(),
+ environment: z.string(),
+ environmentInfo: z.object({
+ id: z.string(),
+ name: z.string(),
+ slug: z.string()
+ }),
+ folderId: z.string().optional(),
+ secrets: SecretsSchema.omit({ secretBlindIndex: true }).array()
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const importedSecrets = await server.services.secretImport.getSecretsFromImports({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.query,
+ projectId: req.query.workspaceId
+ });
+ return { secrets: importedSecrets };
+ }
+ });
+
+ server.route({
+ url: "/secrets/raw",
+ method: "GET",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SecretImports],
+ querystring: z.object({
+ workspaceId: z.string().trim(),
+ environment: z.string().trim(),
+ path: z.string().trim().default("/").transform(removeTrailingSlash)
+ }),
+ response: {
+ 200: z.object({
+ secrets: z
+ .object({
+ secretPath: z.string(),
+ environment: z.string(),
+ environmentInfo: z.object({
+ id: z.string(),
+ name: z.string(),
+ slug: z.string()
+ }),
+ folderId: z.string().optional(),
+ secrets: secretRawSchema.array()
+ })
+ .array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const importedSecrets = await server.services.secretImport.getRawSecretsFromImports({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.query,
+ projectId: req.query.workspaceId
+ });
+ return { secrets: importedSecrets };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v1/deprecated-secret-tag-router.ts b/backend/src/server/routes/v1/deprecated-secret-tag-router.ts
new file mode 100644
index 0000000000..d90475408d
--- /dev/null
+++ b/backend/src/server/routes/v1/deprecated-secret-tag-router.ts
@@ -0,0 +1,213 @@
+import { z } from "zod";
+
+import { SecretTagsSchema } from "@app/db/schemas";
+import { ApiDocsTags, SECRET_TAGS } from "@app/lib/api-docs";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { slugSchema } from "@app/server/lib/schemas";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+
+export const registerDeprecatedSecretTagRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/:projectId/tags",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ params: z.object({
+ projectId: z.string().trim().describe(SECRET_TAGS.LIST.projectId)
+ }),
+ response: {
+ 200: z.object({
+ workspaceTags: SecretTagsSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspaceTags = await server.services.secretTag.getProjectTags({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId
+ });
+ return { workspaceTags };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/tags/:tagId",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ params: z.object({
+ projectId: z.string().trim().describe(SECRET_TAGS.GET_TAG_BY_ID.projectId),
+ tagId: z.string().trim().describe(SECRET_TAGS.GET_TAG_BY_ID.tagId)
+ }),
+ response: {
+ 200: z.object({
+ // akhilmhdh: for terraform backward compatiability
+ workspaceTag: SecretTagsSchema.extend({ name: z.string() })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspaceTag = await server.services.secretTag.getTagById({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ id: req.params.tagId
+ });
+ return { workspaceTag };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/tags/slug/:tagSlug",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ params: z.object({
+ projectId: z.string().trim().describe(SECRET_TAGS.GET_TAG_BY_SLUG.projectId),
+ tagSlug: z.string().trim().describe(SECRET_TAGS.GET_TAG_BY_SLUG.tagSlug)
+ }),
+ response: {
+ 200: z.object({
+ // akhilmhdh: for terraform backward compatiability
+ workspaceTag: SecretTagsSchema.extend({ name: z.string() })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspaceTag = await server.services.secretTag.getTagBySlug({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ slug: req.params.tagSlug,
+ projectId: req.params.projectId
+ });
+ return { workspaceTag };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:projectId/tags",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ params: z.object({
+ projectId: z.string().trim().describe(SECRET_TAGS.CREATE.projectId)
+ }),
+ body: z.object({
+ slug: slugSchema({ max: 64 }).describe(SECRET_TAGS.CREATE.slug),
+ color: z.string().trim().describe(SECRET_TAGS.CREATE.color)
+ }),
+ response: {
+ 200: z.object({
+ workspaceTag: SecretTagsSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspaceTag = await server.services.secretTag.createTag({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ ...req.body
+ });
+ return { workspaceTag };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:projectId/tags/:tagId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ params: z.object({
+ projectId: z.string().trim().describe(SECRET_TAGS.UPDATE.projectId),
+ tagId: z.string().trim().describe(SECRET_TAGS.UPDATE.tagId)
+ }),
+ body: z.object({
+ slug: slugSchema({ max: 64 }).describe(SECRET_TAGS.UPDATE.slug),
+ color: z.string().trim().describe(SECRET_TAGS.UPDATE.color)
+ }),
+ response: {
+ 200: z.object({
+ workspaceTag: SecretTagsSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspaceTag = await server.services.secretTag.updateTag({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body,
+ id: req.params.tagId
+ });
+ return { workspaceTag };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:projectId/tags/:tagId",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Folders],
+ params: z.object({
+ projectId: z.string().trim().describe(SECRET_TAGS.DELETE.projectId),
+ tagId: z.string().trim().describe(SECRET_TAGS.DELETE.tagId)
+ }),
+ response: {
+ 200: z.object({
+ workspaceTag: SecretTagsSchema
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const workspaceTag = await server.services.secretTag.deleteTag({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ id: req.params.tagId
+ });
+ return { workspaceTag };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v2/group-project-router.ts b/backend/src/server/routes/v1/group-project-router.ts
similarity index 100%
rename from backend/src/server/routes/v2/group-project-router.ts
rename to backend/src/server/routes/v1/group-project-router.ts
diff --git a/backend/src/server/routes/v1/identity-ldap-auth-router.ts b/backend/src/server/routes/v1/identity-ldap-auth-router.ts
index 5d3612bf51..512f253e08 100644
--- a/backend/src/server/routes/v1/identity-ldap-auth-router.ts
+++ b/backend/src/server/routes/v1/identity-ldap-auth-router.ts
@@ -8,7 +8,7 @@
import { Authenticator } from "@fastify/passport";
import fastifySession from "@fastify/session";
-import { FastifyRequest } from "fastify";
+import { FastifyReply, FastifyRequest } from "fastify";
import { IncomingMessage } from "http";
import LdapStrategy from "passport-ldapauth";
import { z } from "zod";
@@ -135,19 +135,26 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
})
}
},
- preValidation: passport.authenticate("ldapauth", {
- failWithError: true,
- session: false
- }) as any,
-
- errorHandler: (error) => {
- if (error.name === "AuthenticationError") {
- throw new UnauthorizedError({ message: "Invalid credentials" });
+ preValidation: [
+ (req, res) => {
+ const passportAuth = (request: FastifyRequest, reply: FastifyReply) =>
+ (
+ passport.authenticate("ldapauth", {
+ failWithError: true,
+ session: false
+ }) as any
+ )(request, reply);
+
+ const { identityId, username } = req.body;
+ return server.services.identityLdapAuth.withLdapLockout(
+ {
+ identityId,
+ username
+ },
+ () => passportAuth(req, res)
+ );
}
-
- throw error;
- },
-
+ ],
handler: async (req) => {
if (!req.passportMachineIdentity?.identityId) {
throw new UnauthorizedError({ message: "Invalid request. Missing identity ID or LDAP entry details." });
@@ -241,7 +248,21 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
.int()
.min(0)
.default(0)
- .describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit)
+ .describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit),
+ lockoutEnabled: z.boolean().default(true).describe(LDAP_AUTH.ATTACH.lockoutEnabled),
+ lockoutThreshold: z.number().min(1).max(30).default(3).describe(LDAP_AUTH.ATTACH.lockoutThreshold),
+ lockoutDurationSeconds: z
+ .number()
+ .min(30)
+ .max(86400)
+ .default(300)
+ .describe(LDAP_AUTH.ATTACH.lockoutDurationSeconds),
+ lockoutCounterResetSeconds: z
+ .number()
+ .min(5)
+ .max(3600)
+ .default(30)
+ .describe(LDAP_AUTH.ATTACH.lockoutCounterResetSeconds)
})
.refine(
(val) => val.accessTokenTTL <= val.accessTokenMaxTTL,
@@ -291,7 +312,21 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
.int()
.min(0)
.default(0)
- .describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit)
+ .describe(LDAP_AUTH.ATTACH.accessTokenNumUsesLimit),
+ lockoutEnabled: z.boolean().default(true).describe(LDAP_AUTH.ATTACH.lockoutEnabled),
+ lockoutThreshold: z.number().min(1).max(30).default(3).describe(LDAP_AUTH.ATTACH.lockoutThreshold),
+ lockoutDurationSeconds: z
+ .number()
+ .min(30)
+ .max(86400)
+ .default(300)
+ .describe(LDAP_AUTH.ATTACH.lockoutDurationSeconds),
+ lockoutCounterResetSeconds: z
+ .number()
+ .min(5)
+ .max(3600)
+ .default(30)
+ .describe(LDAP_AUTH.ATTACH.lockoutCounterResetSeconds)
})
.refine(
(val) => val.accessTokenTTL <= val.accessTokenMaxTTL,
@@ -331,7 +366,11 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
accessTokenTTL: identityLdapAuth.accessTokenTTL,
accessTokenNumUsesLimit: identityLdapAuth.accessTokenNumUsesLimit,
allowedFields: req.body.allowedFields,
- templateId: identityLdapAuth.templateId
+ templateId: identityLdapAuth.templateId,
+ lockoutEnabled: identityLdapAuth.lockoutEnabled,
+ lockoutThreshold: identityLdapAuth.lockoutThreshold,
+ lockoutDurationSeconds: identityLdapAuth.lockoutDurationSeconds,
+ lockoutCounterResetSeconds: identityLdapAuth.lockoutCounterResetSeconds
}
}
});
@@ -395,7 +434,21 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
.max(315360000)
.min(0)
.optional()
- .describe(LDAP_AUTH.UPDATE.accessTokenMaxTTL)
+ .describe(LDAP_AUTH.UPDATE.accessTokenMaxTTL),
+ lockoutEnabled: z.boolean().optional().describe(LDAP_AUTH.UPDATE.lockoutEnabled),
+ lockoutThreshold: z.number().min(1).max(30).optional().describe(LDAP_AUTH.UPDATE.lockoutThreshold),
+ lockoutDurationSeconds: z
+ .number()
+ .min(30)
+ .max(86400)
+ .optional()
+ .describe(LDAP_AUTH.UPDATE.lockoutDurationSeconds),
+ lockoutCounterResetSeconds: z
+ .number()
+ .min(5)
+ .max(3600)
+ .optional()
+ .describe(LDAP_AUTH.UPDATE.lockoutCounterResetSeconds)
})
.refine(
(val) => (val.accessTokenMaxTTL && val.accessTokenTTL ? val.accessTokenTTL <= val.accessTokenMaxTTL : true),
@@ -434,7 +487,11 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
accessTokenNumUsesLimit: identityLdapAuth.accessTokenNumUsesLimit,
accessTokenTrustedIps: identityLdapAuth.accessTokenTrustedIps as TIdentityTrustedIp[],
allowedFields: req.body.allowedFields,
- templateId: identityLdapAuth.templateId
+ templateId: identityLdapAuth.templateId,
+ lockoutEnabled: identityLdapAuth.lockoutEnabled,
+ lockoutThreshold: identityLdapAuth.lockoutThreshold,
+ lockoutDurationSeconds: identityLdapAuth.lockoutDurationSeconds,
+ lockoutCounterResetSeconds: identityLdapAuth.lockoutCounterResetSeconds
}
}
});
@@ -553,4 +610,53 @@ export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider)
return { identityLdapAuth };
}
});
+
+ server.route({
+ method: "POST",
+ url: "/ldap-auth/identities/:identityId/clear-lockouts",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.LdapAuth],
+ description: "Clear LDAP Auth Lockouts for identity",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ identityId: z.string().describe(LDAP_AUTH.CLEAR_CLIENT_LOCKOUTS.identityId)
+ }),
+ response: {
+ 200: z.object({
+ deleted: z.number()
+ })
+ }
+ },
+ handler: async (req) => {
+ const clearLockoutsData = await server.services.identityLdapAuth.clearLdapAuthLockouts({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ identityId: req.params.identityId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: clearLockoutsData.orgId,
+ event: {
+ type: EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS,
+ metadata: {
+ identityId: clearLockoutsData.identityId
+ }
+ }
+ });
+
+ return clearLockoutsData;
+ }
+ });
};
diff --git a/backend/src/server/routes/v2/identity-project-router.ts b/backend/src/server/routes/v1/identity-project-router.ts
similarity index 100%
rename from backend/src/server/routes/v2/identity-project-router.ts
rename to backend/src/server/routes/v1/identity-project-router.ts
diff --git a/backend/src/server/routes/v1/index.ts b/backend/src/server/routes/v1/index.ts
index 6108be32bf..4fb07aeacd 100644
--- a/backend/src/server/routes/v1/index.ts
+++ b/backend/src/server/routes/v1/index.ts
@@ -13,8 +13,15 @@ import { registerCaRouter } from "./certificate-authority-router";
import { CERTIFICATE_AUTHORITY_REGISTER_ROUTER_MAP } from "./certificate-authority-routers";
import { registerCertRouter } from "./certificate-router";
import { registerCertificateTemplateRouter } from "./certificate-template-router";
+import { registerDeprecatedProjectEnvRouter } from "./deprecated-project-env-router";
+import { registerDeprecatedProjectMembershipRouter } from "./deprecated-project-membership-router";
+import { registerDeprecatedProjectRouter } from "./deprecated-project-router";
+import { registerDeprecatedSecretFolderRouter } from "./deprecated-secret-folder-router";
+import { registerDeprecatedSecretImportRouter } from "./deprecated-secret-import-router";
+import { registerDeprecatedSecretTagRouter } from "./deprecated-secret-tag-router";
import { registerEventRouter } from "./event-router";
import { registerExternalGroupOrgRoleMappingRouter } from "./external-group-org-role-mapping-router";
+import { registerGroupProjectRouter } from "./group-project-router";
import { registerIdentityAccessTokenRouter } from "./identity-access-token-router";
import { registerIdentityAliCloudAuthRouter } from "./identity-alicloud-auth-router";
import { registerIdentityAwsAuthRouter } from "./identity-aws-iam-auth-router";
@@ -25,6 +32,7 @@ import { registerIdentityKubernetesRouter } from "./identity-kubernetes-auth-rou
import { registerIdentityLdapAuthRouter } from "./identity-ldap-auth-router";
import { registerIdentityOciAuthRouter } from "./identity-oci-auth-router";
import { registerIdentityOidcAuthRouter } from "./identity-oidc-auth-router";
+import { registerIdentityProjectRouter } from "./identity-project-router";
import { registerIdentityRouter } from "./identity-router";
import { registerIdentityTlsCertAuthRouter } from "./identity-tls-cert-auth-router";
import { registerIdentityTokenAuthRouter } from "./identity-token-auth-router";
@@ -45,8 +53,6 @@ import { registerProjectKeyRouter } from "./project-key-router";
import { registerProjectMembershipRouter } from "./project-membership-router";
import { registerProjectRouter } from "./project-router";
import { SECRET_REMINDER_REGISTER_ROUTER_MAP } from "./reminder-routers";
-import { registerSecretFolderRouter } from "./secret-folder-router";
-import { registerSecretImportRouter } from "./secret-import-router";
import { registerSecretRequestsRouter } from "./secret-requests-router";
import { registerSecretSharingRouter } from "./secret-sharing-router";
import { registerSecretTagRouter } from "./secret-tag-router";
@@ -87,8 +93,8 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await server.register(registerNotificationRouter, { prefix: "/notifications" });
await server.register(registerInviteOrgRouter, { prefix: "/invite-org" });
await server.register(registerUserActionRouter, { prefix: "/user-action" });
- await server.register(registerSecretImportRouter, { prefix: "/secret-imports" });
- await server.register(registerSecretFolderRouter, { prefix: "/folders" });
+ await server.register(registerDeprecatedSecretImportRouter, { prefix: "/secret-imports" });
+ await server.register(registerDeprecatedSecretFolderRouter, { prefix: "/folders" });
await server.register(
async (workflowIntegrationRouter) => {
@@ -101,13 +107,26 @@ export const registerV1Routes = async (server: FastifyZodProvider) => {
await server.register(
async (projectRouter) => {
- await projectRouter.register(registerProjectRouter);
- await projectRouter.register(registerProjectEnvRouter);
+ await projectRouter.register(registerDeprecatedProjectRouter);
+ await projectRouter.register(registerDeprecatedProjectEnvRouter);
+ // depreciated completed in use
await projectRouter.register(registerProjectKeyRouter);
+ await projectRouter.register(registerDeprecatedProjectMembershipRouter);
+ await projectRouter.register(registerDeprecatedSecretTagRouter);
+ },
+ { prefix: "/workspace" }
+ );
+
+ await server.register(
+ async (projectRouter) => {
+ await projectRouter.register(registerProjectRouter);
await projectRouter.register(registerProjectMembershipRouter);
+ await projectRouter.register(registerProjectEnvRouter);
await projectRouter.register(registerSecretTagRouter);
+ await projectRouter.register(registerGroupProjectRouter);
+ await projectRouter.register(registerIdentityProjectRouter);
},
- { prefix: "/workspace" }
+ { prefix: "/projects" }
);
await server.register(
diff --git a/backend/src/server/routes/v1/notification-router.ts b/backend/src/server/routes/v1/notification-router.ts
index 5f72b88d62..955a1174ea 100644
--- a/backend/src/server/routes/v1/notification-router.ts
+++ b/backend/src/server/routes/v1/notification-router.ts
@@ -3,8 +3,10 @@ import { z } from "zod";
import { UserNotificationsSchema } from "@app/db/schemas/user-notifications";
import { UnauthorizedError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
export const registerNotificationRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -97,6 +99,16 @@ export const registerNotificationRouter = async (server: FastifyZodProvider) =>
...req.body
});
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.NotificationUpdated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ notificationId: req.params.notificationId,
+ ...req.body
+ }
+ });
+
return { notification };
}
});
diff --git a/backend/src/server/routes/v1/project-env-router.ts b/backend/src/server/routes/v1/project-env-router.ts
index 9a136e1608..81b828b552 100644
--- a/backend/src/server/routes/v1/project-env-router.ts
+++ b/backend/src/server/routes/v1/project-env-router.ts
@@ -11,58 +11,7 @@ import { AuthMode } from "@app/services/auth/auth-type";
export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/environments/:envId",
- config: {
- rateLimit: readLimit
- },
- schema: {
- hide: false,
- tags: [ApiDocsTags.Environments],
- description: "Get Environment",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: z.object({
- // NOTE(daniel): workspaceId isn't used, but we need to keep it for backwards compatibility. The endpoint defined below, uses no project ID, and is takes a pure environment ID.
- 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,
- 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({
- method: "GET",
- url: "/environments/:envId",
+ url: "/:projectId/environments/:envId",
config: {
rateLimit: readLimit
},
@@ -76,7 +25,8 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- envId: z.string().trim().describe(ENVIRONMENTS.GET.id)
+ envId: z.string().trim().describe(ENVIRONMENTS.GET.id),
+ projectId: z.string().trim().describe(ENVIRONMENTS.GET.projectId)
}),
response: {
200: z.object({
@@ -111,7 +61,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
- url: "/:workspaceId/environments",
+ url: "/:projectId/environments",
config: {
rateLimit: writeLimit
},
@@ -125,7 +75,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- workspaceId: z.string().trim().describe(ENVIRONMENTS.CREATE.workspaceId)
+ projectId: z.string().trim().describe(ENVIRONMENTS.CREATE.projectId)
}),
body: z.object({
name: z.string().trim().describe(ENVIRONMENTS.CREATE.name),
@@ -135,7 +85,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
message: z.string(),
- workspace: z.string(),
+ projectId: z.string(),
environment: ProjectEnvironmentsSchema
})
}
@@ -147,7 +97,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
...req.body
});
@@ -164,7 +114,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
});
return {
message: "Successfully created new environment",
- workspace: req.params.workspaceId,
+ projectId: req.params.projectId,
environment
};
}
@@ -172,7 +122,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
server.route({
method: "PATCH",
- url: "/:workspaceId/environments/:id",
+ url: "/:projectId/environments/:id",
config: {
rateLimit: writeLimit
},
@@ -186,7 +136,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- workspaceId: z.string().trim().describe(ENVIRONMENTS.UPDATE.workspaceId),
+ projectId: z.string().trim().describe(ENVIRONMENTS.UPDATE.projectId),
id: z.string().trim().describe(ENVIRONMENTS.UPDATE.id)
}),
body: z.object({
@@ -197,7 +147,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
message: z.string(),
- workspace: z.string(),
+ projectId: z.string(),
environment: ProjectEnvironmentsSchema
})
}
@@ -209,7 +159,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
id: req.params.id,
...req.body
});
@@ -232,7 +182,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
return {
message: "Successfully updated environment",
- workspace: req.params.workspaceId,
+ projectId: req.params.projectId,
environment
};
}
@@ -240,7 +190,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
server.route({
method: "DELETE",
- url: "/:workspaceId/environments/:id",
+ url: "/:projectId/environments/:id",
config: {
rateLimit: writeLimit
},
@@ -254,13 +204,13 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- workspaceId: z.string().trim().describe(ENVIRONMENTS.DELETE.workspaceId),
+ projectId: z.string().trim().describe(ENVIRONMENTS.DELETE.projectId),
id: z.string().trim().describe(ENVIRONMENTS.DELETE.id)
}),
response: {
200: z.object({
message: z.string(),
- workspace: z.string(),
+ projectId: z.string(),
environment: ProjectEnvironmentsSchema
})
}
@@ -272,7 +222,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
id: req.params.id
});
@@ -290,7 +240,7 @@ export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
return {
message: "Successfully deleted environment",
- workspace: req.params.workspaceId,
+ projectId: req.params.projectId,
environment
};
}
diff --git a/backend/src/server/routes/v1/project-membership-router.ts b/backend/src/server/routes/v1/project-membership-router.ts
index cd3734efc4..f3cdfe7016 100644
--- a/backend/src/server/routes/v1/project-membership-router.ts
+++ b/backend/src/server/routes/v1/project-membership-router.ts
@@ -1,7 +1,8 @@
import { z } from "zod";
import {
- OrgMembershipsSchema,
+ OrgMembershipRole,
+ ProjectMembershipRole,
ProjectMembershipsSchema,
ProjectUserMembershipRolesSchema,
UserEncryptionKeysSchema,
@@ -18,7 +19,7 @@ import { ProjectUserMembershipTemporaryMode } from "@app/services/project-member
export const registerProjectMembershipRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/memberships",
+ url: "/:projectId/memberships",
config: {
rateLimit: readLimit
},
@@ -32,7 +33,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIPS.workspaceId)
+ projectId: z.string().trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIPS.projectId)
}),
response: {
200: z.object({
@@ -71,7 +72,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
return { memberships };
}
@@ -79,7 +80,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
server.route({
method: "GET",
- url: "/:workspaceId/memberships/:membershipId",
+ url: "/:projectId/memberships/:membershipId",
config: {
rateLimit: readLimit
},
@@ -91,7 +92,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
}
],
params: z.object({
- workspaceId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.workspaceId),
+ projectId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.projectId),
membershipId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.membershipId)
}),
response: {
@@ -129,7 +130,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
id: req.params.membershipId
});
return { membership };
@@ -138,7 +139,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
server.route({
method: "POST",
- url: "/:workspaceId/memberships/details",
+ url: "/:projectId/memberships/details",
config: {
rateLimit: readLimit
},
@@ -152,7 +153,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
}
],
params: z.object({
- workspaceId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.workspaceId)
+ projectId: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.projectId)
}),
body: z.object({
username: z.string().min(1).trim().describe(PROJECT_USERS.GET_USER_MEMBERSHIP.username)
@@ -191,7 +192,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
username: req.body.username
});
return { membership };
@@ -200,61 +201,83 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
server.route({
method: "POST",
- url: "/:workspaceId/memberships",
+ url: "/:projectId/memberships",
config: {
rateLimit: writeLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectUsers],
+ description: "Invite members to project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().describe(PROJECT_USERS.INVITE_MEMBER.projectId)
}),
body: z.object({
- members: z
- .object({
- orgMembershipId: z.string().trim(),
- workspaceEncryptedKey: z.string().trim(),
- workspaceEncryptedNonce: z.string().trim()
- })
+ emails: z
+ .string()
+ .email()
.array()
- .min(1)
+ .default([])
+ .describe(PROJECT_USERS.INVITE_MEMBER.emails)
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase"),
+ usernames: z
+ .string()
+ .array()
+ .default([])
+ .describe(PROJECT_USERS.INVITE_MEMBER.usernames)
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Username must be lowercase"),
+ roleSlugs: z.string().array().min(1).optional().describe(PROJECT_USERS.INVITE_MEMBER.roleSlugs)
}),
response: {
200: z.object({
- success: z.boolean(),
- data: OrgMembershipsSchema.array()
+ memberships: ProjectMembershipsSchema.array()
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const data = await server.services.projectMembership.addUsersToProject({
- actorId: req.permission.id,
- actor: req.permission.type,
+ const usernamesAndEmails = [...req.body.emails, ...req.body.usernames];
+ const { projectMemberships: memberships } = await server.services.org.inviteUserToOrganization({
actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- members: req.body.members
+ actor: req.permission.type,
+ inviteeEmails: usernamesAndEmails,
+ orgId: req.permission.orgId,
+ organizationRoleSlug: OrgMembershipRole.NoAccess,
+ projects: [
+ {
+ id: req.params.projectId,
+ projectRoleSlug: req.body.roleSlugs || [ProjectMembershipRole.Member]
+ }
+ ]
});
await server.services.auditLog.createAuditLog({
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
...req.auditLogInfo,
event: {
- type: EventType.ADD_BATCH_WORKSPACE_MEMBER,
- metadata: data.map(({ userId }) => ({
+ type: EventType.ADD_BATCH_PROJECT_MEMBER,
+ metadata: memberships.map(({ userId, id }) => ({
userId: userId || "",
+ membershipId: id,
email: ""
}))
}
});
- return { data, success: true };
+ return { memberships };
}
});
server.route({
method: "PATCH",
- url: "/:workspaceId/memberships/:membershipId",
+ url: "/:projectId/memberships/:membershipId",
config: {
rateLimit: writeLimit
},
@@ -268,7 +291,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECT_USERS.UPDATE_USER_MEMBERSHIP.workspaceId),
+ projectId: z.string().trim().describe(PROJECT_USERS.UPDATE_USER_MEMBERSHIP.projectId),
membershipId: z.string().trim().describe(PROJECT_USERS.UPDATE_USER_MEMBERSHIP.membershipId)
}),
body: z.object({
@@ -305,31 +328,87 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
membershipId: req.params.membershipId,
roles: req.body.roles
});
- // await server.services.auditLog.createAuditLog({
- // ...req.auditLogInfo,
- // projectId: req.params.workspaceId,
- // event: {
- // type: EventType.UPDATE_USER_WORKSPACE_ROLE,
- // metadata: {
- // userId: membership.userId,
- // newRole: req.body.role,
- // oldRole: membership.role,
- // email: ""
- // }
- // }
- // });
return { roles };
}
});
server.route({
method: "DELETE",
- url: "/:workspaceId/memberships/:membershipId",
+ url: "/:projectId/memberships",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectUsers],
+ description: "Remove members from project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().describe(PROJECT_USERS.REMOVE_MEMBER.projectId)
+ }),
+ body: z.object({
+ emails: z
+ .string()
+ .email()
+ .array()
+ .default([])
+ .describe(PROJECT_USERS.REMOVE_MEMBER.emails)
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Email must be lowercase"),
+ usernames: z
+ .string()
+ .array()
+ .default([])
+ .describe(PROJECT_USERS.REMOVE_MEMBER.usernames)
+ .refine((val) => val.every((el) => el === el.toLowerCase()), "Username must be lowercase")
+ }),
+ response: {
+ 200: z.object({
+ memberships: ProjectMembershipsSchema.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const memberships = await server.services.projectMembership.deleteProjectMemberships({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ emails: req.body.emails,
+ usernames: req.body.usernames
+ });
+
+ for (const membership of memberships) {
+ // eslint-disable-next-line no-await-in-loop
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ projectId: req.params.projectId,
+ event: {
+ type: EventType.REMOVE_PROJECT_MEMBER,
+ metadata: {
+ userId: membership.userId,
+ email: ""
+ }
+ }
+ });
+ }
+ return { memberships };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:projectId/memberships/:membershipId",
config: {
rateLimit: writeLimit
},
@@ -341,7 +420,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
}
],
params: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
membershipId: z.string().trim()
}),
response: {
@@ -357,15 +436,15 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
membershipId: req.params.membershipId
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
- type: EventType.REMOVE_WORKSPACE_MEMBER,
+ type: EventType.REMOVE_PROJECT_MEMBER,
metadata: {
userId: membership.userId,
email: ""
@@ -378,13 +457,13 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
server.route({
method: "DELETE",
- url: "/:workspaceId/leave",
+ url: "/:projectId/leave",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.object({
@@ -398,7 +477,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
const membership = await server.services.projectMembership.leaveProject({
actorId: req.permission.id,
actor: req.permission.type,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
return { membership };
}
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.ts
index 5e7dce76eb..be8b46dd51 100644
--- a/backend/src/server/routes/v1/project-router.ts
+++ b/backend/src/server/routes/v1/project-router.ts
@@ -2,7 +2,10 @@ import slugify from "@sindresorhus/slugify";
import { z } from "zod";
import {
+ CertificatesSchema,
IntegrationsSchema,
+ PkiAlertsSchema,
+ PkiCollectionsSchema,
ProjectEnvironmentsSchema,
ProjectMembershipsSchema,
ProjectRolesSchema,
@@ -16,18 +19,35 @@ import {
} from "@app/db/schemas";
import { ProjectMicrosoftTeamsConfigsSchema } from "@app/db/schemas/project-microsoft-teams-configs";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { InfisicalProjectTemplate } from "@app/ee/services/project-template/project-template-types";
+import { sanitizedSshCa } from "@app/ee/services/ssh/ssh-certificate-authority-schema";
+import { sanitizedSshCertificate } from "@app/ee/services/ssh-certificate/ssh-certificate-schema";
+import { sanitizedSshCertificateTemplate } from "@app/ee/services/ssh-certificate-template/ssh-certificate-template-schema";
+import { loginMappingSchema, sanitizedSshHost } from "@app/ee/services/ssh-host/ssh-host-schema";
+import { LoginMappingSource } from "@app/ee/services/ssh-host/ssh-host-types";
+import { sanitizedSshHostGroup } from "@app/ee/services/ssh-host-group/ssh-host-group-schema";
import { ApiDocsTags, PROJECTS } from "@app/lib/api-docs";
import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { re2Validator } from "@app/lib/zod";
import { readLimit, requestAccessLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { slugSchema } from "@app/server/lib/schemas";
+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
+import { CaStatus } from "@app/services/certificate-authority/certificate-authority-enums";
+import { sanitizedCertificateTemplate } from "@app/services/certificate-template/certificate-template-schema";
import { validateMicrosoftTeamsChannelsSchema } from "@app/services/microsoft-teams/microsoft-teams-fns";
+import { sanitizedPkiSubscriber } from "@app/services/pki-subscriber/pki-subscriber-schema";
import { ProjectFilterType, SearchProjectSortBy } from "@app/services/project/project-types";
import { validateSlackChannelsField } from "@app/services/slack/slack-auth-validators";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { WorkflowIntegration } from "@app/services/workflow-integration/workflow-integration-types";
-import { integrationAuthPubSchema, SanitizedProjectSchema } from "../sanitizedSchemas";
+import {
+ integrationAuthPubSchema,
+ InternalCertificateAuthorityResponseSchema,
+ SanitizedProjectSchema
+} from "../sanitizedSchemas";
import { sanitizedServiceTokenSchema } from "../v2/service-token-router";
const projectWithEnv = SanitizedProjectSchema.merge(
@@ -40,41 +60,7 @@ const projectWithEnv = SanitizedProjectSchema.merge(
export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/keys",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- workspaceId: z.string().trim()
- }),
- response: {
- 200: z.object({
- publicKeys: z
- .object({
- publicKey: z.string().nullable().optional(),
- userId: z.string()
- })
- .array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const publicKeys = await server.services.projectKey.getProjectPublicKeys({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
- });
- return { publicKeys };
- }
- });
-
- server.route({
- method: "GET",
- url: "/:workspaceId/users",
+ url: "/:projectId/users",
config: {
rateLimit: readLimit
},
@@ -96,7 +82,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
.optional()
}),
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.object({
@@ -142,7 +128,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
includeGroupMembers: req.query.includeGroupMembers,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
actorOrgId: req.permission.orgId,
roles
});
@@ -151,6 +137,83 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Projects],
+ description: "Create a new project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectName: z.string().trim().describe(PROJECTS.CREATE.projectName),
+ projectDescription: z.string().trim().optional().describe(PROJECTS.CREATE.projectDescription),
+ slug: slugSchema({ min: 5, max: 36 }).optional().describe(PROJECTS.CREATE.slug),
+ kmsKeyId: z.string().optional(),
+ template: slugSchema({ field: "Template Name", max: 64 })
+ .optional()
+ .default(InfisicalProjectTemplate.Default)
+ .describe(PROJECTS.CREATE.template),
+ type: z.nativeEnum(ProjectType).default(ProjectType.SecretManager),
+ shouldCreateDefaultEnvs: z.boolean().optional().default(true)
+ }),
+ response: {
+ 200: z.object({
+ project: projectWithEnv
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const project = await server.services.project.createProject({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ projectName: req.body.projectName,
+ projectDescription: req.body.projectDescription,
+ slug: req.body.slug,
+ kmsKeyId: req.body.kmsKeyId,
+ template: req.body.template,
+ type: req.body.type,
+ createDefaultEnvs: req.body.shouldCreateDefaultEnvs
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.ProjectCreated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ orgId: project.orgId,
+ name: project.name,
+ ...req.auditLogInfo
+ }
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: project.id,
+ event: {
+ type: EventType.CREATE_PROJECT,
+ metadata: {
+ ...req.body,
+ name: req.body.projectName
+ }
+ }
+ });
+
+ return { project };
+ }
+ });
+
server.route({
method: "GET",
url: "/",
@@ -158,6 +221,14 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
rateLimit: readLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.Projects],
+ description: "List projects",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
querystring: z.object({
includeRoles: z
.enum(["true", "false"])
@@ -167,7 +238,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- workspaces: projectWithEnv
+ projects: projectWithEnv
.extend({
roles: ProjectRolesSchema.array().optional()
})
@@ -177,7 +248,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspaces = await server.services.project.getProjects({
+ const projects = await server.services.project.getProjects({
includeRoles: req.query.includeRoles,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -185,13 +256,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorOrgId: req.permission.orgId,
type: req.query.type
});
- return { workspaces };
+ return { projects };
}
});
server.route({
method: "GET",
- url: "/:workspaceId",
+ url: "/:projectId",
config: {
rateLimit: readLimit
},
@@ -205,132 +276,124 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECTS.GET.workspaceId)
+ projectId: z.string().trim().describe(PROJECTS.GET.projectId)
}),
response: {
200: z.object({
- workspace: projectWithEnv.optional()
+ project: projectWithEnv.optional()
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspace = await server.services.project.getAProject({
+ const project = await server.services.project.getAProject({
filter: {
type: ProjectFilterType.ID,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
},
actorAuthMethod: req.permission.authMethod,
actorId: req.permission.id,
actor: req.permission.type,
actorOrgId: req.permission.orgId
});
- return { workspace };
+ return { project };
}
});
server.route({
- method: "DELETE",
- url: "/:workspaceId",
+ method: "GET",
+ url: "/slug/:slug",
config: {
- rateLimit: writeLimit
+ rateLimit: readLimit
},
schema: {
hide: false,
tags: [ApiDocsTags.Projects],
- description: "Delete project",
+ description: "Get project details by slug",
security: [
{
bearerAuth: []
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECTS.DELETE.workspaceId)
+ slug: slugSchema({ max: 36 }).describe("The slug of the project to get.")
}),
response: {
- 200: z.object({
- workspace: SanitizedProjectSchema.optional()
- })
+ 200: projectWithEnv
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspace = await server.services.project.deleteProject({
+ const project = await server.services.project.getAProject({
filter: {
- type: ProjectFilterType.ID,
- projectId: req.params.workspaceId
+ slug: req.params.slug,
+ orgId: req.permission.orgId,
+ type: ProjectFilterType.SLUG
},
actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- event: {
- type: EventType.DELETE_PROJECT,
- metadata: workspace
- }
+ actor: req.permission.type
});
- return { workspace };
+ return project;
}
});
server.route({
- url: "/:workspaceId/name",
- method: "POST",
+ method: "DELETE",
+ url: "/:projectId",
config: {
rateLimit: writeLimit
},
schema: {
+ hide: false,
+ tags: [ApiDocsTags.Projects],
+ description: "Delete project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
params: z.object({
- workspaceId: z.string().trim()
- }),
- body: z.object({
- name: z.string().trim()
+ projectId: z.string().trim().describe(PROJECTS.DELETE.projectId)
}),
response: {
200: z.object({
- message: z.string(),
- workspace: SanitizedProjectSchema
+ project: SanitizedProjectSchema.optional()
})
}
},
- onRequest: verifyAuth([AuthMode.JWT]),
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspace = await server.services.project.updateName({
+ const project = await server.services.project.deleteProject({
+ filter: {
+ type: ProjectFilterType.ID,
+ projectId: req.params.projectId
+ },
actorId: req.permission.id,
- actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- name: req.body.name
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
- type: EventType.UPDATE_PROJECT,
- metadata: req.body
+ type: EventType.DELETE_PROJECT,
+ metadata: project
}
});
- return {
- message: "Successfully changed workspace name",
- workspace
- };
+ return { project };
}
});
server.route({
method: "PATCH",
- url: "/:workspaceId",
+ url: "/:projectId",
config: {
rateLimit: writeLimit
},
@@ -344,7 +407,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECTS.UPDATE.workspaceId)
+ projectId: z.string().trim().describe(PROJECTS.UPDATE.projectId)
}),
body: z.object({
name: z
@@ -373,35 +436,35 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
.describe(PROJECTS.UPDATE.slug),
secretSharing: z.boolean().optional().describe(PROJECTS.UPDATE.secretSharing),
showSnapshotsLegacy: z.boolean().optional().describe(PROJECTS.UPDATE.showSnapshotsLegacy),
- defaultProduct: z.nativeEnum(ProjectType).optional().describe(PROJECTS.UPDATE.defaultProduct),
secretDetectionIgnoreValues: z
.array(z.string())
.optional()
- .describe(PROJECTS.UPDATE.secretDetectionIgnoreValues)
+ .describe(PROJECTS.UPDATE.secretDetectionIgnoreValues),
+ pitVersionLimit: z.number().min(1).max(100).optional()
}),
response: {
200: z.object({
- workspace: SanitizedProjectSchema
+ project: SanitizedProjectSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspace = await server.services.project.updateProject({
+ const project = await server.services.project.updateProject({
filter: {
type: ProjectFilterType.ID,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
},
update: {
name: req.body.name,
description: req.body.description,
autoCapitalization: req.body.autoCapitalization,
- defaultProduct: req.body.defaultProduct,
hasDeleteProtection: req.body.hasDeleteProtection,
slug: req.body.slug,
secretSharing: req.body.secretSharing,
showSnapshotsLegacy: req.body.showSnapshotsLegacy,
- secretDetectionIgnoreValues: req.body.secretDetectionIgnoreValues
+ secretDetectionIgnoreValues: req.body.secretDetectionIgnoreValues,
+ pitVersionLimit: req.body.pitVersionLimit
},
actorAuthMethod: req.permission.authMethod,
actorId: req.permission.id,
@@ -412,150 +475,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- event: {
- type: EventType.UPDATE_PROJECT,
- metadata: req.body
- }
- });
-
- return {
- workspace
- };
- }
- });
-
- server.route({
- method: "POST",
- url: "/:workspaceId/auto-capitalization",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- workspaceId: z.string().trim()
- }),
- body: z.object({
- autoCapitalization: z.boolean()
- }),
- response: {
- 200: z.object({
- message: z.string(),
- workspace: SanitizedProjectSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const workspace = await server.services.project.toggleAutoCapitalization({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- autoCapitalization: req.body.autoCapitalization
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- event: {
- type: EventType.UPDATE_PROJECT,
- metadata: req.body
- }
- });
-
- return {
- message: "Successfully changed workspace settings",
- workspace
- };
- }
- });
-
- server.route({
- method: "POST",
- url: "/:workspaceId/delete-protection",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- workspaceId: z.string().trim()
- }),
- body: z.object({
- hasDeleteProtection: z.boolean()
- }),
- response: {
- 200: z.object({
- message: z.string(),
- workspace: SanitizedProjectSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const workspace = await server.services.project.toggleDeleteProtection({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- hasDeleteProtection: req.body.hasDeleteProtection
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: req.params.workspaceId,
- event: {
- type: EventType.UPDATE_PROJECT,
- metadata: req.body
- }
- });
-
- return {
- message: "Successfully changed workspace settings",
- workspace
- };
- }
- });
-
- server.route({
- method: "PUT",
- url: "/:workspaceSlug/version-limit",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- workspaceSlug: z.string().trim()
- }),
- body: z.object({
- pitVersionLimit: z.number().min(1).max(100)
- }),
- response: {
- 200: z.object({
- message: z.string(),
- workspace: SanitizedProjectSchema
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const workspace = await server.services.project.updateVersionLimit({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- pitVersionLimit: req.body.pitVersionLimit,
- workspaceSlug: req.params.workspaceSlug
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: req.permission.orgId,
- projectId: workspace.id,
+ projectId: req.params.projectId,
event: {
type: EventType.UPDATE_PROJECT,
metadata: req.body
@@ -563,21 +483,20 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
});
return {
- message: "Successfully changed workspace version limit",
- workspace
+ project
};
}
});
server.route({
method: "PUT",
- url: "/:workspaceSlug/audit-logs-retention",
+ url: "/:projectId/audit-logs-retention",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceSlug: z.string().trim()
+ projectId: z.string().trim()
}),
body: z.object({
auditLogsRetentionDays: z.number().min(0)
@@ -585,25 +504,28 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
message: z.string(),
- workspace: SanitizedProjectSchema
+ project: SanitizedProjectSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspace = await server.services.project.updateAuditLogsRetention({
+ const project = await server.services.project.updateAuditLogsRetention({
actorId: req.permission.id,
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- workspaceSlug: req.params.workspaceSlug,
- auditLogsRetentionDays: req.body.auditLogsRetentionDays
+ auditLogsRetentionDays: req.body.auditLogsRetentionDays,
+ filter: {
+ projectId: req.params.projectId,
+ type: ProjectFilterType.ID
+ }
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
orgId: req.permission.orgId,
- projectId: workspace.id,
+ projectId: project.id,
event: {
type: EventType.UPDATE_PROJECT,
metadata: req.body
@@ -612,14 +534,14 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
return {
message: "Successfully updated project's audit logs retention period",
- workspace
+ project
};
}
});
server.route({
method: "GET",
- url: "/:workspaceId/integrations",
+ url: "/:projectId/integrations",
config: {
rateLimit: readLimit
},
@@ -633,7 +555,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECTS.LIST_INTEGRATION.workspaceId)
+ projectId: z.string().trim().describe(PROJECTS.LIST_INTEGRATION.projectId)
}),
response: {
200: z.object({
@@ -656,7 +578,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
return { integrations };
}
@@ -664,21 +586,21 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/authorizations",
+ url: "/:projectId/authorizations",
config: {
rateLimit: readLimit
},
schema: {
hide: false,
tags: [ApiDocsTags.Integrations],
- description: "List integration auth objects for a workspace.",
+ description: "List integration auth objects for a project.",
security: [
{
bearerAuth: []
}
],
params: z.object({
- workspaceId: z.string().trim().describe(PROJECTS.LIST_INTEGRATION_AUTHORIZATION.workspaceId)
+ projectId: z.string().trim().describe(PROJECTS.LIST_INTEGRATION_AUTHORIZATION.projectId)
}),
response: {
200: z.object({
@@ -693,7 +615,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
return { authorizations };
}
@@ -701,13 +623,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/service-token-data",
+ url: "/:projectId/service-token-data",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.object({
@@ -722,7 +644,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
return { serviceTokenData };
}
@@ -730,13 +652,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/ssh-config",
+ url: "/:projectId/ssh-config",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: ProjectSshConfigsSchema.pick({
@@ -756,7 +678,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
await server.services.auditLog.createAuditLog({
@@ -777,13 +699,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "PATCH",
- url: "/:workspaceId/ssh-config",
+ url: "/:projectId/ssh-config",
config: {
rateLimit: writeLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
body: z.object({
defaultUserSshCaId: z.string().optional(),
@@ -807,7 +729,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
...req.body
});
@@ -831,13 +753,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/workflow-integration-config/:integration",
+ url: "/:projectId/workflow-integration-config/:integration",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
integration: z.nativeEnum(WorkflowIntegration)
}),
response: {
@@ -876,13 +798,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
integration: req.params.integration
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
type: EventType.GET_PROJECT_WORKFLOW_INTEGRATION_CONFIG,
metadata: {
@@ -936,15 +858,14 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "PUT",
- url: "/:workspaceId/workflow-integration",
+ url: "/:projectId/workflow-integration",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
-
body: z.discriminatedUnion("integration", [
z.object({
integration: z.literal(WorkflowIntegration.SLACK),
@@ -999,13 +920,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actor: req.permission.type,
actorOrgId: req.permission.orgId,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
...req.body
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
type: EventType.UPDATE_PROJECT_WORKFLOW_INTEGRATION_CONFIG,
metadata: {
@@ -1026,13 +947,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
- url: "/:workspaceId/environment-folder-tree",
+ url: "/:projectId/environment-folder-tree",
config: {
rateLimit: readLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
response: {
200: z.record(
@@ -1043,7 +964,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT]),
handler: async (req) => {
const environmentsFolders = await server.services.folder.getProjectEnvironmentsFolders(
- req.params.workspaceId,
+ req.params.projectId,
req.permission
);
@@ -1064,6 +985,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
type: z.nativeEnum(ProjectType).optional(),
orderBy: z.nativeEnum(SearchProjectSortBy).optional().default(SearchProjectSortBy.NAME),
orderDirection: z.nativeEnum(SortDirection).optional().default(SortDirection.ASC),
+ projectIds: z.string().trim().array().optional(),
name: z
.string()
.trim()
@@ -1092,13 +1014,13 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
- url: "/:workspaceId/project-access",
+ url: "/:projectId/project-access",
config: {
rateLimit: requestAccessLimit
},
schema: {
params: z.object({
- workspaceId: z.string().trim()
+ projectId: z.string().trim()
}),
body: z.object({
comment: z
@@ -1132,17 +1054,17 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
await server.services.project.requestProjectAccess({
permission: req.permission,
comment: req.body.comment,
- projectId: req.params.workspaceId
+ projectId: req.params.projectId
});
if (req.auth.actor === ActorType.USER) {
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
event: {
type: EventType.PROJECT_ACCESS_REQUEST,
metadata: {
- projectId: req.params.workspaceId,
+ projectId: req.params.projectId,
requesterEmail: req.auth.user.email || req.auth.user.username,
requesterId: req.auth.userId
}
@@ -1153,4 +1075,456 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
return { message: "Project access request has been send to project admins" };
}
});
+
+ /* Start upgrade of a project */
+ server.route({
+ method: "POST",
+ url: "/:projectId/upgrade",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ body: z.object({
+ userPrivateKey: z.string().trim()
+ }),
+ response: {
+ 200: z.void()
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ await server.services.project.upgradeProject({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ projectId: req.params.projectId,
+ userPrivateKey: req.body.userPrivateKey
+ });
+ }
+ });
+
+ /* Get upgrade status of project */
+ server.route({
+ url: "/:projectId/upgrade/status",
+ method: "GET",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ status: z.string().nullable()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const status = await server.services.project.getProjectUpgradeStatus({
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ actor: req.permission.type,
+ actorId: req.permission.id
+ });
+
+ return { status };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/cas",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiCertificateAuthorities],
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ querystring: z.object({
+ status: z.enum([CaStatus.ACTIVE, CaStatus.PENDING_CERTIFICATE]).optional().describe(PROJECTS.LIST_CAS.status),
+ friendlyName: z.string().optional().describe(PROJECTS.LIST_CAS.friendlyName),
+ commonName: z.string().optional().describe(PROJECTS.LIST_CAS.commonName),
+ offset: z.coerce.number().min(0).max(100).default(0).describe(PROJECTS.LIST_CAS.offset),
+ limit: z.coerce.number().min(1).max(100).default(25).describe(PROJECTS.LIST_CAS.limit)
+ }),
+ response: {
+ 200: z.object({
+ cas: z.array(InternalCertificateAuthorityResponseSchema)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const cas = await server.services.project.listProjectCas({
+ filter: {
+ projectId: req.params.projectId,
+ type: ProjectFilterType.ID
+ },
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ ...req.query
+ });
+ return { cas };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/certificates",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiCertificates],
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ querystring: z.object({
+ friendlyName: z.string().optional().describe(PROJECTS.LIST_CERTIFICATES.friendlyName),
+ commonName: z.string().optional().describe(PROJECTS.LIST_CERTIFICATES.commonName),
+ offset: z.coerce.number().min(0).max(100).default(0).describe(PROJECTS.LIST_CERTIFICATES.offset),
+ limit: z.coerce.number().min(1).max(100).default(25).describe(PROJECTS.LIST_CERTIFICATES.limit)
+ }),
+ response: {
+ 200: z.object({
+ certificates: z.array(CertificatesSchema),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { certificates, totalCount } = await server.services.project.listProjectCertificates({
+ filter: {
+ projectId: req.params.projectId,
+ type: ProjectFilterType.ID
+ },
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ ...req.query
+ });
+ return { certificates, totalCount };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/pki-alerts",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiAlerting],
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ alerts: z.array(PkiAlertsSchema)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { alerts } = await server.services.project.listProjectAlerts({
+ projectId: req.params.projectId,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type
+ });
+
+ return { alerts };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/pki-collections",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiCertificateCollections],
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ collections: z.array(PkiCollectionsSchema)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { pkiCollections } = await server.services.project.listProjectPkiCollections({
+ projectId: req.params.projectId,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type
+ });
+
+ return { collections: pkiCollections };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/pki-subscribers",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiSubscribers],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.LIST_PKI_SUBSCRIBERS.projectId)
+ }),
+ response: {
+ 200: z.object({
+ subscribers: z.array(sanitizedPkiSubscriber)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const subscribers = await server.services.project.listProjectPkiSubscribers({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ projectId: req.params.projectId
+ });
+
+ return { subscribers };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/certificate-templates",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.PkiCertificateTemplates],
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ certificateTemplates: sanitizedCertificateTemplate.array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { certificateTemplates } = await server.services.project.listProjectCertificateTemplates({
+ projectId: req.params.projectId,
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type
+ });
+
+ return { certificateTemplates };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/ssh-certificates",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.LIST_SSH_CAS.projectId)
+ }),
+ querystring: z.object({
+ offset: z.coerce.number().default(0).describe(PROJECTS.LIST_SSH_CERTIFICATES.offset),
+ limit: z.coerce.number().default(25).describe(PROJECTS.LIST_SSH_CERTIFICATES.limit)
+ }),
+ response: {
+ 200: z.object({
+ certificates: z.array(sanitizedSshCertificate),
+ totalCount: z.number()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { certificates, totalCount } = await server.services.project.listProjectSshCertificates({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ projectId: req.params.projectId,
+ offset: req.query.offset,
+ limit: req.query.limit
+ });
+
+ return { certificates, totalCount };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/ssh-certificate-templates",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SshCertificateTemplates],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.LIST_SSH_CERTIFICATE_TEMPLATES.projectId)
+ }),
+ response: {
+ 200: z.object({
+ certificateTemplates: z.array(sanitizedSshCertificateTemplate)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { certificateTemplates } = await server.services.project.listProjectSshCertificateTemplates({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ projectId: req.params.projectId
+ });
+
+ return { certificateTemplates };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/ssh-cas",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SshCertificateAuthorities],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.LIST_SSH_CAS.projectId)
+ }),
+ response: {
+ 200: z.object({
+ cas: z.array(sanitizedSshCa)
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const cas = await server.services.project.listProjectSshCas({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ projectId: req.params.projectId
+ });
+
+ return { cas };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/ssh-hosts",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SshHosts],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.LIST_SSH_HOSTS.projectId)
+ }),
+ response: {
+ 200: z.object({
+ hosts: z.array(
+ sanitizedSshHost.extend({
+ loginMappings: loginMappingSchema
+ .extend({
+ source: z.nativeEnum(LoginMappingSource)
+ })
+ .array()
+ })
+ )
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const hosts = await server.services.project.listProjectSshHosts({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ projectId: req.params.projectId
+ });
+
+ return { hosts };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/ssh-host-groups",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.SshHostGroups],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.LIST_SSH_HOST_GROUPS.projectId)
+ }),
+ response: {
+ 200: z.object({
+ groups: z.array(
+ sanitizedSshHostGroup.extend({
+ loginMappings: loginMappingSchema.array(),
+ hostCount: z.number()
+ })
+ )
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const groups = await server.services.project.listProjectSshHostGroups({
+ actorId: req.permission.id,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ actor: req.permission.type,
+ projectId: req.params.projectId
+ });
+
+ return { groups };
+ }
+ });
};
diff --git a/backend/src/server/routes/v1/secret-tag-router.ts b/backend/src/server/routes/v1/secret-tag-router.ts
index 01ba783fef..3c6c99eaff 100644
--- a/backend/src/server/routes/v1/secret-tag-router.ts
+++ b/backend/src/server/routes/v1/secret-tag-router.ts
@@ -22,20 +22,20 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- workspaceTags: SecretTagsSchema.array()
+ tags: SecretTagsSchema.array()
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspaceTags = await server.services.secretTag.getProjectTags({
+ const tags = await server.services.secretTag.getProjectTags({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
projectId: req.params.projectId
});
- return { workspaceTags };
+ return { tags };
}
});
@@ -55,20 +55,20 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
// akhilmhdh: for terraform backward compatiability
- workspaceTag: SecretTagsSchema.extend({ name: z.string() })
+ tag: SecretTagsSchema.extend({ name: z.string() })
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspaceTag = await server.services.secretTag.getTagById({
+ const tag = await server.services.secretTag.getTagById({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
id: req.params.tagId
});
- return { workspaceTag };
+ return { tag };
}
});
@@ -88,13 +88,13 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
response: {
200: z.object({
// akhilmhdh: for terraform backward compatiability
- workspaceTag: SecretTagsSchema.extend({ name: z.string() })
+ tag: SecretTagsSchema.extend({ name: z.string() })
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspaceTag = await server.services.secretTag.getTagBySlug({
+ const tag = await server.services.secretTag.getTagBySlug({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -102,7 +102,7 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
slug: req.params.tagSlug,
projectId: req.params.projectId
});
- return { workspaceTag };
+ return { tag };
}
});
@@ -124,13 +124,13 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- workspaceTag: SecretTagsSchema
+ tag: SecretTagsSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspaceTag = await server.services.secretTag.createTag({
+ const tag = await server.services.secretTag.createTag({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -138,7 +138,7 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
projectId: req.params.projectId,
...req.body
});
- return { workspaceTag };
+ return { tag };
}
});
@@ -161,13 +161,13 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- workspaceTag: SecretTagsSchema
+ tag: SecretTagsSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspaceTag = await server.services.secretTag.updateTag({
+ const tag = await server.services.secretTag.updateTag({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -175,7 +175,7 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
...req.body,
id: req.params.tagId
});
- return { workspaceTag };
+ return { tag };
}
});
@@ -194,20 +194,20 @@ export const registerSecretTagRouter = async (server: FastifyZodProvider) => {
}),
response: {
200: z.object({
- workspaceTag: SecretTagsSchema
+ tag: SecretTagsSchema
})
}
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const workspaceTag = await server.services.secretTag.deleteTag({
+ const tag = await server.services.secretTag.deleteTag({
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
id: req.params.tagId
});
- return { workspaceTag };
+ return { tag };
}
});
};
diff --git a/backend/src/server/routes/v1/webhook-router.ts b/backend/src/server/routes/v1/webhook-router.ts
index 377af135c8..386628d28d 100644
--- a/backend/src/server/routes/v1/webhook-router.ts
+++ b/backend/src/server/routes/v1/webhook-router.ts
@@ -39,7 +39,7 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
body: z
.object({
type: z.nativeEnum(WebhookType).default(WebhookType.GENERAL),
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
environment: z.string().trim(),
webhookUrl: z.string().url().trim(),
webhookSecretKey: z.string().trim().optional(),
@@ -67,13 +67,12 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- projectId: req.body.workspaceId,
...req.body
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
event: {
type: EventType.CREATE_WEBHOOK,
metadata: {
@@ -216,7 +215,7 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
onRequest: verifyAuth([AuthMode.JWT]),
schema: {
querystring: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
environment: z.string().trim().optional(),
secretPath: z
.string()
@@ -238,7 +237,7 @@ export const registerWebhookRouter = async (server: FastifyZodProvider) => {
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.query,
- projectId: req.query.workspaceId
+ projectId: req.query.projectId
});
return { message: "Successfully fetched webhook", webhooks };
}
diff --git a/backend/src/server/routes/v2/deprecated-group-project-router.ts b/backend/src/server/routes/v2/deprecated-group-project-router.ts
new file mode 100644
index 0000000000..f0e4ee705a
--- /dev/null
+++ b/backend/src/server/routes/v2/deprecated-group-project-router.ts
@@ -0,0 +1,363 @@
+import { z } from "zod";
+
+import {
+ GroupProjectMembershipsSchema,
+ GroupsSchema,
+ ProjectMembershipRole,
+ ProjectUserMembershipRolesSchema,
+ UsersSchema
+} from "@app/db/schemas";
+import { EFilterReturnedUsers } from "@app/ee/services/group/group-types";
+import { ApiDocsTags, GROUPS, PROJECTS } from "@app/lib/api-docs";
+import { ms } from "@app/lib/ms";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { ProjectUserMembershipTemporaryMode } from "@app/services/project-membership/project-membership-types";
+
+export const registerDeprecatedGroupProjectRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/:projectId/groups/:groupIdOrName",
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectGroups],
+ description: "Add group to project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.ADD_GROUP_TO_PROJECT.projectId),
+ groupIdOrName: z.string().trim().describe(PROJECTS.ADD_GROUP_TO_PROJECT.groupIdOrName)
+ }),
+ body: z
+ .object({
+ role: z
+ .string()
+ .trim()
+ .min(1)
+ .default(ProjectMembershipRole.NoAccess)
+ .describe(PROJECTS.ADD_GROUP_TO_PROJECT.role),
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(false).default(false)
+ }),
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(true),
+ temporaryMode: z.nativeEnum(ProjectUserMembershipTemporaryMode),
+ temporaryRange: z.string().refine((val) => ms(val) > 0, "Temporary range must be a positive number"),
+ temporaryAccessStartTime: z.string().datetime()
+ })
+ ])
+ )
+ .optional()
+ })
+ .refine((data) => data.role || data.roles, {
+ message: "Either role or roles must be present",
+ path: ["role", "roles"]
+ }),
+ response: {
+ 200: z.object({
+ groupMembership: GroupProjectMembershipsSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const groupMembership = await server.services.groupProject.addGroupToProject({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ roles: req.body.roles || [{ role: req.body.role }],
+ projectId: req.params.projectId,
+ groupIdOrName: req.params.groupIdOrName
+ });
+
+ return { groupMembership };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:projectId/groups/:groupId",
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectGroups],
+ description: "Update group in project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.UPDATE_GROUP_IN_PROJECT.projectId),
+ groupId: z.string().trim().describe(PROJECTS.UPDATE_GROUP_IN_PROJECT.groupId)
+ }),
+ body: z.object({
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(false).default(false)
+ }),
+ z.object({
+ role: z.string(),
+ isTemporary: z.literal(true),
+ temporaryMode: z.nativeEnum(ProjectUserMembershipTemporaryMode),
+ temporaryRange: z.string().refine((val) => ms(val) > 0, "Temporary range must be a positive number"),
+ temporaryAccessStartTime: z.string().datetime()
+ })
+ ])
+ )
+ .min(1)
+ .describe(PROJECTS.UPDATE_GROUP_IN_PROJECT.roles)
+ }),
+ response: {
+ 200: z.object({
+ roles: ProjectUserMembershipRolesSchema.array()
+ })
+ }
+ },
+ handler: async (req) => {
+ const roles = await server.services.groupProject.updateGroupInProject({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ groupId: req.params.groupId,
+ roles: req.body.roles
+ });
+
+ return { roles };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:projectId/groups/:groupId",
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectGroups],
+ description: "Remove group from project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.REMOVE_GROUP_FROM_PROJECT.projectId),
+ groupId: z.string().trim().describe(PROJECTS.REMOVE_GROUP_FROM_PROJECT.groupId)
+ }),
+ response: {
+ 200: z.object({
+ groupMembership: GroupProjectMembershipsSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const groupMembership = await server.services.groupProject.removeGroupFromProject({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ groupId: req.params.groupId,
+ projectId: req.params.projectId
+ });
+
+ return { groupMembership };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/groups",
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectGroups],
+ description: "Return list of groups in project",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECTS.LIST_GROUPS_IN_PROJECT.projectId)
+ }),
+ response: {
+ 200: z.object({
+ groupMemberships: z
+ .object({
+ id: z.string(),
+ groupId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ 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()
+ })
+ ),
+ group: GroupsSchema.pick({ name: true, id: true, slug: true })
+ })
+ .array()
+ })
+ }
+ },
+ handler: async (req) => {
+ const groupMemberships = await server.services.groupProject.listGroupsInProject({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId
+ });
+
+ return { groupMemberships };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/groups/:groupId",
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectGroups],
+ description: "Return project group",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim(),
+ groupId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ groupMembership: z.object({
+ id: z.string(),
+ groupId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ 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()
+ })
+ ),
+ group: GroupsSchema.pick({ name: true, id: true, slug: true })
+ })
+ })
+ }
+ },
+ handler: async (req) => {
+ const groupMembership = await server.services.groupProject.getGroupInProject({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.params
+ });
+
+ return { groupMembership };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/groups/:groupId/users",
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectGroups],
+ description: "Return project group users",
+ params: z.object({
+ projectId: z.string().trim().describe(GROUPS.LIST_USERS.projectId),
+ groupId: z.string().trim().describe(GROUPS.LIST_USERS.id)
+ }),
+ querystring: z.object({
+ offset: z.coerce.number().min(0).max(100).default(0).describe(GROUPS.LIST_USERS.offset),
+ limit: z.coerce.number().min(1).max(100).default(10).describe(GROUPS.LIST_USERS.limit),
+ username: z.string().trim().optional().describe(GROUPS.LIST_USERS.username),
+ search: z.string().trim().optional().describe(GROUPS.LIST_USERS.search),
+ filter: z.nativeEnum(EFilterReturnedUsers).optional().describe(GROUPS.LIST_USERS.filterUsers)
+ }),
+ response: {
+ 200: z.object({
+ users: UsersSchema.pick({
+ email: true,
+ username: true,
+ firstName: true,
+ lastName: true,
+ id: true
+ })
+ .merge(
+ z.object({
+ isPartOfGroup: z.boolean(),
+ joinedGroupAt: z.date().nullable()
+ })
+ )
+ .array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ handler: async (req) => {
+ const { users, totalCount } = await server.services.groupProject.listProjectGroupUsers({
+ id: req.params.groupId,
+ projectId: req.params.projectId,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.query
+ });
+
+ return { users, totalCount };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v2/deprecated-identity-project-router.ts b/backend/src/server/routes/v2/deprecated-identity-project-router.ts
new file mode 100644
index 0000000000..c16c874aec
--- /dev/null
+++ b/backend/src/server/routes/v2/deprecated-identity-project-router.ts
@@ -0,0 +1,418 @@
+import { z } from "zod";
+
+import {
+ IdentitiesSchema,
+ IdentityProjectMembershipsSchema,
+ ProjectMembershipRole,
+ ProjectUserMembershipRolesSchema
+} from "@app/db/schemas";
+import { ApiDocsTags, ORGANIZATIONS, PROJECT_IDENTITIES } from "@app/lib/api-docs";
+import { BadRequestError } from "@app/lib/errors";
+import { ms } from "@app/lib/ms";
+import { OrderByDirection } from "@app/lib/types";
+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
+import { ProjectIdentityOrderBy } from "@app/services/identity-project/identity-project-types";
+import { ProjectUserMembershipTemporaryMode } from "@app/services/project-membership/project-membership-types";
+
+import { SanitizedProjectSchema } from "../sanitizedSchemas";
+
+export const registerDeprecatedIdentityProjectRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "POST",
+ url: "/:projectId/identity-memberships/:identityId",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectIdentities],
+ description: "Create project identity membership",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim(),
+ identityId: z.string().trim()
+ }),
+ body: z.object({
+ // @depreciated
+ role: z.string().trim().optional().default(ProjectMembershipRole.NoAccess),
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string().describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.role),
+ isTemporary: z
+ .literal(false)
+ .default(false)
+ .describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.role)
+ }),
+ z.object({
+ role: z.string().describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.role),
+ isTemporary: z.literal(true).describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.role),
+ temporaryMode: z
+ .nativeEnum(ProjectUserMembershipTemporaryMode)
+ .describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.role),
+ temporaryRange: z
+ .string()
+ .refine((val) => ms(val) > 0, "Temporary range must be a positive number")
+ .describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.role),
+ temporaryAccessStartTime: z
+ .string()
+ .datetime()
+ .describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.role)
+ })
+ ])
+ )
+ .describe(PROJECT_IDENTITIES.CREATE_IDENTITY_MEMBERSHIP.roles.description)
+ .optional()
+ }),
+ response: {
+ 200: z.object({
+ identityMembership: IdentityProjectMembershipsSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const { role, roles } = req.body;
+ if (!role && !roles) throw new BadRequestError({ message: "You must provide either role or roles field" });
+
+ const identityMembership = await server.services.identityProject.createProjectIdentity({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ identityId: req.params.identityId,
+ projectId: req.params.projectId,
+ roles: roles || [{ role }]
+ });
+ return { identityMembership };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:projectId/identity-memberships/:identityId",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectIdentities],
+ description: "Update project identity memberships",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.projectId),
+ identityId: z.string().trim().describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.identityId)
+ }),
+ body: z.object({
+ roles: z
+ .array(
+ z.union([
+ z.object({
+ role: z.string().describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.role),
+ isTemporary: z
+ .literal(false)
+ .default(false)
+ .describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.isTemporary)
+ }),
+ z.object({
+ role: z.string().describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.role),
+ isTemporary: z.literal(true).describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.isTemporary),
+ temporaryMode: z
+ .nativeEnum(ProjectUserMembershipTemporaryMode)
+ .describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.temporaryMode),
+ temporaryRange: z
+ .string()
+ .refine((val) => ms(val) > 0, "Temporary range must be a positive number")
+ .describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.temporaryRange),
+ temporaryAccessStartTime: z
+ .string()
+ .datetime()
+ .describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.temporaryAccessStartTime)
+ })
+ ])
+ )
+ .min(1)
+ .describe(PROJECT_IDENTITIES.UPDATE_IDENTITY_MEMBERSHIP.roles.description)
+ }),
+ response: {
+ 200: z.object({
+ roles: ProjectUserMembershipRolesSchema.array()
+ })
+ }
+ },
+ handler: async (req) => {
+ const roles = await server.services.identityProject.updateProjectIdentity({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ identityId: req.params.identityId,
+ projectId: req.params.projectId,
+ roles: req.body.roles
+ });
+ return { roles };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:projectId/identity-memberships/:identityId",
+ config: {
+ rateLimit: writeLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectIdentities],
+ description: "Delete project identity memberships",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECT_IDENTITIES.DELETE_IDENTITY_MEMBERSHIP.projectId),
+ identityId: z.string().trim().describe(PROJECT_IDENTITIES.DELETE_IDENTITY_MEMBERSHIP.identityId)
+ }),
+ response: {
+ 200: z.object({
+ identityMembership: IdentityProjectMembershipsSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const identityMembership = await server.services.identityProject.deleteProjectIdentity({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ identityId: req.params.identityId,
+ projectId: req.params.projectId
+ });
+ return { identityMembership };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/identity-memberships",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectIdentities],
+ description: "Return project identity memberships",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECT_IDENTITIES.LIST_IDENTITY_MEMBERSHIPS.projectId)
+ }),
+ querystring: z.object({
+ offset: z.coerce
+ .number()
+ .min(0)
+ .default(0)
+ .describe(PROJECT_IDENTITIES.LIST_IDENTITY_MEMBERSHIPS.offset)
+ .optional(),
+ limit: z.coerce
+ .number()
+ .min(1)
+ .max(20000) // TODO: temp limit until combobox added to add identity to project modal, reduce once added
+ .default(100)
+ .describe(PROJECT_IDENTITIES.LIST_IDENTITY_MEMBERSHIPS.limit)
+ .optional(),
+ orderBy: z
+ .nativeEnum(ProjectIdentityOrderBy)
+ .default(ProjectIdentityOrderBy.Name)
+ .describe(ORGANIZATIONS.LIST_IDENTITY_MEMBERSHIPS.orderBy)
+ .optional(),
+ orderDirection: z
+ .nativeEnum(OrderByDirection)
+ .default(OrderByDirection.ASC)
+ .describe(ORGANIZATIONS.LIST_IDENTITY_MEMBERSHIPS.orderDirection)
+ .optional(),
+ search: z.string().trim().describe(PROJECT_IDENTITIES.LIST_IDENTITY_MEMBERSHIPS.search).optional()
+ }),
+ response: {
+ 200: z.object({
+ identityMemberships: z
+ .object({
+ id: z.string(),
+ identityId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ 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()
+ })
+ ),
+ identity: IdentitiesSchema.pick({ name: true, id: true }).extend({
+ authMethods: z.array(z.string())
+ }),
+ project: SanitizedProjectSchema.pick({ name: true, id: true })
+ })
+ .array(),
+ totalCount: z.number()
+ })
+ }
+ },
+ handler: async (req) => {
+ const { identityMemberships, totalCount } = await server.services.identityProject.listProjectIdentities({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ limit: req.query.limit,
+ offset: req.query.offset,
+ orderBy: req.query.orderBy,
+ orderDirection: req.query.orderDirection,
+ search: req.query.search
+ });
+
+ return { identityMemberships, totalCount };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/identity-memberships/:identityId",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectIdentities],
+ description: "Return project identity membership",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim().describe(PROJECT_IDENTITIES.GET_IDENTITY_MEMBERSHIP_BY_ID.projectId),
+ identityId: z.string().trim().describe(PROJECT_IDENTITIES.GET_IDENTITY_MEMBERSHIP_BY_ID.identityId)
+ }),
+ response: {
+ 200: z.object({
+ identityMembership: z.object({
+ id: z.string(),
+ identityId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ 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()
+ })
+ ),
+ identity: IdentitiesSchema.pick({ name: true, id: true }).extend({
+ authMethods: z.array(z.string())
+ }),
+ project: SanitizedProjectSchema.pick({ name: true, id: true })
+ })
+ })
+ }
+ },
+ handler: async (req) => {
+ const identityMembership = await server.services.identityProject.getProjectIdentityByIdentityId({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId: req.params.projectId,
+ identityId: req.params.identityId
+ });
+ return { identityMembership };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/identity-memberships/:identityMembershipId",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.ProjectIdentities],
+ params: z.object({
+ identityMembershipId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ identityMembership: z.object({
+ id: z.string(),
+ identityId: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ 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()
+ })
+ ),
+ identity: IdentitiesSchema.pick({ name: true, id: true }).extend({
+ authMethods: z.array(z.string())
+ }),
+ project: SanitizedProjectSchema.pick({ name: true, id: true })
+ })
+ })
+ }
+ },
+ handler: async (req) => {
+ const identityMembership = await server.services.identityProject.getProjectIdentityByMembershipId({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ identityMembershipId: req.params.identityMembershipId
+ });
+ return { identityMembership };
+ }
+ });
+};
diff --git a/backend/src/server/routes/v2/project-membership-router.ts b/backend/src/server/routes/v2/deprecated-project-membership-router.ts
similarity index 96%
rename from backend/src/server/routes/v2/project-membership-router.ts
rename to backend/src/server/routes/v2/deprecated-project-membership-router.ts
index 76f1e9c5ea..d88d2f996a 100644
--- a/backend/src/server/routes/v2/project-membership-router.ts
+++ b/backend/src/server/routes/v2/deprecated-project-membership-router.ts
@@ -7,7 +7,7 @@ import { writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
-export const registerProjectMembershipRouter = async (server: FastifyZodProvider) => {
+export const registerDeprecatedProjectMembershipRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
url: "/:projectId/memberships",
@@ -71,7 +71,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
projectId: req.params.projectId,
...req.auditLogInfo,
event: {
- type: EventType.ADD_BATCH_WORKSPACE_MEMBER,
+ type: EventType.ADD_BATCH_PROJECT_MEMBER,
metadata: memberships.map(({ userId, id }) => ({
userId: userId || "",
membershipId: id,
@@ -141,7 +141,7 @@ export const registerProjectMembershipRouter = async (server: FastifyZodProvider
...req.auditLogInfo,
projectId: req.params.projectId,
event: {
- type: EventType.REMOVE_WORKSPACE_MEMBER,
+ type: EventType.REMOVE_PROJECT_MEMBER,
metadata: {
userId: membership.userId,
email: ""
diff --git a/backend/src/server/routes/v2/project-router.ts b/backend/src/server/routes/v2/deprecated-project-router.ts
similarity index 92%
rename from backend/src/server/routes/v2/project-router.ts
rename to backend/src/server/routes/v2/deprecated-project-router.ts
index 8b90913645..7c1045855b 100644
--- a/backend/src/server/routes/v2/project-router.ts
+++ b/backend/src/server/routes/v2/deprecated-project-router.ts
@@ -35,7 +35,8 @@ const projectWithEnv = SanitizedProjectSchema.extend({
kmsSecretManagerKeyId: z.string().nullable().optional()
});
-export const registerProjectRouter = async (server: FastifyZodProvider) => {
+export const registerDeprecatedProjectRouter = async (server: FastifyZodProvider) => {
+ // depreciated
/* Get project key */
server.route({
method: "GET",
@@ -46,7 +47,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
schema: {
description: "Return encrypted project key",
params: z.object({
- workspaceId: z.string().trim().describe(PROJECTS.GET_KEY.workspaceId)
+ workspaceId: z.string().trim().describe(PROJECTS.GET_KEY.projectId)
}),
response: {
200: ProjectKeysSchema.merge(
@@ -72,7 +73,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
...req.auditLogInfo,
projectId: req.params.workspaceId,
event: {
- type: EventType.GET_WORKSPACE_KEY,
+ type: EventType.GET_PROJECT_KEY,
metadata: {
keyId: key?.id as string
}
@@ -83,68 +84,6 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
});
- /* Start upgrade of a project */
- server.route({
- method: "POST",
- url: "/:projectId/upgrade",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- projectId: z.string().trim()
- }),
- body: z.object({
- userPrivateKey: z.string().trim()
- }),
- response: {
- 200: z.void()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- await server.services.project.upgradeProject({
- actorId: req.permission.id,
- actorOrgId: req.permission.orgId,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- projectId: req.params.projectId,
- userPrivateKey: req.body.userPrivateKey
- });
- }
- });
-
- /* Get upgrade status of project */
- server.route({
- url: "/:projectId/upgrade/status",
- method: "GET",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- projectId: z.string().trim()
- }),
- response: {
- 200: z.object({
- status: z.string().nullable()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const status = await server.services.project.getProjectUpgradeStatus({
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId: req.params.projectId,
- actor: req.permission.type,
- actorId: req.permission.id
- });
-
- return { status };
- }
- });
-
/* Create new project */
server.route({
method: "POST",
@@ -186,8 +125,8 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
actor: req.permission.type,
actorOrgId: req.permission.orgId,
actorAuthMethod: req.permission.authMethod,
- workspaceName: req.body.projectName,
- workspaceDescription: req.body.projectDescription,
+ projectName: req.body.projectName,
+ projectDescription: req.body.projectDescription,
slug: req.body.slug,
kmsKeyId: req.body.kmsKeyId,
template: req.body.template,
@@ -224,6 +163,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
});
/* Delete a project by slug */
+ // moved to DELETE /v1/projects/slug/:slug
server.route({
method: "DELETE",
url: "/:slug",
@@ -276,6 +216,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
});
/* Get a project by slug */
+ // moved to GET /v1/projects/slug/:slug
server.route({
method: "GET",
url: "/:slug",
@@ -337,7 +278,6 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
200: SanitizedProjectSchema
}
},
-
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
const project = await server.services.project.updateProject({
diff --git a/backend/src/server/routes/v2/index.ts b/backend/src/server/routes/v2/index.ts
index 93c422d153..aade29bb70 100644
--- a/backend/src/server/routes/v2/index.ts
+++ b/backend/src/server/routes/v2/index.ts
@@ -1,13 +1,15 @@
import { registerCaRouter } from "./certificate-authority-router";
-import { registerGroupProjectRouter } from "./group-project-router";
+import { registerDeprecatedGroupProjectRouter } from "./deprecated-group-project-router";
+import { registerDeprecatedIdentityProjectRouter } from "./deprecated-identity-project-router";
+import { registerDeprecatedProjectMembershipRouter } from "./deprecated-project-membership-router";
+import { registerDeprecatedProjectRouter } from "./deprecated-project-router";
import { registerIdentityOrgRouter } from "./identity-org-router";
-import { registerIdentityProjectRouter } from "./identity-project-router";
import { registerMfaRouter } from "./mfa-router";
import { registerOrgRouter } from "./organization-router";
import { registerPasswordRouter } from "./password-router";
import { registerPkiTemplatesRouter } from "./pki-templates-router";
-import { registerProjectMembershipRouter } from "./project-membership-router";
-import { registerProjectRouter } from "./project-router";
+import { registerSecretFolderRouter } from "./secret-folder-router";
+import { registerSecretImportRouter } from "./secret-import-router";
import { registerServiceTokenRouter } from "./service-token-router";
import { registerUserRouter } from "./user-router";
@@ -32,12 +34,17 @@ export const registerV2Routes = async (server: FastifyZodProvider) => {
},
{ prefix: "/organizations" }
);
+
+ await server.register(registerSecretFolderRouter, { prefix: "/folders" });
+ await server.register(registerSecretImportRouter, { prefix: "/secret-imports" });
+
+ // moved to v1/projects
await server.register(
async (projectServer) => {
- await projectServer.register(registerProjectRouter);
- await projectServer.register(registerIdentityProjectRouter);
- await projectServer.register(registerGroupProjectRouter);
- await projectServer.register(registerProjectMembershipRouter);
+ await projectServer.register(registerDeprecatedProjectRouter);
+ await projectServer.register(registerDeprecatedIdentityProjectRouter);
+ await projectServer.register(registerDeprecatedGroupProjectRouter);
+ await projectServer.register(registerDeprecatedProjectMembershipRouter);
},
{ prefix: "/workspace" }
);
diff --git a/backend/src/server/routes/v1/secret-folder-router.ts b/backend/src/server/routes/v2/secret-folder-router.ts
similarity index 80%
rename from backend/src/server/routes/v1/secret-folder-router.ts
rename to backend/src/server/routes/v2/secret-folder-router.ts
index 8712591479..0bf0624521 100644
--- a/backend/src/server/routes/v1/secret-folder-router.ts
+++ b/backend/src/server/routes/v2/secret-folder-router.ts
@@ -28,7 +28,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
}
],
body: z.object({
- workspaceId: z.string().trim().describe(FOLDERS.CREATE.workspaceId),
+ projectId: z.string().trim().describe(FOLDERS.CREATE.projectId),
environment: z.string().trim().describe(FOLDERS.CREATE.environment),
name: z
.string()
@@ -43,17 +43,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
.default("/")
.transform(prefixWithSlash) // Transformations get skipped if path is undefined
.transform(removeTrailingSlash)
- .describe(FOLDERS.CREATE.path)
- .optional(),
- // backward compatibility with cli
- directory: z
- .string()
- .trim()
- .default("/")
- .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
- .transform(removeTrailingSlash)
- .describe(FOLDERS.CREATE.directory)
- .optional(),
+ .describe(FOLDERS.CREATE.path),
description: z.string().optional().nullable().describe(FOLDERS.CREATE.description)
}),
response: {
@@ -66,27 +56,24 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const path = req.body.path || req.body.directory || "/";
const folder = await server.services.folder.createFolder({
actorId: req.permission.id,
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body,
- projectId: req.body.workspaceId,
- path,
description: req.body.description
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
event: {
type: EventType.CREATE_FOLDER,
metadata: {
environment: req.body.environment,
folderId: folder.id,
folderName: folder.name,
- folderPath: path,
+ folderPath: req.body.path,
...(req.body.description ? { description: req.body.description } : {})
}
}
@@ -115,7 +102,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
folderId: z.string().describe(FOLDERS.UPDATE.folderId)
}),
body: z.object({
- workspaceId: z.string().trim().describe(FOLDERS.UPDATE.workspaceId),
+ projectId: z.string().trim().describe(FOLDERS.UPDATE.projectId),
environment: z.string().trim().describe(FOLDERS.UPDATE.environment),
name: z
.string()
@@ -130,17 +117,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
.default("/")
.transform(prefixWithSlash) // Transformations get skipped if path is undefined
.transform(removeTrailingSlash)
- .describe(FOLDERS.UPDATE.path)
- .optional(),
- // backward compatibility with cli
- directory: z
- .string()
- .trim()
- .default("/")
- .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
- .transform(removeTrailingSlash)
- .describe(FOLDERS.UPDATE.directory)
- .optional(),
+ .describe(FOLDERS.UPDATE.path),
description: z.string().optional().nullable().describe(FOLDERS.UPDATE.description)
}),
response: {
@@ -153,26 +130,23 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const path = req.body.path || req.body.directory || "/";
const { folder, old } = await server.services.folder.updateFolder({
actorId: req.permission.id,
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body,
- projectId: req.body.workspaceId,
- id: req.params.folderId,
- path
+ id: req.params.folderId
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
event: {
type: EventType.UPDATE_FOLDER,
metadata: {
environment: req.body.environment,
folderId: folder.id,
- folderPath: path,
+ folderPath: req.body.path,
newFolderName: folder.name,
oldFolderName: old.name
}
@@ -198,7 +172,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
}
],
body: z.object({
- projectSlug: z.string().trim().describe(FOLDERS.UPDATE.projectSlug),
+ projectId: z.string().trim().describe(FOLDERS.UPDATE.projectId),
folders: z
.object({
id: z.string().describe(FOLDERS.UPDATE.folderId),
@@ -281,7 +255,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
folderIdOrName: z.string().describe(FOLDERS.DELETE.folderIdOrName)
}),
body: z.object({
- workspaceId: z.string().trim().describe(FOLDERS.DELETE.workspaceId),
+ projectId: z.string().trim().describe(FOLDERS.DELETE.projectId),
environment: z.string().trim().describe(FOLDERS.DELETE.environment),
path: z
.string()
@@ -290,16 +264,6 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
.transform(prefixWithSlash) // Transformations get skipped if path is undefined
.transform(removeTrailingSlash)
.describe(FOLDERS.DELETE.path)
- .optional(),
- // keep this here as cli need directory
- directory: z
- .string()
- .trim()
- .default("/")
- .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
- .transform(removeTrailingSlash)
- .describe(FOLDERS.DELETE.directory)
- .optional()
}),
response: {
200: z.object({
@@ -309,26 +273,23 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const path = req.body.path || req.body.directory || "/";
const folder = await server.services.folder.deleteFolder({
actorId: req.permission.id,
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body,
- projectId: req.body.workspaceId,
- idOrName: req.params.folderIdOrName,
- path
+ idOrName: req.params.folderIdOrName
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
event: {
type: EventType.DELETE_FOLDER,
metadata: {
environment: req.body.environment,
folderId: folder.id,
- folderPath: path,
+ folderPath: req.body.path,
folderName: folder.name
}
}
@@ -353,7 +314,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
}
],
querystring: z.object({
- workspaceId: z.string().trim().describe(FOLDERS.LIST.workspaceId),
+ projectId: z.string().trim().describe(FOLDERS.LIST.projectId),
environment: z.string().trim().describe(FOLDERS.LIST.environment),
lastSecretModified: z.string().datetime().trim().optional().describe(FOLDERS.LIST.lastSecretModified),
path: z
@@ -361,16 +322,7 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
.trim()
.transform(prefixWithSlash) // Transformations get skipped if path is undefined
.transform(removeTrailingSlash)
- .describe(FOLDERS.LIST.path)
- .optional(),
- // backward compatibility with cli
- directory: z
- .string()
- .trim()
- .transform(prefixWithSlash) // Transformations get skipped if directory is undefined
- .transform(removeTrailingSlash)
- .describe(FOLDERS.LIST.directory)
- .optional(),
+ .describe(FOLDERS.LIST.path),
recursive: booleanSchema.default(false).describe(FOLDERS.LIST.recursive)
}),
response: {
@@ -383,15 +335,12 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
- const path = req.query.path || req.query.directory || "/";
const folders = await server.services.folder.getFolders({
actorId: req.permission.id,
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- ...req.query,
- projectId: req.query.workspaceId,
- path
+ ...req.query
});
return { folders };
}
diff --git a/backend/src/server/routes/v1/secret-import-router.ts b/backend/src/server/routes/v2/secret-import-router.ts
similarity index 85%
rename from backend/src/server/routes/v1/secret-import-router.ts
rename to backend/src/server/routes/v2/secret-import-router.ts
index fca11f8a05..d9802c4b34 100644
--- a/backend/src/server/routes/v1/secret-import-router.ts
+++ b/backend/src/server/routes/v2/secret-import-router.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
-import { SecretImportsSchema, SecretsSchema } from "@app/db/schemas";
+import { SecretImportsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, SECRET_IMPORTS } from "@app/lib/api-docs";
import { removeTrailingSlash } from "@app/lib/fn";
@@ -27,7 +27,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
}
],
body: z.object({
- workspaceId: z.string().trim().describe(SECRET_IMPORTS.CREATE.workspaceId),
+ projectId: z.string().trim().describe(SECRET_IMPORTS.CREATE.projectId),
environment: z.string().trim().describe(SECRET_IMPORTS.CREATE.environment),
path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.CREATE.path),
import: z.object({
@@ -55,13 +55,13 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
data: req.body.import
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
event: {
type: EventType.CREATE_SECRET_IMPORT,
metadata: {
@@ -97,7 +97,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
secretImportId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.secretImportId)
}),
body: z.object({
- workspaceId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.workspaceId),
+ projectId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.projectId),
environment: z.string().trim().describe(SECRET_IMPORTS.UPDATE.environment),
path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.UPDATE.path),
import: z.object({
@@ -131,13 +131,13 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
actorOrgId: req.permission.orgId,
id: req.params.secretImportId,
...req.body,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
data: req.body.import
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
event: {
type: EventType.UPDATE_SECRET_IMPORT,
metadata: {
@@ -173,7 +173,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
secretImportId: z.string().trim().describe(SECRET_IMPORTS.DELETE.secretImportId)
}),
body: z.object({
- workspaceId: z.string().trim().describe(SECRET_IMPORTS.DELETE.workspaceId),
+ projectId: z.string().trim().describe(SECRET_IMPORTS.DELETE.projectId),
environment: z.string().trim().describe(SECRET_IMPORTS.DELETE.environment),
path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.DELETE.path)
}),
@@ -197,12 +197,12 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
actorOrgId: req.permission.orgId,
id: req.params.secretImportId,
...req.body,
- projectId: req.body.workspaceId
+ projectId: req.body.projectId
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.body.workspaceId,
+ projectId: req.body.projectId,
event: {
type: EventType.DELETE_SECRET_IMPORT,
metadata: {
@@ -236,7 +236,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
secretImportId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.secretImportId)
}),
body: z.object({
- workspaceId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.workspaceId),
+ projectId: z.string().trim().describe(SECRET_IMPORTS.UPDATE.projectId),
environment: z.string().trim().describe(SECRET_IMPORTS.UPDATE.environment),
path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.UPDATE.path)
}),
@@ -255,7 +255,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
actorOrgId: req.permission.orgId,
id: req.params.secretImportId,
...req.body,
- projectId: req.body.workspaceId
+ projectId: req.body.projectId
});
return { message };
@@ -278,7 +278,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
}
],
querystring: z.object({
- workspaceId: z.string().trim().describe(SECRET_IMPORTS.LIST.workspaceId),
+ projectId: z.string().trim().describe(SECRET_IMPORTS.LIST.projectId),
environment: z.string().trim().describe(SECRET_IMPORTS.LIST.environment),
path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.LIST.path)
}),
@@ -301,12 +301,12 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.query,
- projectId: req.query.workspaceId
+ projectId: req.query.projectId
});
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
- projectId: req.query.workspaceId,
+ projectId: req.query.projectId,
event: {
type: EventType.GET_SECRET_IMPORTS,
metadata: {
@@ -386,55 +386,11 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
config: {
rateLimit: secretsLimit
},
- schema: {
- querystring: z.object({
- workspaceId: z.string().trim(),
- environment: z.string().trim(),
- path: z.string().trim().default("/").transform(removeTrailingSlash)
- }),
- response: {
- 200: z.object({
- secrets: z
- .object({
- secretPath: z.string(),
- environment: z.string(),
- environmentInfo: z.object({
- id: z.string(),
- name: z.string(),
- slug: z.string()
- }),
- folderId: z.string().optional(),
- secrets: SecretsSchema.omit({ secretBlindIndex: true }).array()
- })
- .array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
- handler: async (req) => {
- const importedSecrets = await server.services.secretImport.getSecretsFromImports({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- ...req.query,
- projectId: req.query.workspaceId
- });
- return { secrets: importedSecrets };
- }
- });
-
- server.route({
- url: "/secrets/raw",
- method: "GET",
- config: {
- rateLimit: secretsLimit
- },
schema: {
hide: false,
tags: [ApiDocsTags.SecretImports],
querystring: z.object({
- workspaceId: z.string().trim(),
+ projectId: z.string().trim(),
environment: z.string().trim(),
path: z.string().trim().default("/").transform(removeTrailingSlash)
}),
@@ -463,8 +419,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
actor: req.permission.type,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
- ...req.query,
- projectId: req.query.workspaceId
+ ...req.query
});
return { secrets: importedSecrets };
}
diff --git a/backend/src/server/routes/v3/secret-router.ts b/backend/src/server/routes/v3/deprecated-secret-router.ts
similarity index 95%
rename from backend/src/server/routes/v3/secret-router.ts
rename to backend/src/server/routes/v3/deprecated-secret-router.ts
index ce0d4f188b..2a0d425d61 100644
--- a/backend/src/server/routes/v3/secret-router.ts
+++ b/backend/src/server/routes/v3/deprecated-secret-router.ts
@@ -39,7 +39,7 @@ const SecretReferenceNodeTree: z.ZodType<TSecretReferenceNode> = SecretReference
children: z.lazy(() => SecretReferenceNodeTree.array())
});
-export const registerSecretRouter = async (server: FastifyZodProvider) => {
+export const registerDeprecatedSecretRouter = async (server: FastifyZodProvider) => {
server.route({
method: "POST",
url: "/tags/:secretName",
@@ -230,7 +230,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
}
})
.describe(RAW_SECRETS.LIST.metadataFilter),
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.LIST.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.LIST.projectId),
workspaceSlug: z.string().trim().optional().describe(RAW_SECRETS.LIST.workspaceSlug),
environment: z.string().trim().optional().describe(RAW_SECRETS.LIST.environment),
secretPath: z.string().trim().default("/").transform(removeTrailingSlash).describe(RAW_SECRETS.LIST.secretPath),
@@ -298,7 +298,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
workspaceId = projectId;
}
- if (!workspaceId || !environment) throw new BadRequestError({ message: "Missing workspace id or environment" });
+ if (!workspaceId || !environment) throw new BadRequestError({ message: "Missing project id or environment" });
const { secrets, imports } = await server.services.secret.getSecretsRaw({
actorId: req.permission.id,
@@ -336,7 +336,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId,
+ projectId: workspaceId,
environment,
secretPath: req.query.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -405,7 +405,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretName: z.string().trim().describe(RAW_SECRETS.GET.secretName)
}),
querystring: z.object({
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.GET.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.GET.projectId),
workspaceSlug: z.string().trim().optional().describe(RAW_SECRETS.GET.workspaceSlug),
environment: z.string().trim().optional().describe(RAW_SECRETS.GET.environment),
secretPath: z.string().trim().default("/").transform(removeTrailingSlash).describe(RAW_SECRETS.GET.secretPath),
@@ -495,7 +495,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
distinctId: getTelemetryDistinctId(req),
properties: {
numberOfSecrets: 1,
- workspaceId: secret.workspace,
+ projectId: secret.workspace,
environment,
secretPath: req.query.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -526,7 +526,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretName: SecretNameSchema.describe(RAW_SECRETS.CREATE.secretName)
}),
body: z.object({
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.CREATE.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.CREATE.projectId),
projectSlug: z.string().trim().optional().describe(RAW_SECRETS.CREATE.projectSlug),
environment: z.string().trim().describe(RAW_SECRETS.CREATE.environment),
secretPath: z
@@ -627,7 +627,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretId: secret.id,
secretKey: req.params.secretName,
secretVersion: secret.version,
- secretMetadata: req.body.secretMetadata
+ secretMetadata: req.body.secretMetadata,
+ secretTags: secret.tags?.map((tag) => tag.name)
}
}
});
@@ -638,7 +639,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: 1,
- workspaceId: projectId,
+ projectId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -669,7 +670,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretName: BaseSecretNameSchema.describe(RAW_SECRETS.UPDATE.secretName)
}),
body: z.object({
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.projectId),
projectSlug: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.projectSlug),
environment: z.string().trim().describe(RAW_SECRETS.UPDATE.environment),
secretValue: z
@@ -780,7 +781,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretId: secret.id,
secretKey: req.params.secretName,
secretVersion: secret.version,
- secretMetadata: req.body.secretMetadata
+ secretMetadata: req.body.secretMetadata,
+ secretTags: secret.tags?.map((tag) => tag.name)
}
}
});
@@ -791,7 +793,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: 1,
- workspaceId: projectId,
+ projectId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -821,7 +823,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretName: z.string().min(1).describe(RAW_SECRETS.DELETE.secretName)
}),
body: z.object({
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.DELETE.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.DELETE.projectId),
projectSlug: z.string().trim().optional().describe(RAW_SECRETS.DELETE.projectSlug),
environment: z.string().trim().describe(RAW_SECRETS.DELETE.environment),
secretPath: z
@@ -909,7 +911,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: 1,
- workspaceId: projectId,
+ projectId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1017,7 +1019,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: req.query.workspaceId,
+ projectId: req.query.workspaceId,
environment: req.query.environment,
secretPath: req.query.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1097,7 +1099,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: 1,
- workspaceId: req.query.workspaceId,
+ projectId: req.query.workspaceId,
environment: req.query.environment,
secretPath: req.query.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1272,7 +1274,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: 1,
- workspaceId: req.body.workspaceId,
+ projectId: req.body.workspaceId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1466,7 +1468,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: 1,
- workspaceId: req.body.workspaceId,
+ projectId: req.body.workspaceId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1594,7 +1596,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: 1,
- workspaceId: req.body.workspaceId,
+ projectId: req.body.workspaceId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1781,7 +1783,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: req.body.workspaceId,
+ projectId: req.body.workspaceId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -1914,7 +1916,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: req.body.workspaceId,
+ projectId: req.body.workspaceId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -2039,7 +2041,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: req.body.workspaceId,
+ projectId: req.body.workspaceId,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -2067,7 +2069,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
],
body: z.object({
projectSlug: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.projectSlug),
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.projectId),
environment: z.string().trim().describe(RAW_SECRETS.CREATE.environment),
secretPath: z
.string()
@@ -2154,7 +2156,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretId: secret.id,
secretKey: secret.secretKey,
secretVersion: secret.version,
- secretMetadata: secretMetadataMap.get(secret.secretKey)
+ secretMetadata: secretMetadataMap.get(secret.secretKey),
+ secretTags: secret.tags?.map((tag) => tag.name)
}))
}
}
@@ -2166,7 +2169,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: secrets[0].workspace,
+ projectId: secrets[0].workspace,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -2194,7 +2197,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
],
body: z.object({
projectSlug: z.string().trim().optional().describe(RAW_SECRETS.DELETE.projectSlug),
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.DELETE.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.DELETE.projectId),
environment: z.string().trim().describe(RAW_SECRETS.UPDATE.environment),
secretPath: z
.string()
@@ -2288,7 +2291,6 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
return { approval: secretOperation.approval };
}
const { secrets } = secretOperation;
-
const secretMetadataMap = new Map(
inputSecrets.map(({ secretKey, secretMetadata }) => [secretKey, secretMetadata])
);
@@ -2308,7 +2310,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretPath: secret.secretPath,
secretKey: secret.secretKey,
secretVersion: secret.version,
- secretMetadata: secretMetadataMap.get(secret.secretKey)
+ secretMetadata: secretMetadataMap.get(secret.secretKey),
+ secretTags: secret.tags?.map((tag) => tag.name)
}))
}
}
@@ -2328,7 +2331,8 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
secretPath: secret.secretPath,
secretKey: secret.secretKey,
secretVersion: secret.version,
- secretMetadata: secretMetadataMap.get(secret.secretKey)
+ secretMetadata: secretMetadataMap.get(secret.secretKey),
+ secretTags: secret.tags?.map((tag) => tag.name)
}))
}
}
@@ -2341,7 +2345,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: secrets[0].workspace,
+ projectId: secrets[0].workspace,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -2369,7 +2373,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
],
body: z.object({
projectSlug: z.string().trim().optional().describe(RAW_SECRETS.DELETE.projectSlug),
- workspaceId: z.string().trim().optional().describe(RAW_SECRETS.DELETE.workspaceId),
+ workspaceId: z.string().trim().optional().describe(RAW_SECRETS.DELETE.projectId),
environment: z.string().trim().describe(RAW_SECRETS.DELETE.environment),
secretPath: z
.string()
@@ -2459,7 +2463,7 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
organizationId: req.permission.orgId,
properties: {
numberOfSecrets: secrets.length,
- workspaceId: secrets[0].workspace,
+ projectId: secrets[0].workspace,
environment: req.body.environment,
secretPath: req.body.secretPath,
channel: getUserAgentType(req.headers["user-agent"]),
@@ -2469,95 +2473,4 @@ export const registerSecretRouter = async (server: FastifyZodProvider) => {
return { secrets };
}
});
-
- server.route({
- method: "GET",
- url: "/raw/:secretName/secret-reference-tree",
- config: {
- rateLimit: secretsLimit
- },
- schema: {
- hide: false,
- tags: [ApiDocsTags.Secrets],
- description: "Get secret reference tree",
- security: [
- {
- bearerAuth: []
- }
- ],
- params: z.object({
- secretName: z.string().trim().describe(RAW_SECRETS.GET_REFERENCE_TREE.secretName)
- }),
- querystring: z.object({
- workspaceId: z.string().trim().describe(RAW_SECRETS.GET_REFERENCE_TREE.workspaceId),
- environment: z.string().trim().describe(RAW_SECRETS.GET_REFERENCE_TREE.environment),
- secretPath: z
- .string()
- .trim()
- .default("/")
- .transform(removeTrailingSlash)
- .describe(RAW_SECRETS.GET_REFERENCE_TREE.secretPath)
- }),
- response: {
- 200: z.object({
- tree: SecretReferenceNodeTree,
- value: z.string().optional()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { secretName } = req.params;
- const { secretPath, environment, workspaceId } = req.query;
- const { tree, value } = await server.services.secret.getSecretReferenceTree({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId: workspaceId,
- secretName,
- secretPath,
- environment
- });
-
- return { tree, value };
- }
- });
-
- server.route({
- method: "POST",
- url: "/backfill-secret-references",
- config: {
- rateLimit: secretsLimit
- },
- schema: {
- description: "Backfill secret references",
- security: [
- {
- bearerAuth: []
- }
- ],
- body: z.object({
- projectId: z.string().trim().min(1)
- }),
- response: {
- 200: z.object({
- message: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const { projectId } = req.body;
- const message = await server.services.secret.backfillSecretReferences({
- actorId: req.permission.id,
- actor: req.permission.type,
- actorAuthMethod: req.permission.authMethod,
- actorOrgId: req.permission.orgId,
- projectId
- });
-
- return message;
- }
- });
};
diff --git a/backend/src/server/routes/v3/index.ts b/backend/src/server/routes/v3/index.ts
index 1c31741a1f..d7fa94d6be 100644
--- a/backend/src/server/routes/v3/index.ts
+++ b/backend/src/server/routes/v3/index.ts
@@ -1,7 +1,6 @@
+import { registerDeprecatedSecretRouter } from "./deprecated-secret-router";
import { registerExternalMigrationRouter } from "./external-migration-router";
import { registerLoginRouter } from "./login-router";
-import { registerSecretBlindIndexRouter } from "./secret-blind-index-router";
-import { registerSecretRouter } from "./secret-router";
import { registerSignupRouter } from "./signup-router";
import { registerUserRouter } from "./user-router";
@@ -9,7 +8,6 @@ export const registerV3Routes = async (server: FastifyZodProvider) => {
await server.register(registerSignupRouter, { prefix: "/signup" });
await server.register(registerLoginRouter, { prefix: "/auth" });
await server.register(registerUserRouter, { prefix: "/users" });
- await server.register(registerSecretRouter, { prefix: "/secrets" });
- await server.register(registerSecretBlindIndexRouter, { prefix: "/workspaces" });
+ await server.register(registerDeprecatedSecretRouter, { prefix: "/secrets" });
await server.register(registerExternalMigrationRouter, { prefix: "/external-migration" });
};
diff --git a/backend/src/server/routes/v3/secret-blind-index-router.ts b/backend/src/server/routes/v3/secret-blind-index-router.ts
deleted file mode 100644
index cfb27a58e0..0000000000
--- a/backend/src/server/routes/v3/secret-blind-index-router.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { z } from "zod";
-
-import { SecretsSchema } from "@app/db/schemas";
-import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
-import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
-
-export const registerSecretBlindIndexRouter = async (server: FastifyZodProvider) => {
- server.route({
- method: "GET",
- url: "/:projectId/secrets/blind-index-status",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- projectId: z.string().trim()
- }),
- response: {
- 200: z.boolean()
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const count = await server.services.secretBlindIndex.getSecretBlindIndexStatus({
- projectId: req.params.projectId,
- actorAuthMethod: req.permission.authMethod,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId
- });
- return count === 0;
- }
- });
-
- server.route({
- method: "GET",
- url: "/:projectId/secrets",
- config: {
- rateLimit: readLimit
- },
- schema: {
- params: z.object({
- projectId: z.string().trim()
- }),
- response: {
- 200: z.object({
- secrets: SecretsSchema.omit({ secretBlindIndex: true })
- .merge(
- z.object({
- environment: z.string(),
- workspace: z.string()
- })
- )
- .array()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- const secrets = await server.services.secretBlindIndex.getProjectSecrets({
- projectId: req.params.projectId,
- actorAuthMethod: req.permission.authMethod,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId
- });
- return { secrets };
- }
- });
-
- server.route({
- method: "POST",
- url: "/:projectId/secrets/names",
- config: {
- rateLimit: writeLimit
- },
- schema: {
- params: z.object({
- projectId: z.string().trim()
- }),
- body: z.object({
- secretsToUpdate: z
- .object({
- secretName: z.string().trim(),
- secretId: z.string().trim()
- })
- .array()
- }),
- response: {
- 200: z.object({
- message: z.string()
- })
- }
- },
- onRequest: verifyAuth([AuthMode.JWT]),
- handler: async (req) => {
- await server.services.secretBlindIndex.updateProjectSecretName({
- projectId: req.params.projectId,
- secretsToUpdate: req.body.secretsToUpdate,
- actorAuthMethod: req.permission.authMethod,
- actorId: req.permission.id,
- actor: req.permission.type,
- actorOrgId: req.permission.orgId
- });
- return { message: "Successfully named workspace secrets" };
- }
- });
-};
diff --git a/backend/src/server/routes/v4/index.ts b/backend/src/server/routes/v4/index.ts
new file mode 100644
index 0000000000..db2e692223
--- /dev/null
+++ b/backend/src/server/routes/v4/index.ts
@@ -0,0 +1,5 @@
+import { registerSecretRouter } from "./secret-router";
+
+export const registerV4Routes = async (server: FastifyZodProvider) => {
+ await server.register(registerSecretRouter, { prefix: "/secrets" });
+};
diff --git a/backend/src/server/routes/v4/secret-router.ts b/backend/src/server/routes/v4/secret-router.ts
new file mode 100644
index 0000000000..e68bb87a4c
--- /dev/null
+++ b/backend/src/server/routes/v4/secret-router.ts
@@ -0,0 +1,1335 @@
+import picomatch from "picomatch";
+import { z } from "zod";
+
+import { SecretApprovalRequestsSchema, SecretType, ServiceTokenScopes } from "@app/db/schemas";
+import { EventType, SecretApprovalEvent, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
+import { ApiDocsTags, RAW_SECRETS } from "@app/lib/api-docs";
+import { BadRequestError } from "@app/lib/errors";
+import { removeTrailingSlash } from "@app/lib/fn";
+import { secretsLimit } from "@app/server/config/rateLimiter";
+import { BaseSecretNameSchema, SecretNameSchema } from "@app/server/lib/schemas";
+import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
+import { getUserAgentType } from "@app/server/plugins/audit-log";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { ActorType, AuthMode } from "@app/services/auth/auth-type";
+import { ResourceMetadataSchema } from "@app/services/resource-metadata/resource-metadata-schema";
+import { SecretProtectionType } from "@app/services/secret/secret-types";
+import { SecretUpdateMode } from "@app/services/secret-v2-bridge/secret-v2-bridge-types";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+import { SanitizedTagSchema, secretRawSchema } from "../sanitizedSchemas";
+
+const SecretReferenceNode = z.object({
+ key: z.string(),
+ value: z.string().optional(),
+ environment: z.string(),
+ secretPath: z.string()
+});
+
+const convertStringBoolean = (defaultValue: boolean = false) => {
+ return z
+ .enum(["true", "false"])
+ .default(defaultValue ? "true" : "false")
+ .transform((value) => value === "true");
+};
+
+type TSecretReferenceNode = z.infer<typeof SecretReferenceNode> & { children: TSecretReferenceNode[] };
+
+const SecretReferenceNodeTree: z.ZodType<TSecretReferenceNode> = SecretReferenceNode.extend({
+ children: z.lazy(() => SecretReferenceNodeTree.array())
+});
+
+export const registerSecretRouter = async (server: FastifyZodProvider) => {
+ server.route({
+ method: "GET",
+ url: "/",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "List secrets",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ querystring: z.object({
+ metadataFilter: z
+ .string()
+ .optional()
+ .transform((val) => {
+ if (!val) return undefined;
+
+ const result: { key?: string; value?: string }[] = [];
+ const pairs = val.split("|");
+
+ for (const pair of pairs) {
+ const keyValuePair: { key?: string; value?: string } = {};
+ const parts = pair.split(/[,=]/);
+
+ for (let i = 0; i < parts.length; i += 2) {
+ const identifier = parts[i].trim().toLowerCase();
+ const value = parts[i + 1]?.trim();
+
+ if (identifier === "key" && value) {
+ keyValuePair.key = value;
+ } else if (identifier === "value" && value) {
+ keyValuePair.value = value;
+ }
+ }
+
+ if (keyValuePair.key && keyValuePair.value) {
+ result.push(keyValuePair);
+ }
+ }
+
+ return result.length ? result : undefined;
+ })
+ .superRefine((metadata, ctx) => {
+ if (metadata && !Array.isArray(metadata)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message:
+ "Invalid secretMetadata format. Correct format is key=value1,value=value2|key=value3,value=value4."
+ });
+ }
+
+ if (metadata) {
+ if (metadata.length > 10) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "You can only filter by up to 10 metadata fields"
+ });
+ }
+
+ for (const item of metadata) {
+ if (!item.key && !item.value) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message:
+ "Invalid secretMetadata format, key or value must be provided. Correct format is key=value1,value=value2|key=value3,value=value4."
+ });
+ }
+ }
+ }
+ })
+ .describe(RAW_SECRETS.LIST.metadataFilter),
+ projectId: z.string().trim().optional().describe(RAW_SECRETS.LIST.projectId),
+ environment: z.string().trim().optional().describe(RAW_SECRETS.LIST.environment),
+ secretPath: z.string().trim().default("/").transform(removeTrailingSlash).describe(RAW_SECRETS.LIST.secretPath),
+ viewSecretValue: convertStringBoolean(true).describe(RAW_SECRETS.LIST.viewSecretValue),
+ expandSecretReferences: convertStringBoolean().describe(RAW_SECRETS.LIST.expand),
+ recursive: convertStringBoolean().describe(RAW_SECRETS.LIST.recursive),
+ include_imports: convertStringBoolean().describe(RAW_SECRETS.LIST.includeImports),
+ tagSlugs: z
+ .string()
+ .describe(RAW_SECRETS.LIST.tagSlugs)
+ .optional()
+ // split by comma and trim the strings
+ .transform((el) => (el ? el.split(",").map((i) => i.trim()) : []))
+ }),
+ response: {
+ 200: z.object({
+ secrets: secretRawSchema
+ .extend({
+ secretPath: z.string().optional(),
+ secretValueHidden: z.boolean(),
+ secretMetadata: ResourceMetadataSchema.optional(),
+ tags: SanitizedTagSchema.array().optional()
+ })
+ .array(),
+ imports: z
+ .object({
+ secretPath: z.string(),
+ environment: z.string(),
+ folderId: z.string().optional(),
+ secrets: secretRawSchema
+ .omit({ createdAt: true, updatedAt: true })
+ .extend({
+ secretValueHidden: z.boolean(),
+ secretMetadata: ResourceMetadataSchema.optional()
+ })
+ .array()
+ })
+ .array()
+ .optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ // just for delivery hero usecase
+ let { secretPath, environment, projectId } = req.query;
+ if (req.auth.actor === ActorType.SERVICE) {
+ const scope = ServiceTokenScopes.parse(req.auth.serviceToken.scopes);
+ const isSingleScope = scope.length === 1;
+ if (isSingleScope && !picomatch.scan(scope[0].secretPath).isGlob) {
+ secretPath = scope[0].secretPath;
+ environment = scope[0].environment;
+ projectId = req.auth.serviceToken.projectId;
+ }
+ }
+
+ if (!projectId || !environment) throw new BadRequestError({ message: "Missing project id or environment" });
+
+ const { secrets, imports } = await server.services.secret.getSecretsRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ environment,
+ expandSecretReferences: req.query.expandSecretReferences,
+ actorAuthMethod: req.permission.authMethod,
+ projectId,
+ viewSecretValue: req.query.viewSecretValue,
+ path: secretPath,
+ metadataFilter: req.query.metadataFilter,
+ includeImports: req.query.include_imports,
+ recursive: req.query.recursive,
+ tagSlugs: req.query.tagSlugs
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.GET_SECRETS,
+ metadata: {
+ environment,
+ secretPath: req.query.secretPath,
+ numberOfSecrets: secrets.length
+ }
+ }
+ });
+
+ if (getUserAgentType(req.headers["user-agent"]) !== UserAgentType.K8_OPERATOR) {
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretPulled,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ numberOfSecrets: secrets.length,
+ projectId,
+ environment,
+ secretPath: req.query.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+ }
+
+ return { secrets, imports };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/id/:secretId",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ params: z.object({
+ secretId: z.string()
+ }),
+ response: {
+ 200: z.object({
+ secret: secretRawSchema.extend({
+ secretPath: z.string(),
+ tags: SanitizedTagSchema.array().optional(),
+ secretMetadata: ResourceMetadataSchema.optional()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { secretId } = req.params;
+ const secret = await server.services.secret.getSecretByIdRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ secretId
+ });
+
+ return { secret };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:secretName",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Get a secret by name",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretName: z.string().trim().describe(RAW_SECRETS.GET.secretName)
+ }),
+ querystring: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.GET.projectId),
+ environment: z.string().trim().optional().describe(RAW_SECRETS.GET.environment),
+ secretPath: z.string().trim().default("/").transform(removeTrailingSlash).describe(RAW_SECRETS.GET.secretPath),
+ version: z.coerce.number().optional().describe(RAW_SECRETS.GET.version),
+ type: z.nativeEnum(SecretType).default(SecretType.Shared).describe(RAW_SECRETS.GET.type),
+ viewSecretValue: convertStringBoolean(true).describe(RAW_SECRETS.GET.viewSecretValue),
+ expandSecretReferences: convertStringBoolean().describe(RAW_SECRETS.GET.expand),
+ include_imports: convertStringBoolean().describe(RAW_SECRETS.GET.includeImports)
+ }),
+ response: {
+ 200: z.object({
+ secret: secretRawSchema.extend({
+ secretValueHidden: z.boolean(),
+ secretPath: z.string(),
+ tags: SanitizedTagSchema.array().optional(),
+ secretMetadata: ResourceMetadataSchema.optional()
+ })
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ let { secretPath, environment, projectId } = req.query;
+ if (req.auth.actor === ActorType.SERVICE) {
+ const scope = ServiceTokenScopes.parse(req.auth.serviceToken.scopes);
+ const isSingleScope = scope.length === 1;
+ if (isSingleScope && !picomatch.scan(scope[0].secretPath).isGlob) {
+ secretPath = scope[0].secretPath;
+ environment = scope[0].environment;
+ projectId = req.auth.serviceToken.projectId;
+ }
+ }
+
+ if (!environment) throw new BadRequestError({ message: "Missing environment" });
+ if (!projectId) {
+ throw new BadRequestError({ message: "You must provide workspaceId" });
+ }
+
+ const secret = await server.services.secret.getSecretByNameRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ expandSecretReferences: req.query.expandSecretReferences,
+ environment,
+ projectId,
+ viewSecretValue: req.query.viewSecretValue,
+ path: secretPath,
+ secretName: req.params.secretName,
+ type: req.query.type,
+ includeImports: req.query.include_imports,
+ version: req.query.version
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.GET_SECRET,
+ metadata: {
+ environment,
+ secretPath: req.query.secretPath,
+ secretId: secret.id,
+ secretKey: req.params.secretName,
+ secretVersion: secret.version,
+ secretMetadata: secret.secretMetadata
+ }
+ }
+ });
+
+ if (getUserAgentType(req.headers["user-agent"]) !== UserAgentType.K8_OPERATOR) {
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretPulled,
+ organizationId: req.permission.orgId,
+ distinctId: getTelemetryDistinctId(req),
+ properties: {
+ numberOfSecrets: 1,
+ projectId,
+ environment,
+ secretPath: req.query.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+ }
+ return { secret };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/:secretName",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Create secret",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretName: SecretNameSchema.describe(RAW_SECRETS.CREATE.secretName)
+ }),
+ body: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.CREATE.projectId),
+ environment: z.string().trim().describe(RAW_SECRETS.CREATE.environment),
+ secretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.CREATE.secretPath),
+ secretValue: z
+ .string()
+ .transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim()))
+ .describe(RAW_SECRETS.CREATE.secretValue),
+ secretComment: z.string().trim().optional().default("").describe(RAW_SECRETS.CREATE.secretComment),
+ secretMetadata: ResourceMetadataSchema.optional(),
+ tagIds: z.string().array().optional().describe(RAW_SECRETS.CREATE.tagIds),
+ skipMultilineEncoding: z.boolean().optional().describe(RAW_SECRETS.CREATE.skipMultilineEncoding),
+ type: z.nativeEnum(SecretType).default(SecretType.Shared).describe(RAW_SECRETS.CREATE.type),
+ secretReminderRepeatDays: z
+ .number()
+ .optional()
+ .nullable()
+ .describe(RAW_SECRETS.CREATE.secretReminderRepeatDays),
+ secretReminderNote: z
+ .string()
+ .max(1024, "Secret reminder note cannot exceed 1024 characters")
+ .optional()
+ .nullable()
+ .describe(RAW_SECRETS.CREATE.secretReminderNote)
+ }),
+ response: {
+ 200: z.union([
+ z.object({
+ secret: secretRawSchema
+ }),
+ z.object({ approval: SecretApprovalRequestsSchema }).describe("When secret protection policy is enabled")
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretOperation = await server.services.secret.createSecretRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ environment: req.body.environment,
+ actorAuthMethod: req.permission.authMethod,
+ projectId: req.body.projectId,
+ secretPath: req.body.secretPath,
+ secretName: req.params.secretName,
+ type: req.body.type,
+ secretValue: req.body.secretValue,
+ skipMultilineEncoding: req.body.skipMultilineEncoding,
+ secretComment: req.body.secretComment,
+ secretMetadata: req.body.secretMetadata,
+ tagIds: req.body.tagIds,
+ secretReminderNote: req.body.secretReminderNote,
+ secretReminderRepeatDays: req.body.secretReminderRepeatDays
+ });
+ if (secretOperation.type === SecretProtectionType.Approval) {
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.SECRET_APPROVAL_REQUEST,
+ metadata: {
+ committedBy: secretOperation.approval.committerUserId,
+ secretApprovalRequestId: secretOperation.approval.id,
+ secretApprovalRequestSlug: secretOperation.approval.slug,
+ secretPath: req.body.secretPath,
+ environment: req.body.environment,
+ secretKey: req.params.secretName,
+ eventType: SecretApprovalEvent.Create
+ }
+ }
+ });
+
+ return { approval: secretOperation.approval };
+ }
+
+ const { secret } = secretOperation;
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.CREATE_SECRET,
+ metadata: {
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ secretId: secret.id,
+ secretKey: req.params.secretName,
+ secretVersion: secret.version,
+ secretMetadata: req.body.secretMetadata,
+ secretTags: secret.tags?.map((tag) => tag.name)
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretCreated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ numberOfSecrets: 1,
+ projectId: req.body.projectId,
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+
+ return { secret };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/:secretName",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Update secret",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretName: BaseSecretNameSchema.describe(RAW_SECRETS.UPDATE.secretName)
+ }),
+ body: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.UPDATE.projectId),
+ environment: z.string().trim().describe(RAW_SECRETS.UPDATE.environment),
+ secretValue: z
+ .string()
+ .transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim()))
+ .optional()
+ .describe(RAW_SECRETS.UPDATE.secretValue),
+ secretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.UPDATE.secretPath),
+ skipMultilineEncoding: z.boolean().optional().describe(RAW_SECRETS.UPDATE.skipMultilineEncoding),
+ type: z.nativeEnum(SecretType).default(SecretType.Shared).describe(RAW_SECRETS.UPDATE.type),
+ tagIds: z.string().array().optional().describe(RAW_SECRETS.UPDATE.tagIds),
+ metadata: z.record(z.string()).optional(),
+ secretMetadata: ResourceMetadataSchema.optional(),
+ secretReminderNote: z
+ .string()
+ .max(1024, "Secret reminder note cannot exceed 1024 characters")
+ .optional()
+ .nullable()
+ .describe(RAW_SECRETS.UPDATE.secretReminderNote),
+ secretReminderRepeatDays: z
+ .number()
+ .optional()
+ .nullable()
+ .describe(RAW_SECRETS.UPDATE.secretReminderRepeatDays),
+ secretReminderRecipients: z.string().array().optional().describe(RAW_SECRETS.UPDATE.secretReminderRecipients),
+ newSecretName: SecretNameSchema.optional().describe(RAW_SECRETS.UPDATE.newSecretName),
+ secretComment: z.string().optional().describe(RAW_SECRETS.UPDATE.secretComment)
+ }),
+ response: {
+ 200: z.union([
+ z.object({
+ secret: secretRawSchema.extend({
+ secretValueHidden: z.boolean()
+ })
+ }),
+ z.object({ approval: SecretApprovalRequestsSchema }).describe("When secret protection policy is enabled")
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretOperation = await server.services.secret.updateSecretRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId,
+ actorAuthMethod: req.permission.authMethod,
+ environment: req.body.environment,
+ projectId: req.body.projectId,
+ secretPath: req.body.secretPath,
+ secretName: req.params.secretName,
+ type: req.body.type,
+ secretValue: req.body.secretValue,
+ skipMultilineEncoding: req.body.skipMultilineEncoding,
+ tagIds: req.body.tagIds,
+ secretReminderRepeatDays: req.body.secretReminderRepeatDays,
+ secretReminderRecipients: req.body.secretReminderRecipients,
+ secretReminderNote: req.body.secretReminderNote,
+ metadata: req.body.metadata,
+ newSecretName: req.body.newSecretName,
+ secretComment: req.body.secretComment,
+ secretMetadata: req.body.secretMetadata
+ });
+
+ if (secretOperation.type === SecretProtectionType.Approval) {
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.SECRET_APPROVAL_REQUEST,
+ metadata: {
+ committedBy: secretOperation.approval.committerUserId,
+ secretApprovalRequestId: secretOperation.approval.id,
+ secretApprovalRequestSlug: secretOperation.approval.slug,
+ secretPath: req.body.secretPath,
+ environment: req.body.environment,
+ secretKey: req.params.secretName,
+ eventType: SecretApprovalEvent.Update
+ }
+ }
+ });
+
+ return { approval: secretOperation.approval };
+ }
+ const { secret } = secretOperation;
+
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.UPDATE_SECRET,
+ metadata: {
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ secretId: secret.id,
+ secretKey: req.params.secretName,
+ secretVersion: secret.version,
+ secretMetadata: req.body.secretMetadata,
+ secretTags: secret.tags?.map((tag) => tag.name)
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretUpdated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ numberOfSecrets: 1,
+ projectId: req.body.projectId,
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+ return { secret };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/:secretName",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Delete secret",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretName: z.string().min(1).describe(RAW_SECRETS.DELETE.secretName)
+ }),
+ body: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.DELETE.projectId),
+ environment: z.string().trim().describe(RAW_SECRETS.DELETE.environment),
+ secretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.DELETE.secretPath),
+ type: z.nativeEnum(SecretType).default(SecretType.Shared).describe(RAW_SECRETS.DELETE.type)
+ }),
+ response: {
+ 200: z.union([
+ z.object({
+ secret: secretRawSchema.extend({
+ secretValueHidden: z.boolean()
+ })
+ }),
+ z.object({ approval: SecretApprovalRequestsSchema }).describe("When secret protection policy is enabled")
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const secretOperation = await server.services.secret.deleteSecretRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ environment: req.body.environment,
+ projectId: req.body.projectId,
+ secretPath: req.body.secretPath,
+ secretName: req.params.secretName,
+ type: req.body.type
+ });
+ if (secretOperation.type === SecretProtectionType.Approval) {
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.SECRET_APPROVAL_REQUEST,
+ metadata: {
+ committedBy: secretOperation.approval.committerUserId,
+ secretApprovalRequestId: secretOperation.approval.id,
+ secretApprovalRequestSlug: secretOperation.approval.slug,
+ secretPath: req.body.secretPath,
+ environment: req.body.environment,
+ secretKey: req.params.secretName,
+ eventType: SecretApprovalEvent.Delete
+ }
+ }
+ });
+
+ return { approval: secretOperation.approval };
+ }
+
+ const { secret } = secretOperation;
+
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.DELETE_SECRET,
+ metadata: {
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ secretId: secret.id,
+ secretKey: req.params.secretName,
+ secretVersion: secret.version
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretDeleted,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ numberOfSecrets: 1,
+ projectId: req.body.projectId,
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+
+ return { secret };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/move",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ body: z.object({
+ projectId: z.string().trim(),
+ sourceEnvironment: z.string().trim(),
+ sourceSecretPath: z.string().trim().default("/").transform(removeTrailingSlash),
+ destinationEnvironment: z.string().trim(),
+ destinationSecretPath: z.string().trim().default("/").transform(removeTrailingSlash),
+ secretIds: z.string().array(),
+ shouldOverwrite: z.boolean().default(false)
+ }),
+ response: {
+ 200: z.object({
+ isSourceUpdated: z.boolean(),
+ isDestinationUpdated: z.boolean()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { projectId, isSourceUpdated, isDestinationUpdated } = await server.services.secret.moveSecrets({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ ...req.body
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.MOVE_SECRETS,
+ metadata: {
+ sourceEnvironment: req.body.sourceEnvironment,
+ sourceSecretPath: req.body.sourceSecretPath,
+ destinationEnvironment: req.body.destinationEnvironment,
+ destinationSecretPath: req.body.destinationSecretPath,
+ secretIds: req.body.secretIds
+ }
+ }
+ });
+
+ return {
+ isSourceUpdated,
+ isDestinationUpdated
+ };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/batch",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Create many secrets",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.UPDATE.projectId),
+ environment: z.string().trim().describe(RAW_SECRETS.CREATE.environment),
+ secretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.CREATE.secretPath),
+ secrets: z
+ .object({
+ secretKey: SecretNameSchema.describe(RAW_SECRETS.CREATE.secretName),
+ secretValue: z
+ .string()
+ .transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim()))
+ .describe(RAW_SECRETS.CREATE.secretValue),
+ secretComment: z.string().trim().optional().default("").describe(RAW_SECRETS.CREATE.secretComment),
+ skipMultilineEncoding: z.boolean().optional().describe(RAW_SECRETS.CREATE.skipMultilineEncoding),
+ metadata: z.record(z.string()).optional(),
+ secretMetadata: ResourceMetadataSchema.optional(),
+ tagIds: z.string().array().optional().describe(RAW_SECRETS.CREATE.tagIds)
+ })
+ .array()
+ .min(1)
+ }),
+ response: {
+ 200: z.union([
+ z.object({
+ secrets: secretRawSchema.array()
+ }),
+ z.object({ approval: SecretApprovalRequestsSchema }).describe("When secret protection policy is enabled")
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { environment, secretPath, secrets: inputSecrets } = req.body;
+
+ const secretOperation = await server.services.secret.createManySecretsRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ secretPath,
+ environment,
+ projectId: req.body.projectId,
+ secrets: inputSecrets
+ });
+ if (secretOperation.type === SecretProtectionType.Approval) {
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.SECRET_APPROVAL_REQUEST,
+ metadata: {
+ committedBy: secretOperation.approval.committerUserId,
+ secretApprovalRequestId: secretOperation.approval.id,
+ secretApprovalRequestSlug: secretOperation.approval.slug,
+ secretPath,
+ environment,
+ secrets: inputSecrets.map((secret) => ({
+ secretKey: secret.secretKey
+ })),
+ eventType: SecretApprovalEvent.CreateMany
+ }
+ }
+ });
+ return { approval: secretOperation.approval };
+ }
+ const { secrets } = secretOperation;
+
+ const secretMetadataMap = new Map(
+ inputSecrets.map(({ secretKey, secretMetadata }) => [secretKey, secretMetadata])
+ );
+
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.CREATE_SECRETS,
+ metadata: {
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ secrets: secrets.map((secret) => ({
+ secretId: secret.id,
+ secretKey: secret.secretKey,
+ secretVersion: secret.version,
+ secretMetadata: secretMetadataMap.get(secret.secretKey),
+ secretTags: secret.tags?.map((tag) => tag.name)
+ }))
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretCreated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ numberOfSecrets: secrets.length,
+ projectId: req.body.projectId,
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+ return { secrets };
+ }
+ });
+
+ server.route({
+ method: "PATCH",
+ url: "/batch",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Update many secrets",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.DELETE.projectId),
+ environment: z.string().trim().describe(RAW_SECRETS.UPDATE.environment),
+ secretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.UPDATE.secretPath),
+ mode: z
+ .nativeEnum(SecretUpdateMode)
+ .optional()
+ .default(SecretUpdateMode.FailOnNotFound)
+ .describe(RAW_SECRETS.UPDATE.mode),
+ secrets: z
+ .object({
+ secretKey: SecretNameSchema.describe(RAW_SECRETS.UPDATE.secretName),
+ secretValue: z
+ .string()
+ .transform((val) => (val.at(-1) === "\n" ? `${val.trim()}\n` : val.trim()))
+ .optional()
+ .describe(RAW_SECRETS.UPDATE.secretValue),
+ secretPath: z
+ .string()
+ .trim()
+ .transform(removeTrailingSlash)
+ .optional()
+ .describe(RAW_SECRETS.UPDATE.secretPath),
+ secretComment: z.string().trim().optional().describe(RAW_SECRETS.UPDATE.secretComment),
+ skipMultilineEncoding: z.boolean().optional().describe(RAW_SECRETS.UPDATE.skipMultilineEncoding),
+ newSecretName: SecretNameSchema.optional().describe(RAW_SECRETS.UPDATE.newSecretName),
+ tagIds: z.string().array().optional().describe(RAW_SECRETS.UPDATE.tagIds),
+ secretReminderNote: z
+ .string()
+ .max(1024, "Secret reminder note cannot exceed 1024 characters")
+ .optional()
+ .nullable()
+ .describe(RAW_SECRETS.UPDATE.secretReminderNote),
+ secretMetadata: ResourceMetadataSchema.optional(),
+ secretReminderRepeatDays: z
+ .number()
+ .optional()
+ .nullable()
+ .describe(RAW_SECRETS.UPDATE.secretReminderRepeatDays)
+ })
+ .array()
+ .min(1)
+ }),
+ response: {
+ 200: z.union([
+ z.object({
+ secrets: secretRawSchema.extend({ secretValueHidden: z.boolean() }).array()
+ }),
+ z.object({ approval: SecretApprovalRequestsSchema }).describe("When secret protection policy is enabled")
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { environment, secretPath, secrets: inputSecrets } = req.body;
+ const secretOperation = await server.services.secret.updateManySecretsRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ secretPath,
+ environment,
+ projectId: req.body.projectId,
+ secrets: inputSecrets,
+ mode: req.body.mode
+ });
+ if (secretOperation.type === SecretProtectionType.Approval) {
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.SECRET_APPROVAL_REQUEST,
+ metadata: {
+ committedBy: secretOperation.approval.committerUserId,
+ secretApprovalRequestId: secretOperation.approval.id,
+ secretApprovalRequestSlug: secretOperation.approval.slug,
+ secretPath,
+ environment,
+ secrets: inputSecrets.map((secret) => ({
+ secretKey: secret.secretKey,
+ secretPath: secret.secretPath
+ })),
+ eventType: SecretApprovalEvent.UpdateMany
+ }
+ }
+ });
+ return { approval: secretOperation.approval };
+ }
+ const { secrets } = secretOperation;
+
+ const secretMetadataMap = new Map(
+ inputSecrets.map(({ secretKey, secretMetadata }) => [secretKey, secretMetadata])
+ );
+
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.UPDATE_SECRETS,
+ metadata: {
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ secrets: secrets
+ .filter((el) => el.version > 1)
+ .map((secret) => ({
+ secretId: secret.id,
+ secretPath: secret.secretPath,
+ secretKey: secret.secretKey,
+ secretVersion: secret.version,
+ secretMetadata: secretMetadataMap.get(secret.secretKey),
+ secretTags: secret.tags?.map((tag) => tag.name)
+ }))
+ }
+ }
+ });
+ const createdSecrets = secrets.filter((el) => el.version === 1);
+ if (createdSecrets.length) {
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.CREATE_SECRETS,
+ metadata: {
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ secrets: createdSecrets.map((secret) => ({
+ secretId: secret.id,
+ secretPath: secret.secretPath,
+ secretKey: secret.secretKey,
+ secretVersion: secret.version,
+ secretMetadata: secretMetadataMap.get(secret.secretKey)
+ }))
+ }
+ }
+ });
+ }
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretUpdated,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ numberOfSecrets: secrets.length,
+ projectId: req.body.projectId,
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+ return { secrets };
+ }
+ });
+
+ server.route({
+ method: "DELETE",
+ url: "/batch",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Delete many secrets",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.DELETE.projectId),
+ environment: z.string().trim().describe(RAW_SECRETS.DELETE.environment),
+ secretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.DELETE.secretPath),
+ secrets: z
+ .object({
+ secretKey: z.string().describe(RAW_SECRETS.DELETE.secretName),
+ type: z.nativeEnum(SecretType).default(SecretType.Shared)
+ })
+ .array()
+ .min(1)
+ }),
+ response: {
+ 200: z.union([
+ z.object({
+ secrets: secretRawSchema
+ .extend({
+ secretValueHidden: z.boolean()
+ })
+ .array()
+ }),
+ z.object({ approval: SecretApprovalRequestsSchema }).describe("When secret protection policy is enabled")
+ ])
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const { environment, secretPath, secrets: inputSecrets } = req.body;
+ const secretOperation = await server.services.secret.deleteManySecretsRaw({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ environment,
+ secretPath,
+ projectId: req.body.projectId,
+ secrets: inputSecrets
+ });
+ if (secretOperation.type === SecretProtectionType.Approval) {
+ await server.services.auditLog.createAuditLog({
+ projectId: req.body.projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.SECRET_APPROVAL_REQUEST,
+ metadata: {
+ committedBy: secretOperation.approval.committerUserId,
+ secretApprovalRequestId: secretOperation.approval.id,
+ secretApprovalRequestSlug: secretOperation.approval.slug,
+ secretPath,
+ environment,
+ secrets: inputSecrets.map((secret) => ({
+ secretKey: secret.secretKey
+ })),
+ eventType: SecretApprovalEvent.DeleteMany
+ }
+ }
+ });
+
+ return { approval: secretOperation.approval };
+ }
+ const { secrets } = secretOperation;
+
+ await server.services.auditLog.createAuditLog({
+ projectId: secrets[0].workspace,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.DELETE_SECRETS,
+ metadata: {
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ secrets: secrets.map((secret) => ({
+ secretId: secret.id,
+ secretKey: secret.secretKey,
+ secretVersion: secret.version
+ }))
+ }
+ }
+ });
+
+ await server.services.telemetry.sendPostHogEvents({
+ event: PostHogEventTypes.SecretDeleted,
+ distinctId: getTelemetryDistinctId(req),
+ organizationId: req.permission.orgId,
+ properties: {
+ numberOfSecrets: secrets.length,
+ projectId: secrets[0].workspace,
+ environment: req.body.environment,
+ secretPath: req.body.secretPath,
+ channel: getUserAgentType(req.headers["user-agent"]),
+ ...req.auditLogInfo
+ }
+ });
+ return { secrets };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:secretName/secret-reference-tree",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ hide: false,
+ tags: [ApiDocsTags.Secrets],
+ description: "Get secret reference tree",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ secretName: z.string().trim().describe(RAW_SECRETS.GET_REFERENCE_TREE.secretName)
+ }),
+ querystring: z.object({
+ projectId: z.string().trim().describe(RAW_SECRETS.GET_REFERENCE_TREE.projectId),
+ environment: z.string().trim().describe(RAW_SECRETS.GET_REFERENCE_TREE.environment),
+ secretPath: z
+ .string()
+ .trim()
+ .default("/")
+ .transform(removeTrailingSlash)
+ .describe(RAW_SECRETS.GET_REFERENCE_TREE.secretPath)
+ }),
+ response: {
+ 200: z.object({
+ tree: SecretReferenceNodeTree,
+ value: z.string().optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { secretName } = req.params;
+ const { secretPath, environment, projectId } = req.query;
+ const { tree, value, secret } = await server.services.secret.getSecretReferenceTree({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId,
+ secretName,
+ secretPath,
+ environment
+ });
+
+ await server.services.auditLog.createAuditLog({
+ projectId,
+ ...req.auditLogInfo,
+ event: {
+ type: EventType.GET_SECRET,
+ metadata: {
+ environment,
+ secretPath,
+ secretId: secret.id,
+ secretKey: secretName,
+ secretVersion: secret.version
+ }
+ }
+ });
+
+ return { tree, value };
+ }
+ });
+
+ server.route({
+ method: "POST",
+ url: "/backfill-secret-references",
+ config: {
+ rateLimit: secretsLimit
+ },
+ schema: {
+ description: "Backfill secret references",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ body: z.object({
+ projectId: z.string().trim().min(1)
+ }),
+ response: {
+ 200: z.object({
+ message: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const { projectId } = req.body;
+ const message = await server.services.secret.backfillSecretReferences({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ projectId
+ });
+
+ return message;
+ }
+ });
+};
diff --git a/backend/src/services/app-connection/app-connection-dal.ts b/backend/src/services/app-connection/app-connection-dal.ts
index f74f7cf068..10b6a62742 100644
--- a/backend/src/services/app-connection/app-connection-dal.ts
+++ b/backend/src/services/app-connection/app-connection-dal.ts
@@ -1,11 +1,115 @@
+import { Knex } from "knex";
+
import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
+import { TableName, TAppConnections } from "@app/db/schemas";
+import { buildFindFilter, ormify, prependTableNameToFindFilter, selectAllTableCols } from "@app/lib/knex";
+import { transformUsageToProjects } from "@app/services/app-connection/app-connection-fns";
export type TAppConnectionDALFactory = ReturnType<typeof appConnectionDALFactory>;
+type AppConnectionFindFilter = Parameters<typeof buildFindFilter<TAppConnections>>[0];
+
export const appConnectionDALFactory = (db: TDbClient) => {
const appConnectionOrm = ormify(db, TableName.AppConnection);
- return { ...appConnectionOrm };
+ const findWithProjectDetails = async (filter: AppConnectionFindFilter, tx?: Knex) => {
+ const query = (tx || db.replicaNode())(TableName.AppConnection)
+ .leftJoin(TableName.Project, `${TableName.AppConnection}.projectId`, `${TableName.Project}.id`)
+ .select(selectAllTableCols(TableName.AppConnection))
+ .select(
+ // project
+ db.ref("name").withSchema(TableName.Project).as("projectName"),
+ db.ref("type").withSchema(TableName.Project).as("projectType"),
+ db.ref("slug").withSchema(TableName.Project).as("projectSlug")
+ );
+
+ if (filter) {
+ /* eslint-disable @typescript-eslint/no-misused-promises */
+ void query.where(buildFindFilter(prependTableNameToFindFilter(TableName.AppConnection, filter)));
+ }
+
+ const connections = await query;
+
+ return connections.map(({ projectName, projectSlug, projectType, projectId, ...connection }) => ({
+ ...connection,
+ projectId,
+ project: projectId
+ ? {
+ name: projectName,
+ type: projectType,
+ slug: projectSlug,
+ id: projectId
+ }
+ : null
+ }));
+ };
+
+ const findAppConnectionUsageById = async (connectionId: string, tx?: Knex) => {
+ const secretSyncs = await (tx || db.replicaNode())(TableName.SecretSync)
+ .where(`${TableName.SecretSync}.connectionId`, connectionId)
+ .join(TableName.Project, `${TableName.SecretSync}.projectId`, `${TableName.Project}.id`)
+ .select(
+ db.ref("name").withSchema(TableName.SecretSync),
+ db.ref("id").withSchema(TableName.SecretSync),
+ db.ref("projectId").withSchema(TableName.SecretSync),
+ db.ref("name").as("projectName").withSchema(TableName.Project),
+ db.ref("slug").as("projectSlug").withSchema(TableName.Project),
+ db.ref("type").as("projectType").withSchema(TableName.Project)
+ );
+
+ const secretRotations = await (tx || db.replicaNode())(TableName.SecretRotationV2)
+ .where(`${TableName.SecretRotationV2}.connectionId`, connectionId)
+ .join(TableName.SecretFolder, `${TableName.SecretRotationV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .join(TableName.Project, `${TableName.Environment}.projectId`, `${TableName.Project}.id`)
+ .select(
+ db.ref("name").withSchema(TableName.SecretRotationV2),
+ db.ref("id").withSchema(TableName.SecretRotationV2),
+ db.ref("id").as("projectId").withSchema(TableName.Project),
+ db.ref("name").as("projectName").withSchema(TableName.Project),
+ db.ref("slug").as("projectSlug").withSchema(TableName.Project),
+ db.ref("type").as("projectType").withSchema(TableName.Project)
+ );
+
+ const externalCas = await (tx || db.replicaNode())(TableName.ExternalCertificateAuthority)
+ .where(`${TableName.ExternalCertificateAuthority}.appConnectionId`, connectionId)
+ .orWhere(`${TableName.ExternalCertificateAuthority}.dnsAppConnectionId`, connectionId)
+ .join(
+ TableName.CertificateAuthority,
+ `${TableName.ExternalCertificateAuthority}.caId`,
+ `${TableName.CertificateAuthority}.id`
+ )
+ .join(TableName.Project, `${TableName.CertificateAuthority}.projectId`, `${TableName.Project}.id`)
+ .select(
+ db.ref("name").withSchema(TableName.CertificateAuthority),
+ db.ref("id").withSchema(TableName.ExternalCertificateAuthority),
+ db.ref("appConnectionId").withSchema(TableName.ExternalCertificateAuthority),
+ db.ref("dnsAppConnectionId").withSchema(TableName.ExternalCertificateAuthority),
+ db.ref("id").as("projectId").withSchema(TableName.Project),
+ db.ref("name").as("projectName").withSchema(TableName.Project),
+ db.ref("slug").as("projectSlug").withSchema(TableName.Project),
+ db.ref("type").as("projectType").withSchema(TableName.Project)
+ );
+
+ const dataSources = await (tx || db.replicaNode())(TableName.SecretScanningDataSource)
+ .where(`${TableName.SecretScanningDataSource}.connectionId`, connectionId)
+ .join(TableName.Project, `${TableName.SecretScanningDataSource}.projectId`, `${TableName.Project}.id`)
+ .select(
+ db.ref("name").withSchema(TableName.SecretScanningDataSource),
+ db.ref("id").withSchema(TableName.SecretScanningDataSource),
+ db.ref("id").as("projectId").withSchema(TableName.Project),
+ db.ref("name").as("projectName").withSchema(TableName.Project),
+ db.ref("slug").as("projectSlug").withSchema(TableName.Project),
+ db.ref("type").as("projectType").withSchema(TableName.Project)
+ );
+
+ return transformUsageToProjects({
+ secretSyncs,
+ secretRotations,
+ dataSources,
+ externalCas
+ });
+ };
+
+ return { ...appConnectionOrm, findAppConnectionUsageById, findWithProjectDetails };
};
diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts
index 5aacab1b1d..f88b5a3574 100644
--- a/backend/src/services/app-connection/app-connection-fns.ts
+++ b/backend/src/services/app-connection/app-connection-fns.ts
@@ -1,3 +1,4 @@
+import { ProjectType } from "@app/db/schemas";
import { TAppConnections } from "@app/db/schemas/app-connections";
import {
getOCIConnectionListItem,
@@ -8,6 +9,8 @@ import { getOracleDBConnectionListItem, OracleDBConnectionMethod } from "@app/ee
import { TGatewayServiceFactory } from "@app/ee/services/gateway/gateway-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { SECRET_ROTATION_CONNECTION_MAP } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-maps";
+import { SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP } from "@app/ee/services/secret-scanning-v2/secret-scanning-v2-maps";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
import { APP_CONNECTION_NAME_MAP, APP_CONNECTION_PLAN_MAP } from "@app/services/app-connection/app-connection-maps";
@@ -16,6 +19,7 @@ import {
validateSqlConnectionCredentials
} from "@app/services/app-connection/shared/sql";
import { KmsDataKey } from "@app/services/kms/kms-types";
+import { SECRET_SYNC_CONNECTION_MAP } from "@app/services/secret-sync/secret-sync-maps";
import {
getOnePassConnectionListItem,
@@ -133,7 +137,22 @@ import {
} from "./windmill";
import { getZabbixConnectionListItem, validateZabbixConnectionCredentials, ZabbixConnectionMethod } from "./zabbix";
-export const listAppConnectionOptions = () => {
+const SECRET_SYNC_APP_CONNECTION_MAP = Object.fromEntries(
+ Object.entries(SECRET_SYNC_CONNECTION_MAP).map(([key, value]) => [value, key])
+);
+
+const SECRET_ROTATION_APP_CONNECTION_MAP = Object.fromEntries(
+ Object.entries(SECRET_ROTATION_CONNECTION_MAP).map(([key, value]) => [value, key])
+);
+
+const SECRET_SCANNING_APP_CONNECTION_MAP = Object.fromEntries(
+ Object.entries(SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP).map(([key, value]) => [value, key])
+);
+
+// scott: ideally this would be derived from a utilized map like the above
+const PKI_APP_CONNECTIONS = [AppConnection.AWS, AppConnection.Cloudflare, AppConnection.AzureADCS];
+
+export const listAppConnectionOptions = (projectType?: ProjectType) => {
return [
getAwsConnectionListItem(),
getGitHubConnectionListItem(),
@@ -173,22 +192,51 @@ export const listAppConnectionOptions = () => {
getDigitalOceanConnectionListItem(),
getNetlifyConnectionListItem(),
getOktaConnectionListItem()
- ].sort((a, b) => a.name.localeCompare(b.name));
+ ]
+ .filter((option) => {
+ switch (projectType) {
+ case ProjectType.SecretManager:
+ return (
+ Boolean(SECRET_SYNC_APP_CONNECTION_MAP[option.app]) ||
+ Boolean(SECRET_ROTATION_APP_CONNECTION_MAP[option.app])
+ );
+ case ProjectType.SecretScanning:
+ return Boolean(SECRET_SCANNING_APP_CONNECTION_MAP[option.app]);
+ case ProjectType.CertificateManager:
+ return PKI_APP_CONNECTIONS.includes(option.app);
+ case ProjectType.KMS:
+ return false;
+ case ProjectType.SSH:
+ return false;
+ default:
+ return true;
+ }
+ })
+ .sort((a, b) => a.name.localeCompare(b.name));
};
export const encryptAppConnectionCredentials = async ({
orgId,
credentials,
- kmsService
+ kmsService,
+ projectId
}: {
orgId: string;
credentials: TAppConnection["credentials"];
kmsService: TAppConnectionServiceFactoryDep["kmsService"];
+ projectId: string | null | undefined;
}) => {
- const { encryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId
- });
+ const { encryptor } = await kmsService.createCipherPairWithDataKey(
+ projectId
+ ? {
+ type: KmsDataKey.SecretManager,
+ projectId
+ }
+ : {
+ type: KmsDataKey.Organization,
+ orgId
+ }
+ );
const { cipherTextBlob: encryptedCredentialsBlob } = encryptor({
plainText: Buffer.from(JSON.stringify(credentials))
@@ -200,16 +248,22 @@ export const encryptAppConnectionCredentials = async ({
export const decryptAppConnectionCredentials = async ({
orgId,
encryptedCredentials,
- kmsService
+ kmsService,
+ projectId
}: {
orgId: string;
encryptedCredentials: Buffer;
kmsService: TAppConnectionServiceFactoryDep["kmsService"];
+ projectId: string | null | undefined;
}) => {
- const { decryptor } = await kmsService.createCipherPairWithDataKey({
- type: KmsDataKey.Organization,
- orgId
- });
+ const { decryptor } = await kmsService.createCipherPairWithDataKey(
+ projectId
+ ? { type: KmsDataKey.SecretManager, projectId }
+ : {
+ type: KmsDataKey.Organization,
+ orgId
+ }
+ );
const decryptedPlainTextBlob = decryptor({
cipherTextBlob: encryptedCredentials
@@ -343,6 +397,7 @@ export const decryptAppConnection = async (
credentials: await decryptAppConnectionCredentials({
encryptedCredentials: appConnection.encryptedCredentials,
orgId: appConnection.orgId,
+ projectId: appConnection.projectId,
kmsService
}),
credentialsHash: crypto.nativeCrypto.createHash("sha256").update(appConnection.encryptedCredentials).digest("hex")
@@ -413,3 +468,73 @@ export const enterpriseAppCheck = async (
});
}
};
+
+type Resource = {
+ name: string;
+ id: string;
+ projectId: string;
+ projectName: string;
+ projectSlug: string;
+ projectType: string;
+};
+
+type UsageData = {
+ secretSyncs: Resource[];
+ secretRotations: Resource[];
+ dataSources: Resource[];
+ externalCas: Resource[];
+};
+
+type ResourceSummary = {
+ name: string;
+ id: string;
+};
+
+type ProjectWithResources = {
+ id: string;
+ name: string;
+ slug: string;
+ type: ProjectType;
+ resources: {
+ secretSyncs: ResourceSummary[];
+ secretRotations: ResourceSummary[];
+ dataSources: ResourceSummary[];
+ externalCas: (ResourceSummary & { appConnectionId?: string; dnsAppConnectionId?: string })[];
+ };
+};
+
+export const transformUsageToProjects = (data: UsageData): ProjectWithResources[] => {
+ const projectMap = new Map<string, ProjectWithResources>();
+
+ Object.entries(data).forEach(([resourceType, resources]) => {
+ resources.forEach((resource) => {
+ const { projectId, projectName, projectSlug, projectType, name, id, ...rest } = resource;
+
+ const projectKey = projectId;
+
+ if (!projectMap.has(projectKey)) {
+ projectMap.set(projectKey, {
+ id: projectId,
+ name: projectName,
+ slug: projectSlug,
+ type: projectType as ProjectType,
+ resources: {
+ secretSyncs: [],
+ secretRotations: [],
+ dataSources: [],
+ externalCas: []
+ }
+ });
+ }
+
+ const project = projectMap.get(projectKey)!;
+ project.resources[resourceType as keyof ProjectWithResources["resources"]].push({
+ name,
+ id,
+ ...rest
+ });
+ });
+ });
+
+ return Array.from(projectMap.values());
+};
diff --git a/backend/src/services/app-connection/app-connection-schemas.ts b/backend/src/services/app-connection/app-connection-schemas.ts
index d0dcb1a546..3f6e3914a7 100644
--- a/backend/src/services/app-connection/app-connection-schemas.ts
+++ b/backend/src/services/app-connection/app-connection-schemas.ts
@@ -13,7 +13,15 @@ export const BaseAppConnectionSchema = AppConnectionsSchema.omit({
app: true,
method: true
}).extend({
- credentialsHash: z.string().optional()
+ credentialsHash: z.string().optional(),
+ project: z
+ .object({
+ name: z.string(),
+ id: z.string(),
+ type: z.string(),
+ slug: z.string()
+ })
+ .nullish()
});
export const GenericCreateAppConnectionFieldsSchema = (
@@ -28,6 +36,7 @@ export const GenericCreateAppConnectionFieldsSchema = (
.max(256, "Description cannot exceed 256 characters")
.nullish()
.describe(AppConnections.CREATE(app).description),
+ projectId: z.string().optional().describe(AppConnections.CREATE(app).projectId),
isPlatformManagedCredentials: supportsPlatformManagedCredentials
? z.boolean().optional().default(false).describe(AppConnections.CREATE(app).isPlatformManagedCredentials)
: z
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index f5654d2fb9..19d66b9fd8 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -1,5 +1,6 @@
import { ForbiddenError, subject } from "@casl/ability";
+import { ActionProjectType, TAppConnections } from "@app/db/schemas";
import { ValidateOCIConnectionCredentialsSchema } from "@app/ee/services/app-connections/oci";
import { ociConnectionService } from "@app/ee/services/app-connections/oci/oci-connection-service";
import { ValidateOracleDBConnectionCredentialsSchema } from "@app/ee/services/app-connections/oracledb";
@@ -14,6 +15,10 @@ import {
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionAppConnectionActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
import { crypto } from "@app/lib/crypto/cryptography";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
@@ -27,9 +32,8 @@ import {
TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM,
validateAppConnectionCredentials
} from "@app/services/app-connection/app-connection-fns";
-import { auth0ConnectionService } from "@app/services/app-connection/auth0/auth0-connection-service";
-import { githubRadarConnectionService } from "@app/services/app-connection/github-radar/github-radar-connection-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
import { ValidateOnePassConnectionCredentialsSchema } from "./1password";
import { onePassConnectionService } from "./1password/1password-connection-service";
@@ -41,10 +45,13 @@ import {
TAppConnectionConfig,
TAppConnectionRaw,
TCreateAppConnectionDTO,
+ TGetAppConnectionByNameDTO,
TUpdateAppConnectionDTO,
- TValidateAppConnectionCredentialsSchema
+ TValidateAppConnectionCredentialsSchema,
+ TValidateAppConnectionUsageByIdDTO
} from "./app-connection-types";
import { ValidateAuth0ConnectionCredentialsSchema } from "./auth0";
+import { auth0ConnectionService } from "./auth0/auth0-connection-service";
import { ValidateAwsConnectionCredentialsSchema } from "./aws";
import { awsConnectionService } from "./aws/aws-connection-service";
import { ValidateAzureADCSConnectionCredentialsSchema } from "./azure-adcs/azure-adcs-connection-schemas";
@@ -73,6 +80,7 @@ import { gcpConnectionService } from "./gcp/gcp-connection-service";
import { ValidateGitHubConnectionCredentialsSchema } from "./github";
import { githubConnectionService } from "./github/github-connection-service";
import { ValidateGitHubRadarConnectionCredentialsSchema } from "./github-radar";
+import { githubRadarConnectionService } from "./github-radar/github-radar-connection-service";
import { ValidateGitLabConnectionCredentialsSchema } from "./gitlab";
import { gitlabConnectionService } from "./gitlab/gitlab-connection-service";
import { ValidateHCVaultConnectionCredentialsSchema } from "./hc-vault";
@@ -108,13 +116,14 @@ import { zabbixConnectionService } from "./zabbix/zabbix-connection-service";
export type TAppConnectionServiceFactoryDep = {
appConnectionDAL: TAppConnectionDALFactory;
- permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
+ permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getProjectPermission">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayDAL: Pick<TGatewayDALFactory, "find">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "find">;
+ projectDAL: Pick<TProjectDALFactory, "findProjectById">;
};
export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;
@@ -168,29 +177,64 @@ export const appConnectionServiceFactory = ({
gatewayService,
gatewayV2Service,
gatewayDAL,
- gatewayV2DAL
+ gatewayV2DAL,
+ projectDAL
}: TAppConnectionServiceFactoryDep) => {
- const listAppConnectionsByOrg = async (actor: OrgServiceActor, app?: AppConnection) => {
- const { permission } = await permissionService.getOrgPermission(
- actor.type,
- actor.id,
- actor.orgId,
- actor.authMethod,
- actor.orgId
- );
+ const listAppConnections = async (actor: OrgServiceActor, app?: AppConnection, projectId?: string) => {
+ let appConnections: TAppConnections[];
+
+ if (projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Read,
- OrgPermissionSubjects.AppConnections
- );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Read,
+ ProjectPermissionSub.AppConnections
+ );
- const appConnections = await appConnectionDAL.find(
- app
- ? { orgId: actor.orgId, app }
- : {
- orgId: actor.orgId
- }
- );
+ appConnections = (
+ await appConnectionDAL.findWithProjectDetails({
+ projectId,
+ ...(app ? { app } : {})
+ })
+ ).filter((appConnection) =>
+ permission.can(
+ ProjectPermissionAppConnectionActions.Read,
+ subject(ProjectPermissionSub.AppConnections, { connectionId: appConnection.id })
+ )
+ );
+ } else {
+ const { permission } = await permissionService.getOrgPermission(
+ actor.type,
+ actor.id,
+ actor.orgId,
+ actor.authMethod,
+ actor.orgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Read,
+ OrgPermissionSubjects.AppConnections
+ );
+
+ appConnections = (
+ await appConnectionDAL.findWithProjectDetails({
+ orgId: actor.orgId,
+ ...(app ? { app } : {})
+ })
+ ).filter((appConnection) =>
+ permission.can(
+ OrgPermissionAppConnectionActions.Read,
+ subject(OrgPermissionSubjects.AppConnections, { connectionId: appConnection.id })
+ )
+ );
+ }
return Promise.all(
appConnections
@@ -204,18 +248,34 @@ export const appConnectionServiceFactory = ({
if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
- const { permission } = await permissionService.getOrgPermission(
- actor.type,
- actor.id,
- actor.orgId,
- actor.authMethod,
- appConnection.orgId
- );
+ if (appConnection.projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: appConnection.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Read,
- OrgPermissionSubjects.AppConnections
- );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Read,
+ subject(ProjectPermissionSub.AppConnections, { connectionId })
+ );
+ } else {
+ const { permission } = await permissionService.getOrgPermission(
+ actor.type,
+ actor.id,
+ actor.orgId,
+ actor.authMethod,
+ appConnection.orgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Read,
+ subject(OrgPermissionSubjects.AppConnections, { connectionId })
+ );
+ }
if (appConnection.app !== app)
throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });
@@ -223,24 +283,49 @@ export const appConnectionServiceFactory = ({
return decryptAppConnection(appConnection, kmsService);
};
- const findAppConnectionByName = async (app: AppConnection, connectionName: string, actor: OrgServiceActor) => {
- const appConnection = await appConnectionDAL.findOne({ name: connectionName, orgId: actor.orgId });
+ const findAppConnectionByName = async (
+ app: AppConnection,
+ { connectionName, projectId }: TGetAppConnectionByNameDTO,
+ actor: OrgServiceActor
+ ) => {
+ const appConnection = await appConnectionDAL.findOne({
+ name: connectionName,
+ ...(projectId ? { projectId } : { orgId: actor.orgId, projectId: null })
+ });
if (!appConnection)
- throw new NotFoundError({ message: `Could not find App Connection with name ${connectionName}` });
+ throw new NotFoundError({
+ message: `Could not find App Connection with name ${connectionName} in ${projectId ? "project" : "organization"} scope.`
+ });
- const { permission } = await permissionService.getOrgPermission(
- actor.type,
- actor.id,
- actor.orgId,
- actor.authMethod,
- appConnection.orgId
- );
+ if (appConnection.projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: appConnection.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Read,
- OrgPermissionSubjects.AppConnections
- );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Read,
+ subject(ProjectPermissionSub.AppConnections, { connectionId: appConnection.id })
+ );
+ } else {
+ const { permission } = await permissionService.getOrgPermission(
+ actor.type,
+ actor.id,
+ actor.orgId,
+ actor.authMethod,
+ appConnection.orgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Read,
+ subject(OrgPermissionSubjects.AppConnections, { connectionId: appConnection.id })
+ );
+ }
if (appConnection.app !== app)
throw new BadRequestError({ message: `App Connection with name ${connectionName} is not for App "${app}"` });
@@ -249,10 +334,10 @@ export const appConnectionServiceFactory = ({
};
const createAppConnection = async (
- { method, app, credentials, gatewayId, ...params }: TCreateAppConnectionDTO,
+ { method, app, credentials, gatewayId, projectId, ...params }: TCreateAppConnectionDTO,
actor: OrgServiceActor
) => {
- const { permission } = await permissionService.getOrgPermission(
+ const { permission: orgPermission } = await permissionService.getOrgPermission(
actor.type,
actor.id,
actor.orgId,
@@ -260,13 +345,33 @@ export const appConnectionServiceFactory = ({
actor.orgId
);
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Create,
- OrgPermissionSubjects.AppConnections
- );
+ if (projectId) {
+ const project = await projectDAL.findProjectById(projectId);
+
+ if (!project) throw new BadRequestError({ message: `Could not find project with ID ${projectId}` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
- if (gatewayId) {
ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Create,
+ ProjectPermissionSub.AppConnections
+ );
+ } else {
+ ForbiddenError.from(orgPermission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Create,
+ OrgPermissionSubjects.AppConnections
+ );
+ }
+
+ if (gatewayId) {
+ ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionGatewayActions.AttachGateways,
OrgPermissionSubjects.Gateway
);
@@ -304,7 +409,8 @@ export const appConnectionServiceFactory = ({
const encryptedCredentials = await encryptAppConnectionCredentials({
credentials: connectionCredentials,
orgId: actor.orgId,
- kmsService
+ kmsService,
+ projectId
});
return appConnectionDAL.create({
@@ -313,6 +419,7 @@ export const appConnectionServiceFactory = ({
method,
app,
gatewayId,
+ projectId,
...params
});
};
@@ -365,7 +472,7 @@ export const appConnectionServiceFactory = ({
"Failed to update app connection due to plan restriction. Upgrade plan to access enterprise app connections."
);
- const { permission } = await permissionService.getOrgPermission(
+ const { permission: orgPermission } = await permissionService.getOrgPermission(
actor.type,
actor.id,
actor.orgId,
@@ -373,13 +480,29 @@ export const appConnectionServiceFactory = ({
appConnection.orgId
);
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Edit,
- OrgPermissionSubjects.AppConnections
- );
+ if (appConnection.projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: appConnection.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
- if (gatewayId !== appConnection.gatewayId) {
ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Edit,
+ subject(ProjectPermissionSub.AppConnections, { connectionId })
+ );
+ } else {
+ ForbiddenError.from(orgPermission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Edit,
+ subject(OrgPermissionSubjects.AppConnections, { connectionId })
+ );
+ }
+
+ if (gatewayId !== undefined && gatewayId !== appConnection.gatewayId) {
+ ForbiddenError.from(orgPermission).throwUnlessCan(
OrgPermissionGatewayActions.AttachGateways,
OrgPermissionSubjects.Gateway
);
@@ -441,7 +564,8 @@ export const appConnectionServiceFactory = ({
? await encryptAppConnectionCredentials({
credentials: connectionCredentials,
orgId: actor.orgId,
- kmsService
+ kmsService,
+ projectId: appConnection.projectId
})
: undefined;
@@ -491,18 +615,34 @@ export const appConnectionServiceFactory = ({
if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
- const { permission } = await permissionService.getOrgPermission(
- actor.type,
- actor.id,
- actor.orgId,
- actor.authMethod,
- appConnection.orgId
- );
+ if (appConnection.projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: appConnection.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
- ForbiddenError.from(permission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Delete,
- OrgPermissionSubjects.AppConnections
- );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Delete,
+ subject(ProjectPermissionSub.AppConnections, { connectionId })
+ );
+ } else {
+ const { permission } = await permissionService.getOrgPermission(
+ actor.type,
+ actor.id,
+ actor.orgId,
+ actor.authMethod,
+ appConnection.orgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Delete,
+ subject(OrgPermissionSubjects.AppConnections, { connectionId })
+ );
+ }
if (appConnection.app !== app)
throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });
@@ -544,18 +684,34 @@ export const appConnectionServiceFactory = ({
"Failed to connect app due to plan restriction. Upgrade plan to access enterprise app connections."
);
- const { permission: orgPermission } = await permissionService.getOrgPermission(
- actor.type,
- actor.id,
- appConnection.orgId,
- actor.authMethod,
- actor.orgId
- );
+ if (appConnection.projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId: appConnection.projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
- ForbiddenError.from(orgPermission).throwUnlessCan(
- OrgPermissionAppConnectionActions.Connect,
- subject(OrgPermissionSubjects.AppConnections, { connectionId: appConnection.id })
- );
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Connect,
+ subject(ProjectPermissionSub.AppConnections, { connectionId })
+ );
+ } else {
+ const { permission: orgPermission } = await permissionService.getOrgPermission(
+ actor.type,
+ actor.id,
+ appConnection.orgId,
+ actor.authMethod,
+ actor.orgId
+ );
+
+ ForbiddenError.from(orgPermission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Connect,
+ subject(OrgPermissionSubjects.AppConnections, { connectionId })
+ );
+ }
if (appConnection.app !== app)
throw new BadRequestError({
@@ -569,7 +725,23 @@ export const appConnectionServiceFactory = ({
return connection as T;
};
- const listAvailableAppConnectionsForUser = async (app: AppConnection, actor: OrgServiceActor) => {
+ const validateAppConnectionUsageById = async (
+ app: AppConnection,
+ { connectionId, projectId }: TValidateAppConnectionUsageByIdDTO,
+ actor: OrgServiceActor
+ ) => {
+ const appConnection = await connectAppConnectionById(app, connectionId, actor);
+
+ if (appConnection.projectId && appConnection.projectId !== projectId) {
+ throw new BadRequestError({
+ message: `You cannot connect project App Connection with ID "${appConnection.id}" from project with ID "${appConnection.projectId}" to project with ID "${projectId}"`
+ });
+ }
+
+ return appConnection;
+ };
+
+ const listAvailableAppConnectionsForUser = async (app: AppConnection, actor: OrgServiceActor, projectId?: string) => {
const { permission: orgPermission } = await permissionService.getOrgPermission(
actor.type,
actor.id,
@@ -578,28 +750,89 @@ export const appConnectionServiceFactory = ({
actor.orgId
);
- const appConnections = await appConnectionDAL.find({ app, orgId: actor.orgId });
+ let availableProjectConnections: TAppConnections[] = [];
+
+ if (projectId) {
+ const project = await projectDAL.findProjectById(projectId);
- const availableConnections = appConnections.filter((connection) =>
+ if (!project) throw new BadRequestError({ message: `Could not find project with ID ${projectId}` });
+
+ const { permission: projectPermission } = await permissionService.getProjectPermission({
+ actor: actor.type,
+ actorId: actor.id,
+ projectId,
+ actorAuthMethod: actor.authMethod,
+ actorOrgId: actor.orgId,
+ actionProjectType: ActionProjectType.Any
+ });
+
+ ForbiddenError.from(projectPermission).throwUnlessCan(
+ ProjectPermissionAppConnectionActions.Connect,
+ ProjectPermissionSub.AppConnections
+ );
+
+ const projectAppConnections = await appConnectionDAL.find({ app, projectId });
+
+ availableProjectConnections = projectAppConnections.filter((connection) =>
+ projectPermission.can(
+ ProjectPermissionAppConnectionActions.Connect,
+ subject(ProjectPermissionSub.AppConnections, { connectionId: connection.id })
+ )
+ );
+ }
+
+ const orgAppConnections = await appConnectionDAL.find({ app, orgId: actor.orgId, projectId: null });
+
+ const availableOrgConnections = orgAppConnections.filter((connection) =>
orgPermission.can(
OrgPermissionAppConnectionActions.Connect,
subject(OrgPermissionSubjects.AppConnections, { connectionId: connection.id })
)
);
- return availableConnections as Omit<TAppConnection, "credentials">[];
+ return [...availableOrgConnections, ...availableProjectConnections].sort((a, b) =>
+ a.name.toLowerCase().localeCompare(b.name.toLowerCase())
+ ) as Omit<TAppConnection, "credentials">[];
+ };
+
+ const findAppConnectionUsageById = async (app: AppConnection, connectionId: string, actor: OrgServiceActor) => {
+ const appConnection = await appConnectionDAL.findById(connectionId);
+
+ if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
+
+ const { permission } = await permissionService.getOrgPermission(
+ actor.type,
+ actor.id,
+ actor.orgId,
+ actor.authMethod,
+ appConnection.orgId
+ );
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ OrgPermissionAppConnectionActions.Read,
+ OrgPermissionSubjects.AppConnections
+ );
+
+ if (appConnection.app !== app)
+ throw new BadRequestError({ message: `App Connection with ID ${connectionId} is not for App "${app}"` });
+
+ const projectUsage = await appConnectionDAL.findAppConnectionUsageById(connectionId);
+
+ return projectUsage;
};
return {
listAppConnectionOptions,
- listAppConnectionsByOrg,
+ listAppConnections,
findAppConnectionById,
findAppConnectionByName,
createAppConnection,
updateAppConnection,
deleteAppConnection,
connectAppConnectionById,
+ validateAppConnectionUsageById,
listAvailableAppConnectionsForUser,
+ findAppConnectionUsageById,
github: githubConnectionService(connectAppConnectionById, gatewayService, gatewayV2Service),
githubRadar: githubRadarConnectionService(connectAppConnectionById),
gcp: gcpConnectionService(connectAppConnectionById),
diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.ts
index e4af79926f..600438fc98 100644
--- a/backend/src/services/app-connection/app-connection-types.ts
+++ b/backend/src/services/app-connection/app-connection-types.ts
@@ -316,13 +316,23 @@ export type TSqlConnectionInput =
export type TCreateAppConnectionDTO = Pick<
TAppConnectionInput,
- "credentials" | "method" | "name" | "app" | "description" | "isPlatformManagedCredentials" | "gatewayId"
+ "credentials" | "method" | "name" | "app" | "description" | "isPlatformManagedCredentials" | "gatewayId" | "projectId"
>;
-export type TUpdateAppConnectionDTO = Partial<Omit<TCreateAppConnectionDTO, "method" | "app">> & {
+export type TUpdateAppConnectionDTO = Partial<Omit<TCreateAppConnectionDTO, "method" | "app" | "projectId">> & {
connectionId: string;
};
+export type TGetAppConnectionByNameDTO = {
+ connectionName: string;
+ projectId?: string;
+};
+
+export type TValidateAppConnectionUsageByIdDTO = {
+ connectionId: string;
+ projectId: string;
+};
+
export type TAppConnectionConfig =
| TAwsConnectionConfig
| TGitHubConnectionConfig
diff --git a/backend/src/services/app-connection/auth0/auth0-connection-fns.ts b/backend/src/services/app-connection/auth0/auth0-connection-fns.ts
index de4faf6836..944b1f69a3 100644
--- a/backend/src/services/app-connection/auth0/auth0-connection-fns.ts
+++ b/backend/src/services/app-connection/auth0/auth0-connection-fns.ts
@@ -51,7 +51,7 @@ const authorizeAuth0Connection = async ({
};
export const getAuth0ConnectionAccessToken = async (
- { id, orgId, credentials }: TAuth0Connection,
+ { id, orgId, credentials, projectId }: TAuth0Connection,
appConnectionDAL: Pick<TAppConnectionDALFactory, "updateById">,
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
) => {
@@ -72,7 +72,8 @@ export const getAuth0ConnectionAccessToken = async (
const encryptedCredentials = await encryptAppConnectionCredentials({
credentials: updatedCredentials,
orgId,
- kmsService
+ kmsService,
+ projectId
});
await appConnectionDAL.updateById(id, { encryptedCredentials });
diff --git a/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts b/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts
index 552bd89f5a..5e86f67402 100644
--- a/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts
+++ b/backend/src/services/app-connection/azure-adcs/azure-adcs-connection-fns.ts
@@ -352,7 +352,8 @@ export const getAzureADCSConnectionCredentials = async (
const credentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
kmsService,
- encryptedCredentials: appConnection.encryptedCredentials
+ encryptedCredentials: appConnection.encryptedCredentials,
+ projectId: appConnection.projectId
})) as {
username: string;
password: string;
diff --git a/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts b/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts
index 2614cfd12b..22cec0ae7e 100644
--- a/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts
+++ b/backend/src/services/app-connection/azure-client-secrets/azure-client-secrets-connection-fns.ts
@@ -57,6 +57,7 @@ export const getAzureConnectionAccessToken = async (
const credentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
kmsService,
+ projectId: appConnection.projectId,
encryptedCredentials: appConnection.encryptedCredentials
})) as TAzureClientSecretsConnectionCredentials;
@@ -93,6 +94,7 @@ export const getAzureConnectionAccessToken = async (
const encryptedCredentials = await encryptAppConnectionCredentials({
credentials: updatedCredentials,
orgId: appConnection.orgId,
+ projectId: appConnection.projectId,
kmsService
});
@@ -102,6 +104,7 @@ export const getAzureConnectionAccessToken = async (
case AzureClientSecretsConnectionMethod.ClientSecret:
const accessTokenCredentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
+ projectId: appConnection.projectId,
kmsService,
encryptedCredentials: appConnection.encryptedCredentials
})) as TAzureClientSecretsConnectionClientSecretCredentials;
@@ -129,6 +132,7 @@ export const getAzureConnectionAccessToken = async (
const encryptedClientCredentials = await encryptAppConnectionCredentials({
credentials: updatedClientCredentials,
orgId: appConnection.orgId,
+ projectId: appConnection.projectId,
kmsService
});
diff --git a/backend/src/services/app-connection/azure-devops/azure-devops-fns.ts b/backend/src/services/app-connection/azure-devops/azure-devops-fns.ts
index a3a9f10bd8..0bd2188ac8 100644
--- a/backend/src/services/app-connection/azure-devops/azure-devops-fns.ts
+++ b/backend/src/services/app-connection/azure-devops/azure-devops-fns.ts
@@ -70,7 +70,8 @@ export const getAzureDevopsConnection = async (
const oauthCredentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
kmsService,
- encryptedCredentials: appConnection.encryptedCredentials
+ encryptedCredentials: appConnection.encryptedCredentials,
+ projectId: appConnection.projectId
})) as TAzureDevOpsConnectionCredentials;
if (!("refreshToken" in oauthCredentials)) {
@@ -100,7 +101,8 @@ export const getAzureDevopsConnection = async (
const encryptedOAuthCredentials = await encryptAppConnectionCredentials({
credentials: updatedOAuthCredentials,
orgId: appConnection.orgId,
- kmsService
+ kmsService,
+ projectId: appConnection.projectId
});
await appConnectionDAL.updateById(appConnection.id, { encryptedCredentials: encryptedOAuthCredentials });
@@ -111,7 +113,8 @@ export const getAzureDevopsConnection = async (
const accessTokenCredentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
kmsService,
- encryptedCredentials: appConnection.encryptedCredentials
+ encryptedCredentials: appConnection.encryptedCredentials,
+ projectId: appConnection.projectId
})) as { accessToken: string };
if (!("accessToken" in accessTokenCredentials)) {
@@ -124,7 +127,8 @@ export const getAzureDevopsConnection = async (
const clientSecretCredentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
kmsService,
- encryptedCredentials: appConnection.encryptedCredentials
+ encryptedCredentials: appConnection.encryptedCredentials,
+ projectId: appConnection.projectId
})) as TAzureDevOpsConnectionClientSecretCredentials;
const { accessToken, expiresAt, clientId, clientSecret, tenantId: clientTenantId } = clientSecretCredentials;
@@ -153,7 +157,8 @@ export const getAzureDevopsConnection = async (
const encryptedClientCredentials = await encryptAppConnectionCredentials({
credentials: updatedClientCredentials,
orgId: appConnection.orgId,
- kmsService
+ kmsService,
+ projectId: appConnection.projectId
});
await appConnectionDAL.updateById(appConnection.id, { encryptedCredentials: encryptedClientCredentials });
diff --git a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
index d6a260050c..cd35838004 100644
--- a/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
+++ b/backend/src/services/app-connection/azure-key-vault/azure-key-vault-connection-fns.ts
@@ -58,7 +58,8 @@ export const getAzureConnectionAccessToken = async (
const oauthCredentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
kmsService,
- encryptedCredentials: appConnection.encryptedCredentials
+ encryptedCredentials: appConnection.encryptedCredentials,
+ projectId: appConnection.projectId
})) as TAzureKeyVaultConnectionCredentials;
const { data } = await request.post<ExchangeCodeAzureResponse>(
@@ -82,7 +83,8 @@ export const getAzureConnectionAccessToken = async (
const encryptedOAuthCredentials = await encryptAppConnectionCredentials({
credentials: updatedOAuthCredentials,
orgId: appConnection.orgId,
- kmsService
+ kmsService,
+ projectId: appConnection.projectId
});
await appConnectionDAL.updateById(appConnection.id, { encryptedCredentials: encryptedOAuthCredentials });
@@ -95,7 +97,8 @@ export const getAzureConnectionAccessToken = async (
const clientSecretCredentials = (await decryptAppConnectionCredentials({
orgId: appConnection.orgId,
kmsService,
- encryptedCredentials: appConnection.encryptedCredentials
+ encryptedCredentials: appConnection.encryptedCredentials,
+ projectId: appConnection.projectId
})) as TAzureKeyVaultConnectionClientSecretCredentials;
const { accessToken, expiresAt, clientId, clientSecret, tenantId } = clientSecretCredentials;
@@ -124,7 +127,8 @@ export const getAzureConnectionAccessToken = async (
const encryptedClientCredentials = await encryptAppConnectionCredentials({
credentials: updatedClientCredentials,
orgId: appConnection.orgId,
- kmsService
+ kmsService,
+ projectId: appConnection.projectId
});
await appConnectionDAL.updateById(appConnection.id, { encryptedCredentials: encryptedClientCredentials });
diff --git a/backend/src/services/app-connection/camunda/camunda-connection-fns.ts b/backend/src/services/app-connection/camunda/camunda-connection-fns.ts
index 91a033c0e8..b764da3362 100644
--- a/backend/src/services/app-connection/camunda/camunda-connection-fns.ts
+++ b/backend/src/services/app-connection/camunda/camunda-connection-fns.ts
@@ -40,7 +40,7 @@ const authorizeCamundaConnection = async ({
};
export const getCamundaConnectionAccessToken = async (
- { id, orgId, credentials }: TCamundaConnection,
+ { id, orgId, credentials, projectId }: TCamundaConnection,
appConnectionDAL: Pick<TAppConnectionDALFactory, "updateById">,
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
) => {
@@ -61,7 +61,8 @@ export const getCamundaConnectionAccessToken = async (
const encryptedCredentials = await encryptAppConnectionCredentials({
credentials: updatedCredentials,
orgId,
- kmsService
+ kmsService,
+ projectId
});
await appConnectionDAL.updateById(id, { encryptedCredentials });
diff --git a/backend/src/services/app-connection/databricks/databricks-connection-fns.ts b/backend/src/services/app-connection/databricks/databricks-connection-fns.ts
index 8912ad9369..a9128ec517 100644
--- a/backend/src/services/app-connection/databricks/databricks-connection-fns.ts
+++ b/backend/src/services/app-connection/databricks/databricks-connection-fns.ts
@@ -47,7 +47,7 @@ const authorizeDatabricksConnection = async ({
};
export const getDatabricksConnectionAccessToken = async (
- { id, orgId, credentials }: TDatabricksConnection,
+ { id, orgId, credentials, projectId }: TDatabricksConnection,
appConnectionDAL: Pick<TAppConnectionDALFactory, "updateById">,
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
) => {
@@ -68,7 +68,8 @@ export const getDatabricksConnectionAccessToken = async (
const encryptedCredentials = await encryptAppConnectionCredentials({
credentials: updatedCredentials,
orgId,
- kmsService
+ kmsService,
+ projectId
});
await appConnectionDAL.updateById(id, { encryptedCredentials });
diff --git a/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts b/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts
index cb4e27e949..9499d6bf2e 100644
--- a/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts
+++ b/backend/src/services/app-connection/gitlab/gitlab-connection-fns.ts
@@ -64,6 +64,7 @@ export const refreshGitLabToken = async (
refreshToken: string,
appId: string,
orgId: string,
+ projectId: string | undefined | null,
appConnectionDAL: Pick<TAppConnectionDALFactory, "updateById">,
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">,
instanceUrl?: string
@@ -105,7 +106,8 @@ export const refreshGitLabToken = async (
expiresAt
},
orgId,
- kmsService
+ kmsService,
+ projectId
});
await appConnectionDAL.updateById(appId, { encryptedCredentials });
@@ -238,6 +240,7 @@ export const getGitLabConnectionClient = async (
appConnection.credentials.refreshToken,
appConnection.id,
appConnection.orgId,
+ appConnection.projectId,
appConnectionDAL,
kmsService,
appConnection.credentials.instanceUrl
@@ -273,6 +276,7 @@ export const listGitLabProjects = async ({
appConnection.credentials.refreshToken,
appConnection.id,
appConnection.orgId,
+ appConnection.projectId,
appConnectionDAL,
kmsService,
appConnection.credentials.instanceUrl
@@ -341,6 +345,7 @@ export const listGitLabGroups = async ({
appConnection.credentials.refreshToken,
appConnection.id,
appConnection.orgId,
+ appConnection.projectId,
appConnectionDAL,
kmsService,
appConnection.credentials.instanceUrl
diff --git a/backend/src/services/app-connection/heroku/heroku-connection-fns.ts b/backend/src/services/app-connection/heroku/heroku-connection-fns.ts
index 5a8533c832..adbc5cd2b9 100644
--- a/backend/src/services/app-connection/heroku/heroku-connection-fns.ts
+++ b/backend/src/services/app-connection/heroku/heroku-connection-fns.ts
@@ -36,6 +36,7 @@ export const refreshHerokuToken = async (
refreshToken: string,
appId: string,
orgId: string,
+ projectId: string | null | undefined,
appConnectionDAL: Pick<TAppConnectionDALFactory, "updateById">,
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">
): Promise<string> => {
@@ -64,7 +65,8 @@ export const refreshHerokuToken = async (
expiresAt: new Date(Date.now() + data.expires_in * 1000 - 60000)
},
orgId,
- kmsService
+ kmsService,
+ projectId
});
await appConnectionDAL.updateById(appId, { encryptedCredentials });
@@ -186,6 +188,7 @@ export const listHerokuApps = async ({
appConnection.credentials.refreshToken,
appConnection.id,
appConnection.orgId,
+ appConnection.projectId,
appConnectionDAL,
kmsService
);
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index ede9e29e3a..2a680b9b8f 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -14,6 +14,8 @@ import { getServerCfg } from "@app/services/super-admin/super-admin-service";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
+import { TNotificationServiceFactory } from "../notification/notification-service";
+import { NotificationType } from "../notification/notification-types";
import { TOrgDALFactory } from "../org/org-dal";
import { getDefaultOrgMembershipRole } from "../org/org-role-fns";
import { TOrgMembershipDALFactory } from "../org-membership/org-membership-dal";
@@ -47,6 +49,7 @@ type TAuthLoginServiceFactoryDep = {
totpService: Pick<TTotpServiceFactory, "verifyUserTotp" | "verifyWithUserRecoveryCode">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
orgMembershipDAL: TOrgMembershipDALFactory;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export type TAuthLoginFactory = ReturnType<typeof authLoginServiceFactory>;
@@ -57,7 +60,8 @@ export const authLoginServiceFactory = ({
orgDAL,
orgMembershipDAL,
totpService,
- auditLogService
+ auditLogService,
+ notificationService
}: TAuthLoginServiceFactoryDep) => {
/*
* Private
@@ -71,6 +75,16 @@ export const authLoginServiceFactory = ({
if (!isDeviceSeen) {
const newDeviceList = devices.concat([{ ip, userAgent }]);
await userDAL.updateById(user.id, { devices: JSON.stringify(newDeviceList) }, tx);
+
+ await notificationService.createUserNotifications([
+ {
+ userId: user.id,
+ type: NotificationType.LOGIN_FROM_NEW_DEVICE,
+ title: "Login From New Device",
+ body: `A new device with IP **${ip}** and User Agent **${userAgent}** has logged into your account.`
+ }
+ ]);
+
if (user.email) {
await smtpService.sendMail({
template: SmtpTemplates.NewDeviceJoin,
@@ -563,6 +577,18 @@ export const authLoginServiceFactory = ({
.filter(Boolean) as string[];
if (adminEmails.length > 0) {
+ await notificationService.createUserNotifications(
+ orgAdmins
+ .filter((admin) => admin.user.id !== user.id)
+ .map((admin) => ({
+ userId: admin.user.id,
+ orgId: organizationId,
+ type: NotificationType.ADMIN_SSO_BYPASS,
+ title: "Security Alert: Admin SSO Bypass",
+ body: `The org admin **${user.email}** has bypassed enforced SSO login.`
+ }))
+ );
+
await smtpService.sendMail({
recipients: adminEmails,
subjectLine: "Security Alert: Admin SSO Bypass",
diff --git a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
index 830378ca85..b725e55847 100644
--- a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
@@ -42,10 +42,10 @@ import { route53DeleteTxtRecord, route53InsertTxtRecord } from "./dns-providers/
type TAcmeCertificateAuthorityFnsDeps = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
- appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
certificateAuthorityDAL: Pick<
TCertificateAuthorityDALFactory,
- "create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa"
+ "create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
certificateDAL: Pick<TCertificateDALFactory, "create" | "transaction">;
@@ -152,7 +152,11 @@ export const AcmeCertificateAuthorityFns = ({
}
// validates permission to connect
- await appConnectionService.connectAppConnectionById(appConnection.app as AppConnection, dnsAppConnectionId, actor);
+ await appConnectionService.validateAppConnectionUsageById(
+ appConnection.app as AppConnection,
+ { connectionId: dnsAppConnectionId, projectId },
+ actor
+ );
const caEntity = await certificateAuthorityDAL.transaction(async (tx) => {
try {
@@ -242,10 +246,16 @@ export const AcmeCertificateAuthorityFns = ({
});
}
+ const ca = await certificateAuthorityDAL.findById(id);
+
+ if (!ca) {
+ throw new NotFoundError({ message: `Could not find Certificate Authority with ID "${id}"` });
+ }
+
// validates permission to connect
- await appConnectionService.connectAppConnectionById(
+ await appConnectionService.validateAppConnectionUsageById(
appConnection.app as AppConnection,
- dnsAppConnectionId,
+ { connectionId: dnsAppConnectionId, projectId: ca.projectId },
actor
);
diff --git a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
index 0e2619a270..25c5590eb4 100644
--- a/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/azure-ad-cs/azure-ad-cs-certificate-authority-fns.ts
@@ -41,10 +41,10 @@ import {
type TAzureAdCsCertificateAuthorityFnsDeps = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "updateById">;
- appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
certificateAuthorityDAL: Pick<
TCertificateAuthorityDALFactory,
- "create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa"
+ "create" | "transaction" | "findByIdWithAssociatedCa" | "updateById" | "findWithAssociatedCa" | "findById"
>;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
certificateDAL: Pick<TCertificateDALFactory, "create" | "transaction">;
@@ -621,9 +621,9 @@ export const AzureAdCsCertificateAuthorityFns = ({
});
}
- await appConnectionService.connectAppConnectionById(
+ await appConnectionService.validateAppConnectionUsageById(
appConnection.app as AppConnection,
- azureAdcsConnectionId,
+ { connectionId: azureAdcsConnectionId, projectId },
actor
);
@@ -705,9 +705,15 @@ export const AzureAdCsCertificateAuthorityFns = ({
});
}
- await appConnectionService.connectAppConnectionById(
+ const ca = await certificateAuthorityDAL.findById(id);
+
+ if (!ca) {
+ throw new NotFoundError({ message: `Could not find Certificate Authority with ID "${id}"` });
+ }
+
+ await appConnectionService.validateAppConnectionUsageById(
appConnection.app as AppConnection,
- azureAdcsConnectionId,
+ { connectionId: azureAdcsConnectionId, projectId: ca.projectId },
actor
);
diff --git a/backend/src/services/certificate-authority/certificate-authority-queue.ts b/backend/src/services/certificate-authority/certificate-authority-queue.ts
index 0e015da03d..21f7b71e64 100644
--- a/backend/src/services/certificate-authority/certificate-authority-queue.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-queue.ts
@@ -35,7 +35,7 @@ import {
type TCertificateAuthorityQueueFactoryDep = {
certificateAuthorityDAL: TCertificateAuthorityDALFactory;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
- appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "create" | "update">;
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "setItemWithExpiry" | "getItem">;
certificateAuthorityCrlDAL: TCertificateAuthorityCrlDALFactory;
diff --git a/backend/src/services/certificate-authority/certificate-authority-service.ts b/backend/src/services/certificate-authority/certificate-authority-service.ts
index 6cf55fc520..02c5a488a3 100644
--- a/backend/src/services/certificate-authority/certificate-authority-service.ts
+++ b/backend/src/services/certificate-authority/certificate-authority-service.ts
@@ -43,7 +43,7 @@ import { TCreateInternalCertificateAuthorityDTO } from "./internal/internal-cert
type TCertificateAuthorityServiceFactoryDep = {
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
- appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
certificateAuthorityDAL: Pick<
TCertificateAuthorityDALFactory,
| "transaction"
diff --git a/backend/src/services/external-migration/external-migration-fns/import.ts b/backend/src/services/external-migration/external-migration-fns/import.ts
index 5728bf1c06..62888c5bf1 100644
--- a/backend/src/services/external-migration/external-migration-fns/import.ts
+++ b/backend/src/services/external-migration/external-migration-fns/import.ts
@@ -55,7 +55,7 @@ export const importDataIntoInfisicalFn = async ({
actorId,
actorOrgId,
actorAuthMethod,
- workspaceName: project.name,
+ projectName: project.name,
createDefaultEnvs: false,
tx
})
diff --git a/backend/src/services/external-migration/external-migration-queue.ts b/backend/src/services/external-migration/external-migration-queue.ts
index b4974d2aed..770cbbe3a0 100644
--- a/backend/src/services/external-migration/external-migration-queue.ts
+++ b/backend/src/services/external-migration/external-migration-queue.ts
@@ -5,6 +5,8 @@ import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TFolderCommitServiceFactory } from "../folder-commit/folder-commit-service";
import { TKmsServiceFactory } from "../kms/kms-service";
+import { TNotificationServiceFactory } from "../notification/notification-service";
+import { NotificationType } from "../notification/notification-types";
import { TProjectDALFactory } from "../project/project-dal";
import { TProjectServiceFactory } from "../project/project-service";
import { TProjectEnvDALFactory } from "../project-env/project-env-dal";
@@ -42,6 +44,7 @@ export type TExternalMigrationQueueFactoryDep = {
folderVersionDAL: Pick<TSecretFolderVersionDALFactory, "create">;
resourceMetadataDAL: Pick<TResourceMetadataDALFactory, "insertMany" | "delete">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export type TExternalMigrationQueueFactory = ReturnType<typeof externalMigrationQueueFactory>;
@@ -62,9 +65,12 @@ export const externalMigrationQueueFactory = ({
folderDAL,
folderCommitService,
folderVersionDAL,
- resourceMetadataDAL
+ resourceMetadataDAL,
+ notificationService
}: TExternalMigrationQueueFactoryDep) => {
const startImport = async (dto: {
+ orgId: string;
+ actorId: string;
actorEmail: string;
importType: ExternalPlatforms;
data: {
@@ -87,9 +93,19 @@ export const externalMigrationQueueFactory = ({
};
queueService.start(QueueName.ImportSecretsFromExternalSource, async (job) => {
- const { data, actorEmail, importType } = job.data;
+ const { data, actorEmail, importType, actorId, orgId } = job.data;
try {
+ await notificationService.createUserNotifications([
+ {
+ userId: actorId,
+ orgId,
+ type: NotificationType.IMPORT_STARTED,
+ title: "Import Started",
+ body: `An import from **${importType}** to Infisical has been started.`
+ }
+ ]);
+
await smtpService.sendMail({
recipients: [actorEmail],
subjectLine: "Infisical import started",
@@ -137,6 +153,16 @@ export const externalMigrationQueueFactory = ({
);
}
+ await notificationService.createUserNotifications([
+ {
+ userId: actorId,
+ orgId,
+ type: NotificationType.IMPORT_SUCCESSFUL,
+ title: "Import Successful",
+ body: `An import from **${importType}** to Infisical has successfully completed.`
+ }
+ ]);
+
await smtpService.sendMail({
recipients: [actorEmail],
subjectLine: "Infisical import successful",
@@ -146,6 +172,17 @@ export const externalMigrationQueueFactory = ({
template: SmtpTemplates.ExternalImportSuccessful
});
} catch (err) {
+ await notificationService.createUserNotifications([
+ {
+ userId: actorId,
+ orgId,
+ type: NotificationType.IMPORT_FAILED,
+ title: "Import Failed",
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
+ body: `An import from **${importType}** to Infisical has failed: ${(err as any)?.message || "Unknown error"}.`
+ }
+ ]);
+
await smtpService.sendMail({
recipients: [job.data.actorEmail],
subjectLine: "Infisical import failed",
diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.ts
index 73fac00b93..e801b607e9 100644
--- a/backend/src/services/external-migration/external-migration-service.ts
+++ b/backend/src/services/external-migration/external-migration-service.ts
@@ -73,6 +73,8 @@ export const externalMigrationServiceFactory = ({
const encrypted = crypto.encryption().symmetric().encryptWithRootEncryptionKey(stringifiedJson);
await externalMigrationQueue.startImport({
+ actorId: user.id,
+ orgId: actorOrgId,
actorEmail: user.email!,
importType: ExternalPlatforms.EnvKey,
data: {
@@ -131,6 +133,8 @@ export const externalMigrationServiceFactory = ({
const encrypted = crypto.encryption().symmetric().encryptWithRootEncryptionKey(stringifiedJson);
await externalMigrationQueue.startImport({
+ actorId: user.id,
+ orgId: actorOrgId,
actorEmail: user.email!,
importType: ExternalPlatforms.Vault,
data: {
diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
index 47188e26d9..46ec2f98a7 100644
--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { ForbiddenError } from "@casl/ability";
+import slugify from "@sindresorhus/slugify";
import { IdentityAuthMethod } from "@app/db/schemas";
import { TIdentityAuthTemplateDALFactory } from "@app/ee/services/identity-auth-template";
@@ -15,10 +16,18 @@ import {
validatePrivilegeChangeOperation
} from "@app/ee/services/permission/permission-fns";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
-import { BadRequestError, NotFoundError, PermissionBoundaryError } from "@app/lib/errors";
+import {
+ BadRequestError,
+ NotFoundError,
+ PermissionBoundaryError,
+ RateLimitError,
+ UnauthorizedError
+} from "@app/lib/errors";
import { extractIPDetails, isValidIpOrCidr } from "@app/lib/ip";
+import { logger } from "@app/lib/logger";
import { ActorType, AuthTokenType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -32,6 +41,8 @@ import { TIdentityLdapAuthDALFactory } from "./identity-ldap-auth-dal";
import {
AllowedFieldsSchema,
TAttachLdapAuthDTO,
+ TCheckLdapAuthLockoutDTO,
+ TClearLdapAuthLockoutsDTO,
TGetLdapAuthDTO,
TLoginLdapAuthDTO,
TRevokeLdapAuthDTO,
@@ -50,10 +61,19 @@ type TIdentityLdapAuthServiceFactoryDep = {
kmsService: TKmsServiceFactory;
identityDAL: TIdentityDALFactory;
identityAuthTemplateDAL: TIdentityAuthTemplateDALFactory;
+ keyStore: Pick<
+ TKeyStoreFactory,
+ "setItemWithExpiry" | "getItem" | "deleteItem" | "getKeysByPattern" | "deleteItems" | "acquireLock"
+ >;
};
export type TIdentityLdapAuthServiceFactory = ReturnType<typeof identityLdapAuthServiceFactory>;
+type LockoutObject = {
+ lockedOut: boolean;
+ failedAttempts: number;
+};
+
export const identityLdapAuthServiceFactory = ({
identityAccessTokenDAL,
identityDAL,
@@ -62,7 +82,8 @@ export const identityLdapAuthServiceFactory = ({
licenseService,
permissionService,
kmsService,
- identityAuthTemplateDAL
+ identityAuthTemplateDAL,
+ keyStore
}: TIdentityLdapAuthServiceFactoryDep) => {
const getLdapConfig = async (identityId: string) => {
const identity = await identityDAL.findOne({ id: identityId });
@@ -126,13 +147,17 @@ export const identityLdapAuthServiceFactory = ({
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) {
- throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
+ throw new UnauthorizedError({
+ message: "Invalid credentials"
+ });
}
const identityLdapAuth = await identityLdapAuthDAL.findOne({ identityId });
if (!identityLdapAuth) {
- throw new NotFoundError({ message: `Failed to find LDAP auth for identity with ID ${identityId}` });
+ throw new UnauthorizedError({
+ message: "Invalid credentials"
+ });
}
const plan = await licenseService.getPlan(identityMembershipOrg.orgId);
@@ -204,7 +229,11 @@ export const identityLdapAuthServiceFactory = ({
actor,
actorOrgId,
isActorSuperAdmin,
- allowedFields
+ allowedFields,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
}: TAttachLdapAuthDTO) => {
await validateIdentityUpdateForSuperAdminPrivileges(identityId, isActorSuperAdmin);
@@ -337,7 +366,11 @@ export const identityLdapAuthServiceFactory = ({
accessTokenNumUsesLimit,
accessTokenTrustedIps: JSON.stringify(reformattedAccessTokenTrustedIps),
allowedFields: allowedFields ? JSON.stringify(allowedFields) : undefined,
- templateId
+ templateId,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
},
tx
);
@@ -363,7 +396,11 @@ export const identityLdapAuthServiceFactory = ({
actorId,
actorAuthMethod,
actor,
- actorOrgId
+ actorOrgId,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
}: TUpdateLdapAuthDTO) => {
const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
@@ -511,7 +548,11 @@ export const identityLdapAuthServiceFactory = ({
accessTokenNumUsesLimit,
accessTokenTrustedIps: reformattedAccessTokenTrustedIps
? JSON.stringify(reformattedAccessTokenTrustedIps)
- : undefined
+ : undefined,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
});
return { ...updatedLdapAuth, orgId: identityMembershipOrg.orgId };
@@ -611,12 +652,123 @@ export const identityLdapAuthServiceFactory = ({
return revokedIdentityLdapAuth;
};
+ const withLdapLockout = async <T>(
+ { identityId, username }: TCheckLdapAuthLockoutDTO,
+ authFn: () => Promise<T>
+ ): Promise<T> => {
+ const usernameSlug = slugify(username.trim().toLowerCase());
+
+ const LOCKOUT_KEY = `lockout:identity:${identityId}:${IdentityAuthMethod.LDAP_AUTH}:${usernameSlug}`;
+
+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;
+ try {
+ lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 3000, {
+ retryCount: 3,
+ retryDelay: 1500,
+ retryJitter: 100
+ });
+ } catch (e) {
+ logger.info(
+ `identity login failed to acquire lock [identityId=${identityId}] [authMethod=${IdentityAuthMethod.LDAP_AUTH}]`
+ );
+ throw new RateLimitError({ message: "Failed to acquire lock: rate limit exceeded" });
+ }
+
+ try {
+ const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);
+ if (lockoutRaw) {
+ const lockout = JSON.parse(lockoutRaw) as LockoutObject;
+ if (lockout.lockedOut) {
+ throw new UnauthorizedError({
+ message: "This identity auth method is temporarily locked, please try again later"
+ });
+ }
+ }
+
+ const result = await authFn();
+
+ await keyStore.deleteItem(LOCKOUT_KEY);
+
+ return result;
+ } catch (error) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
+ if ((error as any).status === 401) {
+ const identityLdapAuth = await identityLdapAuthDAL.findOne({ identityId });
+ if (!identityLdapAuth) {
+ throw new UnauthorizedError({ message: "Invalid credentials" });
+ }
+
+ if (identityLdapAuth.lockoutEnabled) {
+ let lockout: LockoutObject = {
+ lockedOut: false,
+ failedAttempts: 0
+ };
+
+ const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);
+ if (lockoutRaw) {
+ lockout = JSON.parse(lockoutRaw) as LockoutObject;
+ }
+
+ lockout.failedAttempts += 1;
+ if (lockout.failedAttempts >= identityLdapAuth.lockoutThreshold) {
+ lockout.lockedOut = true;
+ }
+
+ await keyStore.setItemWithExpiry(
+ LOCKOUT_KEY,
+ lockout.lockedOut ? identityLdapAuth.lockoutDurationSeconds : identityLdapAuth.lockoutCounterResetSeconds,
+ JSON.stringify(lockout)
+ );
+ }
+
+ throw new UnauthorizedError({ message: "Invalid credentials" });
+ }
+ throw error;
+ } finally {
+ await lock.release();
+ }
+ };
+
+ const clearLdapAuthLockouts = async ({
+ identityId,
+ actorId,
+ actor,
+ actorOrgId,
+ actorAuthMethod
+ }: TClearLdapAuthLockoutsDTO) => {
+ const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId });
+ if (!identityMembershipOrg) throw new NotFoundError({ message: `Failed to find identity with ID ${identityId}` });
+
+ if (!identityMembershipOrg.identity.authMethods.includes(IdentityAuthMethod.LDAP_AUTH)) {
+ throw new BadRequestError({
+ message: "The identity does not have ldap auth"
+ });
+ }
+
+ const { permission } = await permissionService.getOrgPermission(
+ actor,
+ actorId,
+ identityMembershipOrg.orgId,
+ actorAuthMethod,
+ actorOrgId
+ );
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionIdentityActions.Edit, OrgPermissionSubjects.Identity);
+
+ const deleted = await keyStore.deleteItems({
+ pattern: `lockout:identity:${identityId}:${IdentityAuthMethod.LDAP_AUTH}:*`
+ });
+
+ return { deleted, identityId, orgId: identityMembershipOrg.orgId };
+ };
+
return {
attachLdapAuth,
getLdapConfig,
updateLdapAuth,
login,
revokeIdentityLdapAuth,
- getLdapAuth
+ getLdapAuth,
+ withLdapLockout,
+ clearLdapAuthLockouts
};
};
diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-types.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-types.ts
index 8629763bbb..a4aea7573d 100644
--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-types.ts
+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-types.ts
@@ -27,6 +27,10 @@ export type TAttachLdapAuthDTO = {
accessTokenNumUsesLimit: number;
accessTokenTrustedIps: { ipAddress: string }[];
isActorSuperAdmin?: boolean;
+ lockoutEnabled: boolean;
+ lockoutThreshold: number;
+ lockoutDurationSeconds: number;
+ lockoutCounterResetSeconds: number;
} & Omit<TProjectPermission, "projectId">;
export type TUpdateLdapAuthDTO = {
@@ -43,6 +47,10 @@ export type TUpdateLdapAuthDTO = {
accessTokenMaxTTL?: number;
accessTokenNumUsesLimit?: number;
accessTokenTrustedIps?: { ipAddress: string }[];
+ lockoutEnabled?: boolean;
+ lockoutThreshold?: number;
+ lockoutDurationSeconds?: number;
+ lockoutCounterResetSeconds?: number;
} & Omit<TProjectPermission, "projectId">;
export type TGetLdapAuthDTO = {
@@ -56,3 +64,12 @@ export type TLoginLdapAuthDTO = {
export type TRevokeLdapAuthDTO = {
identityId: string;
} & Omit<TProjectPermission, "projectId">;
+
+export type TClearLdapAuthLockoutsDTO = {
+ identityId: string;
+} & Omit<TProjectPermission, "projectId">;
+
+export type TCheckLdapAuthLockoutDTO = {
+ identityId: string;
+ username: string;
+};
diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.ts
index 8aec163713..979e6f25fb 100644
--- a/backend/src/services/identity-ua/identity-ua-service.ts
+++ b/backend/src/services/identity-ua/identity-ua-service.ts
@@ -84,69 +84,70 @@ export const identityUaServiceFactory = ({
const LOCKOUT_KEY = `lockout:identity:${identityUa.identityId}:${IdentityAuthMethod.UNIVERSAL_AUTH}:${clientId}`;
- let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
- if (identityUa.lockoutEnabled) {
- try {
- lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 500, {
- retryCount: 3,
- retryDelay: 300,
- retryJitter: 100
- });
- } catch (e) {
- logger.info(
- `identity login failed to acquire lock [identityId=${identityUa.identityId}] [authMethod=${IdentityAuthMethod.UNIVERSAL_AUTH}]`
- );
- throw new RateLimitError({ message: "Failed to acquire lock: rate limit exceeded" });
- }
- }
-
- try {
- const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);
+ const lockoutRaw = await keyStore.getItem(LOCKOUT_KEY);
- let lockout: LockoutObject | undefined;
- if (lockoutRaw) {
- lockout = JSON.parse(lockoutRaw) as LockoutObject;
- }
-
- if (lockout && lockout.lockedOut) {
- throw new UnauthorizedError({
- message: "This identity auth method is temporarily locked, please try again later"
- });
- }
+ let lockout: LockoutObject | undefined;
+ if (lockoutRaw) {
+ lockout = JSON.parse(lockoutRaw) as LockoutObject;
+ }
- const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId: identityUa.identityId });
- if (!identityMembershipOrg) {
- throw new UnauthorizedError({
- message: "Invalid credentials"
- });
- }
+ if (lockout && lockout.lockedOut) {
+ throw new UnauthorizedError({
+ message: "This identity auth method is temporarily locked, please try again later"
+ });
+ }
- const clientSecretPrefix = clientSecret.slice(0, 4);
- const clientSecretInfo = await identityUaClientSecretDAL.find({
- identityUAId: identityUa.id,
- isClientSecretRevoked: false,
- clientSecretPrefix
+ const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId: identityUa.identityId });
+ if (!identityMembershipOrg) {
+ throw new UnauthorizedError({
+ message: "Invalid credentials"
});
+ }
- let validClientSecretInfo: (typeof clientSecretInfo)[0] | null = null;
- for await (const info of clientSecretInfo) {
- const isMatch = await crypto.hashing().compareHash(clientSecret, info.clientSecretHash);
+ const clientSecretPrefix = clientSecret.slice(0, 4);
+ const clientSecretInfo = await identityUaClientSecretDAL.find({
+ identityUAId: identityUa.id,
+ isClientSecretRevoked: false,
+ clientSecretPrefix
+ });
- if (isMatch) {
- validClientSecretInfo = info;
- break;
- }
+ let validClientSecretInfo: (typeof clientSecretInfo)[0] | null = null;
+ for await (const info of clientSecretInfo) {
+ const isMatch = await crypto.hashing().compareHash(clientSecret, info.clientSecretHash);
+
+ if (isMatch) {
+ validClientSecretInfo = info;
+ break;
}
+ }
- if (!validClientSecretInfo) {
- if (identityUa.lockoutEnabled) {
- if (!lockout) {
+ if (!validClientSecretInfo) {
+ if (identityUa.lockoutEnabled) {
+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;
+ try {
+ lock = await keyStore.acquireLock([KeyStorePrefixes.IdentityLockoutLock(LOCKOUT_KEY)], 300, {
+ retryCount: 3,
+ retryDelay: 300,
+ retryJitter: 100
+ });
+
+ // Re-fetch the latest lockout data while holding the lock
+ const lockoutRawNew = await keyStore.getItem(LOCKOUT_KEY);
+ if (lockoutRawNew) {
+ lockout = JSON.parse(lockoutRawNew) as LockoutObject;
+ } else {
lockout = {
lockedOut: false,
failedAttempts: 0
};
}
+ if (lockout.lockedOut) {
+ throw new UnauthorizedError({
+ message: "This identity auth method is temporarily locked, please try again later"
+ });
+ }
+
lockout.failedAttempts += 1;
if (lockout.failedAttempts >= identityUa.lockoutThreshold) {
lockout.lockedOut = true;
@@ -157,110 +158,121 @@ export const identityUaServiceFactory = ({
lockout.lockedOut ? identityUa.lockoutDurationSeconds : identityUa.lockoutCounterResetSeconds,
JSON.stringify(lockout)
);
+ } catch (e) {
+ if (lock === undefined) {
+ logger.info(
+ `identity login failed to acquire lock [identityId=${identityUa.identityId}] [authMethod=${IdentityAuthMethod.UNIVERSAL_AUTH}]`
+ );
+ throw new RateLimitError({ message: "Failed to acquire lock: rate limit exceeded" });
+ }
+ throw e;
+ } finally {
+ if (lock) {
+ await lock.release();
+ }
}
-
- throw new UnauthorizedError({ message: "Invalid credentials" });
- } else if (lockout) {
- await keyStore.deleteItem(LOCKOUT_KEY);
}
- const { clientSecretTTL, clientSecretNumUses, clientSecretNumUsesLimit } = validClientSecretInfo;
- if (Number(clientSecretTTL) > 0) {
- const clientSecretCreated = new Date(validClientSecretInfo.createdAt);
- const ttlInMilliseconds = Number(clientSecretTTL) * 1000;
- const currentDate = new Date();
- const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds);
-
- if (currentDate > expirationTime) {
- await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
- isClientSecretRevoked: true
- });
+ throw new UnauthorizedError({ message: "Invalid credentials" });
+ } else if (lockout) {
+ // If credentials are valid, clear any existing lockout record
+ await keyStore.deleteItem(LOCKOUT_KEY);
+ }
- throw new UnauthorizedError({
- message: "Access denied due to expired client secret"
- });
- }
- }
+ const { clientSecretTTL, clientSecretNumUses, clientSecretNumUsesLimit } = validClientSecretInfo;
+ if (Number(clientSecretTTL) > 0) {
+ const clientSecretCreated = new Date(validClientSecretInfo.createdAt);
+ const ttlInMilliseconds = Number(clientSecretTTL) * 1000;
+ const currentDate = new Date();
+ const expirationTime = new Date(clientSecretCreated.getTime() + ttlInMilliseconds);
- if (clientSecretNumUsesLimit > 0 && clientSecretNumUses >= clientSecretNumUsesLimit) {
- // number of times client secret can be used for
- // a login operation reached
+ if (currentDate > expirationTime) {
await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
isClientSecretRevoked: true
});
+
throw new UnauthorizedError({
- message: "Access denied due to client secret usage limit reached"
+ message: "Access denied due to expired client secret"
});
}
+ }
- const accessTokenTTLParams =
- Number(identityUa.accessTokenPeriod) === 0
- ? {
- accessTokenTTL: identityUa.accessTokenTTL,
- accessTokenMaxTTL: identityUa.accessTokenMaxTTL
- }
- : {
- accessTokenTTL: identityUa.accessTokenPeriod,
- // We set a very large Max TTL for periodic tokens to ensure that clients (even outdated ones) can always renew their token
- // without them having to update their SDKs, CLIs, etc. This workaround sets it to 30 years to emulate "forever"
- accessTokenMaxTTL: 1000000000
- };
-
- const identityAccessToken = await identityUaDAL.transaction(async (tx) => {
- const uaClientSecretDoc = await identityUaClientSecretDAL.incrementUsage(validClientSecretInfo!.id, tx);
- await identityOrgMembershipDAL.updateById(
- identityMembershipOrg.id,
- {
- lastLoginAuthMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
- lastLoginTime: new Date()
- },
- tx
- );
- const newToken = await identityAccessTokenDAL.create(
- {
- identityId: identityUa.identityId,
- isAccessTokenRevoked: false,
- identityUAClientSecretId: uaClientSecretDoc.id,
- accessTokenNumUses: 0,
- accessTokenNumUsesLimit: identityUa.accessTokenNumUsesLimit,
- accessTokenPeriod: identityUa.accessTokenPeriod,
- authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
- ...accessTokenTTLParams
- },
- tx
- );
-
- return newToken;
+ if (clientSecretNumUsesLimit > 0 && clientSecretNumUses >= clientSecretNumUsesLimit) {
+ // number of times client secret can be used for
+ // a login operation reached
+ await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
+ isClientSecretRevoked: true
+ });
+ throw new UnauthorizedError({
+ message: "Access denied due to client secret usage limit reached"
});
+ }
- const appCfg = getConfig();
- const accessToken = crypto.jwt().sign(
+ const accessTokenTTLParams =
+ Number(identityUa.accessTokenPeriod) === 0
+ ? {
+ accessTokenTTL: identityUa.accessTokenTTL,
+ accessTokenMaxTTL: identityUa.accessTokenMaxTTL
+ }
+ : {
+ accessTokenTTL: identityUa.accessTokenPeriod,
+ // We set a very large Max TTL for periodic tokens to ensure that clients (even outdated ones) can always renew their token
+ // without them having to update their SDKs, CLIs, etc. This workaround sets it to 30 years to emulate "forever"
+ accessTokenMaxTTL: 1000000000
+ };
+
+ const identityAccessToken = await identityUaDAL.transaction(async (tx) => {
+ const uaClientSecretDoc = await identityUaClientSecretDAL.incrementUsage(validClientSecretInfo!.id, tx);
+ await identityOrgMembershipDAL.updateById(
+ identityMembershipOrg.id,
+ {
+ lastLoginAuthMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ lastLoginTime: new Date()
+ },
+ tx
+ );
+ const newToken = await identityAccessTokenDAL.create(
{
identityId: identityUa.identityId,
- clientSecretId: validClientSecretInfo.id,
- identityAccessTokenId: identityAccessToken.id,
- authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN
- } as TIdentityAccessTokenJwtPayload,
- appCfg.AUTH_SECRET,
- // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error
- Number(identityAccessToken.accessTokenTTL) === 0
- ? undefined
- : {
- expiresIn: Number(identityAccessToken.accessTokenTTL)
- }
+ isAccessTokenRevoked: false,
+ identityUAClientSecretId: uaClientSecretDoc.id,
+ accessTokenNumUses: 0,
+ accessTokenNumUsesLimit: identityUa.accessTokenNumUsesLimit,
+ accessTokenPeriod: identityUa.accessTokenPeriod,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
+ ...accessTokenTTLParams
+ },
+ tx
);
- return {
- accessToken,
- identityUa,
- validClientSecretInfo,
- identityAccessToken,
- identityMembershipOrg,
- ...accessTokenTTLParams
- };
- } finally {
- if (lock) await lock.release();
- }
+ return newToken;
+ });
+
+ const appCfg = getConfig();
+ const accessToken = crypto.jwt().sign(
+ {
+ identityId: identityUa.identityId,
+ clientSecretId: validClientSecretInfo.id,
+ identityAccessTokenId: identityAccessToken.id,
+ authTokenType: AuthTokenType.IDENTITY_ACCESS_TOKEN
+ } as TIdentityAccessTokenJwtPayload,
+ appCfg.AUTH_SECRET,
+ // akhilmhdh: for non-expiry tokens you should not even set the value, including undefined. Even for undefined jsonwebtoken throws error
+ Number(identityAccessToken.accessTokenTTL) === 0
+ ? undefined
+ : {
+ expiresIn: Number(identityAccessToken.accessTokenTTL)
+ }
+ );
+
+ return {
+ accessToken,
+ identityUa,
+ validClientSecretInfo,
+ identityAccessToken,
+ identityMembershipOrg,
+ ...accessTokenTTLParams
+ };
};
const attachUniversalAuth = async ({
diff --git a/backend/src/services/identity/identity-service.ts b/backend/src/services/identity/identity-service.ts
index 969d003310..f216d64836 100644
--- a/backend/src/services/identity/identity-service.ts
+++ b/backend/src/services/identity/identity-service.ts
@@ -33,7 +33,7 @@ type TIdentityServiceFactoryDep = {
identityProjectDAL: Pick<TIdentityProjectDALFactory, "findByIdentityId">;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission" | "getOrgPermissionByRole">;
licenseService: Pick<TLicenseServiceFactory, "getPlan" | "updateSubscriptionOrgMemberCount">;
- keyStore: Pick<TKeyStoreFactory, "getKeysByPattern">;
+ keyStore: Pick<TKeyStoreFactory, "getKeysByPattern" | "getItem">;
};
export type TIdentityServiceFactory = ReturnType<typeof identityServiceFactory>;
@@ -261,12 +261,18 @@ export const identityServiceFactory = ({
const activeLockouts = await keyStore.getKeysByPattern(`lockout:identity:${id}:*`);
const activeLockoutAuthMethods = new Set<string>();
- activeLockouts.forEach((key) => {
+ for await (const key of activeLockouts) {
const parts = key.split(":");
if (parts.length > 3) {
- activeLockoutAuthMethods.add(parts[3]);
+ const lockoutRaw = await keyStore.getItem(key);
+ if (lockoutRaw) {
+ const lockout = JSON.parse(lockoutRaw) as { lockedOut: boolean };
+ if (lockout.lockedOut) {
+ activeLockoutAuthMethods.add(parts[3]);
+ }
+ }
}
- });
+ }
return {
...identity,
diff --git a/backend/src/services/notification/notification-types.ts b/backend/src/services/notification/notification-types.ts
index 30bc872442..a3657c6800 100644
--- a/backend/src/services/notification/notification-types.ts
+++ b/backend/src/services/notification/notification-types.ts
@@ -1,6 +1,21 @@
export enum NotificationType {
ACCESS_APPROVAL_REQUEST = "access-approval-request",
- ACCESS_APPROVAL_REQUEST_UPDATED = "access-approval-request-updated"
+ ACCESS_APPROVAL_REQUEST_UPDATED = "access-approval-request-updated",
+ ACCESS_POLICY_BYPASSED = "access-policy-bypassed",
+ SECRET_CHANGE_REQUEST = "secret-change-request",
+ SECRET_CHANGE_POLICY_BYPASSED = "secret-change-policy-bypassed",
+ SECRET_ROTATION_FAILED = "secret-rotation-failed",
+ SECRET_SCANNING_SECRETS_DETECTED = "secret-scanning-secrets-detected",
+ SECRET_SCANNING_SCAN_FAILED = "secret-scanning-scan-failed",
+ LOGIN_FROM_NEW_DEVICE = "login-from-new-device",
+ ADMIN_SSO_BYPASS = "admin-sso-bypass",
+ IMPORT_STARTED = "import-started",
+ IMPORT_SUCCESSFUL = "import-successful",
+ IMPORT_FAILED = "import-failed",
+ DIRECT_PROJECT_ACCESS_ISSUED_TO_ADMIN = "direct-project-access-issued-to-admin",
+ PROJECT_ACCESS_REQUEST = "project-access-request",
+ PROJECT_INVITATION = "project-invitation",
+ SECRET_SYNC_FAILED = "secret-sync-failed"
}
export interface TCreateUserNotificationDTO {
diff --git a/backend/src/services/org-admin/org-admin-service.ts b/backend/src/services/org-admin/org-admin-service.ts
index 23005e52ba..995afadc14 100644
--- a/backend/src/services/org-admin/org-admin-service.ts
+++ b/backend/src/services/org-admin/org-admin-service.ts
@@ -5,6 +5,8 @@ import { OrgPermissionAdminConsoleAction, OrgPermissionSubjects } from "@app/ee/
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TNotificationServiceFactory } from "../notification/notification-service";
+import { NotificationType } from "../notification/notification-types";
import { TProjectDALFactory } from "../project/project-dal";
import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";
import { TProjectUserMembershipRoleDALFactory } from "../project-membership/project-user-membership-role-dal";
@@ -20,6 +22,7 @@ type TOrgAdminServiceFactoryDep = {
>;
projectUserMembershipRoleDAL: Pick<TProjectUserMembershipRoleDALFactory, "create" | "delete">;
smtpService: Pick<TSmtpService, "sendMail">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export type TOrgAdminServiceFactory = ReturnType<typeof orgAdminServiceFactory>;
@@ -29,7 +32,8 @@ export const orgAdminServiceFactory = ({
projectDAL,
projectMembershipDAL,
projectUserMembershipRoleDAL,
- smtpService
+ smtpService,
+ notificationService
}: TOrgAdminServiceFactoryDep) => {
const listOrgProjects = async ({
actor,
@@ -130,23 +134,34 @@ export const orgAdminServiceFactory = ({
});
const projectMembers = await projectMembershipDAL.findAllProjectMembers(projectId);
- const filteredProjectMembers = projectMembers
- .filter(
- (member) => member.roles.some((role) => role.role === ProjectMembershipRole.Admin) && member.userId !== actorId
- )
- .map((el) => el.user.email!)
- .filter(Boolean);
-
- if (filteredProjectMembers.length) {
- await smtpService.sendMail({
- template: SmtpTemplates.OrgAdminProjectDirectAccess,
- recipients: filteredProjectMembers,
- subjectLine: "Organization Admin Project Direct Access Issued",
- substitutions: {
- projectName: project.name,
- email: projectMembers.find((el) => el.userId === actorId)?.user?.username
- }
- });
+ const projectAdmins = projectMembers.filter(
+ (member) => member.roles.some((role) => role.role === ProjectMembershipRole.Admin) && member.userId !== actorId
+ );
+ const mappedProjectAdmins = projectAdmins.map((el) => el.user.email!).filter(Boolean);
+ const actorEmail = projectMembers.find((el) => el.userId === actorId)?.user?.username;
+
+ if (actorEmail) {
+ await notificationService.createUserNotifications(
+ projectAdmins.map((member) => ({
+ userId: member.userId,
+ orgId: project.orgId,
+ type: NotificationType.DIRECT_PROJECT_ACCESS_ISSUED_TO_ADMIN,
+ title: "Direct Project Access Issued",
+ body: `The organization admin **${actorEmail}** has self-issued direct access to the project **${project.name}**.`
+ }))
+ );
+
+ if (mappedProjectAdmins.length) {
+ await smtpService.sendMail({
+ template: SmtpTemplates.OrgAdminProjectDirectAccess,
+ recipients: mappedProjectAdmins,
+ subjectLine: "Organization Admin Project Direct Access Issued",
+ substitutions: {
+ projectName: project.name,
+ email: actorEmail
+ }
+ });
+ }
}
return { isExistingMember: false, membership: updatedMembership };
};
diff --git a/backend/src/services/project-membership/project-membership-service.ts b/backend/src/services/project-membership/project-membership-service.ts
index 7cf665141e..991bf65d16 100644
--- a/backend/src/services/project-membership/project-membership-service.ts
+++ b/backend/src/services/project-membership/project-membership-service.ts
@@ -18,6 +18,8 @@ import { ms } from "@app/lib/ms";
import { TUserGroupMembershipDALFactory } from "../../ee/services/group/user-group-membership-dal";
import { ActorType } from "../auth/auth-type";
import { TGroupProjectDALFactory } from "../group-project/group-project-dal";
+import { TNotificationServiceFactory } from "../notification/notification-service";
+import { NotificationType } from "../notification/notification-types";
import { TOrgDALFactory } from "../org/org-dal";
import { TProjectDALFactory } from "../project/project-dal";
import { TProjectBotDALFactory } from "../project-bot/project-bot-dal";
@@ -56,6 +58,7 @@ type TProjectMembershipServiceFactoryDep = {
projectUserAdditionalPrivilegeDAL: Pick<TProjectUserAdditionalPrivilegeDALFactory, "delete">;
secretReminderRecipientsDAL: Pick<TSecretReminderRecipientsDALFactory, "delete">;
groupProjectDAL: TGroupProjectDALFactory;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export type TProjectMembershipServiceFactory = ReturnType<typeof projectMembershipServiceFactory>;
@@ -74,7 +77,8 @@ export const projectMembershipServiceFactory = ({
projectDAL,
projectKeyDAL,
secretReminderRecipientsDAL,
- licenseService
+ licenseService,
+ notificationService
}: TProjectMembershipServiceFactoryDep) => {
const getProjectMemberships = async ({
actorId,
@@ -236,6 +240,16 @@ export const projectMembershipServiceFactory = ({
});
if (sendEmails) {
+ await notificationService.createUserNotifications(
+ orgMembers.map((member) => ({
+ userId: member.userId,
+ orgId: project.orgId,
+ type: NotificationType.PROJECT_INVITATION,
+ title: "Project Invitation",
+ body: `You've been invited to join the project **${project.name}**.`
+ }))
+ );
+
const appCfg = getConfig();
await smtpService.sendMail({
template: SmtpTemplates.WorkspaceInvite,
diff --git a/backend/src/services/project/project-dal.ts b/backend/src/services/project/project-dal.ts
index 2766db3798..d64977f8bf 100644
--- a/backend/src/services/project/project-dal.ts
+++ b/backend/src/services/project/project-dal.ts
@@ -399,6 +399,7 @@ export const projectDALFactory = (db: TDbClient) => {
name?: string;
sortBy?: SearchProjectSortBy;
sortDir?: SortDirection;
+ projectIds?: string[];
}) => {
const { limit = 20, offset = 0, sortBy = SearchProjectSortBy.NAME, sortDir = SortDirection.ASC } = dto;
@@ -454,6 +455,11 @@ export const projectDALFactory = (db: TDbClient) => {
if (dto.name) {
void query.whereILike(`${TableName.Project}.name`, `%${dto.name}%`);
}
+
+ if (dto.projectIds?.length) {
+ void query.whereIn(`${TableName.Project}.id`, dto.projectIds);
+ }
+
const docs = await query;
return { docs, totalCount: Number(docs?.[0]?.count ?? 0) };
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index d59f20bc66..8dbba2b4f1 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -57,6 +57,8 @@ import { TKmsServiceFactory } from "../kms/kms-service";
import { validateMicrosoftTeamsChannelsSchema } from "../microsoft-teams/microsoft-teams-fns";
import { TMicrosoftTeamsIntegrationDALFactory } from "../microsoft-teams/microsoft-teams-integration-dal";
import { TProjectMicrosoftTeamsConfigDALFactory } from "../microsoft-teams/project-microsoft-teams-config-dal";
+import { TNotificationServiceFactory } from "../notification/notification-service";
+import { NotificationType } from "../notification/notification-types";
import { TOrgDALFactory } from "../org/org-dal";
import { TPkiAlertDALFactory } from "../pki-alert/pki-alert-dal";
import { TPkiCollectionDALFactory } from "../pki-collection/pki-collection-dal";
@@ -183,6 +185,7 @@ type TProjectServiceFactoryDep = {
>;
projectTemplateService: TProjectTemplateServiceFactory;
reminderService: Pick<TReminderServiceFactory, "deleteReminderBySecretId">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
export type TProjectServiceFactory = ReturnType<typeof projectServiceFactory>;
@@ -227,7 +230,8 @@ export const projectServiceFactory = ({
projectTemplateService,
groupProjectDAL,
smtpService,
- reminderService
+ reminderService,
+ notificationService
}: TProjectServiceFactoryDep) => {
/*
* Create workspace. Make user the admin
@@ -237,8 +241,8 @@ export const projectServiceFactory = ({
actorId,
actorOrgId,
actorAuthMethod,
- workspaceName,
- workspaceDescription,
+ projectName: workspaceName,
+ projectDescription: workspaceDescription,
slug: projectSlug,
kmsKeyId,
tx: trx,
@@ -254,7 +258,13 @@ export const projectServiceFactory = ({
actorAuthMethod,
actorOrgId
);
- ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Workspace);
+
+ if (
+ permission.cannot(OrgPermissionActions.Create, OrgPermissionSubjects.Workspace) &&
+ permission.cannot(OrgPermissionActions.Create, OrgPermissionSubjects.Project)
+ ) {
+ throw new ForbiddenRequestError({ message: "You don't have permission to create a project" });
+ }
const results = await (trx || projectDAL).transaction(async (tx) => {
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateProject(organization.id)]);
@@ -591,7 +601,8 @@ export const projectServiceFactory = ({
secretSharing: update.secretSharing,
defaultProduct: update.defaultProduct,
showSnapshotsLegacy: update.showSnapshotsLegacy,
- secretDetectionIgnoreValues: update.secretDetectionIgnoreValues
+ secretDetectionIgnoreValues: update.secretDetectionIgnoreValues,
+ pitVersionLimit: update.pitVersionLimit
});
return updatedProject;
@@ -684,19 +695,21 @@ export const projectServiceFactory = ({
actorOrgId,
actorAuthMethod,
auditLogsRetentionDays,
- workspaceSlug
+ filter
}: TUpdateAuditLogsRetentionDTO) => {
- const project = await projectDAL.findProjectBySlug(workspaceSlug, actorOrgId);
+ const project = await projectDAL.findProjectByFilter(filter);
+ const projectId = project.id;
+
if (!project) {
throw new NotFoundError({
- message: `Project with slug '${workspaceSlug}' not found`
+ message: `Project not found`
});
}
const { hasRole } = await permissionService.getProjectPermission({
actor,
actorId,
- projectId: project.id,
+ projectId,
actorAuthMethod,
actorOrgId,
actionProjectType: ActionProjectType.Any
@@ -1806,7 +1819,8 @@ export const projectServiceFactory = ({
limit,
type,
orderBy,
- orderDirection
+ orderDirection,
+ projectIds
}: TSearchProjectsDTO) => {
// check user belong to org
await permissionService.getOrgPermission(
@@ -1822,6 +1836,7 @@ export const projectServiceFactory = ({
offset,
name,
type,
+ projectIds,
orgId: permission.orgId,
actor: permission.type,
actorId: permission.id,
@@ -1913,6 +1928,21 @@ export const projectServiceFactory = ({
projectTypeUrl = "cert-management";
}
+ const callbackPath = `/projects/${projectTypeUrl}/${project.id}/access-management?selectedTab=members&requesterEmail=${userDetails.email}`;
+
+ await notificationService.createUserNotifications(
+ projectMembers
+ .filter((member) => member.roles.some((role) => role.role === ProjectMembershipRole.Admin))
+ .map((member) => ({
+ userId: member.userId,
+ orgId: project.orgId,
+ type: NotificationType.PROJECT_ACCESS_REQUEST,
+ title: "Project Access Request",
+ body: `**${userDetails.firstName} ${userDetails.lastName}** (${userDetails.email}) has requested access to the project **${project.name}**.`,
+ link: callbackPath
+ }))
+ );
+
await smtpService.sendMail({
template: SmtpTemplates.ProjectAccessRequest,
recipients: filteredProjectMembers,
@@ -1923,7 +1953,7 @@ export const projectServiceFactory = ({
projectName: project?.name,
orgName: org?.name,
note: comment,
- callback_url: `${appCfg.SITE_URL}/projects/${projectTypeUrl}/${project.id}/access-management?selectedTab=members&requesterEmail=${userDetails.email}`
+ callback_url: `${appCfg.SITE_URL}${callbackPath}`
}
});
};
diff --git a/backend/src/services/project/project-types.ts b/backend/src/services/project/project-types.ts
index ceef78f6ab..74c7e95f4e 100644
--- a/backend/src/services/project/project-types.ts
+++ b/backend/src/services/project/project-types.ts
@@ -42,12 +42,13 @@ export type TCreateProjectDTO = {
actorAuthMethod: ActorAuthMethod;
actorId: string;
actorOrgId?: string;
- workspaceName: string;
- workspaceDescription?: string;
+ projectName: string;
+ projectDescription?: string;
slug?: string;
kmsKeyId?: string;
createDefaultEnvs?: boolean;
template?: string;
+ pitVersionLimit?: number;
tx?: Knex;
type?: ProjectType;
};
@@ -78,7 +79,7 @@ export type TUpdateProjectVersionLimitDTO = {
export type TUpdateAuditLogsRetentionDTO = {
auditLogsRetentionDays: number;
- workspaceSlug: string;
+ filter: Filter;
} & Omit<TProjectPermission, "projectId">;
export type TUpdateProjectNameDTO = {
@@ -90,6 +91,7 @@ export type TUpdateProjectDTO = {
update: {
name?: string;
description?: string;
+ pitVersionLimit?: number;
autoCapitalization?: boolean;
hasDeleteProtection?: boolean;
defaultProduct?: ProjectType;
@@ -221,6 +223,7 @@ export type TSearchProjectsDTO = {
limit?: number;
offset?: number;
orderBy?: SearchProjectSortBy;
+ projectIds?: string[];
orderDirection?: SortDirection;
};
diff --git a/backend/src/services/secret-sync/gitlab/gitlab-sync-fns.ts b/backend/src/services/secret-sync/gitlab/gitlab-sync-fns.ts
index 3c152d8538..7bf45d47ce 100644
--- a/backend/src/services/secret-sync/gitlab/gitlab-sync-fns.ts
+++ b/backend/src/services/secret-sync/gitlab/gitlab-sync-fns.ts
@@ -53,6 +53,7 @@ const getValidAccessToken = async (
connection.credentials.refreshToken,
connection.id,
connection.orgId,
+ connection.projectId,
appConnectionDAL,
kmsService,
connection.credentials.instanceUrl
diff --git a/backend/src/services/secret-sync/heroku/heroku-sync-fns.ts b/backend/src/services/secret-sync/heroku/heroku-sync-fns.ts
index d2f0817dbc..5f23759793 100644
--- a/backend/src/services/secret-sync/heroku/heroku-sync-fns.ts
+++ b/backend/src/services/secret-sync/heroku/heroku-sync-fns.ts
@@ -32,6 +32,7 @@ const getValidAuthToken = async (
connection.credentials.refreshToken,
connection.id,
connection.orgId,
+ connection.projectId,
appConnectionDAL,
kmsService
);
diff --git a/backend/src/services/secret-sync/secret-sync-dal.ts b/backend/src/services/secret-sync/secret-sync-dal.ts
index e50593f100..57c6581ced 100644
--- a/backend/src/services/secret-sync/secret-sync-dal.ts
+++ b/backend/src/services/secret-sync/secret-sync-dal.ts
@@ -31,6 +31,7 @@ const baseSecretSyncQuery = ({ filter, db, tx }: { db: TDbClient; filter?: Secre
db.ref("description").withSchema(TableName.AppConnection).as("connectionDescription"),
db.ref("version").withSchema(TableName.AppConnection).as("connectionVersion"),
db.ref("gatewayId").withSchema(TableName.AppConnection).as("connectionGatewayId"),
+ db.ref("projectId").withSchema(TableName.AppConnection).as("connectionProjectId"),
db.ref("createdAt").withSchema(TableName.AppConnection).as("connectionCreatedAt"),
db.ref("updatedAt").withSchema(TableName.AppConnection).as("connectionUpdatedAt"),
db
@@ -67,6 +68,7 @@ const expandSecretSync = (
connectionVersion,
connectionIsPlatformManagedCredentials,
connectionGatewayId,
+ connectionProjectId,
...el
} = secretSync;
@@ -86,7 +88,8 @@ const expandSecretSync = (
updatedAt: connectionUpdatedAt,
version: connectionVersion,
isPlatformManagedCredentials: connectionIsPlatformManagedCredentials,
- gatewayId: connectionGatewayId
+ gatewayId: connectionGatewayId,
+ projectId: connectionProjectId
},
folder: folder
? {
diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.ts
index f75d84eda5..63faf3b037 100644
--- a/backend/src/services/secret-sync/secret-sync-queue.ts
+++ b/backend/src/services/secret-sync/secret-sync-queue.ts
@@ -61,6 +61,8 @@ import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
import { TFolderCommitServiceFactory } from "../folder-commit/folder-commit-service";
+import { TNotificationServiceFactory } from "../notification/notification-service";
+import { NotificationType } from "../notification/notification-types";
export type TSecretSyncQueueFactory = ReturnType<typeof secretSyncQueueFactory>;
@@ -100,6 +102,7 @@ type TSecretSyncQueueFactoryDep = {
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
};
type SecretSyncActionJob = Job<
@@ -142,7 +145,8 @@ export const secretSyncQueueFactory = ({
folderCommitService,
licenseService,
gatewayService,
- gatewayV2Service
+ gatewayV2Service,
+ notificationService
}: TSecretSyncQueueFactoryDep) => {
const appCfg = getConfig();
@@ -484,13 +488,14 @@ export const secretSyncQueueFactory = ({
try {
const {
- connection: { orgId, encryptedCredentials }
+ connection: { orgId, encryptedCredentials, projectId }
} = secretSync;
const credentials = await decryptAppConnectionCredentials({
orgId,
encryptedCredentials,
- kmsService
+ kmsService,
+ projectId
});
const secretSyncWithCredentials = {
@@ -624,13 +629,14 @@ export const secretSyncQueueFactory = ({
try {
const {
- connection: { orgId, encryptedCredentials }
+ connection: { orgId, encryptedCredentials, projectId }
} = secretSync;
const credentials = await decryptAppConnectionCredentials({
orgId,
encryptedCredentials,
- kmsService
+ kmsService,
+ projectId
});
await $importSecrets(
@@ -744,13 +750,14 @@ export const secretSyncQueueFactory = ({
try {
const {
- connection: { orgId, encryptedCredentials }
+ connection: { orgId, encryptedCredentials, projectId }
} = secretSync;
const credentials = await decryptAppConnectionCredentials({
orgId,
encryptedCredentials,
- kmsService
+ kmsService,
+ projectId
});
const secretMap = await $getInfisicalSecrets(secretSync);
@@ -895,6 +902,19 @@ export const secretSyncQueueFactory = ({
break;
}
+ const syncPath = `/projects/secret-management/${projectId}/integrations/secret-syncs/${destination}/${secretSync.id}`;
+
+ await notificationService.createUserNotifications(
+ projectAdmins.map((admin) => ({
+ userId: admin.userId,
+ orgId: project.orgId,
+ type: NotificationType.SECRET_SYNC_FAILED,
+ title: `Secret Sync Failed to ${actionLabel} Secrets`,
+ body: `Your **${syncDestination}** sync **${name}** failed to complete${failureMessage ? `: \`${failureMessage}\`` : ""}`,
+ link: syncPath
+ }))
+ );
+
await smtpService.sendMail({
recipients: projectAdmins.map((member) => member.user.email!).filter(Boolean),
template: SmtpTemplates.SecretSyncFailed,
@@ -907,7 +927,7 @@ export const secretSyncQueueFactory = ({
secretPath: folder?.path,
environment: environment?.name,
projectName: project.name,
- syncUrl: `${appCfg.SITE_URL}/projects/secret-management/${projectId}/integrations/secret-syncs/${destination}/${secretSync.id}`
+ syncUrl: `${appCfg.SITE_URL}${syncPath}`
}
});
};
diff --git a/backend/src/services/secret-sync/secret-sync-service.ts b/backend/src/services/secret-sync/secret-sync-service.ts
index 3fdb7fea67..ecd7d04a50 100644
--- a/backend/src/services/secret-sync/secret-sync-service.ts
+++ b/backend/src/services/secret-sync/secret-sync-service.ts
@@ -41,7 +41,7 @@ import { TSecretSyncQueueFactory } from "./secret-sync-queue";
type TSecretSyncServiceFactoryDep = {
secretSyncDAL: TSecretSyncDALFactory;
secretImportDAL: TSecretImportDALFactory;
- appConnectionService: Pick<TAppConnectionServiceFactory, "connectAppConnectionById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
folderDAL: Pick<TSecretFolderDALFactory, "findByProjectId" | "findById" | "findBySecretPath">;
@@ -267,7 +267,11 @@ export const secretSyncServiceFactory = ({
const destinationApp = SECRET_SYNC_CONNECTION_MAP[params.destination];
// validates permission to connect and app is valid for sync destination
- await appConnectionService.connectAppConnectionById(destinationApp, params.connectionId, actor);
+ await appConnectionService.validateAppConnectionUsageById(
+ destinationApp,
+ { connectionId: params.connectionId, projectId },
+ actor
+ );
try {
const secretSync = await secretSyncDAL.create({
@@ -362,7 +366,11 @@ export const secretSyncServiceFactory = ({
const destinationApp = SECRET_SYNC_CONNECTION_MAP[secretSync.destination as SecretSync];
// validates permission to connect and app is valid for sync destination
- await appConnectionService.connectAppConnectionById(destinationApp, params.connectionId, actor);
+ await appConnectionService.validateAppConnectionUsageById(
+ destinationApp,
+ { connectionId: params.connectionId, projectId: secretSync.projectId },
+ actor
+ );
}
if (
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
index 93afb3b558..d8220e4f54 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
@@ -446,9 +446,10 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
})
.where((bd) => {
- void bd
- .whereNull(`${TableName.SecretV2}.userId`)
- .orWhere({ [`${TableName.SecretV2}.userId` as "userId"]: userId || null });
+ void bd.whereNull(`${TableName.SecretV2}.userId`);
+ // scott: removing this as we don't need to count overrides
+ // and there is currently a bug when you move secrets that doesn't move the override so this can skew count
+ // .orWhere({ [`${TableName.SecretV2}.userId` as "userId"]: userId || null });
})
.countDistinct(`${TableName.SecretV2}.key`);
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
index 84b622b93f..37a5dcd6fd 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-service.ts
@@ -491,15 +491,16 @@ export const secretV2BridgeServiceFactory = ({
secret = sharedSecretToModify;
}
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionSecretActions.Edit,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: inputSecret.secretName,
- secretTags: secret.tags.map((el) => el.slug)
- })
- );
+ if (secret.type !== SecretType.Personal)
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionSecretActions.Edit,
+ subject(ProjectPermissionSub.Secrets, {
+ environment,
+ secretPath,
+ secretName: inputSecret.secretName,
+ secretTags: secret.tags.map((el) => el.slug)
+ })
+ );
// validate tags
// fetch all tags and if not same count throw error meaning one was invalid tags
@@ -510,17 +511,18 @@ export const secretV2BridgeServiceFactory = ({
const tagsToCheck = inputSecret.tagIds ? newTags : secret.tags;
// now check with new ids
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionSecretActions.Edit,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: inputSecret.secretName,
- ...(tagsToCheck.length && {
- secretTags: tagsToCheck.map((el) => el.slug)
+ if (secret.type !== SecretType.Personal)
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionSecretActions.Edit,
+ subject(ProjectPermissionSub.Secrets, {
+ environment,
+ secretPath,
+ secretName: inputSecret.secretName,
+ ...(tagsToCheck.length && {
+ secretTags: tagsToCheck.map((el) => el.slug)
+ })
})
- })
- );
+ );
if (inputSecret.newSecretName) {
const doesNewNameSecretExist = await secretDAL.findOne({
@@ -727,15 +729,17 @@ export const secretV2BridgeServiceFactory = ({
})
});
if (!secretToDelete) throw new NotFoundError({ message: "Secret not found" });
- ForbiddenError.from(permission).throwUnlessCan(
- ProjectPermissionSecretActions.Delete,
- subject(ProjectPermissionSub.Secrets, {
- environment,
- secretPath,
- secretName: secretToDelete.key,
- secretTags: secretToDelete.tags?.map((el) => el.slug)
- })
- );
+
+ if (secretToDelete.type !== SecretType.Personal)
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionSecretActions.Delete,
+ subject(ProjectPermissionSub.Secrets, {
+ environment,
+ secretPath,
+ secretName: secretToDelete.key,
+ secretTags: secretToDelete.tags?.map((el) => el.slug)
+ })
+ );
try {
const deletedSecret = await secretDAL.transaction(async (tx) => {
@@ -1679,7 +1683,7 @@ export const secretV2BridgeServiceFactory = ({
await scanSecretPolicyViolations(projectId, secretPath, inputSecrets, project.secretDetectionIgnoreValues || []);
// get all tags
- const sanitizedTagIds = inputSecrets.flatMap(({ tagIds = [] }) => tagIds);
+ const sanitizedTagIds = [...new Set(inputSecrets.flatMap(({ tagIds = [] }) => tagIds))];
const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds) : [];
if (tags.length !== sanitizedTagIds.length)
throw new NotFoundError({ message: `Tag not found. Found ${tags.map((el) => el.slug).join(",")}` });
@@ -1927,7 +1931,7 @@ export const secretV2BridgeServiceFactory = ({
});
// get all tags
- const sanitizedTagIds = secretsToUpdate.flatMap(({ tagIds = [] }) => tagIds);
+ const sanitizedTagIds = [...new Set(secretsToUpdate.flatMap(({ tagIds = [] }) => tagIds))];
const tags = sanitizedTagIds.length ? await secretTagDAL.findManyTagsById(projectId, sanitizedTagIds, tx) : [];
if (tags.length !== sanitizedTagIds.length) throw new NotFoundError({ message: "Tag not found" });
const tagsGroupByID = groupBy(tags, (i) => i.id);
@@ -2354,7 +2358,8 @@ export const secretV2BridgeServiceFactory = ({
actorAuthMethod,
limit = 20,
offset = 0,
- secretId
+ secretId,
+ secretVersions: secretVersionsFilter
}: TGetSecretVersionsDTO) => {
const secret = await secretDAL.findById(secretId);
@@ -2391,6 +2396,7 @@ export const secretV2BridgeServiceFactory = ({
const secretVersions = await secretVersionDAL.findVersionsBySecretIdWithActors({
secretId,
projectId: folder.projectId,
+ secretVersions: secretVersionsFilter,
findOpt: {
offset,
limit,
@@ -2960,7 +2966,7 @@ export const secretV2BridgeServiceFactory = ({
secretKey: secretName
});
- return { tree: stackTrace, value: expandedValue };
+ return { tree: stackTrace, value: expandedValue, secret };
};
const getAccessibleSecrets = async ({
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
index fc7d468ff4..5e2ffc1a0f 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-types.ts
@@ -159,6 +159,7 @@ export type TGetSecretVersionsDTO = Omit<TProjectPermission, "projectId"> & {
limit?: number;
offset?: number;
secretId: string;
+ secretVersions?: string[];
};
export type TSecretReference = { environment: string; secretPath: string; secretKey: string };
diff --git a/backend/src/services/secret/secret-service.ts b/backend/src/services/secret/secret-service.ts
index 6bafa3ba6c..3a5ccc6672 100644
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@ -2568,7 +2568,8 @@ export const secretServiceFactory = ({
actorAuthMethod,
limit = 20,
offset = 0,
- secretId
+ secretId,
+ secretVersions: filterSecretVersions
}: TGetSecretVersionsDTO) => {
const secretVersionV2 = await secretV2BridgeService
.getSecretVersions({
@@ -2578,7 +2579,8 @@ export const secretServiceFactory = ({
actorAuthMethod,
limit,
offset,
- secretId
+ secretId,
+ secretVersions: filterSecretVersions
})
.catch((err) => {
if ((err as Error).message === "BadRequest: Failed to find secret") {
@@ -2970,14 +2972,23 @@ export const secretServiceFactory = ({
actor,
actorId,
actorAuthMethod,
- actorOrgId
+ actorOrgId,
+ projectId: inputProjectId
}: TMoveSecretsDTO) => {
- const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
+ let project;
+ if (projectSlug) {
+ project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
+ } else if (inputProjectId) {
+ project = await projectDAL.findById(inputProjectId);
+ }
+
if (!project) {
throw new NotFoundError({
message: `Project with slug '${projectSlug}' not found`
});
}
+
+ const projectId = project.id;
if (project.version === ProjectVersion.V3) {
return secretV2BridgeService.moveSecrets({
sourceEnvironment,
@@ -3170,7 +3181,7 @@ export const secretServiceFactory = ({
});
}
const destinationFolderPolicy = await secretApprovalPolicyService.getSecretApprovalPolicy(
- project.id,
+ projectId,
destinationFolder.environment.slug,
destinationFolder.path
);
@@ -3257,7 +3268,7 @@ export const secretServiceFactory = ({
}
if (locallyUpdatedSecrets.length) {
await fnSecretBulkUpdate({
- projectId: project.id,
+ projectId,
folderId: destinationFolder.id,
secretVersionDAL,
secretDAL,
@@ -3300,7 +3311,7 @@ export const secretServiceFactory = ({
const locallyDeletedSecrets = decryptedSourceSecrets.map((el) => ({ ...el, operation: SecretOperations.Delete }));
const sourceFolderPolicy = await secretApprovalPolicyService.getSecretApprovalPolicy(
- project.id,
+ projectId,
sourceFolder.environment.slug,
sourceFolder.path
);
diff --git a/backend/src/services/secret/secret-types.ts b/backend/src/services/secret/secret-types.ts
index cd341a8b54..d8c778d7e3 100644
--- a/backend/src/services/secret/secret-types.ts
+++ b/backend/src/services/secret/secret-types.ts
@@ -331,6 +331,7 @@ export type TGetSecretVersionsDTO = Omit<TProjectPermission, "projectId"> & {
limit?: number;
offset?: number;
secretId: string;
+ secretVersions?: string[];
};
export type TSecretReference = { environment: string; secretPath: string };
@@ -534,7 +535,8 @@ export type TSyncSecretsDTO<T extends boolean = false> = {
});
export type TMoveSecretsDTO = {
- projectSlug: string;
+ projectId?: string;
+ projectSlug?: string;
sourceEnvironment: string;
sourceSecretPath: string;
destinationEnvironment: string;
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 7e2027f254..de466614ad 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -32,7 +32,8 @@ export enum PostHogEventTypes {
IssueSshHostHostCert = "Issue SSH Host Host Certificate",
SignCert = "Sign PKI Certificate",
IssueCert = "Issue PKI Certificate",
- InvalidateCache = "Invalidate Cache"
+ InvalidateCache = "Invalidate Cache",
+ NotificationUpdated = "Notification Updated"
}
export type TSecretModifiedEvent = {
@@ -46,7 +47,7 @@ export type TSecretModifiedEvent = {
properties: {
numberOfSecrets: number;
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath: string;
channel?: string;
userAgent?: string;
@@ -232,6 +233,14 @@ export type TInvalidateCacheEvent = {
};
};
+export type TNotificationUpdatedEvent = {
+ event: PostHogEventTypes.NotificationUpdated;
+ properties: {
+ notificationId: string;
+ isRead?: boolean;
+ };
+};
+
export type TPostHogEvent = { distinctId: string; organizationId?: string } & (
| TSecretModifiedEvent
| TAdminInitEvent
@@ -251,4 +260,5 @@ export type TPostHogEvent = { distinctId: string; organizationId?: string } & (
| TSignCertificateEvent
| TIssueCertificateEvent
| TInvalidateCacheEvent
+ | TNotificationUpdatedEvent
);
diff --git a/backend/src/services/user/user-service.ts b/backend/src/services/user/user-service.ts
index f97e98fa34..b8058f327f 100644
--- a/backend/src/services/user/user-service.ts
+++ b/backend/src/services/user/user-service.ts
@@ -294,11 +294,18 @@ export const userServiceFactory = ({
// Delete all user aliases since the email is changing
await userAliasDAL.delete({ userId }, tx);
+ // Ensure EMAIL auth method is included if not already present
+ const currentAuthMethods = user.authMethods || [];
+ const updatedAuthMethods = currentAuthMethods.includes(AuthMethod.EMAIL)
+ ? currentAuthMethods
+ : [...currentAuthMethods, AuthMethod.EMAIL];
+
const updatedUser = await userDAL.updateById(
userId,
{
email: newEmail.toLowerCase(),
- username: newEmail.toLowerCase()
+ username: newEmail.toLowerCase(),
+ authMethods: updatedAuthMethods
},
tx
);
diff --git a/docs/api-reference/endpoints/deprecated/environments/create.mdx b/docs/api-reference/endpoints/deprecated/environments/create.mdx
new file mode 100644
index 0000000000..826dcce3df
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/environments/create.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create"
+openapi: "POST /api/v1/workspace/{workspaceId}/environments"
+---
diff --git a/docs/api-reference/endpoints/deprecated/environments/delete.mdx b/docs/api-reference/endpoints/deprecated/environments/delete.mdx
new file mode 100644
index 0000000000..903e58d2a2
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/environments/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete"
+openapi: "DELETE /api/v1/workspace/{workspaceId}/environments/{id}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/environments/update.mdx b/docs/api-reference/endpoints/deprecated/environments/update.mdx
new file mode 100644
index 0000000000..f939686685
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/environments/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update"
+openapi: "PATCH /api/v1/workspace/{workspaceId}/environments/{id}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/folders/create.mdx b/docs/api-reference/endpoints/deprecated/folders/create.mdx
new file mode 100644
index 0000000000..e1ff3004a0
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/folders/create.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create"
+openapi: "POST /api/v1/folders"
+---
diff --git a/docs/api-reference/endpoints/deprecated/folders/delete.mdx b/docs/api-reference/endpoints/deprecated/folders/delete.mdx
new file mode 100644
index 0000000000..a106cc2eba
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/folders/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete"
+openapi: "DELETE /api/v1/folders/{folderIdOrName}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/folders/get-by-id.mdx b/docs/api-reference/endpoints/deprecated/folders/get-by-id.mdx
new file mode 100644
index 0000000000..db3c4d0cc9
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/folders/get-by-id.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get by ID"
+openapi: "GET /api/v1/folders/{id}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/folders/list.mdx b/docs/api-reference/endpoints/deprecated/folders/list.mdx
new file mode 100644
index 0000000000..f40f93273c
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/folders/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List"
+openapi: "GET /api/v1/folders"
+---
diff --git a/docs/api-reference/endpoints/deprecated/folders/update.mdx b/docs/api-reference/endpoints/deprecated/folders/update.mdx
new file mode 100644
index 0000000000..c54778e946
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/folders/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update"
+openapi: "PATCH /api/v1/folders/{folderId}"
+---
diff --git a/docs/api-reference/endpoints/organizations/workspaces.mdx b/docs/api-reference/endpoints/deprecated/organizations/projects.mdx
similarity index 100%
rename from docs/api-reference/endpoints/organizations/workspaces.mdx
rename to docs/api-reference/endpoints/deprecated/organizations/projects.mdx
diff --git a/docs/api-reference/endpoints/deprecated/project-groups/create.mdx b/docs/api-reference/endpoints/deprecated/project-groups/create.mdx
new file mode 100644
index 0000000000..6dd7f1a4f7
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-groups/create.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create Project Membership"
+openapi: "POST /api/v2/workspace/{projectId}/groups/{groupIdOrName}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-groups/delete.mdx b/docs/api-reference/endpoints/deprecated/project-groups/delete.mdx
new file mode 100644
index 0000000000..07db40d7fc
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-groups/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete Project Membership"
+openapi: "DELETE /api/v2/workspace/{projectId}/groups/{groupId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-groups/get-by-id.mdx b/docs/api-reference/endpoints/deprecated/project-groups/get-by-id.mdx
new file mode 100644
index 0000000000..611f39059a
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-groups/get-by-id.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get Project Membership"
+openapi: "GET /api/v2/workspace/{projectId}/groups/{groupId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-groups/list.mdx b/docs/api-reference/endpoints/deprecated/project-groups/list.mdx
new file mode 100644
index 0000000000..1488fb6aeb
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-groups/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List Project Memberships"
+openapi: "GET /api/v2/workspace/{projectId}/groups"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-groups/update.mdx b/docs/api-reference/endpoints/deprecated/project-groups/update.mdx
new file mode 100644
index 0000000000..8b963a1d87
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-groups/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update Project Membership"
+openapi: "PATCH /api/v2/workspace/{projectId}/groups/{groupId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-identities/add-identity-membership.mdx b/docs/api-reference/endpoints/deprecated/project-identities/add-identity-membership.mdx
new file mode 100644
index 0000000000..285b1d1c4f
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-identities/add-identity-membership.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create Identity Membership"
+openapi: "POST /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-identities/delete-identity-membership.mdx b/docs/api-reference/endpoints/deprecated/project-identities/delete-identity-membership.mdx
new file mode 100644
index 0000000000..e2b2666263
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-identities/delete-identity-membership.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete Identity Membership"
+openapi: "DELETE /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-identities/get-by-id.mdx b/docs/api-reference/endpoints/deprecated/project-identities/get-by-id.mdx
new file mode 100644
index 0000000000..37f4192d75
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-identities/get-by-id.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get Identity by ID"
+openapi: "GET /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-identities/list-identity-memberships.mdx b/docs/api-reference/endpoints/deprecated/project-identities/list-identity-memberships.mdx
new file mode 100644
index 0000000000..e5162e693d
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-identities/list-identity-memberships.mdx
@@ -0,0 +1,4 @@
+---
+title: "List Identity Memberships"
+openapi: "GET /api/v2/workspace/{projectId}/identity-memberships"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-identities/update-identity-membership.mdx b/docs/api-reference/endpoints/deprecated/project-identities/update-identity-membership.mdx
new file mode 100644
index 0000000000..667cf7eb34
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-identities/update-identity-membership.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update Identity Membership"
+openapi: "PATCH /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-roles/create.mdx b/docs/api-reference/endpoints/deprecated/project-roles/create.mdx
new file mode 100644
index 0000000000..97570ec36c
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-roles/create.mdx
@@ -0,0 +1,10 @@
+---
+title: "Create"
+openapi: "POST /api/v2/workspace/{projectId}/roles"
+---
+
+<Note>
+ You can read more about the permissions field in the [permissions
+ documentation](/internals/permissions).
+</Note>
+
diff --git a/docs/api-reference/endpoints/deprecated/project-roles/delete.mdx b/docs/api-reference/endpoints/deprecated/project-roles/delete.mdx
new file mode 100644
index 0000000000..41edfa7c3b
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-roles/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete"
+openapi: "DELETE /api/v2/workspace/{projectId}/roles/{roleId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-roles/get-by-slug.mdx b/docs/api-reference/endpoints/deprecated/project-roles/get-by-slug.mdx
new file mode 100644
index 0000000000..dfc5c582a7
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-roles/get-by-slug.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get By Slug"
+openapi: "GET /api/v2/workspace/{projectId}/roles/slug/{roleSlug}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-roles/list.mdx b/docs/api-reference/endpoints/deprecated/project-roles/list.mdx
new file mode 100644
index 0000000000..8d8dc10c19
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-roles/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List"
+openapi: "GET /api/v2/workspace/{projectId}/roles"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-roles/update.mdx b/docs/api-reference/endpoints/deprecated/project-roles/update.mdx
new file mode 100644
index 0000000000..662d5e6170
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-roles/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update"
+openapi: "PATCH /api/v2/workspace/{projectId}/roles/{roleId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-users/delete-membership.mdx b/docs/api-reference/endpoints/deprecated/project-users/delete-membership.mdx
new file mode 100644
index 0000000000..1995e47261
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-users/delete-membership.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete User Membership"
+openapi: "DELETE /api/v1/workspace/{workspaceId}/memberships/{membershipId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/project-users/get-by-username.mdx b/docs/api-reference/endpoints/deprecated/project-users/get-by-username.mdx
new file mode 100644
index 0000000000..ec69d49472
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-users/get-by-username.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get By Username"
+openapi: "POST /api/v1/workspace/{workspaceId}/memberships/details"
+---
diff --git a/docs/api-reference/endpoints/project-users/invite-member-to-workspace.mdx b/docs/api-reference/endpoints/deprecated/project-users/invite-member-to-project.mdx
similarity index 100%
rename from docs/api-reference/endpoints/project-users/invite-member-to-workspace.mdx
rename to docs/api-reference/endpoints/deprecated/project-users/invite-member-to-project.mdx
diff --git a/docs/api-reference/endpoints/deprecated/project-users/memberships.mdx b/docs/api-reference/endpoints/deprecated/project-users/memberships.mdx
new file mode 100644
index 0000000000..3c4735f943
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-users/memberships.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get User Memberships"
+openapi: "GET /api/v1/workspace/{workspaceId}/memberships"
+---
diff --git a/docs/api-reference/endpoints/project-users/remove-member-from-workspace.mdx b/docs/api-reference/endpoints/deprecated/project-users/remove-member-from-project.mdx
similarity index 100%
rename from docs/api-reference/endpoints/project-users/remove-member-from-workspace.mdx
rename to docs/api-reference/endpoints/deprecated/project-users/remove-member-from-project.mdx
diff --git a/docs/api-reference/endpoints/deprecated/project-users/update-membership.mdx b/docs/api-reference/endpoints/deprecated/project-users/update-membership.mdx
new file mode 100644
index 0000000000..9a7aa600f0
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/project-users/update-membership.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update User Membership"
+openapi: "PATCH /api/v1/workspace/{workspaceId}/memberships/{membershipId}"
+---
diff --git a/docs/api-reference/endpoints/workspaces/create-workspace.mdx b/docs/api-reference/endpoints/deprecated/projects/create-project.mdx
similarity index 100%
rename from docs/api-reference/endpoints/workspaces/create-workspace.mdx
rename to docs/api-reference/endpoints/deprecated/projects/create-project.mdx
diff --git a/docs/api-reference/endpoints/workspaces/delete-workspace.mdx b/docs/api-reference/endpoints/deprecated/projects/delete-project.mdx
similarity index 100%
rename from docs/api-reference/endpoints/workspaces/delete-workspace.mdx
rename to docs/api-reference/endpoints/deprecated/projects/delete-project.mdx
diff --git a/docs/api-reference/endpoints/workspaces/get-workspace-by-slug.mdx b/docs/api-reference/endpoints/deprecated/projects/get-project-by-slug.mdx
similarity index 100%
rename from docs/api-reference/endpoints/workspaces/get-workspace-by-slug.mdx
rename to docs/api-reference/endpoints/deprecated/projects/get-project-by-slug.mdx
diff --git a/docs/api-reference/endpoints/workspaces/get-workspace.mdx b/docs/api-reference/endpoints/deprecated/projects/get-project.mdx
similarity index 94%
rename from docs/api-reference/endpoints/workspaces/get-workspace.mdx
rename to docs/api-reference/endpoints/deprecated/projects/get-project.mdx
index edd0a0276f..a27d41b433 100644
--- a/docs/api-reference/endpoints/workspaces/get-workspace.mdx
+++ b/docs/api-reference/endpoints/deprecated/projects/get-project.mdx
@@ -1,4 +1,4 @@
---
title: "Get Project"
openapi: "GET /api/v1/workspace/{workspaceId}"
----
\ No newline at end of file
+---
diff --git a/docs/api-reference/endpoints/workspaces/workspace-key.mdx b/docs/api-reference/endpoints/deprecated/projects/project-key.mdx
similarity index 100%
rename from docs/api-reference/endpoints/workspaces/workspace-key.mdx
rename to docs/api-reference/endpoints/deprecated/projects/project-key.mdx
diff --git a/docs/api-reference/endpoints/workspaces/update-workspace.mdx b/docs/api-reference/endpoints/deprecated/projects/project-workspace.mdx
similarity index 100%
rename from docs/api-reference/endpoints/workspaces/update-workspace.mdx
rename to docs/api-reference/endpoints/deprecated/projects/project-workspace.mdx
diff --git a/docs/api-reference/endpoints/workspaces/rollback-snapshot.mdx b/docs/api-reference/endpoints/deprecated/projects/rollback-snapshot.mdx
similarity index 100%
rename from docs/api-reference/endpoints/workspaces/rollback-snapshot.mdx
rename to docs/api-reference/endpoints/deprecated/projects/rollback-snapshot.mdx
diff --git a/docs/api-reference/endpoints/workspaces/secret-snapshots.mdx b/docs/api-reference/endpoints/deprecated/projects/secret-snapshots.mdx
similarity index 100%
rename from docs/api-reference/endpoints/workspaces/secret-snapshots.mdx
rename to docs/api-reference/endpoints/deprecated/projects/secret-snapshots.mdx
diff --git a/docs/api-reference/endpoints/deprecated/projects/update-project.mdx b/docs/api-reference/endpoints/deprecated/projects/update-project.mdx
new file mode 100644
index 0000000000..699e3e3afe
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/projects/update-project.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update Project"
+openapi: "PATCH /api/v1/workspace/{workspaceId}"
+---
\ No newline at end of file
diff --git a/docs/api-reference/endpoints/deprecated/secret-imports/create.mdx b/docs/api-reference/endpoints/deprecated/secret-imports/create.mdx
new file mode 100644
index 0000000000..3abfb320ff
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-imports/create.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create"
+openapi: "POST /api/v1/secret-imports"
+---
diff --git a/docs/api-reference/endpoints/deprecated/secret-imports/delete.mdx b/docs/api-reference/endpoints/deprecated/secret-imports/delete.mdx
new file mode 100644
index 0000000000..cfa5960b18
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-imports/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete"
+openapi: "DELETE /api/v1/secret-imports/{secretImportId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/secret-imports/list.mdx b/docs/api-reference/endpoints/deprecated/secret-imports/list.mdx
new file mode 100644
index 0000000000..580d4be8d0
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-imports/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List"
+openapi: "GET /api/v1/secret-imports"
+---
diff --git a/docs/api-reference/endpoints/deprecated/secret-imports/update.mdx b/docs/api-reference/endpoints/deprecated/secret-imports/update.mdx
new file mode 100644
index 0000000000..f211332237
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-imports/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update"
+openapi: "PATCH /api/v1/secret-imports/{secretImportId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/secret-tags/create.mdx b/docs/api-reference/endpoints/deprecated/secret-tags/create.mdx
new file mode 100644
index 0000000000..82d0eed175
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-tags/create.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create"
+openapi: "POST /api/v1/workspace/{projectId}/tags"
+---
\ No newline at end of file
diff --git a/docs/api-reference/endpoints/deprecated/secret-tags/delete.mdx b/docs/api-reference/endpoints/deprecated/secret-tags/delete.mdx
new file mode 100644
index 0000000000..cc98f03c28
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-tags/delete.mdx
@@ -0,0 +1,4 @@
+---
+title: "Delete"
+openapi: "DELETE /api/v1/workspace/{projectId}/tags/{tagId}"
+---
\ No newline at end of file
diff --git a/docs/api-reference/endpoints/deprecated/secret-tags/get-by-id.mdx b/docs/api-reference/endpoints/deprecated/secret-tags/get-by-id.mdx
new file mode 100644
index 0000000000..de02fe1332
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-tags/get-by-id.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get By ID"
+openapi: "GET /api/v1/workspace/{projectId}/tags/{tagId}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/secret-tags/get-by-slug.mdx b/docs/api-reference/endpoints/deprecated/secret-tags/get-by-slug.mdx
new file mode 100644
index 0000000000..91eab730f5
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-tags/get-by-slug.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get By Slug"
+openapi: "GET /api/v1/workspace/{projectId}/tags/slug/{tagSlug}"
+---
diff --git a/docs/api-reference/endpoints/deprecated/secret-tags/list.mdx b/docs/api-reference/endpoints/deprecated/secret-tags/list.mdx
new file mode 100644
index 0000000000..c4a940f77c
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-tags/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List"
+openapi: "GET /api/v1/workspace/{projectId}/tags"
+---
\ No newline at end of file
diff --git a/docs/api-reference/endpoints/deprecated/secret-tags/update.mdx b/docs/api-reference/endpoints/deprecated/secret-tags/update.mdx
new file mode 100644
index 0000000000..b9c290db8a
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secret-tags/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update"
+openapi: "PATCH /api/v1/workspace/{projectId}/tags/{tagId}"
+---
diff --git a/docs/api-reference/endpoints/secrets/attach-tags.mdx b/docs/api-reference/endpoints/deprecated/secrets/attach-tags.mdx
similarity index 100%
rename from docs/api-reference/endpoints/secrets/attach-tags.mdx
rename to docs/api-reference/endpoints/deprecated/secrets/attach-tags.mdx
diff --git a/docs/api-reference/endpoints/deprecated/secrets/create-many.mdx b/docs/api-reference/endpoints/deprecated/secrets/create-many.mdx
new file mode 100644
index 0000000000..227c5470d0
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/create-many.mdx
@@ -0,0 +1,5 @@
+---
+title: "Bulk Create"
+openapi: "POST /api/v3/secrets/batch/raw"
+---
+
diff --git a/docs/api-reference/endpoints/deprecated/secrets/create.mdx b/docs/api-reference/endpoints/deprecated/secrets/create.mdx
new file mode 100644
index 0000000000..afee0a719f
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/create.mdx
@@ -0,0 +1,5 @@
+---
+title: "Create"
+openapi: "POST /api/v3/secrets/raw/{secretName}"
+---
+
diff --git a/docs/api-reference/endpoints/deprecated/secrets/delete-many.mdx b/docs/api-reference/endpoints/deprecated/secrets/delete-many.mdx
new file mode 100644
index 0000000000..57c8588d8a
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/delete-many.mdx
@@ -0,0 +1,5 @@
+---
+title: "Bulk Delete"
+openapi: "DELETE /api/v3/secrets/batch/raw"
+---
+
diff --git a/docs/api-reference/endpoints/deprecated/secrets/delete.mdx b/docs/api-reference/endpoints/deprecated/secrets/delete.mdx
new file mode 100644
index 0000000000..ef3abc722d
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/delete.mdx
@@ -0,0 +1,5 @@
+---
+title: "Delete"
+openapi: "DELETE /api/v3/secrets/raw/{secretName}"
+---
+
diff --git a/docs/api-reference/endpoints/secrets/detach-tags.mdx b/docs/api-reference/endpoints/deprecated/secrets/detach-tags.mdx
similarity index 100%
rename from docs/api-reference/endpoints/secrets/detach-tags.mdx
rename to docs/api-reference/endpoints/deprecated/secrets/detach-tags.mdx
diff --git a/docs/api-reference/endpoints/deprecated/secrets/list.mdx b/docs/api-reference/endpoints/deprecated/secrets/list.mdx
new file mode 100644
index 0000000000..4808f6690d
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/list.mdx
@@ -0,0 +1,4 @@
+---
+title: "List"
+openapi: "GET /api/v3/secrets/raw"
+---
diff --git a/docs/api-reference/endpoints/deprecated/secrets/read.mdx b/docs/api-reference/endpoints/deprecated/secrets/read.mdx
new file mode 100644
index 0000000000..6af308e0ff
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/read.mdx
@@ -0,0 +1,5 @@
+---
+title: "Retrieve"
+openapi: "GET /api/v3/secrets/raw/{secretName}"
+---
+
diff --git a/docs/api-reference/endpoints/deprecated/secrets/update-many.mdx b/docs/api-reference/endpoints/deprecated/secrets/update-many.mdx
new file mode 100644
index 0000000000..7586d91bce
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/update-many.mdx
@@ -0,0 +1,5 @@
+---
+title: "Bulk Update"
+openapi: "PATCH /api/v3/secrets/batch/raw"
+---
+
diff --git a/docs/api-reference/endpoints/deprecated/secrets/update.mdx b/docs/api-reference/endpoints/deprecated/secrets/update.mdx
new file mode 100644
index 0000000000..ce68c492e5
--- /dev/null
+++ b/docs/api-reference/endpoints/deprecated/secrets/update.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update"
+openapi: "PATCH /api/v3/secrets/raw/{secretName}"
+---
diff --git a/docs/api-reference/endpoints/environments/create.mdx b/docs/api-reference/endpoints/environments/create.mdx
index 826dcce3df..c7f9b06588 100644
--- a/docs/api-reference/endpoints/environments/create.mdx
+++ b/docs/api-reference/endpoints/environments/create.mdx
@@ -1,4 +1,4 @@
---
title: "Create"
-openapi: "POST /api/v1/workspace/{workspaceId}/environments"
+openapi: "POST /api/v1/projects/{projectId}/environments"
---
diff --git a/docs/api-reference/endpoints/environments/delete.mdx b/docs/api-reference/endpoints/environments/delete.mdx
index 903e58d2a2..2d24192555 100644
--- a/docs/api-reference/endpoints/environments/delete.mdx
+++ b/docs/api-reference/endpoints/environments/delete.mdx
@@ -1,4 +1,4 @@
---
title: "Delete"
-openapi: "DELETE /api/v1/workspace/{workspaceId}/environments/{id}"
+openapi: "DELETE /api/v1/projects/{projectId}/environments/{id}"
---
diff --git a/docs/api-reference/endpoints/environments/update.mdx b/docs/api-reference/endpoints/environments/update.mdx
index f939686685..1583f5220a 100644
--- a/docs/api-reference/endpoints/environments/update.mdx
+++ b/docs/api-reference/endpoints/environments/update.mdx
@@ -1,4 +1,4 @@
---
title: "Update"
-openapi: "PATCH /api/v1/workspace/{workspaceId}/environments/{id}"
+openapi: "PATCH /api/v1/projects/{projectId}/environments/{id}"
---
diff --git a/docs/api-reference/endpoints/folders/create.mdx b/docs/api-reference/endpoints/folders/create.mdx
index e1ff3004a0..13c4abea2e 100644
--- a/docs/api-reference/endpoints/folders/create.mdx
+++ b/docs/api-reference/endpoints/folders/create.mdx
@@ -1,4 +1,4 @@
---
title: "Create"
-openapi: "POST /api/v1/folders"
+openapi: "POST /api/v2/folders"
---
diff --git a/docs/api-reference/endpoints/folders/delete.mdx b/docs/api-reference/endpoints/folders/delete.mdx
index a106cc2eba..71ba9684c8 100644
--- a/docs/api-reference/endpoints/folders/delete.mdx
+++ b/docs/api-reference/endpoints/folders/delete.mdx
@@ -1,4 +1,4 @@
---
title: "Delete"
-openapi: "DELETE /api/v1/folders/{folderIdOrName}"
+openapi: "DELETE /api/v2/folders/{folderIdOrName}"
---
diff --git a/docs/api-reference/endpoints/folders/get-by-id.mdx b/docs/api-reference/endpoints/folders/get-by-id.mdx
index db3c4d0cc9..ebfda35da1 100644
--- a/docs/api-reference/endpoints/folders/get-by-id.mdx
+++ b/docs/api-reference/endpoints/folders/get-by-id.mdx
@@ -1,4 +1,4 @@
---
title: "Get by ID"
-openapi: "GET /api/v1/folders/{id}"
+openapi: "GET /api/v2/folders/{id}"
---
diff --git a/docs/api-reference/endpoints/folders/list.mdx b/docs/api-reference/endpoints/folders/list.mdx
index f40f93273c..1d3a10ed8d 100644
--- a/docs/api-reference/endpoints/folders/list.mdx
+++ b/docs/api-reference/endpoints/folders/list.mdx
@@ -1,4 +1,4 @@
---
title: "List"
-openapi: "GET /api/v1/folders"
+openapi: "GET /api/v2/folders"
---
diff --git a/docs/api-reference/endpoints/folders/update.mdx b/docs/api-reference/endpoints/folders/update.mdx
index c54778e946..969833a04a 100644
--- a/docs/api-reference/endpoints/folders/update.mdx
+++ b/docs/api-reference/endpoints/folders/update.mdx
@@ -1,4 +1,4 @@
---
title: "Update"
-openapi: "PATCH /api/v1/folders/{folderId}"
+openapi: "PATCH /api/v2/folders/{folderId}"
---
diff --git a/docs/api-reference/endpoints/project-groups/create.mdx b/docs/api-reference/endpoints/project-groups/create.mdx
index 6dd7f1a4f7..c40c506a6d 100644
--- a/docs/api-reference/endpoints/project-groups/create.mdx
+++ b/docs/api-reference/endpoints/project-groups/create.mdx
@@ -1,4 +1,4 @@
---
title: "Create Project Membership"
-openapi: "POST /api/v2/workspace/{projectId}/groups/{groupIdOrName}"
+openapi: "POST /api/v1/projects/{projectId}/groups/{groupIdOrName}"
---
diff --git a/docs/api-reference/endpoints/project-groups/delete.mdx b/docs/api-reference/endpoints/project-groups/delete.mdx
index 07db40d7fc..450e055019 100644
--- a/docs/api-reference/endpoints/project-groups/delete.mdx
+++ b/docs/api-reference/endpoints/project-groups/delete.mdx
@@ -1,4 +1,4 @@
---
title: "Delete Project Membership"
-openapi: "DELETE /api/v2/workspace/{projectId}/groups/{groupId}"
+openapi: "DELETE /api/v1/projects/{projectId}/groups/{groupId}"
---
diff --git a/docs/api-reference/endpoints/project-groups/get-by-id.mdx b/docs/api-reference/endpoints/project-groups/get-by-id.mdx
index 611f39059a..89aa6ebac7 100644
--- a/docs/api-reference/endpoints/project-groups/get-by-id.mdx
+++ b/docs/api-reference/endpoints/project-groups/get-by-id.mdx
@@ -1,4 +1,4 @@
---
title: "Get Project Membership"
-openapi: "GET /api/v2/workspace/{projectId}/groups/{groupId}"
+openapi: "GET /api/v1/projects/{projectId}/groups/{groupId}"
---
diff --git a/docs/api-reference/endpoints/project-groups/list.mdx b/docs/api-reference/endpoints/project-groups/list.mdx
index 1488fb6aeb..90b4f957a2 100644
--- a/docs/api-reference/endpoints/project-groups/list.mdx
+++ b/docs/api-reference/endpoints/project-groups/list.mdx
@@ -1,4 +1,4 @@
---
title: "List Project Memberships"
-openapi: "GET /api/v2/workspace/{projectId}/groups"
+openapi: "GET /api/v1/projects/{projectId}/groups"
---
diff --git a/docs/api-reference/endpoints/project-groups/update.mdx b/docs/api-reference/endpoints/project-groups/update.mdx
index 8b963a1d87..0298156732 100644
--- a/docs/api-reference/endpoints/project-groups/update.mdx
+++ b/docs/api-reference/endpoints/project-groups/update.mdx
@@ -1,4 +1,4 @@
---
title: "Update Project Membership"
-openapi: "PATCH /api/v2/workspace/{projectId}/groups/{groupId}"
+openapi: "PATCH /api/v1/projects/{projectId}/groups/{groupId}"
---
diff --git a/docs/api-reference/endpoints/project-identities/add-identity-membership.mdx b/docs/api-reference/endpoints/project-identities/add-identity-membership.mdx
index 285b1d1c4f..8b0122efd6 100644
--- a/docs/api-reference/endpoints/project-identities/add-identity-membership.mdx
+++ b/docs/api-reference/endpoints/project-identities/add-identity-membership.mdx
@@ -1,4 +1,4 @@
---
title: "Create Identity Membership"
-openapi: "POST /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+openapi: "POST /api/v1/projects/{projectId}/identity-memberships/{identityId}"
---
diff --git a/docs/api-reference/endpoints/project-identities/delete-identity-membership.mdx b/docs/api-reference/endpoints/project-identities/delete-identity-membership.mdx
index e2b2666263..10c56e5ecc 100644
--- a/docs/api-reference/endpoints/project-identities/delete-identity-membership.mdx
+++ b/docs/api-reference/endpoints/project-identities/delete-identity-membership.mdx
@@ -1,4 +1,4 @@
---
title: "Delete Identity Membership"
-openapi: "DELETE /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+openapi: "DELETE /api/v1/projects/{projectId}/identity-memberships/{identityId}"
---
diff --git a/docs/api-reference/endpoints/project-identities/get-by-id.mdx b/docs/api-reference/endpoints/project-identities/get-by-id.mdx
index 37f4192d75..801b0d422f 100644
--- a/docs/api-reference/endpoints/project-identities/get-by-id.mdx
+++ b/docs/api-reference/endpoints/project-identities/get-by-id.mdx
@@ -1,4 +1,4 @@
---
title: "Get Identity by ID"
-openapi: "GET /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+openapi: "GET /api/v1/projects/{projectId}/identity-memberships/{identityId}"
---
diff --git a/docs/api-reference/endpoints/project-identities/list-identity-memberships.mdx b/docs/api-reference/endpoints/project-identities/list-identity-memberships.mdx
index e5162e693d..8673350fa9 100644
--- a/docs/api-reference/endpoints/project-identities/list-identity-memberships.mdx
+++ b/docs/api-reference/endpoints/project-identities/list-identity-memberships.mdx
@@ -1,4 +1,4 @@
---
title: "List Identity Memberships"
-openapi: "GET /api/v2/workspace/{projectId}/identity-memberships"
+openapi: "GET /api/v1/projects/{projectId}/identity-memberships"
---
diff --git a/docs/api-reference/endpoints/project-identities/update-identity-membership.mdx b/docs/api-reference/endpoints/project-identities/update-identity-membership.mdx
index 667cf7eb34..ef34363d6b 100644
--- a/docs/api-reference/endpoints/project-identities/update-identity-membership.mdx
+++ b/docs/api-reference/endpoints/project-identities/update-identity-membership.mdx
@@ -1,4 +1,4 @@
---
title: "Update Identity Membership"
-openapi: "PATCH /api/v2/workspace/{projectId}/identity-memberships/{identityId}"
+openapi: "PATCH /api/v1/projects/{projectId}/identity-memberships/{identityId}"
---
diff --git a/docs/api-reference/endpoints/project-roles/create.mdx b/docs/api-reference/endpoints/project-roles/create.mdx
index 97570ec36c..1d3f9eb51f 100644
--- a/docs/api-reference/endpoints/project-roles/create.mdx
+++ b/docs/api-reference/endpoints/project-roles/create.mdx
@@ -1,10 +1,9 @@
---
title: "Create"
-openapi: "POST /api/v2/workspace/{projectId}/roles"
+openapi: "POST /api/v1/projects/{projectId}/roles"
---
<Note>
You can read more about the permissions field in the [permissions
documentation](/internals/permissions).
</Note>
-
diff --git a/docs/api-reference/endpoints/project-roles/delete.mdx b/docs/api-reference/endpoints/project-roles/delete.mdx
index 41edfa7c3b..7b162c6da5 100644
--- a/docs/api-reference/endpoints/project-roles/delete.mdx
+++ b/docs/api-reference/endpoints/project-roles/delete.mdx
@@ -1,4 +1,4 @@
---
title: "Delete"
-openapi: "DELETE /api/v2/workspace/{projectId}/roles/{roleId}"
+openapi: "DELETE /api/v1/projects/{projectId}/roles/{roleId}"
---
diff --git a/docs/api-reference/endpoints/project-roles/get-by-slug.mdx b/docs/api-reference/endpoints/project-roles/get-by-slug.mdx
index dfc5c582a7..adfac8cd35 100644
--- a/docs/api-reference/endpoints/project-roles/get-by-slug.mdx
+++ b/docs/api-reference/endpoints/project-roles/get-by-slug.mdx
@@ -1,4 +1,4 @@
---
title: "Get By Slug"
-openapi: "GET /api/v2/workspace/{projectId}/roles/slug/{roleSlug}"
+openapi: "GET /api/v1/projects/{projectId}/roles/slug/{roleSlug}"
---
diff --git a/docs/api-reference/endpoints/project-roles/list.mdx b/docs/api-reference/endpoints/project-roles/list.mdx
index 8d8dc10c19..df61643704 100644
--- a/docs/api-reference/endpoints/project-roles/list.mdx
+++ b/docs/api-reference/endpoints/project-roles/list.mdx
@@ -1,4 +1,4 @@
---
title: "List"
-openapi: "GET /api/v2/workspace/{projectId}/roles"
+openapi: "GET /api/v1/projects/{projectId}/roles"
---
diff --git a/docs/api-reference/endpoints/project-roles/update.mdx b/docs/api-reference/endpoints/project-roles/update.mdx
index 662d5e6170..56ac34f8b3 100644
--- a/docs/api-reference/endpoints/project-roles/update.mdx
+++ b/docs/api-reference/endpoints/project-roles/update.mdx
@@ -1,4 +1,4 @@
---
title: "Update"
-openapi: "PATCH /api/v2/workspace/{projectId}/roles/{roleId}"
+openapi: "PATCH /api/v1/projects/{projectId}/roles/{roleId}"
---
diff --git a/docs/api-reference/endpoints/project-users/delete-membership.mdx b/docs/api-reference/endpoints/project-users/delete-membership.mdx
index 1995e47261..5c87e94af9 100644
--- a/docs/api-reference/endpoints/project-users/delete-membership.mdx
+++ b/docs/api-reference/endpoints/project-users/delete-membership.mdx
@@ -1,4 +1,4 @@
---
title: "Delete User Membership"
-openapi: "DELETE /api/v1/workspace/{workspaceId}/memberships/{membershipId}"
+openapi: "DELETE /api/v1/projects/{projectId}/memberships/{membershipId}"
---
diff --git a/docs/api-reference/endpoints/project-users/get-by-username.mdx b/docs/api-reference/endpoints/project-users/get-by-username.mdx
index ec69d49472..5e4916b8ef 100644
--- a/docs/api-reference/endpoints/project-users/get-by-username.mdx
+++ b/docs/api-reference/endpoints/project-users/get-by-username.mdx
@@ -1,4 +1,4 @@
---
title: "Get By Username"
-openapi: "POST /api/v1/workspace/{workspaceId}/memberships/details"
+openapi: "POST /api/v1/projects/{projectId}/memberships/details"
---
diff --git a/docs/api-reference/endpoints/project-users/invite-member-to-project.mdx b/docs/api-reference/endpoints/project-users/invite-member-to-project.mdx
new file mode 100644
index 0000000000..c6fda8a092
--- /dev/null
+++ b/docs/api-reference/endpoints/project-users/invite-member-to-project.mdx
@@ -0,0 +1,4 @@
+---
+title: "Invite Member"
+openapi: "POST /api/v1/projects/{projectId}/memberships"
+---
diff --git a/docs/api-reference/endpoints/project-users/memberships.mdx b/docs/api-reference/endpoints/project-users/memberships.mdx
index 3c4735f943..dd79667fe0 100644
--- a/docs/api-reference/endpoints/project-users/memberships.mdx
+++ b/docs/api-reference/endpoints/project-users/memberships.mdx
@@ -1,4 +1,4 @@
---
title: "Get User Memberships"
-openapi: "GET /api/v1/workspace/{workspaceId}/memberships"
+openapi: "GET /api/v1/projects/{projectId}/memberships"
---
diff --git a/docs/api-reference/endpoints/project-users/remove-member-from-project.mdx b/docs/api-reference/endpoints/project-users/remove-member-from-project.mdx
new file mode 100644
index 0000000000..8646aa158e
--- /dev/null
+++ b/docs/api-reference/endpoints/project-users/remove-member-from-project.mdx
@@ -0,0 +1,4 @@
+---
+title: "Remove Member"
+openapi: "DELETE /api/v1/projects/{projectId}/memberships"
+---
diff --git a/docs/api-reference/endpoints/project-users/update-membership.mdx b/docs/api-reference/endpoints/project-users/update-membership.mdx
index 9a7aa600f0..5f1edcf0ab 100644
--- a/docs/api-reference/endpoints/project-users/update-membership.mdx
+++ b/docs/api-reference/endpoints/project-users/update-membership.mdx
@@ -1,4 +1,4 @@
---
title: "Update User Membership"
-openapi: "PATCH /api/v1/workspace/{workspaceId}/memberships/{membershipId}"
+openapi: "PATCH /api/v1/projects/{projectId}/memberships/{membershipId}"
---
diff --git a/docs/api-reference/endpoints/projects/create-project.mdx b/docs/api-reference/endpoints/projects/create-project.mdx
new file mode 100644
index 0000000000..7ee1caff8c
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/create-project.mdx
@@ -0,0 +1,4 @@
+---
+title: "Create Project"
+openapi: "POST /api/v1/projects"
+---
diff --git a/docs/api-reference/endpoints/projects/delete-project.mdx b/docs/api-reference/endpoints/projects/delete-project.mdx
new file mode 100644
index 0000000000..eff96ded53
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/delete-project.mdx
@@ -0,0 +1,8 @@
+---
+title: "Delete Project"
+openapi: "DELETE /api/v1/projects/{projectId}"
+---
+
+<Warning>
+ This operation is irreversible. All data associated with the project will be deleted. Please use with caution.
+</Warning>
diff --git a/docs/api-reference/endpoints/projects/get-project-by-slug.mdx b/docs/api-reference/endpoints/projects/get-project-by-slug.mdx
new file mode 100644
index 0000000000..9bcccc31e6
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/get-project-by-slug.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get Project By Slug"
+openapi: "GET /api/v1/projects/slug/{slug}"
+---
diff --git a/docs/api-reference/endpoints/projects/get-project.mdx b/docs/api-reference/endpoints/projects/get-project.mdx
new file mode 100644
index 0000000000..6ed92833ee
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/get-project.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get Project"
+openapi: "GET /api/v1/projects/{projectId}"
+---
diff --git a/docs/api-reference/endpoints/projects/list-projects.mdx b/docs/api-reference/endpoints/projects/list-projects.mdx
new file mode 100644
index 0000000000..5017023a16
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/list-projects.mdx
@@ -0,0 +1,4 @@
+---
+title: "List Projects"
+openapi: "GET /api/v1/projects"
+---
diff --git a/docs/api-reference/endpoints/projects/rollback-snapshot.mdx b/docs/api-reference/endpoints/projects/rollback-snapshot.mdx
new file mode 100644
index 0000000000..527c861b28
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/rollback-snapshot.mdx
@@ -0,0 +1,4 @@
+---
+title: "Roll Back to Snapshot"
+openapi: "POST /api/v1/secret-snapshot/{secretSnapshotId}/rollback"
+---
diff --git a/docs/api-reference/endpoints/projects/secret-snapshots.mdx b/docs/api-reference/endpoints/projects/secret-snapshots.mdx
new file mode 100644
index 0000000000..182e615079
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/secret-snapshots.mdx
@@ -0,0 +1,4 @@
+---
+title: "Get Snapshots"
+openapi: "GET /api/v1/projects/{projectId}/secret-snapshots"
+---
diff --git a/docs/api-reference/endpoints/projects/update-project.mdx b/docs/api-reference/endpoints/projects/update-project.mdx
new file mode 100644
index 0000000000..99fcc7b76f
--- /dev/null
+++ b/docs/api-reference/endpoints/projects/update-project.mdx
@@ -0,0 +1,4 @@
+---
+title: "Update Project"
+openapi: "PATCH /api/v1/projects/{projectId}"
+---
diff --git a/docs/api-reference/endpoints/secret-imports/create.mdx b/docs/api-reference/endpoints/secret-imports/create.mdx
index 3abfb320ff..f072e59a4c 100644
--- a/docs/api-reference/endpoints/secret-imports/create.mdx
+++ b/docs/api-reference/endpoints/secret-imports/create.mdx
@@ -1,4 +1,4 @@
---
title: "Create"
-openapi: "POST /api/v1/secret-imports"
+openapi: "POST /api/v2/secret-imports"
---
diff --git a/docs/api-reference/endpoints/secret-imports/delete.mdx b/docs/api-reference/endpoints/secret-imports/delete.mdx
index cfa5960b18..d0b35426b6 100644
--- a/docs/api-reference/endpoints/secret-imports/delete.mdx
+++ b/docs/api-reference/endpoints/secret-imports/delete.mdx
@@ -1,4 +1,4 @@
---
title: "Delete"
-openapi: "DELETE /api/v1/secret-imports/{secretImportId}"
+openapi: "DELETE /api/v2/secret-imports/{secretImportId}"
---
diff --git a/docs/api-reference/endpoints/secret-imports/list.mdx b/docs/api-reference/endpoints/secret-imports/list.mdx
index 580d4be8d0..1cf3e1386e 100644
--- a/docs/api-reference/endpoints/secret-imports/list.mdx
+++ b/docs/api-reference/endpoints/secret-imports/list.mdx
@@ -1,4 +1,4 @@
---
title: "List"
-openapi: "GET /api/v1/secret-imports"
+openapi: "GET /api/v2/secret-imports"
---
diff --git a/docs/api-reference/endpoints/secret-imports/update.mdx b/docs/api-reference/endpoints/secret-imports/update.mdx
index f211332237..146fcd76b3 100644
--- a/docs/api-reference/endpoints/secret-imports/update.mdx
+++ b/docs/api-reference/endpoints/secret-imports/update.mdx
@@ -1,4 +1,4 @@
---
title: "Update"
-openapi: "PATCH /api/v1/secret-imports/{secretImportId}"
+openapi: "PATCH /api/v2/secret-imports/{secretImportId}"
---
diff --git a/docs/api-reference/endpoints/secret-tags/create.mdx b/docs/api-reference/endpoints/secret-tags/create.mdx
index 82d0eed175..d4c587979f 100644
--- a/docs/api-reference/endpoints/secret-tags/create.mdx
+++ b/docs/api-reference/endpoints/secret-tags/create.mdx
@@ -1,4 +1,4 @@
---
title: "Create"
-openapi: "POST /api/v1/workspace/{projectId}/tags"
----
\ No newline at end of file
+openapi: "POST /api/v1/projects/{projectId}/tags"
+---
diff --git a/docs/api-reference/endpoints/secret-tags/delete.mdx b/docs/api-reference/endpoints/secret-tags/delete.mdx
index cc98f03c28..121d6816cd 100644
--- a/docs/api-reference/endpoints/secret-tags/delete.mdx
+++ b/docs/api-reference/endpoints/secret-tags/delete.mdx
@@ -1,4 +1,4 @@
---
title: "Delete"
-openapi: "DELETE /api/v1/workspace/{projectId}/tags/{tagId}"
----
\ No newline at end of file
+openapi: "DELETE /api/v1/projects/{projectId}/tags/{tagId}"
+---
diff --git a/docs/api-reference/endpoints/secret-tags/get-by-id.mdx b/docs/api-reference/endpoints/secret-tags/get-by-id.mdx
index de02fe1332..7e1fa8d7f6 100644
--- a/docs/api-reference/endpoints/secret-tags/get-by-id.mdx
+++ b/docs/api-reference/endpoints/secret-tags/get-by-id.mdx
@@ -1,4 +1,4 @@
---
title: "Get By ID"
-openapi: "GET /api/v1/workspace/{projectId}/tags/{tagId}"
+openapi: "GET /api/v1/projects/{projectId}/tags/{tagId}"
---
diff --git a/docs/api-reference/endpoints/secret-tags/get-by-slug.mdx b/docs/api-reference/endpoints/secret-tags/get-by-slug.mdx
index 91eab730f5..c012c97d43 100644
--- a/docs/api-reference/endpoints/secret-tags/get-by-slug.mdx
+++ b/docs/api-reference/endpoints/secret-tags/get-by-slug.mdx
@@ -1,4 +1,4 @@
---
title: "Get By Slug"
-openapi: "GET /api/v1/workspace/{projectId}/tags/slug/{tagSlug}"
+openapi: "GET /api/v1/projects/{projectId}/tags/slug/{tagSlug}"
---
diff --git a/docs/api-reference/endpoints/secret-tags/list.mdx b/docs/api-reference/endpoints/secret-tags/list.mdx
index c4a940f77c..b7e1eca74a 100644
--- a/docs/api-reference/endpoints/secret-tags/list.mdx
+++ b/docs/api-reference/endpoints/secret-tags/list.mdx
@@ -1,4 +1,4 @@
---
title: "List"
-openapi: "GET /api/v1/workspace/{projectId}/tags"
----
\ No newline at end of file
+openapi: "GET /api/v1/projects/{projectId}/tags"
+---
diff --git a/docs/api-reference/endpoints/secret-tags/update.mdx b/docs/api-reference/endpoints/secret-tags/update.mdx
index b9c290db8a..b20ce49f42 100644
--- a/docs/api-reference/endpoints/secret-tags/update.mdx
+++ b/docs/api-reference/endpoints/secret-tags/update.mdx
@@ -1,4 +1,4 @@
---
title: "Update"
-openapi: "PATCH /api/v1/workspace/{projectId}/tags/{tagId}"
+openapi: "PATCH /api/v1/projects/{projectId}/tags/{tagId}"
---
diff --git a/docs/api-reference/endpoints/secrets/create-many.mdx b/docs/api-reference/endpoints/secrets/create-many.mdx
index 227c5470d0..e3d30aef84 100644
--- a/docs/api-reference/endpoints/secrets/create-many.mdx
+++ b/docs/api-reference/endpoints/secrets/create-many.mdx
@@ -1,5 +1,4 @@
---
title: "Bulk Create"
-openapi: "POST /api/v3/secrets/batch/raw"
+openapi: "POST /api/v4/secrets/batch"
---
-
diff --git a/docs/api-reference/endpoints/secrets/create.mdx b/docs/api-reference/endpoints/secrets/create.mdx
index afee0a719f..c04dcf9f49 100644
--- a/docs/api-reference/endpoints/secrets/create.mdx
+++ b/docs/api-reference/endpoints/secrets/create.mdx
@@ -1,5 +1,4 @@
---
title: "Create"
-openapi: "POST /api/v3/secrets/raw/{secretName}"
+openapi: "POST /api/v4/secrets/{secretName}"
---
-
diff --git a/docs/api-reference/endpoints/secrets/delete-many.mdx b/docs/api-reference/endpoints/secrets/delete-many.mdx
index 57c8588d8a..49491c3b94 100644
--- a/docs/api-reference/endpoints/secrets/delete-many.mdx
+++ b/docs/api-reference/endpoints/secrets/delete-many.mdx
@@ -1,5 +1,4 @@
---
title: "Bulk Delete"
-openapi: "DELETE /api/v3/secrets/batch/raw"
+openapi: "DELETE /api/v4/secrets/batch"
---
-
diff --git a/docs/api-reference/endpoints/secrets/delete.mdx b/docs/api-reference/endpoints/secrets/delete.mdx
index ef3abc722d..f71a851e8c 100644
--- a/docs/api-reference/endpoints/secrets/delete.mdx
+++ b/docs/api-reference/endpoints/secrets/delete.mdx
@@ -1,5 +1,4 @@
---
title: "Delete"
-openapi: "DELETE /api/v3/secrets/raw/{secretName}"
+openapi: "DELETE /api/v4/secrets/{secretName}"
---
-
diff --git a/docs/api-reference/endpoints/secrets/list.mdx b/docs/api-reference/endpoints/secrets/list.mdx
index 4808f6690d..6a1f38d68f 100644
--- a/docs/api-reference/endpoints/secrets/list.mdx
+++ b/docs/api-reference/endpoints/secrets/list.mdx
@@ -1,4 +1,4 @@
---
title: "List"
-openapi: "GET /api/v3/secrets/raw"
+openapi: "GET /api/v4/secrets"
---
diff --git a/docs/api-reference/endpoints/secrets/read.mdx b/docs/api-reference/endpoints/secrets/read.mdx
index 6af308e0ff..10e725ba53 100644
--- a/docs/api-reference/endpoints/secrets/read.mdx
+++ b/docs/api-reference/endpoints/secrets/read.mdx
@@ -1,5 +1,4 @@
---
title: "Retrieve"
-openapi: "GET /api/v3/secrets/raw/{secretName}"
+openapi: "GET /api/v4/secrets/{secretName}"
---
-
diff --git a/docs/api-reference/endpoints/secrets/update-many.mdx b/docs/api-reference/endpoints/secrets/update-many.mdx
index 7586d91bce..9aca17148c 100644
--- a/docs/api-reference/endpoints/secrets/update-many.mdx
+++ b/docs/api-reference/endpoints/secrets/update-many.mdx
@@ -1,5 +1,4 @@
---
title: "Bulk Update"
-openapi: "PATCH /api/v3/secrets/batch/raw"
+openapi: "PATCH /api/v4/secrets/batch"
---
-
diff --git a/docs/api-reference/endpoints/secrets/update.mdx b/docs/api-reference/endpoints/secrets/update.mdx
index ce68c492e5..435f3e0c45 100644
--- a/docs/api-reference/endpoints/secrets/update.mdx
+++ b/docs/api-reference/endpoints/secrets/update.mdx
@@ -1,4 +1,4 @@
---
title: "Update"
-openapi: "PATCH /api/v3/secrets/raw/{secretName}"
+openapi: "PATCH /api/v4/secrets/{secretName}"
---
diff --git a/docs/cli/commands/gateway.mdx b/docs/cli/commands/gateway.mdx
index 99d0e10865..bddbf614c9 100644
--- a/docs/cli/commands/gateway.mdx
+++ b/docs/cli/commands/gateway.mdx
@@ -9,7 +9,7 @@ description: "Run the Infisical gateway or manage its systemd service"
infisical gateway start --name=<name> --relay=<relay-name> --auth-method=<auth-method>
```
</Tab>
- <Tab title="Install gateway service">
+ <Tab title="Start gateway as background daemon (Linux only)">
```bash
sudo infisical gateway systemd install --token=<token> --domain=<domain> --name=<name> --relay=<relay-name>
```
@@ -25,29 +25,29 @@ The gateway system uses SSH reverse tunnels over TCP, eliminating firewall compl
<Warning>
**Deprecation and Migration Notice:** The legacy `infisical gateway` command (v1) will be removed in a future release. Please migrate to `infisical gateway start` (Gateway v2).
-If you are moving from Gateway v1 to Gateway v2, this is NOT a drop-in switch. Gateway v2 creates new gateway instances with new gateway IDs. You must update any existing resources that reference gateway IDs (for example: dynamic secret configs, app connections, or other gateway-bound resources) to point to the new Gateway v2 gateway ID. Until you update those references, traffic will continue to target the old v1 gateway.
+If you are moving from Gateway v1 to Gateway v2, this is NOT a drop-in switch. Gateway v2 creates new gateway instances with new gateway IDs. You must update any existing resources that reference gateway IDs (for example: dynamic secret configs, app connections, or other gateway-bound resources) to point to the new Gateway v2 gateway resource. Until you update those references, traffic will continue to target the old v1 gateway.
</Warning>
## Subcommands & flags
<Accordion title="infisical gateway start" defaultOpen="true">
- Run the Infisical gateway component within your VPC. The gateway establishes an SSH reverse tunnel to the specified relay server and provides secure access to private resources.
+ Run the Infisical gateway component within your the network where your target resources are located. The gateway establishes an SSH reverse tunnel to the specified relay server and provides secure access to private resources within your network.
```bash
infisical gateway start --relay=<relay-name> --name=<name> --auth-method=<auth-method>
```
-The gateway component:
+Once started, the gateway component will:
-- Establishes outbound SSH reverse tunnels to relay servers (no inbound firewall rules needed)
-- Authenticates using SSH certificates issued by Infisical
-- Automatically reconnects if the connection is lost
-- Provides access to private resources within your network
+- Establish outbound SSH reverse tunnels to relay servers (no inbound firewall rules needed)
+- Authenticate using SSH certificates issued by Infisical
+- Automatically reconnect if the connection is lost
+- Provide access to private resources within your network
### Authentication
-The Infisical CLI supports multiple authentication methods. Below are the available authentication methods, with their respective flags.
+The Relay supports multiple authentication methods. Below are the available authentication methods, with their respective flags.
<AccordionGroup>
<Accordion title="Universal Auth">
@@ -361,12 +361,12 @@ sudo systemctl disable infisical-gateway # Disable auto-start on boot
</Accordion>
-## Legacy Gateway Commands (Deprecated)
+## Legacy Gateway Commands
<Accordion title="infisical gateway (deprecated)">
<Warning>
**This command is deprecated and will be removed in a future release.**
-
+
Please migrate to `infisical gateway start` for the new TCP-based SSH tunnel architecture.
**Migration required:** If you are currently using Gateway v1 (via `infisical gateway`), moving to Gateway v2 is not in-place. Gateway v2 provisions new gateway instances with new gateway IDs. Update any resources that reference a gateway ID (for example: dynamic secret configs, app connections, or other gateway-bound resources) to use the new Gateway v2 gateway ID. Until you update those references, traffic will continue to target the old v1 gateway.
@@ -593,7 +593,7 @@ The Infisical CLI supports multiple authentication methods. Below are the availa
<Accordion title="infisical gateway install (deprecated)">
<Warning>
**This command is deprecated and will be removed in a future release.**
-
+
Please migrate to `infisical gateway systemd install` for the new TCP-based SSH tunnel architecture with enhanced security and better performance.
**Migration required:** If you previously installed Gateway v1 via `infisical gateway install`, moving to Gateway v2 is not in-place. Gateway v2 provisions new gateway instances with new gateway IDs. Update any resources that reference a gateway ID (for example: dynamic secret configs, app connections, or other gateway-bound resources) to use the new Gateway v2 gateway ID. Until you update those references, traffic will continue to target the old v1 gateway.
diff --git a/docs/cli/commands/relay.mdx b/docs/cli/commands/relay.mdx
index 46a061da30..b377b9ce21 100644
--- a/docs/cli/commands/relay.mdx
+++ b/docs/cli/commands/relay.mdx
@@ -6,88 +6,70 @@ description: "Relay-related commands for Infisical"
<Tabs>
<Tab title="Start relay">
```bash
- infisical relay start --type=<type> --host=<host> --name=<name> --auth-method=<auth-method>
+ infisical relay start --host=<host> --name=<name> --auth-method=<auth-method>
+ ```
+ </Tab>
+ <Tab title="Start relay as background daemon (Linux only)">
+ ```bash
+ # Install systemd service
+ sudo infisical relay systemd install --host=<host> --name=<name> --token=<token>
+
+ # Uninstall systemd service
+ sudo infisical relay systemd uninstall
```
</Tab>
</Tabs>
## Description
-Relay-related commands for Infisical that provide identity-aware relay infrastructure for routing encrypted traffic:
-
-- **Relay**: Identity-aware server that routes encrypted traffic (can be instance-wide or organization-specific)
-
-The relay system uses SSH reverse tunnels over TCP, eliminating firewall complexity and providing excellent performance for enterprise environments.
+Relay-related commands for Infisical that provide identity-aware relay infrastructure for routing encrypted traffic. Relays are organization-deployed servers that route encrypted traffic between Infisical and your gateways.
## Subcommands & flags
<Accordion title="infisical relay start" defaultOpen="true">
- Run the Infisical relay component. The relay handles network traffic routing and can operate in different modes.
+ Run the Infisical relay component. The relay handles network traffic routing between Infisical and your gateways.
```bash
-infisical relay start --type=<type> --host=<host> --name=<name> --auth-method=<auth-method>
+infisical relay start --host=<host> --name=<name> --auth-method=<auth-method>
```
### Flags
- <Accordion title="--type">
- The type of relay to run. Must be either 'instance' or 'org'.
-
- - **`instance`**: Shared relay server that can be used by all organizations on your Infisical instance. Set up by the instance administrator. Uses `INFISICAL_RELAY_AUTH_SECRET` environment variable for authentication, which must be configured by the instance admin.
- - **`org`**: Dedicated relay server that individual organizations deploy and manage in their own infrastructure. Provides enhanced security, custom geographic placement, and compliance benefits. Uses standard Infisical authentication methods.
-
- ```bash
- # Organization relay (customer-deployed)
- infisical relay start --type=org --host=192.168.1.100 --name=my-org-relay
-
- # Instance relay (configured by instance admin)
- INFISICAL_RELAY_AUTH_SECRET=<secret> infisical relay start --type=instance --host=10.0.1.50 --name=shared-relay
- ```
-
- </Accordion>
-
<Accordion title="--host">
The host (IP address or hostname) of the instance where the relay is deployed. This must be a static public IP or resolvable hostname that gateways can reach.
```bash
# Example with IP address
- infisical relay start --host=203.0.113.100 --type=org --name=my-relay
+ infisical relay start --host=203.0.113.100 --name=my-relay
# Example with hostname
- infisical relay start --host=relay.example.com --type=org --name=my-relay
+ infisical relay start --host=relay.example.com --name=my-relay
```
</Accordion>
<Accordion title="--name">
- The name of the relay.
+ The name of the relay. This is an arbitrary identifier for your relay instance.
```bash
# Example
- infisical relay start --name=my-relay --type=org --host=192.168.1.100
+ infisical relay start --name=my-relay --host=192.168.1.100
```
</Accordion>
### Authentication
-**Organization Relays (`--type=org`):**
-Deploy your own relay server in your infrastructure for enhanced security and reduced latency. Supports all standard Infisical authentication methods documented below.
-
-**Instance Relays (`--type=instance`):**
-Shared relay servers that serve all organizations on your Infisical instance. For Infisical Cloud, these are already running and ready to use. For self-hosted deployments, they're set up by the instance administrator. Authentication is handled via the `INFISICAL_RELAY_AUTH_SECRET` environment variable.
+Relays support all standard Infisical authentication methods. Choose the authentication method that best fits your environment and set the corresponding flags when starting the relay.
```bash
-# Organization relay with Universal Auth (customer-deployed)
-infisical relay start --type=org --host=192.168.1.100 --name=my-org-relay --auth-method=universal-auth --client-id=<client-id> --client-secret=<client-secret>
-
-# Instance relay (configured by instance admin)
-INFISICAL_RELAY_AUTH_SECRET=<secret> infisical relay start --type=instance --host=10.0.1.50 --name=shared-relay
+# Example with Universal Auth
+infisical relay start --host=192.168.1.100 --name=my-relay --auth-method=universal-auth --client-id=<client-id> --client-secret=<client-secret>
```
-### Authentication Methods
+### Available Authentication Methods
-The Infisical CLI supports multiple authentication methods for organization relays. Below are the available authentication methods, with their respective flags.
+The Infisical CLI supports multiple authentication methods for relays. Below are the available authentication methods, with their respective flags.
<AccordionGroup>
<Accordion title="Universal Auth">
@@ -108,7 +90,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
</ParamField>
```bash
- infisical relay start --auth-method=universal-auth --client-id=<client-id> --client-secret=<client-secret> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=universal-auth --client-id=<client-id> --client-secret=<client-secret> --host=<host> --name=<name>
```
</Accordion>
@@ -132,7 +114,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
```bash
- infisical relay start --auth-method=kubernetes --machine-identity-id=<machine-identity-id> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=kubernetes --machine-identity-id=<machine-identity-id> --host=<host> --name=<name>
```
</Accordion>
@@ -153,7 +135,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
```bash
- infisical relay start --auth-method=azure --machine-identity-id=<machine-identity-id> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=azure --machine-identity-id=<machine-identity-id> --host=<host> --name=<name>
```
</Accordion>
@@ -174,7 +156,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
```bash
- infisical relay start --auth-method=gcp-id-token --machine-identity-id=<machine-identity-id> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=gcp-id-token --machine-identity-id=<machine-identity-id> --host=<host> --name=<name>
```
</Accordion>
@@ -196,7 +178,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
</ParamField>
```bash
- infisical relay start --auth-method=gcp-iam --machine-identity-id=<machine-identity-id> --service-account-key-file-path=<service-account-key-file-path> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=gcp-iam --machine-identity-id=<machine-identity-id> --service-account-key-file-path=<service-account-key-file-path> --host=<host> --name=<name>
```
</Accordion>
@@ -215,7 +197,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
</ParamField>
```bash
- infisical relay start --auth-method=aws-iam --machine-identity-id=<machine-identity-id> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=aws-iam --machine-identity-id=<machine-identity-id> --host=<host> --name=<name>
```
</Accordion>
@@ -237,7 +219,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
</ParamField>
```bash
- infisical relay start --auth-method=oidc-auth --machine-identity-id=<machine-identity-id> --jwt=<oidc-jwt> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=oidc-auth --machine-identity-id=<machine-identity-id> --jwt=<oidc-jwt> --host=<host> --name=<name>
```
</Accordion>
@@ -261,7 +243,7 @@ The Infisical CLI supports multiple authentication methods for organization rela
```bash
- infisical relay start --auth-method=jwt-auth --jwt=<jwt> --machine-identity-id=<machine-identity-id> --type=org --host=<host> --name=<name>
+ infisical relay start --auth-method=jwt-auth --jwt=<jwt> --machine-identity-id=<machine-identity-id> --host=<host> --name=<name>
```
</Accordion>
@@ -277,30 +259,132 @@ The Infisical CLI supports multiple authentication methods for organization rela
</ParamField>
```bash
- infisical relay start --token=<token> --type=org --host=<host> --name=<name>
+ infisical relay start --token=<token> --host=<host> --name=<name>
```
</Accordion>
</AccordionGroup>
-### Deployment Considerations
+</Accordion>
+
+<Accordion title="infisical relay systemd" defaultOpen="false">
+ Manage systemd service for Infisical relay. This allows you to install and run the relay as a systemd service on Linux systems.
+ ### Requirements
+ - **Operating System**: Linux only (systemd is not supported on other operating systems)
+ - **Privileges**: Root/sudo privileges required for both install and uninstall operations
+ - **Systemd**: The system must be running systemd as the init system
+
+```bash
+infisical relay systemd <subcommand>
+```
+
+### Subcommands
+
+<Accordion title="install">
+ Install and enable systemd service for the relay. Must be run with sudo on Linux systems.
+
+```bash
+sudo infisical relay systemd install --host=<host> --name=<name> --token=<token> [flags]
+```
+
+#### Flags
+
+<Accordion title="--host">
+ The host (IP address or hostname) of the instance where the relay is deployed. This must be a static public IP or resolvable hostname that gateways can reach.
+
+```bash
+# Example with IP address
+sudo infisical relay systemd install --host=203.0.113.100 --name=my-relay --token=<token>
+
+# Example with hostname
+sudo infisical relay systemd install --host=relay.example.com --name=my-relay --token=<token>
+```
+
+</Accordion>
+
+<Accordion title="--name">
+ The name of the relay.
+
+```bash
+# Example
+sudo infisical relay systemd install --name=my-relay --host=192.168.1.100 --token=<token>
+```
+
+</Accordion>
+
+<Accordion title="--token">
+ Connect with Infisical using machine identity access token.
+
+```bash
+# Example
+sudo infisical relay systemd install --token=<machine-identity-token> --host=<host> --name=<name>
+```
+
+</Accordion>
+
+<Accordion title="--domain">
+ Domain of your self-hosted Infisical instance. Optional flag for specifying a custom domain.
+
+```bash
+# Example
+sudo infisical relay systemd install --domain=http://localhost:8080 --token=<token> --host=<host> --name=<name>
+```
+
+</Accordion>
+
+#### Examples
+
+```bash
+# Install relay with token authentication
+sudo infisical relay systemd install --host=192.168.1.100 --name=my-relay --token=<machine-identity-token>
+
+# Install with custom domain
+sudo infisical relay systemd install --domain=http://localhost:8080 --token=<token> --host=<host> --name=<name>
+```
+
+#### Post-installation
+
+After successful installation, the service will be enabled but not started. To start the service:
+
+```bash
+sudo systemctl start infisical-relay
+```
+
+To check the service status:
+
+```bash
+sudo systemctl status infisical-relay
+```
+
+To view service logs:
+
+```bash
+sudo journalctl -u infisical-relay -f
+```
-**When to use Instance Relays (`--type=instance`):**
+</Accordion>
+
+<Accordion title="uninstall">
+ Uninstall and remove systemd service for the relay. Must be run with sudo on Linux systems.
+
+```bash
+sudo infisical relay systemd uninstall
+```
-- You want to get started quickly without setting up your own relay infrastructure
-- You're using Infisical Cloud and want to leverage the existing relay infrastructure
-- You're on a self-hosted instance where the admin has already set up shared relays
-- You don't need custom geographic placement of relay servers
-- You don't have specific compliance requirements that require dedicated infrastructure
-- You want to minimize operational overhead by using shared infrastructure
+#### Examples
-**When to use Organization Relays (`--type=org`):**
+```bash
+# Uninstall the relay systemd service
+sudo infisical relay systemd uninstall
+```
+
+#### What it does
-- You need lower latency by deploying relay servers closer to your resources
-- You have security requirements that mandate running infrastructure in your own environment
-- You have compliance requirements such as data sovereignty or air-gapped environments
-- You need custom network policies or specific networking configurations
-- You have high-scale performance requirements that shared infrastructure can't meet
-- You want full control over your relay infrastructure and its configuration
+- Stops the `infisical-relay` systemd service if it's running
+- Disables the service from starting on boot
+- Removes the systemd service file
+- Cleans up the service configuration
+
+</Accordion>
</Accordion>
diff --git a/docs/docs.json b/docs/docs.json
index 285e11a608..3b7197da81 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -173,8 +173,9 @@
"group": "Gateway",
"pages": [
"documentation/platform/gateways/overview",
- "documentation/platform/gateways/gateway-security",
- "documentation/platform/gateways/networking",
+ "documentation/platform/gateways/gateway-deployment",
+ "documentation/platform/gateways/relay-deployment",
+ "documentation/platform/gateways/security",
{
"group": "Gateway (Deprecated)",
"pages": [
@@ -1009,28 +1010,55 @@
"api-reference/endpoints/organizations/delete-membership",
"api-reference/endpoints/organizations/bulk-delete-memberships",
"api-reference/endpoints/organizations/list-identity-memberships",
- "api-reference/endpoints/organizations/workspaces"
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/organizations/projects"
+ ]
+ }
]
},
{
"group": "Projects",
"pages": [
- "api-reference/endpoints/workspaces/get-workspace-by-slug",
- "api-reference/endpoints/workspaces/create-workspace",
- "api-reference/endpoints/workspaces/delete-workspace",
- "api-reference/endpoints/workspaces/get-workspace",
- "api-reference/endpoints/workspaces/update-workspace",
- "api-reference/endpoints/workspaces/secret-snapshots"
+ "api-reference/endpoints/projects/get-project-by-slug",
+ "api-reference/endpoints/projects/create-project",
+ "api-reference/endpoints/projects/delete-project",
+ "api-reference/endpoints/projects/get-project",
+ "api-reference/endpoints/projects/list-projects",
+ "api-reference/endpoints/projects/update-project",
+ "api-reference/endpoints/projects/secret-snapshots",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/projects/get-project-by-slug",
+ "api-reference/endpoints/deprecated/projects/create-project",
+ "api-reference/endpoints/deprecated/projects/delete-project",
+ "api-reference/endpoints/deprecated/projects/get-project",
+ "api-reference/endpoints/deprecated/projects/update-project",
+ "api-reference/endpoints/deprecated/projects/secret-snapshots"
+ ]
+ }
]
},
{
"group": "Project Users",
"pages": [
- "api-reference/endpoints/project-users/invite-member-to-workspace",
- "api-reference/endpoints/project-users/remove-member-from-workspace",
+ "api-reference/endpoints/project-users/invite-member-to-project",
+ "api-reference/endpoints/project-users/remove-member-from-project",
"api-reference/endpoints/project-users/memberships",
"api-reference/endpoints/project-users/get-by-username",
- "api-reference/endpoints/project-users/update-membership"
+ "api-reference/endpoints/project-users/update-membership",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/project-users/invite-member-to-project",
+ "api-reference/endpoints/deprecated/project-users/remove-member-from-project",
+ "api-reference/endpoints/deprecated/project-users/memberships",
+ "api-reference/endpoints/deprecated/project-users/get-by-username",
+ "api-reference/endpoints/deprecated/project-users/update-membership"
+ ]
+ }
]
},
{
@@ -1040,7 +1068,17 @@
"api-reference/endpoints/project-groups/delete",
"api-reference/endpoints/project-groups/get-by-id",
"api-reference/endpoints/project-groups/list",
- "api-reference/endpoints/project-groups/update"
+ "api-reference/endpoints/project-groups/update",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/project-groups/create",
+ "api-reference/endpoints/deprecated/project-groups/delete",
+ "api-reference/endpoints/deprecated/project-groups/get-by-id",
+ "api-reference/endpoints/deprecated/project-groups/list",
+ "api-reference/endpoints/deprecated/project-groups/update"
+ ]
+ }
]
},
{
@@ -1050,7 +1088,17 @@
"api-reference/endpoints/project-identities/list-identity-memberships",
"api-reference/endpoints/project-identities/get-by-id",
"api-reference/endpoints/project-identities/update-identity-membership",
- "api-reference/endpoints/project-identities/delete-identity-membership"
+ "api-reference/endpoints/project-identities/delete-identity-membership",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/project-identities/add-identity-membership",
+ "api-reference/endpoints/deprecated/project-identities/list-identity-memberships",
+ "api-reference/endpoints/deprecated/project-identities/get-by-id",
+ "api-reference/endpoints/deprecated/project-identities/update-identity-membership",
+ "api-reference/endpoints/deprecated/project-identities/delete-identity-membership"
+ ]
+ }
]
},
{
@@ -1060,7 +1108,17 @@
"api-reference/endpoints/project-roles/update",
"api-reference/endpoints/project-roles/delete",
"api-reference/endpoints/project-roles/get-by-slug",
- "api-reference/endpoints/project-roles/list"
+ "api-reference/endpoints/project-roles/list",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/project-roles/create",
+ "api-reference/endpoints/deprecated/project-roles/update",
+ "api-reference/endpoints/deprecated/project-roles/delete",
+ "api-reference/endpoints/deprecated/project-roles/get-by-slug",
+ "api-reference/endpoints/deprecated/project-roles/list"
+ ]
+ }
]
},
{
@@ -1078,7 +1136,15 @@
"pages": [
"api-reference/endpoints/environments/create",
"api-reference/endpoints/environments/update",
- "api-reference/endpoints/environments/delete"
+ "api-reference/endpoints/environments/delete",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/environments/create",
+ "api-reference/endpoints/deprecated/environments/update",
+ "api-reference/endpoints/deprecated/environments/delete"
+ ]
+ }
]
},
{
@@ -1088,7 +1154,17 @@
"api-reference/endpoints/folders/get-by-id",
"api-reference/endpoints/folders/create",
"api-reference/endpoints/folders/update",
- "api-reference/endpoints/folders/delete"
+ "api-reference/endpoints/folders/delete",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/folders/list",
+ "api-reference/endpoints/deprecated/folders/get-by-id",
+ "api-reference/endpoints/deprecated/folders/create",
+ "api-reference/endpoints/deprecated/folders/update",
+ "api-reference/endpoints/deprecated/folders/delete"
+ ]
+ }
]
},
{
@@ -1099,7 +1175,18 @@
"api-reference/endpoints/secret-tags/get-by-slug",
"api-reference/endpoints/secret-tags/create",
"api-reference/endpoints/secret-tags/update",
- "api-reference/endpoints/secret-tags/delete"
+ "api-reference/endpoints/secret-tags/delete",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/secret-tags/list",
+ "api-reference/endpoints/deprecated/secret-tags/get-by-id",
+ "api-reference/endpoints/deprecated/secret-tags/get-by-slug",
+ "api-reference/endpoints/deprecated/secret-tags/create",
+ "api-reference/endpoints/deprecated/secret-tags/update",
+ "api-reference/endpoints/deprecated/secret-tags/delete"
+ ]
+ }
]
},
{
@@ -1113,8 +1200,21 @@
"api-reference/endpoints/secrets/create-many",
"api-reference/endpoints/secrets/update-many",
"api-reference/endpoints/secrets/delete-many",
- "api-reference/endpoints/secrets/attach-tags",
- "api-reference/endpoints/secrets/detach-tags"
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/secrets/list",
+ "api-reference/endpoints/deprecated/secrets/create",
+ "api-reference/endpoints/deprecated/secrets/read",
+ "api-reference/endpoints/deprecated/secrets/update",
+ "api-reference/endpoints/deprecated/secrets/delete",
+ "api-reference/endpoints/deprecated/secrets/create-many",
+ "api-reference/endpoints/deprecated/secrets/update-many",
+ "api-reference/endpoints/deprecated/secrets/delete-many",
+ "api-reference/endpoints/deprecated/secrets/attach-tags",
+ "api-reference/endpoints/deprecated/secrets/detach-tags"
+ ]
+ }
]
},
{
@@ -1144,7 +1244,16 @@
"api-reference/endpoints/secret-imports/list",
"api-reference/endpoints/secret-imports/create",
"api-reference/endpoints/secret-imports/update",
- "api-reference/endpoints/secret-imports/delete"
+ "api-reference/endpoints/secret-imports/delete",
+ {
+ "group": "Legacy",
+ "pages": [
+ "api-reference/endpoints/deprecated/secret-imports/list",
+ "api-reference/endpoints/deprecated/secret-imports/create",
+ "api-reference/endpoints/deprecated/secret-imports/update",
+ "api-reference/endpoints/deprecated/secret-imports/delete"
+ ]
+ }
]
},
{
diff --git a/docs/documentation/platform/audit-log-streams/audit-log-streams.mdx b/docs/documentation/platform/audit-log-streams/audit-log-streams.mdx
index 50fa75e92e..ad030ec26a 100644
--- a/docs/documentation/platform/audit-log-streams/audit-log-streams.mdx
+++ b/docs/documentation/platform/audit-log-streams/audit-log-streams.mdx
@@ -45,6 +45,116 @@ Infisical Audit Log Streaming enables you to transmit your organization's audit
## Example Providers
<AccordionGroup>
+ <Accordion title="Azure">
+ Infisical offers a dedicated **Azure** provider to stream your audit logs, enabling seamless integration with services like Microsoft Sentinel.
+
+ <Warning>
+ After setting up all Azure resources, it may take 10-20 minutes for logs to begin streaming.
+ </Warning>
+
+ <Steps>
+ <Step title="Create a Data Collection Endpoint">
+ Navigate to [Data Collection Endpoints](https://portal.azure.com/#view/HubsExtension/BrowseResource.ReactView/resourceType/microsoft.insights%2Fdatacollectionendpoints) and click **Create**.
+
+ ![azure create dce](/images/platform/audit-log-streams/azure-create-dce.png)
+
+ Configure your Data Collection Endpoint by providing an **Endpoint Name**, **Subscription**, and a **Resource group**. Then click **Review + Create**.
+
+ ![azure configure dce](/images/platform/audit-log-streams/azure-configure-dce.png)
+
+ After creation, it may take a few minutes for the Data Collection Endpoint to appear. Once visible, click on it and copy the **Logs Ingestion** URL. You will need this URL in later steps.
+
+ ![azure dce url](/images/platform/audit-log-streams/azure-dce-url.png)
+ </Step>
+ <Step title="Create a Log Analytics Workspace">
+ <Info>
+ If you already have a Log Analytics Workspace, you may skip this step.
+ </Info>
+
+ Navigate to [Log Analytics Workspaces](https://portal.azure.com/#browse/Microsoft.OperationalInsights%2Fworkspaces) and click **Create**.
+
+ ![azure create law](/images/platform/audit-log-streams/azure-create-law.png)
+
+ Configure your Log Analytics Workspace by providing a **Subscription**, **Resource group**, and a **Name**. Then click **Review + Create**.
+
+ ![azure configure law](/images/platform/audit-log-streams/azure-configure-law.png)
+
+ Once the workspace is deployed, click **Go to resource** to access it.
+
+ ![azure go to resource](/images/platform/audit-log-streams/azure-go-to-resource.png)
+ </Step>
+ <Step title="Create a Custom Log Table">
+ Within your Log Analytics Workspace, navigate to **Tables** and click **Create**. Select **New custom log (DCR-based)** from the dropdown.
+
+ ![azure new table](/images/platform/audit-log-streams/azure-new-table.png)
+
+ Configure the Custom Log Table: Provide a **Table name** (e.g., `InfisicalLogs`), select the **Data collection endpoint** created in Step 1, and create a new **Data collection rule** as illustrated in the image below. Then, click **Next**.
+
+ ![azure configure table](/images/platform/audit-log-streams/azure-configure-table.png)
+
+ On the **Schema and transformation** page, you'll be prompted to upload a **Log Sample**. Create a `.json` file with the following content and upload it:
+
+ ```json
+ {
+ "id": "00000000-0000-0000-0000-000000000000",
+ "actor": "user",
+ "actorMetadata": {
+ "email": "[email protected]",
+ "userId": "00000000-0000-0000-0000-000000000000",
+ "username": "[email protected]"
+ },
+ "ipAddress": "0.0.0.0",
+ "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
+ "userAgentType": "web",
+ "eventType": "get-secrets",
+ "eventMetadata": {},
+ "projectName": "MyProject",
+ "orgId": "00000000-0000-0000-0000-000000000000",
+ "projectId": "00000000-0000-0000-0000-000000000000",
+ "TimeGenerated": "2025-01-01T00:00:00.000Z"
+ }
+ ```
+
+ Optionally, you can add **Transformations** to further destructure the data. For example, to extract actor email and userId:
+
+ ```
+ source
+ | extend
+ ActorEmail = tostring(actorMetadata.email),
+ ActorUserId = tostring(actorMetadata.userId)
+ ```
+
+ On the final step, click **Create**.
+
+ <Warning>
+ It may take a few minutes for your Custom Log Table to be created and appear under Tables.
+ </Warning>
+ </Step>
+ <Step title="Obtain Data Collection Rule Immutable ID">
+ After creating your Data Collection Rule, you'll need its **Immutable ID**.
+
+ Navigate to [Data collection rules](https://portal.azure.com/#view/HubsExtension/BrowseResource.ReactView/resourceType/microsoft.insights%2Fdatacollectionrules). Click on your newly created DCR and copy its **Immutable ID** for the next step.
+
+ ![azure dcr](/images/platform/audit-log-streams/azure-dcr.png)
+ </Step>
+ <Step title="Create Audit Log Stream on Infisical">
+ In Infisical, create a new audit log stream and select the **Azure** provider. Input the following details:
+
+ - **Tenant ID**: Your Tenant ID
+ - **Client ID**: The Client ID of an App Registration
+ - **Client Secret**: The Client Secret of an App Registration
+ - **Data Collection Endpoint URL**: Obtained from Step 1
+ - **Data Collection Rule Immutable ID**: Obtained from Step 4
+ - **Custom Log Table Name**: Defined in Step 3
+
+ ![azure create als](/images/platform/audit-log-streams/azure-create-als.png)
+
+ <Warning>
+ The App Registration used for authentication must have the **Monitoring Metrics Publisher** role assigned on the **Data Collection Rule** created in Step 3. [See Microsoft Guide](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/tutorial-logs-ingestion-portal#assign-permissions-to-the-dcr).
+ </Warning>
+ </Step>
+ </Steps>
+ </Accordion>
<Accordion title="Better Stack">
You can stream to Better Stack using a **Custom** log stream.
diff --git a/docs/documentation/platform/auth-methods/email-password.mdx b/docs/documentation/platform/auth-methods/email-password.mdx
index f5cb0e6f5f..5a433a5663 100644
--- a/docs/documentation/platform/auth-methods/email-password.mdx
+++ b/docs/documentation/platform/auth-methods/email-password.mdx
@@ -29,6 +29,9 @@ You can update your account email address:
1. Open the `Personal Settings` menu.
2. Navigate to the `Authentication` tab.
3. In the `Change Email` section, enter your new email address.
+<Info>
+If you don't currently have Email authentication enabled, it will be automatically activated when you change your email. You may disable it in the authentication settings after logging in with your new email if needed.
+</Info>
![change email section](../../../images/auth-methods/personal-settings-authentication-change-email-password.png)
4. Click `Send Verification Code` to receive an 6-digit verification code at your new email address.
5. Check your new email inbox and enter the verification code.
diff --git a/docs/documentation/platform/dynamic-secrets/aws-iam.mdx b/docs/documentation/platform/dynamic-secrets/aws-iam.mdx
index 28b177c5f9..2d500a83aa 100644
--- a/docs/documentation/platform/dynamic-secrets/aws-iam.mdx
+++ b/docs/documentation/platform/dynamic-secrets/aws-iam.mdx
@@ -3,49 +3,93 @@ title: "AWS IAM"
description: "Learn how to dynamically generate AWS IAM Users."
---
-The Infisical AWS IAM dynamic secret allows you to generate AWS IAM Users on demand based on a configured AWS policy. Infisical supports several authentication methods to connect to your AWS account, including assuming an IAM Role, using IAM Roles for Service Accounts (IRSA) on EKS, or static Access Keys.
+The Infisical AWS IAM dynamic secret allows you to generate AWS IAM Users and temporary credentials on demand based on a configured AWS policy. Infisical supports several authentication methods to connect to your AWS account, including assuming an IAM Role, using IAM Roles for Service Accounts (IRSA) on EKS, or static Access Keys.
+
+## AWS STS Duration Limits
+
+When using **Temporary Credentials**, AWS STS has specific maximum duration limits:
+
+- **AssumeRole operations**: Maximum 1 hour (3600 seconds) when using temporary credentials
+- **GetSessionToken operations** (Access Key & IRSA): Maximum 12 hours (43200 seconds)
+
+<Info>
+**Automatic Duration Adjustment**: If you specify a TTL that exceeds these AWS limits, Infisical will automatically use the maximum allowed duration instead of failing the operation. This ensures your dynamic secrets work reliably within AWS constraints.
+</Info>
## Prerequisite
-Infisical needs an AWS IAM principal (a user or a role) with the required permissions to create and manage other IAM users. This principal will be responsible for the lifecycle of the dynamically generated users.
+Infisical needs an AWS IAM principal (a user or a role) with the required permissions to create and manage other IAM users and temporary credentials. This principal will be responsible for the lifecycle of the dynamically generated users and temporary credentials.
<Accordion title="Required IAM Permissions">
-```json
-{
- "Version": "2012-10-17",
- "Statement": [
+<Tabs>
+ <Tab title="IAM User">
+ Required permissions for creating temporary IAM users:
+
+ ```json
+ {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": [
+ "iam:AttachUserPolicy",
+ "iam:CreateAccessKey",
+ "iam:CreateUser",
+ "iam:DeleteAccessKey",
+ "iam:DeleteUser",
+ "iam:DeleteUserPolicy",
+ "iam:DetachUserPolicy",
+ "iam:GetUser",
+ "iam:ListAccessKeys",
+ "iam:ListAttachedUserPolicies",
+ "iam:ListGroupsForUser",
+ "iam:ListUserPolicies",
+ "iam:PutUserPolicy",
+ "iam:AddUserToGroup",
+ "iam:RemoveUserFromGroup",
+ "iam:TagUser"
+ ],
+ "Resource": ["*"]
+ }
+ ]
+ }
+ ```
+
+ To minimize managing user access you can attach a resource in format
+
+ > arn:aws:iam::\<account-id\>:user/\<aws-scope-path\>
+
+ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** with a path to minimize managing user access.
+ </Tab>
+
+ <Tab title="Temporary Credentials">
+ Required permissions for Access Key and Assume Role methods:
+
+ ```json
{
- "Effect": "Allow",
- "Action": [
- "iam:AttachUserPolicy",
- "iam:CreateAccessKey",
- "iam:CreateUser",
- "iam:DeleteAccessKey",
- "iam:DeleteUser",
- "iam:DeleteUserPolicy",
- "iam:DetachUserPolicy",
- "iam:GetUser",
- "iam:ListAccessKeys",
- "iam:ListAttachedUserPolicies",
- "iam:ListGroupsForUser",
- "iam:ListUserPolicies",
- "iam:PutUserPolicy",
- "iam:AddUserToGroup",
- "iam:RemoveUserFromGroup",
- "iam:TagUser"
- ],
- "Resource": ["*"]
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Effect": "Allow",
+ "Action": [
+ "sts:GetSessionToken",
+ "sts:AssumeRole"
+ ],
+ "Resource": ["*"]
+ }
+ ]
}
- ]
-}
-```
+ ```
+
-To minimize managing user access you can attach a resource in format
+ To minimize managing user access you can attach a resource in format
-> arn:aws:iam::\<account-id\>:user/\<aws-scope-path\>
+ > arn:aws:iam::\<account-id\>:user/\<aws-scope-path\>
-Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** with a path to minimize managing user access.
+ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** with a path to minimize managing user access.
+ </Tab>
+</Tabs>
</Accordion>
@@ -170,43 +214,76 @@ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** w
Select *Assume Role* method.
</ParamField>
- <ParamField path="Aws Role ARN" type="string" required>
- The ARN of the AWS Role to assume.
+ <ParamField path="Credential Type" type="string" required>
+ Choose the credential generation approach:
+ - **IAM User (Default)**: Creates new temporary IAM users in your AWS account
+ - **Temporary Credentials**: Generates temporary credentials from your role connection
</ParamField>
- <ParamField path="AWS IAM Path" type="string">
- [IAM AWS Path](https://aws.amazon.com/blogs/security/optimize-aws-administration-with-iam-paths/) to scope created IAM User resource access.
+ <ParamField path="Aws Role ARN" type="string" required>
+ The ARN of the AWS Role to assume.
</ParamField>
<ParamField path="AWS Region" type="string" required>
The AWS data center region.
</ParamField>
- <ParamField path="IAM User Permission Boundary" type="string" required>
- The IAM Policy ARN of the [AWS Permissions Boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to attach to IAM users created in the role.
- </ParamField>
+ <Tabs>
+ <Tab title="IAM User">
+ <ParamField path="AWS IAM Path" type="string">
+ [IAM AWS Path](https://aws.amazon.com/blogs/security/optimize-aws-administration-with-iam-paths/) to scope created IAM User resource access.
+ </ParamField>
- <ParamField path="AWS IAM Groups" type="string">
- The AWS IAM groups that should be assigned to the created users. Multiple values can be provided by separating them with commas
- </ParamField>
+ <ParamField path="IAM User Permission Boundary" type="string">
+ The IAM Policy ARN of the [AWS Permissions Boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to attach to IAM users created in the role.
+ </ParamField>
- <ParamField path="AWS Policy ARNs" type="string">
- The AWS IAM managed policies that should be attached to the created users. Multiple values can be provided by separating them with commas
- </ParamField>
+ <ParamField path="AWS IAM Groups" type="string">
+ The AWS IAM groups that should be assigned to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
- <ParamField path="AWS IAM Policy Document" type="string">
- The AWS IAM inline policy that should be attached to the created users.
- Multiple values can be provided by separating them with commas
- </ParamField>
+ <ParamField path="AWS Policy ARNs" type="string">
+ The AWS IAM managed policies that should be attached to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
- <ParamField path="Username Template" type="string" default="{{randomUsername}}">
- Specifies a template for generating usernames. This field allows customization of how usernames are automatically created.
+ <ParamField path="AWS IAM Policy Document" type="string">
+ The AWS IAM inline policy that should be attached to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
- Allowed template variables are
+ <ParamField path="Username Template" type="string" default="{{randomUsername}}">
+ Specifies a template for generating usernames. This field allows customization of how usernames are automatically created.
- - `{{randomUsername}}`: Random username string
- - `{{unixTimestamp}}`: Current Unix timestamp
- </ParamField>
+ Allowed template variables are:
+ - `{{randomUsername}}`: Random username string
+ - `{{unixTimestamp}}`: Current Unix timestamp
+ - `{{identity.name}}`: Name of the identity that is generating the secret
+ - `{{random N}}`: Random string of N characters
+
+ Allowed template functions are:
+ - `truncate`: Truncates a string to a specified length
+ - `replace`: Replaces a substring with another value
+ </ParamField>
+
+ <ParamField path="Tags" type="map<string, string>[]">
+ Tags to be added to the created IAM User resource.
+ </ParamField>
+ </Tab>
+
+ <Tab title="Temporary Credentials">
+ When **Credential Type** is set to **Temporary Credentials**:
+
+ <Info>
+ No additional configuration parameters are required. The generated credentials will:
+ - Inherit the permissions of the assumed role
+ - Include an AWS Session Token
+ - Be valid for the duration specified in Default TTL
+ </Info>
+
+ <Warning>
+ **Duration Limit**: AssumeRole temporary credentials are limited to 1 hour maximum by AWS. TTL values exceeding this limit will be automatically adjusted to 1 hour.
+ </Warning>
+ </Tab>
+ </Tabs>
</Step>
<Step title="Click 'Submit'">
@@ -232,6 +309,18 @@ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** w
Once you click the `Submit` button, a new secret lease will be generated and the credentials for it will be shown to you.
+ **Credentials format depends on your chosen credential type:**
+
+ **IAM User credential type:**
+ - AWS Username
+ - AWS Access Key ID
+ - AWS Secret Access Key
+
+ **Temporary Credentials credential type:**
+ - AWS Access Key ID
+ - AWS Secret Access Key
+ - AWS Session Token
+
![Provision Lease](/images/platform/dynamic-secrets/lease-values-aws-iam.png)
</Step>
</Steps>
@@ -342,36 +431,75 @@ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** w
<ParamField path="Method" type="string" required>
Select *IRSA* method.
</ParamField>
+ <ParamField path="Credential Type" type="string" required>
+ Choose the credential generation approach:
+ - **IAM User**: Creates new temporary IAM users in your AWS account
+ - **Temporary Credentials**: Generates temporary credentials from your IRSA role connection
+ </ParamField>
<ParamField path="Aws Role ARN" type="string" required>
The ARN of the AWS IAM Role for the service account to assume.
</ParamField>
- <ParamField path="AWS IAM Path" type="string">
- [IAM AWS Path](https://aws.amazon.com/blogs/security/optimize-aws-administration-with-iam-paths/) to scope created IAM User resource access.
- </ParamField>
+
<ParamField path="AWS Region" type="string" required>
The AWS data center region.
</ParamField>
- <ParamField path="IAM User Permission Boundary" type="string" required>
- The IAM Policy ARN of the [AWS Permissions Boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to attach to IAM users created in the role.
- </ParamField>
- <ParamField path="AWS IAM Groups" type="string">
- The AWS IAM groups that should be assigned to the created users. Multiple values can be provided by separating them with commas
- </ParamField>
- <ParamField path="AWS Policy ARNs" type="string">
- The AWS IAM managed policies that should be attached to the created users. Multiple values can be provided by separating them with commas
- </ParamField>
- <ParamField path="AWS IAM Policy Document" type="string">
- The AWS IAM inline policy that should be attached to the created users.
- Multiple values can be provided by separating them with commas
- </ParamField>
- <ParamField path="Username Template" type="string" default="{{randomUsername}}">
- Specifies a template for generating usernames. This field allows customization of how usernames are automatically created.
-
- Allowed template variables are
- - `{{randomUsername}}`: Random username string
- - `{{unixTimestamp}}`: Current Unix timestamp
- </ParamField>
+ <Tabs>
+ <Tab title="IAM User">
+ <ParamField path="AWS IAM Path" type="string">
+ [IAM AWS Path](https://aws.amazon.com/blogs/security/optimize-aws-administration-with-iam-paths/) to scope created IAM User resource access.
+ </ParamField>
+
+ <ParamField path="IAM User Permission Boundary" type="string">
+ The IAM Policy ARN of the [AWS Permissions Boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to attach to IAM users created in the role.
+ </ParamField>
+
+ <ParamField path="AWS IAM Groups" type="string">
+ The AWS IAM groups that should be assigned to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
+
+ <ParamField path="AWS Policy ARNs" type="string">
+ The AWS IAM managed policies that should be attached to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
+
+ <ParamField path="AWS IAM Policy Document" type="string">
+ The AWS IAM inline policy that should be attached to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
+
+ <ParamField path="Username Template" type="string" default="{{randomUsername}}">
+ Specifies a template for generating usernames. This field allows customization of how usernames are automatically created.
+
+ Allowed template variables are:
+ - `{{randomUsername}}`: Random username string
+ - `{{unixTimestamp}}`: Current Unix timestamp
+ - `{{identity.name}}`: Name of the identity that is generating the secret
+ - `{{random N}}`: Random string of N characters
+
+ Allowed template functions are:
+ - `truncate`: Truncates a string to a specified length
+ - `replace`: Replaces a substring with another value
+ </ParamField>
+
+ <ParamField path="Tags" type="map<string, string>[]">
+ Tags to be added to the created IAM User resource.
+ </ParamField>
+ </Tab>
+
+ <Tab title="Temporary Credentials">
+ When **Credential Type** is set to **Temporary Credentials**:
+
+ <Info>
+ No additional configuration parameters are required. The generated credentials will:
+ - Inherit the permissions of the assumed IRSA role
+ - Include an AWS Session Token
+ - Be valid for the duration specified in Default TTL
+ </Info>
+
+ <Note>
+ **Duration Limit**: IRSA temporary credentials support up to 12 hours maximum via GetSessionToken. TTL values exceeding this limit will be automatically adjusted.
+ </Note>
+ </Tab>
+ </Tabs>
</Step>
<Step title="Click 'Submit'">
After submitting the form, you will see a dynamic secret created in the dashboard.
@@ -429,6 +557,12 @@ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** w
Select *Access Key* method.
</ParamField>
+ <ParamField path="Credential Type" type="string" required>
+ Choose the credential generation approach:
+ - **IAM User**: Creates new temporary IAM users in your AWS account
+ - **Temporary Credentials**: Generates temporary credentials from your access key connection
+ </ParamField>
+
<ParamField path="AWS Access Key" type="string" required>
The managing AWS IAM User Access Key
</ParamField>
@@ -437,43 +571,66 @@ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** w
The managing AWS IAM User Secret Key
</ParamField>
- <ParamField path="AWS IAM Path" type="string">
- [IAM AWS Path](https://aws.amazon.com/blogs/security/optimize-aws-administration-with-iam-paths/) to scope created IAM User resource access.
- </ParamField>
-
<ParamField path="AWS Region" type="string" required>
The AWS data center region.
</ParamField>
- <ParamField path="IAM User Permission Boundary" type="string" required>
- The IAM Policy ARN of the [AWS Permissions Boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to attach to IAM users created in the role.
- </ParamField>
+ <Tabs>
+ <Tab title="IAM User">
+ <ParamField path="AWS IAM Path" type="string">
+ [IAM AWS Path](https://aws.amazon.com/blogs/security/optimize-aws-administration-with-iam-paths/) to scope created IAM User resource access.
+ </ParamField>
- <ParamField path="AWS IAM Groups" type="string">
- The AWS IAM groups that should be assigned to the created users. Multiple values can be provided by separating them with commas
- </ParamField>
+ <ParamField path="IAM User Permission Boundary" type="string">
+ The IAM Policy ARN of the [AWS Permissions Boundary](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) to attach to IAM users created in the role.
+ </ParamField>
- <ParamField path="AWS Policy ARNs" type="string">
- The AWS IAM managed policies that should be attached to the created users. Multiple values can be provided by separating them with commas
- </ParamField>
+ <ParamField path="AWS IAM Groups" type="string">
+ The AWS IAM groups that should be assigned to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
- <ParamField path="AWS IAM Policy Document" type="string">
- The AWS IAM inline policy that should be attached to the created users.
- Multiple values can be provided by separating them with commas
- </ParamField>
+ <ParamField path="AWS Policy ARNs" type="string">
+ The AWS IAM managed policies that should be attached to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
- <ParamField path="Username Template" type="string" default="{{randomUsername}}">
- Specifies a template for generating usernames. This field allows customization of how usernames are automatically created.
+ <ParamField path="AWS IAM Policy Document" type="string">
+ The AWS IAM inline policy that should be attached to the created users. Multiple values can be provided by separating them with commas.
+ </ParamField>
- Allowed template variables are
+ <ParamField path="Username Template" type="string" default="{{randomUsername}}">
+ Specifies a template for generating usernames. This field allows customization of how usernames are automatically created.
- - `{{randomUsername}}`: Random username string
- - `{{unixTimestamp}}`: Current Unix timestamp
- </ParamField>
+ Allowed template variables are:
+ - `{{randomUsername}}`: Random username string
+ - `{{unixTimestamp}}`: Current Unix timestamp
+ - `{{identity.name}}`: Name of the identity that is generating the secret
+ - `{{random N}}`: Random string of N characters
- <ParamField path="Tags" type="map[string]string">
- Tags to be added to the created IAM User resource.
- </ParamField>
+ Allowed template functions are:
+ - `truncate`: Truncates a string to a specified length
+ - `replace`: Replaces a substring with another value
+ </ParamField>
+
+ <ParamField path="Tags" type="map[string]string">
+ Tags to be added to the created IAM User resource.
+ </ParamField>
+ </Tab>
+
+ <Tab title="Temporary Credentials">
+ When **Credential Type** is set to **Temporary Credentials**:
+
+ <Info>
+ No additional configuration parameters are required. The generated credentials will:
+ - Inherit the permissions of your access key connection
+ - Include an AWS Session Token
+ - Be valid for the duration specified in Default TTL
+ </Info>
+
+ <Note>
+ **Duration Limit**: Access Key temporary credentials support up to 12 hours maximum via GetSessionToken. TTL values exceeding this limit will be automatically adjusted.
+ </Note>
+ </Tab>
+ </Tabs>
</Step>
@@ -500,6 +657,18 @@ Replace **\<account id\>** with your AWS account id and **\<aws-scope-path\>** w
Once you click the `Submit` button, a new secret lease will be generated and the credentials for it will be shown to you.
+ **Credentials format depends on your chosen credential type:**
+
+ **IAM User credential type:**
+ - AWS Username
+ - AWS Access Key ID
+ - AWS Secret Access Key
+
+ **Temporary Credentials credential type:**
+ - AWS Access Key ID
+ - AWS Secret Access Key
+ - AWS Session Token
+
![Provision Lease](/images/platform/dynamic-secrets/lease-values-aws-iam.png)
</Step>
</Steps>
diff --git a/docs/documentation/platform/gateways/gateway-deployment.mdx b/docs/documentation/platform/gateways/gateway-deployment.mdx
new file mode 100644
index 0000000000..40b98965a4
--- /dev/null
+++ b/docs/documentation/platform/gateways/gateway-deployment.mdx
@@ -0,0 +1,265 @@
+---
+title: "Gateway Deployment"
+description: "Complete guide to deploying Infisical Gateways including network configuration and firewall requirements"
+---
+
+Infisical Gateways enables secure communication between your private resources and the Infisical platform without exposing inbound ports in your network.
+This guide covers everything you need to deploy and configure Infisical Gateways.
+
+## Deployment Steps
+
+To successfully deploy an Infisical Gateway for use, follow these steps in order.
+
+<Steps>
+ <Step title="Provision a Machine Identity">
+ Create a machine identity with the correct permissions to create and manage gateways. This identity is used by the gateway to authenticate with Infisical and should be provisioned in advance.
+ The gateway supports several [machine identity auth methods](/documentation/platform/identities/machine-identities), as listed below. Choose the one that best fits your environment and set the corresponding environment variables when deploying the gateway.
+
+ <AccordionGroup>
+ <Accordion title="Universal Auth">
+ Simple and secure authentication using client ID and client secret.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=universal-auth`
+ - `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id>`
+ - `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret>`
+ </Accordion>
+
+ <Accordion title="Token Auth">
+ Direct authentication using a machine identity access token.
+
+ **Environment Variables:**
+ - `INFISICAL_TOKEN=<token>`
+ </Accordion>
+
+ <Accordion title="Native Kubernetes">
+ Authentication using Kubernetes service account tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=kubernetes`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="Native AWS IAM">
+ Authentication using AWS IAM roles.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=aws-iam`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="Native GCP ID Token">
+ Authentication using GCP identity tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=gcp-id-token`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="GCP IAM">
+ Authentication using GCP service account keys.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=gcp-iam`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ - `INFISICAL_GCP_SERVICE_ACCOUNT_KEY_FILE_PATH=<path-to-key-file>`
+ </Accordion>
+
+ <Accordion title="Native Azure">
+ Authentication using Azure managed identity.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=azure`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="OIDC Auth">
+ Authentication using OIDC identity tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=oidc-auth`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ - `INFISICAL_JWT=<oidc-jwt>`
+ </Accordion>
+
+ <Accordion title="JWT Auth">
+ Authentication using JWT tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=jwt-auth`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ - `INFISICAL_JWT=<jwt>`
+ </Accordion>
+ </AccordionGroup>
+ </Step>
+ <Step title="Set Up a Relay Server">
+ Ensure a relay server is running and accessible before you deploy any gateways. You have two options:
+ - **Managed relay (Infisical Cloud, US/EU only):** Managed relays are only available for Infisical Cloud instances in the US and EU regions. If you are using Infisical Cloud in these regions, you can use the provided managed relay.
+ - **Self-hosted relay:** For all other cases, including all self-hosted and dedicated enterprise instances of Infisical, you must deploy your own relay server. You can also choose to deploy your own relay server when using Infisical Cloud if you require reduced geographic proximity to your target resources for lower latency or to reduce network congestion. For setup instructions, see the <a href="/documentation/platform/gateways/relay-deployment">Relay Deployment Guide</a>.
+ </Step>
+ <Step title="Install the Infisical CLI">
+ Make sure the Infisical CLI is installed on the machine or environment where you plan to deploy the gateway. The CLI is required for gateway installation and management.
+
+ See the [CLI Installation Guide](/cli/overview) for instructions.
+ </Step>
+ <Step title="Configure Network & Firewall">
+ Ensure your network and firewall settings allow the gateway to connect to all required services. All connections are outbound only; no inbound ports need to be opened.
+
+ | Protocol | Destination | Port | Purpose |
+ | -------- | ------------------------------------ | ---- | ------------------------------------------ |
+ | TCP | Relay Server IP/Hostname | 2222 | SSH reverse tunnel establishment |
+ | TCP | Infisical instance host (US/EU, other) | 443 | API communication and certificate requests |
+
+ For managed relays, allow outbound traffic to the provided relay server IP/hostname. For self-hosted relays, allow outbound traffic to your own relay server address.
+
+ If you are in a corporate environment with strict egress filtering, ensure outbound TCP 2222 to relay servers and outbound HTTPS 443 to Infisical API endpoints are allowed.
+ </Step>
+ <Step title="Select a Deployment Method">
+ The Infisical CLI is used to install and start the gateway in your chosen environment. The CLI provides commands for both production and development scenarios, and supports a variety of options/flags to configure your deployment.
+
+ To view all available flags and equivalent environment variables for gateway deployment, see the [Gateway CLI Command Reference](/cli/commands/gateway).
+ <Tabs>
+ <Tab title="Linux Server (Production)">
+ For production deployments on Linux servers, install the Gateway as a systemd service so that it runs securely in the background and automatically restarts on failure or system reboot:
+ ```bash
+ sudo infisical gateway systemd install --token <your-machine-identity-token> --domain <your-infisical-domain> --name <gateway-name> --relay <relay-name>
+ sudo systemctl start infisical-gateway
+ ```
+
+
+
+ <Warning>
+ The systemd install command requires a Linux operating system with root/sudo
+ privileges.
+ </Warning>
+ </Tab>
+
+ <Tab title="Kubernetes (Production)">
+ For production deployments on Kubernetes clusters, install the Gateway using the Infisical Helm chart:
+
+ #### Install the latest Helm Chart repository
+
+ ```bash
+ helm repo add infisical-helm-charts 'https://dl.cloudsmith.io/public/infisical/helm-charts/helm/charts/'
+ helm repo update
+ ```
+
+ #### Create a Kubernetes Secret
+
+ The gateway supports all identity authentication methods through environment variables:
+
+ ```bash
+ kubectl create secret generic infisical-gateway-environment \
+ --from-literal=INFISICAL_AUTH_METHOD=universal-auth \
+ --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id> \
+ --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret> \
+ --from-literal=INFISICAL_RELAY_NAME=<relay-name> \
+ --from-literal=INFISICAL_GATEWAY_NAME=<gateway-name>
+ ```
+
+ #### Install the Gateway
+
+ ```bash
+ helm install infisical-gateway infisical-helm-charts/infisical-gateway
+ ```
+ </Tab>
+
+ <Tab title="Development & Testing">
+ For development or testing environments:
+
+ ```bash
+ infisical gateway start --token <token> --relay=<relay-name> --name=<gateway-name>
+ ```
+ </Tab>
+ </Tabs>
+ </Step>
+
+ <Step title="Verify Your Gateway Deployment">
+ After deployment, verify your gateway is working:
+
+ 1. **Check logs** for "Gateway started successfully" message indicating the gateway is running and connected to the relay
+
+ 2. **Verify registration** in the Infisical by visiting the Gateways section of your organization. The new gateway should appear with a recent heartbeat timestamp.
+
+ 3. **Test connectivity** by creating a resource in Infisical that uses the gateway to access a private service. Verify the resource can successfully connect through the gateway.
+ </Step>
+</Steps>
+
+
+
+
+## Frequently Asked Questions
+<Accordion title="Do I need to open any inbound ports on my firewall?">
+No inbound ports need to be opened for gateways. The gateway only makes outbound connections:
+
+- **Outbound SSH** to relay servers on port 2222
+- **Outbound HTTPS** to Infisical API endpoints on port 443
+- **SSH reverse tunnels** handle all communication - no return traffic configuration needed
+
+This design maintains security by avoiding the need for inbound firewall rules that could expose your network to external threats.
+
+</Accordion>
+
+<Accordion title="How do I test network connectivity from the gateway?">
+Test relay connectivity and outbound API access from the gateway:
+
+1. Test SSH port to relay:
+ ```bash
+ nc -zv <relay-ip> 2222
+ ```
+2. Test outbound API access (replace with your Infisical domain if different):
+ ```bash
+ curl -I https://app.infisical.com
+ ```
+</Accordion>
+
+<Accordion title="How do I troubleshoot relay connectivity issues?">
+If the gateway cannot connect to the relay:
+
+1. Verify the relay server is running and accessible
+2. Check firewall rules allow outbound connections on port 2222
+3. Confirm the relay name matches exactly
+4. Test SSH port to relay:
+ ```bash
+ nc -zv <relay-ip> 2222
+ ```
+</Accordion>
+
+<Accordion title="How do I troubleshoot authentication failures?">
+If you encounter authentication failures:
+
+1. Verify machine identity credentials are correct
+2. Check token expiration and renewal
+3. Ensure authentication method is properly configured
+</Accordion>
+
+<Accordion title="Where can I find gateway logs?">
+Check gateway logs for detailed error information:
+
+- **systemd service:**
+ ```bash
+ sudo journalctl -u infisical-gateway -f
+ ```
+- **Kubernetes:**
+ ```bash
+ kubectl logs deployment/infisical-gateway
+ ```
+- **Local installation:** Logs appear in the terminal where you started the gateway
+</Accordion>
+
+<Accordion title="Where is the gateway configuration file stored?">
+For systemd-based installations, the gateway's configuration file is stored at `/etc/infisical/gateway.conf`. You may reference or inspect this file for troubleshooting advanced configuration issues.
+</Accordion>
+
+<Accordion title="What happens if there is a network interruption?">
+The gateway is designed to handle network interruptions gracefully:
+
+- **Automatic reconnection**: The gateway will automatically attempt to reconnect to relay servers if the SSH connection is lost
+- **Connection retry logic**: Built-in retry mechanisms handle temporary network outages without manual intervention
+- **Persistent SSH tunnels**: SSH connections are automatically re-established when connectivity is restored
+- **Certificate rotation**: The gateway handles certificate renewal automatically during reconnection
+- **Graceful degradation**: The gateway logs connection issues and continues attempting to restore connectivity
+
+No manual intervention is typically required during network interruptions.
+
+</Accordion>
diff --git a/docs/documentation/platform/gateways/networking.mdx b/docs/documentation/platform/gateways/networking.mdx
deleted file mode 100644
index 2b068a5350..0000000000
--- a/docs/documentation/platform/gateways/networking.mdx
+++ /dev/null
@@ -1,178 +0,0 @@
----
-title: "Networking"
-description: "Network configuration and firewall requirements for Infisical Gateway"
----
-
-The Infisical Gateway requires outbound network connectivity to establish secure SSH reverse tunnels with relay servers.
-This page outlines the required ports, protocols, and firewall configurations needed for optimal gateway usage.
-
-## Network Architecture
-
-The gateway uses SSH reverse tunnels to establish secure connections with end-to-end encryption:
-
-1. **Gateway** connects outbound to **Relay Servers** using SSH over TCP
-2. **Infisical platform** establishes mTLS connections with gateways for application traffic
-3. **Relay Servers** route the doubly-encrypted traffic (mTLS payload within SSH tunnels) between the platform and gateways
-4. **Double encryption** ensures relay servers cannot access application data - only the platform and gateway can decrypt traffic
-
-## Required Network Connectivity
-
-### Outbound Connections (Required)
-
-The gateway requires the following outbound connectivity:
-
-| Protocol | Destination | Ports | Purpose |
-| -------- | ------------------------------------ | ----- | ------------------------------------------ |
-| TCP | Relay Servers | 2222 | SSH reverse tunnel establishment |
-| TCP | app.infisical.com / eu.infisical.com | 443 | API communication and certificate requests |
-
-### Relay Server Connectivity
-
-**For Instance Relays (Infisical Cloud):** Your firewall must allow outbound connectivity to Infisical-managed relay servers.
-
-**For Organization Relays:** Your firewall must allow outbound connectivity to your own relay server IP addresses or hostnames.
-
-**For Self-hosted Instance Relays:** Your firewall must allow outbound connectivity to relay servers configured by your instance administrator.
-
-<Tabs>
- <Tab title="Instance Relays (Infisical Cloud)">
- Infisical provides multiple managed relay servers with static IP addresses.
- You can whitelist these IPs ahead of time based on which relay server you
- choose to connect to. **Firewall requirements:** Allow outbound TCP
- connections to the desired relay server IP on port 2222.
- </Tab>
- <Tab title="Organization Relays">
- You control the relay server IP addresses or hostnames when deploying your
- own organization relays. **Firewall requirements:** Allow outbound TCP
- connections to your relay server IP or hostname on port 2222. For example,
- if your relay is at `203.0.113.100` or `relay.example.com`, allow TCP to
- `203.0.113.100:2222` or `relay.example.com:2222`.
- </Tab>
- <Tab title="Self-hosted Instance Relays">
- Contact your instance administrator for the relay server IP addresses or
- hostnames configured for your deployment. **Firewall requirements:** Allow
- outbound TCP connections to instance relay servers on port 2222.
- </Tab>
-</Tabs>
-
-## Protocol Details
-
-### SSH over TCP
-
-The gateway uses SSH reverse tunnels for primary communication:
-
-- **Port 2222**: SSH connection to relay servers
-- **Built-in features**: Automatic reconnection, certificate-based authentication, encrypted tunneling
-- **Encryption**: SSH with certificate-based authentication and key exchange
-
-## Firewall Configuration for SSH
-
-The gateway uses standard SSH over TCP, making firewall configuration straightforward.
-
-### TCP Connection Handling
-
-SSH connections over TCP are stateful and handled seamlessly by all modern firewalls:
-
-- **Established connections** are automatically tracked
-- **Return traffic** is allowed for established outbound connections
-- **No special configuration** needed for connection tracking
-- **Standard SSH protocol** that enterprise firewalls handle well
-
-### Simplified Firewall Rules
-
-Since SSH uses TCP, you only need simple outbound rules:
-
-1. **Allow outbound TCP** to relay servers (IP addresses or hostnames) on port 2222
-2. **Allow outbound HTTPS** to Infisical API endpoints on port 443
-3. **No inbound rules required** - all connections are outbound only
-
-## Common Network Scenarios
-
-### Corporate Firewalls
-
-For corporate environments with strict egress filtering:
-
-1. **Allow outbound TCP** to relay servers (IP addresses or hostnames) on port 2222
-2. **Allow outbound HTTPS** to the Infisical API server on port 443
-3. **No inbound rules required** - all connections are outbound only
-4. **Standard TCP rules** - simple and straightforward configuration
-
-### Cloud Environments (AWS/GCP/Azure)
-
-Configure security groups to allow:
-
-- **Outbound TCP** to relay servers (IP addresses or hostnames) on port 2222
-- **Outbound HTTPS** to app.infisical.com/eu.infisical.com on port 443
-- **No inbound rules required** - SSH reverse tunnels are outbound only
-
-## Frequently Asked Questions
-
-<Accordion title="What happens if there is a network interruption?">
-The gateway is designed to handle network interruptions gracefully:
-
-- **Automatic reconnection**: The gateway will automatically attempt to reconnect to relay servers if the SSH connection is lost
-- **Connection retry logic**: Built-in retry mechanisms handle temporary network outages without manual intervention
-- **Persistent SSH tunnels**: SSH connections are automatically re-established when connectivity is restored
-- **Certificate rotation**: The gateway handles certificate renewal automatically during reconnection
-- **Graceful degradation**: The gateway logs connection issues and continues attempting to restore connectivity
-
-No manual intervention is typically required during network interruptions.
-
-</Accordion>
-
-<Accordion title="Why does the gateway use SSH over TCP?">
-SSH over TCP provides several advantages for enterprise gateway communication:
-
-- **Firewall-friendly**: TCP is stateful and handled seamlessly by all enterprise firewalls
-- **Standard protocol**: SSH is a well-established protocol that network teams are familiar with
-- **Certificate-based security**: Uses SSH certificates for strong authentication without shared secrets
-- **Automatic tunneling**: SSH reverse tunnels handle all the complexity of secure communication
-- **Enterprise compatibility**: Works reliably across all enterprise network configurations
-
-TCP's reliability and firewall compatibility make it ideal for enterprise environments where network policies are strictly managed.
-
-</Accordion>
-
-<Accordion title="Do I need to open any inbound ports on my firewall?">
-No inbound ports need to be opened. The gateway only makes outbound connections:
-
-- **Outbound SSH** to relay servers on port 2222
-- **Outbound HTTPS** to Infisical API endpoints on port 443
-- **SSH reverse tunnels** handle all communication - no return traffic configuration needed
-
-This design maintains security by avoiding the need for inbound firewall rules that could expose your network to external threats.
-
-</Accordion>
-
-<Accordion title="What if my firewall blocks SSH connections?">
-If your firewall has strict outbound restrictions:
-
-1. **Work with your network team** to allow outbound TCP connections on port 2222 to relay servers (IP addresses or hostnames)
-2. **Allow standard SSH traffic** - most enterprises already have SSH policies in place
-3. **Consider network policy exceptions** for the gateway host if needed
-4. **Monitor firewall logs** to identify which specific rules are blocking traffic
-
-</Accordion>
-
-<Accordion title="How many relay servers does the gateway connect to?">
-The gateway connects to **one relay server**:
-
-- **Single SSH connection**: Each gateway establishes one SSH reverse tunnel to its assigned relay server
-- **Named relay assignment**: Gateways connect to the specific relay server specified by `--relay`
-- **Automatic reconnection**: If the relay connection is lost, the gateway automatically reconnects to the same relay
-- **Certificate-based authentication**: Each connection uses SSH certificates issued by Infisical for secure authentication
-
-</Accordion>
-<Accordion title="Can the relay servers decrypt traffic going through them?">
-No, relay servers cannot decrypt any traffic passing through them due to end-to-end encryption:
-
-- **Client-to-Gateway mTLS (via TLS-pinned tunnel)**: Clients connect via a proxy that establishes a TLS-pinned tunnel to the gateway; mTLS between the client and gateway is negotiated inside this tunnel, encrypting all application traffic
-- **SSH tunnel encryption**: The mTLS-encrypted traffic is then transmitted through SSH reverse tunnels to relay servers
-- **Double encryption**: Traffic is encrypted twice - once by client mTLS and again by SSH tunnels
-- **Relay only routes traffic**: The relay server only routes the doubly-encrypted traffic without access to either encryption layer
-- **No data storage**: Relay servers do not store any traffic or sensitive information
-- **Certificate isolation**: Each connection uses unique certificates, ensuring complete tenant isolation
-
-The relay infrastructure is designed as a secure routing mechanism where only the client and gateway can decrypt the actual application traffic.
-
-</Accordion>
diff --git a/docs/documentation/platform/gateways/overview.mdx b/docs/documentation/platform/gateways/overview.mdx
index b8ea0102af..c04f2f7d3d 100644
--- a/docs/documentation/platform/gateways/overview.mdx
+++ b/docs/documentation/platform/gateways/overview.mdx
@@ -1,19 +1,14 @@
---
-title: "Gateway"
+title: "Gateway Overview"
sidebarTitle: "Overview"
description: "How to access private network resources from Infisical"
---
![Architecture Overview](../../../images/platform/gateways/gateway-highlevel-diagram.png)
-The Infisical Gateway provides secure access to private resources within your network without needing direct inbound connections to your environment. This method keeps your resources fully protected from external access while enabling Infisical to securely interact with resources like databases.
-
-**Architecture Components:**
-
-- **Gateway**: Lightweight agent deployed within your VPCs that provides access to private resources
-- **Relay**: Infrastructure that routes encrypted traffic (instance-wide or organization-specific)
-
-Common use cases include generating dynamic credentials or rotating credentials for private databases.
+The Infisical Gateway provides secure access to private resources within your network without needing direct inbound connections to your environment.
+This is particularly useful when Infisical isn't hosted within the same network as the resources it needs to reach.
+This method keeps your resources fully protected from external access while enabling Infisical to securely interact with resources like databases.
<Info>
Gateway is a paid feature available under the Enterprise Tier for Infisical
@@ -22,428 +17,62 @@ Common use cases include generating dynamic credentials or rotating credentials
license.
</Info>
-## How It Works
-
-The Gateway system uses SSH reverse tunnels for secure, firewall-friendly connectivity:
-
-1. **Gateway Registration**: The gateway establishes an outbound SSH reverse tunnel to a relay server using SSH certificates issued by Infisical
-2. **Relay Routing**: The relay server routes encrypted traffic between the Infisical platform and gateways
-3. **Resource Access**: The Infisical platform connects to your private resources through the established gateway connections
-
-**Key Benefits:**
-
-- **No inbound firewall rules needed** - all connections are outbound from your network
-- **Firewall-friendly** - uses standard SSH over TCP
-- **Certificate-based authentication** provides enhanced security
-- **Automatic reconnection** if connections are lost
-
-## Deployment
-
-The Infisical Gateway is integrated into the Infisical CLI under the `gateway` command, making it simple to deploy and manage.
-You can install the Gateway in all the same ways you install the Infisical CLI—whether via npm, Docker, or a binary.
-For detailed installation instructions, refer to the Infisical [CLI Installation instructions](/cli/overview).
-
-**Prerequisites:**
-
-1. **Relay Server**: Before deploying gateways, you need a running relay server:
- - **Infisical Cloud**: Instance relays are already available - no setup needed
- - **Self-hosted**: Instance admin must set up shared instance relays, or organizations can deploy their own
-2. **Machine Identity**: Configure a machine identity with appropriate permissions to create and manage gateways
-
-Once authenticated, the Gateway establishes an SSH reverse tunnel to the specified relay server, allowing secure access to your private resources.
-
-### Get started
-
-<Steps>
- <Step title="Create a Gateway Identity">
- 1. Navigate to **Organization Access Control** in your Infisical dashboard.
- 2. Create a dedicated machine identity for your Gateway.
- 3. **Best Practice:** Assign a unique identity to each Gateway for better security and management.
- ![Create Gateway Identity](../../../images/platform/gateways/create-identity-for-gateway.png)
- </Step>
-
- <Step title="Configure Authentication Method">
- You'll need to choose an authentication method to initiate communication with Infisical. View the available machine identity authentication methods [here](/documentation/platform/identities/machine-identities).
- </Step>
-
- <Step title="Choose Your Relay Setup">
- You have two options for relay infrastructure:
-
- <Tabs>
- <Tab title="Use Instance Relays (Easiest)">
- **Infisical Cloud:** Instance relays are already running and available - **no setup required**. You can immediately proceed to deploy gateways using these shared relays.
-
- **Self-hosted:** If your instance admin has set up shared instance relays, you can use them directly. If not, the instance admin can set them up:
- ```bash
- # Instance admin sets up shared relay (one-time setup)
- export INFISICAL_RELAY_AUTH_SECRET=<instance-relay-secret>
- infisical relay start --type=instance --ip=<public-ip> --name=<relay-name>
- ```
- </Tab>
- <Tab title="Deploy Your Own Organization Relay">
- **Available for all users:** Deploy your own dedicated relay infrastructure for enhanced control:
- ```bash
- # Deploy organization-specific relay
- infisical relay start --type=org --ip=<public-ip> --name=<relay-name> --auth-method=universal-auth --client-id=<client-id> --client-secret=<client-secret>
- ```
-
- **When to choose this:**
- - You need lower latency (deploy closer to your resources)
- - Enhanced security requirements
- - Compliance needs (data sovereignty, air-gapped environments)
- - Custom network policies
- </Tab>
- </Tabs>
- </Step>
-
- <Step title="Deploy the Gateway">
- Use the Infisical CLI to deploy the Gateway. You can run it directly or install it as a systemd service for production:
-
- <Tabs>
- <Tab title="Production (systemd)">
- For production deployments on Linux, install the Gateway as a systemd service:
-
- <Warning>
- **Gateway v2:** The `infisical gateway systemd install` command deploys the new Gateway v2 component.
-
- If you are migrating from Gateway v1 (legacy `infisical gateway install` command), this is not in-place. Gateway v2 provisions new gateway instances with new gateway IDs. Update any resources that reference a gateway ID (for example: dynamic secret configs, app connections, or other gateway-bound resources) to use the new Gateway v2 gateway ID.
- </Warning>
-
- ```bash
- sudo infisical gateway systemd install --token <your-machine-identity-token> --domain <your-infisical-domain> --name <gateway-name> --relay <relay-name>
- sudo systemctl start infisical-gateway
- ```
- This will install and start the Gateway as a secure systemd service that:
- - Runs with restricted privileges:
- - Runs as root user (required for secure token management)
- - Restricted access to home directories
- - Private temporary directory
- - Automatically restarts on failure
- - Starts on system boot
- - Manages token and domain configuration securely in `/etc/infisical/gateway.conf`
-
- <Warning>
- The install command requires:
- - Linux operating system
- - Root/sudo privileges
- - Systemd
- </Warning>
- </Tab>
-
- <Tab title="Production (Helm)">
-
- The Gateway can be installed via [Helm](https://helm.sh/). Helm is a package manager for Kubernetes that allows you to define, install, and upgrade Kubernetes applications.
-
- For production deployments on Kubernetes, install the Gateway using the Infisical Helm chart:
-
- ### Install the latest Helm Chart repository
- ```bash
- helm repo add infisical-helm-charts 'https://dl.cloudsmith.io/public/infisical/helm-charts/helm/charts/'
- ```
-
- ### Update the Helm Chart repository
- ```bash
- helm repo update
- ```
-
- ### Create a Kubernetes Secret containing gateway environment variables
-
- The gateway supports all identity authentication methods through the use of environment variables.
- The environment variables must be set in the `infisical-gateway-environment` Kubernetes secret.
-
-
- #### Supported authentication methods
-
- <AccordionGroup>
- <Accordion title="Universal Auth">
- The Universal Auth method is a simple and secure way to authenticate with Infisical. It requires a client ID and a client secret to authenticate with Infisical.
-
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_UNIVERSAL_AUTH_CLIENT_ID" type="string" required>
- Your machine identity client ID.
- </ParamField>
- <ParamField query="INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET" type="string" required>
- Your machine identity client secret.
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `universal-auth` when using Universal Auth.
- </ParamField>
- </Expandable>
- </ParamField>
-
- ```bash
- kubectl create secret generic infisical-gateway-environment \
- --from-literal=INFISICAL_AUTH_METHOD=universal-auth \
- --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id> \
- --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret> \
- --from-literal=INFISICAL_RELAY_NAME=<relay-name> \
- --from-literal=INFISICAL_GATEWAY_NAME=<gateway-name>
- ```
-
- </Accordion>
- <Accordion title="Native Kubernetes">
- The Native Kubernetes method is used to authenticate with Infisical when running in a Kubernetes environment. It requires a service account token to authenticate with Infisical.
+## Core Components
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_MACHINE_IDENTITY_ID" type="string" required>
- Your machine identity ID.
- </ParamField>
- <ParamField query="INFISICAL_KUBERNETES_SERVICE_ACCOUNT_TOKEN_PATH" type="string" optional>
- Path to the Kubernetes service account token to use. Default: `/var/run/secrets/kubernetes.io/serviceaccount/token`.
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `kubernetes` when using Native Kubernetes.
- </ParamField>
- </Expandable>
- </ParamField>
+The Gateway system consists of two primary components working together to enable secure network access:
+<Tabs>
+ <Tab title="Gateway" icon="server">
+ A Gateway is a lightweight service that you deploy within your own network infrastructure to provide secure access to your private resources. Think of it as a secure bridge between Infisical and your internal systems.
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=kubernetes --from-literal=INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>
- ```
+ Gateways must be deployed within the same network where your target resources are located, with direct network connectivity to the private resources you want Infisical to access.
+ For different networks, regions, or isolated environments, you'll need to deploy separate gateways.
- </Accordion>
- <Accordion title="Native Azure">
- The Native Azure method is used to authenticate with Infisical when running in an Azure environment.
+ **Core Functions:**
+ - **Network Placement**: Deployed within your VPCs, data centers, or on-premises infrastructure where your private resources live
+ - **Connection Model**: Only makes outbound connections to Infisical's relay servers, so no inbound firewall rules are needed
+ - **Security Method**: Uses SSH reverse tunnels with certificate-based authentication for maximum security
+ - **Resource Access**: Acts as a proxy to connect Infisical to your private databases, APIs, and other services
+ </Tab>
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_MACHINE_IDENTITY_ID" type="string" required>
- Your machine identity ID.
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `azure` when using Native Azure.
- </ParamField>
- </Expandable>
- </ParamField>
+ <Tab title="Relay Server" icon="route">
+ A Relay Server is the routing infrastructure that enables secure communication between the Infisical platform and your deployed gateways. It acts as an intermediary that never sees your actual data.
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=azure --from-literal=INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>
- ```
- </Accordion>
- <Accordion title="Native GCP ID Token">
- The Native GCP ID Token method is used to authenticate with Infisical when running in a GCP environment.
+ **Core Functions:**
+ - **Traffic Routing**: Routes encrypted traffic between the Infisical platform and your gateways without storing or inspecting the data
+ - **Network Isolation**: Enables secure communication without requiring direct network connections between Infisical and your private infrastructure
+ - **Authentication Management**: Validates SSH certificates and manages secure routing between authenticated gateways
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_MACHINE_IDENTITY_ID" type="string" required>
- Your machine identity ID.
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `gcp-id-token` when using Native GCP ID Token.
- </ParamField>
- </Expandable>
- </ParamField>
+ **Deployment Options:**
+ To reduce operational overhead, Infisical Cloud (US/EU) provides managed relay infrastructure, though organizations can also deploy their own relays for reduced latency.
+ - **Infisical Managed**: Use pre-deployed relays in select regions, shared across all Infisical Cloud organizations. Each organization traffic is isolated and encrypted.
+ - **Self-Deployed**: Deploy your own dedicated relay servers geographically close to your infrastructure for reduced latency.
+ </Tab>
+</Tabs>
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=gcp-id-token --from-literal=INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>
- ```
-
- </Accordion>
- <Accordion title="GCP IAM">
- The GCP IAM method is used to authenticate with Infisical with a GCP service account key.
-
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_MACHINE_IDENTITY_ID" type="string" required>
- Your machine identity ID.
- </ParamField>
- <ParamField query="INFISICAL_GCP_SERVICE_ACCOUNT_KEY_FILE_PATH" type="string" required>
- Path to your GCP service account key file _(Must be in JSON format!)_
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `gcp-iam` when using GCP IAM.
- </ParamField>
- </Expandable>
- </ParamField>
-
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=gcp-iam --from-literal=INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id> --from-literal=INFISICAL_GCP_SERVICE_ACCOUNT_KEY_FILE_PATH=<service-account-key-file-path>
- ```
-
-
- </Accordion>
- <Accordion title="Native AWS IAM">
- The AWS IAM method is used to authenticate with Infisical with an AWS IAM role while running in an AWS environment like EC2, Lambda, etc.
-
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_MACHINE_IDENTITY_ID" type="string" required>
- Your machine identity ID.
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `aws-iam` when using Native AWS IAM.
- </ParamField>
- </Expandable>
- </ParamField>
-
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=aws-iam --from-literal=INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>
- ```
-
- </Accordion>
- <Accordion title="OIDC Auth">
- The OIDC Auth method is used to authenticate with Infisical via identity tokens with OIDC.
-
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_MACHINE_IDENTITY_ID" type="string" required>
- Your machine identity ID.
- </ParamField>
- <ParamField query="INFISICAL_JWT" type="string" required>
- The OIDC JWT from the identity provider.
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `oidc-auth` when using OIDC Auth.
- </ParamField>
- </Expandable>
- </ParamField>
-
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=oidc-auth --from-literal=INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id> --from-literal=INFISICAL_JWT=<oidc-jwt>
- ```
- </Accordion>
-
- <Accordion title="JWT Auth">
- The JWT Auth method is used to authenticate with Infisical via a JWT token.
-
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_JWT" type="string" required>
- The JWT token to use for authentication.
- </ParamField>
- <ParamField query="INFISICAL_MACHINE_IDENTITY_ID" type="string" required>
- Your machine identity ID.
- </ParamField>
- <ParamField query="INFISICAL_AUTH_METHOD" type="string" required>
- The authentication method to use. Must be `jwt-auth` when using JWT Auth.
- </ParamField>
- </Expandable>
- </ParamField>
-
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_AUTH_METHOD=jwt-auth --from-literal=INFISICAL_JWT=<jwt> --from-literal=INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>
- ```
- </Accordion>
- <Accordion title="Token Auth">
- You can use the `INFISICAL_TOKEN` environment variable to authenticate with Infisical with a raw machine identity access token.
-
- <ParamField query="Environment Variables">
- <Expandable title="properties">
- <ParamField query="INFISICAL_TOKEN" type="string" required>
- The machine identity access token to use for authentication.
- </ParamField>
- </Expandable>
- </ParamField>
-
- ```bash
- kubectl create secret generic infisical-gateway-environment --from-literal=INFISICAL_TOKEN=<token>
- ```
- </Accordion>
- </AccordionGroup>
-
-
- #### Required environment variables
-
- In addition to the authentication method above, you **must** include these required variables:
-
- <AccordionGroup>
- <Accordion title="INFISICAL_RELAY_NAME">
- The name of the relay server that this gateway should connect to.
- </Accordion>
- <Accordion title="INFISICAL_GATEWAY_NAME">
- The name of this gateway instance.
- </Accordion>
- </AccordionGroup>
-
- **Complete example with required variables:**
- ```bash
- kubectl create secret generic infisical-gateway-environment \
- --from-literal=INFISICAL_AUTH_METHOD=universal-auth \
- --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id> \
- --from-literal=INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret> \
- --from-literal=INFISICAL_RELAY_NAME=<relay-name> \
- --from-literal=INFISICAL_GATEWAY_NAME=<gateway-name>
- ```
-
- #### Other environment variables
-
- <AccordionGroup>
- <Accordion title="INFISICAL_API_URL">
- The API URL to use for the gateway. By default, `INFISICAL_API_URL` is set to `https://app.infisical.com`.
- </Accordion>
- </AccordionGroup>
-
- ### Install the Infisical Gateway Helm Chart
- <Warning>
- **Version mapping:** Helm chart versions `>= 1.0.0` contain the new Gateway v2 component. Helm chart versions `<= 0.0.5` contain the legacy Gateway v1 component.
-
- If you are moving from Gateway v1 (chart `<= 0.0.5`) to Gateway v2 (chart `>= 1.0.0`), this is not in-place. Gateway v2 provisions new gateway instances with new gateway IDs. Update any resources that reference a gateway ID (for example: dynamic secret configs, app connections, or other gateway-bound resources) to use the new Gateway v2 gateway ID.
- </Warning>
-
- ```bash
- helm install infisical-gateway infisical-helm-charts/infisical-gateway
- ```
-
- ### Check the gateway logs
- After installing the gateway, you can check the logs to ensure it's running as expected.
-
- ```bash
- kubectl logs deployment/infisical-gateway
- ```
-
- You should see the following output which indicates the gateway is running as expected.
- ```bash
- $ kubectl logs deployment/infisical-gateway
- 12:43AM INF Starting gateway
- 12:43AM INF Starting gateway certificate renewal goroutine
- 12:43AM INF Successfully registered gateway and received certificates
- 12:43AM INF Connecting to relay server infisical-start on 152.42.218.156:2222...
- 12:43AM INF Relay connection established for gateway
- 12:43AM INF Received incoming connection, starting TLS handshake
- 12:43AM INF TLS handshake completed successfully
- 12:43AM INF Negotiated ALPN protocol: infisical-ping
- 12:43AM INF Starting ping handler
- 12:43AM INF Ping handler completed
- 12:43AM INF Gateway is reachable by Infisical
- ```
-
- </Tab>
-
- <Tab title="Local Installation (testing)">
- For development or testing, you can run the Gateway directly. Log in with your machine identity and start the Gateway in one command:
- ```bash
- infisical gateway start --token $(infisical login --method=universal-auth --client-id=<> --client-secret=<> --plain) --relay=<relay-name> --name=<gateway-name>
- ```
-
- Alternatively, if you already have the token, use it directly with the `--token` flag:
- ```bash
- infisical gateway start --token <your-machine-identity-token> --relay=<relay-name> --name=<gateway-name>
- ```
-
- Or set it as an environment variable:
- ```bash
- export INFISICAL_TOKEN=<your-machine-identity-token>
- infisical gateway start --relay=<relay-name> --name=<gateway-name>
- ```
- </Tab>
- </Tabs>
-
- For detailed information about the gateway commands and their options, see the [gateway command documentation](/cli/commands/gateway).
+## How It Works
- <Note>
- **Requirements:**
- - Ensure the deployed Gateway has network access to the private resources you intend to connect with Infisical
- - The gateway must be able to reach the relay server (outbound connection only)
- - Replace `<relay-name>` with the name of your relay server and `<gateway-name>` with a unique name for this gateway
- </Note>
+The Gateway system uses SSH reverse tunnels for secure, firewall-friendly connectivity:
- </Step>
-
- <Step title="Verify Gateway Deployment">
- To confirm your Gateway is working, check the deployment status by looking for the message **"Gateway started successfully"** in the Gateway logs. This indicates the Gateway is running properly. Next, verify its registration by opening your Infisical dashboard, navigating to **Organization Access Control**, and selecting the **Gateways** tab. Your newly deployed Gateway should appear in the list.
- ![Gateway List](../../../images/platform/gateways/gateway-list.png)
- </Step>
-</Steps>
+1. **Gateway Registration**: The gateway establishes an outbound SSH reverse tunnel to a relay server using SSH certificates issued by Infisical
+2. **Persistent Connection**: The gateway maintains an open TCP connection with the relay server, creating a secure channel for incoming requests
+3. **Request Routing**: When Infisical needs to access your resources, requests are routed through the relay server to the already-established gateway connection
+4. **Resource Access**: The gateway receives the routed requests and connects to your private resources on behalf of Infisical
+
+## Getting Started
+
+Ready to set up your gateway? Follow the guides below.
+
+<Columns cols={2}>
+ <Card title="Gateway Deployment" href="/documentation/platform/gateways/gateway-deployment">
+ Deploy and configure your gateway within your network infrastructure.
+ </Card>
+ <Card title="Relay Deployment" href="/documentation/platform/gateways/relay-deployment">
+ Set up relay servers if using self-deployed infrastructure.
+ </Card>
+</Columns>
+<Columns cols={1}>
+ <Card title="Security Architecture" href="/documentation/platform/gateways/security">
+ Learn about the security model and implementation best practices.
+ </Card>
+</Columns>
\ No newline at end of file
diff --git a/docs/documentation/platform/gateways/relay-deployment.mdx b/docs/documentation/platform/gateways/relay-deployment.mdx
new file mode 100644
index 0000000000..adf5fdb9de
--- /dev/null
+++ b/docs/documentation/platform/gateways/relay-deployment.mdx
@@ -0,0 +1,243 @@
+---
+title: "Relay Deployment"
+description: "How to deploy Infisical Relay Servers"
+---
+
+Infisical Relay is a secure routing layer that allows Infisical to connect to your private network resources, such as databases or internal APIs, without exposing them to the public internet.
+The relay acts as an intermediary, forwarding encrypted traffic between Infisical and your deployed gateways. This ensures that your sensitive data remains protected and never leaves your network unencrypted.
+With this architecture, you can achieve secure, firewall-friendly access across network boundaries, making it possible for Infisical to interact with resources even in highly restricted environments.
+
+Before diving in, it's important to determine whether you actually need to deploy your own relay server or if you can use Infisical's managed infrastructure.
+
+## Do You Need to Deploy a Relay?
+
+Not all users need to deploy their own relay servers. Infisical provides managed relay infrastructure in US/EU regions for Infisical Cloud users, which requires no setup or maintenance. You only need to deploy a relay if you:
+
+- Are self-hosting Infisical
+- Have a dedicated enterprise instance of Infisical (managed by Infisical)
+- Require closer geographic proximity to target resources than managed relays provide for lower latency and reduced network congestion when accessing resources through the relay
+- Need full control over relay infrastructure and traffic routing
+
+If you are using Infisical Cloud and do not have specific requirements, you can use the managed relays provided by Infisical and skip the rest of this guide.
+
+## Deployment Steps
+
+To successfully deploy an Infisical Relay for use, follow these steps in order.
+
+<Steps>
+ <Step title="Provision a Machine Identity">
+ Create a machine identity with the correct permissions to create and manage relays. This identity is used by the relay to authenticate with Infisical and should be provisioned in advance.
+ The relay supports several [machine identity auth methods](/documentation/platform/identities/machine-identities) for authentication, as listed below. Choose the one that best fits your environment and set the corresponding environment variables when deploying the relay.
+
+ <AccordionGroup>
+ <Accordion title="Universal Auth">
+ Simple and secure authentication using client ID and client secret.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=universal-auth`
+ - `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID=<client-id>`
+ - `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET=<client-secret>`
+ </Accordion>
+
+ <Accordion title="Token Auth">
+ Direct authentication using a machine identity access token.
+
+ **Environment Variables:**
+ - `INFISICAL_TOKEN=<token>`
+ </Accordion>
+
+ <Accordion title="Native Kubernetes">
+ Authentication using Kubernetes service account tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=kubernetes`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="Native AWS IAM">
+ Authentication using AWS IAM roles.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=aws-iam`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="Native GCP ID Token">
+ Authentication using GCP identity tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=gcp-id-token`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="GCP IAM">
+ Authentication using GCP service account keys.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=gcp-iam`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ - `INFISICAL_GCP_SERVICE_ACCOUNT_KEY_FILE_PATH=<path-to-key-file>`
+ </Accordion>
+
+ <Accordion title="Native Azure">
+ Authentication using Azure managed identity.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=azure`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ </Accordion>
+
+ <Accordion title="OIDC Auth">
+ Authentication using OIDC identity tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=oidc-auth`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ - `INFISICAL_JWT=<oidc-jwt>`
+ </Accordion>
+
+ <Accordion title="JWT Auth">
+ Authentication using JWT tokens.
+
+ **Environment Variables:**
+ - `INFISICAL_AUTH_METHOD=jwt-auth`
+ - `INFISICAL_MACHINE_IDENTITY_ID=<machine-identity-id>`
+ - `INFISICAL_JWT=<jwt>`
+ </Accordion>
+ </AccordionGroup>
+ </Step>
+
+ <Step title="Install the Infisical CLI">
+ Install the Infisical CLI on the server where you plan to deploy the relay. The CLI is required for relay installation and management.
+
+ See the [CLI Installation Guide](/cli/overview) for instructions.
+
+ This server must have a static IP address or DNS name to be identifiable by the Infisical platform.
+
+ </Step>
+
+ <Step title="Configure Network & Firewall">
+ Ensure your network and firewall settings allow the server to accept inbound connections and make outbound connections:
+
+ **Inbound Connections Rules:**
+ | Protocol | Source | Port | Purpose |
+ | -------- | ------------------ | ---- | -------------------------------- |
+ | TCP | Gateways | 2222 | SSH reverse tunnel establishment |
+ | TCP | Infisical instance host (US/EU, other) | 8443 | Platform-to-relay communication |
+
+ **Outbound Connections Rules:**
+ | Protocol | Destination | Port | Purpose |
+ | -------- | ------------------------------------ | ---- | ------------------------------------------ |
+ | TCP | Infisical instance host (US/EU, other) | 443 | API communication and certificate requests |
+
+ </Step>
+
+ <Step title="Select a Deployment Method">
+ The Infisical CLI is used to install and start the relay in your chosen environment. The CLI provides commands for both production and development scenarios, and supports a variety of options/flags to configure your deployment.
+
+ To view all available flags and equivalent environment variables for relay deployment, see the [Relay CLI Command Reference](/cli/commands/relay).
+ <Tabs>
+ <Tab title="Linux Server">
+ For production deployments on Linux servers, install the Relay as a systemd service. This installation method only supports [Token Auth](/documentation/platform/identities/token-auth) at the moment.
+
+ Once you have a [Token Auth](/documentation/platform/identities/token-auth) token, set the following environment variables for relay authentication:
+
+ ```bash
+ export INFISICAL_TOKEN=<your-machine-identity-token>
+ ```
+
+ <Warning>
+ The systemd install command requires a Linux operating system with root/sudo privileges.
+ </Warning>
+
+ ```bash
+ sudo infisical relay systemd install \
+ --token <your-machine-identity-token> \
+ --name <relay-name> \
+ --domain <your-infisical-domain> \
+ --host <static-ip-or-dns-of-the-server>
+
+ # Start the relay service
+ sudo systemctl start infisical-relay
+ sudo systemctl enable infisical-relay
+ ```
+ </Tab>
+
+ <Tab title="Other Environments">
+ For non-Linux systems or when you need more control over the relay process:
+
+ ```bash
+ infisical relay start \
+ --type=<type> \
+ --host=<host> \
+ --name=<name> \
+ --auth-method=<auth-method>
+ ```
+
+ This method supports all [machine identity auth methods](/documentation/platform/identities/machine-identities) and runs in the foreground. Suitable for production use on non-Linux systems or development environments.
+ Set the appropriate environment variables for your chosen auth method as described in Step 1 before running the relay start command.
+ </Tab>
+ </Tabs>
+
+ </Step>
+
+</Steps>
+
+## Frequently Asked Questions
+
+<Accordion title="Can the relay servers decrypt traffic going through them?">
+No, relay servers cannot decrypt any traffic passing through them due to end-to-end encryption:
+
+- **Client-to-Gateway mTLS (via TLS-pinned tunnel)**: Clients connect via a proxy that establishes a TLS-pinned tunnel to the gateway; mTLS between the client and gateway is negotiated inside this tunnel, encrypting all application traffic
+- **SSH tunnel encryption**: The mTLS-encrypted traffic is then transmitted through SSH reverse tunnels to relay servers
+- **Double encryption**: Traffic is encrypted twice - once by client mTLS and again by SSH tunnels
+- **Relay only routes traffic**: The relay server only routes the doubly-encrypted traffic without access to either encryption layer
+
+The relay infrastructure is designed as a secure routing mechanism where only the client and gateway can decrypt the actual application traffic.
+
+</Accordion>
+
+<Accordion title="What are the benefits of deploying my own relay?">
+Deploying your own relay provides several advantages:
+
+- **Dedicated resources**: Full control over relay infrastructure and performance
+- **Lower latency**: Deploy closer to your gateways for optimal performance
+- **Compliance**: Meet specific data routing and compliance requirements
+- **Custom network policies**: Implement organization-specific network configurations
+- **Geographic proximity**: Reduce network congestion and improve response times to access resources
+- **High availability**: Deploy multiple relays for redundancy and load distribution
+
+Organization-deployed relays give you complete control over your secure communication infrastructure.
+
+</Accordion>
+
+<Accordion title="How do I troubleshoot connectivity issues?">
+For detailed troubleshooting:
+
+**Platform cannot connect to relay:**
+
+- Check firewall rules allow inbound TCP with TLS on port 8443
+- Test connectivity: `openssl s_client -connect <relay-ip>:8443`
+
+**Test network connectivity:**
+
+```bash
+# Test outbound API access from relay. Replace URL with your Infisical instance if self-hosted
+curl -I https://app.infisical.com
+
+# Test TCP with TLS port from platform
+openssl s_client -connect <relay-ip>:8443
+```
+</Accordion>
+
+<Accordion title="What happens if my relay server goes down?">
+Relay server outages affect gateway connectivity:
+
+- **Gateway reconnection**: Gateways will automatically attempt to reconnect when the relay comes back online
+- **Service interruption**: While the relay is down, the Infisical platform cannot reach gateways through that relay. As a result, any secrets or resources accessed via those gateways will be temporarily unavailable until connectivity is restored.
+- **Multiple relays**: Deploy multiple relay servers for redundancy and high availability
+- **Automatic restart**: Use systemd or container orchestration to automatically restart failed relay services
+
+For production environments, consider deploying multiple relay servers to avoid single points of failure.
+
+</Accordion>
diff --git a/docs/documentation/platform/gateways/gateway-security.mdx b/docs/documentation/platform/gateways/security.mdx
similarity index 91%
rename from docs/documentation/platform/gateways/gateway-security.mdx
rename to docs/documentation/platform/gateways/security.mdx
index 6962c627e4..dc70aa36f0 100644
--- a/docs/documentation/platform/gateways/gateway-security.mdx
+++ b/docs/documentation/platform/gateways/security.mdx
@@ -1,13 +1,9 @@
---
-title: "Gateway Security Architecture"
-sidebarTitle: "Architecture"
-description: "Understand the security model and tenant isolation of Infisical's Gateway"
+title: "Security Architecture"
+description: "Security model, tenant isolation, and best practices for Infisical Gateways and Relays"
---
-# Gateway Security Architecture
-
The Infisical Gateway enables secure access to private resources using SSH reverse tunnels, certificate-based authentication, and a comprehensive PKI (Public Key Infrastructure) system. The architecture provides end-to-end encryption and complete tenant isolation through multiple certificate authorities.
-This document explains the internal security architecture and how tenant isolation is maintained.
## Security Model Overview
@@ -82,16 +78,16 @@ The platform establishes secure direct connections with gateways through a **TLS
2. **Connection Flow**:
```
- Platform ←→ [SSH Reverse Tunnel] ←→ Gateway
+ Platform ←→ [TCP with TLS] ←→ Relay ←→ [SSH Reverse Tunnel] ←→ Gateway
```
- Gateway maintains persistent outbound SSH tunnel to relay server
- - Platform connects directly to gateway through this tunnel
- - TLS handshake occurs over the SSH tunnel, establishing mTLS connection
- - Application traffic flows through the TLS-pinned tunnel
+ - Platform connects to relay server using TCP with TLS
+ - Relay routes encrypted traffic between platform and gateway
+ - TLS handshake occurs between platform and gateway through the relay
+ - Application traffic flows through the TLS-pinned tunnel via relay routing
3. **Security Benefits**:
-
- **No inbound connections**: Gateway never needs to accept incoming connections
- **Certificate-based authentication**: Uses Organization Gateway certificates for mutual TLS
- **Double encryption**: TLS traffic within SSH tunnel provides layered security
@@ -132,7 +128,6 @@ The architecture provides tenant isolation through multiple certificate authorit
- Ephemeral certificate validation ensures time-bound access
2. **Network Isolation**:
-
- Each organization's traffic flows through isolated certificate-authenticated channels
- Relay servers route traffic based on certificate validation without content access
- Gateway validates all incoming connections against Organization Gateway Client CA
diff --git a/docs/documentation/platform/identities/ldap-auth/general.mdx b/docs/documentation/platform/identities/ldap-auth/general.mdx
index 01395b68c4..f496434743 100644
--- a/docs/documentation/platform/identities/ldap-auth/general.mdx
+++ b/docs/documentation/platform/identities/ldap-auth/general.mdx
@@ -34,24 +34,33 @@ To create and manage LDAP auth templates, see our [Machine Identity Auth Templat
To configure LDAP auth for your identity, press the **Add Auth Method** button on the identity's page.
![Add auth method](/images/platform/identities/ldap/identities-org-add-auth-method.png)
-
+
Now select **LDAP Auth** from the list of available auth methods for the identity.
![Select LDAP auth](/images/platform/identities/ldap/identities-org-add-auth-method-modal.png)
-
-
+
+
After selecting **LDAP Auth**, you'll see the form you need to fill out to configure LDAP auth for your identity. The following fields are available:
+ **Configuration Tab**
- `URL`: The LDAP server to connect to such as `ldap://ldap.your-org.com`, `ldaps://ldap.myorg.com:636` _(for connection over SSL/TLS)_, etc.
- `Bind DN`: The DN to bind to the LDAP server with.
- `Bind Pass`: The password to bind to the LDAP server with.
- `Search Base / DN`: Base DN under which to perform user search such as `ou=Users,dc=acme,dc=com`.
- `User Search Filter`: Template used to construct the LDAP user search filter such as `(uid={{username}})`; use literal `{{username}}` to have the given username used in the search. The default is `(uid={{username}})` which is compatible with several common directory schemas.
- `Required Attributes`: A key/value pair of attributes that must be present in the LDAP user entry for them to be authenticated. As an example, if you set key `uid` to value `user1,user2,user3`, then only users with `uid` of `user1`, `user2`, or `user3` will be able to login with this identity. Each value is a comma separated list of attributes.
- - `CA Certificate`: The CA certificate to use when verifying the LDAP server certificate. This field is optional but recommended.
- `Access Token TTL` _(default is 2592000 equivalent to 30 days)_: The lifetime for an access token in seconds. This value will be referenced at renewal time.
- `Access Token Max TTL` _(default is 2592000 equivalent to 30 days)_: The maximum lifetime for an access token in seconds. This value will be referenced at renewal time.
- `Access Token Max Number of Uses` _(default is 0)_: The maximum number of times that an access token can be used; a value of 0 implies infinite number of uses.
+
+ **Lockout Tab**
+ - `Lockout` _(enabled by default)_: The lockout feature will temporarily block login attempts after X consecutive login failures.
+ - `Lockout Threshold` _(default is 3)_: The amount of times login must fail before locking the identity auth method.
+ - `Lockout Duration` _(default is 5 minutes)_: How long an identity auth method lockout lasts.
+ - `Lockout Counter Reset` _(default is 30 seconds)_: How long to wait from the most recent failed login until resetting the lockout counter.
+
+ **Advanced Tab**
+ - `CA Certificate`: The CA certificate to use when verifying the LDAP server certificate. This field is optional but recommended.
- `Access Token Trusted IPs`: The IPs or CIDR ranges that access tokens can be used from. By default, each token is given the 0.0.0.0/0, allowing usage from any network address.
Once you've filled out the form, press **Add** to save your changes.
@@ -91,3 +100,13 @@ To create and manage LDAP auth templates, see our [Machine Identity Auth Templat
</Step>
</Step>
</Steps>
+
+**FAQ**
+
+<AccordionGroup>
+ <Accordion title="How do I reset a lockout?">
+ You can reset (remove) all lockouts for an identity auth method by clicking into the auth method and pressing **Reset All Lockouts**.
+
+ ![ldap reset lockouts](/images/platform/identities/ldap-reset-lockouts.png)
+ </Accordion>
+</AccordionGroup>
diff --git a/docs/documentation/platform/identities/machine-identities.mdx b/docs/documentation/platform/identities/machine-identities.mdx
index b4a18708c9..7e40f85f93 100644
--- a/docs/documentation/platform/identities/machine-identities.mdx
+++ b/docs/documentation/platform/identities/machine-identities.mdx
@@ -38,6 +38,12 @@ To interact with various resources in Infisical, Machine Identities can authenti
- [GCP Auth](/documentation/platform/identities/gcp-auth): A GCP-native authentication method for GCP resources (e.g. Compute Engine, App Engine, Cloud Run, Google Kubernetes Engine, IAM service accounts, etc.).
- [OIDC Auth](/documentation/platform/identities/oidc-auth): A platform-agnostic, JWT-based authentication method for workloads using an OpenID Connect identity provider.
+## Identity Lockout
+
+Lockout is a feature that prevents brute-force attacks on identity login endpoints. Auth methods that support lockout include: [Universal Auth](/documentation/platform/identities/universal-auth), [LDAP Auth](/documentation/platform/identities/ldap-auth/general).
+
+Supported auth methods have lockout enabled by default. If triggered, lockout temporarily disables the login endpoint for 5 minutes after 3 consecutive failed login attempts within a 30-second window. Lockout can be configured and disabled in the identity auth method settings.
+
## FAQ
<AccordionGroup>
@@ -51,15 +57,15 @@ You can learn more about how to do this in the CLI quickstart [here](/cli/usage)
<Accordion title="What is the difference between an identity and service token?">
A service token is a project-level authentication method that is being deprecated in favor of identities. The service token method will be removed in the future in accordance with the deprecation notice and timeline stated [here](https://infisical.com/blog/deprecating-api-keys).
-
+
Amongst many differences, identities provide broader access over the Infisical API, utilizes the same
permission system as user identities, and come with a significantly larger number of configurable authentication and security features.
-
+
If you're looking for a simple authentication method, similar to service tokens, that can be bound onto an identity, we recommend checking out [Token Auth](/documentation/platform/identities/token-auth).
</Accordion>
<Accordion title="Why can I not create, read, update, or delete an identity?">
There are a few reasons for why this might happen:
-
+
- You have insufficient organization permissions to create, read, update, delete identities.
- The identity you are trying to read, update, or delete is more privileged than yourself.
- The role you are trying to create an identity for or update an identity to is more privileged than yours.
diff --git a/docs/documentation/platform/identities/universal-auth.mdx b/docs/documentation/platform/identities/universal-auth.mdx
index 51721f7bf9..3a87f6da99 100644
--- a/docs/documentation/platform/identities/universal-auth.mdx
+++ b/docs/documentation/platform/identities/universal-auth.mdx
@@ -4,7 +4,7 @@ description: "Learn how to authenticate to Infisical from any platform or enviro
---
**Universal Auth** is a platform-agnostic authentication method that can be configured for a [machine identity](/documentation/platform/identities/machine-identities) to authenticate from any platform/environment using a Client ID and Client Secret.
-This authentication method supports setting token periods, which can help [overcome secret zero](#solving-secret-zero-with-periodic-tokens).
+This authentication method supports setting token periods, which can help [overcome secret zero](#solving-secret-zero-with-periodic-tokens).
## Diagram
@@ -65,17 +65,32 @@ using the Universal Auth authentication method.
By default, the identity has been configured with Universal Auth. If you wish, you can edit the Universal Auth configuration
details by pressing to edit the **Authentication** section.
+ Here's some guidance on each field:
+
+ **Configuration Tab**
+
![identities organization create universal auth method 1](/images/platform/identities/identities-org-create-universal-auth-method-1.png)
+
+ - Access Token TTL (default is `2592000` equivalent to 30 days): The lifetime for an access token in seconds. This value will be referenced at renewal time.
+ - Access Token Max TTL (default is `2592000` equivalent to 30 days): The maximum lifetime for an access token in seconds. This value will be referenced at renewal time.
+ - Access Token Max Number of Uses (default is `0`): The maximum number of times that an access token can be used; a value of `0` implies infinite number of uses.
+ - Access Token Period (optional, default is `0`): If set, the access token becomes a renewable, non-expiring token for the specified period (in seconds). TTL and Max TTL are ignored when this is set. This is ideal for "secret zero" scenarios, where a workload needs to bootstrap itself securely without hard-coded static secrets.
+
+ **Lockout Tab**
+
![identities organization create universal auth method 2](/images/platform/identities/identities-org-create-universal-auth-method-2.png)
- Here's some more guidance on each field:
+ - Lockout (enabled by default): The lockout feature will temporarily block login attempts after X consecutive login failures.
+ - Lockout Threshold (default is `3`): The amount of times login must fail before locking the identity auth method.
+ - Lockout Duration (default is `5 minutes`): How long an identity auth method lockout lasts.
+ - Lockout Counter Reset (default is `30 seconds`): How long to wait from the most recent failed login until resetting the lockout counter.
+
+ **Advanced Tab**
+
+ ![identities organization create universal auth method 3](/images/platform/identities/identities-org-create-universal-auth-method-3.png)
- - Access Token TTL (default is `2592000` equivalent to 30 days): The lifetime for an acccess token in seconds. This value will be referenced at renewal time.
- - Access Token Max TTL (default is `2592000` equivalent to 30 days): The maximum lifetime for an acccess token in seconds. This value will be referenced at renewal time.
- - Access Token Max Number of Uses (default is `0`): The maximum number of times that an access token can be used; a value of `0` implies infinite number of uses.
- Client Secret Trusted IPs: The IPs or CIDR ranges that the **Client Secret** can be used from together with the **Client ID** to get back an access token. By default, **Client Secrets** are given the `0.0.0.0/0`, allowing usage from any network address.
- Access Token Trusted IPs: The IPs or CIDR ranges that access tokens can be used from. By default, each token is given the `0.0.0.0/0`, allowing usage from any network address.
- - Access Token Period (optional, default is `0`): If set, the access token becomes a renewable, non-expiring token for the specified period (in seconds). TTL and Max TTL are ignored when this is set. This is ideal for "secret zero" scenarios, where a workload needs to bootstrap itself securely without hard-coded static secrets.
<Warning>
Restricting **Client Secret** and access token usage to specific trusted IPs is a paid feature.
@@ -202,6 +217,10 @@ This approach allows your workload to securely bootstrap and maintain access to
A token can be renewed any number of times where each call to renew it can extend the token's lifetime by increments of the access token's TTL.
Regardless of how frequently an access token is renewed, its lifespan remains bound to the maximum TTL determined at its creation.
+ </Accordion>
+ <Accordion title="How do I reset a lockout?">
+ You can reset (remove) all lockouts for an identity auth method by clicking into the auth method and pressing **Reset All Lockouts**.
+ ![ua reset lockouts](/images/platform/identities/ua-reset-lockouts.png)
</Accordion>
</AccordionGroup>
diff --git a/docs/images/app-connections/general/add-connection.png b/docs/images/app-connections/general/add-connection.png
index ad9d54716c..b6dce69ac1 100644
Binary files a/docs/images/app-connections/general/add-connection.png and b/docs/images/app-connections/general/add-connection.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-configure-dce.png b/docs/images/platform/audit-log-streams/azure-configure-dce.png
new file mode 100644
index 0000000000..b0b32f0b21
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-configure-dce.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-configure-law.png b/docs/images/platform/audit-log-streams/azure-configure-law.png
new file mode 100644
index 0000000000..11ec8d86f5
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-configure-law.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-configure-table.png b/docs/images/platform/audit-log-streams/azure-configure-table.png
new file mode 100644
index 0000000000..7dba237b9f
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-configure-table.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-create-als.png b/docs/images/platform/audit-log-streams/azure-create-als.png
new file mode 100644
index 0000000000..bdfb2f8d6c
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-create-als.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-create-dce.png b/docs/images/platform/audit-log-streams/azure-create-dce.png
new file mode 100644
index 0000000000..00a546c308
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-create-dce.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-create-law.png b/docs/images/platform/audit-log-streams/azure-create-law.png
new file mode 100644
index 0000000000..1150f64ffc
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-create-law.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-dce-url.png b/docs/images/platform/audit-log-streams/azure-dce-url.png
new file mode 100644
index 0000000000..d8c1dc96dc
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-dce-url.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-dcr.png b/docs/images/platform/audit-log-streams/azure-dcr.png
new file mode 100644
index 0000000000..441808947d
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-dcr.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-go-to-resource.png b/docs/images/platform/audit-log-streams/azure-go-to-resource.png
new file mode 100644
index 0000000000..ef197517dc
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-go-to-resource.png differ
diff --git a/docs/images/platform/audit-log-streams/azure-new-table.png b/docs/images/platform/audit-log-streams/azure-new-table.png
new file mode 100644
index 0000000000..829af3e53e
Binary files /dev/null and b/docs/images/platform/audit-log-streams/azure-new-table.png differ
diff --git a/docs/images/platform/identities/identities-org-create-universal-auth-method-1.png b/docs/images/platform/identities/identities-org-create-universal-auth-method-1.png
index d3fe6fbe09..eaef0c10c0 100644
Binary files a/docs/images/platform/identities/identities-org-create-universal-auth-method-1.png and b/docs/images/platform/identities/identities-org-create-universal-auth-method-1.png differ
diff --git a/docs/images/platform/identities/identities-org-create-universal-auth-method-2.png b/docs/images/platform/identities/identities-org-create-universal-auth-method-2.png
index ea0fc96713..9aae59d046 100644
Binary files a/docs/images/platform/identities/identities-org-create-universal-auth-method-2.png and b/docs/images/platform/identities/identities-org-create-universal-auth-method-2.png differ
diff --git a/docs/images/platform/identities/identities-org-create-universal-auth-method-3.png b/docs/images/platform/identities/identities-org-create-universal-auth-method-3.png
new file mode 100644
index 0000000000..c966afdb49
Binary files /dev/null and b/docs/images/platform/identities/identities-org-create-universal-auth-method-3.png differ
diff --git a/docs/images/platform/identities/ldap-reset-lockouts.png b/docs/images/platform/identities/ldap-reset-lockouts.png
new file mode 100644
index 0000000000..c8aae2eff9
Binary files /dev/null and b/docs/images/platform/identities/ldap-reset-lockouts.png differ
diff --git a/docs/images/platform/identities/ua-reset-lockouts.png b/docs/images/platform/identities/ua-reset-lockouts.png
new file mode 100644
index 0000000000..40993da1ac
Binary files /dev/null and b/docs/images/platform/identities/ua-reset-lockouts.png differ
diff --git a/docs/integrations/app-connections/1password.mdx b/docs/integrations/app-connections/1password.mdx
index 394d8bc239..bcd7e8ff77 100644
--- a/docs/integrations/app-connections/1password.mdx
+++ b/docs/integrations/app-connections/1password.mdx
@@ -53,7 +53,7 @@ Infisical supports the use of [Service Accounts](https://developer.1password.com
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -72,7 +72,7 @@ Infisical supports the use of [Service Accounts](https://developer.1password.com
![1Password Connection Modal](/images/app-connections/1password/app-connection-modal.png)
</Step>
<Step title="Connection Created">
- After clicking Create, your **1Password Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **1Password Connection** is established and ready to use with your Infisical project.
![1Password Connection Created](/images/app-connections/1password/app-connection-created.png)
</Step>
@@ -90,6 +90,7 @@ Infisical supports the use of [Service Accounts](https://developer.1password.com
--data '{
"name": "my-1password-connection",
"method": "api-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"instanceUrl": "https://1pass.example.com",
"apiToken": "<YOUR-API-TOKEN>"
@@ -104,6 +105,7 @@ Infisical supports the use of [Service Accounts](https://developer.1password.com
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-1password-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/auth0.mdx b/docs/integrations/app-connections/auth0.mdx
index 42e78cb66c..91c5f5e607 100644
--- a/docs/integrations/app-connections/auth0.mdx
+++ b/docs/integrations/app-connections/auth0.mdx
@@ -42,7 +42,7 @@ Infisical supports the use of [Client Credentials](https://auth0.com/docs/get-st
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **Auth0 Connection** option.
@@ -67,6 +67,7 @@ Infisical supports the use of [Client Credentials](https://auth0.com/docs/get-st
--data '{
"name": "my-auth0-connection",
"method": "client-credentials",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"domain": "xxx-xxxxxxxxx.us.auth0.com",
"clientId": "...",
@@ -83,6 +84,7 @@ Infisical supports the use of [Client Credentials](https://auth0.com/docs/get-st
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-auth0-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/aws.mdx b/docs/integrations/app-connections/aws.mdx
index 195f982478..08ae05be71 100644
--- a/docs/integrations/app-connections/aws.mdx
+++ b/docs/integrations/app-connections/aws.mdx
@@ -184,7 +184,7 @@ Infisical supports two methods for connecting to AWS.
<Step title="Setup AWS Connection in Infisical">
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **AWS Connection** option.
@@ -209,6 +209,7 @@ Infisical supports two methods for connecting to AWS.
--data '{
"name": "my-aws-connection",
"method": "assume-role",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"roleArn": "...",
}
@@ -222,6 +223,7 @@ Infisical supports two methods for connecting to AWS.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-aws-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 123,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
@@ -361,7 +363,7 @@ Infisical supports two methods for connecting to AWS.
<Step title="Setup AWS Connection in Infisical">
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **AWS Connection** option.
@@ -386,6 +388,7 @@ Infisical supports two methods for connecting to AWS.
--data '{
"name": "my-aws-connection",
"method": "access-key",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"accessKeyId": "...",
"secretKey": "..."
@@ -400,6 +403,7 @@ Infisical supports two methods for connecting to AWS.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-aws-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 123,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/azure-app-configuration.mdx b/docs/integrations/app-connections/azure-app-configuration.mdx
index 4efd19f309..cd9c707be3 100644
--- a/docs/integrations/app-connections/azure-app-configuration.mdx
+++ b/docs/integrations/app-connections/azure-app-configuration.mdx
@@ -83,7 +83,7 @@ Infisical currently only supports two methods for connecting to Azure, which are
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/azure-client-secrets.mdx b/docs/integrations/app-connections/azure-client-secrets.mdx
index 37e7d49b05..cb25fb5968 100644
--- a/docs/integrations/app-connections/azure-client-secrets.mdx
+++ b/docs/integrations/app-connections/azure-client-secrets.mdx
@@ -94,7 +94,7 @@ Infisical currently only supports two methods for connecting to Azure, which are
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/azure-devops.mdx b/docs/integrations/app-connections/azure-devops.mdx
index 4744a35c6f..7eabff84ba 100644
--- a/docs/integrations/app-connections/azure-devops.mdx
+++ b/docs/integrations/app-connections/azure-devops.mdx
@@ -117,7 +117,7 @@ Infisical currently supports three methods for connecting to Azure DevOps, which
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/azure-key-vault.mdx b/docs/integrations/app-connections/azure-key-vault.mdx
index 866a1de82d..b2989efae4 100644
--- a/docs/integrations/app-connections/azure-key-vault.mdx
+++ b/docs/integrations/app-connections/azure-key-vault.mdx
@@ -83,7 +83,7 @@ Infisical currently only supports two methods for connecting to Azure, which are
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/bitbucket.mdx b/docs/integrations/app-connections/bitbucket.mdx
index be4fdbee76..3b33852025 100644
--- a/docs/integrations/app-connections/bitbucket.mdx
+++ b/docs/integrations/app-connections/bitbucket.mdx
@@ -78,7 +78,7 @@ Infisical supports the use of [API Tokens](https://support.atlassian.com/bitbuck
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -95,7 +95,7 @@ Infisical supports the use of [API Tokens](https://support.atlassian.com/bitbuck
![Bitbucket Connection Modal](/images/app-connections/bitbucket/step-6.png)
</Step>
<Step title="Connection Created">
- After clicking Create, your **Bitbucket Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **Bitbucket Connection** is established and ready to use with your Infisical project.
![Bitbucket Connection Created](/images/app-connections/bitbucket/step-7.png)
</Step>
@@ -113,6 +113,7 @@ Infisical supports the use of [API Tokens](https://support.atlassian.com/bitbuck
--data '{
"name": "my-bitbucket-connection",
"method": "api-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"email": "[email protected]",
"apiToken": "<YOUR-API-TOKEN>"
@@ -127,6 +128,7 @@ Infisical supports the use of [API Tokens](https://support.atlassian.com/bitbuck
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-bitbucket-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/camunda.mdx b/docs/integrations/app-connections/camunda.mdx
index 68084cea3d..7ad0f8ef92 100644
--- a/docs/integrations/app-connections/camunda.mdx
+++ b/docs/integrations/app-connections/camunda.mdx
@@ -50,8 +50,7 @@ Infisical supports connecting to Camunda APIs using [client credentials](https:/
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings**
- page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/checkly.mdx b/docs/integrations/app-connections/checkly.mdx
index 38234744d3..943a470c28 100644
--- a/docs/integrations/app-connections/checkly.mdx
+++ b/docs/integrations/app-connections/checkly.mdx
@@ -37,7 +37,7 @@ Infisical supports the use of [API Keys](https://app.checklyhq.com/settings/user
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and open the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -55,7 +55,7 @@ Infisical supports the use of [API Keys](https://app.checklyhq.com/settings/user
![Checkly Connection Modal](/images/app-connections/checkly/checkly-app-connection-form.png)
</Step>
<Step title="Connection created">
- After submitting the form, your **Checkly Connection** will be successfully created and ready to use with your Infisical projects.
+ After submitting the form, your **Checkly Connection** will be successfully created and ready to use with your Infisical project.
![Checkly Connection Created](/images/app-connections/checkly/checkly-app-connection-generated.png)
</Step>
@@ -75,6 +75,7 @@ Infisical supports the use of [API Keys](https://app.checklyhq.com/settings/user
--data '{
"name": "my-checkly-connection",
"method": "api-key",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"apiKey": "[API KEY]"
}
@@ -88,6 +89,7 @@ Infisical supports the use of [API Keys](https://app.checklyhq.com/settings/user
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-checkly-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/cloudflare.mdx b/docs/integrations/app-connections/cloudflare.mdx
index 241c737bc7..33a9a992c7 100644
--- a/docs/integrations/app-connections/cloudflare.mdx
+++ b/docs/integrations/app-connections/cloudflare.mdx
@@ -88,8 +88,7 @@ Infisical supports connecting to Cloudflare using API tokens and Account ID for
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings**
- page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/databricks.mdx b/docs/integrations/app-connections/databricks.mdx
index 38d125ea6b..e0b861184f 100644
--- a/docs/integrations/app-connections/databricks.mdx
+++ b/docs/integrations/app-connections/databricks.mdx
@@ -43,8 +43,7 @@ Infisical supports the use of [service principals](https://docs.databricks.com/e
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings**
- page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/digital-ocean.mdx b/docs/integrations/app-connections/digital-ocean.mdx
index 5b047f0176..ff2eccfc19 100644
--- a/docs/integrations/app-connections/digital-ocean.mdx
+++ b/docs/integrations/app-connections/digital-ocean.mdx
@@ -45,7 +45,7 @@ Infisical supports the use of [API Tokens](https://cloud.digitalocean.com/accoun
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and open the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -63,7 +63,7 @@ Infisical supports the use of [API Tokens](https://cloud.digitalocean.com/accoun
![DigitalOcean Connection Modal](/images/app-connections/digital-ocean/app-connection-form.png)
</Step>
<Step title="Connection created">
- After submitting the form, your **DigitalOcean Connection** will be successfully created and ready to use with your Infisical projects.
+ After submitting the form, your **DigitalOcean Connection** will be successfully created and ready to use with your Infisical project.
![DigitalOcean Connection Created](/images/app-connections/digital-ocean/app-connection-generated.png)
</Step>
@@ -82,6 +82,7 @@ Infisical supports the use of [API Tokens](https://cloud.digitalocean.com/accoun
--data '{
"name": "my-digitalocean-connection",
"method": "api-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"apiToken": "[API TOKEN]"
}
@@ -95,6 +96,7 @@ Infisical supports the use of [API Tokens](https://cloud.digitalocean.com/accoun
"appConnection": {
"id": "a1b2c3d4-5678-90ab-cdef-1234567890ab",
"name": "my-digitalocean-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "abcdef12-3456-7890-abcd-ef1234567890",
diff --git a/docs/integrations/app-connections/flyio.mdx b/docs/integrations/app-connections/flyio.mdx
index e42756254e..bf36ccc9bc 100644
--- a/docs/integrations/app-connections/flyio.mdx
+++ b/docs/integrations/app-connections/flyio.mdx
@@ -30,7 +30,7 @@ Infisical supports the use of [Access Tokens](https://fly.io/docs/security/token
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -48,7 +48,7 @@ Infisical supports the use of [Access Tokens](https://fly.io/docs/security/token
![Fly.io Connection Modal](/images/app-connections/flyio/app-connection-modal.png)
</Step>
<Step title="Connection Created">
- After clicking Create, your **Fly.io Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **Fly.io Connection** is established and ready to use with your Infisical project.
![Fly.io Connection Created](/images/app-connections/flyio/app-connection-created.png)
</Step>
@@ -66,6 +66,7 @@ Infisical supports the use of [Access Tokens](https://fly.io/docs/security/token
--data '{
"name": "my-flyio-connection",
"method": "access-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"accessToken": "[PRIVATE TOKEN]"
}
@@ -79,6 +80,7 @@ Infisical supports the use of [Access Tokens](https://fly.io/docs/security/token
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-flyio-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/gcp.mdx b/docs/integrations/app-connections/gcp.mdx
index 129c26c2ab..9458339afc 100644
--- a/docs/integrations/app-connections/gcp.mdx
+++ b/docs/integrations/app-connections/gcp.mdx
@@ -82,8 +82,7 @@ Infisical supports [service account impersonation](https://cloud.google.com/iam/
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings**
- page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/github-radar.mdx b/docs/integrations/app-connections/github-radar.mdx
index 376973efd6..491070a8b8 100644
--- a/docs/integrations/app-connections/github-radar.mdx
+++ b/docs/integrations/app-connections/github-radar.mdx
@@ -97,7 +97,7 @@ Infisical supports GitHub App installation for creating a GitHub Radar Connectio
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/github.mdx b/docs/integrations/app-connections/github.mdx
index 9a952f8155..e44fc405a9 100644
--- a/docs/integrations/app-connections/github.mdx
+++ b/docs/integrations/app-connections/github.mdx
@@ -85,7 +85,7 @@ Infisical supports two methods for connecting to GitHub.
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
@@ -156,7 +156,7 @@ Infisical supports two methods for connecting to GitHub.
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/gitlab.mdx b/docs/integrations/app-connections/gitlab.mdx
index 60e9236ca1..4f7223d939 100644
--- a/docs/integrations/app-connections/gitlab.mdx
+++ b/docs/integrations/app-connections/gitlab.mdx
@@ -70,7 +70,7 @@ Infisical supports two methods for connecting to GitLab: **OAuth** and **Access
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
@@ -193,7 +193,7 @@ Infisical supports two methods for connecting to GitLab: **OAuth** and **Access
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/hashicorp-vault.mdx b/docs/integrations/app-connections/hashicorp-vault.mdx
index c49b53ab82..7d5502fc59 100644
--- a/docs/integrations/app-connections/hashicorp-vault.mdx
+++ b/docs/integrations/app-connections/hashicorp-vault.mdx
@@ -131,7 +131,7 @@ Infisical supports two methods for connecting to Hashicorp Vault.
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the **App Connections** tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -184,6 +184,7 @@ Infisical supports two methods for connecting to Hashicorp Vault.
--data '{
"name": "my-vault-connection",
"method": "app-role",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"instanceUrl": "https://vault.example.com",
"roleId": "4797c4fa-7794-71f0-c8b1-7c87759df5bf",
@@ -199,6 +200,7 @@ Infisical supports two methods for connecting to Hashicorp Vault.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-vault-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2025-04-01T05:31:56Z",
diff --git a/docs/integrations/app-connections/heroku.mdx b/docs/integrations/app-connections/heroku.mdx
index fc2d1fbcc2..9c3397e02e 100644
--- a/docs/integrations/app-connections/heroku.mdx
+++ b/docs/integrations/app-connections/heroku.mdx
@@ -51,7 +51,7 @@ Infisical supports two methods for connecting to Heroku: **OAuth** and **Auth To
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
@@ -93,7 +93,7 @@ Infisical supports two methods for connecting to Heroku: **OAuth** and **Auth To
![Heroku API Token](/images/app-connections/heroku/heroku-api-token.png)
</Step>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/humanitec.mdx b/docs/integrations/app-connections/humanitec.mdx
index 570d3ba5d5..669798eeb2 100644
--- a/docs/integrations/app-connections/humanitec.mdx
+++ b/docs/integrations/app-connections/humanitec.mdx
@@ -53,7 +53,7 @@ Infisical supports connecting to Humanitec using a service user.
![Humanitec Connection Created](/images/app-connections/humanitec/humanitec-user-added.png)
</Step>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings** page.
+ Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/ldap.mdx b/docs/integrations/app-connections/ldap.mdx
index db0b596ceb..f0afa11579 100644
--- a/docs/integrations/app-connections/ldap.mdx
+++ b/docs/integrations/app-connections/ldap.mdx
@@ -33,7 +33,7 @@ Depending on how you intend to use your LDAP connection, there may be additional
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **LDAP Connection** option.
@@ -58,6 +58,7 @@ Depending on how you intend to use your LDAP connection, there may be additional
--data '{
"name": "my-ldap-connection",
"method": "simple-bind",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"provider": "active-directory",
"url": "ldaps://domain-or-ip:636",
@@ -76,6 +77,7 @@ Depending on how you intend to use your LDAP connection, there may be additional
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-ldap-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/mssql.mdx b/docs/integrations/app-connections/mssql.mdx
index 7e940804d8..77e8e676d7 100644
--- a/docs/integrations/app-connections/mssql.mdx
+++ b/docs/integrations/app-connections/mssql.mdx
@@ -62,7 +62,7 @@ Infisical supports connecting to Microsoft SQL Server using database principals.
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **Microsoft SQL Server Connection** option.
@@ -96,6 +96,7 @@ Infisical supports connecting to Microsoft SQL Server using database principals.
--data '{
"name": "my-mssql-connection",
"method": "username-and-password",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"isPlatformManagedCredentials": true,
"credentials": {
"host": "123.4.5.6",
@@ -115,7 +116,8 @@ Infisical supports connecting to Microsoft SQL Server using database principals.
{
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
- "name": "my-pg-connection",
+ "name": "my-mssql-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/mysql.mdx b/docs/integrations/app-connections/mysql.mdx
index 38a8a4e978..6055d77cc3 100644
--- a/docs/integrations/app-connections/mysql.mdx
+++ b/docs/integrations/app-connections/mysql.mdx
@@ -52,7 +52,7 @@ Infisical supports connecting to MySQL using a database role.
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **MySQL Connection** option.
@@ -88,6 +88,7 @@ Infisical supports connecting to MySQL using a database role.
"name": "my-mysql-connection",
"method": "username-and-password",
"isPlatformManagedCredentials": true,
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"host": "123.4.5.6",
"port": 3306,
@@ -107,6 +108,7 @@ Infisical supports connecting to MySQL using a database role.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-mysql-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/netlify.mdx b/docs/integrations/app-connections/netlify.mdx
index cd4dfb1b59..d2a62113c8 100644
--- a/docs/integrations/app-connections/netlify.mdx
+++ b/docs/integrations/app-connections/netlify.mdx
@@ -35,7 +35,7 @@ Infisical supports the use of [Personal Access Tokens](https://docs.netlify.com/
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and open the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -53,7 +53,7 @@ Infisical supports the use of [Personal Access Tokens](https://docs.netlify.com/
![Netlify Connection Modal](/images/app-connections/netlify/app-connection-form.png)
</Step>
<Step title="Connection created">
- After submitting the form, your **Netlify Connection** will be successfully created and ready to use with your Infisical projects.
+ After submitting the form, your **Netlify Connection** will be successfully created and ready to use with your Infisical project.
![Netlify Connection Created](/images/app-connections/netlify/app-connection-generated.png)
</Step>
@@ -72,6 +72,7 @@ Infisical supports the use of [Personal Access Tokens](https://docs.netlify.com/
--data '{
"name": "my-netlify-connection",
"method": "access-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"accessToken": "[ACCESS TOKEN]"
}
@@ -86,6 +87,7 @@ Infisical supports the use of [Personal Access Tokens](https://docs.netlify.com/
"id": "a1b2c3d4-5678-90ab-cdef-1234567890ab",
"name": "my-netlify-connection",
"description": null,
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "abcdef12-3456-7890-abcd-ef1234567890",
"createdAt": "2025-07-19T10:15:00.000Z",
diff --git a/docs/integrations/app-connections/oci.mdx b/docs/integrations/app-connections/oci.mdx
index 58fb3c1d31..10d5fabaa4 100644
--- a/docs/integrations/app-connections/oci.mdx
+++ b/docs/integrations/app-connections/oci.mdx
@@ -117,7 +117,7 @@ Infisical supports the use of [API Signing Key Authentication](https://docs.orac
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -139,7 +139,7 @@ Infisical supports the use of [API Signing Key Authentication](https://docs.orac
![OCI Connection Modal](/images/app-connections/oci/app-connection-modal.png)
</Step>
<Step title="Connection Created">
- After clicking Create, your **OCI Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **OCI Connection** is established and ready to use with your Infisical project.
![OCI Connection Created](/images/app-connections/oci/app-connection-created.png)
</Step>
@@ -157,6 +157,7 @@ Infisical supports the use of [API Signing Key Authentication](https://docs.orac
--data '{
"name": "my-oci-connection",
"method": "access-key",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"userOcid": "ocid1.user.oc1..aaaaaaaagrp35tbkvvad4y2j7sug7xonua7dl2gfp4at2u5i5xj4ghnitg3a",
"tenancyOcid": "ocid1.tenancy.oc1..aaaaaaaaotfma465m4zumfe2ua64mj2m5dwmlw2llh4g4dnfttnakiifonta",
@@ -174,6 +175,7 @@ Infisical supports the use of [API Signing Key Authentication](https://docs.orac
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-oci-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/okta.mdx b/docs/integrations/app-connections/okta.mdx
index 3c1295cf83..cb5edecbda 100644
--- a/docs/integrations/app-connections/okta.mdx
+++ b/docs/integrations/app-connections/okta.mdx
@@ -31,7 +31,7 @@ Infisical supports the use of [API Tokens](https://developer.okta.com/docs/guide
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -48,7 +48,7 @@ Infisical supports the use of [API Tokens](https://developer.okta.com/docs/guide
![Connection Modal](/images/app-connections/okta/step-4.png)
</Step>
<Step title="Connection Created">
- After clicking Create, your **Okta Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **Okta Connection** is established and ready to use with your Infisical project.
![Connection Created](/images/app-connections/okta/step-5.png)
</Step>
@@ -66,6 +66,7 @@ Infisical supports the use of [API Tokens](https://developer.okta.com/docs/guide
--data '{
"name": "my-okta-connection",
"method": "api-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"instanceUrl": "https://example.okta.com",
"apiToken": "<YOUR-API-TOKEN>"
@@ -80,6 +81,7 @@ Infisical supports the use of [API Tokens](https://developer.okta.com/docs/guide
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-okta-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/oracledb.mdx b/docs/integrations/app-connections/oracledb.mdx
index 8cab6371b7..47aa33356f 100644
--- a/docs/integrations/app-connections/oracledb.mdx
+++ b/docs/integrations/app-connections/oracledb.mdx
@@ -62,7 +62,7 @@ Infisical supports connecting to OracleDB using a database user.
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **OracleDB Connection** option.
@@ -98,6 +98,7 @@ Infisical supports connecting to OracleDB using a database user.
"name": "my-oracledb-connection",
"method": "username-and-password",
"isPlatformManagedCredentials": true,
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"host": "123.4.5.6",
"port": 1521,
@@ -117,6 +118,7 @@ Infisical supports connecting to OracleDB using a database user.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-oracledb-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/overview.mdx b/docs/integrations/app-connections/overview.mdx
index e698c43025..8b1032e7df 100644
--- a/docs/integrations/app-connections/overview.mdx
+++ b/docs/integrations/app-connections/overview.mdx
@@ -3,12 +3,16 @@ sidebarTitle: "Overview"
description: "Learn how to manage and configure third-party app connections with Infisical."
---
-App Connections enable your organization to integrate Infisical with third-party services in a secure and versatile way.
+App Connections enable you to integrate your Infisical projects with third-party services in a secure and versatile way.
+
+<Note>
+ App connections can also be created and managed independently in projects now.
+</Note>
## Concept
-App Connections are an organization-level resource used to establish connections with third-party applications
-that can be used across Infisical projects. Example use cases include syncing secrets, generating dynamic secrets, and more.
+App Connections can be used to establish connections with third-party applications
+that can be used across multiple features. Example use cases include syncing secrets, rotating credentials, scanning repositories for secret leaks, and more.
<br />
diff --git a/docs/integrations/app-connections/postgres.mdx b/docs/integrations/app-connections/postgres.mdx
index 2396089053..dcb6c76d87 100644
--- a/docs/integrations/app-connections/postgres.mdx
+++ b/docs/integrations/app-connections/postgres.mdx
@@ -60,7 +60,7 @@ Infisical supports connecting to PostgreSQL using a database role.
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the App Connections tab on the Organization Settings page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **PostgreSQL Connection** option.
@@ -95,6 +95,7 @@ Infisical supports connecting to PostgreSQL using a database role.
"name": "my-pg-connection",
"method": "username-and-password",
"isPlatformManagedCredentials": true,
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"host": "123.4.5.6",
"port": 5432,
@@ -114,6 +115,7 @@ Infisical supports connecting to PostgreSQL using a database role.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-pg-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 1,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/railway.mdx b/docs/integrations/app-connections/railway.mdx
index 7b53d02ad1..b88b3fbf1b 100644
--- a/docs/integrations/app-connections/railway.mdx
+++ b/docs/integrations/app-connections/railway.mdx
@@ -96,7 +96,7 @@ Infisical supports the use of [API Tokens](https://docs.railway.com/guides/publi
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and open the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -115,7 +115,7 @@ Infisical supports the use of [API Tokens](https://docs.railway.com/guides/publi
![Railway Connection Modal](/images/app-connections/railway/railway-app-connection-form.png)
</Step>
<Step title="Connection created">
- After submitting the form, your **Railway Connection** will be successfully created and ready to use with your Infisical projects.
+ After submitting the form, your **Railway Connection** will be successfully created and ready to use with your Infisical project.
![Railway Connection Created](/images/app-connections/railway/railway-app-connection-generated.png)
</Step>
@@ -134,6 +134,7 @@ Infisical supports the use of [API Tokens](https://docs.railway.com/guides/publi
--data '{
"name": "my-railway-connection",
"method": "team-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"apiToken": "[TEAM TOKEN]"
}
@@ -147,6 +148,7 @@ Infisical supports the use of [API Tokens](https://docs.railway.com/guides/publi
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-railway-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/render.mdx b/docs/integrations/app-connections/render.mdx
index 580ec953ec..78e0501353 100644
--- a/docs/integrations/app-connections/render.mdx
+++ b/docs/integrations/app-connections/render.mdx
@@ -33,8 +33,7 @@ Infisical supports connecting to Render using API keys for secure access to your
<Steps>
<Step title="Navigate to App Connections">
- Navigate to the **App Connections** tab on the **Organization Settings**
- page. ![App Connections
+ Navigate to the **App Connections** page in the desired project. ![App Connections
Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
diff --git a/docs/integrations/app-connections/supabase.mdx b/docs/integrations/app-connections/supabase.mdx
index 9716b15265..80290cec9a 100644
--- a/docs/integrations/app-connections/supabase.mdx
+++ b/docs/integrations/app-connections/supabase.mdx
@@ -34,7 +34,7 @@ Infisical supports the use of [Personal Access Tokens](https://supabase.com/dash
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and open the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -53,7 +53,7 @@ Infisical supports the use of [Personal Access Tokens](https://supabase.com/dash
![Supabase Connection Modal](/images/app-connections/supabase/app-connection-form.png)
</Step>
<Step title="Connection created">
- After submitting the form, your **Supabase Connection** will be successfully created and ready to use with your Infisical projects.
+ After submitting the form, your **Supabase Connection** will be successfully created and ready to use with your Infisical project.
![Supabase Connection Created](/images/app-connections/supabase/app-connection-generated.png)
</Step>
@@ -73,6 +73,7 @@ Infisical supports the use of [Personal Access Tokens](https://supabase.com/dash
--data '{
"name": "my-supabase-connection",
"method": "access-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"accessToken": "[Access Token]",
"instanceUrl": "https://api.supabase.com"
@@ -87,6 +88,7 @@ Infisical supports the use of [Personal Access Tokens](https://supabase.com/dash
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-supabase-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/teamcity.mdx b/docs/integrations/app-connections/teamcity.mdx
index 8893559546..311326f074 100644
--- a/docs/integrations/app-connections/teamcity.mdx
+++ b/docs/integrations/app-connections/teamcity.mdx
@@ -51,7 +51,7 @@ Infisical supports connecting to TeamCity using Access Tokens.
<Tab title="Infisical UI">
1. Navigate to App Connections
- In your Infisical dashboard, go to **Organization Settings** and select the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Add Connection
@@ -68,7 +68,7 @@ Infisical supports connecting to TeamCity using Access Tokens.
![TeamCity Connection Modal](/images/app-connections/teamcity/teamcity-app-connection-modal.png)
4. Connection Created
- After clicking Create, your **TeamCity Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **TeamCity Connection** is established and ready to use with your Infisical project.
![TeamCity Connection Created](/images/app-connections/teamcity/teamcity-app-connection-created.png)
</Tab>
<Tab title="API">
@@ -84,6 +84,7 @@ Infisical supports connecting to TeamCity using Access Tokens.
--data '{
"name": "my-teamcity-connection",
"method": "access-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"accessToken": "...",
"instanceUrl": "https://yourcompany.teamcity.com"
@@ -98,6 +99,7 @@ Infisical supports connecting to TeamCity using Access Tokens.
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-teamcity-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/app-connections/terraform-cloud.mdx b/docs/integrations/app-connections/terraform-cloud.mdx
index 02deb22cc8..bc3da7810b 100644
--- a/docs/integrations/app-connections/terraform-cloud.mdx
+++ b/docs/integrations/app-connections/terraform-cloud.mdx
@@ -30,7 +30,7 @@ Infisical supports connecting to Terraform Cloud using a service user.
<Step title="Add Terraform Cloud Connection in Infisical">
<Tabs>
<Tab title="Infisical UI">
- 1. Navigate to the **App Connections** tab on the **Organization Settings** page.
+ 1. Navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Select the **Terraform Cloud Connection** option from the connection options modal.
![Select Terraform Cloud Connection](/images/app-connections/terraform-cloud/terraform-cloud-app-connection-option.png)
@@ -52,6 +52,7 @@ Infisical supports connecting to Terraform Cloud using a service user.
--data '{
"name": "my-terraform-cloud-connection",
"method": "api-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"apiToken": "...",
}
@@ -65,6 +66,7 @@ Infisical supports connecting to Terraform Cloud using a service user.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-terraform-cloud-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 123,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2023-11-07T05:31:56Z",
diff --git a/docs/integrations/app-connections/vercel.mdx b/docs/integrations/app-connections/vercel.mdx
index 7ab7bea1bf..17973db9b1 100644
--- a/docs/integrations/app-connections/vercel.mdx
+++ b/docs/integrations/app-connections/vercel.mdx
@@ -37,7 +37,7 @@ Infisical supports connecting to Vercel using API Tokens.
<Tab title="Infisical UI">
1. Navigate to App Connections
- In your Infisical dashboard, go to **Organization Settings** and select the **App Connections** tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
2. Add Connection
@@ -52,7 +52,7 @@ Infisical supports connecting to Vercel using API Tokens.
![Vercel Connection Modal](/images/app-connections/vercel/vercel-app-connection-modal.png)
4. Connection Created
- After clicking Create, your **Vercel Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **Vercel Connection** is established and ready to use with your Infisical project.
![Vercel Connection Created](/images/app-connections/vercel/vercel-app-connection-created.png)
</Tab>
<Tab title="API">
@@ -67,6 +67,7 @@ Infisical supports connecting to Vercel using API Tokens.
--header 'Content-Type: application/json' \
--data '{
"name": "my-vercel-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"method": "api-token",
"credentials": {
"apiToken": "...",
@@ -81,6 +82,7 @@ Infisical supports connecting to Vercel using API Tokens.
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-vercel-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 123,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2025-04-01T05:31:56Z",
diff --git a/docs/integrations/app-connections/windmill.mdx b/docs/integrations/app-connections/windmill.mdx
index 5cab9fa381..d90c83a1bd 100644
--- a/docs/integrations/app-connections/windmill.mdx
+++ b/docs/integrations/app-connections/windmill.mdx
@@ -47,7 +47,8 @@ Ensure the user generating the access token has the required role and permission
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the **App Connections** tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
+
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
<Step title="Add Connection">
@@ -82,6 +83,7 @@ Ensure the user generating the access token has the required role and permission
--data '{
"name": "my-windmill-connection",
"method": "access-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"token": "...",
"instanceUrl": "https://app.windmill.dev"
@@ -96,6 +98,7 @@ Ensure the user generating the access token has the required role and permission
"appConnection": {
"id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"name": "my-windmill-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"version": 123,
"orgId": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
"createdAt": "2025-04-01T05:31:56Z",
diff --git a/docs/integrations/app-connections/zabbix.mdx b/docs/integrations/app-connections/zabbix.mdx
index c4d47b22e2..45141e8278 100644
--- a/docs/integrations/app-connections/zabbix.mdx
+++ b/docs/integrations/app-connections/zabbix.mdx
@@ -31,7 +31,7 @@ Infisical supports the use of [API Tokens](https://www.zabbix.com/documentation/
<Tab title="Infisical UI">
<Steps>
<Step title="Navigate to App Connections">
- In your Infisical dashboard, go to **Organization Settings** and select the [**App Connections**](https://app.infisical.com/organization/app-connections) tab.
+ In your Infisical dashboard, navigate to the **App Connections** page in the desired project.
![App Connections Tab](/images/app-connections/general/add-connection.png)
</Step>
@@ -50,7 +50,7 @@ Infisical supports the use of [API Tokens](https://www.zabbix.com/documentation/
![Zabbix Connection Modal](/images/app-connections/zabbix/zabbix-app-connection-form.png)
</Step>
<Step title="Connection Created">
- After clicking Create, your **Zabbix Connection** is established and ready to use with your Infisical projects.
+ After clicking Create, your **Zabbix Connection** is established and ready to use with your Infisical project.
![Zabbix Connection Created](/images/app-connections/zabbix/zabbix-app-connection-generated.png)
</Step>
@@ -68,6 +68,7 @@ Infisical supports the use of [API Tokens](https://www.zabbix.com/documentation/
--data '{
"name": "my-zabbix-connection",
"method": "api-token",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"credentials": {
"apiToken": "[API TOKEN]",
"instanceUrl": "https://zabbix.example.com"
@@ -82,6 +83,7 @@ Infisical supports the use of [API Tokens](https://www.zabbix.com/documentation/
"appConnection": {
"id": "e5d18aca-86f7-4026-a95e-efb8aeb0d8e6",
"name": "my-zabbix-connection",
+ "projectId": "7ffbb072-2575-495a-b5b0-127f88caef78",
"description": null,
"version": 1,
"orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
diff --git a/docs/integrations/platforms/kubernetes/infisical-secret-crd.mdx b/docs/integrations/platforms/kubernetes/infisical-secret-crd.mdx
index d72d589570..5368aeb3f8 100644
--- a/docs/integrations/platforms/kubernetes/infisical-secret-crd.mdx
+++ b/docs/integrations/platforms/kubernetes/infisical-secret-crd.mdx
@@ -146,6 +146,7 @@ spec:
projectSlug: <project-slug> # <-- project slug
projectId: <project-id> # <-- project id
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
envSlug: <env-slug> # "dev", "staging", "prod", etc..
secretsPath: "<secrets-path>" # Root is "/"
credentialsRef:
@@ -331,6 +332,7 @@ spec:
projectSlug: your-project-slug
envSlug: prod
secretsPath: "/path"
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
recursive: true
...
```
@@ -526,6 +528,7 @@ spec:
projectSlug: your-project-slug
envSlug: prod
secretsPath: "/path"
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
recursive: true
...
```
@@ -574,6 +577,7 @@ spec:
projectSlug: your-project-slug
envSlug: prod
secretsPath: "/path"
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
recursive: true
...
```
@@ -619,6 +623,7 @@ spec:
projectSlug: your-project-slug
envSlug: prod
secretsPath: "/path"
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
recursive: true
...
```
@@ -664,6 +669,7 @@ spec:
projectSlug: your-project-slug
envSlug: prod
secretsPath: "/path"
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
recursive: true
...
```
@@ -711,6 +717,7 @@ spec:
projectSlug: your-project-slug
envSlug: prod
secretsPath: "/path"
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
recursive: true
...
```
@@ -764,6 +771,7 @@ spec:
projectSlug: <project-slug> # <-- project slug
envSlug: <env-slug> # "dev", "staging", "prod", etc..
secretsPath: "<secrets-path>" # Root is "/"
+ secretName: <secret-name> # OPTIONAL: If you want to fetch a single Infisical secret, you can specify the secret name here. If not specified, all secrets in the specified scope will be fetched.
identityId: <machine-identity-id>
credentialsRef:
secretName: ldap-auth-credentials # <-- name of the Kubernetes secret that stores our machine identity credentials
diff --git a/docs/internals/permissions/organization-permissions.mdx b/docs/internals/permissions/organization-permissions.mdx
index 5f5fc962fe..993e270ed5 100644
--- a/docs/internals/permissions/organization-permissions.mdx
+++ b/docs/internals/permissions/organization-permissions.mdx
@@ -9,7 +9,7 @@ Infisical's organization permissions system follows a role-based access control
Each permission consists of:
-- **Subject**: The resource the permission applies to (e.g., workspaces, members, billing)
+- **Subject**: The resource the permission applies to (e.g., project, members, billing)
- **Action**: The operation that can be performed (e.g., read, create, edit, delete)
Some organization-level resources—specifically `app-connections`—support conditional permissions and permission inversion for more granular access control.
@@ -18,13 +18,13 @@ Some organization-level resources—specifically `app-connections`—support con
Below is a comprehensive list of all available organization-level subjects and their supported actions, organized by functional area.
-### Workspace Management
+### Project Management
-#### Subject: `workspace`
+#### Subject: `project` (formerly workspace)
-| Action | Description |
-| -------- | --------------------- |
-| `create` | Create new workspaces |
+| Action | Description |
+| -------- | ------------------ |
+| `create` | Create new project |
### Role Management
@@ -218,6 +218,15 @@ Supports conditions and permission inversion
| `delete-gateways` | Remove gateways from organization |
| `attach-gateways` | Attach gateways to resources |
+#### Subject: `relay`
+
+| Action | Description |
+| --------------- | ------------------------------- |
+| `list-relays` | View all organization relays |
+| `create-relays` | Add new relays to organization |
+| `edit-relays` | Modify existing relay settings |
+| `delete-relays` | Remove relays from organization |
+
#### Subject: `machine-identity-auth-template`
| Action | Description |
diff --git a/docs/internals/permissions/project-permissions.mdx b/docs/internals/permissions/project-permissions.mdx
index c823cf4a73..3a4dd11e6d 100644
--- a/docs/internals/permissions/project-permissions.mdx
+++ b/docs/internals/permissions/project-permissions.mdx
@@ -86,7 +86,7 @@ Below is a comprehensive list of all available project-level subjects and their
| `edit` | Modify existing tags |
| `delete` | Remove tags from the project |
-#### Subject: `workspace`
+#### Subject: `project`
| Action | Description |
| -------- | ------------------------- |
@@ -135,6 +135,18 @@ Below is a comprehensive list of all available project-level subjects and their
| `edit` | Modify token properties |
| `delete` | Revoke or remove service tokens |
+#### Subject: `app-connections`
+
+Supports conditions and permission inversion
+
+| Action | Description |
+| ------------------------- | ---------------------------------- |
+| `read-app-connections` | View app connection configurations |
+| `create-app-connections` | Create new app connections |
+| `edit-app-connections` | Modify existing app connections |
+| `delete-app-connections` | Remove app connections |
+| `connect-app-connections` | Use app connections |
+
### Secrets Management
#### Subject: `secrets`
diff --git a/docs/sdks/languages/node.mdx b/docs/sdks/languages/node.mdx
index e28e9c9f28..b56bf7400b 100644
--- a/docs/sdks/languages/node.mdx
+++ b/docs/sdks/languages/node.mdx
@@ -50,6 +50,7 @@ The SDK methods are organized into the following high-level categories:
4. `projects`: Creates and manages projects.
5. `environments`: Creates and manages environments.
6. `folders`: Creates and manages folders.
+7. `kms`: Manages KMS keys and encryption/signing operations.
### `auth`
@@ -456,7 +457,7 @@ const project = await client.projects().create({
projectDescription: "<project-description>", // Optional
slug: "<slug-of-project-to-create>", // Optional
template: "<project-template-name>", // Optional
- kmsKeyId: "kms-key-id" // Optional
+ kmsKeyId: "<kms-key-id>" // Optional
});
```
@@ -556,4 +557,223 @@ const folders = await client.folders().listFolders({
- `recursive` (boolean): An optional flag to list folders recursively. Defaults to `false`.
**Returns:**
-- `Folder[]`: An array of folders.
\ No newline at end of file
+- `Folder[]`: An array of folders.
+
+### `kms`
+
+The KMS (Key Management Service) module allows you to create and manage cryptographic keys for encryption and digital signing operations.
+
+#### Create a new KMS key
+
+Creating a new KMS key can be done by using the `.kms().keys().create({})` function. Keys can be created for either encryption/decryption or signing/verification operations.
+
+##### Example for creating an encryption key
+
+```typescript
+import { InfisicalSDK, KeyUsage, EncryptionAlgorithm } from "@infisical/sdk";
+const client = new InfisicalSDK();
+
+await client.auth().universalAuth.login({
+ clientId: "CLIENT_ID",
+ clientSecret: "CLIENT_SECRET"
+});
+
+const encryptionKey = await client.kms().keys().create({
+ projectId: "your-project-id",
+ name: "my-encryption-key",
+ description: "Key for encrypting sensitive data",
+ keyUsage: KeyUsage.ENCRYPTION,
+ encryptionAlgorithm: EncryptionAlgorithm.AES_256_GCM
+});
+
+console.log(encryptionKey);
+```
+
+##### Example for creating a signing key
+
+```typescript
+const signingKey = await client.kms().keys().create({
+ projectId: "your-project-id",
+ name: "my-signing-key",
+ description: "Key for signing documents",
+ keyUsage: KeyUsage.SIGNING,
+ encryptionAlgorithm: EncryptionAlgorithm.RSA_4096
+});
+
+console.log(signingKey);
+```
+
+**Parameters:**
+- `projectId` (string): The ID of your project.
+- `name` (string): The name of the KMS key.
+- `description` (string, optional): A description of the key's purpose.
+- `keyUsage` (KeyUsage): Either `KeyUsage.ENCRYPTION` for encrypt/decrypt operations or `KeyUsage.SIGNING` for sign/verify operations.
+- `encryptionAlgorithm` (EncryptionAlgorithm): The algorithm to use. Options include:
+ - For encryption: `AES_256_GCM`, `AES_128_GCM`, `RSA_4096`, `ECC_NIST_P256`
+ - For signing: `RSA_4096`, `ECC_NIST_P256`
+
+**Returns:**
+- `KmsKey`: The created KMS key object.
+
+#### Get a KMS key by name
+
+```typescript
+const key = await client.kms().keys().getByName({
+ projectId: "your-project-id",
+ name: "my-encryption-key"
+});
+
+console.log(key);
+```
+
+**Parameters:**
+- `projectId` (string): The ID of your project.
+- `name` (string): The name of the KMS key to retrieve.
+
+**Returns:**
+- `KmsKey`: The KMS key object.
+
+#### Delete a KMS key
+
+```typescript
+const deletedKey = await client.kms().keys().delete({
+ keyId: "<kms-key-id>"
+});
+
+console.log(deletedKey);
+```
+
+**Parameters:**
+- `keyId` (string): The ID of the KMS key to delete.
+
+**Returns:**
+- `KmsKey`: The deleted KMS key object.
+
+### `kms.encryption`
+
+The encryption module provides operations for encrypting and decrypting data using KMS keys created with `KeyUsage.ENCRYPTION`.
+
+#### Encrypt data
+
+```typescript
+const encrypted = await client.kms().encryption().encrypt({
+ keyId: "<kms-key-id>",
+ plaintext: "<base64-encoded-data>"
+});
+
+console.log(encrypted); // Returns the ciphertext string
+```
+
+**Parameters:**
+- `keyId` (string): The ID of the encryption key.
+- `plaintext` (string): The data to encrypt. This must be base64 encoded.
+
+**Returns:**
+- `string`: The encrypted ciphertext.
+
+#### Decrypt data
+
+```typescript
+const decrypted = await client.kms().encryption().decrypt({
+ keyId: "<kms-key-id>",
+ ciphertext: "<encrypted-data>"
+});
+
+console.log(decrypted); // Returns the original plaintext
+```
+
+**Parameters:**
+- `keyId` (string): The ID of the encryption key used to encrypt the data.
+- `ciphertext` (string): The encrypted data to decrypt.
+
+**Returns:**
+- `string`: The decrypted plaintext.
+
+### `kms.signing`
+
+The signing module provides operations for digitally signing data and verifying signatures using KMS keys created with `KeyUsage.SIGNING`.
+
+#### Sign data
+
+```typescript
+import { SigningAlgorithm } from "@infisical/sdk";
+
+const signature = await client.kms().signing().sign({
+ keyId: "<kms-key-id>",
+ data: "<base64-encoded-data>",
+ signingAlgorithm: SigningAlgorithm.RSASSA_PSS_SHA_256,
+ isDigest: false // Optional: set to true if data is already a hash digest
+});
+
+console.log(signature);
+```
+
+**Parameters:**
+- `keyId` (string): The ID of the signing key.
+- `data` (string): The data to sign.
+- `signingAlgorithm` (SigningAlgorithm): The signing algorithm to use. Available algorithms:
+ - **RSA PSS** (non-deterministic): `RSASSA_PSS_SHA_256`, `RSASSA_PSS_SHA_384`, `RSASSA_PSS_SHA_512`
+ - **RSA PKCS#1 v1.5** (deterministic): `RSASSA_PKCS1_V1_5_SHA_256`, `RSASSA_PKCS1_V1_5_SHA_384`, `RSASSA_PKCS1_V1_5_SHA_512`
+ - **ECDSA** (non-deterministic): `ECDSA_SHA_256`, `ECDSA_SHA_384`, `ECDSA_SHA_512`
+- `isDigest` (boolean, optional): Whether the data is already a hash digest. Defaults to `false`.
+
+**Returns:**
+- `KmsSignDataResponse`: Object containing the signature, keyId, and signingAlgorithm.
+
+#### Verify a signature
+
+```typescript
+const verification = await client.kms().signing().verify({
+ keyId: "<kms-key-id>",
+ data: "<base64-encoded-original-data>", // Must be base64 encoded
+ signature: "<data-signature>",
+ signingAlgorithm: SigningAlgorithm.RSASSA_PSS_SHA_256,
+ isDigest: false // Optional: set to true if data is already a hash digest
+});
+
+console.log(verification.signatureValid); // true or false
+```
+
+**Parameters:**
+- `keyId` (string): The ID of the signing key used to create the signature.
+- `data` (string): The original data that was signed (must be base64 encoded).
+- `signature` (string): The signature to verify.
+- `signingAlgorithm` (SigningAlgorithm): The same signing algorithm used to create the signature.
+- `isDigest` (boolean, optional): Whether the data is already a hash digest. Defaults to `false`.
+
+**Returns:**
+- `KmsVerifyDataResponse`: Object containing `signatureValid` (boolean), `keyId`, and `signingAlgorithm`.
+
+#### Get supported signing algorithms for a key
+
+```typescript
+const algorithms = await client.kms().signing().listSigningAlgorithms({
+ keyId: "<kms-key-id>"
+});
+
+console.log(algorithms); // Array of supported SigningAlgorithm values
+```
+
+**Parameters:**
+- `keyId` (string): The ID of the KMS signing key.
+
+**Returns:**
+- `SigningAlgorithm[]`: Array of supported signing algorithms for the key.
+
+#### Get public key
+
+Retrieve the public key for signature verification operations.
+
+```typescript
+const publicKey = await client.kms().signing().getPublicKey({
+ keyId: "<kms-key-id>"
+});
+
+console.log(publicKey); // Returns the public key string
+```
+
+**Parameters:**
+- `keyId` (string): The ID of the KMS signing key.
+
+**Returns:**
+- `string`: The public key in PEM format.
\ No newline at end of file
diff --git a/docs/self-hosting/guides/upgrading-infisical.mdx b/docs/self-hosting/guides/upgrading-infisical.mdx
index 60c6edbff7..cae8193bf1 100644
--- a/docs/self-hosting/guides/upgrading-infisical.mdx
+++ b/docs/self-hosting/guides/upgrading-infisical.mdx
@@ -54,4 +54,62 @@ Now, migrations run automatically during boot-up. This improvement streamlines t
- Once the migration is complete, all instances will operate with the updated schema.
5. **Verify the Upgrade:**
- - Review the logs for any migration errors or warnings.
+ - Review the logs for any migration errors or warnings.
+ - Test basic functionality to ensure the upgrade was successful.
+
+## Troubleshooting
+
+### UI Caching Issues After Upgrade
+
+After upgrading your Infisical instance, you may encounter UI-related issues such as:
+- Strange loading behavior
+- Components not rendering correctly
+- Unexpected errors in the browser console
+- Features appearing broken or unresponsive
+
+These issues are often caused by browser caching of the previous version's static assets.
+
+**Solution:**
+1. **Try a private/incognito browser window first** - This is the quickest way to test if the issue is cache-related.
+2. **Clear your browser cache** if the private window works correctly:
+ - **Chrome/Edge:** Press `Ctrl+Shift+Delete` (Windows/Linux) or `Cmd+Shift+Delete` (Mac)
+ - **Firefox:** Press `Ctrl+Shift+Delete` (Windows/Linux) or `Cmd+Shift+Delete` (Mac)
+ - **Safari:** Press `Cmd+Option+E` or go to Develop menu > Empty Caches
+3. **Hard refresh the page** by pressing `Ctrl+F5` (Windows/Linux) or `Cmd+Shift+R` (Mac)
+
+<Note>
+ Caching issues are temporary and typically resolve themselves as the cache expires, but manually clearing the cache provides immediate resolution.
+</Note>
+
+## Downgrade Considerations
+
+While we recommend staying up-to-date with the latest version, there may be scenarios where you need to downgrade your Infisical instance.
+
+<Warning>
+ **Database Compatibility:** Downgrading can be complex due to database schema changes. Always ensure you have proper backups before attempting any version changes.
+</Warning>
+
+### Safe Downgrade Process
+
+1. **Prepare Database Snapshot:**
+ - Create a database snapshot/backup **before** upgrading to the target version
+ - Ensure the snapshot is from a version compatible with your desired downgrade target
+
+2. **Stop Infisical Services:**
+ - Gracefully shut down all Infisical instances to prevent data corruption
+
+3. **Restore Database:**
+ - Restore your database from the pre-upgrade snapshot
+ - **Critical:** Do not attempt to downgrade with a database that has run migrations from a newer version
+
+4. **Deploy Previous Version:**
+ - Deploy the previous Infisical version
+ - Verify that the version matches the database schema in your snapshot
+
+5. **Verify Functionality:**
+ - Test critical functionality to ensure the downgrade was successful
+ - Monitor logs for any compatibility issues
+
+<Note>
+ The safest approach for downgrades is to restore to a known good state (both application and database) rather than attempting to reverse individual migrations.
+</Note>
diff --git a/frontend/src/components/app-connections/AppConnectionOption.tsx b/frontend/src/components/app-connections/AppConnectionOption.tsx
new file mode 100644
index 0000000000..2978dc9f07
--- /dev/null
+++ b/frontend/src/components/app-connections/AppConnectionOption.tsx
@@ -0,0 +1,45 @@
+import { components, OptionProps } from "react-select";
+import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
+import { faBuilding, faPlus } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+
+import { Badge, Tooltip } from "@app/components/v2";
+import { TAvailableAppConnection } from "@app/hooks/api/appConnections";
+
+export const AppConnectionOption = ({
+ isSelected,
+ children,
+ ...props
+}: OptionProps<TAvailableAppConnection>) => {
+ const isCreateOption = props.data.id === "_create";
+
+ return (
+ <components.Option isSelected={isSelected} {...props}>
+ <div className="flex flex-row items-center justify-between">
+ {isCreateOption ? (
+ <div className="flex items-center gap-x-1 text-mineshaft-400">
+ <FontAwesomeIcon icon={faPlus} size="sm" />
+ <span className="mr-auto">Create New Connection</span>
+ </div>
+ ) : (
+ <>
+ <p className="truncate">{children}</p>
+ {!props.data.projectId && (
+ <Tooltip content="This connection belongs to your organization.">
+ <div className="ml-2 mr-auto">
+ <Badge className="flex h-5 w-min items-center gap-1 whitespace-nowrap bg-mineshaft-400/50 text-bunker-300 hover:text-bunker-300">
+ <FontAwesomeIcon icon={faBuilding} size="sm" />
+ Organization
+ </Badge>
+ </div>
+ </Tooltip>
+ )}
+ {isSelected && (
+ <FontAwesomeIcon className="ml-2 text-primary" icon={faCheckCircle} size="sm" />
+ )}
+ </>
+ )}
+ </div>
+ </components.Option>
+ );
+};
diff --git a/frontend/src/components/app-connections/index.ts b/frontend/src/components/app-connections/index.ts
new file mode 100644
index 0000000000..7ced7c9079
--- /dev/null
+++ b/frontend/src/components/app-connections/index.ts
@@ -0,0 +1 @@
+export * from "./AppConnectionOption";
diff --git a/frontend/src/components/navigation/NavHeader.tsx b/frontend/src/components/navigation/NavHeader.tsx
index 1283c02d14..b16015680d 100644
--- a/frontend/src/components/navigation/NavHeader.tsx
+++ b/frontend/src/components/navigation/NavHeader.tsx
@@ -4,7 +4,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Link, useParams } from "@tanstack/react-router";
import { twMerge } from "tailwind-merge";
-import { useOrganization, useWorkspace } from "@app/context";
+import { useOrganization, useProject } from "@app/context";
import { useToggle } from "@app/hooks";
import { createNotification } from "../notifications";
@@ -51,7 +51,7 @@ export default function NavHeader({
isProtectedBranch = false,
protectionPolicyName
}: Props): JSX.Element {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { currentOrg } = useOrganization();
const [isCopied, { timedToggle: toggleIsCopied }] = useToggle(false);
@@ -79,7 +79,7 @@ export default function NavHeader({
<>
<FontAwesomeIcon icon={faAngleRight} className="ml-3 mr-3 text-xs text-gray-400" />
<div className="truncate text-sm font-semibold text-bunker-300">
- {currentWorkspace?.name}
+ {currentProject?.name}
</div>
</>
)}
@@ -93,7 +93,7 @@ export default function NavHeader({
{pageName === "Secrets" ? (
<Link
to="/projects/secret-management/$projectId/overview"
- params={{ projectId: currentWorkspace.id }}
+ params={{ projectId: currentProject.id }}
className="text-sm font-semibold text-primary/80 hover:text-primary"
>
{pageName}
@@ -129,7 +129,7 @@ export default function NavHeader({
<FontAwesomeIcon icon={faAngleRight} className="ml-3 mr-1.5 text-xs text-gray-400" />
<Link
to="/projects/secret-management/$projectId/secrets/$envSlug"
- params={{ projectId: currentWorkspace.id, envSlug: routerEnvSlug }}
+ params={{ projectId: currentProject.id, envSlug: routerEnvSlug }}
className="text-sm font-semibold text-primary/80 hover:text-primary"
>
{userAvailableEnvs?.find(({ slug }) => slug === currentEnv)?.name}
@@ -192,7 +192,7 @@ export default function NavHeader({
<Link
to="/projects/secret-management/$projectId/secrets/$envSlug"
params={{
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
envSlug: routerEnvSlug || ""
}}
search={(query) => ({ ...query, secretPath: newSecretPath })}
diff --git a/frontend/src/components/permissions/AccessTree/hooks/index.ts b/frontend/src/components/permissions/AccessTree/hooks/index.ts
index 717bdaf3a7..b02e6a9d66 100644
--- a/frontend/src/components/permissions/AccessTree/hooks/index.ts
+++ b/frontend/src/components/permissions/AccessTree/hooks/index.ts
@@ -3,7 +3,7 @@ import { useFormContext, useWatch } from "react-hook-form";
import { MongoAbility, MongoQuery } from "@casl/ability";
import { Edge, Node, useEdgesState, useNodesState } from "@xyflow/react";
-import { ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionSub, useProject } from "@app/context";
import { ProjectPermissionSet } from "@app/context/ProjectPermissionContext";
import { useListProjectEnvironmentsFolders } from "@app/hooks/api/secretFolders/queries";
import { TSecretFolderWithPath } from "@app/hooks/api/secretFolders/types";
@@ -36,15 +36,15 @@ export const useAccessTree = (
searchPath: string,
subject: ProjectPermissionSub
) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { secretName, setSecretName, setViewMode, viewMode } = useAccessTreeContext();
const { control } = useFormContext<AccessTreeForm>();
const metadata = useWatch({ control, name: "metadata" });
const [nodes, setNodes] = useNodesState<Node>([]);
const [edges, setEdges] = useEdgesState<Edge>([]);
- const [environment, setEnvironment] = useState(currentWorkspace.environments[0]?.slug ?? "");
+ const [environment, setEnvironment] = useState(currentProject.environments[0]?.slug ?? "");
const { data: environmentsFolders, isPending } = useListProjectEnvironmentsFolders(
- currentWorkspace.id
+ currentProject.id
);
const [levelFolderMap, setLevelFolderMap] = useState<LevelFolderMap>({});
@@ -279,7 +279,7 @@ export const useAccessTree = (
environment,
setEnvironment,
isLoading: isPending,
- environments: currentWorkspace.environments,
+ environments: currentProject.environments,
secretName,
setSecretName,
viewMode,
diff --git a/frontend/src/components/permissions/OrgPermissionCan.tsx b/frontend/src/components/permissions/OrgPermissionCan.tsx
index 8e0bf08adb..bdb39ba1b8 100644
--- a/frontend/src/components/permissions/OrgPermissionCan.tsx
+++ b/frontend/src/components/permissions/OrgPermissionCan.tsx
@@ -1,8 +1,10 @@
import { FunctionComponent, ReactNode } from "react";
-import { BoundCanProps, Can } from "@casl/react";
+import { AbilityTuple, MongoAbility } from "@casl/ability";
+import { Can } from "@casl/react";
import { TooltipProps } from "@app/components/v2/Tooltip/Tooltip";
-import { TOrgPermission, useOrgPermission } from "@app/context/OrgPermissionContext";
+import { useOrgPermission } from "@app/context/OrgPermissionContext";
+import { OrgPermissionSet } from "@app/context/OrgPermissionContext/types";
import { AccessRestrictedBanner, Tooltip } from "../v2";
@@ -14,7 +16,7 @@ export const OrgPermissionGuardBanner = () => {
);
};
-type Props = {
+type Props<T extends AbilityTuple> = {
label?: ReactNode;
// this prop is used when there exist already a tooltip as helper text for users
// so when permission is allowed same tooltip will be reused to show helpertext
@@ -22,9 +24,18 @@ type Props = {
allowedLabel?: string;
renderGuardBanner?: boolean;
tooltipProps?: Omit<TooltipProps, "children">;
-} & BoundCanProps<TOrgPermission>;
+ I: T[0];
+ ability?: MongoAbility<T>;
+ children: ReactNode | ((isAllowed: boolean, ability: T) => ReactNode);
+ passThrough?: boolean;
+} & (
+ | { an: T[1] }
+ | {
+ a: T[1];
+ }
+);
-export const OrgPermissionCan: FunctionComponent<Props> = ({
+export const OrgPermissionCan: FunctionComponent<Props<OrgPermissionSet>> = ({
label = "Access restricted",
children,
passThrough = true,
@@ -41,9 +52,7 @@ export const OrgPermissionCan: FunctionComponent<Props> = ({
{(isAllowed, ability) => {
// akhilmhdh: This is set as type due to error in casl react type.
const finalChild =
- typeof children === "function"
- ? children(isAllowed, ability as TOrgPermission)
- : children;
+ typeof children === "function" ? children(isAllowed, ability as any) : children;
if (!isAllowed && passThrough) {
return (
diff --git a/frontend/src/components/permissions/VariablePermissionCan.tsx b/frontend/src/components/permissions/VariablePermissionCan.tsx
new file mode 100644
index 0000000000..a9e24e3c77
--- /dev/null
+++ b/frontend/src/components/permissions/VariablePermissionCan.tsx
@@ -0,0 +1,17 @@
+import { OrgPermissionCan } from "./OrgPermissionCan";
+import { ProjectPermissionCan } from "./ProjectPermissionCan";
+
+interface PermissionCanProps {
+ type: "project" | "org";
+ I: any;
+ a: any;
+ children: (isAllowed: boolean, ability?: any) => React.ReactNode;
+}
+
+export const VariablePermissionCan = ({ type, children, ...props }: PermissionCanProps) => {
+ if (type === "project") {
+ return <ProjectPermissionCan {...props}>{children}</ProjectPermissionCan>;
+ }
+
+ return <OrgPermissionCan {...props}>{children}</OrgPermissionCan>;
+};
diff --git a/frontend/src/components/permissions/index.tsx b/frontend/src/components/permissions/index.tsx
index c40079a4fa..db6ca32968 100644
--- a/frontend/src/components/permissions/index.tsx
+++ b/frontend/src/components/permissions/index.tsx
@@ -3,3 +3,4 @@ export { GlobPermissionInfo } from "./GlobPermissionInfo";
export { OrgPermissionCan } from "./OrgPermissionCan";
export { PermissionDeniedBanner } from "./PermissionDeniedBanner";
export { ProjectPermissionCan } from "./ProjectPermissionCan";
+export * from "./VariablePermissionCan";
diff --git a/frontend/src/components/project/ProjectOverviewChangeSection.tsx b/frontend/src/components/project/ProjectOverviewChangeSection.tsx
index 0f88ec2e91..852253bb36 100644
--- a/frontend/src/components/project/ProjectOverviewChangeSection.tsx
+++ b/frontend/src/components/project/ProjectOverviewChangeSection.tsx
@@ -6,7 +6,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, FormControl, Input, TextArea } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useUpdateProject } from "@app/hooks/api";
const baseFormSchema = z.object({
@@ -37,35 +37,35 @@ type Props = {
};
export const ProjectOverviewChangeSection = ({ showSlugField = false }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync, isPending } = useUpdateProject();
const { handleSubmit, control, reset, watch } = useForm<BaseFormData | FormDataWithSlug>({
resolver: zodResolver(showSlugField ? formSchemaWithSlug : baseFormSchema)
});
- const currentSlug = showSlugField ? watch("slug") : currentWorkspace?.slug;
+ const currentSlug = showSlugField ? watch("slug") : currentProject?.slug;
useEffect(() => {
- if (currentWorkspace) {
+ if (currentProject) {
reset({
- name: currentWorkspace.name,
- description: currentWorkspace.description ?? "",
- ...(showSlugField && { slug: currentWorkspace.slug })
+ name: currentProject.name,
+ description: currentProject.description ?? "",
+ ...(showSlugField && { slug: currentProject.slug })
});
}
- }, [currentWorkspace, showSlugField]);
+ }, [currentProject, showSlugField]);
const onFormSubmit = async (data: BaseFormData | FormDataWithSlug) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await mutateAsync({
- projectID: currentWorkspace.id,
+ projectId: currentProject.id,
newProjectName: data.name,
newProjectDescription: data.description,
...(showSlugField &&
"slug" in data && {
- newSlug: data.slug !== currentWorkspace.slug ? data.slug : undefined
+ newSlug: data.slug !== currentProject.slug ? data.slug : undefined
})
});
@@ -105,7 +105,7 @@ export const ProjectOverviewChangeSection = ({ showSlugField = false }: Props) =
variant="outline_bg"
size="sm"
onClick={() => {
- navigator.clipboard.writeText(currentWorkspace?.id || "");
+ navigator.clipboard.writeText(currentProject?.id || "");
createNotification({
text: "Copied project ID to clipboard",
type: "success"
diff --git a/frontend/src/components/projects/NewProjectModal.tsx b/frontend/src/components/projects/NewProjectModal.tsx
index 1bbe9f6f1c..dcb11d8736 100644
--- a/frontend/src/components/projects/NewProjectModal.tsx
+++ b/frontend/src/components/projects/NewProjectModal.tsx
@@ -34,10 +34,10 @@ import {
useUser
} from "@app/context";
import { getProjectHomePage, getProjectLottieIcon } from "@app/helpers/project";
-import { useCreateWorkspace, useGetExternalKmsList, useGetUserWorkspaces } from "@app/hooks/api";
+import { useCreateWorkspace, useGetExternalKmsList, useGetUserProjects } from "@app/hooks/api";
import { INTERNAL_KMS_KEY_ID } from "@app/hooks/api/kms/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { InfisicalProjectTemplate, useListProjectTemplates } from "@app/hooks/api/projectTemplates";
-import { ProjectType } from "@app/hooks/api/workspace/types";
const formSchema = z.object({
name: z.string().trim().min(1, "Required").max(64, "Too long, maximum length is 64 characters"),
@@ -89,7 +89,7 @@ const NewProjectForm = ({ onOpenChange }: NewProjectFormProps) => {
const { permission } = useOrgPermission();
const { user } = useUser();
const createWs = useCreateWorkspace();
- const { refetch: refetchWorkspaces } = useGetUserWorkspaces();
+ const { refetch: refetchWorkspaces } = useGetUserProjects();
const { subscription } = useSubscription();
const canReadProjectTemplates = permission.can(
diff --git a/frontend/src/components/projects/RequestProjectAccessModal.tsx b/frontend/src/components/projects/RequestProjectAccessModal.tsx
new file mode 100644
index 0000000000..6d31bf8e62
--- /dev/null
+++ b/frontend/src/components/projects/RequestProjectAccessModal.tsx
@@ -0,0 +1,88 @@
+import { useForm } from "react-hook-form";
+
+import { createNotification } from "@app/components/notifications";
+import { Button, FormControl, Input, Modal, ModalClose, ModalContent } from "@app/components/v2";
+import { useRequestProjectAccess } from "@app/hooks/api";
+import { Project } from "@app/hooks/api/projects/types";
+
+type ContentProps = {
+ projectId: string;
+ onComplete: () => void;
+};
+
+const Content = ({ projectId, onComplete }: ContentProps) => {
+ const form = useForm<{ note: string }>();
+
+ const requestProjectAccess = useRequestProjectAccess();
+
+ const onFormSubmit = ({ note }: { note: string }) => {
+ if (requestProjectAccess.isPending) return;
+ requestProjectAccess.mutate(
+ {
+ comment: note,
+ projectId
+ },
+ {
+ onSuccess: () => {
+ createNotification({
+ type: "success",
+ title: "Project Access Request Sent",
+ text: "Project admins will receive an email of your request"
+ });
+ onComplete();
+ }
+ }
+ );
+ };
+
+ return (
+ <form onSubmit={form.handleSubmit(onFormSubmit)}>
+ <FormControl label="Note">
+ <Input {...form.register("note")} />
+ </FormControl>
+ <div className="mt-4 flex items-center">
+ <Button className="mr-4" size="sm" type="submit" isLoading={form.formState.isSubmitting}>
+ Submit Request
+ </Button>
+ <ModalClose asChild>
+ <Button colorSchema="secondary" variant="plain">
+ Cancel
+ </Button>
+ </ModalClose>
+ </div>
+ </form>
+ );
+};
+
+type RequestProjectAccessModalProps = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ project?: Project;
+ onComplete?: () => void;
+};
+
+export const RequestProjectAccessModal = ({
+ isOpen,
+ onOpenChange,
+ project,
+ onComplete
+}: RequestProjectAccessModalProps) => {
+ if (!project) return null;
+
+ return (
+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>
+ <ModalContent
+ title="Confirm Access Request"
+ subTitle={`Requesting access to project ${project?.name}. You may include an optional note for project admins to review your request.`}
+ >
+ <Content
+ onComplete={() => {
+ onOpenChange(false);
+ if (onComplete) onComplete();
+ }}
+ projectId={project?.id}
+ />
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/frontend/src/components/projects/index.tsx b/frontend/src/components/projects/index.tsx
index 1fb78225d7..a2dc754ad9 100644
--- a/frontend/src/components/projects/index.tsx
+++ b/frontend/src/components/projects/index.tsx
@@ -1 +1,2 @@
export { NewProjectModal } from "./NewProjectModal";
+export * from "./RequestProjectAccessModal";
diff --git a/frontend/src/components/secret-rotations-v2/CreateSecretRotationV2Modal.tsx b/frontend/src/components/secret-rotations-v2/CreateSecretRotationV2Modal.tsx
index f5b9a39b39..41f378b949 100644
--- a/frontend/src/components/secret-rotations-v2/CreateSecretRotationV2Modal.tsx
+++ b/frontend/src/components/secret-rotations-v2/CreateSecretRotationV2Modal.tsx
@@ -1,18 +1,20 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useNavigate, useRouterState } from "@tanstack/react-router";
import { SecretRotationV2Form } from "@app/components/secret-rotations-v2/forms";
+import { TSecretRotationV2Form } from "@app/components/secret-rotations-v2/forms/schemas";
import { SecretRotationV2ModalHeader } from "@app/components/secret-rotations-v2/SecretRotationV2ModalHeader";
import { SecretRotationV2Select } from "@app/components/secret-rotations-v2/SecretRotationV2Select";
import { Modal, ModalContent } from "@app/components/v2";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import { SecretRotation, TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
type SharedProps = {
secretPath: string;
environment?: string;
- environments?: WorkspaceEnv[];
+ environments?: ProjectEnv[];
};
type Props = {
@@ -24,14 +26,23 @@ type ContentProps = {
onComplete: (secretRotation: TSecretRotationV2) => void;
selectedRotation: SecretRotation | null;
setSelectedRotation: (selectedRotation: SecretRotation | null) => void;
+ initialFormData?: Partial<TSecretRotationV2Form>;
+ onCancel: () => void;
} & SharedProps;
-const Content = ({ setSelectedRotation, selectedRotation, ...props }: ContentProps) => {
+const Content = ({
+ setSelectedRotation,
+ selectedRotation,
+ initialFormData,
+ onCancel,
+ ...props
+}: ContentProps) => {
if (selectedRotation) {
return (
<SecretRotationV2Form
- onCancel={() => setSelectedRotation(null)}
+ onCancel={onCancel}
type={selectedRotation}
+ initialFormData={initialFormData}
{...props}
/>
);
@@ -42,12 +53,60 @@ const Content = ({ setSelectedRotation, selectedRotation, ...props }: ContentPro
export const CreateSecretRotationV2Modal = ({ onOpenChange, isOpen, ...props }: Props) => {
const [selectedRotation, setSelectedRotation] = useState<SecretRotation | null>(null);
+ const [initialFormData, setInitialFormData] = useState<Partial<TSecretRotationV2Form>>();
+
+ const {
+ location: {
+ search: { connectionId, connectionName, ...search },
+ pathname
+ }
+ } = useRouterState();
+
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ if (connectionId && connectionName) {
+ const storedFormData = localStorage.getItem("secretRotationFormData");
+
+ if (!storedFormData) return;
+
+ let form: Partial<TSecretRotationV2Form> = {};
+ try {
+ form = JSON.parse(storedFormData) as TSecretRotationV2Form;
+ } catch {
+ return;
+ } finally {
+ localStorage.removeItem("secretRotationFormData");
+ }
+
+ onOpenChange(true);
+
+ setSelectedRotation(form.type ?? null);
+
+ setInitialFormData({
+ ...form,
+ connection: { id: connectionId, name: connectionName }
+ });
+
+ navigate({
+ to: pathname,
+ search
+ });
+ }
+ }, [connectionId, connectionName]);
+
+ const handleReset = () => {
+ setSelectedRotation(null);
+ setInitialFormData(undefined);
+ };
return (
<Modal
isOpen={isOpen}
onOpenChange={(open) => {
- if (!open) setSelectedRotation(null);
+ if (!open) {
+ handleReset();
+ }
onOpenChange(open);
}}
>
@@ -84,9 +143,11 @@ export const CreateSecretRotationV2Modal = ({ onOpenChange, isOpen, ...props }:
>
<Content
onComplete={() => {
- setSelectedRotation(null);
+ handleReset();
onOpenChange(false);
}}
+ onCancel={handleReset}
+ initialFormData={initialFormData}
selectedRotation={selectedRotation}
setSelectedRotation={setSelectedRotation}
{...props}
diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConfigurationFields.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConfigurationFields.tsx
index 1906b743d6..e518752c40 100644
--- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConfigurationFields.tsx
+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConfigurationFields.tsx
@@ -9,14 +9,14 @@ import {
IS_ROTATION_DUAL_CREDENTIALS,
SECRET_ROTATION_MAP
} from "@app/helpers/secretRotationsV2";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import { TSecretRotationV2Form } from "./schemas";
import { SecretRotationV2ConnectionField } from "./SecretRotationV2ConnectionField";
type Props = {
isUpdate: boolean;
- environments?: WorkspaceEnv[];
+ environments?: ProjectEnv[];
};
export const SecretRotationV2ConfigurationFields = ({ isUpdate, environments }: Props) => {
diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx
index 665ab05a63..c2064071f6 100644
--- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx
+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2ConnectionField.tsx
@@ -1,14 +1,17 @@
import { Controller, useFormContext } from "react-hook-form";
+import { SingleValue } from "react-select";
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { Link } from "@tanstack/react-router";
+import { AppConnectionOption } from "@app/components/app-connections";
import { FilterableSelect, FormControl } from "@app/components/v2";
-import { OrgPermissionSubjects, useOrgPermission } from "@app/context";
-import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";
+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
import { SECRET_ROTATION_CONNECTION_MAP } from "@app/helpers/secretRotationsV2";
+import { usePopUp } from "@app/hooks";
import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
+import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
import { TSecretRotationV2Form } from "./schemas";
@@ -18,19 +21,26 @@ type Props = {
};
export const SecretRotationV2ConnectionField = ({ onChange: callback, isUpdate }: Props) => {
- const { permission } = useOrgPermission();
- const { control, watch } = useFormContext<TSecretRotationV2Form>();
+ const { permission } = useProjectPermission();
+ const { control, watch, setValue } = useFormContext<TSecretRotationV2Form>();
+
+ const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
const rotationType = watch("type");
const app = SECRET_ROTATION_CONNECTION_MAP[rotationType];
- const { data: availableConnections, isPending } = useListAvailableAppConnections(app);
+ const { currentProject } = useProject();
+
+ const { data: availableConnections, isPending } = useListAvailableAppConnections(
+ app,
+ currentProject.id
+ );
const connectionName = APP_CONNECTION_MAP[app].name;
const canCreateConnection = permission.can(
- OrgPermissionAppConnectionActions.Create,
- OrgPermissionSubjects.AppConnections
+ ProjectPermissionAppConnectionActions.Create,
+ ProjectPermissionSub.AppConnections
);
const appName = APP_CONNECTION_MAP[app].name;
@@ -66,37 +76,56 @@ export const SecretRotationV2ConnectionField = ({ onChange: callback, isUpdate }
<FilterableSelect
value={value}
onChange={(newValue) => {
+ if ((newValue as SingleValue<{ id: string; name: string }>)?.id === "_create") {
+ handlePopUpOpen("addConnection");
+ onChange(null);
+ // store for oauth callback connections
+ localStorage.setItem("secretRotationFormData", JSON.stringify(watch()));
+ if (callback) callback();
+ return;
+ }
+
onChange(newValue);
if (callback) callback();
}}
isLoading={isPending}
- options={availableConnections}
+ options={[
+ ...(canCreateConnection ? [{ id: "_create", name: "Create Connection" }] : []),
+ ...(availableConnections ?? [])
+ ]}
isDisabled={isUpdate}
placeholder="Select connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
+ components={{ Option: AppConnectionOption }}
/>
</FormControl>
)}
control={control}
name="connection"
/>
- {!isUpdate && availableConnections?.length === 0 && (
+ {!isUpdate && !isPending && !availableConnections?.length && !canCreateConnection && (
<p className="-mt-2.5 mb-2.5 text-xs text-yellow">
<FontAwesomeIcon className="mr-1" size="xs" icon={faInfoCircle} />
- {canCreateConnection ? (
- <>
- You do not have access to any {appName} Connections. Create one from the{" "}
- <Link to="/organization/app-connections" className="underline">
- App Connections
- </Link>{" "}
- page.
- </>
- ) : (
- `You do not have access to any ${appName} Connections. Contact an admin to create one.`
- )}
+ You do not have access to any {appName} Connections. Contact an admin to create one.
</p>
)}
+ <AddAppConnectionModal
+ isOpen={popUp.addConnection.isOpen}
+ onOpenChange={(isOpen) => {
+ // remove form storage, not oauth connection
+ localStorage.removeItem("secretRotationFormData");
+ handlePopUpToggle("addConnection", isOpen);
+ }}
+ projectType={currentProject.type}
+ projectId={currentProject.id}
+ app={app}
+ onComplete={(connection) => {
+ if (connection) {
+ setValue("connection", connection);
+ }
+ }}
+ />
</>
);
};
diff --git a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx
index d931d9d3c1..87869e9255 100644
--- a/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx
+++ b/frontend/src/components/secret-rotations-v2/forms/SecretRotationV2Form.tsx
@@ -11,8 +11,9 @@ import { SecretRotationV2ParametersFields } from "@app/components/secret-rotatio
import { SecretRotationV2ReviewFields } from "@app/components/secret-rotations-v2/forms/SecretRotationV2ReviewFields";
import { SecretRotationV2SecretsMappingFields } from "@app/components/secret-rotations-v2/forms/SecretRotationV2SecretsMappingFields";
import { Button } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { IS_ROTATION_DUAL_CREDENTIALS, SECRET_ROTATION_MAP } from "@app/helpers/secretRotationsV2";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import {
SecretRotation,
TSecretRotationV2,
@@ -22,7 +23,6 @@ import {
useCreateSecretRotationV2,
useUpdateSecretRotationV2
} from "@app/hooks/api/secretRotationsV2/mutations";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
import { SecretRotationV2FormSchema, TSecretRotationV2Form } from "./schemas";
@@ -32,8 +32,9 @@ type Props = {
onCancel: () => void;
secretPath: string;
environment?: string;
- environments?: WorkspaceEnv[];
+ environments?: ProjectEnv[];
secretRotation?: TSecretRotationV2;
+ initialFormData?: Partial<TSecretRotationV2Form>;
};
const FORM_TABS: { name: string; key: string; fields: (keyof TSecretRotationV2Form)[] }[] = [
@@ -64,11 +65,12 @@ export const SecretRotationV2Form = ({
environment: envSlug,
secretPath,
secretRotation,
- environments
+ environments,
+ initialFormData
}: Props) => {
const createSecretRotation = useCreateSecretRotationV2();
const updateSecretRotation = useUpdateSecretRotationV2();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { name: rotationType } = SECRET_ROTATION_MAP[type];
const [selectedTabIndex, setSelectedTabIndex] = useState(0);
@@ -80,7 +82,7 @@ export const SecretRotationV2Form = ({
defaultValues: secretRotation
? {
...secretRotation,
- environment: currentWorkspace?.environments.find((env) => env.slug === envSlug),
+ environment: currentProject?.environments.find((env) => env.slug === envSlug),
secretPath
}
: {
@@ -91,9 +93,10 @@ export const SecretRotationV2Form = ({
hours: 0,
minutes: 0
},
- environment: currentWorkspace?.environments.find((env) => env.slug === envSlug),
+ environment: currentProject?.environments.find((env) => env.slug === envSlug),
secretPath,
- ...(rotationOption!.template as object) // can't infer type since we don't know which specific type it is
+ ...((rotationOption?.template as object) ?? {}), // can't infer type since we don't know which specific type it is
+ ...(initialFormData as object)
},
reValidateMode: "onChange"
});
@@ -115,7 +118,7 @@ export const SecretRotationV2Form = ({
connectionId: connection.id,
environment: environment.slug,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
});
try {
const rotation = await mutation;
diff --git a/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx b/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx
index c95baaae57..fb1081d020 100644
--- a/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx
+++ b/frontend/src/components/secret-scanning/CreateSecretScanningDataSourceModal.tsx
@@ -1,7 +1,9 @@
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useNavigate, useRouterState } from "@tanstack/react-router";
+import { TSecretScanningDataSourceForm } from "@app/components/secret-scanning/forms/schemas";
import { Modal, ModalContent } from "@app/components/v2";
import {
SecretScanningDataSource,
@@ -21,16 +23,19 @@ type ContentProps = {
onComplete: (dataSource: TSecretScanningDataSource) => void;
selectedDataSource: SecretScanningDataSource | null;
setSelectedDataSource: (selectedDataSource: SecretScanningDataSource | null) => void;
+ initialFormData?: Partial<TSecretScanningDataSourceForm>;
+ onCancel: () => void;
};
-const Content = ({ setSelectedDataSource, selectedDataSource, ...props }: ContentProps) => {
+const Content = ({
+ setSelectedDataSource,
+ selectedDataSource,
+ onCancel,
+ ...props
+}: ContentProps) => {
if (selectedDataSource) {
return (
- <SecretScanningDataSourceForm
- onCancel={() => setSelectedDataSource(null)}
- type={selectedDataSource}
- {...props}
- />
+ <SecretScanningDataSourceForm onCancel={onCancel} type={selectedDataSource} {...props} />
);
}
@@ -41,12 +46,60 @@ export const CreateSecretScanningDataSourceModal = ({ onOpenChange, isOpen, ...p
const [selectedDataSource, setSelectedDataSource] = useState<SecretScanningDataSource | null>(
null
);
+ const [initialFormData, setInitialFormData] = useState<Partial<TSecretScanningDataSourceForm>>();
+
+ const {
+ location: {
+ search: { connectionId, connectionName, ...search },
+ pathname
+ }
+ } = useRouterState();
+
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ if (connectionId && connectionName) {
+ const storedFormData = localStorage.getItem("secretScanningDataSourceFormData");
+
+ if (!storedFormData) return;
+
+ let form: Partial<TSecretScanningDataSourceForm> = {};
+ try {
+ form = JSON.parse(storedFormData) as TSecretScanningDataSourceForm;
+ } catch {
+ return;
+ } finally {
+ localStorage.removeItem("secretScanningDataSourceFormData");
+ }
+
+ onOpenChange(true);
+
+ setSelectedDataSource(form.type ?? null);
+
+ setInitialFormData({
+ ...form,
+ connection: { id: connectionId, name: connectionName }
+ });
+
+ navigate({
+ to: pathname,
+ search
+ });
+ }
+ }, [connectionId, connectionName]);
+
+ const resetModal = () => {
+ setSelectedDataSource(null);
+ setInitialFormData(undefined);
+ };
return (
<Modal
isOpen={isOpen}
onOpenChange={(open) => {
- if (!open) setSelectedDataSource(null);
+ if (!open) {
+ resetModal();
+ }
onOpenChange(open);
}}
>
@@ -83,11 +136,13 @@ export const CreateSecretScanningDataSourceModal = ({ onOpenChange, isOpen, ...p
>
<Content
onComplete={() => {
- setSelectedDataSource(null);
+ resetModal();
onOpenChange(false);
}}
+ onCancel={resetModal}
selectedDataSource={selectedDataSource}
setSelectedDataSource={setSelectedDataSource}
+ initialFormData={initialFormData}
{...props}
/>
</ModalContent>
diff --git a/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceConnectionField.tsx b/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceConnectionField.tsx
index 3f995e1d0e..2e9e4a2a5b 100644
--- a/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceConnectionField.tsx
+++ b/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceConnectionField.tsx
@@ -1,14 +1,17 @@
import { Controller, useFormContext } from "react-hook-form";
+import { SingleValue } from "react-select";
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { Link } from "@tanstack/react-router";
+import { AppConnectionOption } from "@app/components/app-connections";
import { FilterableSelect, FormControl } from "@app/components/v2";
-import { OrgPermissionSubjects, useOrgPermission } from "@app/context";
-import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";
+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
import { SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP } from "@app/helpers/secretScanningV2";
+import { usePopUp } from "@app/hooks";
import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
+import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
import { TSecretScanningDataSourceForm } from "./schemas";
@@ -21,19 +24,26 @@ export const SecretScanningDataSourceConnectionField = ({
onChange: callback,
isUpdate
}: Props) => {
- const { permission } = useOrgPermission();
- const { control, watch } = useFormContext<TSecretScanningDataSourceForm>();
+ const { permission } = useProjectPermission();
+ const { control, watch, setValue } = useFormContext<TSecretScanningDataSourceForm>();
+
+ const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
const dataSourceType = watch("type");
const app = SECRET_SCANNING_DATA_SOURCE_CONNECTION_MAP[dataSourceType];
- const { data: availableConnections, isPending } = useListAvailableAppConnections(app);
+ const { currentProject } = useProject();
+
+ const { data: availableConnections, isPending } = useListAvailableAppConnections(
+ app,
+ currentProject.id
+ );
const connectionName = APP_CONNECTION_MAP[app].name;
const canCreateConnection = permission.can(
- OrgPermissionAppConnectionActions.Create,
- OrgPermissionSubjects.AppConnections
+ ProjectPermissionAppConnectionActions.Create,
+ ProjectPermissionSub.AppConnections
);
return (
@@ -67,37 +77,57 @@ export const SecretScanningDataSourceConnectionField = ({
<FilterableSelect
value={value}
onChange={(newValue) => {
+ if ((newValue as SingleValue<{ id: string; name: string }>)?.id === "_create") {
+ handlePopUpOpen("addConnection");
+ onChange(null);
+ // store for oauth callback connections
+ localStorage.setItem("secretScanningDataSourceFormData", JSON.stringify(watch()));
+ if (callback) callback();
+ return;
+ }
+
onChange(newValue);
if (callback) callback();
}}
isLoading={isPending}
- options={availableConnections}
+ options={[
+ ...(canCreateConnection ? [{ id: "_create", name: "Create Connection" }] : []),
+ ...(availableConnections ?? [])
+ ]}
isDisabled={isUpdate}
placeholder="Select connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
+ components={{ Option: AppConnectionOption }}
/>
</FormControl>
)}
control={control}
name="connection"
/>
- {!isUpdate && availableConnections?.length === 0 && (
+ {!isUpdate && !isPending && !availableConnections?.length && !canCreateConnection && (
<p className="-mt-2.5 mb-2.5 text-xs text-yellow">
<FontAwesomeIcon className="mr-1" size="xs" icon={faInfoCircle} />
- {canCreateConnection ? (
- <>
- You do not have access to any {connectionName} Connections. Create one from the{" "}
- <Link to="/organization/app-connections" className="underline">
- App Connections
- </Link>{" "}
- page.
- </>
- ) : (
- `You do not have access to any ${connectionName} Connections. Contact an admin to create one.`
- )}
+ You do not have access to any {connectionName} Connections. Contact an admin to create
+ one.
</p>
)}
+ <AddAppConnectionModal
+ isOpen={popUp.addConnection.isOpen}
+ onOpenChange={(isOpen) => {
+ // remove form storage, not oauth connection
+ localStorage.removeItem("secretScanningDataSourceFormData");
+ handlePopUpToggle("addConnection", isOpen);
+ }}
+ projectType={currentProject.type}
+ projectId={currentProject.id}
+ app={app}
+ onComplete={(connection) => {
+ if (connection) {
+ setValue("connection", connection);
+ }
+ }}
+ />
</>
);
};
diff --git a/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx b/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx
index b1ea0b5597..515a674369 100644
--- a/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx
+++ b/frontend/src/components/secret-scanning/forms/SecretScanningDataSourceForm.tsx
@@ -6,7 +6,7 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { Button } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { SECRET_SCANNING_DATA_SOURCE_MAP } from "@app/helpers/secretScanningV2";
import {
SecretScanningDataSource,
@@ -27,6 +27,7 @@ type Props = {
type: SecretScanningDataSource;
onCancel: () => void;
dataSource?: TSecretScanningDataSource;
+ initialFormData?: Partial<TSecretScanningDataSourceForm>;
};
const FORM_TABS: { name: string; key: string; fields: (keyof TSecretScanningDataSourceForm)[] }[] =
@@ -36,10 +37,16 @@ const FORM_TABS: { name: string; key: string; fields: (keyof TSecretScanningData
{ name: "Review", key: "review", fields: [] }
];
-export const SecretScanningDataSourceForm = ({ type, onComplete, onCancel, dataSource }: Props) => {
+export const SecretScanningDataSourceForm = ({
+ type,
+ onComplete,
+ onCancel,
+ dataSource,
+ initialFormData
+}: Props) => {
const createDataSource = useCreateSecretScanningDataSource();
const updateDataSource = useUpdateSecretScanningDataSource();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { name: sourceType } = SECRET_SCANNING_DATA_SOURCE_MAP[type];
const [selectedTabIndex, setSelectedTabIndex] = useState(0);
@@ -48,7 +55,8 @@ export const SecretScanningDataSourceForm = ({ type, onComplete, onCancel, dataS
resolver: zodResolver(SecretScanningDataSourceSchema),
defaultValues: dataSource ?? {
type,
- isAutoScanEnabled: true // scott: this may need to be derived from type in the future
+ isAutoScanEnabled: true, // scott: this may need to be derived from type in the future
+ ...(initialFormData as object)
},
reValidateMode: "onChange"
});
@@ -63,7 +71,7 @@ export const SecretScanningDataSourceForm = ({ type, onComplete, onCancel, dataS
: createDataSource.mutateAsync({
...formData,
connectionId: connection?.id,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
});
try {
const source = await mutation;
diff --git a/frontend/src/components/secret-syncs/CreateSecretSyncModal.tsx b/frontend/src/components/secret-syncs/CreateSecretSyncModal.tsx
index 5ff72e810f..e504389c05 100644
--- a/frontend/src/components/secret-syncs/CreateSecretSyncModal.tsx
+++ b/frontend/src/components/secret-syncs/CreateSecretSyncModal.tsx
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
+import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas";
import { Modal, ModalContent } from "@app/components/v2";
import { SecretSync, TSecretSync } from "@app/hooks/api/secretSyncs";
@@ -11,18 +12,21 @@ type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
selectSync?: SecretSync | null;
+ initialFormData?: Partial<TSecretSyncForm>;
};
type ContentProps = {
onComplete: (secretSync: TSecretSync) => void;
selectedSync: SecretSync | null;
setSelectedSync: (selectedSync: SecretSync | null) => void;
+ initialFormData?: Partial<TSecretSyncForm>;
};
-const Content = ({ onComplete, setSelectedSync, selectedSync }: ContentProps) => {
+const Content = ({ onComplete, setSelectedSync, selectedSync, initialFormData }: ContentProps) => {
if (selectedSync) {
return (
<CreateSecretSyncForm
+ initialFormData={initialFormData}
onComplete={onComplete}
onCancel={() => setSelectedSync(null)}
destination={selectedSync}
@@ -33,7 +37,12 @@ const Content = ({ onComplete, setSelectedSync, selectedSync }: ContentProps) =>
return <SecretSyncSelect onSelect={setSelectedSync} />;
};
-export const CreateSecretSyncModal = ({ onOpenChange, selectSync = null, ...props }: Props) => {
+export const CreateSecretSyncModal = ({
+ onOpenChange,
+ selectSync = null,
+ initialFormData,
+ ...props
+}: Props) => {
const [selectedSync, setSelectedSync] = useState<SecretSync | null>(selectSync);
useEffect(() => {
@@ -67,6 +76,7 @@ export const CreateSecretSyncModal = ({ onOpenChange, selectSync = null, ...prop
}}
selectedSync={selectedSync}
setSelectedSync={setSelectedSync}
+ initialFormData={initialFormData}
/>
</ModalContent>
</Modal>
diff --git a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx
index 8a1be69c49..4135a9926f 100644
--- a/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx
+++ b/frontend/src/components/secret-syncs/forms/CreateSecretSyncForm.tsx
@@ -8,7 +8,7 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Switch } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs";
import {
SecretSync,
@@ -29,6 +29,7 @@ type Props = {
onComplete: (secretSync: TSecretSync) => void;
destination: SecretSync;
onCancel: () => void;
+ initialFormData?: Partial<TSecretSyncForm>;
};
const FORM_TABS: { name: string; key: string; fields: (keyof TSecretSyncForm)[] }[] = [
@@ -39,14 +40,20 @@ const FORM_TABS: { name: string; key: string; fields: (keyof TSecretSyncForm)[]
{ name: "Review", key: "review", fields: [] }
];
-export const CreateSecretSyncForm = ({ destination, onComplete, onCancel }: Props) => {
+export const CreateSecretSyncForm = ({
+ destination,
+ onComplete,
+ onCancel,
+ initialFormData
+}: Props) => {
const createSecretSync = useCreateSecretSync();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { name: destinationName } = SECRET_SYNC_MAP[destination];
const [showConfirmation, setShowConfirmation] = useState(false);
- const [selectedTabIndex, setSelectedTabIndex] = useState(0);
+ // scoot: right now we only do this when creating a connection so we know index 1
+ const [selectedTabIndex, setSelectedTabIndex] = useState(initialFormData ? 1 : 0);
const { syncOption } = useSecretSyncOption(destination);
@@ -59,7 +66,8 @@ export const CreateSecretSyncForm = ({ destination, onComplete, onCancel }: Prop
initialSyncBehavior: syncOption?.canImportSecrets
? undefined
: SecretSyncInitialSyncBehavior.OverwriteDestination
- }
+ },
+ ...initialFormData
} as Partial<TSecretSyncForm>,
reValidateMode: "onChange"
});
@@ -70,7 +78,7 @@ export const CreateSecretSyncForm = ({ destination, onComplete, onCancel }: Prop
...formData,
connectionId: connection.id,
environment: environment.slug,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
});
createNotification({
diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsx
index 94e5877091..62542a5702 100644
--- a/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsx
+++ b/frontend/src/components/secret-syncs/forms/SecretSyncConnectionField.tsx
@@ -1,14 +1,17 @@
import { Controller, useFormContext } from "react-hook-form";
+import { SingleValue } from "react-select";
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { Link } from "@tanstack/react-router";
+import { AppConnectionOption } from "@app/components/app-connections";
import { FilterableSelect, FormControl } from "@app/components/v2";
-import { OrgPermissionSubjects, useOrgPermission } from "@app/context";
-import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";
+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
import { SECRET_SYNC_CONNECTION_MAP } from "@app/helpers/secretSyncs";
+import { usePopUp } from "@app/hooks";
import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
+import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
import { TSecretSyncForm } from "./schemas";
@@ -17,19 +20,26 @@ type Props = {
};
export const SecretSyncConnectionField = ({ onChange: callback }: Props) => {
- const { permission } = useOrgPermission();
- const { control, watch } = useFormContext<TSecretSyncForm>();
+ const { permission } = useProjectPermission();
+ const { control, watch, setValue } = useFormContext<TSecretSyncForm>();
+
+ const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
const destination = watch("destination");
const app = SECRET_SYNC_CONNECTION_MAP[destination];
- const { data: availableConnections, isPending } = useListAvailableAppConnections(app);
+ const { currentProject } = useProject();
+
+ const { data: availableConnections, isPending } = useListAvailableAppConnections(
+ app,
+ currentProject.id
+ );
const connectionName = APP_CONNECTION_MAP[app].name;
const canCreateConnection = permission.can(
- OrgPermissionAppConnectionActions.Create,
- OrgPermissionSubjects.AppConnections
+ ProjectPermissionAppConnectionActions.Create,
+ ProjectPermissionSub.AppConnections
);
const appName = APP_CONNECTION_MAP[SECRET_SYNC_CONNECTION_MAP[destination]].name;
@@ -51,36 +61,55 @@ export const SecretSyncConnectionField = ({ onChange: callback }: Props) => {
<FilterableSelect
value={value}
onChange={(newValue) => {
+ if ((newValue as SingleValue<{ id: string; name: string }>)?.id === "_create") {
+ handlePopUpOpen("addConnection");
+ onChange(null);
+ // store for oauth callback connections
+ localStorage.setItem("secretSyncFormData", JSON.stringify(watch()));
+ if (callback) callback();
+ return;
+ }
+
onChange(newValue);
if (callback) callback();
}}
isLoading={isPending}
- options={availableConnections}
+ options={[
+ ...(canCreateConnection ? [{ id: "_create", name: "Create Connection" }] : []),
+ ...(availableConnections ?? [])
+ ]}
placeholder="Select connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
+ components={{ Option: AppConnectionOption }}
/>
</FormControl>
)}
control={control}
name="connection"
/>
- {availableConnections?.length === 0 && (
+ {!isPending && !availableConnections?.length && !canCreateConnection && (
<p className="-mt-2.5 mb-2.5 text-xs text-yellow">
<FontAwesomeIcon className="mr-1" size="xs" icon={faInfoCircle} />
- {canCreateConnection ? (
- <>
- You do not have access to any {appName} Connections. Create one from the{" "}
- <Link to="/organization/app-connections" className="underline">
- App Connections
- </Link>{" "}
- page.
- </>
- ) : (
- `You do not have access to any ${appName} Connections. Contact an admin to create one.`
- )}
+ You do not have access to any {appName} Connections. Contact an admin to create one.
</p>
)}
+ <AddAppConnectionModal
+ isOpen={popUp.addConnection.isOpen}
+ onOpenChange={(isOpen) => {
+ // remove form storage, not oauth connection
+ localStorage.removeItem("secretSyncFormData");
+ handlePopUpToggle("addConnection", isOpen);
+ }}
+ projectType={currentProject.type}
+ projectId={currentProject.id}
+ app={app}
+ onComplete={(connection) => {
+ if (connection) {
+ setValue("connection", connection);
+ }
+ }}
+ />
</>
);
};
diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx
index 850ebbc801..127ac503c9 100644
--- a/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx
+++ b/frontend/src/components/secret-syncs/forms/SecretSyncSourceFields.tsx
@@ -4,7 +4,7 @@ import { subject } from "@casl/ability";
import { FilterableSelect, FormControl } from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import {
ProjectPermissionSecretSyncActions,
ProjectPermissionSub
@@ -16,7 +16,7 @@ export const SecretSyncSourceFields = () => {
const { control, watch, setError, clearErrors } = useFormContext<TSecretSyncForm>();
const { permission } = useProjectPermission();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const selectedEnvironment = watch("environment");
const selectedSecretPath = watch("secretPath");
@@ -48,7 +48,7 @@ export const SecretSyncSourceFields = () => {
</p>
<Controller
- defaultValue={currentWorkspace.environments[0]}
+ defaultValue={currentProject.environments[0]}
control={control}
name="environment"
render={({ field: { value, onChange }, fieldState: { error } }) => (
@@ -56,7 +56,7 @@ export const SecretSyncSourceFields = () => {
<FilterableSelect
value={value}
onChange={onChange}
- options={currentWorkspace.environments}
+ options={currentProject.environments}
placeholder="Select environment..."
getOptionLabel={(option) => option?.name}
getOptionValue={(option) => option?.id}
diff --git a/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsx b/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsx
index a9542c90cd..d4f09ea8fc 100644
--- a/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsx
+++ b/frontend/src/components/secrets/SecretReferenceDetails/SecretReferenceDetails.tsx
@@ -13,7 +13,7 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { FormControl, FormLabel, SecretInput, Spinner, Tooltip } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useGetSecretReferenceTree } from "@app/hooks/api";
import { ApiErrorTypes, TApiErrors, TSecretReferenceTraceNode } from "@app/hooks/api/types";
@@ -89,8 +89,8 @@ export const SecretReferenceNode = ({
};
export const SecretReferenceTree = ({ secretPath, environment, secretKey }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data, isPending, isError, error } = useGetSecretReferenceTree({
secretPath,
@@ -130,6 +130,14 @@ export const SecretReferenceTree = ({ secretPath, environment, secretKey }: Prop
);
}
+ if (tree?.children?.length === 0) {
+ return (
+ <div className="flex items-center justify-center py-4">
+ <span className="text-mineshaft-400">This secret does not contain references</span>
+ </div>
+ );
+ }
+
return (
<div>
<FormControl label="Expanded value">
diff --git a/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx b/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx
index b1773b2e39..d48b7d95fb 100644
--- a/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx
+++ b/frontend/src/components/tags/CreateTagModal/CreateTagModal.tsx
@@ -15,7 +15,7 @@ import {
ModalContent,
Tooltip
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateWsTag } from "@app/hooks/api";
import { slugSchema } from "@app/lib/schemas";
@@ -115,11 +115,10 @@ export const CreateTagModal = ({ isOpen, onToggle }: Props): JSX.Element => {
}
});
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { mutateAsync: createWsTag } = useCreateWsTag();
-
const [showHexInput, setShowHexInput] = useState<boolean>(false);
const selectedTagColor = watch("color", secretTagsColors[0].hex);
@@ -130,7 +129,7 @@ export const CreateTagModal = ({ isOpen, onToggle }: Props): JSX.Element => {
const onFormSubmit = async ({ slug, color }: FormData) => {
try {
await createWsTag({
- workspaceID: workspaceId,
+ projectId,
tagColor: color,
tagSlug: slug
});
diff --git a/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx b/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx
index dbeeb87474..7e3d38f4fc 100644
--- a/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx
+++ b/frontend/src/components/v2/InfisicalSecretInput/InfisicalSecretInput.tsx
@@ -3,7 +3,7 @@ import { faFolder, faKey, faLayerGroup, faSearch } from "@fortawesome/free-solid
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Popover from "@radix-ui/react-popover";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useDebounce, useToggle } from "@app/hooks";
import { useGetProjectFolders, useGetProjectSecrets } from "@app/hooks/api";
@@ -55,6 +55,8 @@ type Props = Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "onChange" | "val
secretPath?: string;
environment?: string;
containerClassName?: string;
+ isLoadingValue?: boolean;
+ isErrorLoadingValue?: boolean;
};
type ReferenceItem = {
@@ -76,8 +78,8 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
},
ref
) => {
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const [debouncedValue] = useDebounce(value, 100);
@@ -101,7 +103,7 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
let predicate = suggestionSourceValue;
if (isDeep) {
const [envSlug, ...folderPaths] = suggestionSourceValue.split(".");
- const isValidEnvSlug = currentWorkspace?.environments.find((e) => e.slug === envSlug);
+ const isValidEnvSlug = currentProject?.environments.find((e) => e.slug === envSlug);
suggestionSourceEnv = isValidEnvSlug ? envSlug : undefined;
suggestionSourceSecretPath = `/${folderPaths.slice(0, -1)?.join("/")}`;
predicate = folderPaths[folderPaths.length - 1];
@@ -125,7 +127,7 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
viewSecretValue: false,
environment: suggestionSource.environment || "",
secretPath: suggestionSource.secretPath || "",
- workspaceId,
+ projectId,
options: {
enabled: isPopupOpen
}
@@ -133,7 +135,7 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
const { data: folders } = useGetProjectFolders({
environment: suggestionSource.environment || "",
path: suggestionSource.secretPath || "",
- projectId: workspaceId,
+ projectId,
options: {
enabled: isPopupOpen
}
@@ -148,7 +150,7 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
if (!suggestionSource.isDeep) {
// At first level only environments and secrets
- (currentWorkspace?.environments || []).forEach(({ name, slug }) => {
+ (currentProject?.environments || []).forEach(({ name, slug }) => {
if (name.toLowerCase().startsWith(predicate))
suggestionsArr.push({
label: name,
@@ -185,7 +187,14 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
}
return suggestionsArr;
- }, [secrets, folders, currentWorkspace?.environments, isPopupOpen, suggestionSource.predicate]);
+ }, [
+ secrets,
+ folders,
+ currentProject?.environments,
+ isPopupOpen,
+ suggestionSource.value,
+ suggestionSource.predicate
+ ]);
const handleSuggestionSelect = (selectIndex?: number) => {
const selectedSuggestion =
@@ -307,11 +316,16 @@ export const InfisicalSecretInput = forwardRef<HTMLTextAreaElement, Props>(
ref={handleRef}
onKeyDown={handleKeyDown}
value={value}
- onFocus={() => setIsFocused.on()}
+ onFocus={(evt) => {
+ if (props.onFocus) props.onFocus(evt);
+ setIsFocused.on();
+ }}
onBlur={(evt) => {
// should not on blur when its mouse down selecting a item from suggestion
if (!(evt.relatedTarget?.getAttribute("aria-label") === "suggestion-item"))
setIsFocused.off();
+
+ if (props.onBlur) props.onBlur(evt);
}}
onChange={(e) => onChange?.(e.target.value)}
containerClassName={containerClassName}
diff --git a/frontend/src/components/v2/SecretInput/SecretInput.tsx b/frontend/src/components/v2/SecretInput/SecretInput.tsx
index f9b5b6f1b4..69a6bf49f4 100644
--- a/frontend/src/components/v2/SecretInput/SecretInput.tsx
+++ b/frontend/src/components/v2/SecretInput/SecretInput.tsx
@@ -7,7 +7,16 @@ import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPa
const REGEX = /(\${([a-zA-Z0-9-_.]+)})/g;
-const syntaxHighlight = (content?: string | null, isVisible?: boolean, isImport?: boolean) => {
+const syntaxHighlight = (
+ content?: string | null,
+ isVisible?: boolean,
+ isImport?: boolean,
+ isLoadingValue?: boolean,
+ isErrorLoadingValue?: boolean
+) => {
+ if (isLoadingValue) return HIDDEN_SECRET_VALUE;
+ if (isErrorLoadingValue)
+ return <span className="ph-no-capture text-red/75">Error loading secret value.</span>;
if (isImport && !content) return "IMPORTED";
if (content === "") return "EMPTY";
if (!content) return "EMPTY";
@@ -49,6 +58,8 @@ type Props = TextareaHTMLAttributes<HTMLTextAreaElement> & {
isDisabled?: boolean;
containerClassName?: string;
canEditButNotView?: boolean;
+ isLoadingValue?: boolean;
+ isErrorLoadingValue?: boolean;
};
const commonClassName = "font-mono text-sm caret-white border-none outline-none w-full break-all";
@@ -66,6 +77,8 @@ export const SecretInput = forwardRef<HTMLTextAreaElement, Props>(
isReadOnly,
onFocus,
canEditButNotView,
+ isLoadingValue,
+ isErrorLoadingValue,
...props
},
ref
@@ -84,7 +97,9 @@ export const SecretInput = forwardRef<HTMLTextAreaElement, Props>(
{syntaxHighlight(
value,
isVisible || (isSecretFocused && !valueAlwaysHidden),
- isImport
+ isImport,
+ isLoadingValue,
+ isErrorLoadingValue
)}
</span>
</code>
@@ -115,7 +130,7 @@ export const SecretInput = forwardRef<HTMLTextAreaElement, Props>(
}}
value={value || ""}
{...props}
- readOnly={isReadOnly}
+ readOnly={isReadOnly || isLoadingValue || isErrorLoadingValue}
/>
</div>
</div>
diff --git a/frontend/src/components/v2/SecretPathInput/SecretPathInput.tsx b/frontend/src/components/v2/SecretPathInput/SecretPathInput.tsx
index a1d4fb2a26..a9c08f7ad2 100644
--- a/frontend/src/components/v2/SecretPathInput/SecretPathInput.tsx
+++ b/frontend/src/components/v2/SecretPathInput/SecretPathInput.tsx
@@ -4,7 +4,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Popover from "@radix-ui/react-popover";
import { twMerge } from "tailwind-merge";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useDebounce } from "@app/hooks";
import { useGetFoldersByEnv } from "@app/hooks/api";
@@ -35,12 +35,12 @@ export const SecretPathInput = ({
const [highlightedIndex, setHighlightedIndex] = useState(-1);
const [debouncedInputValue] = useDebounce(inputValue, 200);
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { folderNames: folders } = useGetFoldersByEnv({
path: secretPath,
- environments: [environment || currentWorkspace?.environments?.[0].slug || ""],
- projectId: workspaceId
+ environments: [environment || currentProject?.environments?.[0].slug || ""],
+ projectId
});
useEffect(() => {
diff --git a/frontend/src/context/OrgPermissionContext/types.ts b/frontend/src/context/OrgPermissionContext/types.ts
index 4a569be06b..bcab6169e9 100644
--- a/frontend/src/context/OrgPermissionContext/types.ts
+++ b/frontend/src/context/OrgPermissionContext/types.ts
@@ -1,4 +1,4 @@
-import { MongoAbility } from "@casl/ability";
+import { ForcedSubject, MongoAbility } from "@casl/ability";
export enum OrgPermissionActions {
Read = "read",
@@ -21,6 +21,13 @@ export enum OrgGatewayPermissionActions {
AttachGateways = "attach-gateways"
}
+export enum OrgRelayPermissionActions {
+ CreateRelays = "create-relays",
+ ListRelays = "list-relays",
+ EditRelays = "edit-relays",
+ DeleteRelays = "delete-relays"
+}
+
export enum OrgPermissionMachineIdentityAuthTemplateActions {
ListTemplates = "list-templates",
CreateTemplates = "create-templates",
@@ -32,6 +39,7 @@ export enum OrgPermissionMachineIdentityAuthTemplateActions {
export enum OrgPermissionSubjects {
Workspace = "workspace",
+ Project = "project",
Role = "role",
Member = "member",
Settings = "settings",
@@ -50,6 +58,7 @@ export enum OrgPermissionSubjects {
AppConnections = "app-connections",
Kmip = "kmip",
Gateway = "gateway",
+ Relay = "relay",
SecretShare = "secret-share",
GithubOrgSync = "github-org-sync",
GithubOrgSyncManual = "github-org-sync-manual",
@@ -109,6 +118,7 @@ export type AppConnectionSubjectFields = {
export type OrgPermissionSet =
| [OrgPermissionActions.Create, OrgPermissionSubjects.Workspace]
+ | [OrgPermissionActions.Create, OrgPermissionSubjects.Project]
| [OrgPermissionActions.Read, OrgPermissionSubjects.Workspace]
| [OrgPermissionActions, OrgPermissionSubjects.Role]
| [OrgPermissionActions, OrgPermissionSubjects.Member]
@@ -126,7 +136,6 @@ export type OrgPermissionSet =
| [OrgPermissionAdminConsoleAction, OrgPermissionSubjects.AdminConsole]
| [OrgPermissionAuditLogsActions, OrgPermissionSubjects.AuditLogs]
| [OrgPermissionActions, OrgPermissionSubjects.ProjectTemplates]
- | [OrgPermissionAppConnectionActions, OrgPermissionSubjects.AppConnections]
| [OrgPermissionIdentityActions, OrgPermissionSubjects.Identity]
| [OrgPermissionKmipActions, OrgPermissionSubjects.Kmip]
| [
@@ -134,14 +143,14 @@ export type OrgPermissionSet =
OrgPermissionSubjects.MachineIdentityAuthTemplate
]
| [OrgGatewayPermissionActions, OrgPermissionSubjects.Gateway]
- | [OrgPermissionSecretShareAction, OrgPermissionSubjects.SecretShare];
-// TODO(scott): add back once org UI refactored
-// | [
-// OrgPermissionAppConnectionActions,
-// (
-// | OrgPermissionSubjects.AppConnections
-// | (ForcedSubject<OrgPermissionSubjects.AppConnections> & AppConnectionSubjectFields)
-// )
-// ];
+ | [OrgRelayPermissionActions, OrgPermissionSubjects.Relay]
+ | [OrgPermissionSecretShareAction, OrgPermissionSubjects.SecretShare]
+ | [
+ OrgPermissionAppConnectionActions,
+ (
+ | OrgPermissionSubjects.AppConnections
+ | (ForcedSubject<OrgPermissionSubjects.AppConnections> & AppConnectionSubjectFields)
+ )
+ ];
export type TOrgPermission = MongoAbility<OrgPermissionSet>;
diff --git a/frontend/src/context/ProjectContext/ProjectContext.tsx b/frontend/src/context/ProjectContext/ProjectContext.tsx
new file mode 100644
index 0000000000..7256741ef6
--- /dev/null
+++ b/frontend/src/context/ProjectContext/ProjectContext.tsx
@@ -0,0 +1,22 @@
+import { useSuspenseQuery } from "@tanstack/react-query";
+import { useParams } from "@tanstack/react-router";
+
+import { projectKeys } from "@app/hooks/api";
+import { fetchProjectById } from "@app/hooks/api/projects/queries";
+
+export const useProject = () => {
+ const params = useParams({
+ strict: false
+ });
+ if (!params.projectId) {
+ throw new Error("Missing project id");
+ }
+
+ const { data: currentProject } = useSuspenseQuery({
+ queryKey: projectKeys.getProjectById(params.projectId),
+ queryFn: () => fetchProjectById(params.projectId as string),
+ staleTime: Infinity
+ });
+
+ return { currentProject, projectId: currentProject.id };
+};
diff --git a/frontend/src/context/ProjectContext/index.tsx b/frontend/src/context/ProjectContext/index.tsx
new file mode 100644
index 0000000000..f87ed0a3d1
--- /dev/null
+++ b/frontend/src/context/ProjectContext/index.tsx
@@ -0,0 +1 @@
+export { useProject } from "./ProjectContext";
diff --git a/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx b/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
index a824f6fa64..871d5c338d 100644
--- a/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
+++ b/frontend/src/context/ProjectPermissionContext/ProjectPermissionContext.tsx
@@ -22,8 +22,8 @@ export const useProjectPermission = () => {
const {
data: { permission, membership, assumedPrivilegeDetails }
} = useSuspenseQuery({
- queryKey: roleQueryKeys.getUserProjectPermissions({ workspaceId: projectId }),
- queryFn: () => fetchUserProjectPermissions({ workspaceId: projectId }),
+ queryKey: roleQueryKeys.getUserProjectPermissions({ projectId }),
+ queryFn: () => fetchUserProjectPermissions({ projectId }),
staleTime: Infinity,
select: (data) => {
const rule = unpackRules<RawRuleOf<MongoAbility<ProjectPermissionSet>>>(data.permissions);
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index acfab612f2..ad6b5bb0a6 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -154,6 +154,14 @@ export enum ProjectPermissionAuditLogsActions {
Read = "read"
}
+export enum ProjectPermissionAppConnectionActions {
+ Read = "read-app-connections",
+ Create = "create-app-connections",
+ Edit = "edit-app-connections",
+ Delete = "delete-app-connections",
+ Connect = "connect-app-connections"
+}
+
export enum PermissionConditionOperators {
$IN = "$in",
$ALL = "$all",
@@ -173,6 +181,10 @@ export type IdentityManagementSubjectFields = {
identityId: string;
};
+export type AppConnectionSubjectFields = {
+ connectionId: string;
+};
+
export type ConditionalProjectPermissionSubject =
| ProjectPermissionSub.SecretSyncs
| ProjectPermissionSub.Secrets
@@ -184,7 +196,8 @@ export type ConditionalProjectPermissionSubject =
| ProjectPermissionSub.SecretFolders
| ProjectPermissionSub.SecretImports
| ProjectPermissionSub.SecretRotation
- | ProjectPermissionSub.SecretEvents;
+ | ProjectPermissionSub.SecretEvents
+ | ProjectPermissionSub.AppConnections;
export const formatedConditionsOperatorNames: { [K in PermissionConditionOperators]: string } = {
[PermissionConditionOperators.$EQ]: "equal to",
@@ -263,7 +276,8 @@ export enum ProjectPermissionSub {
SecretScanningDataSources = "secret-scanning-data-sources",
SecretScanningFindings = "secret-scanning-findings",
SecretScanningConfigs = "secret-scanning-configs",
- SecretEvents = "secret-events"
+ SecretEvents = "secret-events",
+ AppConnections = "app-connections"
}
export type SecretSubjectFields = {
@@ -431,6 +445,13 @@ export type ProjectPermissionSet =
| ProjectPermissionSub.SecretEvents
| (ForcedSubject<ProjectPermissionSub.SecretEvents> & SecretEventSubjectFields)
)
+ ]
+ | [
+ ProjectPermissionAppConnectionActions,
+ (
+ | ProjectPermissionSub.AppConnections
+ | (ForcedSubject<ProjectPermissionSub.AppConnections> & AppConnectionSubjectFields)
+ )
];
export type TProjectPermission = MongoAbility<ProjectPermissionSet>;
diff --git a/frontend/src/context/WorkspaceContext/WorkspaceContext.tsx b/frontend/src/context/WorkspaceContext/WorkspaceContext.tsx
deleted file mode 100644
index 8bef13b314..0000000000
--- a/frontend/src/context/WorkspaceContext/WorkspaceContext.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { useSuspenseQuery } from "@tanstack/react-query";
-import { useParams } from "@tanstack/react-router";
-
-import { workspaceKeys } from "@app/hooks/api";
-import { fetchWorkspaceById } from "@app/hooks/api/workspace/queries";
-
-export const useWorkspace = () => {
- const params = useParams({
- strict: false
- });
- if (!params.projectId) {
- throw new Error("Missing project id");
- }
-
- const { data: currentWorkspace } = useSuspenseQuery({
- queryKey: workspaceKeys.getWorkspaceById(params.projectId),
- queryFn: () => fetchWorkspaceById(params.projectId as string),
- staleTime: Infinity
- });
-
- return { currentWorkspace };
-};
diff --git a/frontend/src/context/WorkspaceContext/index.tsx b/frontend/src/context/WorkspaceContext/index.tsx
deleted file mode 100644
index b0c25d4dab..0000000000
--- a/frontend/src/context/WorkspaceContext/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { useWorkspace } from "./WorkspaceContext";
diff --git a/frontend/src/context/index.tsx b/frontend/src/context/index.tsx
index bfb504664d..fff370269b 100644
--- a/frontend/src/context/index.tsx
+++ b/frontend/src/context/index.tsx
@@ -9,6 +9,7 @@ export {
OrgPermissionSubjects,
useOrgPermission
} from "./OrgPermissionContext";
+export { useProject } from "./ProjectContext";
export type { TProjectPermission } from "./ProjectPermissionContext";
export {
ProjectPermissionActions,
@@ -29,4 +30,3 @@ export {
export { useServerConfig } from "./ServerConfigContext";
export { useSubscription } from "./SubscriptionContext";
export { useUser } from "./UserContext";
-export { useWorkspace } from "./WorkspaceContext";
diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.ts
index 88d9bb0d12..99103c7944 100644
--- a/frontend/src/helpers/appConnections.ts
+++ b/frontend/src/helpers/appConnections.ts
@@ -8,6 +8,7 @@ import {
faServer,
faUser
} from "@fortawesome/free-solid-svg-icons";
+import { useRouterState } from "@tanstack/react-router";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
@@ -221,3 +222,11 @@ export const AWS_REGIONS = [
{ name: "AWS GovCloud (US-East)", slug: "us-gov-east-1" },
{ name: "AWS GovCloud (US-West)", slug: "us-gov-west-1" }
];
+
+export const useGetAppConnectionOauthReturnUrl = () => {
+ const {
+ location: { pathname }
+ } = useRouterState();
+
+ return pathname;
+};
diff --git a/frontend/src/helpers/auditLogStreams.ts b/frontend/src/helpers/auditLogStreams.ts
index eee2fc8dae..faa132dd29 100644
--- a/frontend/src/helpers/auditLogStreams.ts
+++ b/frontend/src/helpers/auditLogStreams.ts
@@ -8,6 +8,7 @@ export const AUDIT_LOG_STREAM_PROVIDER_MAP: Record<
LogProvider,
{ name: string; image?: string; icon?: IconDefinition; size?: number }
> = {
+ [LogProvider.Azure]: { name: "Azure", image: "Microsoft Azure.png", size: 60 },
[LogProvider.Cribl]: { name: "Cribl", image: "Cribl.png", size: 60 },
[LogProvider.Custom]: { name: "Custom", icon: faCode },
[LogProvider.Datadog]: { name: "Datadog", image: "Datadog.png" },
@@ -25,6 +26,8 @@ export function getProviderUrl(
return logStream.credentials.url;
case LogProvider.Splunk:
return `https://${logStream.credentials.hostname}:8088/services/collector/event`;
+ case LogProvider.Azure:
+ return `${logStream.credentials.dceUrl}/dataCollectionRules/${logStream.credentials.dcrId}/streams/Custom-${logStream.credentials.cltName}_CL`;
default:
throw new Error(
`Unhandled provider in getProviderUrl: ${(logStream as TAuditLogStream).provider}`
diff --git a/frontend/src/helpers/project.ts b/frontend/src/helpers/project.ts
index 7c91855560..6227b96967 100644
--- a/frontend/src/helpers/project.ts
+++ b/frontend/src/helpers/project.ts
@@ -1,6 +1,6 @@
import { apiRequest } from "@app/config/request";
-import { createWorkspace } from "@app/hooks/api/workspace/queries";
-import { ProjectType, WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { createWorkspace } from "@app/hooks/api/projects/queries";
+import { ProjectEnv, ProjectType } from "@app/hooks/api/projects/types";
const secretsToBeAdded = [
{
@@ -47,8 +47,8 @@ export const initProjectHelper = async ({ projectName }: { projectName: string }
});
try {
- const { data } = await apiRequest.post("/api/v3/secrets/batch/raw", {
- workspaceId: project.id,
+ const { data } = await apiRequest.post("/api/v4/secrets/batch", {
+ projectId: project.id,
environment: "dev",
secretPath: "/",
secrets: secretsToBeAdded
@@ -74,7 +74,7 @@ export const getProjectBaseURL = (type: ProjectType) => {
// @ts-expect-error akhilmhdh: will remove this later
// eslint-disable-next-line @typescript-eslint/no-unused-vars
-export const getProjectHomePage = (type: ProjectType, environments: WorkspaceEnv[]) => {
+export const getProjectHomePage = (type: ProjectType, environments: ProjectEnv[]) => {
switch (type) {
case ProjectType.SecretManager:
return "/projects/secret-management/$projectId/overview" as const;
diff --git a/frontend/src/hooks/api/accessApproval/queries.tsx b/frontend/src/hooks/api/accessApproval/queries.tsx
index 44f260f662..2be6c9535f 100644
--- a/frontend/src/hooks/api/accessApproval/queries.tsx
+++ b/frontend/src/hooks/api/accessApproval/queries.tsx
@@ -16,8 +16,8 @@ import {
export const accessApprovalKeys = {
getAccessApprovalPolicies: (projectSlug: string) =>
[{ projectSlug }, "access-approval-policies"] as const,
- getAccessApprovalPolicyOfABoard: (workspaceId: string, environment: string) =>
- [{ workspaceId, environment }, "access-approval-policy"] as const,
+ getAccessApprovalPolicyOfABoard: (projectId: string, environment: string) =>
+ [{ projectId, environment }, "access-approval-policy"] as const,
getAccessApprovalRequests: (
projectSlug: string,
diff --git a/frontend/src/hooks/api/accessApproval/types.ts b/frontend/src/hooks/api/accessApproval/types.ts
index 5063f4fffd..be698e4690 100644
--- a/frontend/src/hooks/api/accessApproval/types.ts
+++ b/frontend/src/hooks/api/accessApproval/types.ts
@@ -1,7 +1,7 @@
import { EnforcementLevel, PolicyType } from "../policies/enums";
+import { ProjectEnv } from "../projects/types";
import { TProjectPermission } from "../roles/types";
import { ApprovalStatus } from "../secretApprovalRequest/types";
-import { WorkspaceEnv } from "../workspace/types";
export type TAccessApprovalPolicy = {
id: string;
@@ -9,7 +9,7 @@ export type TAccessApprovalPolicy = {
approvals: number;
secretPath: string;
workspace: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
projectId: string;
policyType: PolicyType;
approversRequired: boolean;
diff --git a/frontend/src/hooks/api/appConnections/mutations.tsx b/frontend/src/hooks/api/appConnections/mutations.tsx
index bb8831342d..cee433462b 100644
--- a/frontend/src/hooks/api/appConnections/mutations.tsx
+++ b/frontend/src/hooks/api/appConnections/mutations.tsx
@@ -20,7 +20,10 @@ export const useCreateAppConnection = () => {
return data.appConnection;
},
- onSuccess: () => queryClient.invalidateQueries({ queryKey: appConnectionKeys.list() })
+ onSuccess: ({ projectId, app }) => {
+ queryClient.invalidateQueries({ queryKey: appConnectionKeys.list(projectId) });
+ queryClient.invalidateQueries({ queryKey: appConnectionKeys.listAvailable(app, projectId) });
+ }
});
};
@@ -35,9 +38,10 @@ export const useUpdateAppConnection = () => {
return data.appConnection;
},
- onSuccess: (_, { connectionId, app }) => {
- queryClient.invalidateQueries({ queryKey: appConnectionKeys.list() });
- queryClient.invalidateQueries({ queryKey: appConnectionKeys.byId(app, connectionId) });
+ onSuccess: ({ projectId, app }) => {
+ queryClient.invalidateQueries({ queryKey: appConnectionKeys.list(projectId) });
+ queryClient.invalidateQueries({ queryKey: appConnectionKeys.listAvailable(app, projectId) });
+ // queryClient.invalidateQueries({ queryKey: appConnectionKeys.byId(app, connectionId) });
}
});
};
@@ -50,9 +54,10 @@ export const useDeleteAppConnection = () => {
return data;
},
- onSuccess: (_, { connectionId, app }) => {
- queryClient.invalidateQueries({ queryKey: appConnectionKeys.list() });
- queryClient.invalidateQueries({ queryKey: appConnectionKeys.byId(app, connectionId) });
+ onSuccess: ({ projectId, app }) => {
+ queryClient.invalidateQueries({ queryKey: appConnectionKeys.list(projectId) });
+ queryClient.invalidateQueries({ queryKey: appConnectionKeys.listAvailable(app, projectId) });
+ // queryClient.invalidateQueries({ queryKey: appConnectionKeys.byId(app, connectionId) });
}
});
};
diff --git a/frontend/src/hooks/api/appConnections/queries.tsx b/frontend/src/hooks/api/appConnections/queries.tsx
index dbccade88c..a27ffdc107 100644
--- a/frontend/src/hooks/api/appConnections/queries.tsx
+++ b/frontend/src/hooks/api/appConnections/queries.tsx
@@ -5,29 +5,36 @@ import { apiRequest } from "@app/config/request";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
TAppConnection,
- TAppConnectionMap,
TAppConnectionOptions,
TAvailableAppConnection,
TAvailableAppConnectionsResponse,
- TGetAppConnection,
TListAppConnections
} from "@app/hooks/api/appConnections/types";
import {
TAppConnectionOption,
TAppConnectionOptionMap
} from "@app/hooks/api/appConnections/types/app-options";
+import { ProjectType } from "@app/hooks/api/projects/types";
export const appConnectionKeys = {
all: ["app-connection"] as const,
- options: () => [...appConnectionKeys.all, "options"] as const,
- list: () => [...appConnectionKeys.all, "list"] as const,
- listAvailable: (app: AppConnection) => [...appConnectionKeys.all, app, "list-available"] as const,
- listByApp: (app: AppConnection) => [...appConnectionKeys.list(), app],
- byId: (app: AppConnection, connectionId: string) =>
- [...appConnectionKeys.all, app, "by-id", connectionId] as const
+ options: (projectType?: ProjectType) =>
+ [...appConnectionKeys.all, "options", ...(projectType ? [projectType] : [])] as const,
+ list: (projectId?: string | null) =>
+ [...appConnectionKeys.all, "list", ...(projectId ? [projectId] : [])] as const,
+ listAvailable: (app: AppConnection, projectId?: string | null) =>
+ [...appConnectionKeys.all, app, "list-available", ...(projectId ? [projectId] : [])] as const
+ // scott: may need these in the future but not using now
+ // getUsage: (app: AppConnection, connectionId: string) =>
+ // [...appConnectionKeys.all, "usage", app, connectionId] as const
+ // listByApp: (app: AppConnection) => [...appConnectionKeys.list(), app],
+ // scott: we will need this once we have individual app connection page
+ // byId: (app: AppConnection, connectionId: string) =>
+ // [...appConnectionKeys.all, app, "by-id", connectionId] as const
};
export const useAppConnectionOptions = (
+ projectType?: ProjectType,
options?: Omit<
UseQueryOptions<
TAppConnectionOption[],
@@ -39,10 +46,11 @@ export const useAppConnectionOptions = (
>
) => {
return useQuery({
- queryKey: appConnectionKeys.options(),
+ queryKey: appConnectionKeys.options(projectType),
queryFn: async () => {
const { data } = await apiRequest.get<TAppConnectionOptions>(
- "/api/v1/app-connections/options"
+ "/api/v1/app-connections/options",
+ { params: { projectType } }
);
return data.appConnectionOptions;
@@ -64,6 +72,7 @@ export const useGetAppConnectionOption = <T extends AppConnection>(app: T) => {
};
export const useListAppConnections = (
+ projectId?: string,
options?: Omit<
UseQueryOptions<
TAppConnection[],
@@ -75,10 +84,12 @@ export const useListAppConnections = (
>
) => {
return useQuery({
- queryKey: appConnectionKeys.list(),
+ queryKey: appConnectionKeys.list(projectId),
queryFn: async () => {
- const { data } =
- await apiRequest.get<TListAppConnections<TAppConnection>>("/api/v1/app-connections");
+ const { data } = await apiRequest.get<TListAppConnections<TAppConnection>>(
+ "/api/v1/app-connections",
+ { params: { projectId } }
+ );
return data.appConnections;
},
@@ -88,6 +99,7 @@ export const useListAppConnections = (
export const useListAvailableAppConnections = (
app: AppConnection,
+ projectId: string,
options?: Omit<
UseQueryOptions<
TAvailableAppConnection[],
@@ -99,10 +111,11 @@ export const useListAvailableAppConnections = (
>
) => {
return useQuery({
- queryKey: appConnectionKeys.listAvailable(app),
+ queryKey: appConnectionKeys.listAvailable(app, projectId),
queryFn: async () => {
const { data } = await apiRequest.get<TAvailableAppConnectionsResponse>(
- `/api/v1/app-connections/${app}/available`
+ `/api/v1/app-connections/${app}/available`,
+ { params: { projectId } }
);
return data.appConnections;
@@ -111,53 +124,82 @@ export const useListAvailableAppConnections = (
});
};
-export const useListAppConnectionsByApp = <T extends AppConnection>(
- app: T,
- options?: Omit<
- UseQueryOptions<
- TAppConnectionMap[T][],
- unknown,
- TAppConnectionMap[T][],
- ReturnType<typeof appConnectionKeys.listByApp>
- >,
- "queryKey" | "queryFn"
- >
-) => {
- return useQuery({
- queryKey: appConnectionKeys.listByApp(app),
- queryFn: async () => {
- const { data } = await apiRequest.get<TListAppConnections<TAppConnectionMap[T]>>(
- `/api/v1/app-connections/${app}`
- );
+// scott: may need these in the future but not using now
+// export const useGetAppConnectionUsageById = (
+// app: AppConnection,
+// connectionId: string,
+// options?: Omit<
+// UseQueryOptions<
+// AppConnectionUsage,
+// unknown,
+// AppConnectionUsage,
+// ReturnType<typeof appConnectionKeys.getUsage>
+// >,
+// "queryKey" | "queryFn"
+// >
+// ) => {
+// return useQuery({
+// queryKey: appConnectionKeys.getUsage(app, connectionId),
+// queryFn: async () => {
+// const { data } = await apiRequest.get<AppConnectionUsage>(
+// `/api/v1/app-connections/${app}/${connectionId}/usage`
+// );
+//
+// return data;
+// },
+// ...options
+// });
+// };
- return data.appConnections;
- },
- ...options
- });
-};
+// scott: may need these in the future but not using now
+// export const useListAppConnectionsByApp = <T extends AppConnection>(
+// app: T,
+// options?: Omit<
+// UseQueryOptions<
+// TAppConnectionMap[T][],
+// unknown,
+// TAppConnectionMap[T][],
+// ReturnType<typeof appConnectionKeys.listByApp>
+// >,
+// "queryKey" | "queryFn"
+// >
+// ) => {
+// return useQuery({
+// queryKey: appConnectionKeys.listByApp(app),
+// queryFn: async () => {
+// const { data } = await apiRequest.get<TListAppConnections<TAppConnectionMap[T]>>(
+// `/api/v1/app-connections/${app}`
+// );
+//
+// return data.appConnections;
+// },
+// ...options
+// });
+// };
-export const useGetAppConnectionById = <T extends AppConnection>(
- app: T,
- connectionId: string,
- options?: Omit<
- UseQueryOptions<
- TAppConnectionMap[T],
- unknown,
- TAppConnectionMap[T],
- ReturnType<typeof appConnectionKeys.byId>
- >,
- "queryKey" | "queryFn"
- >
-) => {
- return useQuery({
- queryKey: appConnectionKeys.byId(app, connectionId),
- queryFn: async () => {
- const { data } = await apiRequest.get<TGetAppConnection<TAppConnectionMap[T]>>(
- `/api/v1/app-connections/${app}/${connectionId}`
- );
-
- return data.appConnection;
- },
- ...options
- });
-};
+// scott: we will need this once we have individual app connection page
+// export const useGetAppConnectionById = <T extends AppConnection>(
+// app: T,
+// connectionId: string,
+// options?: Omit<
+// UseQueryOptions<
+// TAppConnectionMap[T],
+// unknown,
+// TAppConnectionMap[T],
+// ReturnType<typeof appConnectionKeys.byId>
+// >,
+// "queryKey" | "queryFn"
+// >
+// ) => {
+// return useQuery({
+// queryKey: appConnectionKeys.byId(app, connectionId),
+// queryFn: async () => {
+// const { data } = await apiRequest.get<TGetAppConnection<TAppConnectionMap[T]>>(
+// `/api/v1/app-connections/${app}/${connectionId}`
+// );
+//
+// return data.appConnection;
+// },
+// ...options
+// });
+// };
diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.ts
index e63979a8e5..8c1d86ca3a 100644
--- a/frontend/src/hooks/api/appConnections/types/index.ts
+++ b/frontend/src/hooks/api/appConnections/types/index.ts
@@ -116,10 +116,11 @@ export type TAppConnection =
| TNetlifyConnection
| TOktaConnection;
-export type TAvailableAppConnection = Pick<TAppConnection, "name" | "id">;
+export type TAvailableAppConnection = Pick<TAppConnection, "name" | "id" | "projectId">;
export type TListAppConnections<T extends TAppConnection> = { appConnections: T[] };
-export type TGetAppConnection<T extends TAppConnection> = { appConnection: T };
+// scott: we will need this once we have individual app connection page
+// export type TGetAppConnection<T extends TAppConnection> = { appConnection: T };
export type TAppConnectionOptions = { appConnectionOptions: TAppConnectionOption[] };
export type TAppConnectionResponse = { appConnection: TAppConnection };
export type TAvailableAppConnectionsResponse = { appConnections: TAvailableAppConnection[] };
@@ -133,6 +134,7 @@ export type TCreateAppConnectionDTO = Pick<
| "description"
| "isPlatformManagedCredentials"
| "gatewayId"
+ | "projectId"
>;
export type TUpdateAppConnectionDTO = Partial<
@@ -150,43 +152,60 @@ export type TDeleteAppConnectionDTO = {
connectionId: string;
};
-export type TAppConnectionMap = {
- [AppConnection.AWS]: TAwsConnection;
- [AppConnection.GitHub]: TGitHubConnection;
- [AppConnection.GitHubRadar]: TGitHubRadarConnection;
- [AppConnection.GCP]: TGcpConnection;
- [AppConnection.AzureKeyVault]: TAzureKeyVaultConnection;
- [AppConnection.AzureAppConfiguration]: TAzureAppConfigurationConnection;
- [AppConnection.AzureClientSecrets]: TAzureClientSecretsConnection;
- [AppConnection.AzureDevOps]: TAzureDevOpsConnection;
- [AppConnection.AzureADCS]: TAzureADCSConnection;
- [AppConnection.Databricks]: TDatabricksConnection;
- [AppConnection.Humanitec]: THumanitecConnection;
- [AppConnection.TerraformCloud]: TTerraformCloudConnection;
- [AppConnection.Vercel]: TVercelConnection;
- [AppConnection.Postgres]: TPostgresConnection;
- [AppConnection.MsSql]: TMsSqlConnection;
- [AppConnection.MySql]: TMySqlConnection;
- [AppConnection.OracleDB]: TOracleDBConnection;
- [AppConnection.Camunda]: TCamundaConnection;
- [AppConnection.Windmill]: TWindmillConnection;
- [AppConnection.Auth0]: TAuth0Connection;
- [AppConnection.HCVault]: THCVaultConnection;
- [AppConnection.LDAP]: TLdapConnection;
- [AppConnection.TeamCity]: TTeamCityConnection;
- [AppConnection.OCI]: TOCIConnection;
- [AppConnection.OnePass]: TOnePassConnection;
- [AppConnection.Heroku]: THerokuConnection;
- [AppConnection.Render]: TRenderConnection;
- [AppConnection.Flyio]: TFlyioConnection;
- [AppConnection.GitLab]: TGitLabConnection;
- [AppConnection.Cloudflare]: TCloudflareConnection;
- [AppConnection.Bitbucket]: TBitbucketConnection;
- [AppConnection.Zabbix]: TZabbixConnection;
- [AppConnection.Railway]: TRailwayConnection;
- [AppConnection.Checkly]: TChecklyConnection;
- [AppConnection.Supabase]: TSupabaseConnection;
- [AppConnection.DigitalOcean]: TDigitalOceanConnection;
- [AppConnection.Netlify]: TNetlifyConnection;
- [AppConnection.Okta]: TOktaConnection;
-};
+// scott: we will need this once we have individual app connection page
+// export type TAppConnectionMap = {
+// [AppConnection.AWS]: TAwsConnection;
+// [AppConnection.GitHub]: TGitHubConnection;
+// [AppConnection.GitHubRadar]: TGitHubRadarConnection;
+// [AppConnection.GCP]: TGcpConnection;
+// [AppConnection.AzureKeyVault]: TAzureKeyVaultConnection;
+// [AppConnection.AzureAppConfiguration]: TAzureAppConfigurationConnection;
+// [AppConnection.AzureClientSecrets]: TAzureClientSecretsConnection;
+// [AppConnection.AzureDevOps]: TAzureDevOpsConnection;
+// [AppConnection.AzureADCS]: TAzureADCSConnection;
+// [AppConnection.Databricks]: TDatabricksConnection;
+// [AppConnection.Humanitec]: THumanitecConnection;
+// [AppConnection.TerraformCloud]: TTerraformCloudConnection;
+// [AppConnection.Vercel]: TVercelConnection;
+// [AppConnection.Postgres]: TPostgresConnection;
+// [AppConnection.MsSql]: TMsSqlConnection;
+// [AppConnection.MySql]: TMySqlConnection;
+// [AppConnection.OracleDB]: TOracleDBConnection;
+// [AppConnection.Camunda]: TCamundaConnection;
+// [AppConnection.Windmill]: TWindmillConnection;
+// [AppConnection.Auth0]: TAuth0Connection;
+// [AppConnection.HCVault]: THCVaultConnection;
+// [AppConnection.LDAP]: TLdapConnection;
+// [AppConnection.TeamCity]: TTeamCityConnection;
+// [AppConnection.OCI]: TOCIConnection;
+// [AppConnection.OnePass]: TOnePassConnection;
+// [AppConnection.Heroku]: THerokuConnection;
+// [AppConnection.Render]: TRenderConnection;
+// [AppConnection.Flyio]: TFlyioConnection;
+// [AppConnection.GitLab]: TGitLabConnection;
+// [AppConnection.Cloudflare]: TCloudflareConnection;
+// [AppConnection.Bitbucket]: TBitbucketConnection;
+// [AppConnection.Zabbix]: TZabbixConnection;
+// [AppConnection.Railway]: TRailwayConnection;
+// [AppConnection.Checkly]: TChecklyConnection;
+// [AppConnection.Supabase]: TSupabaseConnection;
+// [AppConnection.DigitalOcean]: TDigitalOceanConnection;
+// [AppConnection.Netlify]: TNetlifyConnection;
+// [AppConnection.Okta]: TOktaConnection;
+// };
+
+// scott: we will need this once we have individual app connection page
+// export type AppConnectionUsage = {
+// projects: Array<{
+// id: string;
+// name: string;
+// slug: string;
+// type: ProjectType;
+// resources: {
+// secretSyncs: Array<{ id: string; name: string }>;
+// externalCas: Array<{ id: string; name: string }>;
+// secretRotations: Array<{ id: string; name: string }>;
+// dataSources: Array<{ id: string; name: string }>;
+// };
+// }>;
+// };
diff --git a/frontend/src/hooks/api/appConnections/types/root-connection.ts b/frontend/src/hooks/api/appConnections/types/root-connection.ts
index 5b8f5cd023..96198265e1 100644
--- a/frontend/src/hooks/api/appConnections/types/root-connection.ts
+++ b/frontend/src/hooks/api/appConnections/types/root-connection.ts
@@ -1,3 +1,5 @@
+import { ProjectType } from "@app/hooks/api/projects/types";
+
export type TRootAppConnection = {
id: string;
name: string;
@@ -8,4 +10,11 @@ export type TRootAppConnection = {
updatedAt: string;
isPlatformManagedCredentials?: boolean;
gatewayId?: string | null;
+ projectId?: string | null;
+ project?: {
+ name: string;
+ type: ProjectType;
+ slug: string;
+ id: string;
+ } | null;
};
diff --git a/frontend/src/hooks/api/assumePrivileges/mutations.tsx b/frontend/src/hooks/api/assumePrivileges/mutations.tsx
index 50e4e5b6c1..687882fe8f 100644
--- a/frontend/src/hooks/api/assumePrivileges/mutations.tsx
+++ b/frontend/src/hooks/api/assumePrivileges/mutations.tsx
@@ -8,7 +8,7 @@ export const useAssumeProjectPrivileges = () =>
useMutation({
mutationFn: async ({ projectId, actorId, actorType }: TProjectAssumePrivilegesDTO) => {
const { data } = await apiRequest.post<{ message: string }>(
- `/api/v1/workspace/${projectId}/assume-privileges`,
+ `/api/v1/projects/${projectId}/assume-privileges`,
{ actorId, actorType }
);
@@ -20,7 +20,7 @@ export const useRemoveAssumeProjectPrivilege = () =>
useMutation({
mutationFn: async ({ projectId }: { projectId: string }) => {
const { data } = await apiRequest.delete<{ message: string }>(
- `/api/v1/workspace/${projectId}/assume-privileges`
+ `/api/v1/projects/${projectId}/assume-privileges`
);
return data;
diff --git a/frontend/src/hooks/api/auditLogStreams/enums.ts b/frontend/src/hooks/api/auditLogStreams/enums.ts
index 78233f774d..ebef18574c 100644
--- a/frontend/src/hooks/api/auditLogStreams/enums.ts
+++ b/frontend/src/hooks/api/auditLogStreams/enums.ts
@@ -1,4 +1,5 @@
export enum LogProvider {
+ Azure = "azure",
Cribl = "cribl",
Custom = "custom",
Datadog = "datadog",
diff --git a/frontend/src/hooks/api/auditLogStreams/types/index.ts b/frontend/src/hooks/api/auditLogStreams/types/index.ts
index a360cd6772..f780510c2d 100644
--- a/frontend/src/hooks/api/auditLogStreams/types/index.ts
+++ b/frontend/src/hooks/api/auditLogStreams/types/index.ts
@@ -1,4 +1,5 @@
import { LogProvider } from "../enums";
+import { TAzureProviderLogStream } from "./providers/azure-provider";
import { TCriblProviderLogStream } from "./providers/cribl-provider";
import { TCustomProviderLogStream } from "./providers/custom-provider";
import { TDatadogProviderLogStream } from "./providers/datadog-provider";
@@ -8,9 +9,11 @@ export type TAuditLogStream =
| TCustomProviderLogStream
| TDatadogProviderLogStream
| TSplunkProviderLogStream
+ | TAzureProviderLogStream
| TCriblProviderLogStream;
export type TAuditLogStreamProviderMap = {
+ [LogProvider.Azure]: TAzureProviderLogStream;
[LogProvider.Cribl]: TCriblProviderLogStream;
[LogProvider.Custom]: TCustomProviderLogStream;
[LogProvider.Datadog]: TDatadogProviderLogStream;
diff --git a/frontend/src/hooks/api/auditLogStreams/types/providers/azure-provider.ts b/frontend/src/hooks/api/auditLogStreams/types/providers/azure-provider.ts
new file mode 100644
index 0000000000..3086fd7cca
--- /dev/null
+++ b/frontend/src/hooks/api/auditLogStreams/types/providers/azure-provider.ts
@@ -0,0 +1,14 @@
+import { LogProvider } from "../../enums";
+import { TRootProviderLogStream } from "./root-provider";
+
+export type TAzureProviderLogStream = TRootProviderLogStream & {
+ provider: LogProvider.Azure;
+ credentials: {
+ tenantId: string;
+ clientId: string;
+ clientSecret: string;
+ dceUrl: string;
+ dcrId: string;
+ cltName: string;
+ };
+};
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index 186a8e5394..df045fa531 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -20,7 +20,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.CREATE_SECRET]: "Create secret",
[EventType.UPDATE_SECRET]: "Update secret",
[EventType.DELETE_SECRET]: "Delete secret",
- [EventType.GET_WORKSPACE_KEY]: "Read project key",
+ [EventType.GET_PROJECT_KEY]: "Read project key",
[EventType.AUTHORIZE_INTEGRATION]: "Authorize integration",
[EventType.UPDATE_INTEGRATION_AUTH]: "Update integration auth",
[EventType.UNAUTHORIZE_INTEGRATION]: "Unauthorize integration",
@@ -45,8 +45,8 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.CREATE_ENVIRONMENT]: "Create environment",
[EventType.UPDATE_ENVIRONMENT]: "Update environment",
[EventType.DELETE_ENVIRONMENT]: "Delete environment",
- [EventType.ADD_WORKSPACE_MEMBER]: "Add member",
- [EventType.REMOVE_WORKSPACE_MEMBER]: "Remove member",
+ [EventType.ADD_PROJECT_MEMBER]: "Add member",
+ [EventType.REMOVE_PROJECT_MEMBER]: "Remove member",
[EventType.CREATE_FOLDER]: "Create folder",
[EventType.UPDATE_FOLDER]: "Update folder",
[EventType.DELETE_FOLDER]: "Delete folder",
@@ -58,8 +58,8 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.CREATE_SECRET_IMPORT]: "Create secret import",
[EventType.UPDATE_SECRET_IMPORT]: "Update secret import",
[EventType.DELETE_SECRET_IMPORT]: "Delete secret import",
- [EventType.UPDATE_USER_WORKSPACE_DENIED_PERMISSIONS]: "Update denied permissions",
- [EventType.UPDATE_USER_WORKSPACE_ROLE]: "Update user role",
+ [EventType.UPDATE_USER_PROJECT_DENIED_PERMISSIONS]: "Update denied permissions",
+ [EventType.UPDATE_USER_PROJECT_ROLE]: "Update user role",
[EventType.CREATE_CA]: "Create CA",
[EventType.GET_CA]: "Get CA",
[EventType.UPDATE_CA]: "Update CA",
@@ -132,6 +132,8 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.CREATE_APP_CONNECTION]: "Create App Connection",
[EventType.UPDATE_APP_CONNECTION]: "Update App Connection",
[EventType.DELETE_APP_CONNECTION]: "Delete App Connection",
+ [EventType.GET_APP_CONNECTION_USAGE]: "Get App Connection Usage",
+ [EventType.MIGRATE_APP_CONNECTION]: "Migrate App Connection",
[EventType.GET_SECRET_SYNCS]: "List secret syncs",
[EventType.GET_SECRET_SYNC]: "Get Secret Sync",
[EventType.CREATE_SECRET_SYNC]: "Create Secret Sync",
@@ -192,6 +194,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.UPDATE_IDENTITY_LDAP_AUTH]: "Updated LDAP Auth for identity",
[EventType.GET_IDENTITY_LDAP_AUTH]: "Retrieved LDAP Auth for identity",
[EventType.REVOKE_IDENTITY_LDAP_AUTH]: "Revoked LDAP Auth for identity",
+ [EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS]: "Clear LDAP Auth lockouts",
[EventType.SECRET_SCANNING_DATA_SOURCE_LIST]: "List Secret Scanning Data Sources",
[EventType.SECRET_SCANNING_DATA_SOURCE_CREATE]: "Create Secret Scanning Data Source",
@@ -219,7 +222,23 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.UPDATE_ORG]: "Update Organization",
[EventType.CREATE_PROJECT]: "Create Project",
[EventType.UPDATE_PROJECT]: "Update Project",
- [EventType.DELETE_PROJECT]: "Delete Project"
+ [EventType.DELETE_PROJECT]: "Delete Project",
+
+ [EventType.CREATE_SECRET_REMINDER]: "Create Secret Reminder",
+ [EventType.GET_SECRET_REMINDER]: "Get Secret Reminder",
+ [EventType.DELETE_SECRET_REMINDER]: "Delete Secret Reminder",
+
+ [EventType.DASHBOARD_LIST_SECRETS]: "Dashboard List Secrets",
+ [EventType.DASHBOARD_GET_SECRET_VALUE]: "Dashboard Get Secret Value",
+ [EventType.DASHBOARD_GET_SECRET_VERSION_VALUE]: "Dashboard Get Secret Version Value",
+
+ [EventType.CREATE_PROJECT_ROLE]: "Create Project Role",
+ [EventType.UPDATE_PROJECT_ROLE]: "Update Project Role",
+ [EventType.DELETE_PROJECT_ROLE]: "Delete Project Role",
+
+ [EventType.CREATE_ORG_ROLE]: "Create Org Role",
+ [EventType.UPDATE_ORG_ROLE]: "Update Org Role",
+ [EventType.DELETE_ORG_ROLE]: "Delete Org Role"
};
export const userAgentTypeToNameMap: { [K in UserAgentType]: string } = {
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 4fe8948dd8..52ccc3cdc0 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -26,7 +26,7 @@ export enum EventType {
CREATE_SECRET = "create-secret",
UPDATE_SECRET = "update-secret",
DELETE_SECRET = "delete-secret",
- GET_WORKSPACE_KEY = "get-workspace-key",
+ GET_PROJECT_KEY = "get-project-key",
AUTHORIZE_INTEGRATION = "authorize-integration",
UPDATE_INTEGRATION_AUTH = "update-integration-auth",
UNAUTHORIZE_INTEGRATION = "unauthorize-integration",
@@ -54,12 +54,13 @@ export enum EventType {
UPDATE_IDENTITY_LDAP_AUTH = "update-identity-ldap-auth",
GET_IDENTITY_LDAP_AUTH = "get-identity-ldap-auth",
REVOKE_IDENTITY_LDAP_AUTH = "revoke-identity-ldap-auth",
+ CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS = "clear-identity-ldap-auth-lockouts",
CREATE_ENVIRONMENT = "create-environment",
UPDATE_ENVIRONMENT = "update-environment",
DELETE_ENVIRONMENT = "delete-environment",
- ADD_WORKSPACE_MEMBER = "add-workspace-member",
- REMOVE_WORKSPACE_MEMBER = "remove-workspace-member",
+ ADD_PROJECT_MEMBER = "add-project-member",
+ REMOVE_PROJECT_MEMBER = "remove-project-member",
CREATE_FOLDER = "create-folder",
UPDATE_FOLDER = "update-folder",
DELETE_FOLDER = "delete-folder",
@@ -71,8 +72,8 @@ export enum EventType {
CREATE_SECRET_IMPORT = "create-secret-import",
UPDATE_SECRET_IMPORT = "update-secret-import",
DELETE_SECRET_IMPORT = "delete-secret-import",
- UPDATE_USER_WORKSPACE_ROLE = "update-user-workspace-role",
- UPDATE_USER_WORKSPACE_DENIED_PERMISSIONS = "update-user-workspace-denied-permissions",
+ UPDATE_USER_PROJECT_ROLE = "update-user-project-role",
+ UPDATE_USER_PROJECT_DENIED_PERMISSIONS = "update-user-project-denied-permissions",
CREATE_CA = "create-certificate-authority",
GET_CA = "get-certificate-authority",
UPDATE_CA = "update-certificate-authority",
@@ -140,6 +141,8 @@ export enum EventType {
CREATE_APP_CONNECTION = "create-app-connection",
UPDATE_APP_CONNECTION = "update-app-connection",
DELETE_APP_CONNECTION = "delete-app-connection",
+ GET_APP_CONNECTION_USAGE = "get-app-connection-usage",
+ MIGRATE_APP_CONNECTION = "migrate-app-connection",
GET_SECRET_SYNCS = "get-secret-syncs",
GET_SECRET_SYNC = "get-secret-sync",
CREATE_SECRET_SYNC = "create-secret-sync",
@@ -213,5 +216,21 @@ export enum EventType {
CREATE_PROJECT = "create-project",
UPDATE_PROJECT = "update-project",
- DELETE_PROJECT = "delete-project"
+ DELETE_PROJECT = "delete-project",
+
+ CREATE_SECRET_REMINDER = "create-secret-reminder",
+ GET_SECRET_REMINDER = "get-secret-reminder",
+ DELETE_SECRET_REMINDER = "delete-secret-reminder",
+
+ DASHBOARD_LIST_SECRETS = "dashboard-list-secrets",
+ DASHBOARD_GET_SECRET_VALUE = "dashboard-get-secret-value",
+ DASHBOARD_GET_SECRET_VERSION_VALUE = "dashboard-get-secret-version-value",
+
+ CREATE_PROJECT_ROLE = "create-project-role",
+ UPDATE_PROJECT_ROLE = "update-project-role",
+ DELETE_PROJECT_ROLE = "delete-project-role",
+
+ CREATE_ORG_ROLE = "create-org-role",
+ UPDATE_ORG_ROLE = "update-org-role",
+ DELETE_ORG_ROLE = "delete-org-role"
}
diff --git a/frontend/src/hooks/api/auditLogs/queries.tsx b/frontend/src/hooks/api/auditLogs/queries.tsx
index 8cb438c92d..5e25d81043 100644
--- a/frontend/src/hooks/api/auditLogs/queries.tsx
+++ b/frontend/src/hooks/api/auditLogs/queries.tsx
@@ -7,10 +7,10 @@ import { TReactQueryOptions } from "@app/types/reactQuery";
import { Actor, AuditLog, TGetAuditLogsFilter } from "./types";
export const auditLogKeys = {
- getAuditLogs: (workspaceId: string | null, filters: TGetAuditLogsFilter) =>
- [{ workspaceId, filters }, "audit-logs"] as const,
- getAuditLogActorFilterOpts: (workspaceId: string) =>
- [{ workspaceId }, "audit-log-actor-filters"] as const
+ getAuditLogs: (projectId: string | null, filters: TGetAuditLogsFilter) =>
+ [{ projectId, filters }, "audit-logs"] as const,
+ getAuditLogActorFilterOpts: (projectId: string) =>
+ [{ projectId }, "audit-log-actor-filters"] as const
};
export const useGetAuditLogs = (
@@ -56,12 +56,12 @@ export const useGetAuditLogs = (
});
};
-export const useGetAuditLogActorFilterOpts = (workspaceId: string) => {
+export const useGetAuditLogActorFilterOpts = (projectId: string) => {
return useQuery({
- queryKey: auditLogKeys.getAuditLogActorFilterOpts(workspaceId),
+ queryKey: auditLogKeys.getAuditLogActorFilterOpts(projectId),
queryFn: async () => {
const { data } = await apiRequest.get<{ actors: Actor[] }>(
- `/api/v1/workspace/${workspaceId}/audit-logs/filters/actors`
+ `/api/v1/projects/${projectId}/audit-logs/filters/actors`
);
return data.actors;
}
diff --git a/frontend/src/hooks/api/auditLogs/types.tsx b/frontend/src/hooks/api/auditLogs/types.tsx
index 1ca819e606..1bb321fa27 100644
--- a/frontend/src/hooks/api/auditLogs/types.tsx
+++ b/frontend/src/hooks/api/auditLogs/types.tsx
@@ -129,7 +129,7 @@ interface DeleteSecretEvent {
}
interface GetWorkspaceKeyEvent {
- type: EventType.GET_WORKSPACE_KEY;
+ type: EventType.GET_PROJECT_KEY;
metadata: {
keyId: string;
};
@@ -361,7 +361,7 @@ interface DeleteEnvironmentEvent {
}
interface AddWorkspaceMemberEvent {
- type: EventType.ADD_WORKSPACE_MEMBER;
+ type: EventType.ADD_PROJECT_MEMBER;
metadata: {
userId: string;
email: string;
@@ -369,7 +369,7 @@ interface AddWorkspaceMemberEvent {
}
interface RemoveWorkspaceMemberEvent {
- type: EventType.REMOVE_WORKSPACE_MEMBER;
+ type: EventType.REMOVE_PROJECT_MEMBER;
metadata: {
userId: string;
email: string;
@@ -500,7 +500,7 @@ interface DeleteSecretImportEvent {
}
interface UpdateUserRole {
- type: EventType.UPDATE_USER_WORKSPACE_ROLE;
+ type: EventType.UPDATE_USER_PROJECT_ROLE;
metadata: {
userId: string;
email: string;
@@ -510,7 +510,7 @@ interface UpdateUserRole {
}
interface UpdateUserDeniedPermissions {
- type: EventType.UPDATE_USER_WORKSPACE_DENIED_PERMISSIONS;
+ type: EventType.UPDATE_USER_PROJECT_DENIED_PERMISSIONS;
metadata: {
userId: string;
email: string;
@@ -874,6 +874,13 @@ interface IntegrationSyncedEvent {
};
}
+interface ClearIdentityLdapAuthLockoutsEvent {
+ type: EventType.CLEAR_IDENTITY_LDAP_AUTH_LOCKOUTS;
+ metadata: {
+ identityId: string;
+ };
+}
+
export type Event =
| GetSecretsEvent
| GetSecretEvent
@@ -958,7 +965,8 @@ export type Event =
| GetCertificateTemplateEstConfig
| UpdateProjectWorkflowIntegrationConfig
| GetProjectWorkflowIntegrationConfig
- | IntegrationSyncedEvent;
+ | IntegrationSyncedEvent
+ | ClearIdentityLdapAuthLockoutsEvent;
export type AuditLog = {
id: string;
diff --git a/frontend/src/hooks/api/auth/queries.tsx b/frontend/src/hooks/api/auth/queries.tsx
index cb7e3f64c7..d41a4d115a 100644
--- a/frontend/src/hooks/api/auth/queries.tsx
+++ b/frontend/src/hooks/api/auth/queries.tsx
@@ -5,8 +5,8 @@ import { apiRequest } from "@app/config/request";
import { SessionStorageKeys } from "@app/const";
import { organizationKeys } from "../organization/queries";
+import { projectKeys } from "../projects";
import { setAuthToken } from "../reactQuery";
-import { workspaceKeys } from "../workspace";
import {
CompleteAccountDTO,
CompleteAccountSignupDTO,
@@ -101,7 +101,7 @@ export const useSelectOrganization = () => {
},
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: [organizationKeys.getUserOrganizations, workspaceKeys.getAllUserWorkspace]
+ queryKey: [organizationKeys.getUserOrganizations, projectKeys.getAllUserProjects]
});
}
});
diff --git a/frontend/src/hooks/api/ca/mutations.tsx b/frontend/src/hooks/api/ca/mutations.tsx
index f6204d4fc4..a14a0244b9 100644
--- a/frontend/src/hooks/api/ca/mutations.tsx
+++ b/frontend/src/hooks/api/ca/mutations.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import { CaType } from "./enums";
import { caKeys } from "./queries";
import {
@@ -118,8 +118,8 @@ export const useImportCaCertificate = (projectId: string) => {
);
return data;
},
- onSuccess: (_, { caId, projectSlug }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceCas({ projectSlug }) });
+ onSuccess: (_, { caId }) => {
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectCas({ projectId }) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
queryClient.invalidateQueries({
@@ -142,7 +142,7 @@ export const useCreateCertificate = () => {
},
onSuccess: (_, { projectSlug }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.forWorkspaceCertificates(projectSlug)
+ queryKey: projectKeys.forProjectCertificates(projectSlug)
});
}
});
@@ -158,8 +158,8 @@ export const useRenewCa = () => {
);
return data;
},
- onSuccess: (_, { caId, projectSlug }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceCas({ projectSlug }) });
+ onSuccess: ({ projectId }, { caId }) => {
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectCas({ projectId }) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaById(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCert(caId) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCerts(caId) });
diff --git a/frontend/src/hooks/api/ca/types.ts b/frontend/src/hooks/api/ca/types.ts
index 336688ca4d..0443dd5e99 100644
--- a/frontend/src/hooks/api/ca/types.ts
+++ b/frontend/src/hooks/api/ca/types.ts
@@ -182,4 +182,5 @@ export type TRenewCaResponse = {
certificate: string;
certificateChain: string;
serialNumber: string;
+ projectId: string;
};
diff --git a/frontend/src/hooks/api/certificateTemplates/mutations.tsx b/frontend/src/hooks/api/certificateTemplates/mutations.tsx
index d1069e7e67..24a7d0e5f2 100644
--- a/frontend/src/hooks/api/certificateTemplates/mutations.tsx
+++ b/frontend/src/hooks/api/certificateTemplates/mutations.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { caKeys } from "../ca/queries";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import { certTemplateKeys } from "./queries";
import {
TCertificateTemplate,
@@ -29,7 +29,7 @@ export const useCreateCertTemplate = () => {
},
onSuccess: ({ caId }, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceCertificateTemplates(projectId)
+ queryKey: projectKeys.getProjectCertificateTemplates(projectId)
});
queryClient.invalidateQueries({ queryKey: caKeys.getCaCertTemplates(caId) });
}
@@ -49,7 +49,7 @@ export const useUpdateCertTemplate = () => {
},
onSuccess: ({ caId }, { projectId, id }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceCertificateTemplates(projectId)
+ queryKey: projectKeys.getProjectCertificateTemplates(projectId)
});
queryClient.invalidateQueries({ queryKey: certTemplateKeys.getCertTemplateById(id) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCertTemplates(caId) });
@@ -68,7 +68,7 @@ export const useDeleteCertTemplate = () => {
},
onSuccess: ({ caId }, { projectId, id }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceCertificateTemplates(projectId)
+ queryKey: projectKeys.getProjectCertificateTemplates(projectId)
});
queryClient.invalidateQueries({ queryKey: certTemplateKeys.getCertTemplateById(id) });
queryClient.invalidateQueries({ queryKey: caKeys.getCaCertTemplates(caId) });
diff --git a/frontend/src/hooks/api/certificates/mutations.tsx b/frontend/src/hooks/api/certificates/mutations.tsx
index 12f8e834bd..77a3dab72c 100644
--- a/frontend/src/hooks/api/certificates/mutations.tsx
+++ b/frontend/src/hooks/api/certificates/mutations.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { pkiSubscriberKeys } from "../pkiSubscriber/queries";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import {
TCertificate,
TDeleteCertDTO,
@@ -25,7 +25,7 @@ export const useDeleteCert = () => {
},
onSuccess: (_, { projectSlug }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.forWorkspaceCertificates(projectSlug)
+ queryKey: projectKeys.forProjectCertificates(projectSlug)
});
}
});
@@ -47,7 +47,7 @@ export const useRevokeCert = () => {
},
onSuccess: (_, { projectSlug }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.forWorkspaceCertificates(projectSlug)
+ queryKey: projectKeys.forProjectCertificates(projectSlug)
});
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.allPkiSubscriberCertificates()
@@ -68,7 +68,7 @@ export const useImportCertificate = () => {
},
onSuccess: (_, { projectSlug }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.forWorkspaceCertificates(projectSlug)
+ queryKey: projectKeys.forProjectCertificates(projectSlug)
});
}
});
diff --git a/frontend/src/hooks/api/dashboard/queries.tsx b/frontend/src/hooks/api/dashboard/queries.tsx
index fde3a5ee31..3866c63373 100644
--- a/frontend/src/hooks/api/dashboard/queries.tsx
+++ b/frontend/src/hooks/api/dashboard/queries.tsx
@@ -1,5 +1,5 @@
import { useCallback } from "react";
-import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+import { useQuery, useQueryClient, UseQueryOptions } from "@tanstack/react-query";
import { AxiosError } from "axios";
import { apiRequest } from "@app/config/request";
@@ -10,13 +10,15 @@ import {
DashboardProjectSecretsOverview,
DashboardProjectSecretsOverviewResponse,
DashboardSecretsOrderBy,
+ DashboardSecretValue,
TDashboardProjectSecretsQuickSearch,
TDashboardProjectSecretsQuickSearchResponse,
TGetAccessibleSecretsDTO,
TGetDashboardProjectSecretsByKeys,
TGetDashboardProjectSecretsDetailsDTO,
TGetDashboardProjectSecretsOverviewDTO,
- TGetDashboardProjectSecretsQuickSearchDTO
+ TGetDashboardProjectSecretsQuickSearchDTO,
+ TGetSecretValueDTO
} from "@app/hooks/api/dashboard/types";
import { OrderByDirection } from "@app/hooks/api/generic/types";
import { mergePersonalSecrets } from "@app/hooks/api/secrets/queries";
@@ -73,6 +75,15 @@ export const dashboardKeys = {
...dashboardKeys.all(),
"accessible-secrets",
{ projectId, secretPath, environment, filterByAction }
+ ] as const,
+ getSecretValuesRoot: () => [...dashboardKeys.all(), "secrets-values"] as const,
+ getSecretValue: ({ environment, secretPath, secretKey, isOverride }: TGetSecretValueDTO) =>
+ [
+ ...dashboardKeys.getSecretValuesRoot(),
+ environment,
+ secretPath,
+ secretKey,
+ isOverride
] as const
};
@@ -174,6 +185,8 @@ export const useGetProjectSecretsOverview = (
"queryKey" | "queryFn"
>
) => {
+ const queryClient = useQueryClient();
+
return useQuery({
...options,
// wait for all values to be available
@@ -193,8 +206,8 @@ export const useGetProjectSecretsOverview = (
includeSecretRotations,
environments
}),
- queryFn: () =>
- fetchProjectSecretsOverview({
+ queryFn: async () => {
+ const resp = fetchProjectSecretsOverview({
secretPath,
search,
limit,
@@ -208,7 +221,14 @@ export const useGetProjectSecretsOverview = (
includeDynamicSecrets,
includeSecretRotations,
environments
- }),
+ });
+
+ queryClient.invalidateQueries({
+ queryKey: dashboardKeys.getSecretValuesRoot()
+ });
+
+ return resp;
+ },
select: useCallback((data: Awaited<ReturnType<typeof fetchProjectSecretsOverview>>) => {
const { secrets, secretRotations, ...select } = data;
const uniqueSecrets = secrets ? unique(secrets, (i) => i.secretKey) : [];
@@ -254,7 +274,6 @@ export const useGetProjectSecretsDetails = (
search = "",
includeSecrets,
includeFolders,
- viewSecretValue,
includeImports,
includeDynamicSecrets,
includeSecretRotations,
@@ -270,6 +289,8 @@ export const useGetProjectSecretsDetails = (
"queryKey" | "queryFn"
>
) => {
+ const queryClient = useQueryClient();
+
return useQuery({
...options,
// wait for all values to be available
@@ -286,7 +307,6 @@ export const useGetProjectSecretsDetails = (
limit,
orderBy,
orderDirection,
- viewSecretValue,
offset,
projectId,
environment,
@@ -297,14 +317,13 @@ export const useGetProjectSecretsDetails = (
includeSecretRotations,
tags
}),
- queryFn: () =>
- fetchProjectSecretsDetails({
+ queryFn: async () => {
+ const resp = await fetchProjectSecretsDetails({
secretPath,
search,
limit,
orderBy,
orderDirection,
- viewSecretValue,
offset,
projectId,
environment,
@@ -314,7 +333,14 @@ export const useGetProjectSecretsDetails = (
includeDynamicSecrets,
includeSecretRotations,
tags
- }),
+ });
+
+ queryClient.invalidateQueries({
+ queryKey: dashboardKeys.getSecretValuesRoot()
+ });
+
+ return resp;
+ },
select: useCallback(
(data: Awaited<ReturnType<typeof fetchProjectSecretsDetails>>) => ({
...data,
@@ -471,3 +497,31 @@ export const useGetAccessibleSecrets = ({
fetchAccessibleSecrets({ projectId, secretPath, environment, filterByAction, recursive })
});
};
+
+export const fetchSecretValue = async (params: TGetSecretValueDTO) => {
+ const { data } = await apiRequest.get<DashboardSecretValue>("/api/v1/dashboard/secret-value", {
+ params
+ });
+
+ return data;
+};
+
+export const useGetSecretValue = (
+ params: TGetSecretValueDTO,
+ options?: Omit<
+ UseQueryOptions<
+ DashboardSecretValue,
+ unknown,
+ DashboardSecretValue,
+ ReturnType<typeof dashboardKeys.getSecretValue>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: dashboardKeys.getSecretValue(params),
+ queryFn: async () => fetchSecretValue(params),
+ staleTime: 1000 * 60,
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/dashboard/types.ts b/frontend/src/hooks/api/dashboard/types.ts
index fbd5107cde..5a7a519b73 100644
--- a/frontend/src/hooks/api/dashboard/types.ts
+++ b/frontend/src/hooks/api/dashboard/types.ts
@@ -112,7 +112,6 @@ export type TGetDashboardProjectSecretsDetailsDTO = Omit<
TGetDashboardProjectSecretsOverviewDTO,
"environments"
> & {
- viewSecretValue: boolean;
environment: string;
includeImports?: boolean;
tags: Record<string, boolean>;
@@ -156,3 +155,21 @@ export type TGetAccessibleSecretsDTO = {
| ProjectPermissionSecretActions.DescribeSecret
| ProjectPermissionSecretActions.ReadValue;
};
+
+export type TGetSecretValueDTO = {
+ projectId: string;
+ secretKey: string;
+ environment: string;
+ secretPath: string;
+ isOverride?: boolean;
+};
+
+export type DashboardSecretValue =
+ | {
+ value: string;
+ valueOverride: undefined;
+ }
+ | {
+ value: undefined;
+ valueOverride: string;
+ };
diff --git a/frontend/src/hooks/api/dynamicSecret/types.ts b/frontend/src/hooks/api/dynamicSecret/types.ts
index 289bc1d043..03e018dae8 100644
--- a/frontend/src/hooks/api/dynamicSecret/types.ts
+++ b/frontend/src/hooks/api/dynamicSecret/types.ts
@@ -59,6 +59,11 @@ export enum DynamicSecretAwsIamAuth {
IRSA = "irsa"
}
+export enum DynamicSecretAwsIamCredentialType {
+ IamUser = "iam-user",
+ TemporaryCredentials = "temporary-credentials"
+}
+
export type TDynamicSecretProvider =
| {
type: DynamicSecretProviders.SqlDatabase;
@@ -97,6 +102,7 @@ export type TDynamicSecretProvider =
inputs:
| {
method: DynamicSecretAwsIamAuth.AccessKey;
+ credentialType: DynamicSecretAwsIamCredentialType;
accessKey: string;
secretAccessKey: string;
region: string;
@@ -107,6 +113,7 @@ export type TDynamicSecretProvider =
}
| {
method: DynamicSecretAwsIamAuth.AssumeRole;
+ credentialType: DynamicSecretAwsIamCredentialType;
roleArn: string;
region: string;
awsPath?: string;
@@ -116,6 +123,7 @@ export type TDynamicSecretProvider =
}
| {
method: DynamicSecretAwsIamAuth.IRSA;
+ credentialType: DynamicSecretAwsIamCredentialType;
region: string;
awsPath?: string;
policyDocument?: string;
diff --git a/frontend/src/hooks/api/folderCommits/queries.tsx b/frontend/src/hooks/api/folderCommits/queries.tsx
index 1bca7ce9a3..4d37a4f7bd 100644
--- a/frontend/src/hooks/api/folderCommits/queries.tsx
+++ b/frontend/src/hooks/api/folderCommits/queries.tsx
@@ -7,27 +7,27 @@ import { Commit, CommitHistoryItem, CommitWithChanges, RollbackPreview } from ".
export const commitKeys = {
count: ({
- workspaceId,
+ projectId,
environment,
directory
}: {
- workspaceId: string;
+ projectId: string;
environment: string;
directory?: string;
- }) => [{ workspaceId, environment, directory }, "folder-commits-count"] as const,
+ }) => [{ projectId, environment, directory }, "folder-commits-count"] as const,
history: ({
- workspaceId,
+ projectId,
environment,
directory
}: {
- workspaceId: string;
+ projectId: string;
environment: string;
directory?: string;
- }) => [{ workspaceId, environment, directory }, "folder-commits"] as const,
+ }) => [{ projectId, environment, directory }, "folder-commits"] as const,
- details: ({ workspaceId, commitId }: { workspaceId: string; commitId: string }) =>
- [{ workspaceId, commitId }, "commit-details"] as const,
+ details: ({ projectId, commitId }: { projectId: string; commitId: string }) =>
+ [{ projectId, commitId }, "commit-details"] as const,
rollbackPreview: ({
folderId,
@@ -45,11 +45,11 @@ export const commitKeys = {
};
const fetchFolderCommitsCount = async ({
- workspaceId,
+ projectId,
environment,
directory
}: {
- workspaceId: string;
+ projectId: string;
environment: string;
directory?: string;
}) => {
@@ -59,7 +59,7 @@ const fetchFolderCommitsCount = async ({
params: {
environment,
path: directory,
- projectId: workspaceId
+ projectId
}
}
);
@@ -67,7 +67,7 @@ const fetchFolderCommitsCount = async ({
};
const fetchFolderCommitHistory = async (
- workspaceId: string,
+ projectId: string,
environment: string,
directory: string,
offset: number = 0,
@@ -87,7 +87,7 @@ const fetchFolderCommitHistory = async (
params: {
environment,
path: directory,
- projectId: workspaceId,
+ projectId,
offset,
limit,
search,
@@ -97,12 +97,12 @@ const fetchFolderCommitHistory = async (
return res.data;
};
-export const fetchCommitDetails = async (workspaceId: string, commitId: string) => {
+export const fetchCommitDetails = async (projectId: string, commitId: string) => {
const { data } = await apiRequest.get<CommitWithChanges>(
`/api/v1/pit/commits/${commitId}/changes`,
{
params: {
- projectId: workspaceId
+ projectId
}
}
);
@@ -113,7 +113,7 @@ export const fetchRollbackPreview = async (
folderId: string,
commitId: string,
envSlug: string,
- workspaceId: string,
+ projectId: string,
deepRollback: boolean,
secretPath: string
): Promise<RollbackPreview[]> => {
@@ -125,7 +125,7 @@ export const fetchRollbackPreview = async (
environment: envSlug,
deepRollback,
secretPath,
- projectId: workspaceId
+ projectId
}
}
);
@@ -135,7 +135,7 @@ export const fetchRollbackPreview = async (
const fetchRollback = async (
folderId: string,
commitId: string,
- workspaceId: string,
+ projectId: string,
deepRollback: boolean,
message?: string,
envSlug?: string
@@ -147,17 +147,17 @@ const fetchRollback = async (
deepRollback,
message,
environment: envSlug,
- projectId: workspaceId
+ projectId
}
);
return data;
};
-const fetchRevert = async (commitId: string, workspaceId: string) => {
+const fetchRevert = async (commitId: string, projectId: string) => {
const { data } = await apiRequest.post<{ success: boolean; message: string }>(
`/api/v1/pit/commits/${commitId}/revert`,
{
- projectId: workspaceId
+ projectId
}
);
return data;
@@ -180,9 +180,9 @@ export const useCommitRevert = ({
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [
- commitKeys.details({ workspaceId: projectId, commitId }),
- commitKeys.history({ workspaceId: projectId, environment, directory }),
- commitKeys.count({ workspaceId: projectId, environment, directory })
+ commitKeys.details({ projectId, commitId }),
+ commitKeys.history({ projectId, environment, directory }),
+ commitKeys.count({ projectId, environment, directory })
]
});
}
@@ -190,7 +190,7 @@ export const useCommitRevert = ({
};
export const useCommitRollback = ({
- workspaceId,
+ projectId,
commitId,
folderId,
deepRollback,
@@ -198,7 +198,7 @@ export const useCommitRollback = ({
directory,
envSlug
}: {
- workspaceId: string;
+ projectId: string;
commitId: string;
folderId: string;
deepRollback: boolean;
@@ -209,13 +209,13 @@ export const useCommitRollback = ({
const queryClient = useQueryClient();
return useMutation({
mutationFn: (message: string) =>
- fetchRollback(folderId, commitId, workspaceId, deepRollback, message, envSlug),
+ fetchRollback(folderId, commitId, projectId, deepRollback, message, envSlug),
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: [
- commitKeys.details({ workspaceId, commitId }),
- commitKeys.history({ workspaceId, environment, directory }),
- commitKeys.count({ workspaceId, environment, directory })
+ commitKeys.details({ projectId, commitId }),
+ commitKeys.history({ projectId, environment, directory }),
+ commitKeys.count({ projectId, environment, directory })
]
});
}
@@ -223,31 +223,31 @@ export const useCommitRollback = ({
};
export const useGetFolderCommitsCount = ({
- workspaceId,
+ projectId,
environment,
directory,
isPaused
}: {
- workspaceId: string;
+ projectId: string;
environment: string;
directory: string;
isPaused?: boolean;
}) =>
useQuery({
- enabled: Boolean(workspaceId && environment) && !isPaused,
- queryKey: commitKeys.count({ workspaceId, environment, directory }),
- queryFn: () => fetchFolderCommitsCount({ workspaceId, environment, directory })
+ enabled: Boolean(projectId && environment) && !isPaused,
+ queryKey: commitKeys.count({ projectId, environment, directory }),
+ queryFn: () => fetchFolderCommitsCount({ projectId, environment, directory })
});
export const useGetFolderCommitHistory = ({
- workspaceId,
+ projectId,
environment,
directory,
limit = 20,
search,
sort = "desc"
}: {
- workspaceId: string;
+ projectId: string;
environment: string;
directory: string;
limit?: number;
@@ -256,10 +256,10 @@ export const useGetFolderCommitHistory = ({
}) => {
return useInfiniteQuery({
initialPageParam: 0,
- queryKey: [commitKeys.history({ workspaceId, environment, directory }), limit, search, sort],
+ queryKey: [commitKeys.history({ projectId, environment, directory }), limit, search, sort],
queryFn: ({ pageParam }) =>
- fetchFolderCommitHistory(workspaceId, environment, directory, pageParam, limit, search, sort),
- enabled: Boolean(workspaceId && environment),
+ fetchFolderCommitHistory(projectId, environment, directory, pageParam, limit, search, sort),
+ enabled: Boolean(projectId && environment),
select: (data) => {
return (data?.pages ?? [])
?.map((page) => page.commits)
@@ -280,11 +280,11 @@ export const useGetFolderCommitHistory = ({
});
};
-export const useGetCommitDetails = (workspaceId: string, commitId: string) => {
+export const useGetCommitDetails = (projectId: string, commitId: string) => {
return useQuery({
- queryKey: commitKeys.details({ workspaceId, commitId }),
- queryFn: () => fetchCommitDetails(workspaceId, commitId),
- enabled: Boolean(workspaceId) && Boolean(commitId)
+ queryKey: commitKeys.details({ projectId, commitId }),
+ queryFn: () => fetchCommitDetails(projectId, commitId),
+ enabled: Boolean(projectId) && Boolean(commitId)
});
};
diff --git a/frontend/src/hooks/api/groups/queries.tsx b/frontend/src/hooks/api/groups/queries.tsx
index 6fbe0ec130..ca524066f0 100644
--- a/frontend/src/hooks/api/groups/queries.tsx
+++ b/frontend/src/hooks/api/groups/queries.tsx
@@ -138,7 +138,7 @@ export const useListProjectGroupUsers = ({
});
const { data } = await apiRequest.get<{ users: TGroupUser[]; totalCount: number }>(
- `/api/v2/workspace/${projectId}/groups/${id}/users`,
+ `/api/v1/projects/${projectId}/groups/${id}/users`,
{
params
}
diff --git a/frontend/src/hooks/api/identities/mutations.tsx b/frontend/src/hooks/api/identities/mutations.tsx
index 5189f187c4..4ada1fb9bb 100644
--- a/frontend/src/hooks/api/identities/mutations.tsx
+++ b/frontend/src/hooks/api/identities/mutations.tsx
@@ -18,6 +18,7 @@ import {
AddIdentityTlsCertAuthDTO,
AddIdentityTokenAuthDTO,
AddIdentityUniversalAuthDTO,
+ ClearIdentityLdapAuthLockoutsDTO,
ClearIdentityUniversalAuthLockoutsDTO,
ClientSecretData,
CreateIdentityDTO,
@@ -1432,7 +1433,11 @@ export const useAddIdentityLdapAuth = () => {
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
- accessTokenTrustedIps
+ accessTokenTrustedIps,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
}) => {
const { data } = await apiRequest.post<{ identityLdapAuth: IdentityLdapAuth }>(
`/api/v1/auth/ldap-auth/identities/${identityId}`,
@@ -1448,7 +1453,11 @@ export const useAddIdentityLdapAuth = () => {
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
- accessTokenTrustedIps
+ accessTokenTrustedIps,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
}
);
return data.identityLdapAuth;
@@ -1481,7 +1490,11 @@ export const useUpdateIdentityLdapAuth = () => {
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
- accessTokenTrustedIps
+ accessTokenTrustedIps,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
}) => {
const { data } = await apiRequest.patch<{ identityLdapAuth: IdentityLdapAuth }>(
`/api/v1/auth/ldap-auth/identities/${identityId}`,
@@ -1497,7 +1510,11 @@ export const useUpdateIdentityLdapAuth = () => {
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
- accessTokenTrustedIps
+ accessTokenTrustedIps,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
}
);
return data.identityLdapAuth;
@@ -1532,3 +1549,22 @@ export const useDeleteIdentityLdapAuth = () => {
}
});
};
+
+export const useClearIdentityLdapAuthLockouts = () => {
+ const queryClient = useQueryClient();
+ return useMutation<number, object, ClearIdentityLdapAuthLockoutsDTO>({
+ mutationFn: async ({ identityId }) => {
+ const {
+ data: { deleted }
+ } = await apiRequest.post<{ deleted: number }>(
+ `/api/v1/auth/ldap-auth/identities/${identityId}/clear-lockouts`
+ );
+ return deleted;
+ },
+ onSuccess: (_, { identityId }) => {
+ queryClient.invalidateQueries({
+ queryKey: identitiesKeys.getIdentityLdapAuth(identityId)
+ });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/identities/types.ts b/frontend/src/hooks/api/identities/types.ts
index 36f9eae4ea..99e3771434 100644
--- a/frontend/src/hooks/api/identities/types.ts
+++ b/frontend/src/hooks/api/identities/types.ts
@@ -1,7 +1,7 @@
import { OrderByDirection } from "../generic/types";
import { OrgIdentityOrderBy } from "../organization/types";
+import { Project, ProjectUserMembershipTemporaryMode } from "../projects/types";
import { TOrgRole } from "../roles/types";
-import { ProjectUserMembershipTemporaryMode, Workspace } from "../workspace/types";
import { IdentityAuthMethod, IdentityJwtConfigurationType } from "./enums";
export type IdentityTrustedIp = {
@@ -54,7 +54,7 @@ export type IdentityMembershipOrg = {
export type IdentityMembership = {
id: string;
identity: Identity;
- project: Pick<Workspace, "id" | "name" | "type">;
+ project: Pick<Project, "id" | "name" | "type">;
roles: Array<
{
id: string;
@@ -603,6 +603,11 @@ export type AddIdentityLdapAuthDTO = {
accessTokenTrustedIps: {
ipAddress: string;
}[];
+
+ lockoutEnabled: boolean;
+ lockoutThreshold: number;
+ lockoutDurationSeconds: number;
+ lockoutCounterResetSeconds: number;
};
export type UpdateIdentityLdapAuthDTO = {
@@ -625,6 +630,11 @@ export type UpdateIdentityLdapAuthDTO = {
accessTokenTrustedIps?: {
ipAddress: string;
}[];
+
+ lockoutEnabled?: boolean;
+ lockoutThreshold?: number;
+ lockoutDurationSeconds?: number;
+ lockoutCounterResetSeconds?: number;
};
export type DeleteIdentityLdapAuthDTO = {
@@ -650,6 +660,15 @@ export type IdentityLdapAuth = {
accessTokenMaxTTL: number;
accessTokenNumUsesLimit: number;
accessTokenTrustedIps: IdentityTrustedIp[];
+
+ lockoutEnabled: boolean;
+ lockoutThreshold: number;
+ lockoutDurationSeconds: number;
+ lockoutCounterResetSeconds: number;
+};
+
+export type ClearIdentityLdapAuthLockoutsDTO = {
+ identityId: string;
};
export type AddIdentityTokenAuthDTO = {
diff --git a/frontend/src/hooks/api/index.tsx b/frontend/src/hooks/api/index.tsx
index 78dcd3b793..d65c7e72c2 100644
--- a/frontend/src/hooks/api/index.tsx
+++ b/frontend/src/hooks/api/index.tsx
@@ -20,7 +20,6 @@ export * from "./identityProjectAdditionalPrivilege";
export * from "./incidentContacts";
export * from "./integrationAuth";
export * from "./integrations";
-export * from "./keys";
export * from "./kms";
export * from "./ldapConfig";
export * from "./oidcConfig";
@@ -29,6 +28,7 @@ export * from "./organization";
export * from "./pkiAlerts";
export * from "./pkiCollections";
export * from "./pkiSubscriber";
+export * from "./projects";
export * from "./projectUserAdditionalPrivilege";
export * from "./rateLimit";
export * from "./roles";
@@ -54,4 +54,3 @@ export * from "./trustedIps";
export * from "./users";
export * from "./webhooks";
export * from "./workflowIntegrations";
-export * from "./workspace";
diff --git a/frontend/src/hooks/api/integrationAuth/queries.tsx b/frontend/src/hooks/api/integrationAuth/queries.tsx
index 044ec8d2af..f6c936480a 100644
--- a/frontend/src/hooks/api/integrationAuth/queries.tsx
+++ b/frontend/src/hooks/api/integrationAuth/queries.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TReactQueryOptions } from "@app/types/reactQuery";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import {
App,
BitbucketEnvironment,
@@ -970,7 +970,7 @@ export const useAuthorizeIntegration = () => {
},
onSuccess: (res) => {
queryClient.invalidateQueries({
- queryKey: { queryKey: workspaceKeys.getWorkspaceAuthorization(res.workspace) }
+ queryKey: { queryKey: projectKeys.getProjectAuthorization(res.workspace) }
});
}
});
@@ -1016,7 +1016,7 @@ export const useSaveIntegrationAccessToken = () => {
},
onSuccess: (res) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceAuthorization(res.workspace)
+ queryKey: projectKeys.getProjectAuthorization(res.workspace)
});
}
});
@@ -1035,10 +1035,10 @@ export const useDeleteIntegrationAuths = () => {
),
onSuccess: (_, { workspaceId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceAuthorization(workspaceId)
+ queryKey: projectKeys.getProjectAuthorization(workspaceId)
});
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIntegrations(workspaceId)
+ queryKey: projectKeys.getProjectIntegrations(workspaceId)
});
}
});
@@ -1052,10 +1052,10 @@ export const useDeleteIntegrationAuth = () => {
mutationFn: ({ id }) => apiRequest.delete(`/api/v1/integration-auth/${id}`),
onSuccess: (_, { workspaceId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceAuthorization(workspaceId)
+ queryKey: projectKeys.getProjectAuthorization(workspaceId)
});
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIntegrations(workspaceId)
+ queryKey: projectKeys.getProjectIntegrations(workspaceId)
});
}
});
diff --git a/frontend/src/hooks/api/integrations/queries.tsx b/frontend/src/hooks/api/integrations/queries.tsx
index a439f8caa1..69519a5a48 100644
--- a/frontend/src/hooks/api/integrations/queries.tsx
+++ b/frontend/src/hooks/api/integrations/queries.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQuery, useQueryClient, UseQueryOptions } from "@tanstac
import { createNotification } from "@app/components/notifications";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import {
IntegrationMetadataSyncMode,
TCloudIntegration,
@@ -121,7 +121,7 @@ export const useCreateIntegration = () => {
},
onSuccess: (res) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIntegrations(res.workspace)
+ queryKey: projectKeys.getProjectIntegrations(res.workspace)
});
}
});
@@ -141,10 +141,10 @@ export const useDeleteIntegration = () => {
),
onSuccess: (_, { workspaceId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIntegrations(workspaceId)
+ queryKey: projectKeys.getProjectIntegrations(workspaceId)
});
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceAuthorization(workspaceId)
+ queryKey: projectKeys.getProjectAuthorization(workspaceId)
});
}
});
diff --git a/frontend/src/hooks/api/keys/index.tsx b/frontend/src/hooks/api/keys/index.tsx
deleted file mode 100644
index cd4f0aea8c..0000000000
--- a/frontend/src/hooks/api/keys/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { useGetUserWsKey, useUploadWsKey } from "./queries";
diff --git a/frontend/src/hooks/api/keys/queries.tsx b/frontend/src/hooks/api/keys/queries.tsx
deleted file mode 100644
index f902f85d37..0000000000
--- a/frontend/src/hooks/api/keys/queries.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useMutation, useQuery } from "@tanstack/react-query";
-
-import { apiRequest } from "@app/config/request";
-
-import { UploadWsKeyDTO, UserWsKeyPair } from "./types";
-
-const encKeyKeys = {
- getUserWorkspaceKey: (workspaceID: string) => ["workspace-key-pair", { workspaceID }] as const
-};
-
-export const fetchUserWsKey = async (projectId: string) => {
- const { data } = await apiRequest.get<UserWsKeyPair>(
- `/api/v2/workspace/${projectId}/encrypted-key`
- );
-
- return data;
-};
-
-export const useGetUserWsKey = (workspaceID: string) =>
- useQuery({
- queryKey: encKeyKeys.getUserWorkspaceKey(workspaceID),
- queryFn: () => fetchUserWsKey(workspaceID),
- enabled: Boolean(workspaceID)
- });
-
-// mutations
-export const uploadWsKey = async ({ workspaceId, userId, encryptedKey, nonce }: UploadWsKeyDTO) => {
- return apiRequest.post(`/api/v1/workspace/${workspaceId}/key`, {
- key: { userId, encryptedKey, nonce }
- });
-};
-
-export const useUploadWsKey = () =>
- useMutation<object, object, UploadWsKeyDTO>({
- mutationFn: async ({ encryptedKey, nonce, userId, workspaceId }) => {
- return uploadWsKey({
- workspaceId,
- userId,
- encryptedKey,
- nonce
- });
- }
- });
diff --git a/frontend/src/hooks/api/keys/types.ts b/frontend/src/hooks/api/keys/types.ts
deleted file mode 100644
index fc455deaf6..0000000000
--- a/frontend/src/hooks/api/keys/types.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-export type UserWsKeyPair = {
- id: string;
- encryptedKey: string;
- nonce: string;
- sender: Sender;
- receiver: string;
- workspace: string;
- createdAt: string;
- updatedAt: string;
- __v: number;
-};
-
-export type Sender = {
- id: string;
- email: string;
- createdAt: string;
- updatedAt: string;
- __v: number;
- firstName: string;
- lastName: string;
- publicKey: string;
-};
-
-export type UploadWsKeyDTO = {
- userId: string;
- encryptedKey: string;
- nonce: string;
- workspaceId: string;
-};
diff --git a/frontend/src/hooks/api/kms/mutations.tsx b/frontend/src/hooks/api/kms/mutations.tsx
index 2bf27bf6a0..4fb0a5af5b 100644
--- a/frontend/src/hooks/api/kms/mutations.tsx
+++ b/frontend/src/hooks/api/kms/mutations.tsx
@@ -75,7 +75,7 @@ export const useUpdateProjectKms = (projectId: string) => {
mutationFn: async (
updatedData: { type: KmsType.Internal } | { type: KmsType.External; kmsId: string }
) => {
- const { data } = await apiRequest.patch(`/api/v1/workspace/${projectId}/kms`, {
+ const { data } = await apiRequest.patch(`/api/v1/projects/${projectId}/kms`, {
kms: updatedData
});
@@ -91,7 +91,7 @@ export const useLoadProjectKmsBackup = (projectId: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (backup: string) => {
- const { data } = await apiRequest.post(`/api/v1/workspace/${projectId}/kms/backup`, {
+ const { data } = await apiRequest.post(`/api/v1/projects/${projectId}/kms/backup`, {
backup
});
diff --git a/frontend/src/hooks/api/kms/queries.tsx b/frontend/src/hooks/api/kms/queries.tsx
index 9efa9cc512..97d25376ce 100644
--- a/frontend/src/hooks/api/kms/queries.tsx
+++ b/frontend/src/hooks/api/kms/queries.tsx
@@ -49,7 +49,7 @@ export const useGetActiveProjectKms = (projectId: string) => {
name: string;
isExternal: string;
};
- }>(`/api/v1/workspace/${projectId}/kms`);
+ }>(`/api/v1/projects/${projectId}/kms`);
return secretManagerKmsKey;
}
});
@@ -58,7 +58,7 @@ export const useGetActiveProjectKms = (projectId: string) => {
export const fetchProjectKmsBackup = async (projectId: string) => {
const { data } = await apiRequest.get<{
secretManager: string;
- }>(`/api/v1/workspace/${projectId}/kms/backup`);
+ }>(`/api/v1/projects/${projectId}/kms/backup`);
return data;
};
diff --git a/frontend/src/hooks/api/migration/mutations.tsx b/frontend/src/hooks/api/migration/mutations.tsx
index 1827979545..b2694b4587 100644
--- a/frontend/src/hooks/api/migration/mutations.tsx
+++ b/frontend/src/hooks/api/migration/mutations.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
export const useImportEnvKey = () => {
const queryClient = useQueryClient();
@@ -34,7 +34,7 @@ export const useImportEnvKey = () => {
},
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
});
diff --git a/frontend/src/hooks/api/pkiAlerts/mutations.tsx b/frontend/src/hooks/api/pkiAlerts/mutations.tsx
index 34397c1412..df48a6aab3 100644
--- a/frontend/src/hooks/api/pkiAlerts/mutations.tsx
+++ b/frontend/src/hooks/api/pkiAlerts/mutations.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import { pkiAlertKeys } from "./queries";
import { TCreatePkiAlertDTO, TDeletePkiAlertDTO, TPkiAlert, TUpdatePkiAlertDTO } from "./types";
@@ -14,7 +14,7 @@ export const useCreatePkiAlert = () => {
return alert;
},
onSuccess: (_, { projectId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspacePkiAlerts(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(projectId) });
}
});
};
@@ -30,7 +30,7 @@ export const useUpdatePkiAlert = () => {
return alert;
},
onSuccess: (_, { projectId, alertId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspacePkiAlerts(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(projectId) });
queryClient.invalidateQueries({ queryKey: pkiAlertKeys.getPkiAlertById(alertId) });
}
});
@@ -44,7 +44,7 @@ export const useDeletePkiAlert = () => {
return alert;
},
onSuccess: (_, { projectId, alertId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspacePkiAlerts(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectPkiAlerts(projectId) });
queryClient.invalidateQueries({ queryKey: pkiAlertKeys.getPkiAlertById(alertId) });
}
});
diff --git a/frontend/src/hooks/api/pkiCollections/mutations.tsx b/frontend/src/hooks/api/pkiCollections/mutations.tsx
index af1f0af185..a06afcd091 100644
--- a/frontend/src/hooks/api/pkiCollections/mutations.tsx
+++ b/frontend/src/hooks/api/pkiCollections/mutations.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import { pkiCollectionKeys } from "./queries";
import {
TAddItemToPkiCollectionDTO,
@@ -26,7 +26,7 @@ export const useCreatePkiCollection = () => {
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspacePkiCollections(projectId)
+ queryKey: projectKeys.getProjectPkiCollections(projectId)
});
}
});
@@ -44,7 +44,7 @@ export const useUpdatePkiCollection = () => {
},
onSuccess: (_, { projectId, collectionId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspacePkiCollections(projectId)
+ queryKey: projectKeys.getProjectPkiCollections(projectId)
});
queryClient.invalidateQueries({
queryKey: pkiCollectionKeys.getPkiCollectionById(collectionId)
@@ -64,7 +64,7 @@ export const useDeletePkiCollection = () => {
},
onSuccess: (_, { projectId, collectionId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspacePkiCollections(projectId)
+ queryKey: projectKeys.getProjectPkiCollections(projectId)
});
queryClient.invalidateQueries({
queryKey: pkiCollectionKeys.getPkiCollectionById(collectionId)
diff --git a/frontend/src/hooks/api/pkiSubscriber/mutations.tsx b/frontend/src/hooks/api/pkiSubscriber/mutations.tsx
index b30924f97a..57d086780a 100644
--- a/frontend/src/hooks/api/pkiSubscriber/mutations.tsx
+++ b/frontend/src/hooks/api/pkiSubscriber/mutations.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { TCreateCertificateResponse } from "../ca/types";
-import { workspaceKeys } from "../workspace/query-keys";
+import { projectKeys } from "../projects/query-keys";
import { pkiSubscriberKeys } from "./queries";
import {
TCreatePkiSubscriberDTO,
@@ -22,7 +22,7 @@ export const useCreatePkiSubscriber = () => {
},
onSuccess: ({ projectId, name }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspacePkiSubscribers(projectId)
+ queryKey: projectKeys.getProjectPkiSubscribers(projectId)
});
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.getPkiSubscriber({
@@ -46,7 +46,7 @@ export const useUpdatePkiSubscriber = () => {
},
onSuccess: ({ projectId, name }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspacePkiSubscribers(projectId)
+ queryKey: projectKeys.getProjectPkiSubscribers(projectId)
});
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.getPkiSubscriber({
@@ -74,7 +74,7 @@ export const useDeletePkiSubscriber = () => {
},
onSuccess: ({ name, projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspacePkiSubscribers(projectId)
+ queryKey: projectKeys.getProjectPkiSubscribers(projectId)
});
queryClient.invalidateQueries({
queryKey: pkiSubscriberKeys.getPkiSubscriber({
diff --git a/frontend/src/hooks/api/projectTemplates/types.ts b/frontend/src/hooks/api/projectTemplates/types.ts
index f5ff22dffe..d58e80f53e 100644
--- a/frontend/src/hooks/api/projectTemplates/types.ts
+++ b/frontend/src/hooks/api/projectTemplates/types.ts
@@ -1,6 +1,6 @@
import { TProjectRole } from "@app/hooks/api/roles/types";
-import { ProjectType } from "../workspace/types";
+import { ProjectType } from "../projects/types";
export type TProjectTemplate = {
id: string;
diff --git a/frontend/src/hooks/api/workspace/index.tsx b/frontend/src/hooks/api/projects/index.tsx
similarity index 89%
rename from frontend/src/hooks/api/workspace/index.tsx
rename to frontend/src/hooks/api/projects/index.tsx
index df2d55dc3b..ed8eba8158 100644
--- a/frontend/src/hooks/api/workspace/index.tsx
+++ b/frontend/src/hooks/api/projects/index.tsx
@@ -17,15 +17,14 @@ export {
useDeleteWsEnvironment,
useGetProjectSshConfig,
useGetUpgradeProjectStatus,
+ useGetUserProjects,
useGetUserWorkspaceMemberships,
- useGetUserWorkspaces,
useGetWorkspaceAuthorizations,
useGetWorkspaceById,
useGetWorkspaceIdentityMembershipDetails,
useGetWorkspaceIdentityMemberships,
useGetWorkspaceIndexStatus,
useGetWorkspaceIntegrations,
- useGetWorkspaceSecrets,
useGetWorkspaceUserDetails,
useGetWorkspaceUsers,
useGetWorkspaceWorkflowIntegrationConfig,
@@ -41,13 +40,11 @@ export {
useListWorkspaceSshCertificateTemplates,
useListWorkspaceSshHostGroups,
useListWorkspaceSshHosts,
- useNameWorkspaceSecrets,
useSearchProjects,
- useToggleAutoCapitalization,
useUpdateIdentityWorkspaceRole,
useUpdateProject,
useUpdateUserWorkspaceRole,
useUpdateWsEnvironment,
useUpgradeProject
} from "./queries";
-export { workspaceKeys } from "./query-keys";
+export { projectKeys } from "./query-keys";
diff --git a/frontend/src/hooks/api/workspace/mutations.tsx b/frontend/src/hooks/api/projects/mutations.tsx
similarity index 68%
rename from frontend/src/hooks/api/workspace/mutations.tsx
rename to frontend/src/hooks/api/projects/mutations.tsx
index 5cd7e3bbcc..e2a80ff536 100644
--- a/frontend/src/hooks/api/workspace/mutations.tsx
+++ b/frontend/src/hooks/api/projects/mutations.tsx
@@ -3,7 +3,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { userKeys } from "../users/query-keys";
-import { workspaceKeys } from "./query-keys";
+import { projectKeys } from "./query-keys";
import {
TProjectSshConfig,
TUpdateProjectSshConfigDTO,
@@ -24,7 +24,7 @@ export const useAddGroupToWorkspace = () => {
}) => {
const {
data: { groupMembership }
- } = await apiRequest.post(`/api/v2/workspace/${projectId}/groups/${groupId}`, {
+ } = await apiRequest.post(`/api/v1/projects/${projectId}/groups/${groupId}`, {
role
});
@@ -32,7 +32,7 @@ export const useAddGroupToWorkspace = () => {
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectId)
+ queryKey: projectKeys.getProjectGroupMemberships(projectId)
});
}
});
@@ -44,7 +44,7 @@ export const useUpdateGroupWorkspaceRole = () => {
mutationFn: async ({ groupId, projectId, roles }: TUpdateWorkspaceGroupRoleDTO) => {
const {
data: { groupMembership }
- } = await apiRequest.patch(`/api/v2/workspace/${projectId}/groups/${groupId}`, {
+ } = await apiRequest.patch(`/api/v1/projects/${projectId}/groups/${groupId}`, {
roles
});
@@ -52,10 +52,10 @@ export const useUpdateGroupWorkspaceRole = () => {
},
onSuccess: (_, { projectId, groupId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectId)
+ queryKey: projectKeys.getProjectGroupMemberships(projectId)
});
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceGroupMembershipDetails(projectId, groupId)
+ queryKey: projectKeys.getProjectGroupMembershipDetails(projectId, groupId)
});
}
});
@@ -74,12 +74,12 @@ export const useDeleteGroupFromWorkspace = () => {
}) => {
const {
data: { groupMembership }
- } = await apiRequest.delete(`/api/v2/workspace/${projectId}/groups/${groupId}`);
+ } = await apiRequest.delete(`/api/v1/projects/${projectId}/groups/${groupId}`);
return groupMembership;
},
onSuccess: (_, { projectId, username }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectId)
+ queryKey: projectKeys.getProjectGroupMemberships(projectId)
});
if (username) {
@@ -91,25 +91,25 @@ export const useDeleteGroupFromWorkspace = () => {
export const useLeaveProject = () => {
const queryClient = useQueryClient();
- return useMutation<object, object, { workspaceId: string }>({
- mutationFn: ({ workspaceId }) => {
- return apiRequest.delete(`/api/v1/workspace/${workspaceId}/leave`);
+ return useMutation<object, object, { projectId: string }>({
+ mutationFn: ({ projectId }) => {
+ return apiRequest.delete(`/api/v1/projects/${projectId}/leave`);
},
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getAllUserProjects() });
}
});
};
export const useMigrateProjectToV3 = () => {
const queryClient = useQueryClient();
- return useMutation<object, object, { workspaceId: string }>({
- mutationFn: ({ workspaceId }) => {
- return apiRequest.post(`/api/v1/workspace/${workspaceId}/migrate-v3`);
+ return useMutation<object, object, { projectId: string }>({
+ mutationFn: ({ projectId }) => {
+ return apiRequest.post(`/api/v1/projects/${projectId}/migrate-v3`);
},
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
});
@@ -118,7 +118,7 @@ export const useMigrateProjectToV3 = () => {
export const useRequestProjectAccess = () => {
return useMutation<object, object, { projectId: string; comment: string }>({
mutationFn: ({ projectId, comment }) => {
- return apiRequest.post(`/api/v1/workspace/${projectId}/project-access`, {
+ return apiRequest.post(`/api/v1/projects/${projectId}/project-access`, {
comment
});
}
@@ -129,14 +129,14 @@ export const useUpdateProjectSshConfig = () => {
const queryClient = useQueryClient();
return useMutation<TProjectSshConfig, object, TUpdateProjectSshConfigDTO>({
mutationFn: ({ projectId, defaultUserSshCaId, defaultHostSshCaId }) => {
- return apiRequest.patch(`/api/v1/workspace/${projectId}/ssh-config`, {
+ return apiRequest.patch(`/api/v1/projects/${projectId}/ssh-config`, {
defaultUserSshCaId,
defaultHostSshCaId
});
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getProjectSshConfig(projectId)
+ queryKey: projectKeys.getProjectSshConfig(projectId)
});
}
});
diff --git a/frontend/src/hooks/api/workspace/queries.tsx b/frontend/src/hooks/api/projects/queries.tsx
similarity index 55%
rename from frontend/src/hooks/api/workspace/queries.tsx
rename to frontend/src/hooks/api/projects/queries.tsx
index 3c7a6d30c6..0445d59845 100644
--- a/frontend/src/hooks/api/workspace/queries.tsx
+++ b/frontend/src/hooks/api/projects/queries.tsx
@@ -15,7 +15,6 @@ import { TIntegration } from "../integrations/types";
import { TPkiAlert } from "../pkiAlerts/types";
import { TPkiCollection } from "../pkiCollections/types";
import { TPkiSubscriber } from "../pkiSubscriber/types";
-import { EncryptedSecret } from "../secrets/types";
import { TSshCertificate, TSshCertificateAuthority } from "../sshCa/types";
import { TSshCertificateTemplate } from "../sshCertificateTemplates/types";
import { TSshHost } from "../sshHost/types";
@@ -26,42 +25,36 @@ import {
ProjectWorkflowIntegrationConfig,
WorkflowIntegrationPlatform
} from "../workflowIntegrations/types";
-import { workspaceKeys } from "./query-keys";
+import { projectKeys } from "./query-keys";
import {
CreateEnvironmentDTO,
CreateWorkspaceDTO,
DeleteEnvironmentDTO,
DeleteWorkspaceDTO,
- NameWorkspaceSecretsDTO,
+ Project,
+ ProjectEnv,
ProjectIdentityOrderBy,
ProjectType,
TGetUpgradeProjectStatusDTO,
TListProjectIdentitiesDTO,
- ToggleAutoCapitalizationDTO,
- ToggleDeleteProjectProtectionDTO,
TProjectSshConfig,
TSearchProjectsDTO,
TUpdateWorkspaceIdentityRoleDTO,
TUpdateWorkspaceUserRoleDTO,
UpdateAuditLogsRetentionDTO,
UpdateEnvironmentDTO,
- UpdatePitVersionLimitDTO,
- UpdateProjectDTO,
- Workspace,
- WorkspaceEnv
+ UpdateProjectDTO
} from "./types";
-export const fetchWorkspaceById = async (workspaceId: string) => {
- const { data } = await apiRequest.get<{ workspace: Workspace }>(
- `/api/v1/workspace/${workspaceId}`
- );
+export const fetchProjectById = async (projectId: string) => {
+ const { data } = await apiRequest.get<{ project: Project }>(`/api/v1/projects/${projectId}`);
- return data.workspace;
+ return data.project;
};
-const fetchWorkspaceIndexStatus = async (workspaceId: string) => {
+const fetchWorkspaceIndexStatus = async (projectId: string) => {
const { data } = await apiRequest.get<boolean>(
- `/api/v3/workspaces/${workspaceId}/secrets/blind-index-status`
+ `/api/v3/projects/${projectId}/secrets/blind-index-status`
);
return data;
@@ -69,34 +62,24 @@ const fetchWorkspaceIndexStatus = async (workspaceId: string) => {
const fetchProjectUpgradeStatus = async (projectId: string) => {
const { data } = await apiRequest.get<{ status: string }>(
- `/api/v2/workspace/${projectId}/upgrade/status`
+ `/api/v1/projects/${projectId}/upgrade/status`
);
return data;
};
-export const fetchWorkspaceSecrets = async (workspaceId: string) => {
- const {
- data: { secrets }
- } = await apiRequest.get<{ secrets: EncryptedSecret[] }>(
- `/api/v3/workspaces/${workspaceId}/secrets`
- );
-
- return secrets;
-};
-
export const useUpgradeProject = () => {
const queryClient = useQueryClient();
return useMutation<object, object, { projectId: string; privateKey: string }>({
mutationFn: ({ projectId, privateKey }) => {
- return apiRequest.post(`/api/v2/workspace/${projectId}/upgrade`, {
+ return apiRequest.post(`/api/v1/projects/${projectId}/upgrade`, {
userPrivateKey: privateKey
});
},
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
});
@@ -108,7 +91,7 @@ export const useGetUpgradeProjectStatus = ({
refetchInterval
}: TGetUpgradeProjectStatusDTO) => {
return useQuery({
- queryKey: workspaceKeys.getProjectUpgradeStatus(projectId),
+ queryKey: projectKeys.getProjectUpgradeStatus(projectId),
queryFn: () => fetchProjectUpgradeStatus(projectId),
enabled,
refetchInterval
@@ -116,44 +99,36 @@ export const useGetUpgradeProjectStatus = ({
};
const fetchUserWorkspaces = async (includeRoles?: boolean, type?: ProjectType | "all") => {
- const { data } = await apiRequest.get<{ workspaces: Workspace[] }>("/api/v1/workspace", {
+ const { data } = await apiRequest.get<{ projects: Project[] }>("/api/v1/projects", {
params: {
includeRoles,
type
}
});
- return data.workspaces;
-};
-
-export const useGetWorkspaceIndexStatus = (workspaceId: string) => {
- return useQuery({
- queryKey: workspaceKeys.getWorkspaceIndexStatus(workspaceId),
- queryFn: () => fetchWorkspaceIndexStatus(workspaceId),
- enabled: true
- });
+ return data.projects;
};
-export const useGetWorkspaceSecrets = (workspaceId: string) => {
+export const useGetWorkspaceIndexStatus = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceSecrets(workspaceId),
- queryFn: () => fetchWorkspaceSecrets(workspaceId),
+ queryKey: projectKeys.getProjectIndexStatus(projectId),
+ queryFn: () => fetchWorkspaceIndexStatus(projectId),
enabled: true
});
};
export const useGetWorkspaceById = (
- workspaceId: string,
+ projectId: string,
dto?: { refetchInterval?: number | false }
) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceById(workspaceId),
- queryFn: () => fetchWorkspaceById(workspaceId),
- enabled: Boolean(workspaceId),
+ queryKey: projectKeys.getProjectById(projectId),
+ queryFn: () => fetchProjectById(projectId),
+ enabled: Boolean(projectId),
refetchInterval: dto?.refetchInterval
});
};
-export const useGetUserWorkspaces = ({
+export const useGetUserProjects = ({
includeRoles,
options = {}
}: {
@@ -161,19 +136,19 @@ export const useGetUserWorkspaces = ({
options?: { enabled?: boolean };
} = {}) =>
useQuery({
- queryKey: workspaceKeys.getAllUserWorkspace(),
+ queryKey: projectKeys.getAllUserProjects(),
queryFn: () => fetchUserWorkspaces(includeRoles),
...options
});
export const useSearchProjects = ({ options, ...dto }: TSearchProjectsDTO) =>
useQuery({
- queryKey: workspaceKeys.searchWorkspace(dto),
+ queryKey: projectKeys.searchProject(dto),
queryFn: async () => {
const { data } = await apiRequest.post<{
- projects: (Workspace & { isMember: boolean })[];
+ projects: (Project & { isMember: boolean })[];
totalCount: number;
- }>("/api/v1/workspace/search", dto);
+ }>("/api/v1/projects/search", dto);
return data;
},
@@ -181,81 +156,65 @@ export const useSearchProjects = ({ options, ...dto }: TSearchProjectsDTO) =>
});
const fetchUserWorkspaceMemberships = async (orgId: string) => {
- const { data } = await apiRequest.get<Record<string, Workspace[]>>(
- `/api/v1/organization/${orgId}/workspace-memberships`
+ const { data } = await apiRequest.get<Record<string, Project[]>>(
+ `/api/v1/organization/${orgId}/project-memberships`
);
return data;
};
-// to get all userids in an org with the workspace they are part of
+// to get all userids in an org with the project they are part of
export const useGetUserWorkspaceMemberships = (orgId: string) =>
useQuery({
- queryKey: workspaceKeys.getWorkspaceMemberships(orgId),
+ queryKey: projectKeys.getProjectMemberships(orgId),
queryFn: () => fetchUserWorkspaceMemberships(orgId),
enabled: Boolean(orgId)
});
-export const useNameWorkspaceSecrets = () => {
- const queryClient = useQueryClient();
-
- return useMutation<object, object, NameWorkspaceSecretsDTO>({
- mutationFn: async ({ workspaceId, secretsToUpdate }) =>
- apiRequest.post(`/api/v3/workspaces/${workspaceId}/secrets/names`, {
- secretsToUpdate
- }),
- onSuccess: (_, variables) => {
- queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIndexStatus(variables.workspaceId)
- });
- }
- });
-};
-
-const fetchWorkspaceAuthorization = async (workspaceId: string) => {
+const fetchWorkspaceAuthorization = async (projectId: string) => {
const { data } = await apiRequest.get<{ authorizations: IntegrationAuth[] }>(
- `/api/v1/workspace/${workspaceId}/authorizations`
+ `/api/v1/projects/${projectId}/authorizations`
);
return data.authorizations;
};
export const useGetWorkspaceAuthorizations = <TData = IntegrationAuth[],>(
- workspaceId: string,
+ projectId: string,
select?: (data: IntegrationAuth[]) => TData
) =>
useQuery({
- queryKey: workspaceKeys.getWorkspaceAuthorization(workspaceId),
- queryFn: () => fetchWorkspaceAuthorization(workspaceId),
- enabled: Boolean(workspaceId),
+ queryKey: projectKeys.getProjectAuthorization(projectId),
+ queryFn: () => fetchWorkspaceAuthorization(projectId),
+ enabled: Boolean(projectId),
select
});
-export const fetchWorkspaceIntegrations = async (workspaceId: string) => {
+export const fetchWorkspaceIntegrations = async (projectId: string) => {
const { data } = await apiRequest.get<{ integrations: TIntegration[] }>(
- `/api/v1/workspace/${workspaceId}/integrations`
+ `/api/v1/projects/${projectId}/integrations`
);
return data.integrations;
};
-export const useGetWorkspaceIntegrations = (workspaceId: string) =>
+export const useGetWorkspaceIntegrations = (projectId: string) =>
useQuery({
- queryKey: workspaceKeys.getWorkspaceIntegrations(workspaceId),
- queryFn: () => fetchWorkspaceIntegrations(workspaceId),
- enabled: Boolean(workspaceId),
+ queryKey: projectKeys.getProjectIntegrations(projectId),
+ queryFn: () => fetchWorkspaceIntegrations(projectId),
+ enabled: Boolean(projectId),
refetchInterval: 4000
});
export const createWorkspace = (
dto: CreateWorkspaceDTO
-): Promise<{ data: { project: Workspace } }> => {
- return apiRequest.post("/api/v2/workspace", dto);
+): Promise<{ data: { project: Project } }> => {
+ return apiRequest.post("/api/v1/projects", dto);
};
export const useCreateWorkspace = () => {
const queryClient = useQueryClient();
- return useMutation<{ data: { project: Workspace } }, object, CreateWorkspaceDTO>({
+ return useMutation<{ data: { project: Project } }, object, CreateWorkspaceDTO>({
mutationFn: async ({ projectName, projectDescription, kmsKeyId, template, type }) =>
createWorkspace({
projectName,
@@ -266,7 +225,7 @@ export const useCreateWorkspace = () => {
}),
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
});
@@ -275,85 +234,37 @@ export const useCreateWorkspace = () => {
export const useUpdateProject = () => {
const queryClient = useQueryClient();
- return useMutation<Workspace, object, UpdateProjectDTO>({
+ return useMutation<Project, object, UpdateProjectDTO>({
mutationFn: async ({
- projectID,
+ projectId: projectID,
newProjectName,
+ hasDeleteProtection,
newProjectDescription,
newSlug,
secretSharing,
showSnapshotsLegacy,
- secretDetectionIgnoreValues
+ secretDetectionIgnoreValues,
+ autoCapitalization,
+ pitVersionLimit
}) => {
- const { data } = await apiRequest.patch<{ workspace: Workspace }>(
- `/api/v1/workspace/${projectID}`,
+ const { data } = await apiRequest.patch<{ project: Project }>(
+ `/api/v1/projects/${projectID}`,
{
name: newProjectName,
description: newProjectDescription,
slug: newSlug,
secretSharing,
showSnapshotsLegacy,
- secretDetectionIgnoreValues
+ secretDetectionIgnoreValues,
+ autoCapitalization,
+ pitVersionLimit,
+ hasDeleteProtection
}
);
- return data.workspace;
+ return data.project;
},
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
- }
- });
-};
-
-export const useToggleAutoCapitalization = () => {
- const queryClient = useQueryClient();
-
- return useMutation<Workspace, object, ToggleAutoCapitalizationDTO>({
- mutationFn: async ({ workspaceID, state }) => {
- const { data } = await apiRequest.post<{ workspace: Workspace }>(
- `/api/v1/workspace/${workspaceID}/auto-capitalization`,
- {
- autoCapitalization: state
- }
- );
- return data.workspace;
- },
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
- }
- });
-};
-
-export const useToggleDeleteProjectProtection = () => {
- const queryClient = useQueryClient();
-
- return useMutation<Workspace, object, ToggleDeleteProjectProtectionDTO>({
- mutationFn: async ({ workspaceID, state }) => {
- const { data } = await apiRequest.post<{ workspace: Workspace }>(
- `/api/v1/workspace/${workspaceID}/delete-protection`,
- {
- hasDeleteProtection: state
- }
- );
- return data.workspace;
- },
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
- }
- });
-};
-
-export const useUpdateWorkspaceVersionLimit = () => {
- const queryClient = useQueryClient();
-
- return useMutation<Workspace, object, UpdatePitVersionLimitDTO>({
- mutationFn: async ({ projectSlug, pitVersionLimit }) => {
- const { data } = await apiRequest.put(`/api/v1/workspace/${projectSlug}/version-limit`, {
- pitVersionLimit
- });
- return data.workspace;
- },
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getAllUserProjects() });
}
});
};
@@ -361,18 +272,18 @@ export const useUpdateWorkspaceVersionLimit = () => {
export const useUpdateWorkspaceAuditLogsRetention = () => {
const queryClient = useQueryClient();
- return useMutation<Workspace, object, UpdateAuditLogsRetentionDTO>({
+ return useMutation<Project, object, UpdateAuditLogsRetentionDTO>({
mutationFn: async ({ projectSlug, auditLogsRetentionDays }) => {
const { data } = await apiRequest.put(
- `/api/v1/workspace/${projectSlug}/audit-logs-retention`,
+ `/api/v1/projects/${projectSlug}/audit-logs-retention`,
{
auditLogsRetentionDays
}
);
- return data.workspace;
+ return data.project;
},
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getAllUserProjects() });
}
});
};
@@ -380,13 +291,13 @@ export const useUpdateWorkspaceAuditLogsRetention = () => {
export const useDeleteWorkspace = () => {
const queryClient = useQueryClient();
- return useMutation<Workspace, object, DeleteWorkspaceDTO>({
- mutationFn: async ({ workspaceID }) => {
- const { data } = await apiRequest.delete(`/api/v1/workspace/${workspaceID}`);
- return data.workspace;
+ return useMutation<Project, object, DeleteWorkspaceDTO>({
+ mutationFn: async ({ projectID }) => {
+ const { data } = await apiRequest.delete(`/api/v1/projects/${projectID}`);
+ return data.project;
},
onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getAllUserProjects() });
queryClient.invalidateQueries({
queryKey: ["org-admin-projects"]
});
@@ -397,10 +308,10 @@ export const useDeleteWorkspace = () => {
export const useCreateWsEnvironment = () => {
const queryClient = useQueryClient();
- return useMutation<WorkspaceEnv, WorkspaceEnv, CreateEnvironmentDTO>({
- mutationFn: async ({ workspaceId, name, slug }) => {
- const { data } = await apiRequest.post<{ environment: WorkspaceEnv }>(
- `/api/v1/workspace/${workspaceId}/environments`,
+ return useMutation<ProjectEnv, ProjectEnv, CreateEnvironmentDTO>({
+ mutationFn: async ({ projectId, name, slug }) => {
+ const { data } = await apiRequest.post<{ environment: ProjectEnv }>(
+ `/api/v1/projects/${projectId}/environments`,
{
name,
slug
@@ -410,7 +321,7 @@ export const useCreateWsEnvironment = () => {
},
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
});
@@ -420,8 +331,8 @@ export const useUpdateWsEnvironment = () => {
const queryClient = useQueryClient();
return useMutation<object, object, UpdateEnvironmentDTO>({
- mutationFn: ({ workspaceId, id, name, slug, position }) => {
- return apiRequest.patch(`/api/v1/workspace/${workspaceId}/environments/${id}`, {
+ mutationFn: ({ projectId, id, name, slug, position }) => {
+ return apiRequest.patch(`/api/v1/projects/${projectId}/environments/${id}`, {
name,
slug,
position
@@ -429,7 +340,7 @@ export const useUpdateWsEnvironment = () => {
},
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
});
@@ -439,57 +350,54 @@ export const useDeleteWsEnvironment = () => {
const queryClient = useQueryClient();
return useMutation<object, object, DeleteEnvironmentDTO>({
- mutationFn: ({ id, workspaceId }) => {
- return apiRequest.delete(`/api/v1/workspace/${workspaceId}/environments/${id}`);
+ mutationFn: ({ id, projectId }) => {
+ return apiRequest.delete(`/api/v1/projects/${projectId}/environments/${id}`);
},
onSuccess: () => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
});
};
export const useGetWorkspaceUsers = (
- workspaceId: string,
+ projectId: string,
includeGroupMembers?: boolean,
roles?: string[]
) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceUsers(workspaceId, includeGroupMembers, roles),
+ queryKey: projectKeys.getProjectUsers(projectId, includeGroupMembers, roles),
queryFn: async () => {
const {
data: { users }
- } = await apiRequest.get<{ users: TWorkspaceUser[] }>(
- `/api/v1/workspace/${workspaceId}/users`,
- {
- params: {
- includeGroupMembers,
- roles:
- roles && roles.length > 0
- ? roles.map((role) => encodeURIComponent(role)).join(",")
- : undefined
- }
+ } = await apiRequest.get<{ users: TWorkspaceUser[] }>(`/api/v1/projects/${projectId}/users`, {
+ params: {
+ includeGroupMembers,
+ roles:
+ roles && roles.length > 0
+ ? roles.map((role) => encodeURIComponent(role)).join(",")
+ : undefined
}
- );
+ });
return users;
},
enabled: true
});
};
-export const useGetWorkspaceUserDetails = (workspaceId: string, membershipId: string) => {
+export const useGetWorkspaceUserDetails = (projectId: string, membershipId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceUserDetails(workspaceId, membershipId),
+ queryKey: projectKeys.getProjectUserDetails(projectId, membershipId),
queryFn: async () => {
const {
data: { membership }
} = await apiRequest.get<{ membership: TWorkspaceUser }>(
- `/api/v1/workspace/${workspaceId}/memberships/${membershipId}`
+ `/api/v1/projects/${projectId}/memberships/${membershipId}`
);
return membership;
},
- enabled: Boolean(workspaceId) && Boolean(membershipId)
+ enabled: Boolean(projectId) && Boolean(membershipId)
});
};
@@ -499,21 +407,21 @@ export const useDeleteUserFromWorkspace = () => {
return useMutation({
mutationFn: async ({
usernames,
- workspaceId
+ projectId
}: {
- workspaceId: string;
+ projectId: string;
usernames: string[];
orgId: string;
}) => {
const {
data: { deletedMembership }
- } = await apiRequest.delete(`/api/v2/workspace/${workspaceId}/memberships`, {
+ } = await apiRequest.delete(`/api/v1/projects/${projectId}/memberships`, {
data: { usernames }
});
return deletedMembership;
},
- onSuccess: (_, { orgId, workspaceId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceUsers(workspaceId) });
+ onSuccess: (_, { orgId, projectId }) => {
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectUsers(projectId) });
queryClient.invalidateQueries({
queryKey: userKeys.allOrgMembershipProjectMemberships(orgId)
});
@@ -524,21 +432,21 @@ export const useDeleteUserFromWorkspace = () => {
export const useUpdateUserWorkspaceRole = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ membershipId, roles, workspaceId }: TUpdateWorkspaceUserRoleDTO) => {
+ mutationFn: async ({ membershipId, roles, projectId }: TUpdateWorkspaceUserRoleDTO) => {
const {
data: { membership }
} = await apiRequest.patch<{ membership: { projectId: string } }>(
- `/api/v1/workspace/${workspaceId}/memberships/${membershipId}`,
+ `/api/v1/projects/${projectId}/memberships/${membershipId}`,
{
roles
}
);
return membership;
},
- onSuccess: (_, { workspaceId, membershipId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceUsers(workspaceId) });
+ onSuccess: (_, { projectId, membershipId }) => {
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectUsers(projectId) });
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceUserDetails(workspaceId, membershipId)
+ queryKey: projectKeys.getProjectUserDetails(projectId, membershipId)
});
}
});
@@ -549,17 +457,17 @@ export const useAddIdentityToWorkspace = () => {
return useMutation({
mutationFn: async ({
identityId,
- workspaceId,
+ projectId,
role
}: {
identityId: string;
- workspaceId: string;
+ projectId: string;
role?: string;
}) => {
const {
data: { identityMembership }
} = await apiRequest.post(
- `/api/v2/workspace/${workspaceId}/identity-memberships/${identityId}`,
+ `/api/v1/projects/${projectId}/identity-memberships/${identityId}`,
{
role
}
@@ -567,9 +475,9 @@ export const useAddIdentityToWorkspace = () => {
return identityMembership;
},
- onSuccess: (_, { identityId, workspaceId }) => {
+ onSuccess: (_, { identityId, projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIdentityMemberships(workspaceId)
+ queryKey: projectKeys.getProjectIdentityMemberships(projectId)
});
queryClient.invalidateQueries({
queryKey: identitiesKeys.getIdentityProjectMemberships(identityId)
@@ -581,11 +489,11 @@ export const useAddIdentityToWorkspace = () => {
export const useUpdateIdentityWorkspaceRole = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({ identityId, workspaceId, roles }: TUpdateWorkspaceIdentityRoleDTO) => {
+ mutationFn: async ({ identityId, projectId, roles }: TUpdateWorkspaceIdentityRoleDTO) => {
const {
data: { identityMembership }
} = await apiRequest.patch(
- `/api/v2/workspace/${workspaceId}/identity-memberships/${identityId}`,
+ `/api/v1/projects/${projectId}/identity-memberships/${identityId}`,
{
roles
}
@@ -593,15 +501,15 @@ export const useUpdateIdentityWorkspaceRole = () => {
return identityMembership;
},
- onSuccess: (_, { identityId, workspaceId }) => {
+ onSuccess: (_, { identityId, projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIdentityMemberships(workspaceId)
+ queryKey: projectKeys.getProjectIdentityMemberships(projectId)
});
queryClient.invalidateQueries({
queryKey: identitiesKeys.getIdentityProjectMemberships(identityId)
});
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIdentityMembershipDetails(workspaceId, identityId)
+ queryKey: projectKeys.getProjectIdentityMembershipDetails(projectId, identityId)
});
}
});
@@ -610,23 +518,17 @@ export const useUpdateIdentityWorkspaceRole = () => {
export const useDeleteIdentityFromWorkspace = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({
- identityId,
- workspaceId
- }: {
- identityId: string;
- workspaceId: string;
- }) => {
+ mutationFn: async ({ identityId, projectId }: { identityId: string; projectId: string }) => {
const {
data: { identityMembership }
} = await apiRequest.delete(
- `/api/v2/workspace/${workspaceId}/identity-memberships/${identityId}`
+ `/api/v1/projects/${projectId}/identity-memberships/${identityId}`
);
return identityMembership;
},
- onSuccess: (_, { identityId, workspaceId }) => {
+ onSuccess: (_, { identityId, projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceIdentityMemberships(workspaceId)
+ queryKey: projectKeys.getProjectIdentityMemberships(projectId)
});
queryClient.invalidateQueries({
queryKey: identitiesKeys.getIdentityProjectMemberships(identityId)
@@ -637,7 +539,7 @@ export const useDeleteIdentityFromWorkspace = () => {
export const useGetWorkspaceIdentityMemberships = (
{
- workspaceId,
+ projectId,
offset = 0,
limit = 100,
orderBy = ProjectIdentityOrderBy.Name,
@@ -649,14 +551,14 @@ export const useGetWorkspaceIdentityMemberships = (
TProjectIdentitiesList,
unknown,
TProjectIdentitiesList,
- ReturnType<typeof workspaceKeys.getWorkspaceIdentityMembershipsWithParams>
+ ReturnType<typeof projectKeys.getProjectIdentityMembershipsWithParams>
>,
"queryKey" | "queryFn"
>
) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceIdentityMembershipsWithParams({
- workspaceId,
+ queryKey: projectKeys.getProjectIdentityMembershipsWithParams({
+ projectId,
offset,
limit,
orderBy,
@@ -673,7 +575,7 @@ export const useGetWorkspaceIdentityMemberships = (
});
const { data } = await apiRequest.get<TProjectIdentitiesList>(
- `/api/v2/workspace/${workspaceId}/identity-memberships`,
+ `/api/v1/projects/${projectId}/identity-memberships`,
{ params }
);
return data;
@@ -686,12 +588,12 @@ export const useGetWorkspaceIdentityMemberships = (
export const useGetWorkspaceIdentityMembershipDetails = (projectId: string, identityId: string) => {
return useQuery({
enabled: Boolean(projectId && identityId),
- queryKey: workspaceKeys.getWorkspaceIdentityMembershipDetails(projectId, identityId),
+ queryKey: projectKeys.getProjectIdentityMembershipDetails(projectId, identityId),
queryFn: async () => {
const {
data: { identityMembership }
} = await apiRequest.get<{ identityMembership: IdentityMembership }>(
- `/api/v2/workspace/${projectId}/identity-memberships/${identityId}`
+ `/api/v1/projects/${projectId}/identity-memberships/${identityId}`
);
return identityMembership;
}
@@ -701,12 +603,12 @@ export const useGetWorkspaceIdentityMembershipDetails = (projectId: string, iden
export const useGetWorkspaceGroupMembershipDetails = (projectId: string, groupId: string) => {
return useQuery({
enabled: Boolean(projectId && groupId),
- queryKey: workspaceKeys.getWorkspaceGroupMembershipDetails(projectId, groupId),
+ queryKey: projectKeys.getProjectGroupMembershipDetails(projectId, groupId),
queryFn: async () => {
const {
data: { groupMembership }
} = await apiRequest.get<{ groupMembership: TGroupMembership }>(
- `/api/v2/workspace/${projectId}/groups/${groupId}`
+ `/api/v1/projects/${projectId}/groups/${groupId}`
);
return groupMembership;
}
@@ -715,12 +617,12 @@ export const useGetWorkspaceGroupMembershipDetails = (projectId: string, groupId
export const useListWorkspaceGroups = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceGroupMemberships(projectId),
+ queryKey: projectKeys.getProjectGroupMemberships(projectId),
queryFn: async () => {
const {
data: { groupMemberships }
} = await apiRequest.get<{ groupMemberships: TGroupMembership[] }>(
- `/api/v2/workspace/${projectId}/groups`
+ `/api/v1/projects/${projectId}/groups`
);
return groupMemberships;
},
@@ -729,15 +631,15 @@ export const useListWorkspaceGroups = (projectId: string) => {
};
export const useListWorkspaceCas = ({
- projectSlug,
+ projectId,
status
}: {
- projectSlug: string;
+ projectId: string;
status?: CaStatus;
}) => {
return useQuery({
- queryKey: workspaceKeys.specificWorkspaceCas({
- projectSlug,
+ queryKey: projectKeys.specificProjectCas({
+ projectId,
status
}),
queryFn: async () => {
@@ -748,29 +650,29 @@ export const useListWorkspaceCas = ({
const {
data: { cas }
} = await apiRequest.get<{ cas: TCertificateAuthority[] }>(
- `/api/v2/workspace/${projectSlug}/cas`,
+ `/api/v1/projects/${projectId}/cas`,
{
params
}
);
return cas;
},
- enabled: Boolean(projectSlug)
+ enabled: Boolean(projectId)
});
};
export const useListWorkspaceCertificates = ({
- projectSlug,
+ projectId,
offset,
limit
}: {
- projectSlug: string;
+ projectId: string;
offset: number;
limit: number;
}) => {
return useQuery({
- queryKey: workspaceKeys.specificWorkspaceCertificates({
- slug: projectSlug,
+ queryKey: projectKeys.specificProjectCertificates({
+ projectId,
offset,
limit
}),
@@ -783,7 +685,7 @@ export const useListWorkspaceCertificates = ({
const {
data: { certificates, totalCount }
} = await apiRequest.get<{ certificates: TCertificate[]; totalCount: number }>(
- `/api/v2/workspace/${projectSlug}/certificates`,
+ `/api/v1/projects/${projectId}/certificates`,
{
params
}
@@ -791,55 +693,53 @@ export const useListWorkspaceCertificates = ({
return { certificates, totalCount };
},
- enabled: Boolean(projectSlug)
+ enabled: Boolean(projectId)
});
};
-export const useListWorkspacePkiAlerts = ({ workspaceId }: { workspaceId: string }) => {
+export const useListWorkspacePkiAlerts = ({ projectId }: { projectId: string }) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspacePkiAlerts(workspaceId),
+ queryKey: projectKeys.getProjectPkiAlerts(projectId),
queryFn: async () => {
const {
data: { alerts }
- } = await apiRequest.get<{ alerts: TPkiAlert[] }>(
- `/api/v2/workspace/${workspaceId}/pki-alerts`
- );
+ } = await apiRequest.get<{ alerts: TPkiAlert[] }>(`/api/v1/projects/${projectId}/pki-alerts`);
return { alerts };
},
- enabled: Boolean(workspaceId)
+ enabled: Boolean(projectId)
});
};
-export const useListWorkspacePkiCollections = ({ workspaceId }: { workspaceId: string }) => {
+export const useListWorkspacePkiCollections = ({ projectId }: { projectId: string }) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspacePkiCollections(workspaceId),
+ queryKey: projectKeys.getProjectPkiCollections(projectId),
queryFn: async () => {
const {
data: { collections }
} = await apiRequest.get<{ collections: TPkiCollection[] }>(
- `/api/v2/workspace/${workspaceId}/pki-collections`
+ `/api/v1/projects/${projectId}/pki-collections`
);
return { collections };
},
- enabled: Boolean(workspaceId)
+ enabled: Boolean(projectId)
});
};
-export const useListWorkspaceCertificateTemplates = ({ workspaceId }: { workspaceId: string }) => {
+export const useListWorkspaceCertificateTemplates = ({ projectId }: { projectId: string }) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceCertificateTemplates(workspaceId),
+ queryKey: projectKeys.getProjectCertificateTemplates(projectId),
queryFn: async () => {
const {
data: { certificateTemplates }
} = await apiRequest.get<{ certificateTemplates: TCertificateTemplate[] }>(
- `/api/v2/workspace/${workspaceId}/certificate-templates`
+ `/api/v1/projects/${projectId}/certificate-templates`
);
return { certificateTemplates };
},
- enabled: Boolean(workspaceId)
+ enabled: Boolean(projectId)
});
};
@@ -853,7 +753,7 @@ export const useListWorkspaceSshCertificates = ({
projectId: string;
}) => {
return useQuery({
- queryKey: workspaceKeys.specificWorkspaceSshCertificates({
+ queryKey: projectKeys.specificProjectSshCertificates({
offset,
limit,
projectId
@@ -867,7 +767,7 @@ export const useListWorkspaceSshCertificates = ({
const { data } = await apiRequest.get<{
certificates: TSshCertificate[];
totalCount: number;
- }>(`/api/v2/workspace/${projectId}/ssh-certificates`, {
+ }>(`/api/v1/projects/${projectId}/ssh-certificates`, {
params
});
return data;
@@ -878,12 +778,12 @@ export const useListWorkspaceSshCertificates = ({
export const useListWorkspaceSshCas = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceSshCas(projectId),
+ queryKey: projectKeys.getProjectSshCas(projectId),
queryFn: async () => {
const {
data: { cas }
} = await apiRequest.get<{ cas: Omit<TSshCertificateAuthority, "publicKey">[] }>(
- `/api/v2/workspace/${projectId}/ssh-cas`
+ `/api/v1/projects/${projectId}/ssh-cas`
);
return cas;
},
@@ -893,11 +793,11 @@ export const useListWorkspaceSshCas = (projectId: string) => {
export const useListWorkspaceSshHosts = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceSshHosts(projectId),
+ queryKey: projectKeys.getProjectSshHosts(projectId),
queryFn: async () => {
const {
data: { hosts }
- } = await apiRequest.get<{ hosts: TSshHost[] }>(`/api/v2/workspace/${projectId}/ssh-hosts`);
+ } = await apiRequest.get<{ hosts: TSshHost[] }>(`/api/v1/projects/${projectId}/ssh-hosts`);
return hosts;
},
enabled: Boolean(projectId)
@@ -906,12 +806,12 @@ export const useListWorkspaceSshHosts = (projectId: string) => {
export const useListWorkspacePkiSubscribers = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspacePkiSubscribers(projectId),
+ queryKey: projectKeys.getProjectPkiSubscribers(projectId),
queryFn: async () => {
const {
data: { subscribers }
} = await apiRequest.get<{ subscribers: TPkiSubscriber[] }>(
- `/api/v2/workspace/${projectId}/pki-subscribers`
+ `/api/v1/projects/${projectId}/pki-subscribers`
);
return subscribers;
},
@@ -921,12 +821,12 @@ export const useListWorkspacePkiSubscribers = (projectId: string) => {
export const useListWorkspaceSshHostGroups = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceSshHostGroups(projectId),
+ queryKey: projectKeys.getProjectSshHostGroups(projectId),
queryFn: async () => {
const {
data: { groups }
} = await apiRequest.get<{ groups: (TSshHostGroup & { hostCount: number })[] }>(
- `/api/v2/workspace/${projectId}/ssh-host-groups`
+ `/api/v1/projects/${projectId}/ssh-host-groups`
);
return groups;
},
@@ -936,10 +836,10 @@ export const useListWorkspaceSshHostGroups = (projectId: string) => {
export const useListWorkspaceSshCertificateTemplates = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceSshCertificateTemplates(projectId),
+ queryKey: projectKeys.getProjectSshCertificateTemplates(projectId),
queryFn: async () => {
const { data } = await apiRequest.get<{ certificateTemplates: TSshCertificateTemplate[] }>(
- `/api/v2/workspace/${projectId}/ssh-certificate-templates`
+ `/api/v1/projects/${projectId}/ssh-certificate-templates`
);
return data;
},
@@ -948,18 +848,18 @@ export const useListWorkspaceSshCertificateTemplates = (projectId: string) => {
};
export const useGetWorkspaceWorkflowIntegrationConfig = ({
- workspaceId,
+ projectId,
integration
}: {
- workspaceId: string;
+ projectId: string;
integration: WorkflowIntegrationPlatform;
}) => {
return useQuery({
- queryKey: workspaceKeys.getWorkspaceWorkflowIntegrationConfig(workspaceId, integration),
+ queryKey: projectKeys.getProjectWorkflowIntegrationConfig(projectId, integration),
queryFn: async () => {
const { data } = await apiRequest
.get<ProjectWorkflowIntegrationConfig>(
- `/api/v1/workspace/${workspaceId}/workflow-integration-config/${integration}`
+ `/api/v1/projects/${projectId}/workflow-integration-config/${integration}`
)
.catch((err) => {
if (err.response.status === 404) {
@@ -971,16 +871,16 @@ export const useGetWorkspaceWorkflowIntegrationConfig = ({
return data;
},
- enabled: Boolean(workspaceId)
+ enabled: Boolean(projectId)
});
};
export const useGetProjectSshConfig = (projectId: string) => {
return useQuery({
- queryKey: workspaceKeys.getProjectSshConfig(projectId),
+ queryKey: projectKeys.getProjectSshConfig(projectId),
queryFn: async () => {
const { data } = await apiRequest.get<TProjectSshConfig>(
- `/api/v1/workspace/${projectId}/ssh-config`
+ `/api/v1/projects/${projectId}/ssh-config`
);
return data;
diff --git a/frontend/src/hooks/api/projects/query-keys.tsx b/frontend/src/hooks/api/projects/query-keys.tsx
new file mode 100644
index 0000000000..51e3db71cb
--- /dev/null
+++ b/frontend/src/hooks/api/projects/query-keys.tsx
@@ -0,0 +1,77 @@
+import type { CaStatus } from "../ca";
+import { WorkflowIntegrationPlatform } from "../workflowIntegrations/types";
+import { TListProjectIdentitiesDTO, TSearchProjectsDTO } from "./types";
+
+export const projectKeys = {
+ getProjectById: (projectId: string) => ["projects", { projectId }] as const,
+ getProjectSecrets: (projectId: string) => [{ projectId }, "project-secrets"] as const,
+ getProjectIndexStatus: (projectId: string) => [{ projectId }, "project-index-status"] as const,
+ getProjectUpgradeStatus: (projectId: string) => [{ projectId }, "project-upgrade-status"],
+ getProjectMemberships: (orgId: string) => [{ orgId }, "project-memberships"],
+ getProjectAuthorization: (projectId: string) => [{ projectId }, "project-authorizations"],
+ getProjectIntegrations: (projectId: string) => [{ projectId }, "project-integrations"],
+ getAllUserProjects: () => ["projects"] as const,
+ getProjectAuditLogs: (projectId: string) => [{ projectId }, "project-audit-logs"] as const,
+ getProjectUsers: (
+ projectId: string,
+ includeGroupMembers: boolean = false,
+ roles: string[] = []
+ ) => [{ projectId, includeGroupMembers, roles }, "project-users"] as const,
+ getProjectUserDetails: (projectId: string, membershipId: string) =>
+ [{ projectId, membershipId }, "project-user-details"] as const,
+ getProjectIdentityMemberships: (projectId: string) =>
+ [{ projectId }, "project-identity-memberships"] as const,
+ getProjectIdentityMembershipDetails: (projectId: string, identityId: string) =>
+ [{ projectId, identityId }, "project-identity-membership-details"] as const,
+ // allows invalidation using above key without knowing params
+ getProjectIdentityMembershipsWithParams: ({ projectId, ...params }: TListProjectIdentitiesDTO) =>
+ [...projectKeys.getProjectIdentityMemberships(projectId), params] as const,
+ searchProject: (dto: TSearchProjectsDTO) => ["search-projects", dto] as const,
+ getProjectGroupMemberships: (projectId: string) => [{ projectId }, "project-groups"] as const,
+ getProjectGroupMembershipDetails: (projectId: string, groupId: string) =>
+ [{ projectId, groupId }, "project-group-membership-details"] as const,
+ getProjectCas: ({ projectId }: { projectId: string }) => [{ projectId }, "project-cas"] as const,
+ specificProjectCas: ({ projectId, status }: { projectId: string; status?: CaStatus }) =>
+ [...projectKeys.getProjectCas({ projectId }), { status }] as const,
+ allProjectCertificates: () => ["project-certificates"] as const,
+ forProjectCertificates: (projectId: string) =>
+ [...projectKeys.allProjectCertificates(), projectId] as const,
+ specificProjectCertificates: ({
+ projectId,
+ offset,
+ limit
+ }: {
+ projectId: string;
+ offset: number;
+ limit: number;
+ }) => [...projectKeys.forProjectCertificates(projectId), { offset, limit }] as const,
+ getProjectPkiAlerts: (projectId: string) => [{ projectId }, "project-pki-alerts"] as const,
+ getProjectPkiSubscribers: (projectId: string) =>
+ [{ projectId }, "project-pki-subscribers"] as const,
+ getProjectPkiCollections: (projectId: string) =>
+ [{ projectId }, "project-pki-collections"] as const,
+ getProjectCertificateTemplates: (projectId: string) =>
+ [{ projectId }, "project-certificate-templates"] as const,
+ getProjectWorkflowIntegrationConfig: (
+ projectId: string,
+ integration: WorkflowIntegrationPlatform
+ ) => [{ projectId, integration }, "project-workflow-integration-config"] as const,
+ getProjectSshCas: (projectId: string) => [{ projectId }, "project-ssh-cas"] as const,
+ allProjectSshCertificates: (projectId: string) =>
+ [{ projectId }, "project-ssh-certificates"] as const,
+ getProjectSshHosts: (projectId: string) => [{ projectId }, "project-ssh-hosts"] as const,
+ getProjectSshHostGroups: (projectId: string) =>
+ [{ projectId }, "project-ssh-host-groups"] as const,
+ specificProjectSshCertificates: ({
+ offset,
+ limit,
+ projectId
+ }: {
+ offset: number;
+ limit: number;
+ projectId: string;
+ }) => [...projectKeys.allProjectSshCertificates(projectId), { offset, limit }] as const,
+ getProjectSshCertificateTemplates: (projectId: string) =>
+ [{ projectId }, "project-ssh-certificate-templates"] as const,
+ getProjectSshConfig: (projectId: string) => [{ projectId }, "project-ssh-config"] as const
+};
diff --git a/frontend/src/hooks/api/workspace/types.ts b/frontend/src/hooks/api/projects/types.ts
similarity index 84%
rename from frontend/src/hooks/api/workspace/types.ts
rename to frontend/src/hooks/api/projects/types.ts
index 33eb0909f9..59b242d059 100644
--- a/frontend/src/hooks/api/workspace/types.ts
+++ b/frontend/src/hooks/api/projects/types.ts
@@ -20,7 +20,7 @@ export enum ProjectUserMembershipTemporaryMode {
Relative = "relative"
}
-export type Workspace = {
+export type Project = {
__v: number;
id: string;
name: string;
@@ -31,7 +31,7 @@ export type Workspace = {
upgradeStatus: string | null;
updatedAt: string;
autoCapitalization: boolean;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
pitVersionLimit: number;
auditLogsRetentionDays: number;
slug: string;
@@ -43,16 +43,16 @@ export type Workspace = {
secretDetectionIgnoreValues: string[];
};
-export type WorkspaceEnv = {
+export type ProjectEnv = {
id: string;
name: string;
slug: string;
};
-export type WorkspaceTag = { id: string; name: string; slug: string };
+export type ProjectTag = { id: string; name: string; slug: string };
export type NameWorkspaceSecretsDTO = {
- workspaceId: string;
+ projectId: string;
secretsToUpdate: {
secretName: string;
secretId: string;
@@ -76,30 +76,33 @@ export type CreateWorkspaceDTO = {
};
export type UpdateProjectDTO = {
- projectID: string;
+ projectId: string;
newProjectName?: string;
newProjectDescription?: string;
newSlug?: string;
secretSharing?: boolean;
showSnapshotsLegacy?: boolean;
secretDetectionIgnoreValues?: string[];
+ pitVersionLimit?: number;
+ autoCapitalization?: boolean;
+ hasDeleteProtection?: boolean;
};
export type UpdatePitVersionLimitDTO = { projectSlug: string; pitVersionLimit: number };
export type UpdateAuditLogsRetentionDTO = { projectSlug: string; auditLogsRetentionDays: number };
-export type ToggleAutoCapitalizationDTO = { workspaceID: string; state: boolean };
-export type ToggleDeleteProjectProtectionDTO = { workspaceID: string; state: boolean };
+export type ToggleAutoCapitalizationDTO = { projectID: string; state: boolean };
+export type ToggleDeleteProjectProtectionDTO = { projectID: string; state: boolean };
-export type DeleteWorkspaceDTO = { workspaceID: string };
+export type DeleteWorkspaceDTO = { projectID: string };
export type CreateEnvironmentDTO = {
- workspaceId: string;
+ projectId: string;
name: string;
slug: string;
};
export type ReorderEnvironmentsDTO = {
- workspaceId: string;
+ projectId: string;
environmentSlug: string;
environmentName: string;
otherEnvironmentSlug: string;
@@ -107,18 +110,18 @@ export type ReorderEnvironmentsDTO = {
};
export type UpdateEnvironmentDTO = {
- workspaceId: string;
+ projectId: string;
id: string;
name?: string;
slug?: string;
position?: number;
};
-export type DeleteEnvironmentDTO = { workspaceId: string; id: string };
+export type DeleteEnvironmentDTO = { projectId: string; id: string };
export type TUpdateWorkspaceUserRoleDTO = {
membershipId: string;
- workspaceId: string;
+ projectId: string;
roles: (
| {
role: string;
@@ -136,7 +139,7 @@ export type TUpdateWorkspaceUserRoleDTO = {
export type TUpdateWorkspaceIdentityRoleDTO = {
identityId: string;
- workspaceId: string;
+ projectId: string;
roles: (
| {
role: string;
@@ -171,7 +174,7 @@ export type TUpdateWorkspaceGroupRoleDTO = {
};
export type TListProjectIdentitiesDTO = {
- workspaceId: string;
+ projectId: string;
offset?: number;
limit?: number;
orderBy?: ProjectIdentityOrderBy;
@@ -186,6 +189,7 @@ export type TSearchProjectsDTO = {
name?: string;
limit?: number;
offset?: number;
+ projectIds?: string[];
type?: ProjectType;
options?: { enabled?: boolean };
orderBy?: ProjectIdentityOrderBy;
diff --git a/frontend/src/hooks/api/relays/index.tsx b/frontend/src/hooks/api/relays/index.tsx
new file mode 100644
index 0000000000..177955438b
--- /dev/null
+++ b/frontend/src/hooks/api/relays/index.tsx
@@ -0,0 +1,3 @@
+export * from "./mutations";
+export * from "./queries";
+export * from "./types";
diff --git a/frontend/src/hooks/api/relays/mutations.tsx b/frontend/src/hooks/api/relays/mutations.tsx
new file mode 100644
index 0000000000..4e1d52a672
--- /dev/null
+++ b/frontend/src/hooks/api/relays/mutations.tsx
@@ -0,0 +1,17 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { relayQueryKeys } from "./queries";
+
+export const useDeleteRelayById = () => {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => {
+ return apiRequest.delete(`/api/v1/relays/${id}`);
+ },
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: relayQueryKeys.list() });
+ }
+ });
+};
diff --git a/frontend/src/hooks/api/relays/queries.tsx b/frontend/src/hooks/api/relays/queries.tsx
new file mode 100644
index 0000000000..2747243563
--- /dev/null
+++ b/frontend/src/hooks/api/relays/queries.tsx
@@ -0,0 +1,21 @@
+import { useQuery } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { TRelay } from "./types";
+
+export const relayQueryKeys = {
+ list: () => ["relays"] as const
+};
+
+const fetchRelays = async (): Promise<TRelay[]> => {
+ const { data } = await apiRequest.get<TRelay[]>("/api/v1/relays");
+ return data;
+};
+
+export const useGetRelays = () => {
+ return useQuery({
+ queryKey: relayQueryKeys.list(),
+ queryFn: fetchRelays
+ });
+};
diff --git a/frontend/src/hooks/api/relays/types.ts b/frontend/src/hooks/api/relays/types.ts
new file mode 100644
index 0000000000..621fd52db4
--- /dev/null
+++ b/frontend/src/hooks/api/relays/types.ts
@@ -0,0 +1,13 @@
+export type TRelay = {
+ id: string;
+ createdAt: string;
+ updatedAt: string;
+ orgId: string | null;
+ identityId: string | null;
+ name: string;
+ host: string;
+};
+
+export type TDeleteRelayDTO = {
+ id: string;
+};
diff --git a/frontend/src/hooks/api/roles/mutation.tsx b/frontend/src/hooks/api/roles/mutation.tsx
index 6df9aa937c..e9caa68d5a 100644
--- a/frontend/src/hooks/api/roles/mutation.tsx
+++ b/frontend/src/hooks/api/roles/mutation.tsx
@@ -22,7 +22,7 @@ export const useCreateProjectRole = () => {
mutationFn: async ({ projectId, ...dto }: TCreateProjectRoleDTO) => {
const {
data: { role }
- } = await apiRequest.post(`/api/v2/workspace/${projectId}/roles`, dto);
+ } = await apiRequest.post(`/api/v1/projects/${projectId}/roles`, dto);
return role;
},
onSuccess: (_, { projectId }) => {
@@ -38,7 +38,7 @@ export const useUpdateProjectRole = () => {
mutationFn: async ({ id, projectId, ...dto }: TUpdateProjectRoleDTO) => {
const {
data: { role }
- } = await apiRequest.patch(`/api/v2/workspace/${projectId}/roles/${id}`, dto);
+ } = await apiRequest.patch(`/api/v1/projects/${projectId}/roles/${id}`, dto);
return role;
},
onSuccess: (_, { projectId, slug }) => {
@@ -58,7 +58,7 @@ export const useDeleteProjectRole = () => {
mutationFn: async ({ projectId, id }: TDeleteProjectRoleDTO) => {
const {
data: { role }
- } = await apiRequest.delete(`/api/v2/workspace/${projectId}/roles/${id}`);
+ } = await apiRequest.delete(`/api/v1/projects/${projectId}/roles/${id}`);
return role;
},
onSuccess: (_, { projectId }) => {
diff --git a/frontend/src/hooks/api/roles/queries.tsx b/frontend/src/hooks/api/roles/queries.tsx
index a406b6d454..fd7b28db92 100644
--- a/frontend/src/hooks/api/roles/queries.tsx
+++ b/frontend/src/hooks/api/roles/queries.tsx
@@ -46,13 +46,13 @@ export const roleQueryKeys = {
getOrgRole: (orgId: string, roleId: string) => [{ orgId, roleId }, "org-role"] as const,
getUserOrgPermissions: ({ orgId }: TGetUserOrgPermissionsDTO) =>
["user-permissions", { orgId }] as const,
- getUserProjectPermissions: ({ workspaceId }: TGetUserProjectPermissionDTO) =>
- ["user-project-permissions", { workspaceId }] as const
+ getUserProjectPermissions: ({ projectId }: TGetUserProjectPermissionDTO) =>
+ ["user-project-permissions", { projectId }] as const
};
export const getProjectRoles = async (projectId: string) => {
const { data } = await apiRequest.get<{ roles: Array<Omit<TProjectRole, "permissions">> }>(
- `/api/v2/workspace/${projectId}/roles`
+ `/api/v1/projects/${projectId}/roles`
);
return data.roles;
};
@@ -69,7 +69,7 @@ export const useGetProjectRoleBySlug = (projectId: string, roleSlug: string) =>
queryKey: roleQueryKeys.getProjectRoleBySlug(projectId, roleSlug),
queryFn: async () => {
const { data } = await apiRequest.get<{ role: TProjectRole }>(
- `/api/v2/workspace/${projectId}/roles/slug/${roleSlug}`
+ `/api/v1/projects/${projectId}/roles/slug/${roleSlug}`
);
return data.role;
},
@@ -131,9 +131,7 @@ export const useGetUserOrgPermissions = ({ orgId }: TGetUserOrgPermissionsDTO) =
}
});
-export const fetchUserProjectPermissions = async ({
- workspaceId
-}: TGetUserProjectPermissionDTO) => {
+export const fetchUserProjectPermissions = async ({ projectId }: TGetUserProjectPermissionDTO) => {
const { data } = await apiRequest.get<{
data: {
permissions: PackRule<RawRuleOf<MongoAbility<OrgPermissionSet>>>[];
@@ -145,16 +143,16 @@ export const fetchUserProjectPermissions = async ({
actorName: string;
};
};
- }>(`/api/v1/workspace/${workspaceId}/permissions`, {});
+ }>(`/api/v1/projects/${projectId}/permissions`, {});
return data.data;
};
-export const useGetUserProjectPermissions = ({ workspaceId }: TGetUserProjectPermissionDTO) =>
+export const useGetUserProjectPermissions = ({ projectId }: TGetUserProjectPermissionDTO) =>
useQuery({
- queryKey: roleQueryKeys.getUserProjectPermissions({ workspaceId }),
- queryFn: () => fetchUserProjectPermissions({ workspaceId }),
- enabled: Boolean(workspaceId),
+ queryKey: roleQueryKeys.getUserProjectPermissions({ projectId }),
+ queryFn: () => fetchUserProjectPermissions({ projectId }),
+ enabled: Boolean(projectId),
select: (data) => {
const rule = unpackRules<RawRuleOf<MongoAbility<ProjectPermissionSet>>>(data.permissions);
const negatedRules = groupBy(
diff --git a/frontend/src/hooks/api/roles/types.ts b/frontend/src/hooks/api/roles/types.ts
index 12286bf9be..e94f133059 100644
--- a/frontend/src/hooks/api/roles/types.ts
+++ b/frontend/src/hooks/api/roles/types.ts
@@ -9,7 +9,7 @@ export enum ProjectMembershipRole {
}
export type TGetProjectRolesDTO = {
- workspaceId?: string;
+ projectId?: string;
};
export type TProjectRole = {
@@ -52,7 +52,7 @@ export type TGetUserOrgPermissionsDTO = {
};
export type TGetUserProjectPermissionDTO = {
- workspaceId: string;
+ projectId: string;
};
export type TCreateOrgRoleDTO = {
diff --git a/frontend/src/hooks/api/secretApproval/mutation.tsx b/frontend/src/hooks/api/secretApproval/mutation.tsx
index 8370d03674..c8fe51d194 100644
--- a/frontend/src/hooks/api/secretApproval/mutation.tsx
+++ b/frontend/src/hooks/api/secretApproval/mutation.tsx
@@ -11,7 +11,7 @@ export const useCreateSecretApprovalPolicy = () => {
return useMutation<object, object, TCreateSecretPolicyDTO>({
mutationFn: async ({
environments,
- workspaceId,
+ projectId,
approvals,
approvers,
bypassers,
@@ -20,9 +20,9 @@ export const useCreateSecretApprovalPolicy = () => {
enforcementLevel,
allowedSelfApprovals
}) => {
- const { data } = await apiRequest.post("/api/v1/secret-approvals", {
+ const { data } = await apiRequest.post("/api/v2/secret-approvals", {
environments,
- workspaceId,
+ projectId,
approvals,
approvers,
bypassers,
@@ -33,9 +33,9 @@ export const useCreateSecretApprovalPolicy = () => {
});
return data;
},
- onSuccess: (_, { workspaceId }) => {
+ onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: secretApprovalKeys.getApprovalPolicies(workspaceId)
+ queryKey: secretApprovalKeys.getApprovalPolicies(projectId)
});
}
});
@@ -56,7 +56,7 @@ export const useUpdateSecretApprovalPolicy = () => {
allowedSelfApprovals,
environments
}) => {
- const { data } = await apiRequest.patch(`/api/v1/secret-approvals/${id}`, {
+ const { data } = await apiRequest.patch(`/api/v2/secret-approvals/${id}`, {
approvals,
approvers,
bypassers,
@@ -68,9 +68,9 @@ export const useUpdateSecretApprovalPolicy = () => {
});
return data;
},
- onSuccess: (_, { workspaceId }) => {
+ onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: secretApprovalKeys.getApprovalPolicies(workspaceId)
+ queryKey: secretApprovalKeys.getApprovalPolicies(projectId)
});
}
});
@@ -81,12 +81,12 @@ export const useDeleteSecretApprovalPolicy = () => {
return useMutation<object, object, TDeleteSecretPolicyDTO>({
mutationFn: async ({ id }) => {
- const { data } = await apiRequest.delete(`/api/v1/secret-approvals/${id}`);
+ const { data } = await apiRequest.delete(`/api/v2/secret-approvals/${id}`);
return data;
},
- onSuccess: (_, { workspaceId }) => {
+ onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: secretApprovalKeys.getApprovalPolicies(workspaceId)
+ queryKey: secretApprovalKeys.getApprovalPolicies(projectId)
});
}
});
diff --git a/frontend/src/hooks/api/secretApproval/queries.tsx b/frontend/src/hooks/api/secretApproval/queries.tsx
index 52c3743fbf..e81af93b85 100644
--- a/frontend/src/hooks/api/secretApproval/queries.tsx
+++ b/frontend/src/hooks/api/secretApproval/queries.tsx
@@ -10,54 +10,53 @@ import {
} from "./types";
export const secretApprovalKeys = {
- getApprovalPolicies: (workspaceId: string) =>
- [{ workspaceId }, "secret-approval-policies"] as const,
- getApprovalPolicyOfABoard: (workspaceId: string, environment: string, secretPath: string) => [
- { workspaceId, environment, secretPath },
+ getApprovalPolicies: (projectId: string) => [{ projectId }, "secret-approval-policies"] as const,
+ getApprovalPolicyOfABoard: (projectId: string, environment: string, secretPath: string) => [
+ { projectId, environment, secretPath },
"Secret-approval-policy"
]
};
-const fetchApprovalPolicies = async (workspaceId: string) => {
+const fetchApprovalPolicies = async (projectId: string) => {
const { data } = await apiRequest.get<{ approvals: TSecretApprovalPolicy[] }>(
- "/api/v1/secret-approvals",
- { params: { workspaceId } }
+ "/api/v2/secret-approvals",
+ { params: { projectId } }
);
return data.approvals;
};
export const useGetSecretApprovalPolicies = ({
- workspaceId,
+ projectId,
options = {}
}: TGetSecretApprovalPoliciesDTO & TReactQueryOptions) =>
useQuery({
- queryKey: secretApprovalKeys.getApprovalPolicies(workspaceId),
- queryFn: () => fetchApprovalPolicies(workspaceId),
+ queryKey: secretApprovalKeys.getApprovalPolicies(projectId),
+ queryFn: () => fetchApprovalPolicies(projectId),
...options,
- enabled: Boolean(workspaceId) && (options?.enabled ?? true)
+ enabled: Boolean(projectId) && (options?.enabled ?? true)
});
const fetchApprovalPolicyOfABoard = async (
- workspaceId: string,
+ projectId: string,
environment: string,
secretPath: string
) => {
const { data } = await apiRequest.get<{ policy: TSecretApprovalPolicy }>(
- "/api/v1/secret-approvals/board",
- { params: { workspaceId, environment, secretPath } }
+ "/api/v2/secret-approvals/board",
+ { params: { projectId, environment, secretPath } }
);
return data.policy || "";
};
export const useGetSecretApprovalPolicyOfABoard = ({
- workspaceId,
+ projectId,
secretPath = "/",
environment,
options = {}
}: TGetSecretApprovalPolicyOfBoardDTO & TReactQueryOptions) =>
useQuery({
- queryKey: secretApprovalKeys.getApprovalPolicyOfABoard(workspaceId, environment, secretPath),
- queryFn: () => fetchApprovalPolicyOfABoard(workspaceId, environment, secretPath),
+ queryKey: secretApprovalKeys.getApprovalPolicyOfABoard(projectId, environment, secretPath),
+ queryFn: () => fetchApprovalPolicyOfABoard(projectId, environment, secretPath),
...options,
- enabled: Boolean(workspaceId && secretPath && environment) && (options?.enabled ?? true)
+ enabled: Boolean(projectId && secretPath && environment) && (options?.enabled ?? true)
});
diff --git a/frontend/src/hooks/api/secretApproval/types.ts b/frontend/src/hooks/api/secretApproval/types.ts
index 1785ffa8ac..ac912c401b 100644
--- a/frontend/src/hooks/api/secretApproval/types.ts
+++ b/frontend/src/hooks/api/secretApproval/types.ts
@@ -1,11 +1,11 @@
import { EnforcementLevel } from "../policies/enums";
-import { WorkspaceEnv } from "../workspace/types";
+import { ProjectEnv } from "../projects/types";
export type TSecretApprovalPolicy = {
id: string;
- workspace: string;
+ project: string;
name: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
secretPath?: string;
approvals: number;
approvers: Approver[];
@@ -36,17 +36,17 @@ export type Bypasser = {
};
export type TGetSecretApprovalPoliciesDTO = {
- workspaceId: string;
+ projectId: string;
};
export type TGetSecretApprovalPolicyOfBoardDTO = {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
};
export type TCreateSecretPolicyDTO = {
- workspaceId: string;
+ projectId: string;
name?: string;
environments: string[];
secretPath: string;
@@ -67,12 +67,12 @@ export type TUpdateSecretPolicyDTO = {
allowedSelfApprovals?: boolean;
enforcementLevel?: EnforcementLevel;
// for invalidating list
- workspaceId: string;
+ projectId: string;
environments?: string[];
};
export type TDeleteSecretPolicyDTO = {
id: string;
// for invalidating list
- workspaceId: string;
+ projectId: string;
};
diff --git a/frontend/src/hooks/api/secretApprovalRequest/mutation.tsx b/frontend/src/hooks/api/secretApprovalRequest/mutation.tsx
index 78e1b37a1d..6a03b431ca 100644
--- a/frontend/src/hooks/api/secretApprovalRequest/mutation.tsx
+++ b/frontend/src/hooks/api/secretApprovalRequest/mutation.tsx
@@ -36,9 +36,9 @@ export const useUpdateSecretApprovalRequestStatus = () => {
});
return data;
},
- onSuccess: (_, { id, workspaceId }) => {
+ onSuccess: (_, { id, projectId }) => {
queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.detail({ id }) });
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
}
});
};
@@ -53,10 +53,10 @@ export const usePerformSecretApprovalRequestMerge = () => {
});
return data;
},
- onSuccess: (_, { id, workspaceId }) => {
+ onSuccess: (_, { id, projectId }) => {
queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.detail({ id }) });
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.list({ workspaceId }) });
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.list({ projectId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
}
});
};
diff --git a/frontend/src/hooks/api/secretApprovalRequest/queries.tsx b/frontend/src/hooks/api/secretApprovalRequest/queries.tsx
index a1736f70f7..63cdd455e2 100644
--- a/frontend/src/hooks/api/secretApprovalRequest/queries.tsx
+++ b/frontend/src/hooks/api/secretApprovalRequest/queries.tsx
@@ -14,7 +14,7 @@ import {
export const secretApprovalRequestKeys = {
list: ({
- workspaceId,
+ projectId,
environment,
status,
committer,
@@ -23,20 +23,20 @@ export const secretApprovalRequestKeys = {
search
}: TGetSecretApprovalRequestList) =>
[
- { workspaceId, environment, status, committer, offset, limit, search },
+ { projectId, environment, status, committer, offset, limit, search },
"secret-approval-requests"
] as const,
detail: ({ id }: Omit<TGetSecretApprovalRequestDetails, "decryptKey">) =>
[{ id }, "secret-approval-request-detail"] as const,
- count: ({ workspaceId, policyId }: TGetSecretApprovalRequestCount) => [
- { workspaceId },
+ count: ({ projectId, policyId }: TGetSecretApprovalRequestCount) => [
+ { projectId },
"secret-approval-request-count",
...(policyId ? [policyId] : [])
]
};
const fetchSecretApprovalRequestList = async ({
- workspaceId,
+ projectId,
environment,
committer,
status = "open",
@@ -49,7 +49,7 @@ const fetchSecretApprovalRequestList = async ({
totalCount: number;
}>("/api/v1/secret-approval-requests", {
params: {
- workspaceId,
+ projectId,
environment,
committer,
status,
@@ -63,7 +63,7 @@ const fetchSecretApprovalRequestList = async ({
};
export const useGetSecretApprovalRequests = ({
- workspaceId,
+ projectId,
environment,
options = {},
status,
@@ -74,7 +74,7 @@ export const useGetSecretApprovalRequests = ({
}: TGetSecretApprovalRequestList & TReactQueryOptions) =>
useQuery({
queryKey: secretApprovalRequestKeys.list({
- workspaceId,
+ projectId,
environment,
committer,
status,
@@ -84,7 +84,7 @@ export const useGetSecretApprovalRequests = ({
}),
queryFn: () =>
fetchSecretApprovalRequestList({
- workspaceId,
+ projectId,
environment,
status,
committer,
@@ -92,7 +92,7 @@ export const useGetSecretApprovalRequests = ({
offset,
search
}),
- enabled: Boolean(workspaceId) && (options?.enabled ?? true),
+ enabled: Boolean(projectId) && (options?.enabled ?? true),
placeholderData: (previousData) => previousData
});
@@ -127,19 +127,19 @@ export const useGetSecretApprovalRequestDetails = ({
});
const fetchSecretApprovalRequestCount = async ({
- workspaceId,
+ projectId,
policyId
}: TGetSecretApprovalRequestCount) => {
const { data } = await apiRequest.get<{ approvals: TSecretApprovalRequestCount }>(
"/api/v1/secret-approval-requests/count",
- { params: { workspaceId, policyId } }
+ { params: { projectId, policyId } }
);
return data.approvals;
};
export const useGetSecretApprovalRequestCount = ({
- workspaceId,
+ projectId,
policyId,
options = {}
}: TGetSecretApprovalRequestCount & {
@@ -154,8 +154,8 @@ export const useGetSecretApprovalRequestCount = ({
>;
}) =>
useQuery({
- queryKey: secretApprovalRequestKeys.count({ workspaceId, policyId }),
+ queryKey: secretApprovalRequestKeys.count({ projectId, policyId }),
refetchInterval: 15000,
- queryFn: () => fetchSecretApprovalRequestCount({ workspaceId, policyId }),
- enabled: Boolean(workspaceId) && (options?.enabled ?? true)
+ queryFn: () => fetchSecretApprovalRequestCount({ projectId, policyId }),
+ enabled: Boolean(projectId) && (options?.enabled ?? true)
});
diff --git a/frontend/src/hooks/api/secretApprovalRequest/types.ts b/frontend/src/hooks/api/secretApprovalRequest/types.ts
index 0eef3fa3d6..5a381e871b 100644
--- a/frontend/src/hooks/api/secretApprovalRequest/types.ts
+++ b/frontend/src/hooks/api/secretApprovalRequest/types.ts
@@ -55,7 +55,7 @@ export type TSecretApprovalRequest = {
username: string;
isOrgMembershipActive: boolean;
}[];
- workspace: string;
+ project: string;
environment: string;
folderId: string;
secretPath: string;
@@ -110,7 +110,7 @@ export type TSecretApprovalRequestCount = {
};
export type TGetSecretApprovalRequestList = {
- workspaceId: string;
+ projectId: string;
environment?: string;
status?: "open" | "close";
committer?: string;
@@ -120,7 +120,7 @@ export type TGetSecretApprovalRequestList = {
};
export type TGetSecretApprovalRequestCount = {
- workspaceId: string;
+ projectId: string;
policyId?: string;
};
@@ -137,11 +137,11 @@ export type TUpdateSecretApprovalReviewStatusDTO = {
export type TUpdateSecretApprovalRequestStatusDTO = {
status: "open" | "close";
id: string;
- workspaceId: string;
+ projectId: string;
};
export type TPerformSecretApprovalRequestMerge = {
id: string;
- workspaceId: string;
+ projectId: string;
bypassReason?: string;
};
diff --git a/frontend/src/hooks/api/secretFolders/queries.tsx b/frontend/src/hooks/api/secretFolders/queries.tsx
index 9e12f329da..3e752eed31 100644
--- a/frontend/src/hooks/api/secretFolders/queries.tsx
+++ b/frontend/src/hooks/api/secretFolders/queries.tsx
@@ -30,10 +30,10 @@ export const folderQueryKeys = {
["secret-folders", "environment", projectId] as const
};
-const fetchProjectFolders = async (workspaceId: string, environment: string, path = "/") => {
- const { data } = await apiRequest.get<{ folders: TSecretFolder[] }>("/api/v1/folders", {
+const fetchProjectFolders = async (projectId: string, environment: string, path = "/") => {
+ const { data } = await apiRequest.get<{ folders: TSecretFolder[] }>("/api/v2/folders", {
params: {
- workspaceId,
+ projectId,
environment,
path
}
@@ -57,7 +57,7 @@ export const useListProjectEnvironmentsFolders = (
queryKey: folderQueryKeys.getProjectEnvironmentsFolders(projectId),
queryFn: async () => {
const { data } = await apiRequest.get<TProjectEnvironmentsFolders>(
- `/api/v1/workspace/${projectId}/environment-folder-tree`
+ `/api/v1/projects/${projectId}/environment-folder-tree`
);
return data;
},
@@ -145,9 +145,9 @@ export const useCreateFolder = () => {
return useMutation<object, object, TCreateFolderDTO>({
mutationFn: async (dto) => {
- const { data } = await apiRequest.post("/api/v1/folders", {
+ const { data } = await apiRequest.post("/api/v2/folders", {
...dto,
- workspaceId: dto.projectId
+ projectId: dto.projectId
});
return data;
},
@@ -162,13 +162,13 @@ export const useCreateFolder = () => {
queryKey: folderQueryKeys.getSecretFolders({ projectId, environment, path })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ workspaceId: projectId, environment, directory: path })
+ queryKey: secretSnapshotKeys.list({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ workspaceId: projectId, environment, directory: path })
+ queryKey: secretSnapshotKeys.count({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId: projectId, environment, directory: path })
+ queryKey: commitKeys.count({ projectId, environment, directory: path })
});
}
});
@@ -179,10 +179,10 @@ export const useUpdateFolder = () => {
return useMutation<object, object, TUpdateFolderDTO>({
mutationFn: async ({ path = "/", folderId, name, environment, projectId, description }) => {
- const { data } = await apiRequest.patch(`/api/v1/folders/${folderId}`, {
+ const { data } = await apiRequest.patch(`/api/v2/folders/${folderId}`, {
name,
environment,
- workspaceId: projectId,
+ projectId,
path,
description
});
@@ -199,16 +199,16 @@ export const useUpdateFolder = () => {
queryKey: folderQueryKeys.getSecretFolders({ projectId, environment, path })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ workspaceId: projectId, environment, directory: path })
+ queryKey: secretSnapshotKeys.list({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ workspaceId: projectId, environment, directory: path })
+ queryKey: secretSnapshotKeys.count({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId: projectId, environment, directory: path })
+ queryKey: commitKeys.count({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId: projectId, environment, directory: path })
+ queryKey: commitKeys.history({ projectId, environment, directory: path })
});
}
});
@@ -219,10 +219,10 @@ export const useDeleteFolder = () => {
return useMutation<object, object, TDeleteFolderDTO>({
mutationFn: async ({ path = "/", folderId, environment, projectId }) => {
- const { data } = await apiRequest.delete(`/api/v1/folders/${folderId}`, {
+ const { data } = await apiRequest.delete(`/api/v2/folders/${folderId}`, {
data: {
environment,
- workspaceId: projectId,
+ projectId,
path
}
});
@@ -239,16 +239,16 @@ export const useDeleteFolder = () => {
queryKey: folderQueryKeys.getSecretFolders({ projectId, environment, path })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ workspaceId: projectId, environment, directory: path })
+ queryKey: secretSnapshotKeys.list({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ workspaceId: projectId, environment, directory: path })
+ queryKey: secretSnapshotKeys.count({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId: projectId, environment, directory: path })
+ queryKey: commitKeys.count({ projectId, environment, directory: path })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId: projectId, environment, directory: path })
+ queryKey: commitKeys.history({ projectId, environment, directory: path })
});
}
});
@@ -258,9 +258,9 @@ export const useUpdateFolderBatch = () => {
const queryClient = useQueryClient();
return useMutation<object, object, TUpdateFolderBatchDTO>({
- mutationFn: async ({ projectSlug, folders }) => {
- const { data } = await apiRequest.patch("/api/v1/folders/batch", {
- projectSlug,
+ mutationFn: async ({ projectId, folders }) => {
+ const { data } = await apiRequest.patch("/api/v2/folders/batch", {
+ projectId,
folders
});
@@ -283,28 +283,28 @@ export const useUpdateFolderBatch = () => {
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.list({
- workspaceId: projectId,
+ projectId,
environment: folder.environment,
directory: folder.path
})
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.count({
- workspaceId: projectId,
+ projectId,
environment: folder.environment,
directory: folder.path
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.count({
- workspaceId: projectId,
+ projectId,
environment: folder.environment,
directory: folder.path
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.history({
- workspaceId: projectId,
+ projectId,
environment: folder.environment,
directory: folder.path
})
diff --git a/frontend/src/hooks/api/secretFolders/types.ts b/frontend/src/hooks/api/secretFolders/types.ts
index dc9bce70f6..e9ee2ae5d0 100644
--- a/frontend/src/hooks/api/secretFolders/types.ts
+++ b/frontend/src/hooks/api/secretFolders/types.ts
@@ -1,4 +1,4 @@
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
export enum ReservedFolders {
SecretReplication = "__reserve_replication_"
@@ -22,7 +22,7 @@ export type TSecretFolder = {
export type TSecretFolderWithPath = TSecretFolder & { path: string };
export type TProjectEnvironmentsFolders = {
- [key: string]: WorkspaceEnv & { folders: TSecretFolderWithPath[] };
+ [key: string]: ProjectEnv & { folders: TSecretFolderWithPath[] };
};
export type TGetProjectFoldersDTO = {
@@ -63,7 +63,6 @@ export type TDeleteFolderDTO = {
export type TUpdateFolderBatchDTO = {
projectId: string;
- projectSlug: string;
folders: {
name: string;
environment: string;
diff --git a/frontend/src/hooks/api/secretImports/mutation.tsx b/frontend/src/hooks/api/secretImports/mutation.tsx
index 72254bae25..c9484ccfb3 100644
--- a/frontend/src/hooks/api/secretImports/mutation.tsx
+++ b/frontend/src/hooks/api/secretImports/mutation.tsx
@@ -16,10 +16,10 @@ export const useCreateSecretImport = () => {
return useMutation<object, object, TCreateSecretImportDTO>({
mutationFn: async ({ import: secretImport, environment, isReplication, projectId, path }) => {
- const { data } = await apiRequest.post("/api/v1/secret-imports", {
+ const { data } = await apiRequest.post("/api/v2/secret-imports", {
import: secretImport,
environment,
- workspaceId: projectId,
+ projectId,
path,
isReplication
});
@@ -44,11 +44,11 @@ export const useUpdateSecretImport = () => {
return useMutation<object, object, TUpdateSecretImportDTO>({
mutationFn: async ({ environment, import: secretImports, projectId, path, id }) => {
- const { data } = await apiRequest.patch(`/api/v1/secret-imports/${id}`, {
+ const { data } = await apiRequest.patch(`/api/v2/secret-imports/${id}`, {
import: secretImports,
environment,
path,
- workspaceId: projectId
+ projectId
});
return data;
},
@@ -69,10 +69,10 @@ export const useUpdateSecretImport = () => {
export const useResyncSecretReplication = () => {
return useMutation<object, object, TResyncSecretReplicationDTO>({
mutationFn: async ({ environment, projectId, path, id }) => {
- const { data } = await apiRequest.post(`/api/v1/secret-imports/${id}/replication-resync`, {
+ const { data } = await apiRequest.post(`/api/v2/secret-imports/${id}/replication-resync`, {
environment,
path,
- workspaceId: projectId
+ projectId
});
return data;
}
@@ -84,9 +84,9 @@ export const useDeleteSecretImport = () => {
return useMutation<object, object, TDeleteSecretImportDTO>({
mutationFn: async ({ id, projectId, path, environment }) => {
- const { data } = await apiRequest.delete(`/api/v1/secret-imports/${id}`, {
+ const { data } = await apiRequest.delete(`/api/v2/secret-imports/${id}`, {
data: {
- workspaceId: projectId,
+ projectId,
path,
environment
}
diff --git a/frontend/src/hooks/api/secretImports/queries.tsx b/frontend/src/hooks/api/secretImports/queries.tsx
index ea6ea68ef5..5d80c36498 100644
--- a/frontend/src/hooks/api/secretImports/queries.tsx
+++ b/frontend/src/hooks/api/secretImports/queries.tsx
@@ -30,10 +30,10 @@ export const secretImportKeys = {
const fetchSecretImport = async ({ projectId, environment, path = "/" }: TGetSecretImports) => {
const { data } = await apiRequest.get<{ secretImports: TSecretImport[] }>(
- "/api/v1/secret-imports",
+ "/api/v2/secret-imports",
{
params: {
- workspaceId: projectId,
+ projectId,
environment,
path
}
@@ -65,16 +65,12 @@ export const useGetSecretImports = ({
queryFn: () => fetchSecretImport({ path, projectId, environment })
});
-const fetchImportedSecrets = async (
- workspaceId: string,
- environment: string,
- directory?: string
-) => {
+const fetchImportedSecrets = async (projectId: string, environment: string, directory?: string) => {
const { data } = await apiRequest.get<{ secrets: TImportedSecrets[] }>(
- "/api/v1/secret-imports/secrets/raw",
+ "/api/v1/dashboard/secret-imports",
{
params: {
- workspaceId,
+ projectId,
environment,
path: directory
}
@@ -89,10 +85,10 @@ const fetchImportedFolders = async ({
path
}: TGetImportedFoldersByEnvDTO) => {
const { data } = await apiRequest.get<{ secretImports: TSecretImport[] }>(
- "/api/v1/secret-imports",
+ "/api/v2/secret-imports",
{
params: {
- workspaceId: projectId,
+ projectId,
environment,
path
}
@@ -136,13 +132,13 @@ export const useGetImportedSecretsSingleEnv = ({
id: encSecret.id,
env: encSecret.environment,
key: encSecret.secretKey,
- value: encSecret.secretValue,
secretValueHidden: encSecret.secretValueHidden,
tags: encSecret.tags,
comment: encSecret.secretComment,
createdAt: encSecret.createdAt,
updatedAt: encSecret.updatedAt,
- version: encSecret.version
+ version: encSecret.version,
+ isEmpty: encSecret.isEmpty
};
})
}));
@@ -176,7 +172,6 @@ export const useGetImportedSecretsAllEnvs = ({
id: encSecret.id,
env: encSecret.environment,
key: encSecret.secretKey,
- value: encSecret.secretValue,
secretValueHidden: encSecret.secretValueHidden,
tags: encSecret.tags,
comment: encSecret.secretComment,
@@ -237,7 +232,9 @@ export const useGetImportedSecretsAllEnvs = ({
return {
secret: secret?.secrets.find((s) => s.key === secretName),
- environmentInfo: secret?.environmentInfo
+ environmentInfo: secret?.environmentInfo,
+ secretPath: secret?.secretPath,
+ environment: secret?.environment
};
}
return undefined;
diff --git a/frontend/src/hooks/api/secretImports/types.ts b/frontend/src/hooks/api/secretImports/types.ts
index d950c2ca26..d17641398b 100644
--- a/frontend/src/hooks/api/secretImports/types.ts
+++ b/frontend/src/hooks/api/secretImports/types.ts
@@ -1,11 +1,11 @@
+import { ProjectEnv } from "../projects/types";
import { SecretV3Raw } from "../secrets/types";
-import { WorkspaceEnv } from "../workspace/types";
export type TSecretImport = {
id: string;
folderId: string;
importPath: string;
- importEnv: WorkspaceEnv;
+ importEnv: ProjectEnv;
position: string;
createdAt: string;
updatedAt: string;
@@ -25,10 +25,10 @@ export type TGetImportedFoldersByEnvDTO = {
export type TImportedSecrets = {
environment: string;
- environmentInfo: WorkspaceEnv;
+ environmentInfo: ProjectEnv;
secretPath: string;
folderId: string;
- secrets: SecretV3Raw[];
+ secrets: Omit<SecretV3Raw, "secretValue">[];
};
export type TGetSecretImports = {
diff --git a/frontend/src/hooks/api/secretRotation/types.ts b/frontend/src/hooks/api/secretRotation/types.ts
index 19c4cdcdf4..c5f939c5c6 100644
--- a/frontend/src/hooks/api/secretRotation/types.ts
+++ b/frontend/src/hooks/api/secretRotation/types.ts
@@ -1,4 +1,4 @@
-import { WorkspaceEnv } from "../workspace/types";
+import { ProjectEnv } from "../projects/types";
export enum TProviderFunctionTypes {
HTTP = "http",
@@ -80,7 +80,7 @@ export type TSecretRotation = {
customProvider: string;
workspace: string;
envId: string;
- environment: WorkspaceEnv;
+ environment: ProjectEnv;
secretPath: string;
outputs: Array<{
key: string;
diff --git a/frontend/src/hooks/api/secretSnapshots/queries.tsx b/frontend/src/hooks/api/secretSnapshots/queries.tsx
index daee390543..f5492918ca 100644
--- a/frontend/src/hooks/api/secretSnapshots/queries.tsx
+++ b/frontend/src/hooks/api/secretSnapshots/queries.tsx
@@ -14,25 +14,25 @@ import {
} from "./types";
export const secretSnapshotKeys = {
- list: ({ workspaceId, environment, directory }: Omit<TGetSecretSnapshotsDTO, "limit">) =>
- [{ workspaceId, environment, directory }, "secret-snapshot"] as const,
+ list: ({ projectId, environment, directory }: Omit<TGetSecretSnapshotsDTO, "limit">) =>
+ [{ projectId, environment, directory }, "secret-snapshot"] as const,
snapshotData: (snapshotId: string) => [{ snapshotId }, "secret-snapshot"] as const,
- count: ({ environment, workspaceId, directory }: Omit<TGetSecretSnapshotsDTO, "limit">) => [
- { workspaceId, environment, directory },
+ count: ({ environment, projectId, directory }: Omit<TGetSecretSnapshotsDTO, "limit">) => [
+ { projectId, environment, directory },
"count",
"secret-snapshot"
]
};
const fetchWorkspaceSnaphots = async ({
- workspaceId,
+ projectId,
environment,
directory = "/",
limit = 10,
offset = 0
}: TGetSecretSnapshotsDTO & { offset: number }) => {
const res = await apiRequest.get<{ secretSnapshots: TSecretSnapshot[] }>(
- `/api/v1/workspace/${workspaceId}/secret-snapshots`,
+ `/api/v1/projects/${projectId}/secret-snapshots`,
{
params: {
limit,
@@ -49,7 +49,7 @@ const fetchWorkspaceSnaphots = async ({
export const useGetWorkspaceSnapshotList = (dto: TGetSecretSnapshotsDTO & { isPaused?: boolean }) =>
useInfiniteQuery({
initialPageParam: 0,
- enabled: Boolean(dto.workspaceId && dto.environment) && !dto.isPaused,
+ enabled: Boolean(dto.projectId && dto.environment) && !dto.isPaused,
queryKey: secretSnapshotKeys.list({ ...dto }),
queryFn: ({ pageParam }) => fetchWorkspaceSnaphots({ ...dto, offset: pageParam }),
getNextPageParam: (lastPage, pages) =>
@@ -115,12 +115,12 @@ export const useGetSnapshotSecrets = ({ snapshotId }: TSnapshotDataProps) =>
});
const fetchWorkspaceSecretSnaphotCount = async (
- workspaceId: string,
+ projectId: string,
environment: string,
directory = "/"
) => {
const res = await apiRequest.get<{ count: number }>(
- `/api/v1/workspace/${workspaceId}/secret-snapshots/count`,
+ `/api/v1/projects/${projectId}/secret-snapshots/count`,
{
params: {
environment,
@@ -132,15 +132,15 @@ const fetchWorkspaceSecretSnaphotCount = async (
};
export const useGetWsSnapshotCount = ({
- workspaceId,
+ projectId,
environment,
directory,
isPaused
}: Omit<TGetSecretSnapshotsDTO, "limit"> & { isPaused?: boolean }) =>
useQuery({
- enabled: Boolean(workspaceId && environment) && !isPaused,
- queryKey: secretSnapshotKeys.count({ workspaceId, environment, directory }),
- queryFn: () => fetchWorkspaceSecretSnaphotCount(workspaceId, environment, directory)
+ enabled: Boolean(projectId && environment) && !isPaused,
+ queryKey: secretSnapshotKeys.count({ projectId, environment, directory }),
+ queryFn: () => fetchWorkspaceSecretSnaphotCount(projectId, environment, directory)
});
export const usePerformSecretRollback = () => {
@@ -151,22 +151,22 @@ export const usePerformSecretRollback = () => {
const { data } = await apiRequest.post(`/api/v1/secret-snapshot/${snapshotId}/rollback`);
return data;
},
- onSuccess: (_, { workspaceId, environment, directory }) => {
+ onSuccess: (_, { projectId, environment, directory }) => {
queryClient.invalidateQueries({
- queryKey: [{ workspaceId, environment, secretPath: directory }, "secrets"]
+ queryKey: [{ projectId, environment, secretPath: directory }, "secrets"]
});
queryClient.invalidateQueries({
- queryKey: ["secret-folders", { projectId: workspaceId, environment, path: directory }]
+ queryKey: ["secret-folders", { projectId, environment, path: directory }]
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ workspaceId, environment, directory })
+ queryKey: secretSnapshotKeys.list({ projectId, environment, directory })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ workspaceId, environment, directory })
+ queryKey: secretSnapshotKeys.count({ projectId, environment, directory })
});
queryClient.invalidateQueries({
queryKey: dashboardKeys.getDashboardSecrets({
- projectId: workspaceId,
+ projectId,
secretPath: directory ?? "/"
})
});
diff --git a/frontend/src/hooks/api/secretSnapshots/types.ts b/frontend/src/hooks/api/secretSnapshots/types.ts
index e7ebb18de1..9b1f954805 100644
--- a/frontend/src/hooks/api/secretSnapshots/types.ts
+++ b/frontend/src/hooks/api/secretSnapshots/types.ts
@@ -1,9 +1,9 @@
import { SecretVersions } from "../secrets/types";
-import { WorkspaceEnv } from "../types";
+import { ProjectEnv } from "../types";
export type TSecretSnapshot = {
id: string;
- workspace: string;
+ projectId: string;
secretVersions: string[];
createdAt: string;
updatedAt: string;
@@ -13,7 +13,7 @@ export type TSnapshotData = Omit<TSecretSnapshot, "secretVersions"> & {
id: string;
secretVersions: (SecretVersions & { isRotatedSecret?: boolean })[];
folderVersion: Array<{ name: string; id: string }>;
- environment: WorkspaceEnv;
+ environment: ProjectEnv;
};
export type TSnapshotDataProps = {
@@ -22,7 +22,7 @@ export type TSnapshotDataProps = {
};
export type TGetSecretSnapshotsDTO = {
- workspaceId: string;
+ projectId: string;
limit: number;
environment: string;
directory?: string;
@@ -30,7 +30,7 @@ export type TGetSecretSnapshotsDTO = {
export type TSecretRollbackDTO = {
snapshotId: string;
- workspaceId: string;
+ projectId: string;
environment: string;
directory?: string;
};
diff --git a/frontend/src/hooks/api/secrets/mutations.tsx b/frontend/src/hooks/api/secrets/mutations.tsx
index 11ebad4b13..de960cd04f 100644
--- a/frontend/src/hooks/api/secrets/mutations.tsx
+++ b/frontend/src/hooks/api/secrets/mutations.tsx
@@ -33,18 +33,18 @@ export const useCreateSecretV3 = ({
secretPath = "/",
type,
environment,
- workspaceId,
+ projectId,
secretKey,
secretValue,
secretComment,
skipMultilineEncoding,
tagIds
}) => {
- const { data } = await apiRequest.post(`/api/v3/secrets/raw/${secretKey}`, {
+ const { data } = await apiRequest.post(`/api/v4/secrets/${secretKey}`, {
secretPath,
type,
environment,
- workspaceId,
+ projectId,
secretValue,
secretComment,
skipMultilineEncoding,
@@ -52,26 +52,26 @@ export const useCreateSecretV3 = ({
});
return data;
},
- onSuccess: (_, { workspaceId, environment, secretPath }) => {
+ onSuccess: (_, { projectId, environment, secretPath }) => {
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
},
...options
});
@@ -88,7 +88,7 @@ export const useUpdateSecretV3 = ({
secretPath = "/",
type,
environment,
- workspaceId,
+ projectId,
secretKey,
secretValue,
tagIds,
@@ -100,8 +100,8 @@ export const useUpdateSecretV3 = ({
skipMultilineEncoding,
secretMetadata
}) => {
- const { data } = await apiRequest.patch(`/api/v3/secrets/raw/${secretKey}`, {
- workspaceId,
+ const { data } = await apiRequest.patch(`/api/v4/secrets/${secretKey}`, {
+ projectId,
environment,
type,
secretReminderNote,
@@ -117,26 +117,26 @@ export const useUpdateSecretV3 = ({
});
return data;
},
- onSuccess: (_, { workspaceId, environment, secretPath }) => {
+ onSuccess: (_, { projectId, environment, secretPath }) => {
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
},
...options
});
@@ -150,17 +150,10 @@ export const useDeleteSecretV3 = ({
const queryClient = useQueryClient();
return useMutation<object, object, TDeleteSecretsV3DTO>({
- mutationFn: async ({
- secretPath = "/",
- type,
- environment,
- workspaceId,
- secretKey,
- secretId
- }) => {
- const { data } = await apiRequest.delete(`/api/v3/secrets/raw/${secretKey}`, {
+ mutationFn: async ({ secretPath = "/", type, environment, projectId, secretKey, secretId }) => {
+ const { data } = await apiRequest.delete(`/api/v4/secrets/${secretKey}`, {
data: {
- workspaceId,
+ projectId,
environment,
type,
secretPath,
@@ -169,26 +162,26 @@ export const useDeleteSecretV3 = ({
});
return data;
},
- onSuccess: (_, { workspaceId, environment, secretPath }) => {
+ onSuccess: (_, { projectId, environment, secretPath }) => {
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
},
...options
});
@@ -202,35 +195,35 @@ export const useCreateSecretBatch = ({
const queryClient = useQueryClient();
return useMutation<object, object, TCreateSecretBatchDTO>({
- mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets }) => {
- const { data } = await apiRequest.post("/api/v3/secrets/batch/raw", {
- workspaceId,
+ mutationFn: async ({ secretPath = "/", projectId, environment, secrets }) => {
+ const { data } = await apiRequest.post("/api/v4/secrets/batch", {
+ projectId,
environment,
secretPath,
secrets
});
return data;
},
- onSuccess: (_, { workspaceId, environment, secretPath }) => {
+ onSuccess: (_, { projectId, environment, secretPath }) => {
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
},
...options
});
@@ -244,35 +237,35 @@ export const useUpdateSecretBatch = ({
const queryClient = useQueryClient();
return useMutation<object, object, TUpdateSecretBatchDTO>({
- mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets }) => {
- const { data } = await apiRequest.patch("/api/v3/secrets/batch/raw", {
- workspaceId,
+ mutationFn: async ({ secretPath = "/", projectId, environment, secrets }) => {
+ const { data } = await apiRequest.patch("/api/v4/secrets/batch", {
+ projectId,
environment,
secretPath,
secrets
});
return data;
},
- onSuccess: (_, { workspaceId, environment, secretPath }) => {
+ onSuccess: (_, { projectId, environment, secretPath }) => {
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
},
...options
});
@@ -286,10 +279,10 @@ export const useDeleteSecretBatch = ({
const queryClient = useQueryClient();
return useMutation<object, object, TDeleteSecretBatchDTO>({
- mutationFn: async ({ secretPath = "/", workspaceId, environment, secrets }) => {
- const { data } = await apiRequest.delete("/api/v3/secrets/batch/raw", {
+ mutationFn: async ({ secretPath = "/", projectId, environment, secrets }) => {
+ const { data } = await apiRequest.delete("/api/v4/secrets/batch", {
data: {
- workspaceId,
+ projectId,
environment,
secretPath,
secrets
@@ -297,26 +290,26 @@ export const useDeleteSecretBatch = ({
});
return data;
},
- onSuccess: (_, { workspaceId, environment, secretPath }) => {
+ onSuccess: (_, { projectId, environment, secretPath }) => {
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
},
...options
});
@@ -340,23 +333,23 @@ export const useMoveSecrets = ({
mutationFn: async ({
sourceEnvironment,
sourceSecretPath,
- projectSlug,
destinationEnvironment,
destinationSecretPath,
secretIds,
- shouldOverwrite
+ shouldOverwrite,
+ projectId
}) => {
const { data } = await apiRequest.post<{
isSourceUpdated: boolean;
isDestinationUpdated: boolean;
- }>("/api/v3/secrets/move", {
+ }>("/api/v4/secrets/move", {
sourceEnvironment,
sourceSecretPath,
- projectSlug,
destinationEnvironment,
destinationSecretPath,
secretIds,
- shouldOverwrite
+ shouldOverwrite,
+ projectId
});
return data;
@@ -370,7 +363,7 @@ export const useMoveSecrets = ({
});
queryClient.invalidateQueries({
queryKey: secretKeys.getProjectSecret({
- workspaceId: projectId,
+ projectId,
environment: sourceEnvironment,
secretPath: sourceSecretPath
})
@@ -378,33 +371,33 @@ export const useMoveSecrets = ({
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.list({
environment: sourceEnvironment,
- workspaceId: projectId,
+ projectId,
directory: sourceSecretPath
})
});
queryClient.invalidateQueries({
queryKey: secretSnapshotKeys.count({
environment: sourceEnvironment,
- workspaceId: projectId,
+ projectId,
directory: sourceSecretPath
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.count({
- workspaceId: projectId,
+ projectId,
environment: sourceEnvironment,
directory: sourceSecretPath
})
});
queryClient.invalidateQueries({
queryKey: commitKeys.history({
- workspaceId: projectId,
+ projectId,
environment: sourceEnvironment,
directory: sourceSecretPath
})
});
queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ workspaceId: projectId })
+ queryKey: secretApprovalRequestKeys.count({ projectId })
});
},
...options
@@ -412,14 +405,14 @@ export const useMoveSecrets = ({
};
export const createSecret = async (dto: TCreateSecretsV3DTO) => {
- const { data } = await apiRequest.post(`/api/v3/secrets/${dto.secretKey}`, dto);
+ const { data } = await apiRequest.post(`/api/v4/secrets/${dto.secretKey}`, dto);
return data;
};
export const useBackfillSecretReference = () =>
useMutation<{ message: string }, object, { projectId: string }>({
mutationFn: async ({ projectId }) => {
- const { data } = await apiRequest.post("/api/v3/secrets/backfill-secret-references", {
+ const { data } = await apiRequest.post("/api/v4/secrets/backfill-secret-references", {
projectId
});
return data.message;
@@ -432,16 +425,16 @@ export const useCreateCommit = () => {
object,
object,
{
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
pendingChanges: PendingChanges;
message: string;
}
>({
- mutationFn: async ({ workspaceId, environment, secretPath, pendingChanges, message }) => {
+ mutationFn: async ({ projectId, environment, secretPath, pendingChanges, message }) => {
const { data } = await apiRequest.post("/api/v1/pit/batch/commit", {
- projectId: workspaceId,
+ projectId,
environment,
secretPath,
changes: {
@@ -501,26 +494,26 @@ export const useCreateCommit = () => {
});
return data;
},
- onSuccess: (_, { workspaceId, environment, secretPath }) => {
+ onSuccess: (_, { projectId, environment, secretPath }) => {
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ environment, workspaceId, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({ environment, projectId, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
- queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ workspaceId }) });
+ queryClient.invalidateQueries({ queryKey: secretApprovalRequestKeys.count({ projectId }) });
}
});
};
diff --git a/frontend/src/hooks/api/secrets/queries.tsx b/frontend/src/hooks/api/secrets/queries.tsx
index 443b74df89..95d0b9cdff 100644
--- a/frontend/src/hooks/api/secrets/queries.tsx
+++ b/frontend/src/hooks/api/secrets/queries.tsx
@@ -6,6 +6,7 @@ import axios from "axios";
import { createNotification } from "@app/components/notifications";
import { apiRequest } from "@app/config/request";
import { useToggle } from "@app/hooks/useToggle";
+import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
import { ERROR_NOT_ALLOWED_READ_SECRETS } from "./constants";
import {
@@ -21,41 +22,45 @@ import {
TGetProjectSecretsKey,
TGetSecretAccessListDTO,
TGetSecretReferenceTreeDTO,
- TSecretReferenceTraceNode
+ TGetSecretVersionValue,
+ TSecretReferenceTraceNode,
+ TSecretVersionValue
} from "./types";
export const secretKeys = {
// this is also used in secretSnapshot part
getProjectSecret: ({
- workspaceId,
+ projectId,
environment,
secretPath,
viewSecretValue
}: TGetProjectSecretsKey) =>
- [{ workspaceId, environment, secretPath, viewSecretValue }, "secrets"] as const,
+ [{ projectId, environment, secretPath, viewSecretValue }, "secrets"] as const,
getSecretVersion: (secretId: string) => [{ secretId }, "secret-versions"] as const,
+ getSecretVersionValue: (secretId: string, version: number) =>
+ ["secret-versions", secretId, version] as const,
getSecretAccessList: ({
- workspaceId,
+ projectId,
environment,
secretPath,
secretKey
}: TGetSecretAccessListDTO) =>
- ["secret-access-list", { workspaceId, environment, secretPath, secretKey }] as const,
+ ["secret-access-list", { projectId, environment, secretPath, secretKey }] as const,
getSecretReferenceTree: (dto: TGetSecretReferenceTreeDTO) => ["secret-reference-tree", dto]
};
export const fetchProjectSecrets = async ({
- workspaceId,
+ projectId,
environment,
secretPath,
includeImports,
expandSecretReferences,
viewSecretValue
}: TGetProjectSecretsKey) => {
- const { data } = await apiRequest.get<SecretV3RawResponse>("/api/v3/secrets/raw", {
+ const { data } = await apiRequest.get<SecretV3RawResponse>("/api/v4/secrets", {
params: {
environment,
- workspaceId,
+ projectId,
secretPath,
viewSecretValue,
expandSecretReferences,
@@ -67,14 +72,17 @@ export const fetchProjectSecrets = async ({
};
export const mergePersonalSecrets = (rawSecrets: SecretV3Raw[]) => {
- const personalSecrets: Record<string, { id: string; value?: string; env: string }> = {};
+ const personalSecrets: Record<
+ string,
+ { id: string; value?: string; env: string; isEmpty?: boolean }
+ > = {};
const secrets: SecretV3RawSanitized[] = [];
rawSecrets.forEach((el) => {
const decryptedSecret: SecretV3RawSanitized = {
id: el.id,
env: el.environment,
key: el.secretKey,
- value: el.secretValue,
+ value: el.secretValueHidden ? HIDDEN_SECRET_VALUE : el.secretValue,
secretValueHidden: el.secretValueHidden,
tags: el.tags || [],
comment: el.secretComment || "",
@@ -89,14 +97,16 @@ export const mergePersonalSecrets = (rawSecrets: SecretV3Raw[]) => {
secretMetadata: el.secretMetadata,
isRotatedSecret: el.isRotatedSecret,
rotationId: el.rotationId,
- reminder: el.reminder
+ reminder: el.reminder,
+ isEmpty: el.isEmpty
};
if (el.type === SecretType.Personal) {
personalSecrets[decryptedSecret.key] = {
id: el.id,
value: el.secretValue,
- env: el.environment
+ env: el.environment,
+ isEmpty: el.isEmpty
};
} else {
secrets.push(decryptedSecret);
@@ -109,6 +119,8 @@ export const mergePersonalSecrets = (rawSecrets: SecretV3Raw[]) => {
sec.idOverride = personalSecret.id;
sec.valueOverride = personalSecret.value;
sec.overrideAction = "modified";
+ sec.isEmpty = personalSecret.isEmpty;
+ sec.secretValueHidden = false;
}
});
@@ -116,7 +128,7 @@ export const mergePersonalSecrets = (rawSecrets: SecretV3Raw[]) => {
};
export const useGetProjectSecrets = ({
- workspaceId,
+ projectId,
environment,
secretPath,
viewSecretValue,
@@ -135,14 +147,14 @@ export const useGetProjectSecrets = ({
useQuery({
...options,
// wait for all values to be available
- enabled: Boolean(workspaceId && environment) && (options?.enabled ?? true),
+ enabled: Boolean(projectId && environment) && (options?.enabled ?? true),
queryKey: secretKeys.getProjectSecret({
- workspaceId,
+ projectId,
environment,
secretPath,
viewSecretValue
}),
- queryFn: () => fetchProjectSecrets({ workspaceId, environment, secretPath, viewSecretValue }),
+ queryFn: () => fetchProjectSecrets({ projectId, environment, secretPath, viewSecretValue }),
select: useCallback(
(data: Awaited<ReturnType<typeof fetchProjectSecrets>>) => mergePersonalSecrets(data.secrets),
[]
@@ -150,7 +162,7 @@ export const useGetProjectSecrets = ({
});
export const useGetProjectSecretsAllEnv = ({
- workspaceId,
+ projectId,
envs,
secretPath
}: TGetProjectSecretsAllEnvDTO) => {
@@ -159,11 +171,11 @@ export const useGetProjectSecretsAllEnv = ({
const secrets = useQueries({
queries: envs.map((environment) => ({
queryKey: secretKeys.getProjectSecret({
- workspaceId,
+ projectId,
environment,
secretPath
}),
- enabled: Boolean(workspaceId && environment),
+ enabled: Boolean(projectId && environment),
onError: (error: unknown) => {
if (axios.isAxiosError(error) && !isErrorHandled) {
const { message, requestId } = error.response?.data as {
@@ -187,7 +199,7 @@ export const useGetProjectSecretsAllEnv = ({
setIsErrorHandled.on();
}
},
- queryFn: () => fetchProjectSecrets({ workspaceId, environment, secretPath }),
+ queryFn: () => fetchProjectSecrets({ projectId, environment, secretPath }),
staleTime: 60 * 1000,
// eslint-disable-next-line react-hooks/rules-of-hooks
select: useCallback(
@@ -238,7 +250,7 @@ export const useGetProjectSecretsAllEnv = ({
const fetchEncryptedSecretVersion = async (secretId: string, offset: number, limit: number) => {
const { data } = await apiRequest.get<{ secretVersions: SecretVersions[] }>(
- `/api/v1/secret/${secretId}/secret-versions`,
+ `/api/v1/dashboard/secret-versions/${secretId}`,
{
params: {
limit,
@@ -259,6 +271,26 @@ export const useGetSecretVersion = (dto: GetSecretVersionsDTO) =>
}, [])
});
+export const fetchSecretVersionValue = async (secretId: string, version: number) => {
+ const { data } = await apiRequest.get<TSecretVersionValue>(
+ `/api/v1/dashboard/secret-versions/${secretId}/value/${version}`
+ );
+ return data.value;
+};
+
+export const useGetSecretVersionValue = (
+ dto: TGetSecretVersionValue,
+ options?: Omit<
+ UseQueryOptions<string, unknown, string, ReturnType<typeof secretKeys.getSecretVersionValue>>,
+ "queryKey" | "queryFn"
+ >
+) =>
+ useQuery({
+ queryKey: secretKeys.getSecretVersionValue(dto.secretId, dto.version),
+ queryFn: () => fetchSecretVersionValue(dto.secretId, dto.version),
+ ...options
+ });
+
export const useGetSecretAccessList = (dto: TGetSecretAccessListDTO) =>
useQuery({
enabled: Boolean(dto.secretKey),
@@ -270,7 +302,7 @@ export const useGetSecretAccessList = (dto: TGetSecretAccessListDTO) =>
users: SecretAccessListEntry[];
}>(`/api/v1/secrets/${dto.secretKey}/access-list`, {
params: {
- workspaceId: dto.workspaceId,
+ projectId: dto.projectId,
environment: dto.environment,
secretPath: dto.secretPath
}
@@ -287,11 +319,11 @@ const fetchSecretReferenceTree = async ({
environmentSlug
}: TGetSecretReferenceTreeDTO) => {
const { data } = await apiRequest.get<{ tree: TSecretReferenceTraceNode; value: string }>(
- `/api/v3/secrets/raw/${secretKey}/secret-reference-tree`,
+ `/api/v4/secrets/${secretKey}/secret-reference-tree`,
{
params: {
secretPath,
- workspaceId: projectId,
+ projectId,
environment: environmentSlug
}
}
diff --git a/frontend/src/hooks/api/secrets/types.ts b/frontend/src/hooks/api/secrets/types.ts
index 1b232cfac3..68a3852c0c 100644
--- a/frontend/src/hooks/api/secrets/types.ts
+++ b/frontend/src/hooks/api/secrets/types.ts
@@ -17,30 +17,6 @@ export type SecretReminderRecipient = {
};
id: string;
};
-export type EncryptedSecret = {
- id: string;
- version: number;
- workspace: string;
- type: SecretType;
- environment: string;
- secretKeyCiphertext: string;
- secretKeyIV: string;
- secretKeyTag: string;
- secretValueCiphertext: string;
- secretValueIV: string;
- secretValueTag: string;
- secretValueHidden: boolean;
- __v: number;
- createdAt: string;
- updatedAt: string;
- skipMultilineEncoding?: boolean;
- secretCommentCiphertext: string;
- secretCommentIV: string;
- secretCommentTag: string;
- secretReminderRepeatDays?: number | null;
- secretReminderNote?: string | null;
- tags: WsTag[];
-};
// both personal and shared secret stitched together for dashboard
export type SecretV3RawSanitized = {
@@ -71,12 +47,13 @@ export type SecretV3RawSanitized = {
isPending?: boolean;
pendingAction?: PendingAction;
reminder?: Reminder;
+ isEmpty?: boolean;
};
export type SecretV3Raw = {
id: string;
_id: string;
- workspace: string;
+ project: string;
environment: string;
version: number;
type: string;
@@ -97,6 +74,7 @@ export type SecretV3Raw = {
rotationId?: string;
secretReminderRecipients?: SecretReminderRecipient[];
reminder?: Reminder;
+ isEmpty?: boolean;
};
export type SecretV3RawResponse = {
@@ -113,7 +91,7 @@ export type SecretVersions = {
id: string;
secretId: string;
version: number;
- workspace: string;
+ project: string;
type: SecretType;
isDeleted: boolean;
envId: string;
@@ -136,7 +114,7 @@ export type SecretVersions = {
// dto
export type TGetProjectSecretsKey = {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath?: string;
includeImports?: boolean;
@@ -148,7 +126,7 @@ export type TGetProjectSecretsKey = {
export type TGetProjectSecretsDTO = TGetProjectSecretsKey;
export type TGetProjectSecretsAllEnvDTO = {
- workspaceId: string;
+ projectId: string;
envs: string[];
folderId?: string;
secretPath?: string;
@@ -161,8 +139,17 @@ export type GetSecretVersionsDTO = {
offset: number;
};
+export type TGetSecretVersionValue = {
+ secretId: string;
+ version: number;
+};
+
+export type TSecretVersionValue = {
+ value: string;
+};
+
export type TGetSecretAccessListDTO = {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
secretKey: string;
@@ -174,14 +161,14 @@ export type TCreateSecretsV3DTO = {
secretComment: string;
skipMultilineEncoding?: boolean;
secretPath: string;
- workspaceId: string;
+ projectId: string;
environment: string;
type: SecretType;
tagIds?: string[];
};
export type TUpdateSecretsV3DTO = {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
type: SecretType;
@@ -198,7 +185,7 @@ export type TUpdateSecretsV3DTO = {
};
export type TDeleteSecretsV3DTO = {
- workspaceId: string;
+ projectId: string;
environment: string;
type: SecretType;
secretPath: string;
@@ -207,7 +194,7 @@ export type TDeleteSecretsV3DTO = {
};
export type TCreateSecretBatchDTO = {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
secrets: Array<{
@@ -224,7 +211,7 @@ export type TCreateSecretBatchDTO = {
};
export type TUpdateSecretBatchDTO = {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
secrets: Array<{
@@ -241,7 +228,7 @@ export type TUpdateSecretBatchDTO = {
};
export type TDeleteSecretBatchDTO = {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
secrets: Array<{
@@ -251,7 +238,6 @@ export type TDeleteSecretBatchDTO = {
};
export type TMoveSecretsDTO = {
- projectSlug: string;
projectId: string;
sourceEnvironment: string;
sourceSecretPath: string;
diff --git a/frontend/src/hooks/api/serviceTokens/queries.tsx b/frontend/src/hooks/api/serviceTokens/queries.tsx
index 06b9b09c6f..41421b2796 100644
--- a/frontend/src/hooks/api/serviceTokens/queries.tsx
+++ b/frontend/src/hooks/api/serviceTokens/queries.tsx
@@ -13,9 +13,9 @@ const serviceTokenKeys = {
getAllWorkspaceServiceToken: (workspaceID: string) => [{ workspaceID }, "service-tokens"] as const
};
-const fetchWorkspaceServiceTokens = async (workspaceID: string) => {
+const fetchWorkspaceServiceTokens = async (projectID: string) => {
const { data } = await apiRequest.get<{ serviceTokenData: ServiceToken[] }>(
- `/api/v1/workspace/${workspaceID}/service-token-data`
+ `/api/v1/projects/${projectID}/service-token-data`
);
return data.serviceTokenData;
diff --git a/frontend/src/hooks/api/sshCa/mutations.tsx b/frontend/src/hooks/api/sshCa/mutations.tsx
index c7e90c3b9d..fc6c43ef40 100644
--- a/frontend/src/hooks/api/sshCa/mutations.tsx
+++ b/frontend/src/hooks/api/sshCa/mutations.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace/query-keys";
+import { projectKeys } from "../projects/query-keys";
import {
TCreateSshCaDTO,
TDeleteSshCaDTO,
@@ -28,7 +28,7 @@ export const useCreateSshCa = () => {
return ca;
},
onSuccess: ({ projectId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceSshCas(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectSshCas(projectId) });
}
});
};
@@ -43,7 +43,7 @@ export const useUpdateSshCa = () => {
return ca;
},
onSuccess: ({ projectId }, { caId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceSshCas(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectSshCas(projectId) });
queryClient.invalidateQueries({ queryKey: sshCaKeys.getSshCaById(caId) });
}
});
@@ -59,7 +59,7 @@ export const useDeleteSshCa = () => {
return ca;
},
onSuccess: ({ projectId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceSshCas(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectSshCas(projectId) });
}
});
};
@@ -76,7 +76,7 @@ export const useSignSshKey = () => {
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.allWorkspaceSshCertificates(projectId)
+ queryKey: projectKeys.allProjectSshCertificates(projectId)
});
}
});
@@ -94,7 +94,7 @@ export const useIssueSshCreds = () => {
},
onSuccess: (_, { projectId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.allWorkspaceSshCertificates(projectId)
+ queryKey: projectKeys.allProjectSshCertificates(projectId)
});
}
});
diff --git a/frontend/src/hooks/api/sshHost/mutations.tsx b/frontend/src/hooks/api/sshHost/mutations.tsx
index f6b831f3e7..0c1b67103a 100644
--- a/frontend/src/hooks/api/sshHost/mutations.tsx
+++ b/frontend/src/hooks/api/sshHost/mutations.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace/query-keys";
+import { projectKeys } from "../projects/query-keys";
import { TCreateSshHostDTO, TDeleteSshHostDTO, TSshHost, TUpdateSshHostDTO } from "./types";
export const useCreateSshHost = () => {
@@ -13,7 +13,7 @@ export const useCreateSshHost = () => {
return host;
},
onSuccess: ({ projectId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceSshHosts(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectSshHosts(projectId) });
}
});
};
@@ -26,7 +26,7 @@ export const useUpdateSshHost = () => {
return host;
},
onSuccess: ({ projectId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceSshHosts(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectSshHosts(projectId) });
}
});
};
@@ -39,7 +39,7 @@ export const useDeleteSshHost = () => {
return host;
},
onSuccess: ({ projectId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceSshHosts(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectSshHosts(projectId) });
}
});
};
diff --git a/frontend/src/hooks/api/sshHostGroup/mutations.tsx b/frontend/src/hooks/api/sshHostGroup/mutations.tsx
index b75cff1872..fa9eebb07e 100644
--- a/frontend/src/hooks/api/sshHostGroup/mutations.tsx
+++ b/frontend/src/hooks/api/sshHostGroup/mutations.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace/query-keys";
+import { projectKeys } from "../projects/query-keys";
import { sshHostGroupKeys } from "./queries";
import {
TCreateSshHostGroupDTO,
@@ -20,7 +20,7 @@ export const useCreateSshHostGroup = () => {
},
onSuccess: ({ projectId, id }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceSshHostGroups(projectId)
+ queryKey: projectKeys.getProjectSshHostGroups(projectId)
});
queryClient.invalidateQueries({
queryKey: sshHostGroupKeys.getSshHostGroupById(id)
@@ -41,10 +41,10 @@ export const useUpdateSshHostGroup = () => {
},
onSuccess: ({ projectId }, { sshHostGroupId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceSshHostGroups(projectId)
+ queryKey: projectKeys.getProjectSshHostGroups(projectId)
});
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceSshHosts(projectId)
+ queryKey: projectKeys.getProjectSshHosts(projectId)
});
queryClient.invalidateQueries({
queryKey: sshHostGroupKeys.getSshHostGroupById(sshHostGroupId)
@@ -64,10 +64,10 @@ export const useDeleteSshHostGroup = () => {
},
onSuccess: ({ projectId }, { sshHostGroupId }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceSshHostGroups(projectId)
+ queryKey: projectKeys.getProjectSshHostGroups(projectId)
});
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceSshHosts(projectId)
+ queryKey: projectKeys.getProjectSshHosts(projectId)
});
queryClient.invalidateQueries({
queryKey: sshHostGroupKeys.getSshHostGroupById(sshHostGroupId)
diff --git a/frontend/src/hooks/api/tags/queries.tsx b/frontend/src/hooks/api/tags/queries.tsx
index bdbb9659d8..0234cec4d0 100644
--- a/frontend/src/hooks/api/tags/queries.tsx
+++ b/frontend/src/hooks/api/tags/queries.tsx
@@ -4,23 +4,21 @@ import { apiRequest } from "@app/config/request";
import { CreateTagDTO, DeleteTagDTO, UserWsTags, WsTag } from "./types";
-const workspaceTags = {
- getWsTags: (workspaceID: string) => ["workspace-tags", { workspaceID }] as const
+const projectTags = {
+ getWsTags: (projectID: string) => ["project-tags", { projectID }] as const
};
-const fetchWsTag = async (workspaceID: string) => {
- const { data } = await apiRequest.get<{ workspaceTags: UserWsTags }>(
- `/api/v1/workspace/${workspaceID}/tags`
- );
+const fetchWsTag = async (projectID: string) => {
+ const { data } = await apiRequest.get<{ tags: UserWsTags }>(`/api/v1/projects/${projectID}/tags`);
- return data.workspaceTags;
+ return data.tags;
};
-export const useGetWsTags = (workspaceID: string) => {
+export const useGetWsTags = (projectID: string) => {
return useQuery({
- queryKey: workspaceTags.getWsTags(workspaceID),
- queryFn: () => fetchWsTag(workspaceID),
- enabled: Boolean(workspaceID)
+ queryKey: projectTags.getWsTags(projectID),
+ queryFn: () => fetchWsTag(projectID),
+ enabled: Boolean(projectID)
});
};
@@ -28,18 +26,15 @@ export const useCreateWsTag = () => {
const queryClient = useQueryClient();
return useMutation<WsTag, object, CreateTagDTO>({
- mutationFn: async ({ workspaceID, tagColor, tagSlug }) => {
- const { data } = await apiRequest.post<{ workspaceTag: WsTag }>(
- `/api/v1/workspace/${workspaceID}/tags`,
- {
- color: tagColor || "",
- slug: tagSlug
- }
- );
- return data.workspaceTag;
+ mutationFn: async ({ projectId: projectID, tagColor, tagSlug }) => {
+ const { data } = await apiRequest.post<{ tag: WsTag }>(`/api/v1/projects/${projectID}/tags`, {
+ color: tagColor || "",
+ slug: tagSlug
+ });
+ return data.tag;
},
onSuccess: (tagData) => {
- queryClient.invalidateQueries({ queryKey: workspaceTags.getWsTags(tagData?.projectId) });
+ queryClient.invalidateQueries({ queryKey: projectTags.getWsTags(tagData?.projectId) });
}
});
};
@@ -49,13 +44,13 @@ export const useDeleteWsTag = () => {
return useMutation<WsTag, object, DeleteTagDTO>({
mutationFn: async ({ tagID, projectId }) => {
- const { data } = await apiRequest.delete<{ workspaceTag: WsTag }>(
- `/api/v1/workspace/${projectId}/tags/${tagID}`
+ const { data } = await apiRequest.delete<{ tag: WsTag }>(
+ `/api/v1/projects/${projectId}/tags/${tagID}`
);
- return data.workspaceTag;
+ return data.tag;
},
onSuccess: (tagData) => {
- queryClient.invalidateQueries({ queryKey: workspaceTags.getWsTags(tagData?.projectId) });
+ queryClient.invalidateQueries({ queryKey: projectTags.getWsTags(tagData?.projectId) });
}
});
};
diff --git a/frontend/src/hooks/api/tags/types.ts b/frontend/src/hooks/api/tags/types.ts
index 72d710cfa0..09ac221473 100644
--- a/frontend/src/hooks/api/tags/types.ts
+++ b/frontend/src/hooks/api/tags/types.ts
@@ -13,7 +13,7 @@ export type WsTag = {
export type WorkspaceTag = { id: string; name: string; slug: string };
export type CreateTagDTO = {
- workspaceID: string;
+ projectId: string;
tagSlug: string;
tagColor: string;
};
diff --git a/frontend/src/hooks/api/trustedIps/queries.ts b/frontend/src/hooks/api/trustedIps/queries.ts
index 57a5d58445..36815b3139 100644
--- a/frontend/src/hooks/api/trustedIps/queries.ts
+++ b/frontend/src/hooks/api/trustedIps/queries.ts
@@ -5,15 +5,15 @@ import { apiRequest } from "@app/config/request";
import { TrustedIp } from "./types";
const trustedIps = {
- getTrustedIps: (workspaceId: string) => [{ workspaceId }, "trusted-ips"] as const
+ getTrustedIps: (projectId: string) => [{ projectId }, "trusted-ips"] as const
};
-export const useGetTrustedIps = (workspaceId: string) => {
+export const useGetTrustedIps = (projectId: string) => {
return useQuery({
- queryKey: trustedIps.getTrustedIps(workspaceId),
+ queryKey: trustedIps.getTrustedIps(projectId),
queryFn: async () => {
const { data } = await apiRequest.get<{ trustedIps: TrustedIp[] }>(
- `/api/v1/workspace/${workspaceId}/trusted-ips`
+ `/api/v1/projects/${projectId}/trusted-ips`
);
return data.trustedIps;
@@ -25,17 +25,17 @@ export const useAddTrustedIp = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
- workspaceId,
+ projectId,
ipAddress,
comment,
isActive
}: {
- workspaceId: string;
+ projectId: string;
ipAddress: string;
comment?: string;
isActive: boolean;
}) => {
- const { data } = await apiRequest.post(`/api/v1/workspace/${workspaceId}/trusted-ips`, {
+ const { data } = await apiRequest.post(`/api/v1/projects/${projectId}/trusted-ips`, {
ipAddress,
...(comment ? { comment } : {}),
isActive
@@ -44,7 +44,7 @@ export const useAddTrustedIp = () => {
return data;
},
onSuccess(_, dto) {
- queryClient.invalidateQueries({ queryKey: trustedIps.getTrustedIps(dto.workspaceId) });
+ queryClient.invalidateQueries({ queryKey: trustedIps.getTrustedIps(dto.projectId) });
}
});
};
@@ -53,20 +53,20 @@ export const useUpdateTrustedIp = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
- workspaceId,
+ projectId,
trustedIpId,
ipAddress,
comment,
isActive
}: {
- workspaceId: string;
+ projectId: string;
trustedIpId: string;
ipAddress: string;
comment?: string;
isActive: boolean;
}) => {
const { data } = await apiRequest.patch(
- `/api/v1/workspace/${workspaceId}/trusted-ips/${trustedIpId}`,
+ `/api/v1/projects/${projectId}/trusted-ips/${trustedIpId}`,
{
ipAddress,
...(comment ? { comment } : {}),
@@ -77,7 +77,7 @@ export const useUpdateTrustedIp = () => {
return data;
},
onSuccess(_, dto) {
- queryClient.invalidateQueries({ queryKey: trustedIps.getTrustedIps(dto.workspaceId) });
+ queryClient.invalidateQueries({ queryKey: trustedIps.getTrustedIps(dto.projectId) });
}
});
};
@@ -85,21 +85,15 @@ export const useUpdateTrustedIp = () => {
export const useDeleteTrustedIp = () => {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: async ({
- workspaceId,
- trustedIpId
- }: {
- workspaceId: string;
- trustedIpId: string;
- }) => {
+ mutationFn: async ({ projectId, trustedIpId }: { projectId: string; trustedIpId: string }) => {
const { data } = await apiRequest.delete(
- `/api/v1/workspace/${workspaceId}/trusted-ips/${trustedIpId}`
+ `/api/v1/projects/${projectId}/trusted-ips/${trustedIpId}`
);
return data;
},
onSuccess(_, dto) {
- queryClient.invalidateQueries({ queryKey: trustedIps.getTrustedIps(dto.workspaceId) });
+ queryClient.invalidateQueries({ queryKey: trustedIps.getTrustedIps(dto.projectId) });
}
});
};
diff --git a/frontend/src/hooks/api/types.ts b/frontend/src/hooks/api/types.ts
index 8c29d48258..4b73eba28b 100644
--- a/frontend/src/hooks/api/types.ts
+++ b/frontend/src/hooks/api/types.ts
@@ -7,8 +7,19 @@ export type { GetAuthTokenAPI } from "./auth/types";
export type { IncidentContact } from "./incidentContacts/types";
export type { IntegrationAuth } from "./integrationAuth/types";
export type { TCloudIntegration, TIntegration } from "./integrations/types";
-export type { UserWsKeyPair } from "./keys/types";
export type { Organization } from "./organization/types";
+export type {
+ CreateEnvironmentDTO,
+ CreateWorkspaceDTO,
+ DeleteEnvironmentDTO,
+ DeleteWorkspaceDTO,
+ Project,
+ ProjectEnv,
+ ProjectTag,
+ ToggleAutoCapitalizationDTO,
+ UpdateEnvironmentDTO,
+ UpdateProjectDTO
+} from "./projects/types";
export type { TSecretApprovalPolicy } from "./secretApproval/types";
export type {
TGetSecretApprovalRequestDetails,
@@ -29,18 +40,6 @@ export type { SubscriptionPlan } from "./subscriptions/types";
export type { WsTag } from "./tags/types";
export type { OrgUser, TWorkspaceUser, User, UserEnc } from "./users/types";
export type { TWebhook } from "./webhooks/types";
-export type {
- CreateEnvironmentDTO,
- CreateWorkspaceDTO,
- DeleteEnvironmentDTO,
- DeleteWorkspaceDTO,
- ToggleAutoCapitalizationDTO,
- UpdateEnvironmentDTO,
- UpdateProjectDTO,
- Workspace,
- WorkspaceEnv,
- WorkspaceTag
-} from "./workspace/types";
export enum ApiErrorTypes {
ValidationError = "ValidationFailure",
diff --git a/frontend/src/hooks/api/users/mutation.tsx b/frontend/src/hooks/api/users/mutation.tsx
index 1f3fdf3ad4..7acfb8fe08 100644
--- a/frontend/src/hooks/api/users/mutation.tsx
+++ b/frontend/src/hooks/api/users/mutation.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace";
+import { projectKeys } from "../projects";
import { userKeys } from "./query-keys";
import { AddUserToWsDTONonE2EE } from "./types";
@@ -11,14 +11,14 @@ export const useAddUserToWsNonE2EE = () => {
return useMutation<object, object, AddUserToWsDTONonE2EE>({
mutationFn: async ({ projectId, usernames, roleSlugs }) => {
- const { data } = await apiRequest.post(`/api/v2/workspace/${projectId}/memberships`, {
+ const { data } = await apiRequest.post(`/api/v1/projects/${projectId}/memberships`, {
usernames,
roleSlugs
});
return data;
},
onSuccess: (_, { orgId, projectId }) => {
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceUsers(projectId) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectUsers(projectId) });
queryClient.invalidateQueries({
queryKey: userKeys.allOrgMembershipProjectMemberships(orgId)
});
diff --git a/frontend/src/hooks/api/users/queries.tsx b/frontend/src/hooks/api/users/queries.tsx
index 77289fee64..2c01253619 100644
--- a/frontend/src/hooks/api/users/queries.tsx
+++ b/frontend/src/hooks/api/users/queries.tsx
@@ -8,9 +8,9 @@ import { queryClient as qc } from "@app/hooks/api/reactQuery";
import { APIKeyDataV2 } from "../apiKeys/types";
import { MfaMethod } from "../auth/types";
import { TGroupWithProjectMemberships } from "../groups/types";
+import { projectKeys } from "../projects";
import { setAuthToken } from "../reactQuery";
import { subscriptionQueryKeys } from "../subscriptions/queries";
-import { workspaceKeys } from "../workspace";
import { userKeys } from "./query-keys";
import {
AddUserToOrgDTO,
@@ -197,10 +197,10 @@ export const useAddUsersToOrg = () => {
projects?.forEach((project) => {
if (project.slug) {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceGroupMemberships(project.slug)
+ queryKey: projectKeys.getProjectGroupMemberships(project.slug)
});
}
- queryClient.invalidateQueries({ queryKey: workspaceKeys.getWorkspaceUsers(project.id) });
+ queryClient.invalidateQueries({ queryKey: projectKeys.getProjectUsers(project.id) });
});
}
});
diff --git a/frontend/src/hooks/api/users/types.ts b/frontend/src/hooks/api/users/types.ts
index 5a90d4b646..a59965dfc0 100644
--- a/frontend/src/hooks/api/users/types.ts
+++ b/frontend/src/hooks/api/users/types.ts
@@ -1,5 +1,5 @@
import { MfaMethod } from "../auth/types";
-import { ProjectType, ProjectUserMembershipTemporaryMode } from "../workspace/types";
+import { ProjectType, ProjectUserMembershipTemporaryMode } from "../projects/types";
export enum AuthMethod {
EMAIL = "email",
diff --git a/frontend/src/hooks/api/webhooks/mutation.tsx b/frontend/src/hooks/api/webhooks/mutation.tsx
index 10d5e472e3..66eb8ae170 100644
--- a/frontend/src/hooks/api/webhooks/mutation.tsx
+++ b/frontend/src/hooks/api/webhooks/mutation.tsx
@@ -13,8 +13,8 @@ export const useCreateWebhook = () => {
const { data } = await apiRequest.post("/api/v1/webhooks", dto);
return data;
},
- onSuccess: (_, { workspaceId }) => {
- queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(workspaceId) });
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(projectId) });
}
});
};
@@ -27,11 +27,11 @@ export const useTestWebhook = () => {
const { data } = await apiRequest.post(`/api/v1/webhooks/${webhookId}/test`);
return data;
},
- onSuccess: (_, { workspaceId }) => {
- queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(workspaceId) });
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(projectId) });
},
- onError: (_, { workspaceId }) => {
- queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(workspaceId) });
+ onError: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(projectId) });
}
});
};
@@ -46,8 +46,8 @@ export const useUpdateWebhook = () => {
});
return data;
},
- onSuccess: (_, { workspaceId }) => {
- queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(workspaceId) });
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(projectId) });
}
});
};
@@ -60,8 +60,8 @@ export const useDeleteWebhook = () => {
const { data } = await apiRequest.delete(`/api/v1/webhooks/${dto.webhookId}`);
return data;
},
- onSuccess: (_, { workspaceId }) => {
- queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(workspaceId) });
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({ queryKey: queryKeys.getWebhooks(projectId) });
}
});
};
diff --git a/frontend/src/hooks/api/webhooks/query.tsx b/frontend/src/hooks/api/webhooks/query.tsx
index fc18404097..3f92a96950 100644
--- a/frontend/src/hooks/api/webhooks/query.tsx
+++ b/frontend/src/hooks/api/webhooks/query.tsx
@@ -8,19 +8,19 @@ export const queryKeys = {
getWebhooks: (workspaceId: string) => ["webhooks", { workspaceId }]
};
-const fetchWebhooks = async (workspaceId: string) => {
+const fetchWebhooks = async (projectId: string) => {
const { data } = await apiRequest.get<{ webhooks: TWebhook[] }>("/api/v1/webhooks", {
params: {
- workspaceId
+ projectId
}
});
return data.webhooks;
};
-export const useGetWebhooks = (workspaceId: string) =>
+export const useGetWebhooks = (projectId: string) =>
useQuery({
- queryKey: queryKeys.getWebhooks(workspaceId),
- queryFn: () => fetchWebhooks(workspaceId),
- enabled: Boolean(workspaceId)
+ queryKey: queryKeys.getWebhooks(projectId),
+ queryFn: () => fetchWebhooks(projectId),
+ enabled: Boolean(projectId)
});
diff --git a/frontend/src/hooks/api/webhooks/types.ts b/frontend/src/hooks/api/webhooks/types.ts
index 86183bf1ba..7e2758ff89 100644
--- a/frontend/src/hooks/api/webhooks/types.ts
+++ b/frontend/src/hooks/api/webhooks/types.ts
@@ -23,7 +23,7 @@ export type TWebhook = {
};
export type TCreateWebhookDto = {
- workspaceId: string;
+ projectId: string;
environment: string;
webhookUrl: string;
webhookSecretKey?: string;
@@ -33,16 +33,16 @@ export type TCreateWebhookDto = {
export type TUpdateWebhookDto = {
webhookId: string;
- workspaceId: string;
+ projectId: string;
isDisabled?: boolean;
};
export type TDeleteWebhookDto = {
webhookId: string;
- workspaceId: string;
+ projectId: string;
};
export type TTestWebhookDTO = {
webhookId: string;
- workspaceId: string;
+ projectId: string;
};
diff --git a/frontend/src/hooks/api/workflowIntegrations/mutation.tsx b/frontend/src/hooks/api/workflowIntegrations/mutation.tsx
index 89c65f888b..d362c7b826 100644
--- a/frontend/src/hooks/api/workflowIntegrations/mutation.tsx
+++ b/frontend/src/hooks/api/workflowIntegrations/mutation.tsx
@@ -2,7 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { workspaceKeys } from "../workspace/query-keys";
+import { projectKeys } from "../projects/query-keys";
import { workflowIntegrationKeys } from "./queries";
import {
TCheckMicrosoftTeamsIntegrationInstallationStatusDTO,
@@ -118,15 +118,15 @@ export const useUpdateProjectWorkflowIntegrationConfig = () => {
return useMutation({
mutationFn: async (dto: TUpdateProjectWorkflowIntegrationConfigDTO) => {
const { data } = await apiRequest.put(
- `/api/v1/workspace/${dto.workspaceId}/workflow-integration`,
+ `/api/v1/projects/${dto.projectId}/workflow-integration`,
dto
);
return data;
},
- onSuccess: (_, { workspaceId, integration }) => {
+ onSuccess: (_, { projectId: workspaceId, integration }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceWorkflowIntegrationConfig(workspaceId, integration)
+ queryKey: projectKeys.getProjectWorkflowIntegrationConfig(workspaceId, integration)
});
}
});
@@ -138,14 +138,14 @@ export const useDeleteProjectWorkflowIntegration = () => {
return useMutation({
mutationFn: async (dto: TDeleteProjectWorkflowIntegrationDTO) => {
const { data } = await apiRequest.delete(
- `/api/v1/workspace/${dto.projectId}/workflow-integration/${dto.integration}/${dto.integrationId}`
+ `/api/v1/projects/${dto.projectId}/workflow-integration/${dto.integration}/${dto.integrationId}`
);
return data;
},
onSuccess: (_, { projectId, integration }) => {
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getWorkspaceWorkflowIntegrationConfig(projectId, integration)
+ queryKey: projectKeys.getProjectWorkflowIntegrationConfig(projectId, integration)
});
}
});
diff --git a/frontend/src/hooks/api/workflowIntegrations/types.ts b/frontend/src/hooks/api/workflowIntegrations/types.ts
index 4d2baf4bf9..6688501246 100644
--- a/frontend/src/hooks/api/workflowIntegrations/types.ts
+++ b/frontend/src/hooks/api/workflowIntegrations/types.ts
@@ -106,7 +106,7 @@ export type ProjectWorkflowIntegrationConfig =
export type TUpdateProjectWorkflowIntegrationConfigDTO =
| {
integration: WorkflowIntegrationPlatform.SLACK;
- workspaceId: string;
+ projectId: string;
integrationId: string;
isAccessRequestNotificationEnabled: boolean;
accessRequestChannels: string;
@@ -115,7 +115,7 @@ export type TUpdateProjectWorkflowIntegrationConfigDTO =
}
| {
integration: WorkflowIntegrationPlatform.MICROSOFT_TEAMS;
- workspaceId: string;
+ projectId: string;
integrationId: string;
isAccessRequestNotificationEnabled: boolean;
isSecretRequestNotificationEnabled: boolean;
diff --git a/frontend/src/hooks/api/workspace/query-keys.tsx b/frontend/src/hooks/api/workspace/query-keys.tsx
deleted file mode 100644
index aca6f48b7d..0000000000
--- a/frontend/src/hooks/api/workspace/query-keys.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { TListProjectIdentitiesDTO, TSearchProjectsDTO } from "@app/hooks/api/workspace/types";
-
-import type { CaStatus } from "../ca";
-import { WorkflowIntegrationPlatform } from "../workflowIntegrations/types";
-
-export const workspaceKeys = {
- getWorkspaceById: (workspaceId: string) => ["workspaces", { workspaceId }] as const,
- getWorkspaceSecrets: (workspaceId: string) => [{ workspaceId }, "workspace-secrets"] as const,
- getWorkspaceIndexStatus: (workspaceId: string) =>
- [{ workspaceId }, "workspace-index-status"] as const,
- getProjectUpgradeStatus: (workspaceId: string) => [{ workspaceId }, "workspace-upgrade-status"],
- getWorkspaceMemberships: (orgId: string) => [{ orgId }, "workspace-memberships"],
- getWorkspaceAuthorization: (workspaceId: string) => [{ workspaceId }, "workspace-authorizations"],
- getWorkspaceIntegrations: (workspaceId: string) => [{ workspaceId }, "workspace-integrations"],
- getAllUserWorkspace: () => ["workspaces"] as const,
- getWorkspaceAuditLogs: (workspaceId: string) =>
- [{ workspaceId }, "workspace-audit-logs"] as const,
- getWorkspaceUsers: (
- workspaceId: string,
- includeGroupMembers: boolean = false,
- roles: string[] = []
- ) => [{ workspaceId, includeGroupMembers, roles }, "workspace-users"] as const,
- getWorkspaceUserDetails: (workspaceId: string, membershipId: string) =>
- [{ workspaceId, membershipId }, "workspace-user-details"] as const,
- getWorkspaceIdentityMemberships: (workspaceId: string) =>
- [{ workspaceId }, "workspace-identity-memberships"] as const,
- getWorkspaceIdentityMembershipDetails: (workspaceId: string, identityId: string) =>
- [{ workspaceId, identityId }, "workspace-identity-membership-details"] as const,
- // allows invalidation using above key without knowing params
- getWorkspaceIdentityMembershipsWithParams: ({
- workspaceId,
- ...params
- }: TListProjectIdentitiesDTO) =>
- [...workspaceKeys.getWorkspaceIdentityMemberships(workspaceId), params] as const,
- searchWorkspace: (dto: TSearchProjectsDTO) => ["search-projects", dto] as const,
- getWorkspaceGroupMemberships: (workspaceId: string) =>
- [{ workspaceId }, "workspace-groups"] as const,
- getWorkspaceGroupMembershipDetails: (workspaceId: string, groupId: string) =>
- [{ workspaceId, groupId }, "workspace-group-membership-details"] as const,
- getWorkspaceCas: ({ projectSlug }: { projectSlug: string }) =>
- [{ projectSlug }, "workspace-cas"] as const,
- specificWorkspaceCas: ({ projectSlug, status }: { projectSlug: string; status?: CaStatus }) =>
- [...workspaceKeys.getWorkspaceCas({ projectSlug }), { status }] as const,
- allWorkspaceCertificates: () => ["workspace-certificates"] as const,
- forWorkspaceCertificates: (slug: string) =>
- [...workspaceKeys.allWorkspaceCertificates(), slug] as const,
- specificWorkspaceCertificates: ({
- slug,
- offset,
- limit
- }: {
- slug: string;
- offset: number;
- limit: number;
- }) => [...workspaceKeys.forWorkspaceCertificates(slug), { offset, limit }] as const,
- getWorkspacePkiAlerts: (workspaceId: string) =>
- [{ workspaceId }, "workspace-pki-alerts"] as const,
- getWorkspacePkiSubscribers: (projectId: string) =>
- [{ projectId }, "workspace-pki-subscribers"] as const,
- getWorkspacePkiCollections: (workspaceId: string) =>
- [{ workspaceId }, "workspace-pki-collections"] as const,
- getWorkspaceCertificateTemplates: (workspaceId: string) =>
- [{ workspaceId }, "workspace-certificate-templates"] as const,
- getWorkspaceWorkflowIntegrationConfig: (
- workspaceId: string,
- integration: WorkflowIntegrationPlatform
- ) => [{ workspaceId, integration }, "workspace-workflow-integration-config"] as const,
- getWorkspaceSshCas: (projectId: string) => [{ projectId }, "workspace-ssh-cas"] as const,
- allWorkspaceSshCertificates: (projectId: string) =>
- [{ projectId }, "workspace-ssh-certificates"] as const,
- getWorkspaceSshHosts: (projectId: string) => [{ projectId }, "workspace-ssh-hosts"] as const,
- getWorkspaceSshHostGroups: (projectId: string) =>
- [{ projectId }, "workspace-ssh-host-groups"] as const,
- specificWorkspaceSshCertificates: ({
- offset,
- limit,
- projectId
- }: {
- offset: number;
- limit: number;
- projectId: string;
- }) => [...workspaceKeys.allWorkspaceSshCertificates(projectId), { offset, limit }] as const,
- getWorkspaceSshCertificateTemplates: (projectId: string) =>
- [{ projectId }, "workspace-ssh-certificate-templates"] as const,
- getProjectSshConfig: (projectId: string) => [{ projectId }, "project-ssh-config"] as const
-};
diff --git a/frontend/src/hooks/useGetProjectTypeFromRoute.tsx b/frontend/src/hooks/useGetProjectTypeFromRoute.tsx
index 3156216dbf..972671a96d 100644
--- a/frontend/src/hooks/useGetProjectTypeFromRoute.tsx
+++ b/frontend/src/hooks/useGetProjectTypeFromRoute.tsx
@@ -1,7 +1,7 @@
import { useMemo } from "react";
import { useRouterState } from "@tanstack/react-router";
-import { ProjectType } from "@app/hooks/api/workspace/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
export const useGetProjectTypeFromRoute = () => {
const { location } = useRouterState();
diff --git a/frontend/src/hooks/usePathAccessPolicies.tsx b/frontend/src/hooks/usePathAccessPolicies.tsx
index 1fbc5fd520..0ad25b0d20 100644
--- a/frontend/src/hooks/usePathAccessPolicies.tsx
+++ b/frontend/src/hooks/usePathAccessPolicies.tsx
@@ -1,6 +1,6 @@
import { useMemo } from "react";
-import { useSubscription, useWorkspace } from "@app/context";
+import { useProject, useSubscription } from "@app/context";
import { useGetAccessApprovalPolicies } from "@app/hooks/api";
const matchesPath = (folderPath: string, pattern: string) => {
@@ -37,10 +37,10 @@ type Params = {
};
export const usePathAccessPolicies = ({ secretPath, environment }: Params) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { subscription } = useSubscription();
const { data: policies } = useGetAccessApprovalPolicies({
- projectSlug: currentWorkspace.slug,
+ projectSlug: currentProject.slug,
options: {
enabled: subscription.secretApproval
}
diff --git a/frontend/src/layouts/KmsLayout/KmsLayout.tsx b/frontend/src/layouts/KmsLayout/KmsLayout.tsx
index c34bc3626e..285f3b7f8f 100644
--- a/frontend/src/layouts/KmsLayout/KmsLayout.tsx
+++ b/frontend/src/layouts/KmsLayout/KmsLayout.tsx
@@ -4,12 +4,12 @@ import { Link, Outlet } from "@tanstack/react-router";
import { motion } from "framer-motion";
import { Lottie, Menu, MenuGroup, MenuItem } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import { AssumePrivilegeModeBanner } from "../ProjectLayout/components/AssumePrivilegeModeBanner";
export const KmsLayout = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { assumedPrivilegeDetails } = useProjectPermission();
return (
@@ -34,7 +34,7 @@ export const KmsLayout = () => {
<Link
to="/projects/kms/$projectId/overview"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -51,7 +51,7 @@ export const KmsLayout = () => {
<Link
to="/projects/kms/$projectId/kmip"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -70,7 +70,7 @@ export const KmsLayout = () => {
<Link
to="/projects/kms/$projectId/access-management"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -87,7 +87,7 @@ export const KmsLayout = () => {
<Link
to="/projects/kms/$projectId/audit-logs"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -104,7 +104,7 @@ export const KmsLayout = () => {
<Link
to="/projects/kms/$projectId/settings"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
index e9bb6a902a..71be38b110 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Navbar.tsx
@@ -40,7 +40,7 @@ import { envConfig } from "@app/config/env";
import { useOrganization, useSubscription, useUser } from "@app/context";
import { isInfisicalCloud } from "@app/helpers/platform";
import { useToggle } from "@app/hooks";
-import { useGetOrganizations, useLogoutUser, workspaceKeys } from "@app/hooks/api";
+import { projectKeys, useGetOrganizations, useLogoutUser } from "@app/hooks/api";
import { authKeys, selectOrganization } from "@app/hooks/api/auth/queries";
import { MfaMethod } from "@app/hooks/api/auth/types";
import { getAuthToken } from "@app/hooks/api/reactQuery";
@@ -135,7 +135,7 @@ export const Navbar = () => {
const handleOrgChange = async (orgId: string) => {
queryClient.removeQueries({ queryKey: authKeys.getAuthToken });
- queryClient.removeQueries({ queryKey: workspaceKeys.getAllUserWorkspace() });
+ queryClient.removeQueries({ queryKey: projectKeys.getAllUserProjects() });
const { token, isMfaEnabled, mfaMethod } = await selectOrganization({
organizationId: orgId
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx
index 59e6861fc9..29fd25415e 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/Notification.tsx
@@ -26,7 +26,11 @@ export const Notification = ({ notification, onDelete }: Props) => {
{!notification.isRead && (
<FontAwesomeIcon icon={faCircle} className="mt-1.5 size-2 text-yellow-400" />
)}
- <Tooltip content={<Markdown>{notification.title}</Markdown>} delayDuration={300}>
+ <Tooltip
+ content={<Markdown>{notification.title}</Markdown>}
+ delayDuration={300}
+ className="z-[1000]"
+ >
<span className="overflow-hidden text-ellipsis whitespace-nowrap text-sm font-medium leading-5 text-mineshaft-100">
<Markdown components={{ p: "span" }}>{notification.title}</Markdown>
</span>
diff --git a/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx b/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx
index a5e9166d99..69a56d5a88 100644
--- a/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/NavBar/NotificationDropdown.tsx
@@ -46,7 +46,7 @@ export const NotificationDropdown = () => {
<DropdownMenuContent
align="end"
side="bottom"
- className="mt-3 flex h-[550px] w-[400px] overflow-hidden rounded-lg"
+ className="z-[999] mt-3 flex h-[550px] w-[400px] overflow-hidden rounded-lg"
>
<div className="flex w-full flex-col">
<div className="flex items-center justify-between border-b border-mineshaft-500 px-3 py-2">
diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx
index 4ab5051f89..e1c1e89f90 100644
--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx
+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/OrgSidebar.tsx
@@ -5,6 +5,7 @@ import {
faInfinity,
faMoneyBill,
faPlug,
+ faRoute,
faShare,
faTable,
faUsers,
@@ -136,6 +137,18 @@ export const OrgSidebar = ({ isHidden }: Props) => {
</MenuItem>
)}
</Link>
+ <Link to="/organization/relays">
+ {({ isActive }) => (
+ <MenuItem isSelected={isActive}>
+ <div className="mx-1 flex gap-2">
+ <div className="w-6">
+ <FontAwesomeIcon icon={faRoute} className="mr-4" />
+ </div>
+ Relays
+ </div>
+ </MenuItem>
+ )}
+ </Link>
</MenuGroup>
</Menu>
<div className="flex-grow" />
diff --git a/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx b/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
index da9b5acdf2..ec47273309 100644
--- a/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
+++ b/frontend/src/layouts/PkiManagerLayout/PkiManagerLayout.tsx
@@ -7,6 +7,7 @@ import {
faFileLines,
faHome,
faMobile,
+ faPlug,
faSitemap,
faStamp,
faUsers
@@ -16,12 +17,12 @@ import { Link, Outlet } from "@tanstack/react-router";
import { motion } from "framer-motion";
import { Lottie, Menu, MenuGroup, MenuItem } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import { AssumePrivilegeModeBanner } from "../ProjectLayout/components/AssumePrivilegeModeBanner";
export const PkiManagerLayout = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { assumedPrivilegeDetails } = useProjectPermission();
const { t } = useTranslation();
@@ -48,7 +49,7 @@ export const PkiManagerLayout = () => {
<Link
to="/projects/cert-management/$projectId/subscribers"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -65,7 +66,7 @@ export const PkiManagerLayout = () => {
<Link
to="/projects/cert-management/$projectId/certificate-templates"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -82,7 +83,7 @@ export const PkiManagerLayout = () => {
<Link
to="/projects/cert-management/$projectId/certificates"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -99,7 +100,7 @@ export const PkiManagerLayout = () => {
<Link
to="/projects/cert-management/$projectId/certificate-authorities"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -116,7 +117,7 @@ export const PkiManagerLayout = () => {
<Link
to="/projects/cert-management/$projectId/alerting"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -130,12 +131,29 @@ export const PkiManagerLayout = () => {
</MenuItem>
)}
</Link>
+ <Link
+ to="/projects/cert-management/$projectId/app-connections"
+ params={{
+ projectId: currentProject.id
+ }}
+ >
+ {({ isActive }) => (
+ <MenuItem isSelected={isActive}>
+ <div className="mx-1 flex gap-2">
+ <div className="w-6">
+ <FontAwesomeIcon icon={faPlug} />
+ </div>
+ App Connections
+ </div>
+ </MenuItem>
+ )}
+ </Link>
</MenuGroup>
<MenuGroup title="Others">
<Link
to="/projects/cert-management/$projectId/access-management"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -152,7 +170,7 @@ export const PkiManagerLayout = () => {
<Link
to="/projects/cert-management/$projectId/audit-logs"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -169,7 +187,7 @@ export const PkiManagerLayout = () => {
<Link
to="/projects/cert-management/$projectId/settings"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
diff --git a/frontend/src/layouts/ProjectLayout/components/AssumePrivilegeModeBanner/AssumePrivilegeModeBanner.tsx b/frontend/src/layouts/ProjectLayout/components/AssumePrivilegeModeBanner/AssumePrivilegeModeBanner.tsx
index 995083ee7f..754d805475 100644
--- a/frontend/src/layouts/ProjectLayout/components/AssumePrivilegeModeBanner/AssumePrivilegeModeBanner.tsx
+++ b/frontend/src/layouts/ProjectLayout/components/AssumePrivilegeModeBanner/AssumePrivilegeModeBanner.tsx
@@ -2,13 +2,13 @@ import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Button } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import { getProjectHomePage } from "@app/helpers/project";
import { useRemoveAssumeProjectPrivilege } from "@app/hooks/api";
import { ActorType } from "@app/hooks/api/auditLogs/enums";
export const AssumePrivilegeModeBanner = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const exitAssumePrivilegeMode = useRemoveAssumeProjectPrivilege();
const { assumedPrivilegeDetails } = useProjectPermission();
@@ -32,15 +32,12 @@ export const AssumePrivilegeModeBanner = () => {
onClick={() => {
exitAssumePrivilegeMode.mutate(
{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
{
onSuccess: () => {
- const url = getProjectHomePage(
- currentWorkspace.type,
- currentWorkspace.environments
- );
- window.location.href = url.replace("$projectId", currentWorkspace.id);
+ const url = getProjectHomePage(currentProject.type, currentProject.environments);
+ window.location.href = url.replace("$projectId", currentProject.id);
}
}
);
diff --git a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
index ebc28a2271..eb5b229389 100644
--- a/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
+++ b/frontend/src/layouts/ProjectLayout/components/ProjectSelect/ProjectSelect.tsx
@@ -28,21 +28,21 @@ import {
OrgPermissionActions,
OrgPermissionSubjects,
useOrganization,
- useSubscription,
- useWorkspace
+ useProject,
+ useSubscription
} from "@app/context";
import { getProjectHomePage } from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
-import { useGetUserWorkspaces } from "@app/hooks/api";
+import { useGetUserProjects } from "@app/hooks/api";
+import { Project } from "@app/hooks/api/projects/types";
import { useUpdateUserProjectFavorites } from "@app/hooks/api/users/mutation";
import { useGetUserProjectFavorites } from "@app/hooks/api/users/queries";
-import { Workspace } from "@app/hooks/api/workspace/types";
export const ProjectSelect = () => {
const [searchProject, setSearchProject] = useState("");
- const { currentWorkspace } = useWorkspace();
+ const { currentProject: currentWorkspace } = useProject();
const { currentOrg } = useOrganization();
- const { data: workspaces = [] } = useGetUserWorkspaces();
+ const { data: projects = [] } = useGetUserProjects();
const { data: projectFavorites } = useGetUserProjectFavorites(currentOrg.id);
const { subscription } = useSubscription();
@@ -86,16 +86,16 @@ export const ProjectSelect = () => {
"upgradePlan"
] as const);
- const projects = useMemo(() => {
- const projectOptions = workspaces
- .map((w): Workspace & { isFavorite: boolean } => ({
+ const projectsSortedByFav = useMemo(() => {
+ const projectOptions = projects
+ .map((w): Project & { isFavorite: boolean } => ({
...w,
isFavorite: Boolean(projectFavorites?.includes(w.id))
}))
.sort((a, b) => Number(b.isFavorite) - Number(a.isFavorite));
return projectOptions;
- }, [workspaces, projectFavorites, currentWorkspace]);
+ }, [projects, projectFavorites, currentWorkspace]);
return (
<div className="-mr-2 flex w-full items-center gap-1">
@@ -147,7 +147,7 @@ export const ProjectSelect = () => {
/>
</div>
<div className="thin-scrollbar max-h-80 overflow-auto">
- {projects
+ {projectsSortedByFav
?.filter((el) => el.name?.toLowerCase().includes(searchProject.toLowerCase()))
?.map((workspace) => {
return (
@@ -200,16 +200,20 @@ export const ProjectSelect = () => {
</div>
<div className="mt-1 h-1 border-t border-mineshaft-600" />
<OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Workspace}>
- {(isAllowed) => (
- <DropdownMenuItem
- isDisabled={!isAllowed}
- icon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() =>
- handlePopUpOpen(isAddingProjectsAllowed ? "addNewWs" : "upgradePlan")
- }
- >
- New Project
- </DropdownMenuItem>
+ {(isOldProjectPermissionAllowed) => (
+ <OrgPermissionCan I={OrgPermissionActions.Create} a={OrgPermissionSubjects.Project}>
+ {(isAllowed) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed && !isOldProjectPermissionAllowed}
+ icon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() =>
+ handlePopUpOpen(isAddingProjectsAllowed ? "addNewWs" : "upgradePlan")
+ }
+ >
+ New Project
+ </DropdownMenuItem>
+ )}
+ </OrgPermissionCan>
)}
</OrgPermissionCan>
</DropdownMenuContent>
diff --git a/frontend/src/layouts/SecretManagerLayout/SecretManagerLayout.tsx b/frontend/src/layouts/SecretManagerLayout/SecretManagerLayout.tsx
index 0584e8e9c5..0b9b934c37 100644
--- a/frontend/src/layouts/SecretManagerLayout/SecretManagerLayout.tsx
+++ b/frontend/src/layouts/SecretManagerLayout/SecretManagerLayout.tsx
@@ -6,6 +6,7 @@ import {
faCog,
faHome,
faMobile,
+ faPlug,
faPuzzlePiece,
faUsers,
faVault
@@ -15,7 +16,7 @@ import { Link, Outlet, useLocation } from "@tanstack/react-router";
import { motion } from "framer-motion";
import { Badge, Lottie, Menu, MenuGroup, MenuItem } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import {
useGetAccessRequestsCount,
useGetSecretApprovalRequestCount,
@@ -25,16 +26,15 @@ import {
import { AssumePrivilegeModeBanner } from "../ProjectLayout/components/AssumePrivilegeModeBanner";
export const SecretManagerLayout = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject, projectId } = useProject();
const { assumedPrivilegeDetails } = useProjectPermission();
const { t } = useTranslation();
- const workspaceId = currentWorkspace?.id || "";
- const projectSlug = currentWorkspace?.slug || "";
+ const projectSlug = currentProject?.slug || "";
const location = useLocation();
const { data: secretApprovalReqCount } = useGetSecretApprovalRequestCount({
- workspaceId
+ projectId
});
const { data: accessApprovalRequestCount } = useGetAccessRequestsCount({
projectSlug
@@ -42,7 +42,7 @@ export const SecretManagerLayout = () => {
// we only show the secret rotations v1 tab if they have existing rotations
const { data: secretRotations } = useGetSecretRotations({
- workspaceId,
+ workspaceId: projectId,
options: {
refetchOnMount: false
}
@@ -74,9 +74,9 @@ export const SecretManagerLayout = () => {
<Link
to="/projects/secret-management/$projectId/overview"
params={{
- projectId: currentWorkspace.id,
- ...(currentWorkspace.environments.length
- ? { envSlug: currentWorkspace.environments[0]?.slug }
+ projectId: currentProject.id,
+ ...(currentProject.environments.length
+ ? { envSlug: currentProject.environments[0]?.slug }
: {})
}}
>
@@ -85,7 +85,7 @@ export const SecretManagerLayout = () => {
isSelected={
isActive ||
location.pathname.startsWith(
- `/projects/secret-management/${currentWorkspace.id}/overview`
+ `/projects/secret-management/${currentProject.id}/overview`
)
}
>
@@ -101,7 +101,7 @@ export const SecretManagerLayout = () => {
<Link
to="/projects/secret-management/$projectId/integrations"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -119,7 +119,7 @@ export const SecretManagerLayout = () => {
<Link
to="/projects/secret-management/$projectId/secret-rotation"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -137,7 +137,7 @@ export const SecretManagerLayout = () => {
<Link
to="/projects/secret-management/$projectId/approval"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -159,12 +159,29 @@ export const SecretManagerLayout = () => {
</MenuItem>
)}
</Link>
+ <Link
+ to="/projects/secret-management/$projectId/app-connections"
+ params={{
+ projectId: currentProject.id
+ }}
+ >
+ {({ isActive }) => (
+ <MenuItem isSelected={isActive}>
+ <div className="mx-1 flex gap-2">
+ <div className="w-6">
+ <FontAwesomeIcon icon={faPlug} />
+ </div>
+ App Connections
+ </div>
+ </MenuItem>
+ )}
+ </Link>
</MenuGroup>
<MenuGroup title="Others">
<Link
to="/projects/secret-management/$projectId/access-management"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -181,7 +198,7 @@ export const SecretManagerLayout = () => {
<Link
to="/projects/secret-management/$projectId/audit-logs"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -198,7 +215,7 @@ export const SecretManagerLayout = () => {
<Link
to="/projects/secret-management/$projectId/settings"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
diff --git a/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx b/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx
index 265fcc003c..af7bba5d1b 100644
--- a/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx
+++ b/frontend/src/layouts/SecretScanningLayout/SecretScanningLayout.tsx
@@ -4,6 +4,7 @@ import {
faDatabase,
faHome,
faMagnifyingGlass,
+ faPlug,
faUsers
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
@@ -13,9 +14,9 @@ import { motion } from "framer-motion";
import { Badge, Lottie, Menu, MenuGroup, MenuItem } from "@app/components/v2";
import {
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { ProjectPermissionSecretScanningFindingActions } from "@app/context/ProjectPermissionContext/types";
import { useGetSecretScanningUnresolvedFindingCount } from "@app/hooks/api/secretScanningV2";
@@ -23,14 +24,14 @@ import { useGetSecretScanningUnresolvedFindingCount } from "@app/hooks/api/secre
import { AssumePrivilegeModeBanner } from "../ProjectLayout/components/AssumePrivilegeModeBanner";
export const SecretScanningLayout = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { assumedPrivilegeDetails } = useProjectPermission();
const { permission } = useProjectPermission();
const { subscription } = useSubscription();
const { data: unresolvedFindings } = useGetSecretScanningUnresolvedFindingCount(
- currentWorkspace.id,
+ currentProject.id,
{
enabled:
subscription.secretScanning &&
@@ -64,7 +65,7 @@ export const SecretScanningLayout = () => {
<Link
to="/projects/secret-scanning/$projectId/data-sources"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -81,7 +82,7 @@ export const SecretScanningLayout = () => {
<Link
to="/projects/secret-scanning/$projectId/findings"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -100,12 +101,29 @@ export const SecretScanningLayout = () => {
</MenuItem>
)}
</Link>
+ <Link
+ to="/projects/secret-scanning/$projectId/app-connections"
+ params={{
+ projectId: currentProject.id
+ }}
+ >
+ {({ isActive }) => (
+ <MenuItem isSelected={isActive}>
+ <div className="mx-1 flex gap-2">
+ <div className="w-6">
+ <FontAwesomeIcon icon={faPlug} />
+ </div>
+ App Connections
+ </div>
+ </MenuItem>
+ )}
+ </Link>
</MenuGroup>
<MenuGroup title="Others">
<Link
to="/projects/secret-scanning/$projectId/access-management"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -122,7 +140,7 @@ export const SecretScanningLayout = () => {
<Link
to="/projects/secret-scanning/$projectId/audit-logs"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -139,7 +157,7 @@ export const SecretScanningLayout = () => {
<Link
to="/projects/secret-scanning/$projectId/settings"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
diff --git a/frontend/src/layouts/SshLayout/SshLayout.tsx b/frontend/src/layouts/SshLayout/SshLayout.tsx
index 9c807723e7..92872ec1ff 100644
--- a/frontend/src/layouts/SshLayout/SshLayout.tsx
+++ b/frontend/src/layouts/SshLayout/SshLayout.tsx
@@ -15,14 +15,14 @@ import { Lottie, Menu, MenuGroup, MenuItem } from "@app/components/v2";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { AssumePrivilegeModeBanner } from "../ProjectLayout/components/AssumePrivilegeModeBanner";
export const SshLayout = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { assumedPrivilegeDetails } = useProjectPermission();
return (
@@ -47,7 +47,7 @@ export const SshLayout = () => {
<Link
to="/projects/ssh/$projectId/overview"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -70,7 +70,7 @@ export const SshLayout = () => {
<Link
to="/projects/ssh/$projectId/cas"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -93,7 +93,7 @@ export const SshLayout = () => {
<Link
to="/projects/ssh/$projectId/access-management"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -110,7 +110,7 @@ export const SshLayout = () => {
<Link
to="/projects/ssh/$projectId/audit-logs"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
@@ -127,7 +127,7 @@ export const SshLayout = () => {
<Link
to="/projects/ssh/$projectId/settings"
params={{
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}}
>
{({ isActive }) => (
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx
index 04fafa0b21..5601e48db6 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertModal.tsx
@@ -13,7 +13,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreatePkiAlert,
useGetPkiAlertById,
@@ -60,15 +60,15 @@ type Props = {
};
export const PkiAlertModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: alert } = useGetPkiAlertById(
(popUp?.pkiAlert?.data as { alertId: string })?.alertId || ""
);
const { data: pkiCollections } = useListWorkspacePkiCollections({
- workspaceId: projectId
+ projectId
});
const { mutateAsync: createPkiAlert } = useCreatePkiAlert();
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx
index 497f10c395..d3aeefab79 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsSection.tsx
@@ -4,7 +4,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, DeleteActionModal } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useDeletePkiAlert } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -12,8 +12,8 @@ import { PkiAlertModal } from "./PkiAlertModal";
import { PkiAlertsTable } from "./PkiAlertsTable";
export const PkiAlertsSection = () => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { mutateAsync: deletePkiAlert } = useDeletePkiAlert();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsTable.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsTable.tsx
index b67c5a2c6e..4ddbd46713 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsTable.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiAlertsTable.tsx
@@ -10,7 +10,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useListWorkspacePkiAlerts } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -24,11 +24,11 @@ type Props = {
};
export const PkiAlertsTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data, isPending } = useListWorkspacePkiAlerts({
- workspaceId: projectId
+ projectId
});
return (
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx
index 366f51c629..5900a1ba96 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionModal.tsx
@@ -6,7 +6,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreatePkiCollection,
useGetPkiCollectionById,
@@ -28,8 +28,8 @@ type Props = {
export const PkiCollectionModal = ({ popUp, handlePopUpToggle }: Props) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: pkiCollection } = useGetPkiCollectionById(
(popUp?.pkiCollection?.data as { collectionId: string })?.collectionId || ""
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx
index 81f5a86098..66732ad88a 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionSection.tsx
@@ -4,7 +4,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, DeleteActionModal } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useDeletePkiCollection } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -12,8 +12,8 @@ import { PkiCollectionModal } from "./PkiCollectionModal";
import { PkiCollectionTable } from "./PkiCollectionTable";
export const PkiCollectionSection = () => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { mutateAsync: deletePkiCollection } = useDeletePkiCollection();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
diff --git a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionTable.tsx b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionTable.tsx
index ff525b1f4a..ebd86973f5 100644
--- a/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionTable.tsx
+++ b/frontend/src/pages/cert-manager/AlertingPage/components/PkiCollectionTable.tsx
@@ -19,7 +19,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useListWorkspacePkiCollections } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -32,11 +32,11 @@ type Props = {
export const PkiCollectionTable = ({ handlePopUpOpen }: Props) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data, isPending } = useListWorkspacePkiCollections({
- workspaceId: projectId
+ projectId
});
return (
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
index 0bf3c44312..4e58592153 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/CertAuthDetailsByIDPage.tsx
@@ -15,7 +15,7 @@ import {
Tooltip
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { CaType, useDeleteCa, useGetCa } from "@app/hooks/api";
import { TInternalCertificateAuthority } from "@app/hooks/api/ca/types";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -30,7 +30,7 @@ import {
} from "./components";
const Page = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
const params = useParams({
from: ROUTE_PATHS.CertManager.CertAuthDetailsByIDPage.id
@@ -38,11 +38,11 @@ const Page = () => {
const { caName } = params as { caName: string };
const { data } = useGetCa({
caName,
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
type: CaType.INTERNAL
}) as { data: TInternalCertificateAuthority };
- const projectId = currentWorkspace?.id || "";
+ const projectId = currentProject?.id || "";
const { mutateAsync: deleteCa } = useDeleteCa();
@@ -55,11 +55,11 @@ const Page = () => {
const onRemoveCaSubmit = async () => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
await deleteCa({
caName,
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
type: CaType.INTERNAL
});
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
index f12fcfd280..9ee5c1b8ba 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaDetailsSection.tsx
@@ -4,7 +4,7 @@ import { format } from "date-fns";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, IconButton, Tooltip } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useTimedReset } from "@app/hooks";
import { CaStatus, CaType, InternalCaType, useGetCa } from "@app/hooks/api";
import { caStatusToNameMap, caTypeToNameMap } from "@app/hooks/api/ca/constants";
@@ -21,7 +21,7 @@ type Props = {
};
export const CaDetailsSection = ({ caName, handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [copyTextId, isCopyingId, setCopyTextId] = useTimedReset<string>({
initialState: "Copy ID to clipboard"
});
@@ -31,7 +31,7 @@ export const CaDetailsSection = ({ caName, handlePopUpOpen }: Props) => {
const { data } = useGetCa({
caName,
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
type: CaType.INTERNAL
});
diff --git a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
index 6f9cf3a1c3..857586a584 100644
--- a/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
+++ b/frontend/src/pages/cert-manager/CertAuthDetailsByIDPage/components/CaRenewalModal.tsx
@@ -13,7 +13,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
CaRenewalType,
useRenewCa
@@ -45,8 +45,8 @@ type Props = {
};
export const CaRenewalModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectSlug = currentWorkspace?.slug || "";
+ const { currentProject } = useProject();
+ const projectSlug = currentProject?.slug || "";
const popUpData = popUp?.renewCa?.data as {
caId: string;
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx
index 6f79cbb246..d737e6c45e 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/ExternalCaInstallForm.tsx
@@ -8,7 +8,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, IconButton, TextArea, Tooltip } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useTimedReset } from "@app/hooks";
import { useGetCaCsr, useImportCaCertificate } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -26,7 +26,7 @@ type Props = {
};
export const ExternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [copyTextCaCsr, isCopyingCaCsr, setCopyTextCaCsr] = useTimedReset<string>({
initialState: "Copy to clipboard"
});
@@ -41,7 +41,7 @@ export const ExternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
});
const { data: csr } = useGetCaCsr(caId);
- const { mutateAsync: importCaCertificate } = useImportCaCertificate(currentWorkspace.id);
+ const { mutateAsync: importCaCertificate } = useImportCaCertificate(currentProject.id);
useEffect(() => {
reset();
@@ -49,11 +49,11 @@ export const ExternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
const onFormSubmit = async ({ certificate, certificateChain }: FormData) => {
try {
- if (!csr || !caId || !currentWorkspace?.slug) return;
+ if (!csr || !caId || !currentProject?.slug) return;
await importCaCertificate({
caId,
- projectSlug: currentWorkspace?.slug,
+ projectSlug: currentProject?.slug,
certificate,
certificateChain
});
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx
index 677407dc88..5979d97118 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaInstallCertModal/InternalCaInstallForm.tsx
@@ -6,7 +6,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Select, SelectItem } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
CaStatus,
useGetCaById,
@@ -46,16 +46,16 @@ type Props = {
};
export const InternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: cas } = useListWorkspaceCas({
- projectSlug: currentWorkspace?.slug ?? "",
+ projectId: currentProject.id,
status: CaStatus.ACTIVE
});
const { data: ca } = useGetCaById(caId);
const { data: csr } = useGetCaCsr(caId);
const { mutateAsync: signIntermediate } = useSignIntermediate();
- const { mutateAsync: importCaCertificate } = useImportCaCertificate(currentWorkspace.id);
+ const { mutateAsync: importCaCertificate } = useImportCaCertificate(currentProject.id);
const {
control,
@@ -102,7 +102,7 @@ export const InternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
const onFormSubmit = async ({ notAfter, maxPathLength }: FormData) => {
try {
- if (!csr || !caId || !currentWorkspace?.slug) return;
+ if (!csr || !caId || !currentProject?.slug) return;
const { certificate, certificateChain } = await signIntermediate({
caId: parentCaId,
@@ -114,7 +114,7 @@ export const InternalCaInstallForm = ({ caId, handlePopUpToggle }: Props) => {
await importCaCertificate({
caId,
- projectSlug: currentWorkspace?.slug,
+ projectSlug: currentProject?.slug,
certificate,
certificateChain
});
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx
index d3040576fa..2a976d6823 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaModal.tsx
@@ -16,7 +16,7 @@ import {
Switch
// DatePicker
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
CaStatus,
CaType,
@@ -84,10 +84,10 @@ const caTypes = [
];
export const CaModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: ca } = useGetCa({
caName: (popUp?.ca?.data as { name: string })?.name || "",
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
type: CaType.INTERNAL
});
@@ -178,13 +178,13 @@ export const CaModal = ({ popUp, handlePopUpToggle }: Props) => {
configuration
}: FormData) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
if (ca) {
// update
await updateMutateAsync({
caName: ca.name,
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
name,
type: CaType.INTERNAL,
status,
@@ -193,7 +193,7 @@ export const CaModal = ({ popUp, handlePopUpToggle }: Props) => {
} else {
// create
await createMutateAsync({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
name,
type,
status,
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
index 5de6027fa7..ed4e8f8471 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaSection.tsx
@@ -5,7 +5,7 @@ import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, DeleteActionModal } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { CaStatus, CaType, useDeleteCa, useUpdateCa } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -15,7 +15,7 @@ import { CaModal } from "./CaModal";
import { CaTable } from "./CaTable";
export const CaSection = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: deleteCa } = useDeleteCa();
const { mutateAsync: updateCa } = useUpdateCa();
@@ -30,9 +30,9 @@ export const CaSection = () => {
const onRemoveCaSubmit = async (caName: string) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
- await deleteCa({ caName, projectId: currentWorkspace.id, type: CaType.INTERNAL });
+ await deleteCa({ caName, projectId: currentProject.id, type: CaType.INTERNAL });
createNotification({
text: "Successfully deleted CA",
@@ -50,9 +50,9 @@ export const CaSection = () => {
const onUpdateCaStatus = async ({ caName, status }: { caName: string; status: CaStatus }) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
- await updateCa({ caName, projectId: currentWorkspace.id, type: CaType.INTERNAL, status });
+ await updateCa({ caName, projectId: currentProject.id, type: CaType.INTERNAL, status });
createNotification({
text: `Successfully ${status === CaStatus.ACTIVE ? "enabled" : "disabled"} CA`,
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx
index 00ab03625a..81fce98c66 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/CaTable.tsx
@@ -22,7 +22,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { CaStatus, CaType, useListCasByTypeAndProjectId } from "@app/hooks/api";
import {
caStatusToNameMap,
@@ -49,8 +49,8 @@ type Props = {
export const CaTable = ({ handlePopUpOpen }: Props) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const { data, isPending } = useListCasByTypeAndProjectId(CaType.INTERNAL, currentWorkspace.id);
+ const { currentProject } = useProject();
+ const { data, isPending } = useListCasByTypeAndProjectId(CaType.INTERNAL, currentProject.id);
const cas = data as TInternalCertificateAuthority[];
return (
@@ -80,7 +80,7 @@ export const CaTable = ({ handlePopUpOpen }: Props) => {
navigate({
to: "/projects/cert-management/$projectId/ca/$caName",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
caName: ca.name
}
})
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
index 68757f5496..121c32e5f5 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
@@ -4,6 +4,7 @@ import { SingleValue } from "react-select";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
+import { AppConnectionOption } from "@app/components/app-connections";
import { createNotification } from "@app/components/notifications";
import {
Button,
@@ -16,7 +17,7 @@ import {
SelectItem,
Switch
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
import {
TAvailableAppConnection,
@@ -127,11 +128,11 @@ const caTypes = [
];
export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: ca, isLoading: isCaLoading } = useGetCa({
caName: (popUp?.ca?.data as { name: string })?.name || "",
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
type: (popUp?.ca?.data as { type: CaType })?.type || ""
});
@@ -201,17 +202,17 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
}, [popUp?.ca?.isOpen, popUp?.ca?.data, reset, ca]);
const { data: availableRoute53Connections, isPending: isRoute53Pending } =
- useListAvailableAppConnections(AppConnection.AWS, {
+ useListAvailableAppConnections(AppConnection.AWS, currentProject.id, {
enabled: caType === CaType.ACME
});
const { data: availableCloudflareConnections, isPending: isCloudflarePending } =
- useListAvailableAppConnections(AppConnection.Cloudflare, {
+ useListAvailableAppConnections(AppConnection.Cloudflare, currentProject.id, {
enabled: caType === CaType.ACME
});
const { data: availableAzureConnections, isPending: isAzurePending } =
- useListAvailableAppConnections(AppConnection.AzureADCS, {
+ useListAvailableAppConnections(AppConnection.AzureADCS, currentProject.id, {
enabled: caType === CaType.AZURE_AD_CS
});
@@ -297,7 +298,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
configuration: formConfiguration
}: FormData) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
let configPayload: any;
@@ -321,7 +322,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
if (ca) {
await updateMutateAsync({
caName: ca.name,
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
name,
type,
status,
@@ -330,7 +331,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
});
} else {
await createMutateAsync({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
name,
type,
status,
@@ -457,6 +458,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
placeholder="Select connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
+ components={{ Option: AppConnectionOption }}
/>
</FormControl>
)}
@@ -599,6 +601,7 @@ export const ExternalCaModal = ({ popUp, handlePopUpToggle }: Props) => {
placeholder="Select connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
+ components={{ Option: AppConnectionOption }}
/>
</FormControl>
)}
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx
index c8d117e210..7e60b03730 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaSection.tsx
@@ -5,7 +5,7 @@ import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, DeleteActionModal } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { CaStatus, CaType, useDeleteCa, useUpdateCa } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -13,7 +13,7 @@ import { ExternalCaModal } from "./ExternalCaModal";
import { ExternalCaTable } from "./ExternalCaTable";
export const ExternalCaSection = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: deleteCa } = useDeleteCa();
const { mutateAsync: updateCa } = useUpdateCa();
@@ -26,9 +26,9 @@ export const ExternalCaSection = () => {
const onRemoveCaSubmit = async (caName: string, type: CaType) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
- await deleteCa({ caName, type, projectId: currentWorkspace.id });
+ await deleteCa({ caName, type, projectId: currentProject.id });
createNotification({
text: "Successfully deleted CA",
@@ -54,9 +54,9 @@ export const ExternalCaSection = () => {
status: CaStatus;
}) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
- await updateCa({ caName: name, type, status, projectId: currentWorkspace.id });
+ await updateCa({ caName: name, type, status, projectId: currentProject.id });
createNotification({
text: `Successfully ${status === CaStatus.ACTIVE ? "enabled" : "disabled"} CA`,
diff --git a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx
index e7b18f4291..a948473e8f 100644
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaTable.tsx
@@ -26,7 +26,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { CaStatus, CaType, useListExternalCasByProjectId } from "@app/hooks/api";
import { caStatusToNameMap, getCaStatusBadgeVariant } from "@app/hooks/api/ca/constants";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -44,8 +44,8 @@ type Props = {
};
export const ExternalCaTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const { data, isPending } = useListExternalCasByProjectId(currentWorkspace.id);
+ const { currentProject } = useProject();
+ const { data, isPending } = useListExternalCasByProjectId(currentProject.id);
return (
<div>
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
index c4cffe7b01..70b51cbbe5 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateImportModal.tsx
@@ -14,7 +14,7 @@ import {
SelectItem,
TextArea
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useGetCert, useImportCertificate, useListWorkspacePkiCollections } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -48,13 +48,13 @@ type TCertificateDetails = {
export const CertificateImportModal = ({ popUp, handlePopUpToggle }: Props) => {
const [certificateDetails, setCertificateDetails] = useState<TCertificateDetails | null>(null);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: cert } = useGetCert(
(popUp?.certificateImport?.data as { serialNumber: string })?.serialNumber || ""
);
const { data } = useListWorkspacePkiCollections({
- workspaceId: currentWorkspace?.id || ""
+ projectId: currentProject?.id || ""
});
const { mutateAsync: importCertificate } = useImportCertificate();
@@ -76,10 +76,10 @@ export const CertificateImportModal = ({ popUp, handlePopUpToggle }: Props) => {
collectionId
}: FormData) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
const { serialNumber, certificate, certificateChain, privateKey } = await importCertificate({
- projectSlug: currentWorkspace.slug,
+ projectSlug: currentProject.slug,
certificatePem,
privateKeyPem,
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx
index a10743023e..a8509fe174 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateModal.tsx
@@ -22,7 +22,7 @@ import {
SelectItem,
Tooltip
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
CaStatus,
useCreateCertificate,
@@ -89,22 +89,22 @@ const CERT_TEMPLATE_NONE_VALUE = "none";
export const CertificateModal = ({ popUp, handlePopUpToggle }: Props) => {
const [certificateDetails, setCertificateDetails] = useState<TCertificateDetails | null>(null);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: cert } = useGetCert(
(popUp?.certificate?.data as { serialNumber: string })?.serialNumber || ""
);
const { data: cas } = useListWorkspaceCas({
- projectSlug: currentWorkspace?.slug ?? "",
+ projectId: currentProject.id,
status: CaStatus.ACTIVE
});
const { data } = useListWorkspacePkiCollections({
- workspaceId: currentWorkspace?.id || ""
+ projectId: currentProject?.id || ""
});
const { data: templatesData } = useListWorkspaceCertificateTemplates({
- workspaceId: currentWorkspace?.id || ""
+ projectId: currentProject?.id || ""
});
const { mutateAsync: createCertificate } = useCreateCertificate();
@@ -191,12 +191,12 @@ export const CertificateModal = ({ popUp, handlePopUpToggle }: Props) => {
extendedKeyUsages
}: FormData) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
const { serialNumber, certificate, certificateChain, privateKey } = await createCertificate({
caId: !selectedCertTemplate ? caId : undefined,
certificateTemplateId: selectedCertTemplate ? selectedCertTemplateId : undefined,
- projectSlug: currentWorkspace.slug,
+ projectSlug: currentProject.slug,
pkiCollectionId: collectionId,
friendlyName,
commonName,
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx
index 2f14fda3fc..1d15392960 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateRevocationModal.tsx
@@ -4,7 +4,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Modal, ModalContent, Select, SelectItem } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useRevokeCert } from "@app/hooks/api";
import { crlReasons } from "@app/hooks/api/certificates/constants";
import { CrlReason } from "@app/hooks/api/certificates/enums";
@@ -35,7 +35,7 @@ type Props = {
};
export const CertificateRevocationModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: revokeCertificate } = useRevokeCert();
const {
@@ -49,12 +49,12 @@ export const CertificateRevocationModal = ({ popUp, handlePopUpToggle }: Props)
const onFormSubmit = async ({ revocationReason }: FormData) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
const { serialNumber } = popUp.revokeCertificate.data as { serialNumber: string };
await revokeCertificate({
- projectSlug: currentWorkspace.slug,
+ projectSlug: currentProject.slug,
serialNumber,
revocationReason
});
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx
index d709458f0c..8f547e5735 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplateModal.tsx
@@ -22,7 +22,7 @@ import {
SelectItem,
Tooltip
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
CaStatus,
useCreateCertTemplate,
@@ -82,7 +82,7 @@ type Props = {
};
export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: ca } = useGetCaById(caId);
@@ -91,12 +91,12 @@ export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Pro
);
const { data: cas } = useListWorkspaceCas({
- projectSlug: currentWorkspace?.slug ?? "",
+ projectId: currentProject?.id,
status: CaStatus.ACTIVE
});
const { data: collectionsData } = useListWorkspacePkiCollections({
- workspaceId: currentWorkspace?.id || ""
+ projectId: currentProject?.id || ""
});
const { mutateAsync: createCertTemplate } = useCreateCertTemplate();
@@ -155,7 +155,7 @@ export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Pro
keyUsages,
extendedKeyUsages
}: FormData) => {
- if (!currentWorkspace?.id) {
+ if (!currentProject?.id) {
return;
}
@@ -163,7 +163,7 @@ export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Pro
if (certTemplate) {
await updateCertTemplate({
id: certTemplate.id,
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
pkiCollectionId: collectionId,
caId,
name,
@@ -184,7 +184,7 @@ export const CertificateTemplateModal = ({ popUp, handlePopUpToggle, caId }: Pro
});
} else {
await createCertTemplate({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
pkiCollectionId: collectionId,
caId,
name,
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx
index 0db7ba9237..89f9780e8d 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificateTemplatesSection.tsx
@@ -12,7 +12,7 @@ import { DeleteActionModal, IconButton } from "@app/components/v2";
import {
ProjectPermissionPkiTemplateActions,
ProjectPermissionSub,
- useWorkspace
+ useProject
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteCertTemplate } from "@app/hooks/api";
@@ -33,18 +33,18 @@ export const CertificateTemplatesSection = ({ caId }: Props) => {
"upgradePlan"
] as const);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: deleteCertTemplate } = useDeleteCertTemplate();
const onRemoveCertificateTemplateSubmit = async (id: string) => {
- if (!currentWorkspace?.id) {
+ if (!currentProject?.id) {
return;
}
try {
await deleteCertTemplate({
id,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
});
createNotification({
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
index 44ddbc8bad..696d077624 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesSection.tsx
@@ -7,7 +7,7 @@ import { Button, DeleteActionModal } from "@app/components/v2";
import {
ProjectPermissionCertificateActions,
ProjectPermissionSub,
- useWorkspace
+ useProject
} from "@app/context";
import { useDeleteCert } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -19,7 +19,7 @@ import { CertificateRevocationModal } from "./CertificateRevocationModal";
import { CertificatesTable } from "./CertificatesTable";
export const CertificatesSection = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: deleteCert } = useDeleteCert();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
@@ -32,9 +32,9 @@ export const CertificatesSection = () => {
const onRemoveCertificateSubmit = async (serialNumber: string) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
- await deleteCert({ serialNumber, projectSlug: currentWorkspace.slug });
+ await deleteCert({ serialNumber, projectSlug: currentProject.slug });
createNotification({
text: "Successfully deleted certificate",
diff --git a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
index 98f83bc02a..3cf35ebd62 100644
--- a/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
+++ b/frontend/src/pages/cert-manager/CertificatesPage/components/CertificatesTable.tsx
@@ -33,7 +33,7 @@ import {
import {
ProjectPermissionCertificateActions,
ProjectPermissionSub,
- useWorkspace
+ useProject
} from "@app/context";
import { useListWorkspaceCertificates } from "@app/hooks/api";
import { caSupportsCapability } from "@app/hooks/api/ca/constants";
@@ -62,15 +62,15 @@ export const CertificatesTable = ({ handlePopUpOpen }: Props) => {
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE_INIT);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data, isPending } = useListWorkspaceCertificates({
- projectSlug: currentWorkspace?.slug ?? "",
+ projectId: currentProject?.slug ?? "",
offset: (page - 1) * perPage,
limit: perPage
});
// Fetch CA data to determine capabilities
- const { data: caData } = useListCasByProjectId(currentWorkspace?.id ?? "");
+ const { data: caData } = useListCasByProjectId(currentProject?.id ?? "");
// Create mapping from caId to CA type for capability checking
const caCapabilityMap = useMemo(() => {
diff --git a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx
index 0261d55fd1..c53df83be9 100644
--- a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/PkiCollectionDetailsByIDPage.tsx
@@ -16,7 +16,7 @@ import {
Tooltip
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useDeletePkiCollection, useGetPkiCollectionById } from "@app/hooks/api";
import { PkiItemType } from "@app/hooks/api/pkiCollections/constants";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -30,8 +30,8 @@ export const PkiCollectionPage = () => {
from: ROUTE_PATHS.CertManager.PkiCollectionDetailsByIDPage.id
});
const collectionId = params.collectionId as string;
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data } = useGetPkiCollectionById(collectionId);
const { mutateAsync: deletePkiCollection } = useDeletePkiCollection();
diff --git a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx
index f356f21908..3bcc3dc317 100644
--- a/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx
+++ b/frontend/src/pages/cert-manager/PkiCollectionDetailsByIDPage/components/AddPkiCollectionItemModal.tsx
@@ -4,7 +4,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Modal, ModalContent, Select, SelectItem } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
CaStatus,
useAddItemToPkiCollection,
@@ -41,15 +41,15 @@ export const AddPkiCollectionItemModal = ({
popUp,
handlePopUpToggle
}: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: cas } = useListWorkspaceCas({
- projectSlug: currentWorkspace?.slug || "",
+ projectId: currentProject?.id || "",
status: CaStatus.ACTIVE
});
const { data } = useListWorkspaceCertificates({
- projectSlug: currentWorkspace?.slug || "",
+ projectId: currentProject?.slug || "",
offset: 0,
limit: 25
});
diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx
index 04db9861b7..d7d44d4b56 100644
--- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/PkiSubscriberDetailsByIDPage.tsx
@@ -19,7 +19,7 @@ import { ROUTE_PATHS } from "@app/const/routes";
import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionSub,
- useWorkspace
+ useProject
} from "@app/context";
import { useDeletePkiSubscriber, useGetPkiSubscriber } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -29,8 +29,8 @@ import { PkiSubscriberCertificatesSection, PkiSubscriberDetailsSection } from ".
const Page = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const subscriberName = useParams({
from: ROUTE_PATHS.CertManager.PkiSubscriberDetailsByIDPage.id,
select: (el) => el.subscriberName
diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx
index 62e7337bd3..d3533d71d1 100644
--- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberCertificatesTable.tsx
@@ -27,8 +27,8 @@ import {
import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { useGetPkiSubscriberCertificates } from "@app/hooks/api";
import { caSupportsCapability } from "@app/hooks/api/ca/constants";
@@ -45,8 +45,8 @@ type Props = {
const PER_PAGE_INIT = 25;
export const PkiSubscriberCertificatesTable = ({ subscriberName, handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const { permission } = useProjectPermission();
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE_INIT);
@@ -64,7 +64,7 @@ export const PkiSubscriberCertificatesTable = ({ subscriberName, handlePopUpOpen
);
// Fetch CA data to determine capabilities
- const { data: caData } = useListCasByProjectId(currentWorkspace.id);
+ const { data: caData } = useListCasByProjectId(currentProject.id);
// Create mapping from caId to CA type for capability checking
const caCapabilityMap = useMemo(() => {
diff --git a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx
index 1f15982a4f..bb928dcc28 100644
--- a/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscriberDetailsByIDPage/components/PkiSubscriberDetailsSection.tsx
@@ -16,8 +16,8 @@ import {
import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { useTimedReset } from "@app/hooks";
import {
@@ -44,8 +44,8 @@ type TCertificateDetails = {
};
export const PkiSubscriberDetailsSection = ({ subscriberName, handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const { permission } = useProjectPermission();
const [certificateDetails, setCertificateDetails] = useState<TCertificateDetails | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx
index f6deb97cb9..932f3201b4 100644
--- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberModal.tsx
@@ -22,7 +22,7 @@ import {
TabPanel,
Tabs
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
CaType,
useCreatePkiSubscriber,
@@ -158,8 +158,8 @@ const schema = z
export type FormData = z.infer<typeof schema>;
export const PkiSubscriberModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const { data: subscribers } = useListWorkspacePkiSubscribers(projectId);
const { data: cas } = useListCasByProjectId(projectId);
const [tabValue, setTabValue] = useState<FormTab>(FormTab.Configuration);
diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx
index f81636e491..f9680af9bd 100644
--- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscriberSection.tsx
@@ -7,7 +7,7 @@ import { Button, DeleteActionModal } from "@app/components/v2";
import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionSub,
- useWorkspace
+ useProject
} from "@app/context";
import { useDeletePkiSubscriber, useUpdatePkiSubscriber } from "@app/hooks/api";
import { PkiSubscriberStatus } from "@app/hooks/api/pkiSubscriber/types";
@@ -17,8 +17,8 @@ import { PkiSubscriberModal } from "./PkiSubscriberModal";
import { PkiSubscribersTable } from "./PkiSubscribersTable";
export const PkiSubscriberSection = () => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const { mutateAsync: deletePkiSubscriber } = useDeletePkiSubscriber();
const { mutateAsync: updatePkiSubscriber } = useUpdatePkiSubscriber();
@@ -55,7 +55,7 @@ export const PkiSubscriberSection = () => {
status: PkiSubscriberStatus;
}) => {
try {
- if (!currentWorkspace?.slug) return;
+ if (!currentProject?.slug) return;
await updatePkiSubscriber({ subscriberName, projectId, status });
diff --git a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx
index d649c43a73..d28c2d3a2c 100644
--- a/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx
+++ b/frontend/src/pages/cert-manager/PkiSubscribersPage/components/PkiSubscribersTable.tsx
@@ -30,7 +30,7 @@ import {
import {
ProjectPermissionPkiSubscriberActions,
ProjectPermissionSub,
- useWorkspace
+ useProject
} from "@app/context";
import { useListWorkspacePkiSubscribers } from "@app/hooks/api";
import {
@@ -49,8 +49,8 @@ type Props = {
export const PkiSubscribersTable = ({ handlePopUpOpen }: Props) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const { data, isPending } = useListWorkspacePkiSubscribers(currentWorkspace?.id || "");
+ const { currentProject } = useProject();
+ const { data, isPending } = useListWorkspacePkiSubscribers(currentProject?.id || "");
return (
<div>
<TableContainer>
@@ -77,7 +77,7 @@ export const PkiSubscribersTable = ({ handlePopUpOpen }: Props) => {
navigate({
to: "/projects/cert-management/$projectId/subscribers/$subscriberName",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
subscriberName: subscriber.name
}
})
diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx
index 4449e9a977..2ffe688131 100644
--- a/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx
+++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/PkiTemplateListPage.tsx
@@ -42,8 +42,8 @@ import {
import {
ProjectPermissionPkiTemplateActions,
ProjectPermissionSub,
- useSubscription,
- useWorkspace
+ useProject,
+ useSubscription
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteCertTemplateV2 } from "@app/hooks/api";
@@ -55,7 +55,7 @@ import { PkiTemplateForm } from "./components/PkiTemplateForm";
const PER_PAGE_INIT = 25;
export const PkiTemplateListPage = () => {
const { t } = useTranslation();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE_INIT);
const { handlePopUpToggle, popUp, handlePopUpOpen, handlePopUpClose } = usePopUp([
@@ -68,7 +68,7 @@ export const PkiTemplateListPage = () => {
const { subscription } = useSubscription();
const { data, isPending } = useListCertificateTemplates({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
offset: (page - 1) * perPage,
limit: perPage
});
@@ -78,7 +78,7 @@ export const PkiTemplateListPage = () => {
const onRemovePkiSubscriberSubmit = async () => {
try {
const pkiTemplate = await deleteCertTemplate.mutateAsync({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
templateName: popUp?.deleteTemplate?.data?.name
});
diff --git a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx
index f52c83725f..b8cdbfe1c3 100644
--- a/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx
+++ b/frontend/src/pages/cert-manager/PkiTemplateListPage/components/PkiTemplateForm.tsx
@@ -18,7 +18,7 @@ import {
Input,
Tooltip
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreateCertTemplateV2,
useListCasByProjectId,
@@ -72,9 +72,9 @@ type Props = {
};
export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
- const { data: cas, isPending: isCaLoading } = useListCasByProjectId(currentWorkspace.id);
+ const { data: cas, isPending: isCaLoading } = useListCasByProjectId(currentProject.id);
const { mutateAsync: createCertTemplate } = useCreateCertTemplateV2();
const { mutateAsync: updateCertTemplate } = useUpdateCertTemplateV2();
@@ -124,7 +124,7 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => {
extendedKeyUsages,
ca
}: FormData) => {
- if (!currentWorkspace?.id) {
+ if (!currentProject?.id) {
return;
}
@@ -132,7 +132,7 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => {
if (certTemplate) {
await updateCertTemplate({
templateName: certTemplate.name,
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
caName: ca.name,
name,
commonName,
@@ -152,7 +152,7 @@ export const PkiTemplateForm = ({ certTemplate, handlePopUpToggle }: Props) => {
});
} else {
await createCertTemplate({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
caName: ca.name,
name,
commonName,
diff --git a/frontend/src/pages/cert-manager/layout.tsx b/frontend/src/pages/cert-manager/layout.tsx
index 6b846909e0..c8ec6a23b3 100644
--- a/frontend/src/pages/cert-manager/layout.tsx
+++ b/frontend/src/pages/cert-manager/layout.tsx
@@ -1,9 +1,9 @@
import { createFileRoute } from "@tanstack/react-router";
import { BreadcrumbTypes } from "@app/components/v2";
-import { workspaceKeys } from "@app/hooks/api";
+import { projectKeys } from "@app/hooks/api";
+import { fetchProjectById } from "@app/hooks/api/projects/queries";
import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
-import { fetchWorkspaceById } from "@app/hooks/api/workspace/queries";
import { PkiManagerLayout } from "@app/layouts/PkiManagerLayout";
import { ProjectSelect } from "@app/layouts/ProjectLayout/components/ProjectSelect";
@@ -13,15 +13,15 @@ export const Route = createFileRoute(
component: PkiManagerLayout,
beforeLoad: async ({ params, context }) => {
const project = await context.queryClient.ensureQueryData({
- queryKey: workspaceKeys.getWorkspaceById(params.projectId),
- queryFn: () => fetchWorkspaceById(params.projectId)
+ queryKey: projectKeys.getProjectById(params.projectId),
+ queryFn: () => fetchProjectById(params.projectId)
});
await context.queryClient.ensureQueryData({
queryKey: roleQueryKeys.getUserProjectPermissions({
- workspaceId: params.projectId
+ projectId: params.projectId
}),
- queryFn: () => fetchUserProjectPermissions({ workspaceId: params.projectId })
+ queryFn: () => fetchUserProjectPermissions({ projectId: params.projectId })
});
return {
diff --git a/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx b/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx
index 8c959c7b07..7abbee35fc 100644
--- a/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx
+++ b/frontend/src/pages/kms/KmipPage/components/KmipClientModal.tsx
@@ -13,7 +13,7 @@ import {
ModalContent,
TextArea
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateKmipClient, useUpdateKmipClient } from "@app/hooks/api/kmip";
import { KmipPermission, TKmipClient } from "@app/hooks/api/kmip/types";
@@ -60,8 +60,8 @@ type FormProps = Pick<Props, "kmipClient"> & {
const KmipClientForm = ({ onComplete, kmipClient }: FormProps) => {
const createKmipClient = useCreateKmipClient();
const updateKmipClient = useUpdateKmipClient();
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const isUpdate = !!kmipClient;
const {
diff --git a/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx b/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx
index bcc49b11a1..5abad9f181 100644
--- a/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx
+++ b/frontend/src/pages/kms/KmipPage/components/KmipClientTable.tsx
@@ -39,9 +39,9 @@ import {
import {
ProjectPermissionKmipActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import {
getUserTablePreference,
@@ -59,9 +59,9 @@ import { KmipClientCertificateModal } from "./KmipClientCertificateModal";
import { KmipClientModal } from "./KmipClientModal";
export const KmipClientTable = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
- const projectId = currentWorkspace?.id ?? "";
+ const projectId = currentProject?.id ?? "";
const {
offset,
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx
index c43b6c8d0d..93c0102b16 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx
@@ -14,7 +14,7 @@ import {
SelectItem,
TextArea
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { keyUsageDefaultOption, kmsKeyUsageOptions } from "@app/helpers/kms";
import {
AllowedEncryptionKeyAlgorithms,
@@ -49,8 +49,8 @@ type FormProps = Pick<Props, "cmek"> & {
const CmekForm = ({ onComplete, cmek }: FormProps) => {
const createCmek = useCreateCmek();
const updateCmek = useUpdateCmek();
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const isUpdate = !!cmek;
const {
diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
index e1a2fe7892..b1a7c409c2 100644
--- a/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
+++ b/frontend/src/pages/kms/OverviewPage/components/CmekTable.tsx
@@ -49,8 +49,8 @@ import {
ProjectPermissionActions,
ProjectPermissionCmekActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { kmsKeyUsageOptions } from "@app/helpers/kms";
import {
@@ -87,10 +87,10 @@ const getStatusBadgeProps = (
};
export const CmekTable = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { permission } = useProjectPermission();
- const projectId = currentWorkspace?.id ?? "";
+ const projectId = currentProject?.id ?? "";
const {
offset,
diff --git a/frontend/src/pages/kms/layout.tsx b/frontend/src/pages/kms/layout.tsx
index 60bc35ab72..f29a7627a6 100644
--- a/frontend/src/pages/kms/layout.tsx
+++ b/frontend/src/pages/kms/layout.tsx
@@ -1,9 +1,9 @@
import { createFileRoute } from "@tanstack/react-router";
import { BreadcrumbTypes } from "@app/components/v2";
-import { workspaceKeys } from "@app/hooks/api";
+import { projectKeys } from "@app/hooks/api";
+import { fetchProjectById } from "@app/hooks/api/projects/queries";
import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
-import { fetchWorkspaceById } from "@app/hooks/api/workspace/queries";
import { KmsLayout } from "@app/layouts/KmsLayout";
import { ProjectSelect } from "@app/layouts/ProjectLayout/components/ProjectSelect";
@@ -13,15 +13,15 @@ export const Route = createFileRoute(
component: KmsLayout,
beforeLoad: async ({ params, context }) => {
const project = await context.queryClient.ensureQueryData({
- queryKey: workspaceKeys.getWorkspaceById(params.projectId),
- queryFn: () => fetchWorkspaceById(params.projectId)
+ queryKey: projectKeys.getProjectById(params.projectId),
+ queryFn: () => fetchProjectById(params.projectId)
});
await context.queryClient.ensureQueryData({
queryKey: roleQueryKeys.getUserProjectPermissions({
- workspaceId: params.projectId
+ projectId: params.projectId
}),
- queryFn: () => fetchUserProjectPermissions({ workspaceId: params.projectId })
+ queryFn: () => fetchUserProjectPermissions({ projectId: params.projectId })
});
return {
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx
index ee0cddc5c1..31f7e56ebe 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm.tsx
@@ -3,6 +3,7 @@ import { Controller, useFieldArray, useForm } from "react-hook-form";
import { faPlus, faQuestionCircle, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
+import ms from "ms";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
@@ -25,6 +26,7 @@ import {
OrgPermissionMachineIdentityAuthTemplateActions,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
+import { getObjectFromSeconds } from "@app/helpers/datetime";
import {
MachineIdentityAuthMethod,
useAddIdentityLdapAuth,
@@ -35,6 +37,8 @@ import { IdentityTrustedIp } from "@app/hooks/api/identities/types";
import { useGetAvailableTemplates } from "@app/hooks/api/identityAuthTemplates/queries";
import { UsePopUpState } from "@app/hooks/usePopUp";
+import { LockoutTab } from "./lockout/LockoutTab";
+import { superRefineLockout } from "./lockout/super-refine";
import { IdentityFormTab } from "./types";
const schema = z
@@ -74,9 +78,28 @@ const schema = z
ipAddress: z.string().max(50)
})
)
- .min(1)
+ .min(1),
+
+ lockoutEnabled: z.boolean().default(true),
+ lockoutThreshold: z
+ .string()
+ .refine(
+ (value) => Number(value) <= 30 && Number(value) >= 1,
+ "Lockout threshold must be between 1 and 30"
+ ),
+ lockoutDurationValue: z.string(),
+ lockoutDurationUnit: z.enum(["s", "m", "h", "d"], {
+ invalid_type_error: "Please select a valid time unit"
+ }),
+ lockoutCounterResetValue: z.string(),
+ lockoutCounterResetUnit: z.enum(["s", "m", "h"], {
+ invalid_type_error: "Please select a valid time unit"
+ })
})
+ .required()
.superRefine((data, ctx) => {
+ superRefineLockout(data, ctx);
+
// Validation based on scope
if (data.scope === "template") {
if (!data.templateId) {
@@ -178,12 +201,25 @@ export const IdentityLdapAuthForm = ({
accessTokenTTL: "2592000",
accessTokenMaxTTL: "2592000",
accessTokenNumUsesLimit: "0",
- accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]
+ accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
+ lockoutEnabled: true,
+ lockoutThreshold: "3",
+ lockoutDurationValue: "5",
+ lockoutDurationUnit: "m",
+ lockoutCounterResetValue: "30",
+ lockoutCounterResetUnit: "s"
}
});
const scope = watch("scope");
+ const lockoutEnabledWatch = watch("lockoutEnabled");
+ const lockoutThresholdWatch = watch("lockoutThreshold");
+ const lockoutDurationValueWatch = watch("lockoutDurationValue");
+ const lockoutDurationUnitWatch = watch("lockoutDurationUnit");
+ const lockoutCounterResetValueWatch = watch("lockoutCounterResetValue");
+ const lockoutCounterResetUnitWatch = watch("lockoutCounterResetUnit");
+
const {
fields: accessTokenTrustedIpsFields,
append: appendAccessTokenTrustedIp,
@@ -210,6 +246,9 @@ export const IdentityLdapAuthForm = ({
if (data) {
const detectedScope = determineScope(data);
+ const lockoutDurationObj = getObjectFromSeconds(data.lockoutDurationSeconds);
+ const lockoutCounterResetObj = getObjectFromSeconds(data.lockoutCounterResetSeconds);
+
reset({
scope: detectedScope,
templateId: data.templateId || "",
@@ -229,7 +268,13 @@ export const IdentityLdapAuthForm = ({
ipAddress: `${ipAddress}${prefix !== undefined ? `/${prefix}` : ""}`
};
}
- )
+ ),
+ lockoutEnabled: data.lockoutEnabled,
+ lockoutThreshold: String(data.lockoutThreshold),
+ lockoutDurationValue: String(lockoutDurationObj.value),
+ lockoutDurationUnit: lockoutDurationObj.unit as "s" | "m" | "h" | "d",
+ lockoutCounterResetValue: String(lockoutCounterResetObj.value),
+ lockoutCounterResetUnit: lockoutCounterResetObj.unit as "s" | "m" | "h"
});
return;
}
@@ -247,7 +292,13 @@ export const IdentityLdapAuthForm = ({
accessTokenTTL: "2592000",
accessTokenMaxTTL: "2592000",
accessTokenNumUsesLimit: "0",
- accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }]
+ accessTokenTrustedIps: [{ ipAddress: "0.0.0.0/0" }, { ipAddress: "::/0" }],
+ lockoutEnabled: true,
+ lockoutThreshold: "3",
+ lockoutDurationValue: "5",
+ lockoutDurationUnit: "m",
+ lockoutCounterResetValue: "30",
+ lockoutCounterResetUnit: "s"
});
}, [data, reset]);
@@ -275,9 +326,19 @@ export const IdentityLdapAuthForm = ({
accessTokenTTL,
accessTokenMaxTTL,
accessTokenNumUsesLimit,
- accessTokenTrustedIps
+ accessTokenTrustedIps,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationValue,
+ lockoutDurationUnit,
+ lockoutCounterResetValue,
+ lockoutCounterResetUnit
} = formData;
+ const lockoutDurationSeconds = ms(`${lockoutDurationValue}${lockoutDurationUnit}`) / 1000;
+ const lockoutCounterResetSeconds =
+ ms(`${lockoutCounterResetValue}${lockoutCounterResetUnit}`) / 1000;
+
const basePayload = {
organizationId: orgId,
identityId,
@@ -287,7 +348,11 @@ export const IdentityLdapAuthForm = ({
accessTokenTTL: Number(accessTokenTTL),
accessTokenMaxTTL: Number(accessTokenMaxTTL),
accessTokenNumUsesLimit: Number(accessTokenNumUsesLimit),
- accessTokenTrustedIps
+ accessTokenTrustedIps,
+ lockoutEnabled,
+ lockoutThreshold: Number(lockoutThreshold),
+ lockoutDurationSeconds,
+ lockoutCounterResetSeconds
};
// Add scope-specific fields
@@ -327,7 +392,10 @@ export const IdentityLdapAuthForm = ({
return (
<form
onSubmit={handleSubmit(onFormSubmit, (fields) => {
- setTabValue(
+ const firstErrorField = Object.keys(fields)[0];
+ let tab = IdentityFormTab.Advanced;
+
+ if (
[
"scope",
"templateId",
@@ -340,15 +408,29 @@ export const IdentityLdapAuthForm = ({
"allowedFields",
"accessTokenMaxTTL",
"accessTokenNumUsesLimit"
- ].includes(Object.keys(fields)[0])
- ? IdentityFormTab.Configuration
- : IdentityFormTab.Advanced
- );
+ ].includes(firstErrorField)
+ ) {
+ tab = IdentityFormTab.Configuration;
+ } else if (
+ [
+ "lockoutEnabled",
+ "lockoutThreshold",
+ "lockoutDurationValue",
+ "lockoutDurationUnit",
+ "lockoutCounterResetValue",
+ "lockoutCounterResetUnit"
+ ].includes(firstErrorField)
+ ) {
+ tab = IdentityFormTab.Lockout;
+ }
+
+ setTabValue(tab);
})}
>
<Tabs value={tabValue} onValueChange={(value) => setTabValue(value as IdentityFormTab)}>
<TabList>
<Tab value={IdentityFormTab.Configuration}>Configuration</Tab>
+ <Tab value={IdentityFormTab.Lockout}>Lockout</Tab>
<Tab value={IdentityFormTab.Advanced}>Advanced</Tab>
</TabList>
<TabPanel value={IdentityFormTab.Configuration}>
@@ -691,6 +773,15 @@ export const IdentityLdapAuthForm = ({
)}
/>
</TabPanel>
+ <LockoutTab
+ control={control}
+ lockoutEnabled={lockoutEnabledWatch}
+ lockoutThreshold={lockoutThresholdWatch}
+ lockoutDurationValue={lockoutDurationValueWatch}
+ lockoutDurationUnit={lockoutDurationUnitWatch}
+ lockoutCounterResetValue={lockoutCounterResetValueWatch}
+ lockoutCounterResetUnit={lockoutCounterResetUnitWatch}
+ />
<TabPanel value={IdentityFormTab.Advanced}>
<Controller
control={control}
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx
index 791fdb716d..bd95bdd86e 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentitySection.tsx
@@ -181,7 +181,7 @@ export const IdentitySection = withPermission(
type="submit"
leftIcon={<FontAwesomeIcon icon={faPlus} />}
onClick={() => {
- if (subscription && !subscription.kmip) {
+ if (subscription && !subscription.machineIdentityAuthTemplates) {
handlePopUpOpen("upgradePlan");
return;
}
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx
index 2489be7bed..b4f9330d92 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm.tsx
@@ -12,9 +12,6 @@ import {
FormControl,
IconButton,
Input,
- Select,
- SelectItem,
- Switch,
Tab,
TabList,
TabPanel,
@@ -30,6 +27,8 @@ import {
import { IdentityTrustedIp } from "@app/hooks/api/identities/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
+import { LockoutTab } from "./lockout/LockoutTab";
+import { superRefineLockout } from "./lockout/super-refine";
import { IdentityFormTab } from "./types";
const schema = z
@@ -83,61 +82,7 @@ const schema = z
})
})
.required()
- .superRefine((data, ctx) => {
- const {
- lockoutDurationValue,
- lockoutCounterResetValue,
- lockoutDurationUnit,
- lockoutCounterResetUnit,
- lockoutEnabled
- } = data;
-
- if (!lockoutEnabled) return;
-
- let isAnyParseError = false;
-
- const parsedLockoutDuration = parseInt(lockoutDurationValue, 10);
- if (Number.isNaN(parsedLockoutDuration)) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Lockout duration must be a number",
- path: ["lockoutDurationValue"]
- });
- isAnyParseError = true;
- }
-
- const parsedLockoutCounterReset = parseInt(lockoutCounterResetValue, 10);
- if (Number.isNaN(parsedLockoutCounterReset)) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Lockout counter reset must be a number",
- path: ["lockoutCounterResetValue"]
- });
- isAnyParseError = true;
- }
-
- if (isAnyParseError) return;
-
- const lockoutDurationInSeconds = ms(`${parsedLockoutDuration}${lockoutDurationUnit}`) / 1000;
- const lockoutCounterResetInSeconds =
- ms(`${parsedLockoutCounterReset}${lockoutCounterResetUnit}`) / 1000;
-
- if (lockoutDurationInSeconds > 86400 || lockoutDurationInSeconds < 30) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Lockout duration must be between 30 seconds and 1 day",
- path: ["lockoutDurationValue"]
- });
- }
-
- if (lockoutCounterResetInSeconds > 3600 || lockoutCounterResetInSeconds < 5) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: "Lockout counter reset must be between 5 seconds and 1 hour",
- path: ["lockoutCounterResetValue"]
- });
- }
- });
+ .superRefine(superRefineLockout);
export type FormData = z.infer<typeof schema>;
@@ -432,187 +377,15 @@ export const IdentityUniversalAuthForm = ({
)}
/>
</TabPanel>
- <TabPanel value={IdentityFormTab.Lockout}>
- <div className="mb-3 flex flex-col">
- <Controller
- control={control}
- name="lockoutEnabled"
- defaultValue
- render={({ field: { value, onChange }, fieldState: { error } }) => {
- return (
- <FormControl
- helperText={`The lockout feature will prevent login attempts for ${lockoutDurationValueWatch}${lockoutDurationUnitWatch} after ${lockoutThresholdWatch} consecutive login failures. If ${lockoutCounterResetValueWatch}${lockoutCounterResetUnitWatch} pass after the most recent failure, the lockout counter resets.`}
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Switch
- className="ml-0 mr-3 bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"
- containerClassName="flex-row-reverse w-fit"
- id="lockout-enabled"
- thumbClassName="bg-mineshaft-800"
- onCheckedChange={onChange}
- isChecked={value}
- >
- Lockout
- </Switch>
- </FormControl>
- );
- }}
- />
- <div className="flex flex-col gap-2">
- <Controller
- control={control}
- name="lockoutThreshold"
- render={({ field, fieldState: { error } }) => {
- return (
- <FormControl
- className={`mb-0 flex-grow ${lockoutEnabledWatch ? "" : "opacity-70"}`}
- label="Lockout Threshold"
- isError={Boolean(error)}
- errorText={error?.message}
- tooltipText="The amount of times login must fail before locking the identity auth method"
- >
- <Input
- {...field}
- placeholder="Enter lockout threshold..."
- isDisabled={!lockoutEnabledWatch}
- />
- </FormControl>
- );
- }}
- />
- <div className="flex items-end gap-2">
- <Controller
- control={control}
- name="lockoutDurationValue"
- render={({ field, fieldState: { error } }) => {
- return (
- <FormControl
- className={`mb-0 flex-grow ${lockoutEnabledWatch ? "" : "opacity-70"}`}
- label="Lockout Duration"
- isError={Boolean(error)}
- errorText={error?.message}
- tooltipText="How long an identity auth method lockout lasts"
- >
- <Input
- {...field}
- placeholder="Enter lockout duration..."
- isDisabled={!lockoutEnabledWatch}
- />
- </FormControl>
- );
- }}
- />
- <Controller
- control={control}
- name="lockoutDurationUnit"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- className={`mb-0 ${lockoutEnabledWatch ? "" : "opacity-70"}`}
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Select
- isDisabled={!lockoutEnabledWatch}
- value={field.value}
- className="min-w-32 pr-2"
- onValueChange={field.onChange}
- position="popper"
- >
- <SelectItem
- value="s"
- className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
- >
- <div className="ml-3 font-medium">Seconds</div>
- </SelectItem>
- <SelectItem
- value="m"
- className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
- >
- <div className="ml-3 font-medium">Minutes</div>
- </SelectItem>
- <SelectItem
- value="h"
- className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
- >
- <div className="ml-3 font-medium">Hours</div>
- </SelectItem>
- <SelectItem
- value="d"
- className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
- >
- <div className="ml-3 font-medium">Days</div>
- </SelectItem>
- </Select>
- </FormControl>
- )}
- />
- </div>
- <div className="flex items-end gap-2">
- <Controller
- control={control}
- name="lockoutCounterResetValue"
- render={({ field, fieldState: { error } }) => {
- return (
- <FormControl
- className={`mb-0 flex-grow ${lockoutEnabledWatch ? "" : "opacity-70"}`}
- label="Lockout Counter Reset"
- isError={Boolean(error)}
- errorText={error?.message}
- tooltipText="How long to wait from the most recent failed login until resetting the lockout counter"
- >
- <Input
- {...field}
- placeholder="Enter lockout counter reset..."
- isDisabled={!lockoutEnabledWatch}
- />
- </FormControl>
- );
- }}
- />
- <Controller
- control={control}
- name="lockoutCounterResetUnit"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- className={`mb-0 ${lockoutEnabledWatch ? "" : "opacity-70"}`}
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Select
- isDisabled={!lockoutEnabledWatch}
- value={field.value}
- className="min-w-32 pr-2"
- onValueChange={field.onChange}
- position="popper"
- >
- <SelectItem
- value="s"
- className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
- >
- <div className="ml-3 font-medium">Seconds</div>
- </SelectItem>
- <SelectItem
- value="m"
- className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
- >
- <div className="ml-3 font-medium">Minutes</div>
- </SelectItem>
- <SelectItem
- value="h"
- className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
- >
- <div className="ml-3 font-medium">Hours</div>
- </SelectItem>
- </Select>
- </FormControl>
- )}
- />
- </div>
- </div>
- </div>
- </TabPanel>
-
+ <LockoutTab
+ control={control}
+ lockoutEnabled={lockoutEnabledWatch}
+ lockoutThreshold={lockoutThresholdWatch}
+ lockoutDurationValue={lockoutDurationValueWatch}
+ lockoutDurationUnit={lockoutDurationUnitWatch}
+ lockoutCounterResetValue={lockoutCounterResetValueWatch}
+ lockoutCounterResetUnit={lockoutCounterResetUnitWatch}
+ />
<TabPanel value={IdentityFormTab.Advanced}>
{clientSecretTrustedIpsFields.map(({ id }, index) => (
<div className="mb-3 flex items-end space-x-2" key={id}>
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/lockout/LockoutTab.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/lockout/LockoutTab.tsx
new file mode 100644
index 0000000000..3d386a20f9
--- /dev/null
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/lockout/LockoutTab.tsx
@@ -0,0 +1,205 @@
+import { Control, Controller } from "react-hook-form";
+
+import { FormControl, Input, Select, SelectItem, Switch, TabPanel } from "@app/components/v2";
+
+import { IdentityFormTab } from "../types";
+
+export const LockoutTab = ({
+ control,
+ lockoutEnabled,
+ lockoutThreshold,
+ lockoutDurationValue,
+ lockoutDurationUnit,
+ lockoutCounterResetValue,
+ lockoutCounterResetUnit
+}: {
+ control: Control<any>;
+ lockoutEnabled: boolean;
+ lockoutThreshold: string;
+ lockoutDurationValue: string;
+ lockoutDurationUnit: "s" | "m" | "h" | "d";
+ lockoutCounterResetValue: string;
+ lockoutCounterResetUnit: "s" | "m" | "h";
+}) => {
+ return (
+ <TabPanel value={IdentityFormTab.Lockout}>
+ <div className="mb-3 flex flex-col">
+ <Controller
+ control={control}
+ name="lockoutEnabled"
+ render={({ field: { value, onChange }, fieldState: { error } }) => {
+ return (
+ <FormControl
+ helperText={`The lockout feature will prevent login attempts for ${lockoutDurationValue}${lockoutDurationUnit} after ${lockoutThreshold} consecutive login failures. If ${lockoutCounterResetValue}${lockoutCounterResetUnit} pass after the most recent failure, the lockout counter resets.`}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Switch
+ className="ml-0 mr-3 bg-mineshaft-400/80 shadow-inner data-[state=checked]:bg-green/80"
+ containerClassName="flex-row-reverse w-fit"
+ id="lockout-enabled"
+ thumbClassName="bg-mineshaft-800"
+ onCheckedChange={onChange}
+ isChecked={value}
+ >
+ Lockout
+ </Switch>
+ </FormControl>
+ );
+ }}
+ />
+ <div className="flex flex-col gap-2">
+ <Controller
+ control={control}
+ name="lockoutThreshold"
+ render={({ field, fieldState: { error } }) => {
+ return (
+ <FormControl
+ className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
+ label="Lockout Threshold"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ tooltipText="The amount of times login must fail before locking the identity auth method"
+ >
+ <Input
+ {...field}
+ placeholder="Enter lockout threshold..."
+ isDisabled={!lockoutEnabled}
+ />
+ </FormControl>
+ );
+ }}
+ />
+ <div className="flex items-end gap-2">
+ <Controller
+ control={control}
+ name="lockoutDurationValue"
+ render={({ field, fieldState: { error } }) => {
+ return (
+ <FormControl
+ className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
+ label="Lockout Duration"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ tooltipText="How long an identity auth method lockout lasts"
+ >
+ <Input
+ {...field}
+ placeholder="Enter lockout duration..."
+ isDisabled={!lockoutEnabled}
+ />
+ </FormControl>
+ );
+ }}
+ />
+ <Controller
+ control={control}
+ name="lockoutDurationUnit"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className={`mb-0 ${lockoutEnabled ? "" : "opacity-70"}`}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Select
+ isDisabled={!lockoutEnabled}
+ value={field.value}
+ className="min-w-32 pr-2"
+ onValueChange={field.onChange}
+ position="popper"
+ >
+ <SelectItem
+ value="s"
+ className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
+ >
+ <div className="ml-3 font-medium">Seconds</div>
+ </SelectItem>
+ <SelectItem
+ value="m"
+ className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
+ >
+ <div className="ml-3 font-medium">Minutes</div>
+ </SelectItem>
+ <SelectItem
+ value="h"
+ className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
+ >
+ <div className="ml-3 font-medium">Hours</div>
+ </SelectItem>
+ <SelectItem
+ value="d"
+ className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
+ >
+ <div className="ml-3 font-medium">Days</div>
+ </SelectItem>
+ </Select>
+ </FormControl>
+ )}
+ />
+ </div>
+ <div className="flex items-end gap-2">
+ <Controller
+ control={control}
+ name="lockoutCounterResetValue"
+ render={({ field, fieldState: { error } }) => {
+ return (
+ <FormControl
+ className={`mb-0 flex-grow ${lockoutEnabled ? "" : "opacity-70"}`}
+ label="Lockout Counter Reset"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ tooltipText="How long to wait from the most recent failed login until resetting the lockout counter"
+ >
+ <Input
+ {...field}
+ placeholder="Enter lockout counter reset..."
+ isDisabled={!lockoutEnabled}
+ />
+ </FormControl>
+ );
+ }}
+ />
+ <Controller
+ control={control}
+ name="lockoutCounterResetUnit"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ className={`mb-0 ${lockoutEnabled ? "" : "opacity-70"}`}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ >
+ <Select
+ isDisabled={!lockoutEnabled}
+ value={field.value}
+ className="min-w-32 pr-2"
+ onValueChange={field.onChange}
+ position="popper"
+ >
+ <SelectItem
+ value="s"
+ className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
+ >
+ <div className="ml-3 font-medium">Seconds</div>
+ </SelectItem>
+ <SelectItem
+ value="m"
+ className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
+ >
+ <div className="ml-3 font-medium">Minutes</div>
+ </SelectItem>
+ <SelectItem
+ value="h"
+ className="relative py-2 pl-6 pr-8 text-sm hover:bg-mineshaft-700"
+ >
+ <div className="ml-3 font-medium">Hours</div>
+ </SelectItem>
+ </Select>
+ </FormControl>
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ </TabPanel>
+ );
+};
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/lockout/super-refine.ts b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/lockout/super-refine.ts
new file mode 100644
index 0000000000..a597f810f0
--- /dev/null
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/lockout/super-refine.ts
@@ -0,0 +1,67 @@
+import ms from "ms";
+import { z } from "zod";
+
+export function superRefineLockout(
+ data: {
+ lockoutDurationValue: string;
+ lockoutCounterResetValue: string;
+ lockoutDurationUnit: "s" | "m" | "h" | "d";
+ lockoutCounterResetUnit: "s" | "m" | "h";
+ lockoutEnabled: boolean;
+ },
+ ctx: z.RefinementCtx
+) {
+ const {
+ lockoutDurationValue,
+ lockoutCounterResetValue,
+ lockoutDurationUnit,
+ lockoutCounterResetUnit,
+ lockoutEnabled
+ } = data;
+
+ if (lockoutEnabled) {
+ let isAnyParseError = false;
+
+ const parsedLockoutDuration = parseInt(lockoutDurationValue, 10);
+ if (Number.isNaN(parsedLockoutDuration)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Lockout duration must be a number",
+ path: ["lockoutDurationValue"]
+ });
+ isAnyParseError = true;
+ }
+
+ const parsedLockoutCounterReset = parseInt(lockoutCounterResetValue, 10);
+ if (Number.isNaN(parsedLockoutCounterReset)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Lockout counter reset must be a number",
+ path: ["lockoutCounterResetValue"]
+ });
+ isAnyParseError = true;
+ }
+
+ if (!isAnyParseError) {
+ const lockoutDurationInSeconds = ms(`${parsedLockoutDuration}${lockoutDurationUnit}`) / 1000;
+ const lockoutCounterResetInSeconds =
+ ms(`${parsedLockoutCounterReset}${lockoutCounterResetUnit}`) / 1000;
+
+ if (lockoutDurationInSeconds > 86400 || lockoutDurationInSeconds < 30) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Lockout duration must be between 30 seconds and 1 day",
+ path: ["lockoutDurationValue"]
+ });
+ }
+
+ if (lockoutCounterResetInSeconds > 3600 || lockoutCounterResetInSeconds < 5) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "Lockout counter reset must be between 5 seconds and 1 hour",
+ path: ["lockoutCounterResetValue"]
+ });
+ }
+ }
+ }
+}
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
index 7f751fc7d0..c1c9f0b0af 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
@@ -21,10 +21,10 @@ import {
useAddUsersToOrg,
useFetchServerStatus,
useGetOrgRoles,
- useGetUserWorkspaces
+ useGetUserProjects
} from "@app/hooks/api";
+import { ProjectType, ProjectVersion } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { ProjectType, ProjectVersion } from "@app/hooks/api/workspace/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { OrgInviteLink } from "./OrgInviteLink";
@@ -76,7 +76,7 @@ export const AddOrgMemberModal = ({
const { data: organizationRoles } = useGetOrgRoles(currentOrg?.id ?? "");
const { data: serverDetails } = useFetchServerStatus();
const { mutateAsync: addUsersMutateAsync } = useAddUsersToOrg();
- const { data: projects, isPending: isProjectsLoading } = useGetUserWorkspaces({
+ const { data: projects, isPending: isProjectsLoading } = useGetUserProjects({
includeRoles: true
});
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/AppConnectionsPage.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/AppConnectionsPage.tsx
index ff3f31c9e3..80aefe3f27 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/AppConnectionsPage.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/AppConnectionsPage.tsx
@@ -1,24 +1,17 @@
import { Helmet } from "react-helmet";
-import { faArrowUpRightFromSquare, faBookOpen, faPlus } from "@fortawesome/free-solid-svg-icons";
+import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { OrgPermissionCan } from "@app/components/permissions";
-import { Button, PageHeader } from "@app/components/v2";
+import { PageHeader } from "@app/components/v2";
import {
OrgPermissionAppConnectionActions,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
import { withPermission } from "@app/hoc";
-import { usePopUp } from "@app/hooks";
-import {
- AddAppConnectionModal,
- AppConnectionsTable
-} from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
+import { AppConnectionsTable } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
export const AppConnectionsPage = withPermission(
() => {
- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["addConnection"] as const);
-
return (
<div className="bg-bunker-800">
<Helmet>
@@ -30,54 +23,18 @@ export const AppConnectionsPage = withPermission(
<div className="w-full max-w-7xl">
<PageHeader
className="w-full"
- title={
- <div className="flex w-full items-center">
- <span>App Connections</span>
- <a
- className="-mt-1.5"
- href="https://infisical.com/docs/integrations/app-connections/overview"
- target="_blank"
- rel="noopener noreferrer"
- >
- <div className="ml-2 inline-block rounded-md bg-yellow/20 px-1.5 text-sm font-normal text-yellow opacity-80 hover:opacity-100">
- <FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
- <span>Docs</span>
- <FontAwesomeIcon
- icon={faArrowUpRightFromSquare}
- className="mb-[0.07rem] ml-1.5 text-[10px]"
- />
- </div>
- </a>
- <OrgPermissionCan
- I={OrgPermissionAppConnectionActions.Create}
- a={OrgPermissionSubjects.AppConnections}
- >
- {(isAllowed) => (
- <Button
- colorSchema="secondary"
- type="submit"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => {
- handlePopUpOpen("addConnection");
- }}
- isDisabled={!isAllowed}
- className="ml-auto"
- >
- Add Connection
- </Button>
- )}
- </OrgPermissionCan>
- </div>
- }
- description="Create and configure connections with third-party apps for re-use across Infisical projects"
+ title="App Connections"
+ description="Manage organization App Connections"
/>
- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <AppConnectionsTable />
- <AddAppConnectionModal
- isOpen={popUp.addConnection.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("addConnection", isOpen)}
- />
+ <div className="mb-4 flex w-full flex-col rounded-md border border-blue-500/50 bg-blue-500/30 px-4 py-2 text-sm text-blue-200">
+ <div className="flex items-center">
+ <FontAwesomeIcon icon={faInfoCircle} className="mb-0.5 mr-2 text-sm" />
+ <span className="text-sm text-blue-200">
+ App connections can also be created and managed independently in projects now.
+ </span>
+ </div>
</div>
+ <AppConnectionsTable />
</div>
</div>
</div>
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AddAppConnectionModal.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AddAppConnectionModal.tsx
index c74985a3f8..c52f89dc9b 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AddAppConnectionModal.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AddAppConnectionModal.tsx
@@ -3,6 +3,7 @@ import { useState } from "react";
import { Modal, ModalContent } from "@app/components/v2";
import { TAppConnection } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { AppConnectionForm } from "./AppConnectionForm";
import { AppConnectionsSelect } from "./AppConnectionList";
@@ -10,29 +11,44 @@ import { AppConnectionsSelect } from "./AppConnectionList";
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
+ projectId?: string;
+ projectType?: ProjectType;
+ app?: AppConnection;
+ onComplete?: (appConnection: TAppConnection) => void;
};
type ContentProps = {
onComplete: (appConnection: TAppConnection) => void;
+ projectId?: string;
+ projectType?: ProjectType;
+ app?: AppConnection;
};
-const Content = ({ onComplete }: ContentProps) => {
+const Content = ({ onComplete, projectId, projectType, app }: ContentProps) => {
const [selectedApp, setSelectedApp] = useState<AppConnection | null>(null);
- if (selectedApp) {
+ if (app ?? selectedApp) {
return (
<AppConnectionForm
onComplete={onComplete}
- onBack={() => setSelectedApp(null)}
- app={selectedApp}
+ onBack={app ? undefined : () => setSelectedApp(null)}
+ app={(app ?? selectedApp)!}
+ projectId={projectId}
/>
);
}
- return <AppConnectionsSelect onSelect={setSelectedApp} />;
+ return <AppConnectionsSelect onSelect={setSelectedApp} projectType={projectType} />;
};
-export const AddAppConnectionModal = ({ isOpen, onOpenChange }: Props) => {
+export const AddAppConnectionModal = ({
+ isOpen,
+ onOpenChange,
+ projectId,
+ projectType,
+ app,
+ onComplete
+}: Props) => {
return (
<Modal isOpen={isOpen} onOpenChange={onOpenChange}>
<ModalContent
@@ -40,7 +56,15 @@ export const AddAppConnectionModal = ({ isOpen, onOpenChange }: Props) => {
title="Add Connection"
subTitle="Select a third-party app to connect to."
>
- <Content onComplete={() => onOpenChange(false)} />
+ <Content
+ projectId={projectId}
+ projectType={projectType}
+ app={app}
+ onComplete={(appConnection) => {
+ if (onComplete) onComplete(appConnection);
+ onOpenChange(false);
+ }}
+ />
</ModalContent>
</Modal>
);
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
index f1826e5aef..f82e4107d9 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
@@ -52,12 +52,15 @@ type FormProps = {
onComplete: (appConnection: TAppConnection) => void;
} & ({ appConnection: TAppConnection } | { app: AppConnection });
-type CreateFormProps = FormProps & { app: AppConnection };
+type CreateFormProps = FormProps & {
+ app: AppConnection;
+ projectId?: string;
+};
type UpdateFormProps = FormProps & {
appConnection: TAppConnection;
};
-const CreateForm = ({ app, onComplete }: CreateFormProps) => {
+const CreateForm = ({ app, onComplete, projectId }: CreateFormProps) => {
const createAppConnection = useCreateAppConnection();
const { name: appName } = APP_CONNECTION_MAP[app];
@@ -68,7 +71,10 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
>
) => {
try {
- const connection = await createAppConnection.mutateAsync(formData);
+ const connection = await createAppConnection.mutateAsync({
+ ...formData,
+ projectId
+ });
createNotification({
text: `Successfully added ${appName} Connection`,
type: "success"
@@ -88,15 +94,15 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
case AppConnection.AWS:
return <AwsConnectionForm onSubmit={onSubmit} />;
case AppConnection.GitHub:
- return <GitHubConnectionForm />;
+ return <GitHubConnectionForm projectId={projectId} />;
case AppConnection.GitHubRadar:
- return <GitHubRadarConnectionForm />;
+ return <GitHubRadarConnectionForm projectId={projectId} />;
case AppConnection.GCP:
return <GcpConnectionForm onSubmit={onSubmit} />;
case AppConnection.AzureKeyVault:
- return <AzureKeyVaultConnectionForm onSubmit={onSubmit} />;
+ return <AzureKeyVaultConnectionForm onSubmit={onSubmit} projectId={projectId} />;
case AppConnection.AzureAppConfiguration:
- return <AzureAppConfigurationConnectionForm onSubmit={onSubmit} />;
+ return <AzureAppConfigurationConnectionForm onSubmit={onSubmit} projectId={projectId} />;
case AppConnection.AzureADCS:
return <AzureADCSConnectionForm onSubmit={onSubmit} />;
case AppConnection.Databricks:
@@ -118,9 +124,9 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
case AppConnection.Camunda:
return <CamundaConnectionForm onSubmit={onSubmit} />;
case AppConnection.AzureClientSecrets:
- return <AzureClientSecretsConnectionForm onSubmit={onSubmit} />;
+ return <AzureClientSecretsConnectionForm onSubmit={onSubmit} projectId={projectId} />;
case AppConnection.AzureDevOps:
- return <AzureDevOpsConnectionForm onSubmit={onSubmit} />;
+ return <AzureDevOpsConnectionForm onSubmit={onSubmit} projectId={projectId} />;
case AppConnection.Windmill:
return <WindmillConnectionForm onSubmit={onSubmit} />;
case AppConnection.Auth0:
@@ -142,7 +148,7 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
case AppConnection.Flyio:
return <FlyioConnectionForm onSubmit={onSubmit} />;
case AppConnection.GitLab:
- return <GitLabConnectionForm onSubmit={onSubmit} />;
+ return <GitLabConnectionForm onSubmit={onSubmit} projectId={projectId} />;
case AppConnection.Cloudflare:
return <CloudflareConnectionForm onSubmit={onSubmit} />;
case AppConnection.Bitbucket:
@@ -200,16 +206,33 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
case AppConnection.AWS:
return <AwsConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
case AppConnection.GitHub:
- return <GitHubConnectionForm appConnection={appConnection} />;
+ return (
+ <GitHubConnectionForm appConnection={appConnection} projectId={appConnection.projectId} />
+ );
case AppConnection.GitHubRadar:
- return <GitHubRadarConnectionForm appConnection={appConnection} />;
+ return (
+ <GitHubRadarConnectionForm
+ appConnection={appConnection}
+ projectId={appConnection.projectId}
+ />
+ );
case AppConnection.GCP:
return <GcpConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
case AppConnection.AzureKeyVault:
- return <AzureKeyVaultConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
+ return (
+ <AzureKeyVaultConnectionForm
+ appConnection={appConnection}
+ onSubmit={onSubmit}
+ projectId={appConnection.projectId}
+ />
+ );
case AppConnection.AzureAppConfiguration:
return (
- <AzureAppConfigurationConnectionForm appConnection={appConnection} onSubmit={onSubmit} />
+ <AzureAppConfigurationConnectionForm
+ appConnection={appConnection}
+ onSubmit={onSubmit}
+ projectId={appConnection.projectId}
+ />
);
case AppConnection.AzureADCS:
return <AzureADCSConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
@@ -232,9 +255,21 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
case AppConnection.Camunda:
return <CamundaConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.AzureClientSecrets:
- return <AzureClientSecretsConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
+ return (
+ <AzureClientSecretsConnectionForm
+ appConnection={appConnection}
+ onSubmit={onSubmit}
+ projectId={appConnection.projectId}
+ />
+ );
case AppConnection.AzureDevOps:
- return <AzureDevOpsConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
+ return (
+ <AzureDevOpsConnectionForm
+ appConnection={appConnection}
+ onSubmit={onSubmit}
+ projectId={appConnection.projectId}
+ />
+ );
case AppConnection.Windmill:
return <WindmillConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Auth0:
@@ -256,7 +291,13 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
case AppConnection.Flyio:
return <FlyioConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.GitLab:
- return <GitLabConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
+ return (
+ <GitLabConnectionForm
+ onSubmit={onSubmit}
+ appConnection={appConnection}
+ projectId={appConnection.projectId}
+ />
+ );
case AppConnection.Cloudflare:
return <CloudflareConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Bitbucket:
@@ -278,12 +319,12 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
}
};
-type Props = { onBack?: () => void } & Pick<FormProps, "onComplete"> &
+type Props = { onBack?: () => void; projectId?: string } & Pick<FormProps, "onComplete"> &
(
| { app: AppConnection; appConnection?: undefined }
| { app?: undefined; appConnection: TAppConnection }
);
-export const AppConnectionForm = ({ onBack, ...props }: Props) => {
+export const AppConnectionForm = ({ onBack, projectId, ...props }: Props) => {
const { app, appConnection } = props;
return (
@@ -296,7 +337,7 @@ export const AppConnectionForm = ({ onBack, ...props }: Props) => {
{appConnection ? (
<UpdateForm {...props} appConnection={appConnection} />
) : (
- <CreateForm {...props} app={app} />
+ <CreateForm {...props} app={app} projectId={projectId} />
)}
</div>
);
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureAppConfigurationConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureAppConfigurationConnectionForm.tsx
index 433abf076d..3772478f05 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureAppConfigurationConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureAppConfigurationConnectionForm.tsx
@@ -6,7 +6,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, FormControl, Input, ModalClose, Select, SelectItem } from "@app/components/v2";
-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import {
+ APP_CONNECTION_MAP,
+ getAppConnectionMethodDetails,
+ useGetAppConnectionOauthReturnUrl
+} from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import {
AzureAppConfigurationConnectionMethod,
@@ -15,6 +19,7 @@ import {
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { AzureAppConfigurationFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
@@ -25,6 +30,7 @@ type ClientSecretForm = z.infer<typeof clientSecretSchema>;
type Props = {
appConnection?: TAzureAppConfigurationConnection;
onSubmit: (formData: ClientSecretForm) => Promise<void>;
+ projectId: string | undefined | null;
};
const baseSchema = genericAppConnectionFieldsSchema.extend({
@@ -96,7 +102,11 @@ const getDefaultValues = (appConnection?: TAzureAppConfigurationConnection): Par
return base;
};
-export const AzureAppConfigurationConnectionForm = ({ appConnection, onSubmit }: Props) => {
+export const AzureAppConfigurationConnectionForm = ({
+ appConnection,
+ onSubmit,
+ projectId
+}: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
@@ -110,6 +120,8 @@ export const AzureAppConfigurationConnectionForm = ({ appConnection, onSubmit }:
defaultValues: getDefaultValues(appConnection)
});
+ const returnUrl = useGetAppConnectionOauthReturnUrl();
+
const {
handleSubmit,
control,
@@ -128,7 +140,12 @@ export const AzureAppConfigurationConnectionForm = ({ appConnection, onSubmit }:
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"azureAppConfigurationConnectionFormData",
- JSON.stringify({ ...formData, connectionId: appConnection?.id })
+ JSON.stringify({
+ ...formData,
+ connectionId: appConnection?.id,
+ projectId,
+ returnUrl
+ } as AzureAppConfigurationFormData)
);
window.location.assign(
`https://login.microsoftonline.com/${formData.tenantId || "common"}/oauth2/v2.0/authorize?client_id=${oauthClientId}&response_type=code&redirect_uri=${window.location.origin}/organization/app-connections/azure/oauth/callback&response_mode=query&scope=https://azconfig.io/.default%20openid%20offline_access&state=${state}<:>azure-app-configuration`
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsx
index 6f70f789e3..dcfdbaa087 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureClientSecretsConnectionForm.tsx
@@ -7,7 +7,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, FormControl, Input, ModalClose, Select, SelectItem } from "@app/components/v2";
-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import {
+ APP_CONNECTION_MAP,
+ getAppConnectionMethodDetails,
+ useGetAppConnectionOauthReturnUrl
+} from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import {
AzureClientSecretsConnectionMethod,
@@ -16,6 +20,7 @@ import {
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { AzureClientSecretsFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
@@ -26,6 +31,7 @@ type ClientSecretForm = z.infer<typeof clientSecretSchema>;
type Props = {
appConnection?: TAzureClientSecretsConnection;
onSubmit: (formData: ClientSecretForm) => Promise<void>;
+ projectId: string | undefined | null;
};
const baseSchema = genericAppConnectionFieldsSchema.extend({
@@ -97,7 +103,7 @@ const getDefaultValues = (appConnection?: TAzureClientSecretsConnection): Partia
return base;
};
-export const AzureClientSecretsConnectionForm = ({ appConnection, onSubmit }: Props) => {
+export const AzureClientSecretsConnectionForm = ({ appConnection, onSubmit, projectId }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
@@ -111,6 +117,8 @@ export const AzureClientSecretsConnectionForm = ({ appConnection, onSubmit }: Pr
defaultValues: getDefaultValues(appConnection)
});
+ const returnUrl = useGetAppConnectionOauthReturnUrl();
+
const {
handleSubmit,
control,
@@ -129,7 +137,12 @@ export const AzureClientSecretsConnectionForm = ({ appConnection, onSubmit }: Pr
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"azureClientSecretsConnectionFormData",
- JSON.stringify({ ...formData, connectionId: appConnection?.id })
+ JSON.stringify({
+ ...formData,
+ connectionId: appConnection?.id,
+ projectId,
+ returnUrl
+ } as AzureClientSecretsFormData)
);
window.location.assign(
`https://login.microsoftonline.com/${formData.tenantId || "common"}/oauth2/v2.0/authorize?client_id=${oauthClientId}&response_type=code&redirect_uri=${window.location.origin}/organization/app-connections/azure/oauth/callback&response_mode=query&scope=https://graph.microsoft.com/.default%20openid%20offline_access&state=${state}<:>azure-client-secrets`
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureDevOpsConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureDevOpsConnectionForm.tsx
index c4511a0dab..7d2a4ce7d2 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureDevOpsConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureDevOpsConnectionForm.tsx
@@ -7,7 +7,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, FormControl, Input, ModalClose, Select, SelectItem } from "@app/components/v2";
-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import {
+ APP_CONNECTION_MAP,
+ getAppConnectionMethodDetails,
+ useGetAppConnectionOauthReturnUrl
+} from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import {
AzureDevOpsConnectionMethod,
@@ -16,6 +20,7 @@ import {
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { AzureDevOpsFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
@@ -65,6 +70,7 @@ type OnSubmitForm = z.infer<typeof accessTokenSchema> | z.infer<typeof clientSec
type Props = {
appConnection?: TAzureDevOpsConnection;
onSubmit: (formData: OnSubmitForm) => Promise<void>;
+ projectId: string | undefined | null;
};
const getDefaultValues = (appConnection?: TAzureDevOpsConnection): Partial<FormData> => {
@@ -132,7 +138,7 @@ const getDefaultValues = (appConnection?: TAzureDevOpsConnection): Partial<FormD
return base;
};
-export const AzureDevOpsConnectionForm = ({ appConnection, onSubmit }: Props) => {
+export const AzureDevOpsConnectionForm = ({ appConnection, onSubmit, projectId }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
@@ -146,6 +152,8 @@ export const AzureDevOpsConnectionForm = ({ appConnection, onSubmit }: Props) =>
defaultValues: getDefaultValues(appConnection)
});
+ const returnUrl = useGetAppConnectionOauthReturnUrl();
+
const {
handleSubmit,
control,
@@ -164,7 +172,12 @@ export const AzureDevOpsConnectionForm = ({ appConnection, onSubmit }: Props) =>
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"azureDevOpsConnectionFormData",
- JSON.stringify({ ...formData, connectionId: appConnection?.id })
+ JSON.stringify({
+ ...formData,
+ connectionId: appConnection?.id,
+ projectId,
+ returnUrl
+ } as AzureDevOpsFormData)
);
window.location.assign(
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx
index ed99fda016..8c0f00acfa 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AzureKeyVaultConnectionForm.tsx
@@ -6,7 +6,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, FormControl, Input, ModalClose, Select, SelectItem } from "@app/components/v2";
-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import {
+ APP_CONNECTION_MAP,
+ getAppConnectionMethodDetails,
+ useGetAppConnectionOauthReturnUrl
+} from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import { useGetAppConnectionOption } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
@@ -15,6 +19,7 @@ import {
TAzureKeyVaultConnection
} from "@app/hooks/api/appConnections/types/azure-key-vault-connection";
+import { AzureKeyVaultFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
@@ -25,6 +30,7 @@ type ClientSecretForm = z.infer<typeof clientSecretSchema>;
type Props = {
appConnection?: TAzureKeyVaultConnection;
onSubmit: (formData: ClientSecretForm) => Promise<void>;
+ projectId: string | undefined | null;
};
const baseSchema = genericAppConnectionFieldsSchema.extend({
@@ -96,7 +102,7 @@ const getDefaultValues = (appConnection?: TAzureKeyVaultConnection): Partial<For
return base;
};
-export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit }: Props) => {
+export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit, projectId }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
@@ -110,6 +116,8 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit }: Props)
defaultValues: getDefaultValues(appConnection)
});
+ const returnUrl = useGetAppConnectionOauthReturnUrl();
+
const {
handleSubmit,
control,
@@ -129,7 +137,12 @@ export const AzureKeyVaultConnectionForm = ({ appConnection, onSubmit }: Props)
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"azureKeyVaultConnectionFormData",
- JSON.stringify({ ...formData, connectionId: appConnection?.id })
+ JSON.stringify({
+ ...formData,
+ connectionId: appConnection?.id,
+ projectId,
+ returnUrl
+ } as AzureKeyVaultFormData)
);
window.location.assign(
`https://login.microsoftonline.com/${formData.tenantId || "common"}/oauth2/v2.0/authorize?client_id=${oauthClientId}&response_type=code&redirect_uri=${window.location.origin}/organization/app-connections/azure/oauth/callback&response_mode=query&scope=https://vault.azure.net/.default%20openid%20offline_access&state=${state}<:>azure-key-vault`
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
index 5c9a5bcd3c..c69f662c69 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubConnectionForm.tsx
@@ -25,7 +25,11 @@ import {
OrgGatewayPermissionActions,
OrgPermissionSubjects
} from "@app/context/OrgPermissionContext/types";
-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import {
+ APP_CONNECTION_MAP,
+ getAppConnectionMethodDetails,
+ useGetAppConnectionOauthReturnUrl
+} from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import { gatewaysQueryKeys } from "@app/hooks/api";
import {
@@ -35,6 +39,7 @@ import {
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { GithubFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
@@ -42,6 +47,7 @@ import {
type Props = {
appConnection?: TGitHubConnection;
+ projectId: string | undefined | null;
};
const formSchema = genericAppConnectionFieldsSchema.extend({
@@ -63,7 +69,7 @@ const formSchema = genericAppConnectionFieldsSchema.extend({
type FormData = z.infer<typeof formSchema>;
-export const GitHubConnectionForm = ({ appConnection }: Props) => {
+export const GitHubConnectionForm = ({ appConnection, projectId }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
@@ -98,13 +104,21 @@ export const GitHubConnectionForm = ({ appConnection }: Props) => {
const selectedMethod = watch("method");
const instanceType = watch("credentials.instanceType");
+ const returnUrl = useGetAppConnectionOauthReturnUrl();
+
const onSubmit = (formData: FormData) => {
setIsRedirecting(true);
const state = crypto.randomBytes(16).toString("hex");
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"githubConnectionFormData",
- JSON.stringify({ ...formData, connectionId: appConnection?.id })
+ JSON.stringify({
+ ...formData,
+ credentials: formData.credentials as TGitHubConnection["credentials"],
+ connectionId: appConnection?.id,
+ projectId,
+ returnUrl
+ } as GithubFormData)
);
const githubHost =
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubRadarConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubRadarConnectionForm.tsx
index f9c39a5028..446eeb4cc0 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubRadarConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitHubRadarConnectionForm.tsx
@@ -6,7 +6,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, FormControl, ModalClose, Select, SelectItem } from "@app/components/v2";
-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import {
+ APP_CONNECTION_MAP,
+ getAppConnectionMethodDetails,
+ useGetAppConnectionOauthReturnUrl
+} from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import {
GitHubRadarConnectionMethod,
@@ -15,6 +19,7 @@ import {
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { GithubRadarFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
@@ -22,6 +27,7 @@ import {
type Props = {
appConnection?: TGitHubRadarConnection;
+ projectId: string | undefined | null;
};
const formSchema = genericAppConnectionFieldsSchema.extend({
@@ -31,7 +37,7 @@ const formSchema = genericAppConnectionFieldsSchema.extend({
type FormData = z.infer<typeof formSchema>;
-export const GitHubRadarConnectionForm = ({ appConnection }: Props) => {
+export const GitHubRadarConnectionForm = ({ appConnection, projectId }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
@@ -48,6 +54,8 @@ export const GitHubRadarConnectionForm = ({ appConnection }: Props) => {
}
});
+ const returnUrl = useGetAppConnectionOauthReturnUrl();
+
const {
handleSubmit,
control,
@@ -63,7 +71,12 @@ export const GitHubRadarConnectionForm = ({ appConnection }: Props) => {
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"githubRadarConnectionFormData",
- JSON.stringify({ ...formData, connectionId: appConnection?.id })
+ JSON.stringify({
+ ...formData,
+ connectionId: appConnection?.id,
+ projectId,
+ returnUrl
+ } as GithubRadarFormData)
);
switch (formData.method) {
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitLabConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitLabConnectionForm.tsx
index 8cbc2c54c5..ed4e022c4d 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitLabConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/GitLabConnectionForm.tsx
@@ -16,7 +16,11 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import {
+ APP_CONNECTION_MAP,
+ getAppConnectionMethodDetails,
+ useGetAppConnectionOauthReturnUrl
+} from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import { useGetAppConnectionOption } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
@@ -26,6 +30,7 @@ import {
TGitLabConnection
} from "@app/hooks/api/appConnections/types/gitlab-connection";
+import { GitLabFormData } from "../../../OauthCallbackPage/OauthCallbackPage.types";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
@@ -34,6 +39,7 @@ import {
type Props = {
appConnection?: TGitLabConnection;
onSubmit: (formData: FormData) => Promise<void>;
+ projectId: string | undefined | null;
};
const formSchema = z.discriminatedUnion("method", [
@@ -72,7 +78,7 @@ const formSchema = z.discriminatedUnion("method", [
type FormData = z.infer<typeof formSchema>;
-export const GitLabConnectionForm = ({ appConnection, onSubmit: formSubmit }: Props) => {
+export const GitLabConnectionForm = ({ appConnection, onSubmit: formSubmit, projectId }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
@@ -98,6 +104,8 @@ export const GitLabConnectionForm = ({ appConnection, onSubmit: formSubmit }: Pr
} as FormData))
});
+ const returnUrl = useGetAppConnectionOauthReturnUrl();
+
const {
handleSubmit,
control,
@@ -132,8 +140,10 @@ export const GitLabConnectionForm = ({ appConnection, onSubmit: formSubmit }: Pr
JSON.stringify({
...formData,
connectionId: appConnection?.id,
- isUpdate
- })
+ isUpdate,
+ projectId,
+ returnUrl
+ } as GitLabFormData)
);
// Redirect to Gitlab OAuth
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx
index 2087ebf633..0137d5a9e0 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionList.tsx
@@ -9,14 +9,16 @@ import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
import { usePagination, usePopUp, useResetPageHelper } from "@app/hooks";
import { useAppConnectionOptions } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { ProjectType } from "@app/hooks/api/projects/types";
type Props = {
onSelect: (app: AppConnection) => void;
+ projectType?: ProjectType;
};
-export const AppConnectionsSelect = ({ onSelect }: Props) => {
+export const AppConnectionsSelect = ({ onSelect, projectType }: Props) => {
const { subscription } = useSubscription();
- const { isPending, data: appConnectionOptions } = useAppConnectionOptions();
+ const { isPending, data: appConnectionOptions } = useAppConnectionOptions(projectType);
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx
index fb7f880c49..941a90db49 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionRow.tsx
@@ -1,19 +1,23 @@
import { useCallback } from "react";
+import { subject } from "@casl/ability";
import {
faAsterisk,
+ faBuilding,
faCheck,
faCopy,
faEdit,
faEllipsisV,
faInfoCircle,
faServer,
+ faTable,
faTrash
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Link } from "@tanstack/react-router";
import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
-import { OrgPermissionCan } from "@app/components/permissions";
+import { VariablePermissionCan } from "@app/components/permissions";
import {
Badge,
DropdownMenu,
@@ -25,9 +29,11 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { OrgPermissionSubjects } from "@app/context";
+import { OrgPermissionSubjects, ProjectPermissionSub } from "@app/context";
import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";
+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import { getProjectBaseURL } from "@app/helpers/project";
import { useToggle } from "@app/hooks";
import { TAppConnection } from "@app/hooks/api/appConnections";
@@ -36,15 +42,18 @@ type Props = {
onDelete: (appConnection: TAppConnection) => void;
onEditCredentials: (appConnection: TAppConnection) => void;
onEditDetails: (appConnection: TAppConnection) => void;
+ isProjectView: boolean;
};
export const AppConnectionRow = ({
appConnection,
onDelete,
onEditCredentials,
- onEditDetails
+ onEditDetails,
+ isProjectView
}: Props) => {
- const { id, name, method, app, description, isPlatformManagedCredentials } = appConnection;
+ const { id, name, method, app, description, isPlatformManagedCredentials, project } =
+ appConnection;
const [isIdCopied, setIsIdCopied] = useToggle(false);
@@ -111,7 +120,38 @@ export const AppConnectionRow = ({
{methodDetails.name}
</p>
</Td>
-
+ {!isProjectView && (
+ <Td className="!min-w-[8rem] max-w-0">
+ {project ? (
+ <Link
+ // @ts-expect-error app-connections aren't in kms/ssh
+ to={`${getProjectBaseURL(project.type)}/app-connections`}
+ params={{
+ projectId: project.id
+ }}
+ className="underline"
+ >
+ <p className="truncate">
+ <FontAwesomeIcon
+ size="sm"
+ className="mr-1.5 text-mineshaft-300/75"
+ icon={faTable}
+ />
+ {project.name}
+ </p>
+ </Link>
+ ) : (
+ <p className="truncate">
+ <FontAwesomeIcon
+ size="sm"
+ className="mr-1.5 text-mineshaft-300/75"
+ icon={faBuilding}
+ />
+ Organization
+ </p>
+ )}
+ </Td>
+ )}
<Td>
<div className="flex items-center justify-end gap-2">
{isPlatformManagedCredentials && (
@@ -143,48 +183,91 @@ export const AppConnectionRow = ({
>
Copy Connection ID
</DropdownMenuItem>
- <OrgPermissionCan
- I={OrgPermissionAppConnectionActions.Edit}
- a={OrgPermissionSubjects.AppConnections}
- >
- {(isAllowed: boolean) => (
- <DropdownMenuItem
- isDisabled={!isAllowed}
- icon={<FontAwesomeIcon icon={faEdit} />}
- onClick={() => onEditDetails(appConnection)}
+ {(isProjectView || !project) && (
+ <>
+ <VariablePermissionCan
+ type={isProjectView ? "project" : "org"}
+ I={
+ isProjectView
+ ? ProjectPermissionAppConnectionActions.Edit
+ : OrgPermissionAppConnectionActions.Edit
+ }
+ a={
+ isProjectView
+ ? subject(ProjectPermissionSub.AppConnections, {
+ connectionId: id
+ })
+ : subject(OrgPermissionSubjects.AppConnections, {
+ connectionId: id
+ })
+ }
>
- Edit Details
- </DropdownMenuItem>
- )}
- </OrgPermissionCan>
- <OrgPermissionCan
- I={OrgPermissionAppConnectionActions.Edit}
- a={OrgPermissionSubjects.AppConnections}
- >
- {(isAllowed: boolean) => (
- <DropdownMenuItem
- isDisabled={!isAllowed}
- icon={<FontAwesomeIcon icon={faAsterisk} />}
- onClick={() => onEditCredentials(appConnection)}
+ {(isAllowed: boolean) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed}
+ icon={<FontAwesomeIcon icon={faEdit} />}
+ onClick={() => onEditDetails(appConnection)}
+ >
+ Edit Details
+ </DropdownMenuItem>
+ )}
+ </VariablePermissionCan>
+ <VariablePermissionCan
+ type={isProjectView ? "project" : "org"}
+ I={
+ isProjectView
+ ? ProjectPermissionAppConnectionActions.Edit
+ : OrgPermissionAppConnectionActions.Edit
+ }
+ a={
+ isProjectView
+ ? subject(ProjectPermissionSub.AppConnections, {
+ connectionId: id
+ })
+ : subject(OrgPermissionSubjects.AppConnections, {
+ connectionId: id
+ })
+ }
>
- {isPlatformManagedCredentials ? "View" : "Edit"} Credentials
- </DropdownMenuItem>
- )}
- </OrgPermissionCan>
- <OrgPermissionCan
- I={OrgPermissionAppConnectionActions.Delete}
- a={OrgPermissionSubjects.AppConnections}
- >
- {(isAllowed: boolean) => (
- <DropdownMenuItem
- isDisabled={!isAllowed}
- icon={<FontAwesomeIcon icon={faTrash} />}
- onClick={() => onDelete(appConnection)}
+ {(isAllowed: boolean) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed}
+ icon={<FontAwesomeIcon icon={faAsterisk} />}
+ onClick={() => onEditCredentials(appConnection)}
+ >
+ {isPlatformManagedCredentials ? "View" : "Edit"} Credentials
+ </DropdownMenuItem>
+ )}
+ </VariablePermissionCan>
+ <VariablePermissionCan
+ type={isProjectView ? "project" : "org"}
+ I={
+ isProjectView
+ ? ProjectPermissionAppConnectionActions.Delete
+ : OrgPermissionAppConnectionActions.Delete
+ }
+ a={
+ isProjectView
+ ? subject(ProjectPermissionSub.AppConnections, {
+ connectionId: id
+ })
+ : subject(OrgPermissionSubjects.AppConnections, {
+ connectionId: id
+ })
+ }
>
- Delete Connection
- </DropdownMenuItem>
- )}
- </OrgPermissionCan>
+ {(isAllowed: boolean) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed}
+ icon={<FontAwesomeIcon icon={faTrash} />}
+ onClick={() => onDelete(appConnection)}
+ >
+ Delete Connection
+ </DropdownMenuItem>
+ )}
+ </VariablePermissionCan>
+ </>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</Tooltip>
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx
index bc448663a3..91ad35d4a3 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionsTable.tsx
@@ -2,16 +2,21 @@ import { useMemo, useState } from "react";
import {
faArrowDown,
faArrowUp,
+ faArrowUpRightFromSquare,
+ faBookOpen,
faCheckCircle,
faFilter,
faMagnifyingGlass,
faPlug,
+ faPlus,
faSearch
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { twMerge } from "tailwind-merge";
+import { VariablePermissionCan } from "@app/components/permissions";
import {
+ Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -29,6 +34,9 @@ import {
THead,
Tr
} from "@app/components/v2";
+import { OrgPermissionSubjects, ProjectPermissionSub } from "@app/context";
+import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";
+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
import {
getUserTablePreference,
@@ -39,7 +47,9 @@ import { usePagination, usePopUp, useResetPageHelper } from "@app/hooks";
import { TAppConnection, useListAppConnections } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
+import { AddAppConnectionModal } from "./AddAppConnectionModal";
import { AppConnectionRow } from "./AppConnectionRow";
import { DeleteAppConnectionModal } from "./DeleteAppConnectionModal";
import { EditAppConnectionCredentialsModal } from "./EditAppConnectionCredentialsModal";
@@ -48,22 +58,45 @@ import { EditAppConnectionDetailsModal } from "./EditAppConnectionDetailsModal";
enum AppConnectionsOrderBy {
App = "app",
Name = "name",
- Method = "method"
+ Method = "method",
+ ManagedBy = "managed-by"
}
type AppConnectionFilters = {
apps: AppConnection[];
};
-export const AppConnectionsTable = () => {
- const { isPending, data: appConnections = [] } = useListAppConnections();
+enum View {
+ All = "all",
+ Scope = "scope"
+}
+
+const APP_CONNECTION_VIEW_STORAGE_KEY = "app-connection-view";
+
+type Props = {
+ projectId?: string;
+ projectType?: ProjectType;
+};
+
+export const AppConnectionsTable = ({ projectId, projectType }: Props) => {
+ const isProjectView = Boolean(projectId);
+ const { isPending, data: appConnections = [] } = useListAppConnections(projectId);
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([
+ "addConnection",
"deleteConnection",
"editCredentials",
"editDetails"
] as const);
+ const [view, setView] = useState<View>(() => {
+ const storedView = localStorage.getItem(APP_CONNECTION_VIEW_STORAGE_KEY) as View | null;
+
+ if (storedView && Object.values(View).includes(storedView)) return storedView;
+
+ return View.Scope;
+ });
+
const [filters, setFilters] = useState<AppConnectionFilters>({
apps: []
});
@@ -96,6 +129,10 @@ export const AppConnectionsTable = () => {
.filter((appConnection) => {
const { app, method, name } = appConnection;
+ if (view === View.Scope && !isProjectView && appConnection.projectId) {
+ return false;
+ }
+
if (filters.apps.length && !filters.apps.includes(app)) return false;
const searchValue = search.trim().toLowerCase();
@@ -121,6 +158,13 @@ export const AppConnectionsTable = () => {
.localeCompare(
getAppConnectionMethodDetails(connectionTwo.method).name.toLowerCase()
);
+ case AppConnectionsOrderBy.ManagedBy:
+ if (!connectionOne.project) return 1;
+ if (!connectionTwo.project) return -1;
+
+ return connectionOne.project.name
+ .toLowerCase()
+ .localeCompare(connectionTwo.project.name.toLowerCase());
case AppConnectionsOrderBy.App:
default:
return APP_CONNECTION_MAP[connectionOne.app].name
@@ -128,7 +172,7 @@ export const AppConnectionsTable = () => {
.localeCompare(APP_CONNECTION_MAP[connectionTwo.app].name.toLowerCase());
}
}),
- [appConnections, orderDirection, search, orderBy, filters]
+ [appConnections, orderDirection, search, orderBy, filters, view]
);
useResetPageHelper({
@@ -165,8 +209,87 @@ export const AppConnectionsTable = () => {
handlePopUpOpen("editDetails", appConnection);
return (
- <div>
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <div className="mb-4 flex items-center justify-between">
+ <div>
+ <div className="flex items-center gap-1">
+ <p className="text-xl font-semibold text-mineshaft-100">App Connections</p>
+ <a
+ href="https://infisical.com/docs/integrations/app-connections/overview"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <div className="ml-1 mt-[0.12rem] inline-block rounded-md bg-yellow/20 px-1.5 text-sm text-yellow opacity-80 hover:opacity-100">
+ <FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
+ <span>Docs</span>
+ <FontAwesomeIcon
+ icon={faArrowUpRightFromSquare}
+ className="mb-[0.07rem] ml-1.5 text-[10px]"
+ />
+ </div>
+ </a>
+ </div>
+ <p className="text-sm text-bunker-300">
+ Create and configure connections with third-party apps for re-use across your project
+ {isProjectView ? "" : "s"}.
+ </p>
+ </div>
+ <VariablePermissionCan
+ type={isProjectView ? "project" : "org"}
+ I={
+ isProjectView
+ ? ProjectPermissionAppConnectionActions.Create
+ : OrgPermissionAppConnectionActions.Create
+ }
+ a={
+ isProjectView
+ ? ProjectPermissionSub.AppConnections
+ : OrgPermissionSubjects.AppConnections
+ }
+ >
+ {(isAllowed) => (
+ <Button
+ colorSchema="secondary"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => handlePopUpOpen("addConnection")}
+ isDisabled={!isAllowed}
+ >
+ Add Connection
+ </Button>
+ )}
+ </VariablePermissionCan>
+ </div>
<div className="flex gap-2">
+ {!isProjectView && (
+ <div className="flex gap-x-0.5 rounded-md border border-mineshaft-600 bg-mineshaft-800 p-1">
+ <Button
+ variant="outline_bg"
+ onClick={() => {
+ setView(View.Scope);
+ localStorage.setItem(APP_CONNECTION_VIEW_STORAGE_KEY, View.Scope);
+ }}
+ size="xs"
+ className={`${
+ view === View.Scope ? "bg-mineshaft-500" : "bg-transparent"
+ } min-w-[5rem] rounded border-none hover:bg-mineshaft-600`}
+ >
+ Organization
+ </Button>
+ <Button
+ variant="outline_bg"
+ onClick={() => {
+ setView(View.All);
+ localStorage.setItem(APP_CONNECTION_VIEW_STORAGE_KEY, View.All);
+ }}
+ size="xs"
+ className={`${
+ view === View.All ? "bg-mineshaft-500" : "bg-transparent"
+ } min-w-[5rem] rounded border-none hover:bg-mineshaft-600`}
+ >
+ All
+ </Button>
+ </div>
+ )}
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
@@ -188,38 +311,46 @@ export const AppConnectionsTable = () => {
<FontAwesomeIcon icon={faFilter} />
</IconButton>
</DropdownMenuTrigger>
- <DropdownMenuContent className="thin-scrollbar max-h-[70vh] overflow-y-auto" align="end">
+ <DropdownMenuContent
+ sideOffset={2}
+ className="thin-scrollbar max-h-[70vh] overflow-y-auto"
+ align="end"
+ >
<DropdownMenuLabel>Filter by Apps</DropdownMenuLabel>
{appConnections.length ? (
- [...new Set(appConnections.map(({ app }) => app))].map((app) => (
- <DropdownMenuItem
- onClick={(e) => {
- e.preventDefault();
- setFilters((prev) => ({
- ...prev,
- apps: prev.apps.includes(app)
- ? prev.apps.filter((a) => a !== app)
- : [...prev.apps, app]
- }));
- }}
- key={app}
- icon={
- filters.apps.includes(app) && (
- <FontAwesomeIcon className="text-primary" icon={faCheckCircle} />
- )
- }
- iconPos="right"
- >
- <div className="flex items-center gap-2">
- <img
- alt={`${APP_CONNECTION_MAP[app].name} integration`}
- src={`/images/integrations/${APP_CONNECTION_MAP[app].image}`}
- className="h-4 w-4"
- />
- <span>{APP_CONNECTION_MAP[app].name}</span>
- </div>
- </DropdownMenuItem>
- ))
+ [...new Set(appConnections.map(({ app }) => app))]
+ .sort((a, b) => {
+ return a.toLowerCase().localeCompare(b.toLowerCase());
+ })
+ .map((app) => (
+ <DropdownMenuItem
+ onClick={(e) => {
+ e.preventDefault();
+ setFilters((prev) => ({
+ ...prev,
+ apps: prev.apps.includes(app)
+ ? prev.apps.filter((a) => a !== app)
+ : [...prev.apps, app]
+ }));
+ }}
+ key={app}
+ icon={
+ filters.apps.includes(app) && (
+ <FontAwesomeIcon className="text-primary" icon={faCheckCircle} />
+ )
+ }
+ iconPos="right"
+ >
+ <div className="flex items-center gap-2">
+ <img
+ alt={`${APP_CONNECTION_MAP[app].name} integration`}
+ src={`/images/integrations/${APP_CONNECTION_MAP[app].image}`}
+ className="h-4 w-4"
+ />
+ <span>{APP_CONNECTION_MAP[app].name}</span>
+ </div>
+ </DropdownMenuItem>
+ ))
) : (
<DropdownMenuItem isDisabled>No Connections Configured</DropdownMenuItem>
)}
@@ -269,7 +400,21 @@ export const AppConnectionsTable = () => {
</IconButton>
</div>
</Th>
-
+ {!isProjectView && (
+ <Th>
+ <div className="flex items-center">
+ Managed By
+ <IconButton
+ variant="plain"
+ className={getClassName(AppConnectionsOrderBy.ManagedBy)}
+ ariaLabel="sort"
+ onClick={() => handleSort(AppConnectionsOrderBy.ManagedBy)}
+ >
+ <FontAwesomeIcon icon={getColSortIcon(AppConnectionsOrderBy.ManagedBy)} />
+ </IconButton>
+ </div>
+ </Th>
+ )}
<Th className="w-5" />
</Tr>
</THead>
@@ -284,6 +429,7 @@ export const AppConnectionsTable = () => {
onDelete={handleDelete}
onEditCredentials={handleEditCredentials}
onEditDetails={handleEditDetails}
+ isProjectView={isProjectView}
/>
))}
</TBody>
@@ -323,6 +469,12 @@ export const AppConnectionsTable = () => {
onOpenChange={(isOpen) => handlePopUpToggle("editDetails", isOpen)}
appConnection={popUp.editDetails.data}
/>
+ <AddAppConnectionModal
+ isOpen={popUp.addConnection.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("addConnection", isOpen)}
+ projectId={projectId}
+ projectType={projectType}
+ />
</div>
);
};
diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
index 2798a71212..f5f6d2c88e 100644
--- a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.tsx
@@ -12,73 +12,14 @@ import {
AzureKeyVaultConnectionMethod,
GitHubConnectionMethod,
GitLabConnectionMethod,
- TAzureAppConfigurationConnection,
- TAzureClientSecretsConnection,
- TAzureDevOpsConnection,
- TAzureKeyVaultConnection,
- TGitHubConnection,
- TGitHubRadarConnection,
- TGitLabConnection,
+ TAppConnection,
useCreateAppConnection,
useUpdateAppConnection
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { IntegrationsListPageTabs } from "@app/types/integrations";
-type BaseFormData = {
- returnUrl?: string;
- connectionId?: string;
- isUpdate?: boolean;
-};
-
-type GithubFormData = BaseFormData &
- Pick<TGitHubConnection, "name" | "method" | "description" | "gatewayId" | "credentials">;
-
-type GithubRadarFormData = BaseFormData &
- Pick<TGitHubRadarConnection, "name" | "method" | "description">;
-
-type GitLabFormData = BaseFormData &
- Pick<TGitLabConnection, "name" | "method" | "description" | "credentials">;
-
-type AzureKeyVaultFormData = BaseFormData &
- Pick<TAzureKeyVaultConnection, "name" | "method" | "description"> &
- Pick<TAzureKeyVaultConnection["credentials"], "tenantId">;
-
-type AzureAppConfigurationFormData = BaseFormData &
- Pick<TAzureAppConfigurationConnection, "name" | "method" | "description"> &
- Pick<TAzureAppConfigurationConnection["credentials"], "tenantId">;
-
-type AzureClientSecretsFormData = BaseFormData &
- Pick<TAzureClientSecretsConnection, "name" | "method" | "description"> &
- Pick<TAzureClientSecretsConnection["credentials"], "tenantId">;
-
-type OAuthCredentials = Extract<
- TAzureDevOpsConnection,
- { method: AzureDevOpsConnectionMethod.OAuth }
->["credentials"];
-type AccessTokenCredentials = Extract<
- TAzureDevOpsConnection,
- { method: AzureDevOpsConnectionMethod.AccessToken }
->["credentials"];
-
-type AzureDevOpsFormData = BaseFormData &
- Pick<TAzureDevOpsConnection, "name" | "method" | "description"> &
- (Pick<OAuthCredentials, "tenantId" | "orgName"> | Pick<AccessTokenCredentials, "orgName">);
-
-type FormDataMap = {
- [AppConnection.GitHub]: GithubFormData & { app: AppConnection.GitHub };
- [AppConnection.GitHubRadar]: GithubRadarFormData & { app: AppConnection.GitHubRadar };
- [AppConnection.GitLab]: GitLabFormData & { app: AppConnection.GitLab };
- [AppConnection.AzureKeyVault]: AzureKeyVaultFormData & { app: AppConnection.AzureKeyVault };
- [AppConnection.AzureAppConfiguration]: AzureAppConfigurationFormData & {
- app: AppConnection.AzureAppConfiguration;
- };
- [AppConnection.AzureClientSecrets]: AzureClientSecretsFormData & {
- app: AppConnection.AzureClientSecrets;
- };
- [AppConnection.AzureDevOps]: AzureDevOpsFormData & {
- app: AppConnection.AzureDevOps;
- };
-};
+import { FormDataMap } from "./OauthCallbackPage.types";
const formDataStorageFieldMap: Partial<Record<AppConnection, string>> = {
[AppConnection.GitHub]: "githubConnectionFormData",
@@ -148,11 +89,14 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.GitLab);
- const { connectionId, name, description, returnUrl, isUpdate, credentials } = formData;
+ const { connectionId, name, description, returnUrl, isUpdate, projectId, credentials } =
+ formData;
+
+ let connection: TAppConnection;
try {
if (isUpdate && connectionId) {
- await updateAppConnection.mutateAsync({
+ connection = await updateAppConnection.mutateAsync({
app: AppConnection.GitLab,
connectionId,
credentials: {
@@ -161,10 +105,11 @@ export const OAuthCallbackPage = () => {
}
});
} else {
- await createAppConnection.mutateAsync({
+ connection = await createAppConnection.mutateAsync({
app: AppConnection.GitLab,
name,
description,
+ projectId,
method: GitLabConnectionMethod.OAuth,
credentials: {
code: code as string,
@@ -173,14 +118,12 @@ export const OAuthCallbackPage = () => {
});
}
- navigate({
- to: returnUrl ?? "/organization/app-connections"
- });
-
return {
connectionId,
returnUrl,
- appConnectionName: formData.app
+ appConnectionName: formData.app,
+ projectId,
+ connection
};
} catch (err: any) {
createNotification({
@@ -189,7 +132,10 @@ export const OAuthCallbackPage = () => {
type: "error"
});
navigate({
- to: returnUrl ?? "/organization/app-connections"
+ to: returnUrl,
+ params: {
+ projectId
+ }
});
return null;
}
@@ -201,11 +147,13 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.AzureKeyVault);
- const { connectionId, name, description, returnUrl } = formData;
+ const { connectionId, name, description, returnUrl, projectId } = formData;
+
+ let connection: TAppConnection;
try {
if (connectionId) {
- await updateAppConnection.mutateAsync({
+ connection = await updateAppConnection.mutateAsync({
app: AppConnection.AzureKeyVault,
connectionId,
credentials: {
@@ -214,10 +162,11 @@ export const OAuthCallbackPage = () => {
}
});
} else {
- await createAppConnection.mutateAsync({
+ connection = await createAppConnection.mutateAsync({
app: AppConnection.AzureKeyVault,
name,
description,
+ projectId,
method: AzureKeyVaultConnectionMethod.OAuth,
credentials: {
tenantId: formData.tenantId,
@@ -232,14 +181,20 @@ export const OAuthCallbackPage = () => {
type: "error"
});
navigate({
- to: returnUrl ?? "/organization/app-connections"
+ to: returnUrl,
+ params: {
+ projectId
+ }
});
+ return null;
}
return {
connectionId,
returnUrl,
- appConnectionName: formData.app
+ appConnectionName: formData.app,
+ projectId,
+ connection
};
}, []);
@@ -249,11 +204,13 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.AzureAppConfiguration);
- const { connectionId, name, description, returnUrl } = formData;
+ const { connectionId, name, description, returnUrl, projectId } = formData;
+
+ let connection: TAppConnection;
try {
if (connectionId) {
- await updateAppConnection.mutateAsync({
+ connection = await updateAppConnection.mutateAsync({
app: AppConnection.AzureAppConfiguration,
connectionId,
credentials: {
@@ -262,10 +219,11 @@ export const OAuthCallbackPage = () => {
}
});
} else {
- await createAppConnection.mutateAsync({
+ connection = await createAppConnection.mutateAsync({
app: AppConnection.AzureAppConfiguration,
name,
description,
+ projectId,
method: AzureAppConfigurationConnectionMethod.OAuth,
credentials: {
code: code as string,
@@ -280,14 +238,20 @@ export const OAuthCallbackPage = () => {
type: "error"
});
navigate({
- to: returnUrl ?? "/organization/app-connections"
+ to: returnUrl,
+ params: {
+ projectId
+ }
});
+ return null;
}
return {
connectionId,
returnUrl,
- appConnectionName: formData.app
+ appConnectionName: formData.app,
+ projectId,
+ connection
};
}, []);
@@ -297,11 +261,13 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.AzureClientSecrets);
- const { connectionId, name, description, returnUrl } = formData;
+ const { connectionId, name, description, returnUrl, projectId } = formData;
+
+ let connection: TAppConnection;
try {
if (connectionId) {
- await updateAppConnection.mutateAsync({
+ connection = await updateAppConnection.mutateAsync({
app: AppConnection.AzureClientSecrets,
connectionId,
credentials: {
@@ -310,11 +276,12 @@ export const OAuthCallbackPage = () => {
}
});
} else {
- await createAppConnection.mutateAsync({
+ connection = await createAppConnection.mutateAsync({
app: AppConnection.AzureClientSecrets,
name,
description,
method: AzureClientSecretsConnectionMethod.OAuth,
+ projectId,
credentials: {
code: code as string,
tenantId: formData.tenantId
@@ -328,14 +295,20 @@ export const OAuthCallbackPage = () => {
type: "error"
});
navigate({
- to: returnUrl ?? "/organization/app-connections"
+ to: returnUrl,
+ params: {
+ projectId
+ }
});
+ return null;
}
return {
connectionId,
returnUrl,
- appConnectionName: formData.app
+ appConnectionName: formData.app,
+ projectId,
+ connection
};
}, []);
@@ -345,7 +318,9 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.AzureDevOps);
- const { connectionId, name, description, returnUrl } = formData;
+ const { connectionId, name, description, returnUrl, projectId } = formData;
+
+ let connection: TAppConnection;
try {
if (!("tenantId" in formData)) {
@@ -353,7 +328,7 @@ export const OAuthCallbackPage = () => {
}
if (connectionId) {
- await updateAppConnection.mutateAsync({
+ connection = await updateAppConnection.mutateAsync({
app: AppConnection.AzureDevOps,
connectionId,
credentials: {
@@ -363,11 +338,12 @@ export const OAuthCallbackPage = () => {
}
});
} else {
- await createAppConnection.mutateAsync({
+ connection = await createAppConnection.mutateAsync({
app: AppConnection.AzureDevOps,
name,
description,
method: AzureDevOpsConnectionMethod.OAuth,
+ projectId,
credentials: {
code: code as string,
tenantId: formData.tenantId as string,
@@ -382,14 +358,20 @@ export const OAuthCallbackPage = () => {
type: "error"
});
navigate({
- to: returnUrl ?? "/organization/app-connections"
+ to: returnUrl,
+ params: {
+ projectId
+ }
});
+ return null;
}
return {
connectionId,
returnUrl,
- appConnectionName: formData.app
+ appConnectionName: formData.app,
+ projectId,
+ connection
};
}, []);
@@ -399,11 +381,14 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.GitHub);
- const { connectionId, name, description, returnUrl, gatewayId, credentials } = formData;
+ const { connectionId, name, description, returnUrl, gatewayId, credentials, projectId } =
+ formData;
+
+ let connection: TAppConnection;
try {
if (connectionId) {
- await updateAppConnection.mutateAsync({
+ connection = await updateAppConnection.mutateAsync({
app: AppConnection.GitHub,
...(installationId
? {
@@ -427,10 +412,11 @@ export const OAuthCallbackPage = () => {
})
});
} else {
- await createAppConnection.mutateAsync({
+ connection = await createAppConnection.mutateAsync({
app: AppConnection.GitHub,
name,
description,
+ projectId,
...(installationId
? {
method: GitHubConnectionMethod.App,
@@ -460,14 +446,20 @@ export const OAuthCallbackPage = () => {
type: "error"
});
navigate({
- to: returnUrl ?? "/organization/app-connections"
+ to: returnUrl,
+ params: {
+ projectId
+ }
});
+ return null;
}
return {
connectionId,
returnUrl,
- appConnectionName: formData.app
+ appConnectionName: formData.app,
+ projectId,
+ connection
};
}, []);
@@ -477,11 +469,13 @@ export const OAuthCallbackPage = () => {
clearState(AppConnection.GitHubRadar);
- const { connectionId, name, description, returnUrl } = formData;
+ const { connectionId, name, description, returnUrl, projectId } = formData;
+
+ let connection: TAppConnection;
try {
if (connectionId) {
- await updateAppConnection.mutateAsync({
+ connection = await updateAppConnection.mutateAsync({
app: AppConnection.GitHubRadar,
connectionId,
credentials: {
@@ -490,11 +484,12 @@ export const OAuthCallbackPage = () => {
}
});
} else {
- await createAppConnection.mutateAsync({
+ connection = await createAppConnection.mutateAsync({
app: AppConnection.GitHubRadar,
name,
description,
method: GitHubConnectionMethod.App,
+ projectId,
credentials: {
code: code as string,
installationId: installationId as string
@@ -508,14 +503,20 @@ export const OAuthCallbackPage = () => {
type: "error"
});
navigate({
- to: returnUrl ?? "/organization/app-connections"
+ to: returnUrl,
+ params: {
+ projectId
+ }
});
+ return null;
}
return {
connectionId,
returnUrl,
- appConnectionName: formData.app
+ appConnectionName: formData.app,
+ projectId,
+ connection
};
}, []);
@@ -530,8 +531,13 @@ export const OAuthCallbackPage = () => {
if (!isReady) return;
(async () => {
- let data: { connectionId?: string; returnUrl?: string; appConnectionName?: string } | null =
- null;
+ let data: {
+ returnUrl: string;
+ appConnectionName: string;
+ connectionId?: string;
+ projectId?: string;
+ connection: TAppConnection;
+ } | null = null;
if (appConnection === AppConnection.GitHub) {
data = await handleGithub();
@@ -554,16 +560,26 @@ export const OAuthCallbackPage = () => {
text: `Successfully ${data.connectionId ? "updated" : "added"} ${data.appConnectionName ? APP_CONNECTION_MAP[data.appConnectionName as AppConnection].name : ""} Connection`,
type: "success"
});
- } else {
- createNotification({
- text: "Failed to add connection",
- type: "error"
+
+ await navigate({
+ to: data.returnUrl,
+ params: {
+ projectId: data.projectId ?? undefined
+ },
+ // scott: if it's not an app connection page we need to pass connection details as it's an inline creation
+ search: data.returnUrl.includes("app-connections")
+ ? undefined
+ : {
+ connectionId: data.connection.id,
+ connectionName: data.connection.name,
+ ...(data.returnUrl.includes("integrations")
+ ? {
+ selectedTab: IntegrationsListPageTabs.SecretSyncs
+ }
+ : {})
+ }
});
}
-
- await navigate({
- to: data?.returnUrl ?? "/organization/app-connections"
- });
})();
}, [isReady]);
diff --git a/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.types.ts b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.types.ts
new file mode 100644
index 0000000000..6c76a60b3b
--- /dev/null
+++ b/frontend/src/pages/organization/AppConnections/OauthCallbackPage/OauthCallbackPage.types.ts
@@ -0,0 +1,68 @@
+import {
+ AzureDevOpsConnectionMethod,
+ TAzureAppConfigurationConnection,
+ TAzureClientSecretsConnection,
+ TAzureDevOpsConnection,
+ TAzureKeyVaultConnection,
+ TGitHubConnection,
+ TGitHubRadarConnection,
+ TGitLabConnection
+} from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+
+type BaseFormData = {
+ returnUrl: string;
+ connectionId?: string;
+ isUpdate?: boolean;
+ projectId: string;
+};
+
+export type GithubFormData = BaseFormData &
+ Pick<TGitHubConnection, "name" | "method" | "description" | "gatewayId" | "credentials">;
+
+export type GithubRadarFormData = BaseFormData &
+ Pick<TGitHubRadarConnection, "name" | "method" | "description">;
+
+export type GitLabFormData = BaseFormData &
+ Pick<TGitLabConnection, "name" | "method" | "description" | "credentials">;
+
+export type AzureKeyVaultFormData = BaseFormData &
+ Pick<TAzureKeyVaultConnection, "name" | "method" | "description"> &
+ Pick<TAzureKeyVaultConnection["credentials"], "tenantId">;
+
+export type AzureAppConfigurationFormData = BaseFormData &
+ Pick<TAzureAppConfigurationConnection, "name" | "method" | "description"> &
+ Pick<TAzureAppConfigurationConnection["credentials"], "tenantId">;
+
+export type AzureClientSecretsFormData = BaseFormData &
+ Pick<TAzureClientSecretsConnection, "name" | "method" | "description"> &
+ Pick<TAzureClientSecretsConnection["credentials"], "tenantId">;
+
+type OAuthCredentials = Extract<
+ TAzureDevOpsConnection,
+ { method: AzureDevOpsConnectionMethod.OAuth }
+>["credentials"];
+type AccessTokenCredentials = Extract<
+ TAzureDevOpsConnection,
+ { method: AzureDevOpsConnectionMethod.AccessToken }
+>["credentials"];
+
+export type AzureDevOpsFormData = BaseFormData &
+ Pick<TAzureDevOpsConnection, "name" | "method" | "description"> &
+ (Pick<OAuthCredentials, "tenantId" | "orgName"> | Pick<AccessTokenCredentials, "orgName">);
+
+export type FormDataMap = {
+ [AppConnection.GitHub]: GithubFormData & { app: AppConnection.GitHub };
+ [AppConnection.GitHubRadar]: GithubRadarFormData & { app: AppConnection.GitHubRadar };
+ [AppConnection.GitLab]: GitLabFormData & { app: AppConnection.GitLab };
+ [AppConnection.AzureKeyVault]: AzureKeyVaultFormData & { app: AppConnection.AzureKeyVault };
+ [AppConnection.AzureAppConfiguration]: AzureAppConfigurationFormData & {
+ app: AppConnection.AzureAppConfiguration;
+ };
+ [AppConnection.AzureClientSecrets]: AzureClientSecretsFormData & {
+ app: AppConnection.AzureClientSecrets;
+ };
+ [AppConnection.AzureDevOps]: AzureDevOpsFormData & {
+ app: AppConnection.AzureDevOps;
+ };
+};
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx
index 715f9c0b23..40b2f973f9 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsFilter.tsx
@@ -21,7 +21,7 @@ import {
SelectItem
} from "@app/components/v2";
import { useOrganization } from "@app/context";
-import { useGetUserWorkspaces } from "@app/hooks/api";
+import { useGetUserProjects } from "@app/hooks/api";
import {
eventToNameMap,
secretEvents,
@@ -29,7 +29,7 @@ import {
} from "@app/hooks/api/auditLogs/constants";
import { EventType } from "@app/hooks/api/auditLogs/enums";
import { UserAgentType } from "@app/hooks/api/auth/types";
-import { Workspace } from "@app/hooks/api/workspace/types";
+import { Project } from "@app/hooks/api/projects/types";
import { LogFilterItem } from "./LogFilterItem";
import { auditLogFilterFormSchema, Presets, TAuditLogFilterFormData } from "./types";
@@ -44,7 +44,7 @@ type Props = {
presets?: Presets;
setFilter: (data: TAuditLogFilterFormData) => void;
filter: TAuditLogFilterFormData;
- project?: Workspace;
+ project?: Project;
};
const getActiveFilterCount = (filter: TAuditLogFilterFormData) => {
@@ -72,7 +72,7 @@ const getActiveFilterCount = (filter: TAuditLogFilterFormData) => {
};
export const LogsFilter = ({ presets, setFilter, filter, project }: Props) => {
- const { data: workspaces = [] } = useGetUserWorkspaces();
+ const { data: workspaces = [] } = useGetUserProjects();
const { currentOrg } = useOrganization();
const workspacesInOrg = workspaces.filter((ws) => ws.orgId === currentOrg?.id);
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx
index 5bbb42d329..f1173447c1 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx
@@ -13,7 +13,7 @@ import {
} from "@app/context";
import { Timezone } from "@app/helpers/datetime";
import { withPermission, withProjectPermission } from "@app/hoc";
-import { Workspace } from "@app/hooks/api/workspace/types";
+import { Project } from "@app/hooks/api/projects/types";
import { usePopUp } from "@app/hooks/usePopUp";
import { LogsDateFilter } from "./LogsDateFilter";
@@ -31,7 +31,7 @@ type Props = {
refetchInterval?: number;
showFilters?: boolean;
pageView?: boolean;
- project?: Workspace;
+ project?: Project;
};
const LogsSectionComponent = ({
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/types.tsx b/frontend/src/pages/organization/AuditLogsPage/components/types.tsx
index 8e0ec9ba98..b1338be24b 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/types.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/types.tsx
@@ -1,7 +1,7 @@
import { z } from "zod";
import { ActorType, EventType, UserAgentType } from "@app/hooks/api/auditLogs/enums";
-import { ProjectType } from "@app/hooks/api/workspace/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
export enum AuditLogDateFilterType {
Relative = "relative",
diff --git a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx
index 729654d76c..a0d4408724 100644
--- a/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx
+++ b/frontend/src/pages/organization/Gateways/GatewayListPage/GatewayListPage.tsx
@@ -4,11 +4,11 @@ import {
faArrowUpRightFromSquare,
faBookOpen,
faCopy,
+ faDoorClosed,
faEdit,
faEllipsisV,
faInfoCircle,
faMagnifyingGlass,
- faPlug,
faSearch,
faTrash
} from "@fortawesome/free-solid-svg-icons";
@@ -243,7 +243,7 @@ export const GatewayListPage = withPermission(
? "No Gateways match search..."
: "No Gateways have been configured"
}
- icon={gateways?.length ? faSearch : faPlug}
+ icon={gateways?.length ? faSearch : faDoorClosed}
/>
)}
<DeleteActionModal
diff --git a/frontend/src/pages/organization/Gateways/Relay/RelayListPage/RelayListPage.tsx b/frontend/src/pages/organization/Gateways/Relay/RelayListPage/RelayListPage.tsx
new file mode 100644
index 0000000000..2557631821
--- /dev/null
+++ b/frontend/src/pages/organization/Gateways/Relay/RelayListPage/RelayListPage.tsx
@@ -0,0 +1,214 @@
+import { useState } from "react";
+import { Helmet } from "react-helmet";
+import {
+ faArrowUpRightFromSquare,
+ faBookOpen,
+ faCopy,
+ faDoorClosed,
+ faEllipsisV,
+ faMagnifyingGlass,
+ faSearch,
+ faTrash
+} from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { formatRelative } from "date-fns";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import {
+ DeleteActionModal,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ EmptyState,
+ IconButton,
+ Input,
+ PageHeader,
+ Table,
+ TableContainer,
+ TableSkeleton,
+ TBody,
+ Td,
+ Th,
+ THead,
+ Tooltip,
+ Tr
+} from "@app/components/v2";
+import {
+ OrgPermissionSubjects,
+ OrgRelayPermissionActions
+} from "@app/context/OrgPermissionContext/types";
+import { withPermission } from "@app/hoc";
+import { usePopUp } from "@app/hooks";
+import { useDeleteRelayById, useGetRelays } from "@app/hooks/api/relays";
+
+export const RelayListPage = withPermission(
+ () => {
+ const [search, setSearch] = useState("");
+ const { data: relays, isPending: isRelaysLoading } = useGetRelays();
+
+ const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["deleteRelay"] as const);
+
+ const deleteRelayById = useDeleteRelayById();
+
+ const handleDeleteRelay = async () => {
+ const data = popUp.deleteRelay.data as { id: string };
+ await deleteRelayById.mutateAsync(data.id);
+
+ handlePopUpToggle("deleteRelay");
+ createNotification({
+ type: "success",
+ text: "Successfully deleted relay"
+ });
+ };
+
+ const filteredRelays = relays?.filter((el) =>
+ el.name.toLowerCase().includes(search.toLowerCase())
+ );
+
+ return (
+ <div className="bg-bunker-800">
+ <Helmet>
+ <title>Infisical | Relays</title>
+ <meta property="og:image" content="/images/message.png" />
+ </Helmet>
+ <div className="flex w-full justify-center bg-bunker-800 text-white">
+ <div className="w-full max-w-7xl">
+ <PageHeader
+ className="w-full"
+ title={
+ <div className="flex w-full items-center">
+ <span>Relays</span>
+ <a
+ className="-mt-1.5"
+ href="https://infisical.com/docs/documentation/platform/gateways/relay-deployment"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <div className="ml-2 inline-block rounded-md bg-yellow/20 px-1.5 text-sm font-normal text-yellow opacity-80 hover:opacity-100">
+ <FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
+ <span>Docs</span>
+ <FontAwesomeIcon
+ icon={faArrowUpRightFromSquare}
+ className="mb-[0.07rem] ml-1.5 text-[10px]"
+ />
+ </div>
+ </a>
+ </div>
+ }
+ description="Create and configure relays to securely access private network resources from Infisical"
+ />
+ <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <div>
+ <div className="flex gap-2">
+ <Input
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
+ placeholder="Search relay..."
+ className="flex-1"
+ />
+ </div>
+ <TableContainer className="mt-4">
+ <Table>
+ <THead>
+ <Tr>
+ <Th className="w-1/3">Name</Th>
+ <Th>Host</Th>
+ <Th>Created</Th>
+ <Th className="w-5" />
+ </Tr>
+ </THead>
+ <TBody>
+ {isRelaysLoading && (
+ <TableSkeleton innerKey="relay-table" columns={4} key="relay-table" />
+ )}
+ {filteredRelays?.map((el) => (
+ <Tr key={el.id}>
+ <Td>
+ <div className="flex items-center gap-2">
+ <span>{el.name}</span>
+ {!el.orgId && (
+ <Tooltip content="This is a managed relay provided by Infisical">
+ <span className="rounded bg-mineshaft-700 px-1.5 py-0.5 text-xs text-mineshaft-400">
+ Managed
+ </span>
+ </Tooltip>
+ )}
+ </div>
+ </Td>
+ <Td>{el.host}</Td>
+ <Td>{formatRelative(new Date(el.createdAt), new Date())}</Td>
+ <Td className="w-5">
+ <Tooltip className="max-w-sm text-center" content="Options">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ ariaLabel="Options"
+ colorSchema="secondary"
+ className="w-6"
+ variant="plain"
+ >
+ <FontAwesomeIcon icon={faEllipsisV} />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ icon={<FontAwesomeIcon icon={faCopy} />}
+ onClick={() => navigator.clipboard.writeText(el.id)}
+ >
+ Copy ID
+ </DropdownMenuItem>
+ <OrgPermissionCan
+ I={OrgRelayPermissionActions.DeleteRelays}
+ a={OrgPermissionSubjects.Relay}
+ >
+ {(isAllowed: boolean) => (
+ <DropdownMenuItem
+ isDisabled={!isAllowed || !el.orgId}
+ icon={<FontAwesomeIcon icon={faTrash} />}
+ className="text-red"
+ onClick={() => handlePopUpOpen("deleteRelay", el)}
+ >
+ Delete Relay
+ </DropdownMenuItem>
+ )}
+ </OrgPermissionCan>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </Tooltip>
+ </Td>
+ </Tr>
+ ))}
+ </TBody>
+ </Table>
+ {!isRelaysLoading && !filteredRelays?.length && (
+ <EmptyState
+ title={
+ relays?.length
+ ? "No Relays match search..."
+ : "No Relays have been configured"
+ }
+ icon={relays?.length ? faSearch : faDoorClosed}
+ />
+ )}
+ <DeleteActionModal
+ isOpen={popUp.deleteRelay.isOpen}
+ title={`Are you sure you want to delete relay ${
+ (popUp?.deleteRelay?.data as { name: string })?.name || ""
+ }?`}
+ onChange={(isOpen) => handlePopUpToggle("deleteRelay", isOpen)}
+ deleteKey="confirm"
+ onDeleteApproved={() => handleDeleteRelay()}
+ />
+ </TableContainer>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ },
+ { action: OrgRelayPermissionActions.ListRelays, subject: OrgPermissionSubjects.Relay }
+);
diff --git a/frontend/src/pages/organization/Gateways/Relay/RelayListPage/route.tsx b/frontend/src/pages/organization/Gateways/Relay/RelayListPage/route.tsx
new file mode 100644
index 0000000000..125f1c58c9
--- /dev/null
+++ b/frontend/src/pages/organization/Gateways/Relay/RelayListPage/route.tsx
@@ -0,0 +1,16 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { RelayListPage } from "./RelayListPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/organization/relays/"
+)({
+ component: RelayListPage,
+ context: () => ({
+ breadcrumbs: [
+ {
+ label: "Relays"
+ }
+ ]
+ })
+});
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx
index a0565d50da..2e5c7101c7 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityAddToProjectModal.tsx
@@ -17,7 +17,7 @@ import {
useAddIdentityToWorkspace,
useGetIdentityProjectMemberships,
useGetProjectRoles,
- useGetUserWorkspaces,
+ useGetUserProjects,
useGetWorkspaceById
} from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -44,7 +44,7 @@ type Props = {
const Content = ({ identityId, handlePopUpToggle }: Omit<Props, "popUp">) => {
const { currentOrg } = useOrganization();
- const { data: workspaces = [] } = useGetUserWorkspaces();
+ const { data: workspaces = [] } = useGetUserProjects();
const { mutateAsync: addIdentityToWorkspace } = useAddIdentityToWorkspace();
const {
@@ -77,7 +77,7 @@ const Content = ({ identityId, handlePopUpToggle }: Omit<Props, "popUp">) => {
const onFormSubmit = async ({ project: selectedProject, role }: FormData) => {
try {
await addIdentityToWorkspace({
- workspaceId: selectedProject.id,
+ projectId: selectedProject.id,
identityId,
role: role.slug || undefined
});
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectRow.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectRow.tsx
index 5b0aac0b79..1622962ea5 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectRow.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectRow.tsx
@@ -8,7 +8,7 @@ import { createNotification } from "@app/components/notifications";
import { IconButton, Td, Tooltip, Tr } from "@app/components/v2";
import { getProjectBaseURL } from "@app/helpers/project";
import { formatProjectRoleName } from "@app/helpers/roles";
-import { useGetUserWorkspaces } from "@app/hooks/api";
+import { useGetUserProjects } from "@app/hooks/api";
import { IdentityMembership } from "@app/hooks/api/identities/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -31,7 +31,7 @@ export const IdentityProjectRow = ({
membership: { id, createdAt, identity, project, roles },
handlePopUpOpen
}: Props) => {
- const { data: workspaces } = useGetUserWorkspaces();
+ const { data: workspaces } = useGetUserProjects();
const navigate = useNavigate();
const isAccessible = useMemo(() => {
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx
index 0ea97c4d30..321a84ccbd 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/IdentityProjectsSection/IdentityProjectsSection.tsx
@@ -25,7 +25,7 @@ export const IdentityProjectsSection = ({ identityId }: Props) => {
try {
await deleteMutateAsync({
identityId: id,
- workspaceId: projectId
+ projectId
});
createNotification({
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityAuthLockoutFields.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityAuthLockoutFields.tsx
new file mode 100644
index 0000000000..b5cb2d901d
--- /dev/null
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/IdentityAuthLockoutFields.tsx
@@ -0,0 +1,81 @@
+import { useState } from "react";
+import { UseMutationResult } from "@tanstack/react-query";
+import ms from "ms";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import { Button } from "@app/components/v2";
+import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/context";
+
+import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";
+
+export const LockoutFields = ({
+ clearLockoutsResult,
+ lockedOut,
+ identityId,
+ data,
+ onResetAllLockouts
+}: {
+ clearLockoutsResult: UseMutationResult<number, object, { identityId: string }, unknown>;
+ lockedOut: boolean;
+ identityId: string;
+ data: {
+ lockoutEnabled: boolean;
+ lockoutThreshold: number;
+ lockoutDurationSeconds: number;
+ lockoutCounterResetSeconds: number;
+ };
+ onResetAllLockouts: () => void;
+}) => {
+ const { mutateAsync, isPending } = clearLockoutsResult;
+
+ const [lockedOutState, setLockedOutState] = useState(lockedOut);
+
+ async function clearLockouts() {
+ try {
+ const deleted = await mutateAsync({ identityId });
+ createNotification({
+ text: `Successfully cleared ${deleted} lockout${deleted === 1 ? "" : "s"}`,
+ type: "success"
+ });
+ setLockedOutState(false);
+ onResetAllLockouts();
+ } catch (error) {
+ console.error(error);
+ createNotification({
+ text: "Failed to clear lockouts. Please try again.",
+ type: "error"
+ });
+ }
+ }
+
+ return (
+ <>
+ <div className="col-span-2 mt-3 flex justify-between border-b border-mineshaft-500 pb-2">
+ <span className="text-bunker-300">Lockout Options</span>
+ <OrgPermissionCan I={OrgPermissionIdentityActions.Edit} a={OrgPermissionSubjects.Identity}>
+ {(isAllowed) => (
+ <Button
+ isDisabled={!isAllowed || !lockedOutState || isPending}
+ size="xs"
+ onClick={() => clearLockouts()}
+ isLoading={isPending}
+ colorSchema="secondary"
+ >
+ Reset All Lockouts
+ </Button>
+ )}
+ </OrgPermissionCan>
+ </div>
+ <IdentityAuthFieldDisplay label="Lockout Threshold">
+ {data.lockoutThreshold}
+ </IdentityAuthFieldDisplay>
+ <IdentityAuthFieldDisplay label="Lockout Duration">
+ {ms(data.lockoutDurationSeconds * 1000, { long: true })}
+ </IdentityAuthFieldDisplay>
+ <IdentityAuthFieldDisplay label="Lockout Counter Reset">
+ {ms(data.lockoutCounterResetSeconds * 1000, { long: true })}
+ </IdentityAuthFieldDisplay>
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityLdapAuthContent.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityLdapAuthContent.tsx
index f732fd5ed0..9c20a1bbe9 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityLdapAuthContent.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityLdapAuthContent.tsx
@@ -2,11 +2,12 @@ import { faBan, faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Badge, EmptyState, Spinner, Tooltip } from "@app/components/v2";
-import { useGetIdentityLdapAuth } from "@app/hooks/api";
+import { useClearIdentityLdapAuthLockouts, useGetIdentityLdapAuth } from "@app/hooks/api";
import { IdentityLdapAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityLdapAuthForm";
import { ViewIdentityContentWrapper } from "@app/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityContentWrapper";
import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";
+import { LockoutFields } from "./IdentityAuthLockoutFields";
import { ViewAuthMethodProps } from "./types";
export const ViewIdentityLdapAuthContent = ({
@@ -14,9 +15,12 @@ export const ViewIdentityLdapAuthContent = ({
handlePopUpToggle,
handlePopUpOpen,
onDelete,
- popUp
+ popUp,
+ lockedOut,
+ onResetAllLockouts
}: ViewAuthMethodProps) => {
const { data, isPending } = useGetIdentityLdapAuth(identityId);
+ const clearLockoutsResult = useClearIdentityLdapAuthLockouts();
if (isPending) {
return (
@@ -98,6 +102,18 @@ export const ViewIdentityLdapAuthContent = ({
</Tooltip>
)}
</IdentityAuthFieldDisplay>
+ <IdentityAuthFieldDisplay label="Lockout">
+ {data.lockoutEnabled ? "Enabled" : "Disabled"}
+ </IdentityAuthFieldDisplay>
+ {data.lockoutEnabled && (
+ <LockoutFields
+ identityId={identityId}
+ lockedOut={lockedOut}
+ clearLockoutsResult={clearLockoutsResult}
+ data={data}
+ onResetAllLockouts={onResetAllLockouts}
+ />
+ )}
</ViewIdentityContentWrapper>
);
};
diff --git a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityUniversalAuthContent.tsx b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityUniversalAuthContent.tsx
index b05a873cea..4d7b95087c 100644
--- a/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityUniversalAuthContent.tsx
+++ b/frontend/src/pages/organization/IdentityDetailsByIDPage/components/ViewIdentityAuthModal/ViewIdentityUniversalAuthContent.tsx
@@ -1,12 +1,7 @@
-import { useState } from "react";
import { faBan, faCheck, faCopy } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import ms from "ms";
-import { createNotification } from "@app/components/notifications";
-import { OrgPermissionCan } from "@app/components/permissions";
-import { Button, EmptyState, IconButton, Spinner, Tooltip } from "@app/components/v2";
-import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/context";
+import { EmptyState, IconButton, Spinner, Tooltip } from "@app/components/v2";
import { useTimedReset } from "@app/hooks";
import {
useClearIdentityUniversalAuthLockouts,
@@ -16,6 +11,7 @@ import {
import { IdentityUniversalAuthForm } from "@app/pages/organization/AccessManagementPage/components/OrgIdentityTab/components/IdentitySection/IdentityUniversalAuthForm";
import { IdentityAuthFieldDisplay } from "./IdentityAuthFieldDisplay";
+import { LockoutFields } from "./IdentityAuthLockoutFields";
import { IdentityUniversalAuthClientSecretsTable } from "./IdentityUniversalAuthClientSecretsTable";
import { ViewAuthMethodProps } from "./types";
import { ViewIdentityContentWrapper } from "./ViewIdentityContentWrapper";
@@ -32,33 +28,12 @@ export const ViewIdentityUniversalAuthContent = ({
const { data, isPending } = useGetIdentityUniversalAuth(identityId);
const { data: clientSecrets = [], isPending: clientSecretsPending } =
useGetIdentityUniversalAuthClientSecrets(identityId);
- const { mutateAsync: clearLockoutsFn, isPending: isClearLockoutsPending } =
- useClearIdentityUniversalAuthLockouts();
-
- const [lockedOutState, setLockedOutState] = useState(lockedOut);
+ const clearLockoutsResult = useClearIdentityUniversalAuthLockouts();
const [copyTextClientId, isCopyingClientId, setCopyTextClientId] = useTimedReset<string>({
initialState: "Copy Client ID to clipboard"
});
- async function clearLockouts() {
- try {
- const deleted = await clearLockoutsFn({ identityId });
- createNotification({
- text: `Successfully cleared ${deleted} lockout${deleted === 1 ? "" : "s"}`,
- type: "success"
- });
- setLockedOutState(false);
- onResetAllLockouts();
- } catch (error) {
- console.error(error);
- createNotification({
- text: "Failed to clear lockouts. Please try again.",
- type: "error"
- });
- }
- }
-
if (isPending || clientSecretsPending) {
return (
<div className="flex w-full items-center justify-center">
@@ -119,36 +94,13 @@ export const ViewIdentityUniversalAuthContent = ({
{data.lockoutEnabled ? "Enabled" : "Disabled"}
</IdentityAuthFieldDisplay>
{data.lockoutEnabled && (
- <>
- <div className="col-span-2 mt-3 flex justify-between border-b border-mineshaft-500 pb-2">
- <span className="text-bunker-300">Lockout Options</span>
- <OrgPermissionCan
- I={OrgPermissionIdentityActions.Edit}
- a={OrgPermissionSubjects.Identity}
- >
- {(isAllowed) => (
- <Button
- isDisabled={!isAllowed || !lockedOutState || isClearLockoutsPending}
- size="xs"
- onClick={() => clearLockouts()}
- isLoading={isClearLockoutsPending}
- colorSchema="secondary"
- >
- Reset All Lockouts
- </Button>
- )}
- </OrgPermissionCan>
- </div>
- <IdentityAuthFieldDisplay label="Lockout Threshold">
- {data.lockoutThreshold}
- </IdentityAuthFieldDisplay>
- <IdentityAuthFieldDisplay label="Lockout Duration">
- {ms(data.lockoutDurationSeconds * 1000, { long: true })}
- </IdentityAuthFieldDisplay>
- <IdentityAuthFieldDisplay label="Lockout Counter Reset">
- {ms(data.lockoutCounterResetSeconds * 1000, { long: true })}
- </IdentityAuthFieldDisplay>
- </>
+ <LockoutFields
+ identityId={identityId}
+ lockedOut={lockedOut}
+ clearLockoutsResult={clearLockoutsResult}
+ data={data}
+ onResetAllLockouts={onResetAllLockouts}
+ />
)}
<div className="col-span-2 my-3">
<div className="mb-3 border-b border-mineshaft-500 pb-2">
diff --git a/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx b/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx
index 7b066a0996..f7d20e2b7f 100644
--- a/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/components/AllProjectView.tsx
@@ -1,5 +1,4 @@
import { useState } from "react";
-import { useForm } from "react-hook-form";
import {
faArrowDownAZ,
faBorderAll,
@@ -16,6 +15,7 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { OrgPermissionCan } from "@app/components/permissions";
+import { RequestProjectAccessModal } from "@app/components/projects/RequestProjectAccessModal";
import {
Badge,
Button,
@@ -24,12 +24,9 @@ import {
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
- FormControl,
IconButton,
Input,
Lottie,
- Modal,
- ModalContent,
Pagination,
Skeleton,
Tooltip
@@ -43,12 +40,8 @@ import {
setUserTablePreference
} from "@app/helpers/userTablePreferences";
import { useDebounce, usePagination, usePopUp, useResetPageHelper } from "@app/hooks";
-import {
- useOrgAdminAccessProject,
- useRequestProjectAccess,
- useSearchProjects
-} from "@app/hooks/api";
-import { ProjectType, Workspace, WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { useOrgAdminAccessProject, useSearchProjects } from "@app/hooks/api";
+import { Project, ProjectEnv, ProjectType } from "@app/hooks/api/projects/types";
import {
ProjectListToggle,
ProjectListView
@@ -62,53 +55,6 @@ type Props = {
onProjectListViewChange: (value: ProjectListView) => void;
};
-type RequestAccessModalProps = {
- projectId: string;
- onPopUpToggle: () => void;
-};
-
-const RequestAccessModal = ({ projectId, onPopUpToggle }: RequestAccessModalProps) => {
- const form = useForm<{ note: string }>();
-
- const requestProjectAccess = useRequestProjectAccess();
-
- const onFormSubmit = ({ note }: { note: string }) => {
- if (requestProjectAccess.isPending) return;
- requestProjectAccess.mutate(
- {
- comment: note,
- projectId
- },
- {
- onSuccess: () => {
- createNotification({
- type: "success",
- title: "Project Access Request Sent",
- text: "Project admins will receive an email of your request"
- });
- onPopUpToggle();
- }
- }
- );
- };
-
- return (
- <form onSubmit={form.handleSubmit(onFormSubmit)}>
- <FormControl label="Note">
- <Input {...form.register("note")} />
- </FormControl>
- <div className="mt-4 flex items-center">
- <Button className="mr-4" size="sm" type="submit" isLoading={form.formState.isSubmitting}>
- Submit Request
- </Button>
- <Button colorSchema="secondary" variant="plain" onClick={() => onPopUpToggle()}>
- Cancel
- </Button>
- </div>
- </form>
- );
-};
-
export const AllProjectView = ({
onAddNewProject,
onUpgradePlan,
@@ -155,7 +101,7 @@ export const AllProjectView = ({
const handleAccessProject = async (
type: ProjectType,
projectId: string,
- environments: WorkspaceEnv[]
+ environments: ProjectEnv[]
) => {
try {
await orgAdminAccessProject.mutateAsync({
@@ -180,7 +126,7 @@ export const AllProjectView = ({
offset,
totalCount: searchedProjects?.totalCount || 0
});
- const requestedWorkspaceDetails = (popUp.requestAccessConfirmation.data || {}) as Workspace;
+ const requestedWorkspaceDetails = (popUp.requestAccessConfirmation.data || {}) as Project;
const handleToggleFilterByProjectType = (el: ProjectType) =>
setProjectTypeFilter((state) => (state === el ? undefined : el));
@@ -278,22 +224,26 @@ export const AllProjectView = ({
</IconButton>
</div>
<OrgPermissionCan I={OrgPermissionActions.Create} an={OrgPermissionSubjects.Workspace}>
- {(isAllowed) => (
- <Button
- isDisabled={!isAllowed}
- colorSchema="secondary"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => {
- if (isAddingProjectsAllowed) {
- onAddNewProject();
- } else {
- onUpgradePlan();
- }
- }}
- className="ml-2"
- >
- Add New Project
- </Button>
+ {(isOldProjectPermissionAllowed) => (
+ <OrgPermissionCan I={OrgPermissionActions.Create} an={OrgPermissionSubjects.Project}>
+ {(isAllowed) => (
+ <Button
+ isDisabled={!isAllowed && !isOldProjectPermissionAllowed}
+ colorSchema="secondary"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => {
+ if (isAddingProjectsAllowed) {
+ onAddNewProject();
+ } else {
+ onUpgradePlan();
+ }
+ }}
+ className="ml-2"
+ >
+ Add New Project
+ </Button>
+ )}
+ </OrgPermissionCan>
)}
</OrgPermissionCan>
</div>
@@ -419,20 +369,11 @@ export const AllProjectView = ({
<div className="text-center font-light">No Projects Found</div>
</div>
)}
- <Modal
+ <RequestProjectAccessModal
isOpen={popUp.requestAccessConfirmation.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("requestAccessConfirmation", isOpen)}
- >
- <ModalContent
- title="Confirm Access Request"
- subTitle={`Requesting access to project ${requestedWorkspaceDetails?.name}. You may include an optional note for project admins to review your request.`}
- >
- <RequestAccessModal
- onPopUpToggle={() => handlePopUpToggle("requestAccessConfirmation")}
- projectId={requestedWorkspaceDetails?.id}
- />
- </ModalContent>
- </Modal>
+ project={requestedWorkspaceDetails}
+ />
</div>
);
};
diff --git a/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx b/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx
index d63099273e..46f520d411 100644
--- a/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx
+++ b/frontend/src/pages/organization/ProjectsPage/components/MyProjectView.tsx
@@ -39,11 +39,11 @@ import {
setUserTablePreference
} from "@app/helpers/userTablePreferences";
import { usePagination, useResetPageHelper } from "@app/hooks";
-import { useGetUserWorkspaces } from "@app/hooks/api";
+import { useGetUserProjects } from "@app/hooks/api";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { Project, ProjectType } from "@app/hooks/api/projects/types";
import { useUpdateUserProjectFavorites } from "@app/hooks/api/users/mutation";
import { useGetUserProjectFavorites } from "@app/hooks/api/users/queries";
-import { ProjectType, Workspace } from "@app/hooks/api/workspace/types";
import {
ProjectListToggle,
ProjectListView
@@ -79,7 +79,7 @@ export const MyProjectView = ({
{}
);
- const { data: workspaces = [], isPending: isWorkspaceLoading } = useGetUserWorkspaces();
+ const { data: workspaces = [], isPending: isWorkspaceLoading } = useGetUserProjects();
const {
setPage,
perPage,
@@ -136,7 +136,7 @@ export const MyProjectView = ({
const { workspacesWithFaveProp } = useMemo(() => {
const workspacesWithFav = filteredWorkspaces
- .map((w): Workspace & { isFavorite: boolean } => ({
+ .map((w): Project & { isFavorite: boolean } => ({
...w,
isFavorite: Boolean(projectFavorites?.includes(w.id))
}))
@@ -188,7 +188,7 @@ export const MyProjectView = ({
}
};
- const renderProjectGridItem = (workspace: Workspace, isFavorite: boolean) => (
+ const renderProjectGridItem = (workspace: Project, isFavorite: boolean) => (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events
<div
onClick={() => {
@@ -242,7 +242,7 @@ export const MyProjectView = ({
</p>
</div>
);
- const renderProjectListItem = (workspace: Workspace, isFavorite: boolean, index: number) => (
+ const renderProjectListItem = (workspace: Project, isFavorite: boolean, index: number) => (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events
<div
onClick={() => {
@@ -480,22 +480,26 @@ export const MyProjectView = ({
</IconButton>
</div>
<OrgPermissionCan I={OrgPermissionActions.Create} an={OrgPermissionSubjects.Workspace}>
- {(isAllowed) => (
- <Button
- isDisabled={!isAllowed}
- colorSchema="secondary"
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- onClick={() => {
- if (isAddingProjectsAllowed) {
- onAddNewProject();
- } else {
- onUpgradePlan();
- }
- }}
- className="ml-2"
- >
- Add New Project
- </Button>
+ {(isOldProjectV1Allowed) => (
+ <OrgPermissionCan I={OrgPermissionActions.Create} an={OrgPermissionSubjects.Project}>
+ {(isAllowed) => (
+ <Button
+ isDisabled={!isAllowed && !isOldProjectV1Allowed}
+ colorSchema="secondary"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => {
+ if (isAddingProjectsAllowed) {
+ onAddNewProject();
+ } else {
+ onUpgradePlan();
+ }
+ }}
+ className="ml-2"
+ >
+ Add New Project
+ </Button>
+ )}
+ </OrgPermissionCan>
)}
</OrgPermissionCan>
</div>
diff --git a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts
index 03b86f2abd..68da9cad27 100644
--- a/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts
+++ b/frontend/src/pages/organization/RoleByIDPage/components/OrgRoleModifySection.utils.ts
@@ -11,7 +11,8 @@ import {
OrgPermissionIdentityActions,
OrgPermissionKmipActions,
OrgPermissionMachineIdentityAuthTemplateActions,
- OrgPermissionSecretShareAction
+ OrgPermissionSecretShareAction,
+ OrgRelayPermissionActions
} from "@app/context/OrgPermissionContext/types";
import { TPermission } from "@app/hooks/api/roles/types";
@@ -90,6 +91,15 @@ const orgGatewayPermissionSchema = z
})
.optional();
+const orgRelayPermissionSchema = z
+ .object({
+ [OrgRelayPermissionActions.ListRelays]: z.boolean().optional(),
+ [OrgRelayPermissionActions.EditRelays]: z.boolean().optional(),
+ [OrgRelayPermissionActions.DeleteRelays]: z.boolean().optional(),
+ [OrgRelayPermissionActions.CreateRelays]: z.boolean().optional()
+ })
+ .optional();
+
const machineIdentityAuthTemplatePermissionSchema = z
.object({
[OrgPermissionMachineIdentityAuthTemplateActions.ListTemplates]: z.boolean().optional(),
@@ -122,12 +132,11 @@ export const formSchema = z.object({
.refine((val) => val !== "custom", { message: "Cannot use custom as its a keyword" }),
permissions: z
.object({
- workspace: z
+ project: z
.object({
create: z.boolean().optional()
})
.optional(),
-
"audit-logs": auditLogsPermissionSchema,
member: generalPermissionSchema,
groups: groupPermissionSchema,
@@ -148,6 +157,7 @@ export const formSchema = z.object({
"app-connections": appConnectionsPermissionSchema,
kmip: kmipPermissionSchema,
gateway: orgGatewayPermissionSchema,
+ relay: orgRelayPermissionSchema,
"machine-identity-auth-template": machineIdentityAuthTemplatePermissionSchema,
"secret-share": secretSharingPermissionSchema
})
@@ -162,7 +172,11 @@ export const rolePermission2Form = (permissions: TPermission[] = []) => {
// i would have to write a if loop with both conditions same
const formVal: Record<string, any> = {};
permissions.forEach((permission) => {
- const { subject, action } = permission;
+ const { action } = permission;
+ let { subject } = permission;
+ if (subject === OrgPermissionSubjects.Workspace) {
+ subject = OrgPermissionSubjects.Project;
+ }
if (!formVal?.[subject]) formVal[subject] = {};
formVal[subject][action] = true;
});
diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionRelayRow.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionRelayRow.tsx
new file mode 100644
index 0000000000..bb14327423
--- /dev/null
+++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgPermissionRelayRow.tsx
@@ -0,0 +1,180 @@
+import { useEffect, useMemo } from "react";
+import { Control, Controller, UseFormSetValue, useWatch } from "react-hook-form";
+import { faChevronDown, faChevronRight } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+
+import { createNotification } from "@app/components/notifications";
+import { Checkbox, Select, SelectItem, Td, Tr } from "@app/components/v2";
+import { OrgRelayPermissionActions } from "@app/context/OrgPermissionContext/types";
+import { useToggle } from "@app/hooks";
+
+import { TFormSchema } from "../OrgRoleModifySection.utils";
+
+type Props = {
+ isEditable: boolean;
+ setValue: UseFormSetValue<TFormSchema>;
+ control: Control<TFormSchema>;
+};
+
+enum Permission {
+ NoAccess = "no-access",
+ ReadOnly = "read-only",
+ FullAccess = "full-access",
+ Custom = "custom"
+}
+
+const PERMISSION_ACTIONS = [
+ { action: OrgRelayPermissionActions.ListRelays, label: "List Relays" },
+ { action: OrgRelayPermissionActions.CreateRelays, label: "Create Relays" },
+ { action: OrgRelayPermissionActions.EditRelays, label: "Edit Relays" },
+ { action: OrgRelayPermissionActions.DeleteRelays, label: "Delete Relays" }
+] as const;
+
+export const OrgRelayPermissionRow = ({ isEditable, control, setValue }: Props) => {
+ const [isRowExpanded, setIsRowExpanded] = useToggle();
+ const [isCustom, setIsCustom] = useToggle();
+
+ const rule = useWatch({
+ control,
+ name: "permissions.relay"
+ });
+
+ const selectedPermissionCategory = useMemo(() => {
+ const actions = Object.keys(rule || {}) as Array<keyof typeof rule>;
+ const totalActions = PERMISSION_ACTIONS.length;
+ const score = actions.map((key) => (rule?.[key] ? 1 : 0)).reduce((a, b) => a + b, 0 as number);
+
+ if (isCustom) return Permission.Custom;
+ if (score === 0) return Permission.NoAccess;
+ if (score === totalActions) return Permission.FullAccess;
+ if (score === 1 && rule?.[OrgRelayPermissionActions.ListRelays]) return Permission.ReadOnly;
+
+ return Permission.Custom;
+ }, [rule, isCustom]);
+
+ useEffect(() => {
+ if (selectedPermissionCategory === Permission.Custom) setIsCustom.on();
+ else setIsCustom.off();
+ }, [selectedPermissionCategory]);
+
+ useEffect(() => {
+ const isRowCustom = selectedPermissionCategory === Permission.Custom;
+ if (isRowCustom) {
+ setIsRowExpanded.on();
+ }
+ }, []);
+
+ const handlePermissionChange = (val: Permission) => {
+ if (!val) return;
+ if (val === Permission.Custom) {
+ setIsRowExpanded.on();
+ setIsCustom.on();
+ return;
+ }
+ setIsCustom.off();
+
+ switch (val) {
+ case Permission.FullAccess:
+ setValue(
+ "permissions.relay",
+ {
+ [OrgRelayPermissionActions.ListRelays]: true,
+ [OrgRelayPermissionActions.EditRelays]: true,
+ [OrgRelayPermissionActions.CreateRelays]: true,
+ [OrgRelayPermissionActions.DeleteRelays]: true
+ },
+ { shouldDirty: true }
+ );
+ break;
+ case Permission.ReadOnly:
+ setValue(
+ "permissions.relay",
+ {
+ [OrgRelayPermissionActions.ListRelays]: true,
+ [OrgRelayPermissionActions.EditRelays]: false,
+ [OrgRelayPermissionActions.CreateRelays]: false,
+ [OrgRelayPermissionActions.DeleteRelays]: false
+ },
+ { shouldDirty: true }
+ );
+ break;
+
+ case Permission.NoAccess:
+ default:
+ setValue(
+ "permissions.relay",
+ {
+ [OrgRelayPermissionActions.ListRelays]: false,
+ [OrgRelayPermissionActions.EditRelays]: false,
+ [OrgRelayPermissionActions.CreateRelays]: false,
+ [OrgRelayPermissionActions.DeleteRelays]: false
+ },
+ { shouldDirty: true }
+ );
+ }
+ };
+
+ return (
+ <>
+ <Tr
+ className="h-10 cursor-pointer transition-colors duration-100 hover:bg-mineshaft-700"
+ onClick={() => setIsRowExpanded.toggle()}
+ >
+ <Td className="w-4">
+ <FontAwesomeIcon className="w-4" icon={isRowExpanded ? faChevronDown : faChevronRight} />
+ </Td>
+ <Td className="w-full select-none">Relays</Td>
+ <Td>
+ <Select
+ value={selectedPermissionCategory}
+ className="h-8 w-40 bg-mineshaft-700"
+ dropdownContainerClassName="border text-left border-mineshaft-600 bg-mineshaft-800"
+ onValueChange={handlePermissionChange}
+ isDisabled={!isEditable}
+ position="popper"
+ >
+ <SelectItem value={Permission.NoAccess}>No Access</SelectItem>
+ <SelectItem value={Permission.ReadOnly}>Read Only</SelectItem>
+ <SelectItem value={Permission.FullAccess}>Full Access</SelectItem>
+ <SelectItem value={Permission.Custom}>Custom</SelectItem>
+ </Select>
+ </Td>
+ </Tr>
+ {isRowExpanded && (
+ <Tr>
+ <Td colSpan={3} className="border-mineshaft-500 bg-mineshaft-900 p-8">
+ <div className="flex flex-grow flex-wrap justify-start gap-x-8 gap-y-4">
+ {PERMISSION_ACTIONS.map(({ action, label }) => {
+ return (
+ <Controller
+ name={`permissions.relay.${action}`}
+ key={`permissions.relay.${action}`}
+ control={control}
+ render={({ field }) => (
+ <Checkbox
+ isChecked={Boolean(field.value)}
+ onCheckedChange={(e) => {
+ if (!isEditable) {
+ createNotification({
+ type: "error",
+ text: "Failed to update default role"
+ });
+ return;
+ }
+ field.onChange(e);
+ }}
+ id={`permissions.relay.${action}`}
+ >
+ {label}
+ </Checkbox>
+ )}
+ />
+ );
+ })}
+ </div>
+ </Td>
+ </Tr>
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgRoleWorkspaceRow.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgRoleWorkspaceRow.tsx
index 2746e10bc6..5f9041a299 100644
--- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgRoleWorkspaceRow.tsx
+++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/OrgRoleWorkspaceRow.tsx
@@ -28,7 +28,7 @@ export const OrgRoleWorkspaceRow = ({ isEditable, control, setValue }: Props) =>
const rule = useWatch({
control,
- name: "permissions.workspace"
+ name: "permissions.project"
});
const selectedPermissionCategory = useMemo(() => {
@@ -60,7 +60,7 @@ export const OrgRoleWorkspaceRow = ({ isEditable, control, setValue }: Props) =>
setIsCustom.off();
if (val === Permission.NoAccess) {
- setValue("permissions.workspace", { create: false }, { shouldDirty: true });
+ setValue("permissions.project", { create: false }, { shouldDirty: true });
}
};
@@ -95,8 +95,8 @@ export const OrgRoleWorkspaceRow = ({ isEditable, control, setValue }: Props) =>
{PERMISSION_ACTIONS.map(({ action, label }) => {
return (
<Controller
- name={`permissions.workspace.${action}`}
- key={`permissions.workspace.${action}`}
+ name={`permissions.project.${action}`}
+ key={`permissions.project.${action}`}
control={control}
render={({ field }) => (
<Checkbox
diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionRow.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionRow.tsx
index 0254e8240e..8712185761 100644
--- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionRow.tsx
+++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionRow.tsx
@@ -65,10 +65,11 @@ type Props = {
title: string;
formName: keyof Omit<
Exclude<TFormSchema["permissions"], undefined>,
- | "workspace"
+ | "project"
| "organization-admin-console"
| "kmip"
| "gateway"
+ | "relay"
| "secret-share"
| "billing"
| "audit-logs"
diff --git a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx
index 3b606cbb15..0fa704757c 100644
--- a/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx
+++ b/frontend/src/pages/organization/RoleByIDPage/components/RolePermissionsSection/RolePermissionsSection.tsx
@@ -23,6 +23,7 @@ import { OrgPermissionGroupRow } from "./OrgPermissionGroupRow";
import { OrgPermissionIdentityRow } from "./OrgPermissionIdentityRow";
import { OrgPermissionKmipRow } from "./OrgPermissionKmipRow";
import { OrgPermissionMachineIdentityAuthTemplateRow } from "./OrgPermissionMachineIdentityAuthTemplateRow";
+import { OrgRelayPermissionRow } from "./OrgPermissionRelayRow";
import { OrgPermissionSecretShareRow } from "./OrgPermissionSecretShareRow";
import { OrgRoleWorkspaceRow } from "./OrgRoleWorkspaceRow";
import { RolePermissionRow } from "./RolePermissionRow";
@@ -188,6 +189,11 @@ export const RolePermissionsSection = ({ roleId }: Props) => {
setValue={setValue}
isEditable={isCustomRole}
/>
+ <OrgRelayPermissionRow
+ control={control}
+ setValue={setValue}
+ isEditable={isCustomRole}
+ />
<OrgPermissionBillingRow
control={control}
setValue={setValue}
diff --git a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx
index 6de5a0ecf3..f59ae23aa5 100644
--- a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AuditLogStreamForm.tsx
@@ -6,6 +6,7 @@ import { TAuditLogStream } from "@app/hooks/api/types";
import { DiscriminativePick } from "@app/types";
import { AuditLogStreamHeader } from "../components/AuditLogStreamHeader";
+import { AzureProviderAuditLogStreamForm } from "./AzureProviderAuditLogStreamForm";
import { CriblProviderAuditLogStreamForm } from "./CriblProviderAuditLogStreamForm";
import { CustomProviderAuditLogStreamForm } from "./CustomProviderAuditLogStreamForm";
import { DatadogProviderAuditLogStreamForm } from "./DatadogProviderAuditLogStreamForm";
@@ -45,6 +46,8 @@ const CreateForm = ({ provider, onComplete }: CreateFormProps) => {
};
switch (provider) {
+ case LogProvider.Azure:
+ return <AzureProviderAuditLogStreamForm onSubmit={onSubmit} />;
case LogProvider.Cribl:
return <CriblProviderAuditLogStreamForm onSubmit={onSubmit} />;
case LogProvider.Custom:
@@ -86,6 +89,10 @@ const UpdateForm = ({ auditLogStream, onComplete }: UpdateFormProps) => {
};
switch (auditLogStream.provider) {
+ case LogProvider.Azure:
+ return (
+ <AzureProviderAuditLogStreamForm onSubmit={onSubmit} auditLogStream={auditLogStream} />
+ );
case LogProvider.Cribl:
return (
<CriblProviderAuditLogStreamForm onSubmit={onSubmit} auditLogStream={auditLogStream} />
diff --git a/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AzureProviderAuditLogStreamForm.tsx b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AzureProviderAuditLogStreamForm.tsx
new file mode 100644
index 0000000000..131ea1c85a
--- /dev/null
+++ b/frontend/src/pages/organization/SettingsPage/components/AuditLogStreamTab/AuditLogStreamForm/AzureProviderAuditLogStreamForm.tsx
@@ -0,0 +1,158 @@
+import { Controller, FormProvider, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { z } from "zod";
+
+import { Button, FormControl, Input, ModalClose, SecretInput } from "@app/components/v2";
+import { LogProvider } from "@app/hooks/api/auditLogStreams/enums";
+import { TAzureProviderLogStream } from "@app/hooks/api/auditLogStreams/types/providers/azure-provider";
+
+type Props = {
+ auditLogStream?: TAzureProviderLogStream;
+ onSubmit: (formData: FormData) => void;
+};
+
+const formSchema = z.object({
+ provider: z.literal(LogProvider.Azure),
+ credentials: z.object({
+ tenantId: z.string().trim().uuid(),
+ clientId: z.string().trim().uuid(),
+ clientSecret: z.string().trim().length(40),
+ dceUrl: z.string().trim().url().min(1).max(255),
+ dcrId: z
+ .string()
+ .trim()
+ .regex(/^dcr-[0-9a-f]{32}$/, "DCR ID must be in dcr-*** format"),
+ cltName: z.string().trim().min(1).max(255)
+ })
+});
+
+type FormData = z.infer<typeof formSchema>;
+
+export const AzureProviderAuditLogStreamForm = ({ auditLogStream, onSubmit }: Props) => {
+ const isUpdate = Boolean(auditLogStream);
+
+ const form = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: auditLogStream ?? {
+ provider: LogProvider.Azure
+ }
+ });
+
+ const {
+ handleSubmit,
+ control,
+ formState: { isSubmitting, isDirty }
+ } = form;
+
+ return (
+ <FormProvider {...form}>
+ <form onSubmit={handleSubmit(onSubmit)}>
+ <Controller
+ name="credentials.tenantId"
+ control={control}
+ shouldUnregister
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Tenant ID"
+ >
+ <Input {...field} placeholder="00000000-0000-0000-0000-000000000000" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.clientId"
+ control={control}
+ shouldUnregister
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Client ID"
+ >
+ <Input {...field} placeholder="00000000-0000-0000-0000-000000000000" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.clientSecret"
+ control={control}
+ shouldUnregister
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Client Secret"
+ >
+ <SecretInput
+ containerClassName="text-gray-400 group-focus-within:!border-primary-400/50 border border-mineshaft-500 bg-mineshaft-900 px-2.5 py-1.5"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.dceUrl"
+ control={control}
+ shouldUnregister
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Data Collection Endpoint URL"
+ >
+ <Input {...field} placeholder="https://example.eastus-1.ingest.monitor.azure.com" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.dcrId"
+ control={control}
+ shouldUnregister
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Data Collection Rule Immutable ID"
+ >
+ <Input {...field} placeholder="dcr-00000000000000000000000000000000" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ name="credentials.cltName"
+ control={control}
+ shouldUnregister
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Custom Log Table Name"
+ >
+ <Input {...field} placeholder="InfisicalLogs" />
+ </FormControl>
+ )}
+ />
+ <div className="mt-8 flex items-center">
+ <Button
+ className="mr-4"
+ size="sm"
+ type="submit"
+ colorSchema="secondary"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting || !isDirty}
+ >
+ {isUpdate ? "Update Credentials" : "Create Log Stream"}
+ </Button>
+ <ModalClose asChild>
+ <Button colorSchema="secondary" variant="plain">
+ Cancel
+ </Button>
+ </ModalClose>
+ </div>
+ </form>
+ </FormProvider>
+ );
+};
diff --git a/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/ExternalMigrationsTab.tsx b/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/ExternalMigrationsTab.tsx
index 6ca1a5c28b..8c6d511b11 100644
--- a/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/ExternalMigrationsTab.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/ExternalMigrationsTab/ExternalMigrationsTab.tsx
@@ -1,9 +1,8 @@
import { faArrowUpRightFromSquare, faBookOpen, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { OrgPermissionCan } from "@app/components/permissions";
import { Button } from "@app/components/v2";
-import { OrgPermissionActions, OrgPermissionSubjects, useOrgPermission } from "@app/context";
+import { useOrgPermission } from "@app/context";
import { usePopUp } from "@app/hooks";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
@@ -15,52 +14,45 @@ export const ExternalMigrationsTab = () => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["selectImportPlatform"] as const);
return (
- <OrgPermissionCan
- I={OrgPermissionActions.Create}
- a={OrgPermissionSubjects.Workspace}
- renderGuardBanner
- passThrough={false}
- >
- <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
- <div className="flex justify-between">
- <div className="flex items-center gap-2">
- <p className="text-xl font-semibold text-mineshaft-100">Import from external source</p>
-
- <div>
- <a
- target="_blank"
- rel="noopener noreferrer"
- href="https://infisical.com/docs/documentation/platform/external-migrations/overview"
- >
- <div className="ml-2 inline-block rounded-md bg-yellow/20 px-1.5 pb-[0.03rem] pt-[0.04rem] text-sm text-yellow opacity-80 hover:opacity-100">
- <FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
- Docs
- <FontAwesomeIcon
- icon={faArrowUpRightFromSquare}
- className="mb-[0.07rem] ml-1.5 text-xxs"
- />
- </div>
- </a>
- </div>
+ <div className="rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
+ <div className="flex justify-between">
+ <div className="flex items-center gap-2">
+ <p className="text-xl font-semibold text-mineshaft-100">Import from external source</p>
+
+ <div>
+ <a
+ target="_blank"
+ rel="noopener noreferrer"
+ href="https://infisical.com/docs/documentation/platform/external-migrations/overview"
+ >
+ <div className="ml-2 inline-block rounded-md bg-yellow/20 px-1.5 pb-[0.03rem] pt-[0.04rem] text-sm text-yellow opacity-80 hover:opacity-100">
+ <FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
+ Docs
+ <FontAwesomeIcon
+ icon={faArrowUpRightFromSquare}
+ className="mb-[0.07rem] ml-1.5 text-xxs"
+ />
+ </div>
+ </a>
</div>
-
- <Button
- onClick={() => {
- handlePopUpOpen("selectImportPlatform");
- }}
- isDisabled={membership?.role !== ProjectMembershipRole.Admin}
- leftIcon={<FontAwesomeIcon icon={faPlus} />}
- >
- Import
- </Button>
</div>
- <p className="mb-4 text-gray-400">Import data from another platform to Infisical.</p>
- <SelectImportFromPlatformModal
- isOpen={popUp.selectImportPlatform.isOpen}
- onToggle={(state) => handlePopUpToggle("selectImportPlatform", state)}
- />
+ <Button
+ onClick={() => {
+ handlePopUpOpen("selectImportPlatform");
+ }}
+ isDisabled={membership?.role !== ProjectMembershipRole.Admin}
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ >
+ Import
+ </Button>
</div>
- </OrgPermissionCan>
+ <p className="mb-4 text-gray-400">Import data from another platform to Infisical.</p>
+
+ <SelectImportFromPlatformModal
+ isOpen={popUp.selectImportPlatform.isOpen}
+ onToggle={(state) => handlePopUpToggle("selectImportPlatform", state)}
+ />
+ </div>
);
};
diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx
index c3ecdfa79a..08d350c9c8 100644
--- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/EditProjectTemplateSection/components/EditProjectTemplate.tsx
@@ -7,8 +7,8 @@ import { Button, DeleteActionModal } from "@app/components/v2";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context";
import { getProjectTitle } from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { TProjectTemplate, useDeleteProjectTemplate } from "@app/hooks/api/projectTemplates";
-import { ProjectType } from "@app/hooks/api/workspace/types";
import { ProjectTemplateDetailsModal } from "../../ProjectTemplateDetailsModal";
import { ProjectTemplateEnvironmentsForm } from "./ProjectTemplateEnvironmentsForm";
diff --git a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx
index 3c5e138e3c..ad4f2776af 100644
--- a/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx
+++ b/frontend/src/pages/organization/SettingsPage/components/ProjectTemplatesTab/components/ProjectTemplateDetailsModal.tsx
@@ -15,12 +15,12 @@ import {
TextArea
} from "@app/components/v2";
import { getProjectLottieIcon } from "@app/helpers/project";
+import { ProjectType } from "@app/hooks/api/projects/types";
import {
TProjectTemplate,
useCreateProjectTemplate,
useUpdateProjectTemplate
} from "@app/hooks/api/projectTemplates";
-import { ProjectType } from "@app/hooks/api/workspace/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx
index bd19db761f..572be1d817 100644
--- a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx
+++ b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserAddToProjectModal.tsx
@@ -9,9 +9,9 @@ import { useOrganization } from "@app/context";
import {
useAddUserToWsNonE2EE,
useGetOrgMembershipProjectMemberships,
- useGetUserWorkspaces
+ useGetUserProjects
} from "@app/hooks/api";
-import { ProjectVersion } from "@app/hooks/api/workspace/types";
+import { ProjectVersion } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
const schema = z
@@ -34,7 +34,7 @@ type Props = {
const UserAddToProjectModalChild = ({ membershipId, popUp, handlePopUpToggle }: Props) => {
const { currentOrg } = useOrganization();
const orgId = currentOrg?.id || "";
- const { data: workspaces = [] } = useGetUserWorkspaces();
+ const { data: workspaces = [] } = useGetUserProjects();
const { mutateAsync: addUserToWorkspaceNonE2EE } = useAddUserToWsNonE2EE();
diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectRow.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectRow.tsx
index aac501fce0..a7a88a72c4 100644
--- a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectRow.tsx
+++ b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectRow.tsx
@@ -7,7 +7,7 @@ import { createNotification } from "@app/components/notifications";
import { IconButton, Td, Tooltip, Tr } from "@app/components/v2";
import { getProjectBaseURL } from "@app/helpers/project";
import { formatProjectRoleName } from "@app/helpers/roles";
-import { useGetUserWorkspaces } from "@app/hooks/api";
+import { useGetUserProjects } from "@app/hooks/api";
import { TWorkspaceUser } from "@app/hooks/api/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { OrgAccessControlTabSections } from "@app/types/org";
@@ -24,7 +24,7 @@ export const UserProjectRow = ({
membership: { id, project, user, roles },
handlePopUpOpen
}: Props) => {
- const { data: workspaces = [] } = useGetUserWorkspaces();
+ const { data: workspaces = [] } = useGetUserProjects();
const navigate = useNavigate();
const isAccessible = useMemo(() => {
diff --git a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectsSection.tsx b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectsSection.tsx
index c93e1fa8be..e06ed390d0 100644
--- a/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectsSection.tsx
+++ b/frontend/src/pages/organization/UserDetailsByIDPage/components/UserProjectsSection/UserProjectsSection.tsx
@@ -32,7 +32,7 @@ export const UserProjectsSection = ({ membershipId }: Props) => {
const handleRemoveUser = async (projectId: string, username: string) => {
try {
- await removeUserFromWorkspace({ workspaceId: projectId, usernames: [username], orgId });
+ await removeUserFromWorkspace({ projectId, usernames: [username], orgId });
createNotification({
text: "Successfully removed user from project",
type: "success"
diff --git a/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx b/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx
index 8bb007e889..9da8770d22 100644
--- a/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx
+++ b/frontend/src/pages/project/AccessControlPage/AccessControlPage.tsx
@@ -3,9 +3,9 @@ import { useTranslation } from "react-i18next";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
-import { ProjectType } from "@app/hooks/api/workspace/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectAccessControlTabs } from "@app/types/project";
import {
@@ -18,7 +18,7 @@ import {
const Page = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const selectedTab = useSearch({
strict: false,
select: (el) => el.selectedTab
@@ -26,15 +26,15 @@ const Page = () => {
const updateSelectedTab = (tab: string) => {
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/access-management` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/access-management` as const,
search: (prev) => ({ ...prev, selectedTab: tab }),
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}
});
};
- const isSecretManager = currentWorkspace.type === ProjectType.SecretManager;
+ const isSecretManager = currentProject.type === ProjectType.SecretManager;
return (
<div className="container mx-auto flex flex-col justify-between bg-bunker-800 text-white">
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx
index f909f92b44..a279bd1b01 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupModal.tsx
@@ -6,7 +6,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FilterableSelect, FormControl, Modal, ModalContent } from "@app/components/v2";
-import { useOrganization, useWorkspace } from "@app/context";
+import { useOrganization, useProject } from "@app/context";
import {
useAddGroupToWorkspace,
useGetOrganizationGroups,
@@ -31,14 +31,14 @@ type Props = {
const Content = ({ popUp, handlePopUpToggle }: Props) => {
const { currentOrg } = useOrganization();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const orgId = currentOrg?.id || "";
const { data: groups } = useGetOrganizationGroups(orgId);
- const { data: groupMemberships } = useListWorkspaceGroups(currentWorkspace?.id || "");
+ const { data: groupMemberships } = useListWorkspaceGroups(currentProject?.id || "");
- const { data: roles } = useGetProjectRoles(currentWorkspace?.id || "");
+ const { data: roles } = useGetProjectRoles(currentProject?.id || "");
const { mutateAsync: addGroupToWorkspaceMutateAsync } = useAddGroupToWorkspace();
@@ -64,7 +64,7 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => {
const onFormSubmit = async ({ group, role }: FormData) => {
try {
await addGroupToWorkspaceMutateAsync({
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
groupId: group.id,
role: role.slug || undefined
});
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx
index 91b6d31868..49ff350fd6 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupRoles.tsx
@@ -24,13 +24,13 @@ import {
Tag,
Tooltip
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { formatProjectRoleName } from "@app/helpers/roles";
import { usePopUp } from "@app/hooks";
import { useGetProjectRoles, useUpdateGroupWorkspaceRole } from "@app/hooks/api";
import { TGroupMembership } from "@app/hooks/api/groups/types";
+import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/projects/types";
import { TProjectRole } from "@app/hooks/api/roles/types";
-import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/workspace/types";
import { groupBy } from "@app/lib/fn/array";
const temporaryRoleFormSchema = z.object({
@@ -213,7 +213,7 @@ type FormProps = {
};
const GroupRolesForm = ({ projectRoles, roles, groupId, onClose }: FormProps) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [searchRoles, setSearchRoles] = useState("");
@@ -255,7 +255,7 @@ const GroupRolesForm = ({ projectRoles, roles, groupId, onClose }: FormProps) =>
try {
await updateGroupWorkspaceRole.mutateAsync({
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
groupId,
roles: selectedRoles
});
@@ -373,11 +373,11 @@ export const GroupRoles = ({
className,
popperContentProps
}: TMemberRolesProp) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { popUp, handlePopUpToggle } = usePopUp(["editRole"] as const);
const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(
- currentWorkspace?.id ?? ""
+ currentProject?.id ?? ""
);
return (
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx
index 5ba6082e18..ee23a57781 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsSection.tsx
@@ -8,8 +8,8 @@ import { Button, DeleteActionModal } from "@app/components/v2";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useSubscription,
- useWorkspace
+ useProject,
+ useSubscription
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteGroupFromWorkspace } from "@app/hooks/api";
@@ -19,7 +19,7 @@ import { GroupTable } from "./GroupsTable";
export const GroupsSection = () => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: deleteMutateAsync } = useDeleteGroupFromWorkspace();
@@ -44,7 +44,7 @@ export const GroupsSection = () => {
try {
await deleteMutateAsync({
groupId,
- projectId: currentWorkspace?.id || ""
+ projectId: currentProject?.id || ""
});
createNotification({
diff --git a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx
index 9bd98084eb..3ce5b40623 100644
--- a/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/GroupsTab/components/GroupsSection/GroupsTable.tsx
@@ -32,7 +32,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import {
getUserTablePreference,
@@ -61,7 +61,7 @@ enum GroupsOrderBy {
}
export const GroupTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
const {
@@ -85,7 +85,7 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
};
const { data: groupMemberships = [], isPending } = useListWorkspaceGroups(
- currentWorkspace?.id || ""
+ currentProject?.id || ""
);
const filteredGroupMemberships = useMemo(() => {
@@ -159,9 +159,9 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
onKeyDown={(evt) => {
if (evt.key === "Enter") {
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/groups/$groupId` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/groups/$groupId` as const,
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
groupId: id
}
});
@@ -169,9 +169,9 @@ export const GroupTable = ({ handlePopUpOpen }: Props) => {
}}
onClick={() =>
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/groups/$groupId` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/groups/$groupId` as const,
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
groupId: id
}
})
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx
index 5b6e773dbc..7fbe999345 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/IdentityTab.tsx
@@ -45,7 +45,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import { formatProjectRoleName } from "@app/helpers/roles";
import {
@@ -57,7 +57,7 @@ import { withProjectPermission } from "@app/hoc";
import { usePagination, useResetPageHelper } from "@app/hooks";
import { useDeleteIdentityFromWorkspace, useGetWorkspaceIdentityMemberships } from "@app/hooks/api";
import { OrderByDirection } from "@app/hooks/api/generic/types";
-import { ProjectIdentityOrderBy } from "@app/hooks/api/workspace/types";
+import { ProjectIdentityOrderBy } from "@app/hooks/api/projects/types";
import { usePopUp } from "@app/hooks/usePopUp";
import { IdentityModal } from "./components/IdentityModal";
@@ -66,7 +66,7 @@ const MAX_ROLES_TO_BE_SHOWN_IN_TABLE = 2;
export const IdentityTab = withProjectPermission(
() => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject, projectId } = useProject();
const navigate = useNavigate();
const {
@@ -92,11 +92,9 @@ export const IdentityTab = withProjectPermission(
setUserTablePreference("projectIdentityTable", PreferenceKey.PerPage, newPerPage);
};
- const workspaceId = currentWorkspace?.id ?? "";
-
const { data, isPending, isFetching } = useGetWorkspaceIdentityMemberships(
{
- workspaceId: currentWorkspace?.id || "",
+ projectId,
offset,
limit,
orderDirection,
@@ -126,7 +124,7 @@ export const IdentityTab = withProjectPermission(
try {
await deleteMutateAsync({
identityId,
- workspaceId
+ projectId
});
createNotification({
@@ -261,9 +259,9 @@ export const IdentityTab = withProjectPermission(
onKeyDown={(evt) => {
if (evt.key === "Enter") {
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/identities/$identityId` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/identities/$identityId` as const,
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
identityId: id
}
});
@@ -271,9 +269,9 @@ export const IdentityTab = withProjectPermission(
}}
onClick={() =>
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/identities/$identityId` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/identities/$identityId` as const,
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
identityId: id
}
})
diff --git a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx
index 1baf80b9b1..7261ba8394 100644
--- a/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/IdentityTab/components/IdentityModal.tsx
@@ -14,7 +14,7 @@ import {
ModalContent,
Spinner
} from "@app/components/v2";
-import { useOrganization, useWorkspace } from "@app/context";
+import { useOrganization, useProject } from "@app/context";
import {
useAddIdentityToWorkspace,
useGetIdentityMembershipOrgs,
@@ -37,10 +37,9 @@ type Props = {
const Content = ({ popUp, handlePopUpToggle }: Props) => {
const { currentOrg } = useOrganization();
- const { currentWorkspace } = useWorkspace();
+ const { projectId } = useProject();
const organizationId = currentOrg?.id || "";
- const workspaceId = currentWorkspace?.id || "";
const { data: identityMembershipOrgsData, isPending: isMembershipsLoading } =
useGetIdentityMembershipOrgs({
@@ -49,12 +48,12 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => {
});
const identityMembershipOrgs = identityMembershipOrgsData?.identityMemberships;
const { data: identityMembershipsData } = useGetWorkspaceIdentityMemberships({
- workspaceId,
+ projectId,
limit: 20000 // TODO: this is temp to preserve functionality for larger projects, will optimize in PR referenced above
});
const identityMemberships = identityMembershipsData?.identityMemberships;
- const { data: roles, isPending: isRolesLoading } = useGetProjectRoles(workspaceId);
+ const { data: roles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
const { mutateAsync: addIdentityToWorkspaceMutateAsync } = useAddIdentityToWorkspace();
@@ -80,7 +79,7 @@ const Content = ({ popUp, handlePopUpToggle }: Props) => {
const onFormSubmit = async ({ identity, role }: FormData) => {
try {
await addIdentityToWorkspaceMutateAsync({
- workspaceId,
+ projectId,
identityId: identity.id,
role: role.slug || undefined
});
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
index d9c9a87185..cdf49cf128 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
@@ -22,7 +22,7 @@ import {
OrgPermissionSubjects,
useOrganization,
useOrgPermission,
- useWorkspace
+ useProject
} from "@app/context";
import {
useAddUsersToOrg,
@@ -30,8 +30,8 @@ import {
useGetProjectRoles,
useGetWorkspaceUsers
} from "@app/hooks/api";
+import { ProjectVersion } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { ProjectVersion } from "@app/hooks/api/workspace/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
const addMemberFormSchema = z.object({
@@ -57,7 +57,7 @@ type Props = {
export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
const { t } = useTranslation();
const { currentOrg } = useOrganization();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate({ from: "" });
const { permission } = useOrgPermission();
const requesterEmail = useSearch({
@@ -66,12 +66,12 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
});
const orgId = currentOrg?.id || "";
- const workspaceId = currentWorkspace?.id || "";
+ const projectId = currentProject?.id || "";
- const { data: members } = useGetWorkspaceUsers(workspaceId);
+ const { data: members } = useGetWorkspaceUsers(projectId);
const { data: orgUsers } = useGetOrgUsers(orgId);
- const { data: roles } = useGetProjectRoles(currentWorkspace?.id || "");
+ const { data: roles } = useGetProjectRoles(currentProject?.id || "");
const {
control,
@@ -94,7 +94,7 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
}, [requesterEmail]);
const onAddMembers = async ({ orgMemberships, projectRoleSlugs }: TAddMemberForm) => {
- if (!currentWorkspace) return;
+ if (!currentProject) return;
if (!currentOrg?.id) return;
const existingMembers = orgMemberships.filter((membership) => !membership.isNewInvitee);
@@ -109,7 +109,7 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
if (!selectedMembers) return;
try {
- if (currentWorkspace.version === ProjectVersion.V1) {
+ if (currentProject.version === ProjectVersion.V1) {
createNotification({
type: "error",
text: "Please upgrade your project to invite new members to the project."
@@ -146,8 +146,8 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
organizationRoleSlug: ProjectMembershipRole.Member, // only applies to new invites
projects: [
{
- slug: currentWorkspace.slug,
- id: currentWorkspace.id,
+ slug: currentProject.slug,
+ id: currentProject.id,
projectRoleSlug: projectRoleSlugs.map((role) => role.slug)
}
]
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx
index d18f8715a1..291a5b58b6 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRbacSection.tsx
@@ -29,14 +29,14 @@ import {
ProjectPermissionActions,
ProjectPermissionMemberActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { useGetProjectRoles, useUpdateUserWorkspaceRole } from "@app/hooks/api";
+import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { TWorkspaceUser } from "@app/hooks/api/types";
-import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/workspace/types";
const roleFormSchema = z.object({
roles: z
@@ -64,9 +64,8 @@ type Props = {
};
export const MemberRbacSection = ({ projectMember, onOpenUpgradeModal }: Props) => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
- const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(workspaceId);
+ const { projectId } = useProject();
+ const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
const { permission } = useProjectPermission();
const isMemberEditDisabled = permission.cannot(
ProjectPermissionMemberActions.Edit,
@@ -130,7 +129,7 @@ export const MemberRbacSection = ({ projectMember, onOpenUpgradeModal }: Props)
try {
await updateMembershipRole.mutateAsync({
- workspaceId,
+ projectId,
membershipId: projectMember.id,
roles: sanitizedRoles
});
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRoleForm.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRoleForm.tsx
index 7352572938..187e1813a0 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRoleForm.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/MemberRoleForm.tsx
@@ -1,7 +1,7 @@
import { Link } from "@tanstack/react-router";
import { Alert, AlertDescription } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import { TWorkspaceUser } from "@app/hooks/api/types";
@@ -12,7 +12,7 @@ type Props = {
onOpenUpgradeModal: (title: string) => void;
};
export const MemberRoleForm = ({ projectMember, onOpenUpgradeModal }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
return (
<div>
<MemberRbacSection projectMember={projectMember} onOpenUpgradeModal={onOpenUpgradeModal} />
@@ -22,9 +22,9 @@ export const MemberRoleForm = ({ projectMember, onOpenUpgradeModal }: Props) =>
>
<AlertDescription>
<Link
- to={`${getProjectBaseURL(currentWorkspace.type)}/members/$membershipId` as const}
+ to={`${getProjectBaseURL(currentProject.type)}/members/$membershipId` as const}
params={{
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
membershipId: projectMember.id
}}
>
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx
index 5dd4397444..3e93ec3921 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MemberRoleForm/SpecificPrivilegeSection.tsx
@@ -43,8 +43,8 @@ import {
ProjectPermissionActions,
ProjectPermissionMemberActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { removeTrailingSlash } from "@app/helpers/string";
import { usePopUp } from "@app/hooks";
@@ -89,7 +89,7 @@ export const SpecificPrivilegeSecretForm = ({
secretPath?: string;
onClose?: () => void;
}) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
"deletePrivilege",
@@ -129,7 +129,7 @@ export const SpecificPrivilegeSecretForm = ({
temporaryAccess: privilege
}
: {
- environmentSlug: currentWorkspace.environments?.[0]?.slug,
+ environmentSlug: currentProject.environments?.[0]?.slug,
secretPath: initialSecretPath,
read: selectedActions.includes(ProjectPermissionActions.Read),
edit: selectedActions.includes(ProjectPermissionActions.Edit),
@@ -202,7 +202,7 @@ export const SpecificPrivilegeSecretForm = ({
// This is used for requesting access additional privileges, not directly creating a privilege!
const handleRequestAccess = async (data: TSecretPermissionForm) => {
if (!policies) return;
- if (!currentWorkspace) {
+ if (!currentProject) {
createNotification({
type: "error",
text: "No workspace found.",
@@ -253,7 +253,7 @@ export const SpecificPrivilegeSecretForm = ({
...(data.temporaryAccess.isTemporary && {
temporaryRange: data.temporaryAccess.temporaryRange
}),
- projectSlug: currentWorkspace.slug,
+ projectSlug: currentProject.slug,
isTemporary: data.temporaryAccess.isTemporary,
permissions: actions
.filter(({ allowed }) => allowed)
@@ -307,7 +307,7 @@ export const SpecificPrivilegeSecretForm = ({
position="popper"
dropdownContainerClassName="max-w-none"
>
- {currentWorkspace?.environments?.map(({ slug, id, name }) => (
+ {currentProject?.environments?.map(({ slug, id, name }) => (
<SelectItem value={slug} key={id}>
{name}
</SelectItem>
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx
index a8ecde73ae..da56164532 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersSection.tsx
@@ -9,7 +9,7 @@ import {
ProjectPermissionActions,
ProjectPermissionSub,
useOrganization,
- useWorkspace
+ useProject
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteUserFromWorkspace } from "@app/hooks/api";
@@ -19,7 +19,7 @@ import { MembersTable } from "./MembersTable";
export const MembersSection = () => {
const { currentOrg } = useOrganization();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: removeUserFromWorkspace } = useDeleteUserFromWorkspace();
@@ -32,11 +32,11 @@ export const MembersSection = () => {
const handleRemoveUser = async () => {
const username = (popUp?.removeMember?.data as { username: string })?.username;
if (!currentOrg?.id) return;
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
try {
await removeUserFromWorkspace({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
usernames: [username],
orgId: currentOrg.id
});
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx
index 2cbe144ee4..22eb50460b 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/MembersTable.tsx
@@ -44,12 +44,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import {
- ProjectPermissionActions,
- ProjectPermissionSub,
- useUser,
- useWorkspace
-} from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject, useUser } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import { formatProjectRoleName } from "@app/helpers/roles";
import {
@@ -81,7 +76,7 @@ type Filter = {
};
export const MembersTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { user } = useUser();
const navigate = useNavigate();
const [filter, setFilter] = useState<Filter>({
@@ -90,8 +85,8 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
const filterRoles = useMemo(() => filter.roles, [filter.roles]);
const userId = user?.id || "";
- const workspaceId = currentWorkspace?.id || "";
- const { data: projectRoles } = useGetProjectRoles(workspaceId);
+ const projectId = currentProject?.id || "";
+ const { data: projectRoles } = useGetProjectRoles(projectId);
const {
search,
@@ -116,7 +111,7 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
};
const { data: members = [], isPending: isMembersLoading } = useGetWorkspaceUsers(
- workspaceId,
+ projectId,
undefined,
filterRoles
);
@@ -312,9 +307,9 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
onKeyDown={(evt) => {
if (evt.key === "Enter") {
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/members/$membershipId`,
+ to: `${getProjectBaseURL(currentProject.type)}/members/$membershipId`,
params: {
- projectId: workspaceId,
+ projectId,
membershipId
}
});
@@ -322,9 +317,9 @@ export const MembersTable = ({ handlePopUpOpen }: Props) => {
}}
onClick={() =>
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/members/$membershipId`,
+ to: `${getProjectBaseURL(currentProject.type)}/members/$membershipId`,
params: {
- projectId: workspaceId,
+ projectId,
membershipId
}
})
diff --git a/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx b/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx
index 211f1d0e81..e7b3b10b8d 100644
--- a/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/ProjectRoleListTab/components/ProjectRoleList/ProjectRoleList.tsx
@@ -39,7 +39,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import { isCustomProjectRole } from "@app/helpers/roles";
import {
@@ -67,8 +67,8 @@ export const ProjectRoleList = () => {
"deleteRole",
"duplicateRole"
] as const);
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: roles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
@@ -250,9 +250,9 @@ export const ProjectRoleList = () => {
className="h-10 cursor-pointer transition-colors duration-100 hover:bg-mineshaft-700"
onClick={() =>
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/roles/$roleSlug`,
+ to: `${getProjectBaseURL(currentProject.type)}/roles/$roleSlug`,
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
roleSlug: slug
}
})
@@ -292,9 +292,9 @@ export const ProjectRoleList = () => {
onClick={(e) => {
e.stopPropagation();
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/roles/$roleSlug`,
+ to: `${getProjectBaseURL(currentProject.type)}/roles/$roleSlug`,
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
roleSlug: slug
}
});
diff --git a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx
index 8264d47bf6..d63b6bb9c8 100644
--- a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/AddServiceTokenModal.tsx
@@ -22,7 +22,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useToggle } from "@app/hooks";
import { useCreateServiceToken } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -70,7 +70,7 @@ type Props = {
const ServiceTokenForm = () => {
const { t } = useTranslation();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const {
control,
handleSubmit,
@@ -81,7 +81,7 @@ const ServiceTokenForm = () => {
scopes: [
{
secretPath: "/",
- environment: currentWorkspace?.environments?.[0]?.slug
+ environment: currentProject?.environments?.[0]?.slug
}
]
}
@@ -111,7 +111,7 @@ const ServiceTokenForm = () => {
const onFormSubmit = async ({ name, scopes, expiresIn, permissions }: FormData) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
const randomBytes = crypto.randomBytes(16).toString("hex");
@@ -122,7 +122,7 @@ const ServiceTokenForm = () => {
scopes,
expiresIn: Number(expiresIn),
name,
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
randomBytes,
permissions: Object.entries(permissions)
.filter(([, permissionsValue]) => permissionsValue)
@@ -172,7 +172,7 @@ const ServiceTokenForm = () => {
<Controller
control={control}
name={`scopes.${index}.environment`}
- defaultValue={currentWorkspace?.environments?.[0]?.slug}
+ defaultValue={currentProject?.environments?.[0]?.slug}
render={({ field: { onChange, ...field }, fieldState: { error } }) => (
<FormControl
className="mb-0"
@@ -186,7 +186,7 @@ const ServiceTokenForm = () => {
onValueChange={(e) => onChange(e)}
className="w-full"
>
- {currentWorkspace?.environments.map(({ name, slug }) => (
+ {currentProject?.environments.map(({ name, slug }) => (
<SelectItem value={slug} key={slug}>
{name}
</SelectItem>
@@ -225,7 +225,7 @@ const ServiceTokenForm = () => {
variant="outline_bg"
onClick={() =>
append({
- environment: currentWorkspace?.environments?.[0]?.slug || "",
+ environment: currentProject?.environments?.[0]?.slug || "",
secretPath: ""
})
}
@@ -334,7 +334,7 @@ const ServiceTokenForm = () => {
export const AddServiceTokenModal = ({ popUp, handlePopUpToggle }: Props) => {
const { t } = useTranslation();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
return (
<Modal
@@ -346,7 +346,7 @@ export const AddServiceTokenModal = ({ popUp, handlePopUpToggle }: Props) => {
<ModalContent
title={
t("section.token.add-dialog.title", {
- target: currentWorkspace?.name
+ target: currentProject?.name
}) as string
}
subTitle={t("section.token.add-dialog.description") as string}
diff --git a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx
index 4f364b6b63..5c0c70ebb1 100644
--- a/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/ServiceTokenTab/components/ServiceTokenSection/ServiceTokenTable.tsx
@@ -33,7 +33,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import {
getUserTablePreference,
PreferenceKey,
@@ -63,9 +63,9 @@ enum TokensOrderBy {
}
export const ServiceTokenTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data, isPending } = useGetUserWsServiceTokens({
- workspaceID: currentWorkspace?.id || ""
+ workspaceID: currentProject?.id || ""
});
const {
diff --git a/frontend/src/pages/project/AppConnectionsPage/AppConnectionsPage.tsx b/frontend/src/pages/project/AppConnectionsPage/AppConnectionsPage.tsx
new file mode 100644
index 0000000000..84fb69b832
--- /dev/null
+++ b/frontend/src/pages/project/AppConnectionsPage/AppConnectionsPage.tsx
@@ -0,0 +1,41 @@
+import { Helmet } from "react-helmet";
+
+import { PageHeader } from "@app/components/v2";
+import { useProject } from "@app/context";
+import {
+ ProjectPermissionAppConnectionActions,
+ ProjectPermissionSub
+} from "@app/context/ProjectPermissionContext/types";
+import { withProjectPermission } from "@app/hoc";
+import { AppConnectionsTable } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
+
+export const AppConnectionsPage = withProjectPermission(
+ () => {
+ const { currentProject } = useProject();
+
+ return (
+ <div className="bg-bunker-800">
+ <Helmet>
+ <title>Infisical | App Connections</title>
+ <link rel="icon" href="/infisical.ico" />
+ <meta property="og:image" content="/images/message.png" />
+ </Helmet>
+ <div className="flex w-full justify-center bg-bunker-800 text-white">
+ <div className="w-full max-w-7xl">
+ <PageHeader
+ className="w-full"
+ title="App Connections"
+ description="Manage project App Connections"
+ />
+
+ <AppConnectionsTable projectId={currentProject.id} projectType={currentProject.type} />
+ </div>
+ </div>
+ </div>
+ );
+ },
+ {
+ action: ProjectPermissionAppConnectionActions.Read,
+ subject: ProjectPermissionSub.AppConnections
+ }
+);
diff --git a/frontend/src/pages/project/AppConnectionsPage/route-cert-manager.tsx b/frontend/src/pages/project/AppConnectionsPage/route-cert-manager.tsx
new file mode 100644
index 0000000000..8be255e73b
--- /dev/null
+++ b/frontend/src/pages/project/AppConnectionsPage/route-cert-manager.tsx
@@ -0,0 +1,19 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AppConnectionsPage } from "./AppConnectionsPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections"
+)({
+ component: AppConnectionsPage,
+ beforeLoad: ({ context }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "App Connections"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/AppConnectionsPage/route-secret-manager.tsx b/frontend/src/pages/project/AppConnectionsPage/route-secret-manager.tsx
new file mode 100644
index 0000000000..2767c8689c
--- /dev/null
+++ b/frontend/src/pages/project/AppConnectionsPage/route-secret-manager.tsx
@@ -0,0 +1,19 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AppConnectionsPage } from "./AppConnectionsPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/app-connections"
+)({
+ component: AppConnectionsPage,
+ beforeLoad: ({ context }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "App Connections"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/AppConnectionsPage/route-secret-scanning.tsx b/frontend/src/pages/project/AppConnectionsPage/route-secret-scanning.tsx
new file mode 100644
index 0000000000..7249264959
--- /dev/null
+++ b/frontend/src/pages/project/AppConnectionsPage/route-secret-scanning.tsx
@@ -0,0 +1,19 @@
+import { createFileRoute } from "@tanstack/react-router";
+
+import { AppConnectionsPage } from "./AppConnectionsPage";
+
+export const Route = createFileRoute(
+ "/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/app-connections"
+)({
+ component: AppConnectionsPage,
+ beforeLoad: ({ context }) => {
+ return {
+ breadcrumbs: [
+ ...context.breadcrumbs,
+ {
+ label: "App Connections"
+ }
+ ]
+ };
+ }
+});
diff --git a/frontend/src/pages/project/AuditLogsPage/AuditLogsPage.tsx b/frontend/src/pages/project/AuditLogsPage/AuditLogsPage.tsx
index 0c83b05204..1e9b1ad547 100644
--- a/frontend/src/pages/project/AuditLogsPage/AuditLogsPage.tsx
+++ b/frontend/src/pages/project/AuditLogsPage/AuditLogsPage.tsx
@@ -1,11 +1,11 @@
import { Helmet } from "react-helmet";
import { PageHeader } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { LogsSection } from "@app/pages/organization/AuditLogsPage/components";
export const AuditLogsPage = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
return (
<div className="container mx-auto flex flex-col justify-between bg-bunker-800 text-white">
@@ -19,7 +19,7 @@ export const AuditLogsPage = () => {
title="Audit logs"
description="Audit logs for security and compliance teams to monitor information access."
/>
- <LogsSection pageView project={currentWorkspace} />
+ <LogsSection pageView project={currentProject} />
</div>
</div>
</div>
diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx
index a3dfabcd01..d6bda7ea10 100644
--- a/frontend/src/pages/project/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/GroupDetailsByIDPage/GroupDetailsByIDPage.tsx
@@ -4,8 +4,8 @@ import { useParams } from "@tanstack/react-router";
import { ProjectPermissionCan } from "@app/components/permissions";
import { EmptyState, PageHeader, Spinner } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
-import { useGetWorkspaceGroupMembershipDetails } from "@app/hooks/api/workspace/queries";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
+import { useGetWorkspaceGroupMembershipDetails } from "@app/hooks/api/projects/queries";
import { GroupDetailsSection } from "./components/GroupDetailsSection";
import { GroupMembersSection } from "./components/GroupMembersSection";
@@ -16,10 +16,10 @@ const Page = () => {
select: (el) => el.groupId as string
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: groupMembership, isPending } = useGetWorkspaceGroupMembershipDetails(
- currentWorkspace.id,
+ currentProject.id,
groupId
);
diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx
index 90c3270673..0689d674ad 100644
--- a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx
+++ b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupDetailsSection.tsx
@@ -14,7 +14,7 @@ import {
IconButton
} from "@app/components/v2";
import { CopyButton } from "@app/components/v2/CopyButton";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
import { useDeleteGroupFromWorkspace } from "@app/hooks/api";
@@ -31,14 +31,14 @@ export const GroupDetailsSection = ({ groupMembership }: Props) => {
] as const);
const { mutateAsync: deleteMutateAsync } = useDeleteGroupFromWorkspace();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
const onRemoveGroupSubmit = async () => {
try {
await deleteMutateAsync({
groupId: groupMembership.group.id,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
});
createNotification({
@@ -47,9 +47,9 @@ export const GroupDetailsSection = ({ groupMembership }: Props) => {
});
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/access-management`,
+ to: `${getProjectBaseURL(currentProject.type)}/access-management`,
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: "groups"
diff --git a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx
index 7d155ba43c..1df989602d 100644
--- a/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx
+++ b/frontend/src/pages/project/GroupDetailsByIDPage/components/GroupMembersSection/GroupMembersTable.tsx
@@ -23,7 +23,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { getProjectHomePage } from "@app/helpers/project";
import {
getUserTablePreference,
@@ -69,12 +69,12 @@ export const GroupMembersTable = ({ groupMembership }: Props) => {
setUserTablePreference("projectGroupMembersTable", PreferenceKey.PerPage, newPerPage);
};
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: groupMemberships, isPending } = useListProjectGroupUsers({
id: groupMembership.group.id,
groupSlug: groupMembership.group.slug,
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
offset,
limit: perPage,
search,
@@ -127,7 +127,7 @@ export const GroupMembersTable = ({ groupMembership }: Props) => {
{
actorId: userId,
actorType: ActorType.USER,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
{
onSuccess: () => {
@@ -136,8 +136,8 @@ export const GroupMembersTable = ({ groupMembership }: Props) => {
text: "User privilege assumption has started"
});
- const url = getProjectHomePage(currentWorkspace.type, currentWorkspace.environments);
- window.location.href = url.replace("$projectId", currentWorkspace.id);
+ const url = getProjectHomePage(currentProject.type, currentProject.environments);
+ window.location.href = url.replace("$projectId", currentProject.id);
}
}
);
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
index e1da4edabf..993320e562 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/IdentityDetailsByIDPage.tsx
@@ -18,7 +18,7 @@ import {
ProjectPermissionActions,
ProjectPermissionIdentityActions,
ProjectPermissionSub,
- useWorkspace
+ useProject
} from "@app/context";
import { getProjectBaseURL, getProjectHomePage } from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
@@ -38,12 +38,10 @@ const Page = () => {
strict: false,
select: (el) => el.identityId as string
});
- const { currentWorkspace } = useWorkspace();
-
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject, projectId } = useProject();
const { data: identityMembershipDetails, isPending: isMembershipDetailsLoading } =
- useGetWorkspaceIdentityMembershipDetails(workspaceId, identityId);
+ useGetWorkspaceIdentityMembershipDetails(projectId, identityId);
const { mutateAsync: deleteMutateAsync, isPending: isDeletingIdentity } =
useDeleteIdentityFromWorkspace();
@@ -59,7 +57,7 @@ const Page = () => {
{
actorId: identityId,
actorType: ActorType.IDENTITY,
- projectId: workspaceId
+ projectId
},
{
onSuccess: () => {
@@ -67,8 +65,8 @@ const Page = () => {
type: "success",
text: "Identity privilege assumption has started"
});
- const url = getProjectHomePage(currentWorkspace.type, currentWorkspace.environments);
- window.location.href = url.replace("$projectId", currentWorkspace.id);
+ const url = getProjectHomePage(currentProject.type, currentProject.environments);
+ window.location.href = url.replace("$projectId", currentProject.id);
}
}
);
@@ -78,7 +76,7 @@ const Page = () => {
try {
await deleteMutateAsync({
identityId,
- workspaceId
+ projectId
});
createNotification({
text: "Successfully removed identity from project",
@@ -86,9 +84,9 @@ const Page = () => {
});
handlePopUpClose("deleteIdentity");
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/access-management` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/access-management` as const,
params: {
- projectId: workspaceId
+ projectId
},
search: {
selectedTab: "identities"
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx
index fe574a32db..9b4be2cb8d 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityProjectAdditionalPrivilegeSection/IdentityProjectAdditionalPrivilegeModifySection.tsx
@@ -24,8 +24,8 @@ import {
import {
ProjectPermissionIdentityActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import {
useCreateIdentityProjectAdditionalPrivilege,
@@ -78,8 +78,8 @@ export const IdentityProjectAdditionalPrivilegeModifySection = ({
isDisabled
}: Props) => {
const isCreate = !privilegeId;
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: privilegeDetails, isPending } = useGetIdentityProjectPrivilegeDetails({
identityId,
projectId,
@@ -225,7 +225,7 @@ export const IdentityProjectAdditionalPrivilegeModifySection = ({
>
Save
</Button>
- <AddPoliciesButton isDisabled={isDisabled} projectType={currentWorkspace.type} />
+ <AddPoliciesButton isDisabled={isDisabled} projectType={currentProject.type} />
</div>
</div>
</div>
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx
index 1fa98628e9..eb8653acba 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleDetailsSection.tsx
@@ -23,7 +23,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { formatProjectRoleName } from "@app/helpers/roles";
import { usePopUp } from "@app/hooks";
import { useUpdateIdentityWorkspaceRole } from "@app/hooks/api";
@@ -41,7 +41,7 @@ export const IdentityRoleDetailsSection = ({
identityMembershipDetails,
isMembershipDetailsLoading
}: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
"deleteRole",
"modifyRole"
@@ -53,7 +53,7 @@ export const IdentityRoleDetailsSection = ({
try {
const updatedRoles = identityMembershipDetails?.roles?.filter((el) => el.id !== id);
await updateIdentityWorkspaceRole({
- workspaceId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
identityId: identityMembershipDetails.identity.id,
roles: updatedRoles.map(
({
diff --git a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx
index c5860ec11f..d47f4a74e1 100644
--- a/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx
+++ b/frontend/src/pages/project/IdentityDetailsByIDPage/components/IdentityRoleDetailsSection/IdentityRoleModify.tsx
@@ -29,13 +29,13 @@ import {
ProjectPermissionActions,
ProjectPermissionIdentityActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { useGetProjectRoles, useUpdateIdentityWorkspaceRole } from "@app/hooks/api";
import { IdentityMembership } from "@app/hooks/api/identities/types";
+import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/workspace/types";
const roleFormSchema = z.object({
roles: z
@@ -62,9 +62,8 @@ type Props = {
};
export const IdentityRoleModify = ({ identityProjectMembership }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
- const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(workspaceId);
+ const { projectId } = useProject();
+ const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
const { permission } = useProjectPermission();
const isIdentityEditDisabled = permission.cannot(
ProjectPermissionIdentityActions.Edit,
@@ -117,7 +116,7 @@ export const IdentityRoleModify = ({ identityProjectMembership }: Props) => {
try {
await updateIdentityWorkspaceRole.mutateAsync({
- workspaceId,
+ projectId,
identityId: identityProjectMembership.identity.id,
roles: sanitizedRoles
});
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
index 7fadf2cb9b..23b8299daf 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/MemberDetailsByIDPage.tsx
@@ -19,7 +19,7 @@ import {
ProjectPermissionMemberActions,
ProjectPermissionSub,
useOrganization,
- useWorkspace
+ useProject
} from "@app/context";
import { getProjectBaseURL, getProjectHomePage } from "@app/helpers/project";
import { usePopUp } from "@app/hooks";
@@ -40,12 +40,10 @@ export const Page = () => {
select: (el) => el.membershipId as string
});
const { currentOrg } = useOrganization();
- const { currentWorkspace } = useWorkspace();
-
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject, projectId } = useProject();
const { data: membershipDetails, isPending: isMembershipDetailsLoading } =
- useGetWorkspaceUserDetails(workspaceId, membershipId);
+ useGetWorkspaceUserDetails(projectId, membershipId);
const { mutateAsync: removeUserFromWorkspace, isPending: isRemovingUserFromWorkspace } =
useDeleteUserFromWorkspace();
@@ -63,7 +61,7 @@ export const Page = () => {
{
actorId: userId,
actorType: ActorType.USER,
- projectId: workspaceId
+ projectId
},
{
onSuccess: () => {
@@ -72,19 +70,19 @@ export const Page = () => {
text: "User privilege assumption has started"
});
- const url = getProjectHomePage(currentWorkspace.type, currentWorkspace.environments);
- window.location.href = url.replace("$projectId", currentWorkspace.id);
+ const url = getProjectHomePage(currentProject.type, currentProject.environments);
+ window.location.href = url.replace("$projectId", currentProject.id);
}
}
);
};
const handleRemoveUser = async () => {
- if (!currentOrg?.id || !currentWorkspace?.id || !membershipDetails?.user?.username) return;
+ if (!currentOrg?.id || !currentProject?.id || !membershipDetails?.user?.username) return;
try {
await removeUserFromWorkspace({
- workspaceId: currentWorkspace.id,
+ projectId,
usernames: [membershipDetails?.user?.username],
orgId: currentOrg.id
});
@@ -93,9 +91,9 @@ export const Page = () => {
type: "success"
});
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/access-management` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/access-management` as const,
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}
});
} catch (error) {
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx
index 9817aefdb7..6fa54247ff 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberProjectAdditionalPrivilegeSection/MembershipProjectAdditionalPrivilegeModifySection.tsx
@@ -23,8 +23,8 @@ import {
import {
ProjectPermissionMemberActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import {
useCreateProjectUserAdditionalPrivilege,
@@ -77,8 +77,8 @@ export const MembershipProjectAdditionalPrivilegeModifySection = ({
isDisabled
}: Props) => {
const isCreate = !privilegeId;
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: privilegeDetails, isPending } = useGetProjectUserPrivilegeDetails(
privilegeId || ""
);
@@ -221,7 +221,7 @@ export const MembershipProjectAdditionalPrivilegeModifySection = ({
>
Save
</Button>
- <AddPoliciesButton isDisabled={isDisabled} projectType={currentWorkspace.type} />
+ <AddPoliciesButton isDisabled={isDisabled} projectType={currentProject.type} />
</div>
</div>
</div>
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx
index 5ff78360dc..012141c038 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleDetailsSection.tsx
@@ -22,12 +22,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import {
- ProjectPermissionActions,
- ProjectPermissionSub,
- useUser,
- useWorkspace
-} from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject, useUser } from "@app/context";
import { formatProjectRoleName } from "@app/helpers/roles";
import { usePopUp } from "@app/hooks";
import { useUpdateUserWorkspaceRole } from "@app/hooks/api";
@@ -49,7 +44,7 @@ export const MemberRoleDetailsSection = ({
}: Props) => {
const { user } = useUser();
const userId = user?.id;
- const { currentWorkspace } = useWorkspace();
+ const { projectId } = useProject();
const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
"deleteRole",
"modifyRole"
@@ -63,7 +58,7 @@ export const MemberRoleDetailsSection = ({
try {
const updatedRoles = membershipDetails?.roles?.filter((el) => el.id !== id);
await updateUserWorkspaceRole({
- workspaceId: currentWorkspace?.id || "",
+ projectId,
roles: updatedRoles.map(
({
role,
diff --git a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx
index 739b22b7d6..e7a05f70f2 100644
--- a/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx
+++ b/frontend/src/pages/project/MemberDetailsByIDPage/components/MemberRoleDetailsSection/MemberRoleModify.tsx
@@ -29,14 +29,14 @@ import {
ProjectPermissionActions,
ProjectPermissionMemberActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { useGetProjectRoles, useUpdateUserWorkspaceRole } from "@app/hooks/api";
+import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { TWorkspaceUser } from "@app/hooks/api/types";
-import { ProjectUserMembershipTemporaryMode } from "@app/hooks/api/workspace/types";
const roleFormSchema = z.object({
roles: z
@@ -65,9 +65,8 @@ type Props = {
export const MemberRoleModify = ({ projectMember, onOpenUpgradeModal }: Props) => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
- const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(workspaceId);
+ const { projectId } = useProject();
+ const { data: projectRoles, isPending: isRolesLoading } = useGetProjectRoles(projectId);
const { permission } = useProjectPermission();
const isMemberEditDisabled = permission.cannot(
ProjectPermissionMemberActions.Edit,
@@ -131,7 +130,7 @@ export const MemberRoleModify = ({ projectMember, onOpenUpgradeModal }: Props) =
try {
await updateMembershipRole.mutateAsync({
- workspaceId,
+ projectId,
membershipId: projectMember.id,
roles: sanitizedRoles
});
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx
index e400767a1b..775244b4dd 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/RoleDetailsBySlugPage.tsx
@@ -16,7 +16,7 @@ import {
DropdownMenuTrigger,
PageHeader
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import { useDeleteProjectRole, useGetProjectRoleBySlug } from "@app/hooks/api";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
@@ -33,8 +33,8 @@ const Page = () => {
strict: false,
select: (el) => el.roleSlug as string
});
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data } = useGetProjectRoleBySlug(projectId, roleSlug as string);
@@ -48,7 +48,7 @@ const Page = () => {
const onDeleteRoleSubmit = async () => {
try {
- if (!currentWorkspace?.slug || !data?.id) return;
+ if (!currentProject?.slug || !data?.id) return;
await deleteProjectRole({
projectId,
@@ -61,7 +61,7 @@ const Page = () => {
});
handlePopUpClose("deleteRole");
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/access-management` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/access-management` as const,
params: {
projectId
},
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/AddPoliciesButton.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/AddPoliciesButton.tsx
index abdf5c5d59..37f6b38686 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/AddPoliciesButton.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/AddPoliciesButton.tsx
@@ -9,7 +9,7 @@ import {
IconButton
} from "@app/components/v2";
import { usePopUp } from "@app/hooks";
-import { ProjectType } from "@app/hooks/api/workspace/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { PolicySelectionModal } from "@app/pages/project/RoleDetailsBySlugPage/components/PolicySelectionModal";
import { PolicyTemplateModal } from "@app/pages/project/RoleDetailsBySlugPage/components/PolicyTemplateModal";
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/AppConnectionPermissionConditions.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/AppConnectionPermissionConditions.tsx
new file mode 100644
index 0000000000..2991d895cf
--- /dev/null
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/AppConnectionPermissionConditions.tsx
@@ -0,0 +1,19 @@
+import { ProjectPermissionSub } from "@app/context/ProjectPermissionContext/types";
+
+import { ConditionsFields } from "./ConditionsFields";
+
+type Props = {
+ position?: number;
+ isDisabled?: boolean;
+};
+
+export const AppConnectionPermissionConditions = ({ position = 0, isDisabled }: Props) => {
+ return (
+ <ConditionsFields
+ isDisabled={isDisabled}
+ subject={ProjectPermissionSub.AppConnections}
+ position={position}
+ selectOptions={[{ value: "connectionId", label: "Connection ID" }]}
+ />
+ );
+};
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/DuplicateProjectRoleModal.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/DuplicateProjectRoleModal.tsx
index 24974225ea..d365620899 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/DuplicateProjectRoleModal.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/DuplicateProjectRoleModal.tsx
@@ -5,7 +5,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent, Spinner } from "@app/components/v2";
-import { ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionSub, useProject } from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
import { getProjectBaseURL } from "@app/helpers/project";
import { useCreateProjectRole, useGetProjectRoleBySlug } from "@app/hooks/api";
@@ -45,7 +45,7 @@ const Content = ({ role, onClose }: ContentProps) => {
resolver: zodResolver(schema)
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const createRole = useCreateProjectRole();
const navigate = useNavigate();
@@ -70,7 +70,7 @@ const Content = ({ role, onClose }: ContentProps) => {
});
const newRole = await createRole.mutateAsync({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
permissions: sanitizedPermission,
...form
});
@@ -81,10 +81,10 @@ const Content = ({ role, onClose }: ContentProps) => {
});
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/roles/$roleSlug` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/roles/$roleSlug` as const,
params: {
roleSlug: newRole.slug,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}
});
@@ -142,9 +142,9 @@ const Content = ({ role, onClose }: ContentProps) => {
};
export const DuplicateProjectRoleModal = ({ isOpen, onOpenChange, roleSlug }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
- const { data: role, isPending } = useGetProjectRoleBySlug(currentWorkspace.id, roleSlug ?? "");
+ const { data: role, isPending } = useGetProjectRoleBySlug(currentProject.id, roleSlug ?? "");
if (!roleSlug) return null;
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx
index a39ae8d640..f6c44b386c 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PermissionConditionHelpers.tsx
@@ -23,6 +23,7 @@ export const renderOperatorSelectItems = (type: string) => {
case "secretTags":
return <SelectItem value={PermissionConditionOperators.$IN}>Contains</SelectItem>;
case "identityId":
+ case "connectionId":
return (
<>
<SelectItem value={PermissionConditionOperators.$EQ}>Equal</SelectItem>
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicySelectionModal.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicySelectionModal.tsx
index 845c5f54ec..22e64d48e2 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicySelectionModal.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicySelectionModal.tsx
@@ -19,7 +19,7 @@ import {
Tr
} from "@app/components/v2";
import { ProjectPermissionSub } from "@app/context";
-import { ProjectType } from "@app/hooks/api/workspace/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import {
EXCLUDED_PERMISSION_SUBS,
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicyTemplateModal.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicyTemplateModal.tsx
index d9cae62446..3064311bc3 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicyTemplateModal.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/PolicyTemplateModal.tsx
@@ -13,7 +13,7 @@ import {
ModalContent
} from "@app/components/v2";
import { ProjectPermissionSub } from "@app/context";
-import { ProjectType } from "@app/hooks/api/workspace/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import {
PROJECT_PERMISSION_OBJECT,
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index 8562753740..89c1e5d860 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -12,6 +12,7 @@ import {
} from "@app/context";
import {
PermissionConditionOperators,
+ ProjectPermissionAppConnectionActions,
ProjectPermissionAuditLogsActions,
ProjectPermissionCommitsActions,
ProjectPermissionDynamicSecretActions,
@@ -32,8 +33,8 @@ import {
TPermissionCondition,
TPermissionConditionOperators
} from "@app/context/ProjectPermissionContext/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { TProjectPermission } from "@app/hooks/api/roles/types";
-import { ProjectType } from "@app/hooks/api/workspace/types";
const GeneralPolicyActionSchema = z.object({
read: z.boolean().optional(),
@@ -134,6 +135,14 @@ const SecretScanningConfigPolicyActionSchema = z.object({
[ProjectPermissionSecretScanningConfigActions.Update]: z.boolean().optional()
});
+const AppConnectionPolicyActionSchema = z.object({
+ [ProjectPermissionAppConnectionActions.Create]: z.boolean().optional(),
+ [ProjectPermissionAppConnectionActions.Read]: z.boolean().optional(),
+ [ProjectPermissionAppConnectionActions.Edit]: z.boolean().optional(),
+ [ProjectPermissionAppConnectionActions.Delete]: z.boolean().optional(),
+ [ProjectPermissionAppConnectionActions.Connect]: z.boolean().optional()
+});
+
const KmipPolicyActionSchema = z.object({
[ProjectPermissionKmipActions.ReadClients]: z.boolean().optional(),
[ProjectPermissionKmipActions.CreateClients]: z.boolean().optional(),
@@ -311,6 +320,12 @@ export const projectRoleFormSchema = z.object({
})
.array()
.default([]),
+ [ProjectPermissionSub.AppConnections]: AppConnectionPolicyActionSchema.extend({
+ inverted: z.boolean().optional(),
+ conditions: ConditionSchema
+ })
+ .array()
+ .default([]),
[ProjectPermissionSub.Commits]: CommitPolicyActionSchema.array().default([]),
[ProjectPermissionSub.Member]: MemberPolicyActionSchema.array().default([]),
@@ -393,7 +408,8 @@ type TConditionalFields =
| ProjectPermissionSub.SecretRotation
| ProjectPermissionSub.Identity
| ProjectPermissionSub.SecretSyncs
- | ProjectPermissionSub.SecretEvents;
+ | ProjectPermissionSub.SecretEvents
+ | ProjectPermissionSub.AppConnections;
export const isConditionalSubjects = (
subject: ProjectPermissionSub
@@ -408,7 +424,8 @@ export const isConditionalSubjects = (
subject === ProjectPermissionSub.PkiSubscribers ||
subject === ProjectPermissionSub.CertificateTemplates ||
subject === ProjectPermissionSub.SecretSyncs ||
- subject === ProjectPermissionSub.SecretEvents;
+ subject === ProjectPermissionSub.SecretEvents ||
+ subject === ProjectPermissionSub.AppConnections;
const convertCaslConditionToFormOperator = (caslConditions: TPermissionCondition) => {
const formConditions: z.infer<typeof ConditionSchema> = [];
@@ -515,7 +532,8 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
ProjectPermissionSub.SshCertificates,
ProjectPermissionSub.SshHostGroups,
ProjectPermissionSub.SecretSyncs,
- ProjectPermissionSub.SecretEvents
+ ProjectPermissionSub.SecretEvents,
+ ProjectPermissionSub.AppConnections
].includes(subject)
) {
// from above statement we are sure it won't be undefined
@@ -654,6 +672,27 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
return;
}
+ if (subject === ProjectPermissionSub.AppConnections) {
+ const canCreate = action.includes(ProjectPermissionAppConnectionActions.Create);
+ const canRead = action.includes(ProjectPermissionAppConnectionActions.Read);
+ const canEdit = action.includes(ProjectPermissionAppConnectionActions.Edit);
+ const canDelete = action.includes(ProjectPermissionAppConnectionActions.Delete);
+ const canConnect = action.includes(ProjectPermissionAppConnectionActions.Connect);
+
+ // from above statement we are sure it won't be undefined
+ formVal[subject]!.push({
+ [ProjectPermissionAppConnectionActions.Read]: canRead,
+ [ProjectPermissionAppConnectionActions.Create]: canCreate,
+ [ProjectPermissionAppConnectionActions.Edit]: canEdit,
+ [ProjectPermissionAppConnectionActions.Delete]: canDelete,
+ [ProjectPermissionAppConnectionActions.Connect]: canConnect,
+ conditions: conditions ? convertCaslConditionToFormOperator(conditions) : [],
+ inverted
+ });
+
+ return;
+ }
+
// for other subjects
const canRead = action.includes(ProjectPermissionActions.Read);
const canEdit = action.includes(ProjectPermissionActions.Edit);
@@ -1597,6 +1636,31 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
value: ProjectPermissionSecretEventActions.SubscribeImportMutations
}
]
+ },
+ [ProjectPermissionSub.AppConnections]: {
+ title: "App Connections",
+ actions: [
+ {
+ label: "Read",
+ value: ProjectPermissionAppConnectionActions.Read
+ },
+ {
+ label: "Create",
+ value: ProjectPermissionAppConnectionActions.Create
+ },
+ {
+ label: "Update",
+ value: ProjectPermissionAppConnectionActions.Edit
+ },
+ {
+ label: "Delete",
+ value: ProjectPermissionAppConnectionActions.Delete
+ },
+ {
+ label: "Connect",
+ value: ProjectPermissionAppConnectionActions.Connect
+ }
+ ]
}
};
@@ -1669,7 +1733,8 @@ export const ProjectTypePermissionSubjects: Record<
...KmsPermissionSubjects(),
...CertificateManagerPermissionSubjects(),
...SshPermissionSubjects(),
- ...SecretScanningSubject()
+ ...SecretScanningSubject(),
+ [ProjectPermissionSub.AppConnections]: true
},
[ProjectType.KMS]: {
...SharedPermissionSubjects,
@@ -1677,7 +1742,8 @@ export const ProjectTypePermissionSubjects: Record<
...SecretsManagerPermissionSubjects(),
...CertificateManagerPermissionSubjects(),
...SshPermissionSubjects(),
- ...SecretScanningSubject()
+ ...SecretScanningSubject(),
+ [ProjectPermissionSub.AppConnections]: false
},
[ProjectType.CertificateManager]: {
...SharedPermissionSubjects,
@@ -1685,7 +1751,8 @@ export const ProjectTypePermissionSubjects: Record<
...KmsPermissionSubjects(),
...SecretsManagerPermissionSubjects(),
...SshPermissionSubjects(),
- ...SecretScanningSubject()
+ ...SecretScanningSubject(),
+ [ProjectPermissionSub.AppConnections]: true
},
[ProjectType.SSH]: {
...SharedPermissionSubjects,
@@ -1693,7 +1760,8 @@ export const ProjectTypePermissionSubjects: Record<
...CertificateManagerPermissionSubjects(),
...KmsPermissionSubjects(),
...SecretsManagerPermissionSubjects(),
- ...SecretScanningSubject()
+ ...SecretScanningSubject(),
+ [ProjectPermissionSub.AppConnections]: false
},
[ProjectType.SecretScanning]: {
...SharedPermissionSubjects,
@@ -1701,7 +1769,8 @@ export const ProjectTypePermissionSubjects: Record<
...SshPermissionSubjects(),
...CertificateManagerPermissionSubjects(),
...KmsPermissionSubjects(),
- ...SecretsManagerPermissionSubjects()
+ ...SecretsManagerPermissionSubjects(),
+ [ProjectPermissionSub.AppConnections]: true
}
};
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx
index eb7a2ba830..e34f868929 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RoleModal.tsx
@@ -6,7 +6,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { getProjectBaseURL } from "@app/helpers/project";
import {
useCreateProjectRole,
@@ -38,8 +38,8 @@ export const RoleModal = ({ popUp, handlePopUpToggle }: Props) => {
roleSlug: string;
};
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: role } = useGetProjectRoleBySlug(projectId, popupData?.roleSlug ?? "");
@@ -101,7 +101,7 @@ export const RoleModal = ({ popUp, handlePopUpToggle }: Props) => {
});
navigate({
- to: `${getProjectBaseURL(currentWorkspace.type)}/roles/$roleSlug` as const,
+ to: `${getProjectBaseURL(currentProject.type)}/roles/$roleSlug` as const,
params: {
roleSlug: newRole.slug,
projectId
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx
index f50446a8ef..347ebaf99c 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/RolePermissionsSection.tsx
@@ -8,14 +8,15 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { createNotification } from "@app/components/notifications";
import { AccessTree } from "@app/components/permissions";
import { Button } from "@app/components/v2";
-import { ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionSub, useProject } from "@app/context";
import { ProjectPermissionSet } from "@app/context/ProjectPermissionContext";
import { evaluatePermissionsAbility } from "@app/helpers/permissions";
import { useGetProjectRoleBySlug, useUpdateProjectRole } from "@app/hooks/api";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { ProjectType } from "@app/hooks/api/workspace/types";
import { AddPoliciesButton } from "./AddPoliciesButton";
+import { AppConnectionPermissionConditions } from "./AppConnectionPermissionConditions";
import { DynamicSecretPermissionConditions } from "./DynamicSecretPermissionConditions";
import { GeneralPermissionConditions } from "./GeneralPermissionConditions";
import { GeneralPermissionPolicies } from "./GeneralPermissionPolicies";
@@ -77,6 +78,10 @@ export const renderConditionalComponents = (
return <SecretEventPermissionConditions isDisabled={isDisabled} />;
}
+ if (subject === ProjectPermissionSub.AppConnections) {
+ return <AppConnectionPermissionConditions isDisabled={isDisabled} />;
+ }
+
return <GeneralPermissionConditions isDisabled={isDisabled} type={subject} />;
}
@@ -84,10 +89,10 @@ export const renderConditionalComponents = (
};
export const RolePermissionsSection = ({ roleSlug, isDisabled }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: role, isPending } = useGetProjectRoleBySlug(
- currentWorkspace?.id ?? "",
+ currentProject?.id ?? "",
roleSlug as string
);
@@ -126,7 +131,7 @@ export const RolePermissionsSection = ({ roleSlug, isDisabled }: Props) => {
(role?.slug ?? "") as ProjectMembershipRole
);
- const isSecretManagerProject = currentWorkspace.type === ProjectType.SecretManager;
+ const isSecretManagerProject = currentProject.type === ProjectType.SecretManager;
const permissions = form.watch("permissions");
@@ -178,7 +183,7 @@ export const RolePermissionsSection = ({ roleSlug, isDisabled }: Props) => {
Save
</Button>
<div className="ml-2 border-l border-mineshaft-500 pl-4">
- <AddPoliciesButton isDisabled={isDisabled} projectType={currentWorkspace.type} />
+ <AddPoliciesButton isDisabled={isDisabled} projectType={currentProject.type} />
</div>
</div>
)}
diff --git a/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx b/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx
index 7c65b18573..11f4f0270c 100644
--- a/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx
+++ b/frontend/src/pages/project/SettingsPage/components/AuditLogsRetentionSection/AuditLogsRetentionSection.tsx
@@ -5,10 +5,10 @@ import { z } from "zod";
import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input } from "@app/components/v2";
-import { useProjectPermission, useSubscription, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission, useSubscription } from "@app/context";
import { usePopUp } from "@app/hooks";
+import { useUpdateWorkspaceAuditLogsRetention } from "@app/hooks/api/projects/queries";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { useUpdateWorkspaceAuditLogsRetention } from "@app/hooks/api/workspace/queries";
const formSchema = z.object({
auditLogsRetentionDays: z.coerce.number().min(0)
@@ -19,7 +19,7 @@ type TForm = z.infer<typeof formSchema>;
export const AuditLogsRetentionSection = () => {
const { mutateAsync: updateAuditLogsRetention } = useUpdateWorkspaceAuditLogsRetention();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { membership } = useProjectPermission();
const { subscription } = useSubscription();
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);
@@ -32,11 +32,11 @@ export const AuditLogsRetentionSection = () => {
resolver: zodResolver(formSchema),
values: {
auditLogsRetentionDays:
- currentWorkspace?.auditLogsRetentionDays ?? subscription?.auditLogsRetentionDays ?? 0
+ currentProject?.auditLogsRetentionDays ?? subscription?.auditLogsRetentionDays ?? 0
}
});
- if (!currentWorkspace) return null;
+ if (!currentProject) return null;
const handleAuditLogsRetentionSubmit = async ({ auditLogsRetentionDays }: TForm) => {
try {
@@ -59,7 +59,7 @@ export const AuditLogsRetentionSection = () => {
await updateAuditLogsRetention({
auditLogsRetentionDays,
- projectSlug: currentWorkspace.slug
+ projectSlug: currentProject.slug
});
createNotification({
diff --git a/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx b/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx
index 2ac1236077..efc69831d5 100644
--- a/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx
+++ b/frontend/src/pages/project/SettingsPage/components/DeleteProjectProtection/DeleteProjectProtection.tsx
@@ -1,20 +1,19 @@
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Checkbox } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
-import { useToggleDeleteProjectProtection } from "@app/hooks/api/workspace/queries";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
+import { useUpdateProject } from "@app/hooks/api";
export const DeleteProjectProtection = () => {
- const { currentWorkspace } = useWorkspace();
- const { mutateAsync } = useToggleDeleteProjectProtection();
+ const { projectId, currentProject } = useProject();
+
+ const { mutateAsync } = useUpdateProject();
const handleToggleDeleteProjectProtection = async (state: boolean) => {
try {
- if (!currentWorkspace?.id) return;
-
await mutateAsync({
- workspaceID: currentWorkspace.id,
- state
+ projectId,
+ hasDeleteProtection: state
});
const text = `Successfully ${state ? "enabled" : "disabled"} delete protection`;
@@ -40,7 +39,7 @@ export const DeleteProjectProtection = () => {
<Checkbox
id="hasDeleteProtection"
isDisabled={!isAllowed}
- isChecked={currentWorkspace?.hasDeleteProtection ?? false}
+ isChecked={currentProject?.hasDeleteProtection ?? false}
onCheckedChange={(state) => {
handleToggleDeleteProjectProtection(state as boolean);
}}
diff --git a/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx b/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx
index ac589ba594..4771e0c887 100644
--- a/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx
+++ b/frontend/src/pages/project/SettingsPage/components/DeleteProjectSection/DeleteProjectSection.tsx
@@ -9,8 +9,8 @@ import {
ProjectPermissionActions,
ProjectPermissionSub,
useOrganization,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { useToggle } from "@app/hooks";
import { useDeleteWorkspace, useGetWorkspaceUsers, useLeaveProject } from "@app/hooks/api";
@@ -26,13 +26,13 @@ export const DeleteProjectSection = () => {
const { currentOrg } = useOrganization();
const { hasProjectRole, membership } = useProjectPermission();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [isDeleting, setIsDeleting] = useToggle();
const [isLeaving, setIsLeaving] = useToggle();
const deleteWorkspace = useDeleteWorkspace();
const leaveProject = useLeaveProject();
const { data: members, isPending: isMembersLoading } = useGetWorkspaceUsers(
- currentWorkspace?.id || ""
+ currentProject?.id || ""
);
// If isNoAccessMember is true, then the user can't read the workspace members. So we need to handle this case separately.
@@ -51,10 +51,10 @@ export const DeleteProjectSection = () => {
const handleDeleteWorkspaceSubmit = async () => {
setIsDeleting.on();
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await deleteWorkspace.mutateAsync({
- workspaceID: currentWorkspace?.id
+ projectID: currentProject?.id
});
createNotification({
@@ -81,7 +81,7 @@ export const DeleteProjectSection = () => {
try {
setIsLeaving.on();
- if (!currentWorkspace?.id || !currentOrg?.id) return;
+ if (!currentProject?.id || !currentOrg?.id) return;
// If there's no members, and the user has access to read members, something went wrong.
if (!members && !isNoAccessMember) return;
@@ -110,7 +110,7 @@ export const DeleteProjectSection = () => {
// If it's actually a no-access member, then we don't really care about the members.
await leaveProject.mutateAsync({
- workspaceId: currentWorkspace.id
+ projectId: currentProject.id
});
navigate({
@@ -141,7 +141,7 @@ export const DeleteProjectSection = () => {
type="submit"
onClick={() => handlePopUpOpen("deleteWorkspace")}
>
- {`Delete ${currentWorkspace?.name}`}
+ {`Delete ${currentProject?.name}`}
</Button>
)}
</ProjectPermissionCan>
@@ -154,7 +154,7 @@ export const DeleteProjectSection = () => {
type="submit"
onClick={() => handlePopUpOpen("leaveWorkspace")}
>
- {`Leave ${currentWorkspace?.name}`}
+ {`Leave ${currentProject?.name}`}
</Button>
)}
</div>
@@ -162,7 +162,7 @@ export const DeleteProjectSection = () => {
<DeleteActionModal
isOpen={popUp.deleteWorkspace.isOpen}
title="Are you sure you want to delete this project?"
- subTitle={`Permanently delete ${currentWorkspace?.name} and all of its data. This action is not reversible, so please be careful.`}
+ subTitle={`Permanently delete ${currentProject?.name} and all of its data. This action is not reversible, so please be careful.`}
onChange={(isOpen) => handlePopUpToggle("deleteWorkspace", isOpen)}
deleteKey="confirm"
buttonText="Delete Project"
@@ -172,7 +172,7 @@ export const DeleteProjectSection = () => {
<LeaveProjectModal
isOpen={popUp.leaveWorkspace.isOpen}
title="Are you sure you want to leave this project?"
- subTitle={`If you leave ${currentWorkspace?.name} you will lose access to the project and its contents.`}
+ subTitle={`If you leave ${currentProject?.name} you will lose access to the project and its contents.`}
onChange={(isOpen) => handlePopUpToggle("leaveWorkspace", isOpen)}
deleteKey="confirm"
buttonText="Leave Project"
diff --git a/frontend/src/pages/public/ErrorPage/ErrorPage.tsx b/frontend/src/pages/public/ErrorPage/ErrorPage.tsx
index 1910eb891d..ef6a837ae5 100644
--- a/frontend/src/pages/public/ErrorPage/ErrorPage.tsx
+++ b/frontend/src/pages/public/ErrorPage/ErrorPage.tsx
@@ -5,7 +5,17 @@ import { AxiosError } from "axios";
import { Button } from "@app/components/v2";
+import { ProjectAccessError } from "./components";
+
export const ErrorPage = ({ error }: ErrorComponentProps) => {
+ if (
+ error instanceof AxiosError &&
+ error.status === 403 &&
+ error.response?.data?.error === "User not a part of the specified project"
+ ) {
+ return <ProjectAccessError />;
+ }
+
return (
<div className="flex h-screen w-screen items-center justify-center bg-mineshaft-900">
<div className="flex max-w-3xl flex-col rounded-md border border-mineshaft-600 bg-mineshaft-800 p-8 text-center text-mineshaft-200">
diff --git a/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx b/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx
new file mode 100644
index 0000000000..d6fd57d562
--- /dev/null
+++ b/frontend/src/pages/public/ErrorPage/components/ProjectAccessError.tsx
@@ -0,0 +1,109 @@
+import { faHome } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { Link, useNavigate, useParams } from "@tanstack/react-router";
+
+import { createNotification } from "@app/components/notifications";
+import { OrgPermissionCan } from "@app/components/permissions";
+import { RequestProjectAccessModal } from "@app/components/projects";
+import { AccessRestrictedBanner, Button } from "@app/components/v2";
+import { OrgPermissionSubjects } from "@app/context";
+import { OrgPermissionAdminConsoleAction } from "@app/context/OrgPermissionContext/types";
+import { usePopUp } from "@app/hooks";
+import { useOrgAdminAccessProject, useSearchProjects } from "@app/hooks/api";
+
+export const ProjectAccessError = () => {
+ const orgAdminAccessProject = useOrgAdminAccessProject();
+
+ const navigate = useNavigate();
+
+ const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp([
+ "requestAccessConfirmation"
+ ] as const);
+
+ const { projectId } = useParams({
+ strict: false
+ });
+
+ const { data, isPending: isProjectLoading } = useSearchProjects({
+ projectIds: projectId ? [projectId] : [],
+ options: {
+ enabled: Boolean(projectId)
+ }
+ });
+
+ const [project] = data?.projects ?? [];
+
+ const handleAccessProject = async () => {
+ if (!project) return;
+ try {
+ await orgAdminAccessProject.mutateAsync({
+ projectId: project.id
+ });
+ await navigate({
+ to: "."
+ });
+ } catch {
+ createNotification({
+ text: "Failed to access project",
+ type: "error"
+ });
+ }
+ };
+
+ return (
+ <div className="flex h-full w-full items-center justify-center">
+ <AccessRestrictedBanner
+ body={
+ <>
+ You are not currently a member of this project. Request access to join project.
+ <div className="mt-4 flex w-full justify-center gap-2">
+ <Link to="/organization/projects">
+ <Button variant="outline_bg">
+ <FontAwesomeIcon icon={faHome} className="mr-2" />
+ Back To Home
+ </Button>
+ </Link>
+ <OrgPermissionCan
+ I={OrgPermissionAdminConsoleAction.AccessAllProjects}
+ an={OrgPermissionSubjects.AdminConsole}
+ >
+ {(isAllowed) =>
+ isAllowed ? (
+ <Button
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ handleAccessProject();
+ }}
+ disabled={orgAdminAccessProject.isPending}
+ isLoading={isProjectLoading || orgAdminAccessProject.isPending}
+ >
+ Join Project as Admin
+ </Button>
+ ) : (
+ <Button
+ onClick={() => handlePopUpOpen("requestAccessConfirmation")}
+ isLoading={isProjectLoading}
+ >
+ Request Access to Project
+ </Button>
+ )
+ }
+ </OrgPermissionCan>
+ </div>
+ <RequestProjectAccessModal
+ isOpen={popUp.requestAccessConfirmation.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("requestAccessConfirmation", isOpen)}
+ project={project}
+ onComplete={() => {
+ navigate({
+ to: "/organization/projects"
+ });
+ }}
+ />
+ </>
+ }
+ />
+ </div>
+ );
+};
diff --git a/frontend/src/pages/public/ErrorPage/components/index.ts b/frontend/src/pages/public/ErrorPage/components/index.ts
new file mode 100644
index 0000000000..1940497e92
--- /dev/null
+++ b/frontend/src/pages/public/ErrorPage/components/index.ts
@@ -0,0 +1 @@
+export * from "./ProjectAccessError";
diff --git a/frontend/src/pages/secret-manager/CommitDetailsPage/CommitDetailsPage.tsx b/frontend/src/pages/secret-manager/CommitDetailsPage/CommitDetailsPage.tsx
index 06f79e9f04..facbd782b6 100644
--- a/frontend/src/pages/secret-manager/CommitDetailsPage/CommitDetailsPage.tsx
+++ b/frontend/src/pages/secret-manager/CommitDetailsPage/CommitDetailsPage.tsx
@@ -2,7 +2,7 @@ import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { ProjectPermissionCan } from "@app/components/permissions";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
ProjectPermissionCommitsActions,
ProjectPermissionSub
@@ -23,7 +23,7 @@ export const CommitDetailsPage = () => {
from: ROUTE_PATHS.SecretManager.CommitDetailsPage.id,
select: (el) => el.folderId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
const routerQueryParams: { secretPath?: string } = useSearch({
@@ -36,7 +36,7 @@ export const CommitDetailsPage = () => {
navigate({
to: "/projects/secret-management/$projectId/commits/$environment/$folderId",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
folderId,
environment: envSlug
},
@@ -51,7 +51,7 @@ export const CommitDetailsPage = () => {
navigate({
to: "/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId/restore",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
folderId,
environment: envSlug,
commitId: selectedCommitId
@@ -73,7 +73,7 @@ export const CommitDetailsPage = () => {
>
<CommitDetailsTab
selectedCommitId={selectedCommitId}
- workspaceId={currentWorkspace.id}
+ projectId={currentProject.id}
goBackToHistory={handleGoBackToHistory}
envSlug={envSlug}
goToRollbackPreview={handleGoToRollbackPreview}
diff --git a/frontend/src/pages/secret-manager/CommitDetailsPage/components/CommitDetailsTab/CommitDetailsTab.tsx b/frontend/src/pages/secret-manager/CommitDetailsPage/components/CommitDetailsTab/CommitDetailsTab.tsx
index 483d00861d..4d8ac4a700 100644
--- a/frontend/src/pages/secret-manager/CommitDetailsPage/components/CommitDetailsTab/CommitDetailsTab.tsx
+++ b/frontend/src/pages/secret-manager/CommitDetailsPage/components/CommitDetailsTab/CommitDetailsTab.tsx
@@ -53,13 +53,13 @@ const formatDisplayDate = (dateString: string): string => {
export const CommitDetailsTab = ({
selectedCommitId,
- workspaceId,
+ projectId,
envSlug,
goBackToHistory,
goToRollbackPreview
}: {
selectedCommitId: string;
- workspaceId: string;
+ projectId: string;
envSlug: string;
goBackToHistory: () => void;
goToRollbackPreview: () => void;
@@ -71,7 +71,7 @@ export const CommitDetailsTab = ({
"revertChanges"
] as const);
- const { data: commitDetails, isLoading } = useGetCommitDetails(workspaceId, selectedCommitId);
+ const { data: commitDetails, isLoading } = useGetCommitDetails(projectId, selectedCommitId);
const routerQueryParams: { secretPath?: string } = useSearch({
from: ROUTE_PATHS.SecretManager.CommitDetailsPage.id
@@ -80,7 +80,7 @@ export const CommitDetailsTab = ({
const { mutateAsync: revert } = useCommitRevert({
commitId: selectedCommitId,
- projectId: workspaceId,
+ projectId,
environment: envSlug,
directory: secretPath
});
diff --git a/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx b/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx
index e06daea38e..ae082d8eaa 100644
--- a/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx
+++ b/frontend/src/pages/secret-manager/CommitDetailsPage/components/RollbackPreviewTab/RollbackPreviewTab.tsx
@@ -17,7 +17,7 @@ import {
Tooltip
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
ProjectPermissionCommitsActions,
ProjectPermissionSub
@@ -79,7 +79,7 @@ export const RollbackPreviewTab = (): JSX.Element => {
const [deepRollback, setDeepRollback] = useState<boolean>(false);
const [message, setMessage] = useState<string>("");
const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const envSlug = useParams({
from: ROUTE_PATHS.SecretManager.RollbackPreviewPage.id,
select: (el) => el.environment
@@ -104,7 +104,7 @@ export const RollbackPreviewTab = (): JSX.Element => {
navigate({
to: "/projects/secret-management/$projectId/commits/$environment/$folderId",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
folderId,
environment: envSlug
},
@@ -120,7 +120,7 @@ export const RollbackPreviewTab = (): JSX.Element => {
] as const);
const { mutateAsync: rollback } = useCommitRollback({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
commitId: selectedCommitId,
folderId,
deepRollback,
@@ -133,7 +133,7 @@ export const RollbackPreviewTab = (): JSX.Element => {
folderId,
selectedCommitId,
envSlug,
- currentWorkspace.id,
+ currentProject.id,
deepRollback,
secretPath
);
diff --git a/frontend/src/pages/secret-manager/CommitsPage/CommitsPage.tsx b/frontend/src/pages/secret-manager/CommitsPage/CommitsPage.tsx
index 1acb764469..2dba8ad550 100644
--- a/frontend/src/pages/secret-manager/CommitsPage/CommitsPage.tsx
+++ b/frontend/src/pages/secret-manager/CommitsPage/CommitsPage.tsx
@@ -4,7 +4,7 @@ import { ProjectPermissionCan } from "@app/components/permissions";
import { PageHeader } from "@app/components/v2";
import { NoticeBannerV2 } from "@app/components/v2/NoticeBannerV2/NoticeBannerV2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
ProjectPermissionCommitsActions,
ProjectPermissionSub
@@ -17,7 +17,7 @@ export const CommitsPage = () => {
from: ROUTE_PATHS.SecretManager.CommitsPage.id,
select: (el) => el.environment
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
const folderId = useParams({
from: ROUTE_PATHS.SecretManager.CommitsPage.id,
@@ -33,7 +33,7 @@ export const CommitsPage = () => {
navigate({
to: "/projects/secret-management/$projectId/commits/$environment/$folderId/$commitId",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
folderId,
environment: envSlug,
commitId
@@ -67,7 +67,7 @@ export const CommitsPage = () => {
>
<CommitHistoryTab
onSelectCommit={handleSelectCommit}
- projectId={currentWorkspace.id}
+ projectId={currentProject.id}
environment={envSlug}
secretPath={secretPath}
/>
diff --git a/frontend/src/pages/secret-manager/CommitsPage/components/CommitHistoryTab/CommitHistoryTab.tsx b/frontend/src/pages/secret-manager/CommitsPage/components/CommitHistoryTab/CommitHistoryTab.tsx
index 58191f3897..d5f982529a 100644
--- a/frontend/src/pages/secret-manager/CommitsPage/components/CommitHistoryTab/CommitHistoryTab.tsx
+++ b/frontend/src/pages/secret-manager/CommitsPage/components/CommitHistoryTab/CommitHistoryTab.tsx
@@ -136,7 +136,7 @@ export const CommitHistoryTab = ({
isFetchingNextPage,
hasNextPage
} = useGetFolderCommitHistory({
- workspaceId: projectId,
+ projectId,
environment,
directory: secretPath,
limit,
diff --git a/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistModal.tsx b/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistModal.tsx
index 4d95b6388a..36f5858502 100644
--- a/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistModal.tsx
+++ b/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistModal.tsx
@@ -5,7 +5,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAddTrustedIp, useGetMyIp, useUpdateTrustedIp } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -27,7 +27,7 @@ type Props = {
export const IPAllowlistModal = ({ popUp, handlePopUpClose, handlePopUpToggle }: Props) => {
const { data, isPending } = useGetMyIp();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const addTrustedIp = useAddTrustedIp();
const updateTrustedIp = useUpdateTrustedIp();
@@ -65,11 +65,11 @@ export const IPAllowlistModal = ({ popUp, handlePopUpClose, handlePopUpToggle }:
const onIPAllowlistModalSubmit = async ({ ipAddress, comment }: FormData) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
if (popUp?.trustedIp?.data) {
await updateTrustedIp.mutateAsync({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
trustedIpId: (popUp?.trustedIp?.data as { trustedIpId: string })?.trustedIpId,
ipAddress,
comment,
@@ -77,7 +77,7 @@ export const IPAllowlistModal = ({ popUp, handlePopUpClose, handlePopUpToggle }:
});
} else {
await addTrustedIp.mutateAsync({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
ipAddress,
comment,
isActive: true
diff --git a/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistSection.tsx b/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistSection.tsx
index 63b410ee28..fc2890b7f9 100644
--- a/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistSection.tsx
+++ b/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistSection.tsx
@@ -8,8 +8,8 @@ import { Button, DeleteActionModal } from "@app/components/v2";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useSubscription,
- useWorkspace
+ useProject,
+ useSubscription
} from "@app/context";
import { useDeleteTrustedIp } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -20,7 +20,7 @@ import { IPAllowlistTable } from "./IPAllowlistTable";
export const IPAllowlistSection = () => {
const { mutateAsync } = useDeleteTrustedIp();
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"trustedIp",
@@ -30,10 +30,10 @@ export const IPAllowlistSection = () => {
const onDeleteTrustedIpSubmit = async (trustedIpId: string) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await mutateAsync({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
trustedIpId
});
diff --git a/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistTable.tsx b/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistTable.tsx
index 42ecc8d8a0..8f3336be87 100644
--- a/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistTable.tsx
+++ b/frontend/src/pages/secret-manager/IPAllowlistPage/components/IPAllowlistTable.tsx
@@ -18,8 +18,8 @@ import {
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useSubscription,
- useWorkspace
+ useProject,
+ useSubscription
} from "@app/context";
import { useGetTrustedIps } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -41,8 +41,8 @@ type Props = {
export const IPAllowlistTable = ({ popUp, handlePopUpOpen, handlePopUpToggle }: Props) => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
- const { data, isPending } = useGetTrustedIps(currentWorkspace?.id ?? "");
+ const { currentProject } = useProject();
+ const { data, isPending } = useGetTrustedIps(currentProject?.id ?? "");
const formatType = (type: string, prefix?: number) => {
return `${type.slice(0, 2).toUpperCase() + type.slice(2)} ${
@@ -77,10 +77,10 @@ export const IPAllowlistTable = ({ popUp, handlePopUpOpen, handlePopUpToggle }:
<Td>{comment}</Td>
{/* <Td>
<div className="flex items-center">
- <FontAwesomeIcon
- icon={faCircle}
+ <FontAwesomeIcon
+ icon={faCircle}
color="#2ecc71"
- />
+ />
<p className="ml-4">Active</p>
</div>
</Td> */}
diff --git a/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx b/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx
index c1ba83ae62..3788d955ef 100644
--- a/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/IntegrationsDetailsByIDPage.tsx
@@ -20,11 +20,11 @@ import {
Tooltip
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { OrgPermissionActions, OrgPermissionSubjects, useWorkspace } from "@app/context";
+import { OrgPermissionActions, OrgPermissionSubjects, useProject } from "@app/context";
import { usePopUp, useToggle } from "@app/hooks";
import { useGetIntegration } from "@app/hooks/api";
import { useDeleteIntegration, useSyncIntegration } from "@app/hooks/api/integrations/queries";
-import { ProjectType } from "@app/hooks/api/workspace/types";
+import { ProjectType } from "@app/hooks/api/projects/types";
import { IntegrationAuditLogsSection } from "./components/IntegrationAuditLogsSection";
import { IntegrationConnectionSection } from "./components/IntegrationConnectionSection";
@@ -45,8 +45,8 @@ export const IntegrationDetailsByIDPage = () => {
const [shouldDeleteSecrets, setShouldDeleteSecrets] = useToggle(false);
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const { mutateAsync: syncIntegration } = useSyncIntegration();
const { mutateAsync: deleteIntegration } = useDeleteIntegration();
@@ -56,7 +56,7 @@ export const IntegrationDetailsByIDPage = () => {
try {
await deleteIntegration({
id: integrationId,
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
shouldDeleteIntegrationSecrets
});
diff --git a/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/components/IntegrationAuditLogsSection.tsx b/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/components/IntegrationAuditLogsSection.tsx
index c27b1bb08d..6a808814e5 100644
--- a/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/components/IntegrationAuditLogsSection.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsDetailsByIDPage/components/IntegrationAuditLogsSection.tsx
@@ -1,7 +1,7 @@
import { Link } from "@tanstack/react-router";
import { EmptyState } from "@app/components/v2";
-import { useSubscription, useWorkspace } from "@app/context";
+import { useProject, useSubscription } from "@app/context";
import { EventType } from "@app/hooks/api/auditLogs/enums";
import { TIntegrationWithEnv } from "@app/hooks/api/integrations/types";
import { LogsSection } from "@app/pages/organization/AuditLogsPage/components/LogsSection";
@@ -15,7 +15,7 @@ type Props = {
export const IntegrationAuditLogsSection = ({ integration }: Props) => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const auditLogsRetentionDays = subscription?.auditLogsRetentionDays ?? 30;
@@ -31,7 +31,7 @@ export const IntegrationAuditLogsSection = ({ integration }: Props) => {
<LogsSection
refetchInterval={4000}
showFilters={false}
- project={currentWorkspace}
+ project={currentProject}
presets={{
eventMetadata: { integrationId: integration.id },
startDate: new Date(
diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/IntegrationsListPage.tsx b/frontend/src/pages/secret-manager/IntegrationsListPage/IntegrationsListPage.tsx
index 172dda3029..26263f0adb 100644
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/IntegrationsListPage.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/IntegrationsListPage.tsx
@@ -5,7 +5,7 @@ import { useNavigate, useSearch } from "@tanstack/react-router";
import { ProjectPermissionCan } from "@app/components/permissions";
import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { ProjectPermissionSecretSyncActions } from "@app/context/ProjectPermissionContext/types";
import { IntegrationsListPageTabs } from "@app/types/integrations";
@@ -18,7 +18,7 @@ import {
export const IntegrationsListPage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { t } = useTranslation();
const { selectedTab } = useSearch({
@@ -30,7 +30,7 @@ export const IntegrationsListPage = () => {
to: ROUTE_PATHS.SecretManager.IntegrationsListPage.path,
search: (prev) => ({ ...prev, selectedTab: tab as IntegrationsListPageTabs }),
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}
});
};
diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/components/CloudIntegrationSection/CloudIntegrationSection.tsx b/frontend/src/pages/secret-manager/IntegrationsListPage/components/CloudIntegrationSection/CloudIntegrationSection.tsx
index 935ad1a8cd..42f661606e 100644
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/components/CloudIntegrationSection/CloudIntegrationSection.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/components/CloudIntegrationSection/CloudIntegrationSection.tsx
@@ -24,8 +24,8 @@ import { ROUTE_PATHS } from "@app/const/routes";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { SecretSync } from "@app/hooks/api/secretSyncs";
@@ -60,7 +60,7 @@ export const CloudIntegrationSection = ({
"deleteConfirmation"
] as const);
const { permission } = useProjectPermission();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
const isEmpty = !isLoading && !cloudIntegrations?.length;
@@ -68,12 +68,12 @@ export const CloudIntegrationSection = ({
const sortedCloudIntegrations = useMemo(() => {
const sortedIntegrations = cloudIntegrations.sort((a, b) => a.name.localeCompare(b.name));
- if (currentWorkspace?.environments.length === 0) {
+ if (currentProject?.environments.length === 0) {
return sortedIntegrations.map((integration) => ({ ...integration, isAvailable: false }));
}
return sortedIntegrations;
- }, [cloudIntegrations, currentWorkspace?.environments]);
+ }, [cloudIntegrations, currentProject?.environments]);
const [search, setSearch] = useState("");
@@ -83,9 +83,9 @@ export const CloudIntegrationSection = ({
return (
<div>
- {currentWorkspace?.environments.length === 0 && (
+ {currentProject?.environments.length === 0 && (
<div className="px-5">
- <NoEnvironmentsBanner projectId={currentWorkspace.id} />
+ <NoEnvironmentsBanner projectId={currentProject.id} />
</div>
)}
<div className="m-4 mt-0 flex flex-col items-start justify-between px-2 text-xl">
@@ -138,7 +138,7 @@ export const CloudIntegrationSection = ({
navigate({
to: ROUTE_PATHS.SecretManager.IntegrationsListPage.path,
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.SecretSyncs,
diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/IntegrationRow.tsx b/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/IntegrationRow.tsx
index df862b8ba1..c83e242546 100644
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/IntegrationRow.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/IntegrationRow.tsx
@@ -15,7 +15,7 @@ import { twMerge } from "tailwind-merge";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Badge, IconButton, Td, Tooltip, Tr } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { TCloudIntegration } from "@app/hooks/api/integrations/types";
import { TIntegration } from "@app/hooks/api/types";
@@ -37,7 +37,7 @@ export const IntegrationRow = ({
cloudIntegration
}: IProps) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { id, secretPath, syncMessage, isSynced } = integration;
@@ -62,7 +62,7 @@ export const IntegrationRow = ({
to: "/projects/secret-management/$projectId/integrations/$integrationId",
params: {
integrationId: integration.id,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
}
})
}
diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/NativeIntegrationsTab.tsx b/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/NativeIntegrationsTab.tsx
index f3706940c1..b4f790075d 100644
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/NativeIntegrationsTab.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/components/NativeIntegrationsTab/NativeIntegrationsTab.tsx
@@ -5,7 +5,7 @@ import { useNavigate } from "@tanstack/react-router";
import { createNotification } from "@app/components/notifications";
import { Button, Checkbox, DeleteActionModal, Spinner } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { usePopUp, useToggle } from "@app/hooks";
import {
useDeleteIntegration,
@@ -27,8 +27,8 @@ enum IntegrationView {
}
export const NativeIntegrationsTab = () => {
- const { currentWorkspace } = useWorkspace();
- const { environments, id: workspaceId } = currentWorkspace;
+ const { currentProject } = useProject();
+ const { environments, id: workspaceId } = currentProject;
const navigate = useNavigate();
const { data: cloudIntegrations, isPending: isCloudIntegrationsLoading } =
@@ -91,7 +91,7 @@ export const NativeIntegrationsTab = () => {
if (!selectedCloudIntegration) return;
try {
- redirectForProviderAuth(currentWorkspace.id, navigate, selectedCloudIntegration);
+ redirectForProviderAuth(currentProject.id, navigate, selectedCloudIntegration);
} catch (error) {
console.error(error);
}
diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/SecretSyncsTable.tsx b/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/SecretSyncsTable.tsx
index fcd42a10fa..ed96dcd45a 100644
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/SecretSyncsTable.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/SecretSyncsTable.tsx
@@ -36,7 +36,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { SECRET_SYNC_MAP } from "@app/helpers/secretSyncs";
import {
getUserTablePreference,
@@ -109,7 +109,7 @@ export const SecretSyncsTable = ({ secretSyncs }: Props) => {
environmentIds: []
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const {
search,
@@ -372,7 +372,7 @@ export const SecretSyncsTable = ({ secretSyncs }: Props) => {
<DropdownMenuItem isDisabled>No Secret Syncs Configured</DropdownMenuItem>
)}
<DropdownMenuLabel>Environment</DropdownMenuLabel>
- {currentWorkspace.environments.map((env) => (
+ {currentProject.environments.map((env) => (
<DropdownMenuItem
onClick={(e) => {
e.preventDefault();
diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncsTab.tsx b/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncsTab.tsx
index 20a3c74df1..f1866cda00 100644
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncsTab.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncsTab.tsx
@@ -1,13 +1,14 @@
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import { faArrowUpRightFromSquare, faBookOpen, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ProjectPermissionCan } from "@app/components/permissions";
import { CreateSecretSyncModal } from "@app/components/secret-syncs";
+import { TSecretSyncForm } from "@app/components/secret-syncs/forms/schemas";
import { Button, Spinner } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionSub, useProject } from "@app/context";
import { ProjectPermissionSecretSyncActions } from "@app/context/ProjectPermissionContext/types";
import { usePopUp } from "@app/hooks";
import { useListSecretSyncs } from "@app/hooks/api/secretSyncs";
@@ -16,14 +17,15 @@ import { SecretSyncsTable } from "./SecretSyncTable";
export const SecretSyncsTab = () => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["addSync"] as const);
+ const [initialSyncFormData, setInitialSyncFormData] = useState<Partial<TSecretSyncForm>>();
- const { addSync, ...search } = useSearch({
+ const { addSync, connectionId, connectionName, ...search } = useSearch({
from: ROUTE_PATHS.SecretManager.IntegrationsListPage.id
});
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
if (!addSync) return;
@@ -32,14 +34,46 @@ export const SecretSyncsTab = () => {
navigate({
to: ROUTE_PATHS.SecretManager.IntegrationsListPage.path,
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search
});
}, [addSync]);
+ useEffect(() => {
+ if (connectionId && connectionName) {
+ const storedFormData = localStorage.getItem("secretSyncFormData");
+
+ if (!storedFormData) return;
+
+ let form: Partial<TSecretSyncForm> = {};
+ try {
+ form = JSON.parse(storedFormData) as TSecretSyncForm;
+ } catch {
+ return;
+ } finally {
+ localStorage.removeItem("secretSyncFormData");
+ }
+
+ handlePopUpOpen("addSync", form.destination);
+
+ setInitialSyncFormData({
+ ...form,
+ connection: { id: connectionId, name: connectionName }
+ });
+
+ navigate({
+ to: ROUTE_PATHS.SecretManager.IntegrationsListPage.path,
+ params: {
+ projectId: currentProject.id
+ },
+ search
+ });
+ }
+ }, [connectionId, connectionName]);
+
const { data: secretSyncs = [], isPending: isSecretSyncsPending } = useListSecretSyncs(
- currentWorkspace.id,
+ currentProject.id,
{
refetchInterval: 30000
}
@@ -100,7 +134,11 @@ export const SecretSyncsTab = () => {
<CreateSecretSyncModal
selectSync={popUp.addSync.data}
isOpen={popUp.addSync.isOpen}
- onOpenChange={(isOpen) => handlePopUpToggle("addSync", isOpen)}
+ initialFormData={initialSyncFormData}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) setInitialSyncFormData(undefined);
+ handlePopUpToggle("addSync", isOpen);
+ }}
/>
</>
);
diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/route.tsx b/frontend/src/pages/secret-manager/IntegrationsListPage/route.tsx
index b7f8236da5..405aec3e95 100644
--- a/frontend/src/pages/secret-manager/IntegrationsListPage/route.tsx
+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/route.tsx
@@ -2,22 +2,24 @@ import { createFileRoute, redirect } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
-import { workspaceKeys } from "@app/hooks/api";
+import { projectKeys } from "@app/hooks/api";
import { TIntegration } from "@app/hooks/api/integrations/types";
+import { fetchWorkspaceIntegrations } from "@app/hooks/api/projects/queries";
import {
fetchSecretSyncsByProjectId,
SecretSync,
secretSyncKeys,
TSecretSync
} from "@app/hooks/api/secretSyncs";
-import { fetchWorkspaceIntegrations } from "@app/hooks/api/workspace/queries";
import { IntegrationsListPageTabs } from "@app/types/integrations";
import { IntegrationsListPage } from "./IntegrationsListPage";
const IntegrationsListPageQuerySchema = z.object({
selectedTab: z.nativeEnum(IntegrationsListPageTabs).optional(),
- addSync: z.nativeEnum(SecretSync).optional()
+ addSync: z.nativeEnum(SecretSync).optional(),
+ connectionId: z.string().optional(),
+ connectionName: z.string().optional()
});
export const Route = createFileRoute(
@@ -57,7 +59,7 @@ export const Route = createFileRoute(
let integrations: TIntegration[];
try {
integrations = await context.queryClient.ensureQueryData({
- queryKey: workspaceKeys.getWorkspaceIntegrations(projectId),
+ queryKey: projectKeys.getProjectIntegrations(projectId),
queryFn: () => fetchWorkspaceIntegrations(projectId)
});
} catch {
diff --git a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
index 910e07eac5..e48cfb78cd 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/OverviewPage.tsx
@@ -63,9 +63,9 @@ import {
ProjectPermissionActions,
ProjectPermissionDynamicSecretActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { ProjectPermissionSecretRotationActions } from "@app/context/ProjectPermissionContext/types";
import {
@@ -92,16 +92,11 @@ import {
import { useGetProjectSecretsOverview } from "@app/hooks/api/dashboard/queries";
import { DashboardSecretsOrderBy, ProjectSecretsImportedBy } from "@app/hooks/api/dashboard/types";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { ProjectVersion } from "@app/hooks/api/projects/types";
import { useUpdateFolderBatch } from "@app/hooks/api/secretFolders/queries";
import { TUpdateFolderBatchDTO } from "@app/hooks/api/secretFolders/types";
import { TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
-import {
- SecretType,
- SecretV3RawSanitized,
- TSecretFolder,
- WorkspaceEnv
-} from "@app/hooks/api/types";
-import { ProjectVersion } from "@app/hooks/api/workspace/types";
+import { ProjectEnv, SecretType, SecretV3RawSanitized, TSecretFolder } from "@app/hooks/api/types";
import {
useDynamicSecretOverview,
useFolderOverview,
@@ -173,10 +168,9 @@ export const OverviewPage = () => {
const [debouncedScrollOffset] = useDebounce(scrollOffset);
const { permission } = useProjectPermission();
const tableRef = useRef<HTMLDivElement>(null);
- const { currentWorkspace } = useWorkspace();
- const isProjectV3 = currentWorkspace?.version === ProjectVersion.V3;
- const workspaceId = currentWorkspace?.id as string;
- const projectSlug = currentWorkspace?.slug as string;
+ const { currentProject, projectId } = useProject();
+ const isProjectV3 = currentProject?.version === ProjectVersion.V3;
+ const projectSlug = currentProject?.slug as string;
const [searchFilter, setSearchFilter] = useState("");
const [debouncedSearchFilter, setDebouncedSearchFilter] = useDebounce(searchFilter);
const secretPath = (routerSearch?.secretPath as string) || "/";
@@ -246,7 +240,7 @@ export const OverviewPage = () => {
};
}, []);
- const userAvailableEnvs = currentWorkspace?.environments || [];
+ const userAvailableEnvs = currentProject?.environments || [];
const userAvailableDynamicSecretEnvs = userAvailableEnvs.filter((env) =>
permission.can(
ProjectPermissionDynamicSecretActions.CreateRootCredential,
@@ -267,7 +261,7 @@ export const OverviewPage = () => {
)
);
- const [filteredEnvs, setFilteredEnvs] = useState<WorkspaceEnv[]>([]);
+ const [filteredEnvs, setFilteredEnvs] = useState<ProjectEnv[]>([]);
const visibleEnvs = filteredEnvs.length ? filteredEnvs : userAvailableEnvs;
const {
@@ -276,7 +270,7 @@ export const OverviewPage = () => {
getImportedSecretByKey,
getEnvImportedSecretKeyCount
} = useGetImportedSecretsAllEnvs({
- projectId: workspaceId,
+ projectId,
path: secretPath,
environments: (userAvailableEnvs || []).map(({ slug }) => slug)
});
@@ -284,7 +278,7 @@ export const OverviewPage = () => {
const isFilteredByResources = Object.values(filter).some(Boolean);
const { isPending: isOverviewLoading, data: overview } = useGetProjectSecretsOverview(
{
- projectId: workspaceId,
+ projectId,
environments: visibleEnvs.map((env) => env.slug),
secretPath,
orderDirection,
@@ -355,9 +349,7 @@ export const OverviewPage = () => {
getSecretRotationStatusesByName
} = useSecretRotationOverview(secretRotations);
- const { secKeys, getEnvSecretKeyCount } = useSecretOverview(
- secrets?.concat(secretImportsShaped) || []
- );
+ const { secKeys, getEnvSecretKeyCount } = useSecretOverview(secrets || []);
const getSecretByKey = useCallback(
(env: string, key: string) => {
@@ -368,7 +360,7 @@ export const OverviewPage = () => {
);
const { data: tags } = useGetWsTags(
- permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags) ? workspaceId : ""
+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags) ? projectId : ""
);
const { mutateAsync: createSecretV3 } = useCreateSecretV3();
@@ -398,7 +390,7 @@ export const OverviewPage = () => {
name: folderName,
path: secretPath,
environment,
- projectId: workspaceId,
+ projectId,
description
});
});
@@ -456,9 +448,8 @@ export const OverviewPage = () => {
try {
await updateFolderBatch({
- projectSlug,
folders: updatedFolders,
- projectId: workspaceId
+ projectId
});
createNotification({
type: "success",
@@ -491,7 +482,7 @@ export const OverviewPage = () => {
);
if (folderName && parentPath && canCreateFolder) {
await createFolder({
- projectId: workspaceId,
+ projectId,
path: parentPath,
environment: env,
name: folderName
@@ -500,7 +491,7 @@ export const OverviewPage = () => {
}
const result = await createSecretV3({
environment: env,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
secretValue: value,
@@ -555,7 +546,7 @@ export const OverviewPage = () => {
try {
const result = await updateSecretV3({
environment: env,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
secretValue,
@@ -586,7 +577,7 @@ export const OverviewPage = () => {
try {
const result = await deleteSecretV3({
environment: env,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
secretId,
@@ -655,7 +646,7 @@ export const OverviewPage = () => {
);
if (folderName && parentPath && canCreateFolder) {
await createFolder({
- projectId: workspaceId,
+ projectId,
environment: slug,
path: parentPath,
name: folderName
@@ -669,7 +660,7 @@ export const OverviewPage = () => {
navigate({
to: "/projects/secret-management/$projectId/secrets/$envSlug",
params: {
- projectId: workspaceId,
+ projectId,
envSlug: slug
},
search: query
@@ -738,6 +729,9 @@ export const OverviewPage = () => {
userAvailableEnvs.forEach((env) => {
secrets?.forEach((secret) => {
+ // bulk actions don't apply to rotation secrets (move/delete)
+ if (secret.isRotatedSecret) return;
+
if (allRowsSelectedOnPage.isChecked) {
delete newChecks[EntryType.SECRET][secret.key];
} else {
@@ -1099,7 +1093,7 @@ export const OverviewPage = () => {
tags={tags}
onChange={setSearchFilter}
environments={userAvailableEnvs}
- projectId={currentWorkspace?.id}
+ projectId={currentProject?.id}
/>
{userAvailableEnvs.length > 0 && (
<div>
@@ -1419,7 +1413,7 @@ export const OverviewPage = () => {
<Link
to="/projects/secret-management/$projectId/settings"
params={{
- projectId: workspaceId
+ projectId
}}
hash="environments"
>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx
index 7087faf72d..d4f8bbafea 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/CreateSecretForm/CreateSecretForm.tsx
@@ -19,8 +19,8 @@ import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
import { getKeyValue } from "@app/helpers/parseEnvVar";
@@ -57,16 +57,15 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
formState: { isSubmitting, errors }
} = useForm<TFormSchema>({ resolver: zodResolver(typeSchema) });
- const { currentWorkspace } = useWorkspace();
+ const { currentProject, projectId } = useProject();
const { permission } = useProjectPermission();
const canReadTags = permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags);
- const workspaceId = currentWorkspace?.id || "";
- const environments = currentWorkspace?.environments || [];
+ const environments = currentProject?.environments || [];
const { mutateAsync: createSecretV3 } = useCreateSecretV3();
const { mutateAsync: createFolder } = useCreateFolder();
const { data: projectTags, isPending: isTagsLoading } = useGetWsTags(
- canReadTags ? workspaceId : ""
+ canReadTags ? projectId : ""
);
const secretKeyInputRef = useRef<HTMLInputElement>(null);
@@ -93,7 +92,7 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
if (folderName && parentPath && canCreateFolder) {
await createFolder({
- projectId: workspaceId,
+ projectId,
path: parentPath,
environment,
name: folderName
@@ -106,7 +105,7 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
return {
...(await createSecretV3({
environment,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
secretValue: value || "",
@@ -176,7 +175,7 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
if (!secretKey || isWholeKeyHighlighted) {
e.preventDefault();
- const keyStr = currentWorkspace.autoCapitalization ? key.toUpperCase() : key;
+ const keyStr = currentProject.autoCapitalization ? key.toUpperCase() : key;
setValue("key", keyStr);
if (value) {
setValue("value", value);
@@ -191,7 +190,7 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
try {
const parsedSlug = slugSchema.parse(slug);
await createWsTag.mutateAsync({
- workspaceID: workspaceId,
+ projectId,
tagSlug: parsedSlug,
tagColor: ""
});
@@ -220,7 +219,7 @@ export const CreateSecretForm = ({ secretPath = "/", onClose }: Props) => {
}}
placeholder="Type your secret name"
onPaste={handlePaste}
- autoCapitalization={currentWorkspace?.autoCapitalization}
+ autoCapitalization={currentProject?.autoCapitalization}
/>
</FormControl>
<Controller
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewSecretRotationRow/SecretOverviewRotationSecretRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewSecretRotationRow/SecretOverviewRotationSecretRow.tsx
new file mode 100644
index 0000000000..f8efdf17ef
--- /dev/null
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewSecretRotationRow/SecretOverviewRotationSecretRow.tsx
@@ -0,0 +1,77 @@
+import { twMerge } from "tailwind-merge";
+
+import { SecretInput, Tooltip } from "@app/components/v2";
+import { Blur } from "@app/components/v2/Blur";
+import { useProject } from "@app/context";
+import { useToggle } from "@app/hooks";
+import { useGetSecretValue } from "@app/hooks/api/dashboard/queries";
+import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
+import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
+
+interface SecretOverviewRotationSecretRowProps {
+ secret: SecretV3RawSanitized | null;
+ isSecretVisible: boolean;
+ environment: string;
+ secretPath: string;
+}
+
+export const SecretOverviewRotationSecretRow = ({
+ secret,
+ isSecretVisible,
+ environment,
+ secretPath
+}: SecretOverviewRotationSecretRowProps) => {
+ const [isFieldFocused, setIsFieldFocused] = useToggle();
+
+ const { currentProject } = useProject();
+
+ const canFetchValue = Boolean(secret);
+
+ const { data: secretValueData, isError } = useGetSecretValue(
+ {
+ secretKey: secret?.key ?? "",
+ environment,
+ secretPath,
+ projectId: currentProject.id
+ },
+ {
+ enabled: canFetchValue && (isSecretVisible || isFieldFocused)
+ }
+ );
+
+ const secretValue = isError
+ ? "Error loading secret value..."
+ : (secretValueData?.valueOverride ?? secretValueData?.value ?? HIDDEN_SECRET_VALUE);
+
+ return (
+ <Tooltip
+ className="max-w-sm"
+ content={secret ? undefined : "You do not have permission to view this secret."}
+ >
+ <tr className="!last:border-b-0 h-full hover:bg-mineshaft-700">
+ <td className="flex h-full items-center" style={{ padding: "0.5rem 1rem" }}>
+ <span className={twMerge(!secret && "blur")}>{secret?.key ?? "********"}</span>
+ </td>
+ <td className="col-span-2 h-full w-full" style={{ padding: "0.5rem 1rem" }}>
+ {/* eslint-disable-next-line no-nested-ternary */}
+ {!secret ? (
+ <div className="h-full pl-4 blur">********</div>
+ ) : secret.secretValueHidden ? (
+ <Blur
+ className="py-0"
+ tooltipText="You do not have permission to read the value of this secret."
+ />
+ ) : (
+ <SecretInput
+ isReadOnly
+ value={secretValue}
+ isVisible={isSecretVisible}
+ onFocus={() => setIsFieldFocused.on()}
+ onBlur={() => setIsFieldFocused.off()}
+ />
+ )}
+ </td>
+ </tr>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewSecretRotationRow/SecretOverviewSecretRotationRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewSecretRotationRow/SecretOverviewSecretRotationRow.tsx
index 17f328fe2e..46a5e73280 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewSecretRotationRow/SecretOverviewSecretRotationRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewSecretRotationRow/SecretOverviewSecretRotationRow.tsx
@@ -16,8 +16,6 @@ import { twMerge } from "tailwind-merge";
import { ProjectPermissionCan } from "@app/components/permissions";
import { SecretRotationV2StatusBadge } from "@app/components/secret-rotations-v2/SecretRotationV2StatusBadge";
import { Badge, IconButton, TableContainer, Tag, Td, Tooltip, Tr } from "@app/components/v2";
-import { Blur } from "@app/components/v2/Blur";
-import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import {
ProjectPermissionSecretRotationActions,
ProjectPermissionSub
@@ -27,6 +25,8 @@ import { useToggle } from "@app/hooks";
import { SecretRotationStatus, TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
import { getExpandedRowStyle } from "@app/pages/secret-manager/OverviewPage/components/utils";
+import { SecretOverviewRotationSecretRow } from "./SecretOverviewRotationSecretRow";
+
type Props = {
secretRotationName: string;
environments: { name: string; slug: string }[];
@@ -256,52 +256,13 @@ export const SecretOverviewSecretRotationRow = ({
<tbody className="border-t-2 border-mineshaft-600">
{secrets.map((secret, index) => {
return (
- <Tooltip
- className="max-w-sm"
- content={
- secret
- ? undefined
- : "You do not have permission to view this secret."
- }
- >
- <tr
- // eslint-disable-next-line react/no-array-index-key
- key={`rotation-secret-${secretRotation.id}-${index}`}
- className="!last:border-b-0 h-full hover:bg-mineshaft-700"
- >
- <td
- className="flex h-full items-center"
- style={{ padding: "0.5rem 1rem" }}
- >
- <span className={twMerge(!secret && "blur")}>
- {secret?.key ?? "********"}
- </span>
- </td>
- <td
- className="col-span-2 h-full w-full"
- style={{ padding: "0.5rem 1rem" }}
- >
- {/* eslint-disable-next-line no-nested-ternary */}
- {!secret ? (
- <div className="h-full pl-4 blur">********</div>
- ) : secret.secretValueHidden ? (
- <Blur
- className="py-0"
- tooltipText="You do not have permission to read the value of this secret."
- />
- ) : (
- <InfisicalSecretInput
- isReadOnly
- value={secret.value}
- isVisible={isSecretVisible}
- secretPath={secretRotation.folder.path}
- environment={secretRotation.environment.slug}
- onChange={() => {}}
- />
- )}
- </td>
- </tr>
- </Tooltip>
+ <SecretOverviewRotationSecretRow
+ key={`rotation-secret-${secretRotation.id}-${index + 1}`}
+ secret={secret}
+ secretPath={secretRotation.folder.path}
+ environment={secretRotation.environment.slug}
+ isSecretVisible={isSecretVisible}
+ />
);
})}
</tbody>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsx
index 4b07e62420..a6ed5fc58d 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretEditRow.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { subject } from "@casl/ability";
import {
@@ -10,14 +10,12 @@ import {
faXmark
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useQueryClient } from "@tanstack/react-query";
import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
-import {
- hasSecretReference,
- SecretReferenceTree
-} from "@app/components/secrets/SecretReferenceDetails";
+import { SecretReferenceTree } from "@app/components/secrets/SecretReferenceDetails";
import {
DeleteActionModal,
IconButton,
@@ -27,12 +25,23 @@ import {
Tooltip
} from "@app/components/v2";
import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
-import { ProjectPermissionActions, ProjectPermissionSub, useProjectPermission } from "@app/context";
+import {
+ ProjectPermissionActions,
+ ProjectPermissionSub,
+ useProject,
+ useProjectPermission
+} from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
import { usePopUp, useToggle } from "@app/hooks";
-import { SecretType } from "@app/hooks/api/types";
+import {
+ dashboardKeys,
+ fetchSecretValue,
+ useGetSecretValue
+} from "@app/hooks/api/dashboard/queries";
+import { ProjectEnv, SecretType, SecretV3RawSanitized } from "@app/hooks/api/types";
import { hasSecretReadValueOrDescribePermission } from "@app/lib/fn/permission";
import { CollapsibleSecretImports } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/CollapsibleSecretImports";
+import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
type Props = {
defaultValue?: string | null;
@@ -56,6 +65,15 @@ type Props = {
) => Promise<void>;
onSecretDelete: (env: string, key: string, secretId?: string) => Promise<void>;
isRotatedSecret?: boolean;
+ isEmpty?: boolean;
+ importedSecret?:
+ | {
+ secretPath: string;
+ secret?: SecretV3RawSanitized;
+ environmentInfo?: ProjectEnv;
+ environment: string;
+ }
+ | undefined;
importedBy?: {
environment: { name: string; slug: string };
folders: {
@@ -81,24 +99,68 @@ export const SecretEditRow = ({
isVisible,
secretId,
isRotatedSecret,
- importedBy
+ importedBy,
+ importedSecret,
+ isEmpty
}: Props) => {
const { handlePopUpOpen, handlePopUpToggle, handlePopUpClose, popUp } = usePopUp([
"editSecret"
] as const);
+ const queryClient = useQueryClient();
+
+ const { currentProject } = useProject();
+
+ const [isFieldFocused, setIsFieldFocused] = useToggle();
+
+ const fetchSecretValueParams = importedSecret
+ ? {
+ environment: importedSecret.environment,
+ secretPath: importedSecret.secretPath,
+ secretKey: importedSecret.secret?.key ?? "",
+ projectId: currentProject.id
+ }
+ : {
+ environment,
+ secretPath,
+ secretKey: secretName,
+ projectId: currentProject.id,
+ isOverride
+ };
+
+ // scott: only fetch value if secret exists, has non-empty value and user has permission
+ const canFetchValue = Boolean(importedSecret ?? secretId) && !isEmpty && !secretValueHidden;
+
+ const {
+ data: secretValueData,
+ isPending: isPendingSecretValueData,
+ isError: isErrorFetchingSecretValue
+ } = useGetSecretValue(fetchSecretValueParams, {
+ enabled: canFetchValue && (isVisible || isFieldFocused)
+ });
+
+ const isFetchingSecretValue = canFetchValue && isPendingSecretValueData;
+ const isSecretValueFetched = Boolean(secretValueData);
+
const {
handleSubmit,
control,
reset,
getValues,
+ setValue,
formState: { isDirty, isSubmitting }
} = useForm({
- values: {
- value: defaultValue || null
+ defaultValues: {
+ value: secretValueData?.valueOverride ?? secretValueData?.value ?? (defaultValue || null)
}
});
+ useEffect(() => {
+ if (secretValueData && !isDirty) {
+ setValue("value", secretValueData.valueOverride ?? secretValueData.value);
+ }
+ }, [secretValueData]);
+
const { permission } = useProjectPermission();
const [isDeleting, setIsDeleting] = useToggle();
@@ -113,6 +175,25 @@ export const SecretEditRow = ({
};
const handleCopySecretToClipboard = async () => {
+ if (!isSecretValueFetched && !isDirty) {
+ try {
+ const data = await fetchSecretValue(fetchSecretValueParams);
+
+ queryClient.setQueryData(dashboardKeys.getSecretValue(fetchSecretValueParams), data);
+
+ await window.navigator.clipboard.writeText(data.valueOverride ?? data.value);
+ createNotification({ type: "success", text: "Copied secret to clipboard" });
+ return;
+ } catch (e) {
+ console.error(e);
+ createNotification({
+ type: "error",
+ text: "Failed to fetch secret value."
+ });
+ return;
+ }
+ }
+
const { value } = getValues();
if (value) {
try {
@@ -221,14 +302,25 @@ export const SecretEditRow = ({
)}
<div className="flex-grow border-r border-r-mineshaft-600 pl-1 pr-2">
<Controller
- disabled={isImportedSecret && !defaultValue}
control={control}
name="value"
render={({ field }) => (
<InfisicalSecretInput
{...field}
- isReadOnly={isImportedSecret || (isRotatedSecret && !isOverride)}
- value={field.value as string}
+ isReadOnly={
+ isImportedSecret ||
+ (isRotatedSecret && !isOverride) ||
+ isFetchingSecretValue ||
+ isErrorFetchingSecretValue
+ }
+ value={
+ // eslint-disable-next-line no-nested-ternary
+ isFetchingSecretValue
+ ? HIDDEN_SECRET_VALUE
+ : isErrorFetchingSecretValue
+ ? "Error fetching secret value..."
+ : (field.value as string)
+ }
key="secret-input"
isVisible={isVisible && !secretValueHidden}
secretPath={secretPath}
@@ -236,6 +328,11 @@ export const SecretEditRow = ({
isImport={isImportedSecret}
defaultValue={secretValueHidden ? "" : undefined}
canEditButNotView={secretValueHidden && !isOverride}
+ onFocus={() => setIsFieldFocused.on()}
+ onBlur={() => {
+ field.onBlur();
+ setIsFieldFocused.off();
+ }}
/>
)}
/>
@@ -309,18 +406,12 @@ export const SecretEditRow = ({
<Modal>
<ModalTrigger asChild>
<div className="opacity-0 group-hover:opacity-100">
- <Tooltip
- content={
- hasSecretReference(defaultValue || "")
- ? "Secret Reference Tree"
- : "Secret does not contain references"
- }
- >
+ <Tooltip content="Secret Reference Tree">
<IconButton
variant="plain"
ariaLabel="reference-tree"
className="h-full"
- isDisabled={!hasSecretReference(defaultValue || "") || !canReadSecretValue}
+ isDisabled={!canReadSecretValue || !secretId || isEmpty}
>
<FontAwesomeIcon icon={faProjectDiagram} />
</IconButton>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx
index 006b9b0d66..cb23078807 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretOverviewTableRow.tsx
@@ -22,7 +22,7 @@ import {
} from "@app/context/ProjectPermissionContext/types";
import { useToggle } from "@app/hooks";
import { SecretType, SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { getExpandedRowStyle } from "@app/pages/secret-manager/OverviewPage/components/utils";
import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
@@ -50,7 +50,14 @@ type Props = {
getImportedSecretByKey: (
env: string,
secretName: string
- ) => { secret?: SecretV3RawSanitized; environmentInfo?: WorkspaceEnv } | undefined;
+ ) =>
+ | {
+ secret?: SecretV3RawSanitized;
+ secretPath: string;
+ environment: string;
+ environmentInfo?: ProjectEnv;
+ }
+ | undefined;
scrollOffset: number;
importedBy?: {
environment: { name: string; slug: string };
@@ -140,7 +147,7 @@ export const SecretOverviewTableRow = ({
const isSecretImported = isImportedSecretPresentInEnv(slug, secretKey);
const isSecretPresent = Boolean(secret);
- const isSecretEmpty = secret?.value === "";
+ const isSecretEmpty = secret?.isEmpty;
return (
<Td
key={`sec-overview-${slug}-${i + 1}-value`}
@@ -254,7 +261,7 @@ export const SecretOverviewTableRow = ({
<FontAwesomeIcon icon={faRotate} />
</Tooltip>
)}
- {secret?.valueOverride && (
+ {secret?.idOverride && (
<Tooltip content="Personal Override">
<FontAwesomeIcon icon={faCodeBranch} />
</Tooltip>
@@ -266,11 +273,13 @@ export const SecretOverviewTableRow = ({
secretPath={secretPath}
isVisible={isSecretVisible}
secretName={secretKey}
+ isEmpty={secret?.isEmpty}
secretValueHidden={secret?.secretValueHidden || false}
defaultValue={getDefaultValue(secret, importedSecret)}
secretId={secret?.id}
- isOverride={Boolean(secret?.valueOverride)}
+ isOverride={Boolean(secret?.idOverride)}
isImportedSecret={isImportedSecret}
+ importedSecret={importedSecret}
isCreatable={isCreatable}
onSecretDelete={onSecretDelete}
onSecretCreate={onSecretCreate}
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretRenameRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretRenameRow.tsx
index d15e96a91e..5e1f27f57d 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretRenameRow.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretOverviewTableRow/SecretRenameRow.tsx
@@ -10,7 +10,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { IconButton, Input, Spinner, Tooltip } from "@app/components/v2";
-import { ProjectPermissionSub, useProjectPermission, useWorkspace } from "@app/context";
+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
import { useToggle } from "@app/hooks";
import { useUpdateSecretV3 } from "@app/hooks/api";
@@ -37,7 +37,7 @@ export const formSchema = z.object({
type TFormSchema = z.infer<typeof formSchema>;
function SecretRenameRow({ environments, getSecretByKey, secretKey, secretPath }: Props) {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject, projectId } = useProject();
const { permission } = useProjectPermission();
const secrets = environments.map((env) => getSecretByKey(env.slug, secretKey));
@@ -68,7 +68,6 @@ function SecretRenameRow({ environments, getSecretByKey, secretKey, secretPath }
secret?.overrideAction === SecretActionType.Created ||
secret?.overrideAction === SecretActionType.Modified
);
- const workspaceId = currentWorkspace?.id || "";
const [isSecNameCopied, setIsSecNameCopied] = useToggle(false);
@@ -111,7 +110,7 @@ function SecretRenameRow({ environments, getSecretByKey, secretKey, secretPath }
return updateSecretV3({
environment: secret?.env,
- workspaceId,
+ projectId,
secretPath,
secretKey: secret.key,
secretValue: secret.value || "",
@@ -163,7 +162,7 @@ function SecretRenameRow({ environments, getSecretByKey, secretKey, secretPath }
<Input
autoComplete="off"
isReadOnly={isReadOnly || secrets.filter(Boolean).length === 0}
- autoCapitalization={currentWorkspace?.autoCapitalization}
+ autoCapitalization={currentProject?.autoCapitalization}
variant="plain"
isDisabled={isOverriden}
placeholder={error?.message}
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx
index a4a3fcde47..0c4b46b85d 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchModal.tsx
@@ -33,8 +33,8 @@ import {
} from "@app/components/v2";
import { useDebounce } from "@app/hooks";
import { useGetProjectSecretsQuickSearch } from "@app/hooks/api/dashboard";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import { WsTag } from "@app/hooks/api/tags/types";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
import { QuickSearchSecretRotationItem } from "@app/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchSecretRotationItem";
import { RowType } from "@app/pages/secret-manager/SecretDashboardPage/SecretMainPage.types";
@@ -43,7 +43,7 @@ import { QuickSearchFolderItem } from "./QuickSearchFolderItem";
import { QuickSearchSecretItem } from "./QuickSearchSecretItem";
export type QuickSearchModalProps = {
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
projectId: string;
tags?: WsTag[];
isSingleEnv?: boolean;
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchSecretItem.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchSecretItem.tsx
index a9d592b1ce..b90edef1d6 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchSecretItem.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretSearchInput/components/QuickSearchSecretItem.tsx
@@ -25,13 +25,15 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
+import { useProject } from "@app/context";
import { reverseTruncate } from "@app/helpers/reverseTruncate";
import { useTimedReset } from "@app/hooks";
+import { fetchSecretValue } from "@app/hooks/api/dashboard/queries";
import { TDashboardProjectSecretsQuickSearch } from "@app/hooks/api/dashboard/types";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
type Props = {
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
secretGroup: TDashboardProjectSecretsQuickSearch["secrets"][string];
onClose: () => void;
isSingleEnv?: boolean;
@@ -53,6 +55,8 @@ export const QuickSearchSecretItem = ({
initialState: false
});
+ const { currentProject } = useProject();
+
const [groupSecret] = secretGroup;
const handleNavigate = () => {
@@ -67,14 +71,29 @@ export const QuickSearchSecretItem = ({
onClose();
};
- const handleCopy = (value: string, env: string) => {
- navigator.clipboard.writeText(value);
- createNotification({
- type: "info",
- title: isSingleEnv ? "Secret value copied." : `Secret value copied from ${env}.`,
- text: ""
- });
- setIsUrlCopied(true);
+ const handleCopy = async (env: string) => {
+ try {
+ const data = await fetchSecretValue({
+ environment: groupSecret.env,
+ secretPath: groupSecret.path!,
+ secretKey: groupSecret.key,
+ projectId: currentProject.id
+ });
+
+ navigator.clipboard.writeText(data.valueOverride ?? data.value!);
+ createNotification({
+ type: "info",
+ title: isSingleEnv ? "Secret value copied." : `Secret value copied from ${env}.`,
+ text: ""
+ });
+ setIsUrlCopied(true);
+ } catch (error) {
+ console.error(error);
+ createNotification({
+ type: "error",
+ text: "Error fetching secret value"
+ });
+ }
};
const secretGroupTags = secretGroup.flatMap((secret) => secret.tags);
@@ -146,7 +165,7 @@ export const QuickSearchSecretItem = ({
e.stopPropagation();
const el = envSlugMap.get(groupSecret.env)?.name;
if (el) {
- handleCopy(groupSecret.value!, el);
+ handleCopy(el);
}
}}
>
@@ -173,7 +192,7 @@ export const QuickSearchSecretItem = ({
e.stopPropagation();
const el = envSlugMap.get(secret.env)?.name;
if (el) {
- handleCopy(secret.value!, el);
+ handleCopy(el);
}
}}
key={secret.id}
@@ -214,7 +233,7 @@ export const QuickSearchSecretItem = ({
e.stopPropagation();
const el = envSlugMap.get(secret.env)?.name;
if (el) {
- handleCopy(secret.value!, el);
+ handleCopy(el);
}
}}
key={secret.id}
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretV2MigrationSection/SecretV2MigrationSection.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretV2MigrationSection/SecretV2MigrationSection.tsx
index 14faa7e9e2..0485898273 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretV2MigrationSection/SecretV2MigrationSection.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretV2MigrationSection/SecretV2MigrationSection.tsx
@@ -8,11 +8,11 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, Checkbox, Modal, ModalContent, Spinner } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import { usePopUp } from "@app/hooks";
-import { useGetWorkspaceById, useMigrateProjectToV3, workspaceKeys } from "@app/hooks/api";
+import { projectKeys, useGetWorkspaceById, useMigrateProjectToV3 } from "@app/hooks/api";
+import { ProjectVersion } from "@app/hooks/api/projects/types";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { ProjectVersion } from "@app/hooks/api/workspace/types";
enum ProjectUpgradeStatus {
InProgress = "IN_PROGRESS",
@@ -28,14 +28,14 @@ const formSchema = z.object({
export const SecretV2MigrationSection = () => {
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["migrationInfo"] as const);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const queryClient = useQueryClient();
const { data: workspaceDetails, refetch } = useGetWorkspaceById(
// if v3 no need to fetch
- currentWorkspace?.version === ProjectVersion.V3 ? "" : currentWorkspace?.id || "",
+ currentProject?.version === ProjectVersion.V3 ? "" : currentProject?.id || "",
{
refetchInterval:
- currentWorkspace?.upgradeStatus === ProjectUpgradeStatus.InProgress ? 2000 : false
+ currentProject?.upgradeStatus === ProjectUpgradeStatus.InProgress ? 2000 : false
}
);
const { membership } = useProjectPermission();
@@ -54,12 +54,12 @@ export const SecretV2MigrationSection = () => {
createNotification({ type: "success", text: "Project upgrade completed successfully" });
migrateProjectToV3.reset();
queryClient.invalidateQueries({
- queryKey: workspaceKeys.getAllUserWorkspace()
+ queryKey: projectKeys.getAllUserProjects()
});
}
}, [isProjectUpgraded, Boolean(migrateProjectToV3.data)]);
- if (isProjectUpgraded || currentWorkspace?.version === ProjectVersion.V3) return null;
+ if (isProjectUpgraded || currentProject?.version === ProjectVersion.V3) return null;
const isUpgrading = workspaceDetails?.upgradeStatus === ProjectUpgradeStatus.InProgress;
const didProjectUpgradeFailed = workspaceDetails?.upgradeStatus === ProjectUpgradeStatus.Failed;
@@ -67,7 +67,7 @@ export const SecretV2MigrationSection = () => {
const handleMigrationSecretV2 = async () => {
try {
handlePopUpToggle("migrationInfo");
- await migrateProjectToV3.mutateAsync({ workspaceId: currentWorkspace?.id || "" });
+ await migrateProjectToV3.mutateAsync({ projectId: currentProject?.id || "" });
refetch();
createNotification({
text: "Project upgrade started",
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx
index 11ee3def8b..8f84cd6122 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/SelectionPanel.tsx
@@ -9,9 +9,9 @@ import { Button, DeleteActionModal, Tooltip } from "@app/components/v2";
import {
ProjectPermissionActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
import { usePopUp } from "@app/hooks";
@@ -66,9 +66,8 @@ export const SelectionPanel = ({
);
const selectedCount = selectedFolderCount + selectedKeysCount;
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
- const userAvailableEnvs = currentWorkspace?.environments || [];
+ const { currentProject, projectId } = useProject();
+ const userAvailableEnvs = currentProject?.environments || [];
const { mutateAsync: deleteBatchSecretV3 } = useDeleteSecretBatch();
const { mutateAsync: deleteFolder } = useDeleteFolder();
@@ -134,7 +133,7 @@ export const SelectionPanel = ({
folderId: folder?.id,
path: secretPath,
environment: env.slug,
- projectId: workspaceId
+ projectId
});
}
})
@@ -173,7 +172,7 @@ export const SelectionPanel = ({
processedEntries += secretsToDelete.length;
await deleteBatchSecretV3({
secretPath,
- workspaceId,
+ projectId,
environment: env.slug,
secrets: secretsToDelete
});
@@ -281,8 +280,8 @@ export const SelectionPanel = ({
isOpen={popUp.bulkMoveSecrets.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("bulkMoveSecrets", isOpen)}
environments={userAvailableEnvs}
- projectId={workspaceId}
- projectSlug={currentWorkspace.slug}
+ projectId={projectId}
+ projectSlug={currentProject.slug}
sourceSecretPath={secretPath}
secrets={selectedEntries[EntryType.SECRET]}
onComplete={resetSelectedEntries}
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx
index bb7862f091..30ea57957b 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SelectionPanel/components/MoveSecretsDialog/MoveSecretsDialog.tsx
@@ -30,13 +30,13 @@ import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionCo
import { useDebounce } from "@app/hooks";
import { useMoveSecrets } from "@app/hooks/api";
import { useGetProjectSecretsQuickSearch } from "@app/hooks/api/dashboard";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
projectId: string;
projectSlug: string;
sourceSecretPath: string;
@@ -64,7 +64,6 @@ type MoveResults = {
const Content = ({
onComplete,
secrets,
- projectSlug,
environments,
projectId,
sourceSecretPath
@@ -189,7 +188,6 @@ const Content = ({
try {
const { isDestinationUpdated, isSourceUpdated } = await moveSecrets.mutateAsync({
- projectSlug,
shouldOverwrite,
sourceEnvironment: environment.slug,
sourceSecretPath,
diff --git a/frontend/src/pages/secret-manager/OverviewPage/route.tsx b/frontend/src/pages/secret-manager/OverviewPage/route.tsx
index 968286e139..2be6c6f258 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/route.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/route.tsx
@@ -6,7 +6,9 @@ import { OverviewPage } from "./OverviewPage";
const SecretOverviewPageQuerySchema = z.object({
search: z.string().catch(""),
- secretPath: z.string().catch("/")
+ secretPath: z.string().catch("/"),
+ connectionId: z.string().optional(),
+ connectionName: z.string().optional()
});
export const Route = createFileRoute(
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/SecretApprovalsPage.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/SecretApprovalsPage.tsx
index bc82e9b90b..77106a57c2 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/SecretApprovalsPage.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/SecretApprovalsPage.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";
import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import { Badge } from "@app/components/v2/Badge";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useGetAccessRequestsCount, useGetSecretApprovalRequestCount } from "@app/hooks/api";
import { AccessApprovalRequest } from "./components/AccessApprovalRequest";
@@ -20,11 +20,10 @@ enum TabSection {
export const SecretApprovalsPage = () => {
const { t } = useTranslation();
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
- const projectSlug = currentWorkspace?.slug || "";
+ const { currentProject, projectId } = useProject();
+ const projectSlug = currentProject?.slug || "";
const { data: secretApprovalReqCount } = useGetSecretApprovalRequestCount({
- workspaceId: projectId
+ projectId
});
const { data: accessApprovalRequestCount } = useGetAccessRequestsCount({ projectSlug });
const defaultTab =
@@ -67,7 +66,7 @@ export const SecretApprovalsPage = () => {
<AccessApprovalRequest projectId={projectId} projectSlug={projectSlug} />
</TabPanel>
<TabPanel value={TabSection.Policies}>
- <ApprovalPolicyList workspaceId={projectId} />
+ <ApprovalPolicyList projectId={projectId} />
</TabPanel>
</Tabs>
</div>
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx
index ad905c1f6c..ca04665a5f 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/AccessApprovalRequest.tsx
@@ -39,10 +39,10 @@ import { Badge } from "@app/components/v2/Badge";
import {
ProjectPermissionMemberActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
useSubscription,
- useUser,
- useWorkspace
+ useUser
} from "@app/context";
import {
getUserTablePreference,
@@ -110,7 +110,7 @@ export const AccessApprovalRequest = ({
const { permission } = useProjectPermission();
const { user } = useUser();
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: members } = useGetWorkspaceUsers(projectId, true);
const membersGroupById = members?.reduce<Record<string, TWorkspaceUser>>(
@@ -410,7 +410,7 @@ export const AccessApprovalRequest = ({
<DropdownMenuLabel className="sticky top-0 bg-mineshaft-900">
Select an Environment
</DropdownMenuLabel>
- {currentWorkspace?.environments.map(({ slug, name }) => (
+ {currentProject?.environments.map(({ slug, name }) => (
<DropdownMenuItem
onClick={() => setEnvFilter((state) => (state === slug ? undefined : slug))}
key={`request-filter-${slug}`}
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx
index e7269298a5..a9691724db 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/AccessApprovalRequest/components/ReviewAccessModal.tsx
@@ -25,7 +25,7 @@ import {
Tooltip
} from "@app/components/v2";
import { Badge } from "@app/components/v2/Badge";
-import { ProjectPermissionActions, useUser, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, useProject, useUser } from "@app/context";
import { usePopUp } from "@app/hooks";
import { useListWorkspaceGroups, useReviewAccessRequest } from "@app/hooks/api";
import {
@@ -102,8 +102,8 @@ export const ReviewAccessRequestModal = ({
const [bypassApproval, setBypassApproval] = useState(false);
const [bypassReason, setBypassReason] = useState("");
- const { currentWorkspace } = useWorkspace();
- const { data: groupMemberships = [] } = useListWorkspaceGroups(currentWorkspace?.id || "");
+ const { currentProject } = useProject();
+ const { data: groupMemberships = [] } = useListWorkspaceGroups(currentProject?.id || "");
const { user } = useUser();
const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["editRequest"] as const);
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/ApprovalPolicyList.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/ApprovalPolicyList.tsx
index 3d292f9a28..bb20643e81 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/ApprovalPolicyList.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/ApprovalPolicyList.tsx
@@ -40,9 +40,9 @@ import {
import {
ProjectPermissionSub,
TProjectPermission,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { ProjectPermissionActions } from "@app/context/ProjectPermissionContext/types";
import {
@@ -59,14 +59,14 @@ import {
import { useGetAccessApprovalPolicies } from "@app/hooks/api/accessApproval/queries";
import { OrderByDirection } from "@app/hooks/api/generic/types";
import { PolicyType } from "@app/hooks/api/policies/enums";
-import { TAccessApprovalPolicy, Workspace } from "@app/hooks/api/types";
+import { Project, TAccessApprovalPolicy } from "@app/hooks/api/types";
import { AccessPolicyForm } from "./components/AccessPolicyModal";
import { ApprovalPolicyRow } from "./components/ApprovalPolicyRow";
import { RemoveApprovalPolicyModal } from "./components/RemoveApprovalPolicyModal";
interface IProps {
- workspaceId: string;
+ projectId: string;
}
enum PolicyOrderBy {
@@ -81,24 +81,24 @@ type PolicyFilters = {
environmentIds: string[];
};
-const useApprovalPolicies = (permission: TProjectPermission, currentWorkspace?: Workspace) => {
+const useApprovalPolicies = (permission: TProjectPermission, currentProject?: Project) => {
const { data: accessPolicies, isPending: isAccessPoliciesLoading } = useGetAccessApprovalPolicies(
{
- projectSlug: currentWorkspace?.slug as string,
+ projectSlug: currentProject?.slug as string,
options: {
enabled:
permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretApproval) &&
- !!currentWorkspace?.slug
+ !!currentProject?.slug
}
}
);
const { data: secretPolicies, isPending: isSecretPoliciesLoading } = useGetSecretApprovalPolicies(
{
- workspaceId: currentWorkspace?.id as string,
+ projectId: currentProject?.id as string,
options: {
enabled:
permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.SecretApproval) &&
- !!currentWorkspace?.id
+ !!currentProject?.id
}
}
);
@@ -118,7 +118,7 @@ const useApprovalPolicies = (permission: TProjectPermission, currentWorkspace?:
};
};
-export const ApprovalPolicyList = ({ workspaceId }: IProps) => {
+export const ApprovalPolicyList = ({ projectId }: IProps) => {
const { handlePopUpToggle, handlePopUpOpen, popUp } = usePopUp([
"policyForm",
"deletePolicy",
@@ -126,14 +126,14 @@ export const ApprovalPolicyList = ({ workspaceId }: IProps) => {
] as const);
const { permission } = useProjectPermission();
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
- const { data: members } = useGetWorkspaceUsers(workspaceId, true);
- const { data: groups } = useListWorkspaceGroups(currentWorkspace?.id || "");
+ const { data: members } = useGetWorkspaceUsers(projectId, true);
+ const { data: groups } = useListWorkspaceGroups(currentProject?.id || "");
const { policies, isLoading: isPoliciesLoading } = useApprovalPolicies(
permission,
- currentWorkspace
+ currentProject
);
const [filters, setFilters] = useState<PolicyFilters>({
@@ -367,7 +367,7 @@ export const ApprovalPolicyList = ({ workspaceId }: IProps) => {
Change Policy
</DropdownMenuItem>
<DropdownMenuLabel>Environment</DropdownMenuLabel>
- {currentWorkspace.environments.map((env) => (
+ {currentProject.environments.map((env) => (
<DropdownMenuItem
onClick={(e) => {
e.preventDefault();
@@ -466,7 +466,7 @@ export const ApprovalPolicyList = ({ workspaceId }: IProps) => {
</Td>
</Tr>
)}
- {!!currentWorkspace &&
+ {!!currentProject &&
filteredPolicies
?.slice(offset, perPage * page)
.map((policy) => (
@@ -497,8 +497,8 @@ export const ApprovalPolicyList = ({ workspaceId }: IProps) => {
</div>
</motion.div>
<AccessPolicyForm
- projectId={currentWorkspace.id}
- projectSlug={currentWorkspace.slug}
+ projectId={currentProject.id}
+ projectSlug={currentProject.slug}
isOpen={popUp.policyForm.isOpen}
onToggle={(isOpen) => handlePopUpToggle("policyForm", isOpen)}
members={members}
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx
index 856c16ee17..b78b8aa0c1 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/AccessPolicyModal.tsx
@@ -22,7 +22,7 @@ import {
Tooltip
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { getMemberLabel } from "@app/helpers/members";
import { policyDetails } from "@app/helpers/policies";
import {
@@ -207,10 +207,10 @@ const Form = ({
name: "sequenceApprovers"
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: groups } = useListWorkspaceGroups(projectId);
- const availableEnvironments = currentWorkspace?.environments || [];
+ const availableEnvironments = currentProject?.environments || [];
const isAccessPolicyType = watch("policyType") === PolicyType.AccessPolicy;
const { mutateAsync: createAccessApprovalPolicy } = useCreateAccessApprovalPolicy();
@@ -246,7 +246,7 @@ const Form = ({
approvers: [...userApprovers, ...groupApprovers],
bypassers: bypassers.length > 0 ? bypassers : undefined,
environments: environments.map((env) => env.slug),
- workspaceId: currentWorkspace?.id || ""
+ projectId: currentProject?.id || ""
});
} else {
await createAccessApprovalPolicy({
@@ -302,7 +302,7 @@ const Form = ({
...data,
approvers: [...userApprovers, ...groupApprovers],
bypassers: bypassers.length > 0 ? bypassers : undefined,
- workspaceId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
environments: environments.map((env) => env.slug)
});
} else {
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsx
index 89a97003e6..13147b37ba 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/ApprovalPolicyRow.tsx
@@ -33,13 +33,13 @@ import { Approver } from "@app/hooks/api/accessApproval/types";
import { TGroupMembership } from "@app/hooks/api/groups/types";
import { EnforcementLevel, PolicyType } from "@app/hooks/api/policies/enums";
import { ApproverType } from "@app/hooks/api/secretApproval/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { TWorkspaceUser } from "@app/hooks/api/users/types";
interface IPolicy {
id: string;
name: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
projectId?: string;
secretPath?: string;
approvals: number;
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/RemoveApprovalPolicyModal.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/RemoveApprovalPolicyModal.tsx
index d267ffc785..c9f92f6ede 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/RemoveApprovalPolicyModal.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/ApprovalPolicyList/components/RemoveApprovalPolicyModal.tsx
@@ -4,7 +4,7 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { DeleteActionModal, Spinner } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useDeleteAccessApprovalPolicy,
useDeleteSecretApprovalPolicy,
@@ -29,18 +29,18 @@ export const RemoveApprovalPolicyModal = ({
const { mutateAsync: deleteSecretApprovalPolicy } = useDeleteSecretApprovalPolicy();
const { mutateAsync: deleteAccessApprovalPolicy } = useDeleteAccessApprovalPolicy();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const handleDeletePolicy = async () => {
try {
if (policyType === PolicyType.ChangePolicy) {
await deleteSecretApprovalPolicy({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
id: policyId
});
} else {
await deleteAccessApprovalPolicy({
- projectSlug: currentWorkspace.slug,
+ projectSlug: currentProject.slug,
id: policyId
});
}
@@ -59,14 +59,14 @@ export const RemoveApprovalPolicyModal = ({
const deleteSecretApprovalData = useGetSecretApprovalRequestCount({
policyId,
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
options: {
enabled: Boolean(policyId) && policyType === PolicyType.ChangePolicy
}
});
const deleteAccessApprovalData = useGetAccessRequestsCount({
- projectSlug: currentWorkspace.slug,
+ projectSlug: currentProject.slug,
policyId,
options: {
enabled: Boolean(policyId) && policyType === PolicyType.AccessPolicy
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/SecretApprovalRequest.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/SecretApprovalRequest.tsx
index 46b611328f..827d14f1e5 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/SecretApprovalRequest.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/SecretApprovalRequest.tsx
@@ -35,9 +35,9 @@ import { ROUTE_PATHS } from "@app/const/routes";
import {
ProjectPermissionMemberActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useUser,
- useWorkspace
+ useUser
} from "@app/context";
import {
getUserTablePreference,
@@ -58,8 +58,7 @@ import {
} from "./components/SecretApprovalRequestChanges";
export const SecretApprovalRequest = () => {
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject, projectId } = useProject();
const [selectedApprovalId, setSelectedApprovalId] = useState<string | null>(null);
// filters
@@ -92,7 +91,7 @@ export const SecretApprovalRequest = () => {
isPending: isApprovalRequestLoading,
refetch
} = useGetSecretApprovalRequests({
- workspaceId,
+ projectId,
status: statusFilter,
environment: envFilter,
committer: committerFilter,
@@ -105,14 +104,14 @@ export const SecretApprovalRequest = () => {
const secretApprovalRequests = data?.approvals ?? [];
const { data: secretApprovalRequestCount, isSuccess: isSecretApprovalReqCountSuccess } =
- useGetSecretApprovalRequestCount({ workspaceId });
+ useGetSecretApprovalRequestCount({ projectId });
const { user: userSession } = useUser();
const search = useSearch({
from: ROUTE_PATHS.SecretManager.ApprovalPage.id
});
const { permission } = useProjectPermission();
- const { data: members } = useGetWorkspaceUsers(workspaceId);
+ const { data: members } = useGetWorkspaceUsers(projectId);
const isSecretApprovalScreen = Boolean(selectedApprovalId);
const { requestId } = search;
@@ -143,7 +142,6 @@ export const SecretApprovalRequest = () => {
exit={{ opacity: 0, translateX: 30 }}
>
<SecretApprovalRequestChanges
- workspaceId={workspaceId}
approvalRequestId={selectedApprovalId || ""}
onGoBack={handleGoBackSecretRequestDetail}
/>
@@ -241,7 +239,7 @@ export const SecretApprovalRequest = () => {
<DropdownMenuLabel className="sticky top-0 bg-mineshaft-900">
Select an Environment
</DropdownMenuLabel>
- {currentWorkspace?.environments.map(({ slug, name }) => (
+ {currentProject?.environments.map(({ slug, name }) => (
<DropdownMenuItem
onClick={() => setEnvFilter((state) => (state === slug ? undefined : slug))}
key={`request-filter-${slug}`}
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestAction.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestAction.tsx
index ee45a442b4..9bafb36d45 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestAction.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestAction.tsx
@@ -13,6 +13,7 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { Button, Checkbox, FormControl, Input } from "@app/components/v2";
+import { useProject } from "@app/context";
import {
usePerformSecretApprovalRequestMerge,
useUpdateSecretApprovalRequestStatus
@@ -28,7 +29,6 @@ type Props = {
canApprove?: boolean;
isBypasser: boolean;
statusChangeByEmail?: string;
- workspaceId: string;
enforcementLevel: EnforcementLevel;
};
@@ -39,11 +39,11 @@ export const SecretApprovalRequestAction = ({
isMergable,
approvals,
statusChangeByEmail,
- workspaceId,
enforcementLevel,
canApprove,
isBypasser
}: Props) => {
+ const { projectId } = useProject();
const { mutateAsync: performSecretApprovalMerge, isPending: isMerging } =
usePerformSecretApprovalRequestMerge();
@@ -62,7 +62,7 @@ export const SecretApprovalRequestAction = ({
try {
await performSecretApprovalMerge({
id: approvalRequestId,
- workspaceId,
+ projectId,
bypassReason: byPassApproval ? bypassReason : undefined
});
createNotification({
@@ -83,7 +83,7 @@ export const SecretApprovalRequestAction = ({
await updateSecretStatusChange({
id: approvalRequestId,
status: reqState,
- workspaceId
+ projectId
});
createNotification({
type: "success",
diff --git a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestChanges.tsx b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestChanges.tsx
index 636952c336..0cce12c476 100644
--- a/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestChanges.tsx
+++ b/frontend/src/pages/secret-manager/SecretApprovalsPage/components/SecretApprovalRequest/components/SecretApprovalRequestChanges.tsx
@@ -33,7 +33,7 @@ import {
TextArea,
Tooltip
} from "@app/components/v2";
-import { useUser, useWorkspace } from "@app/context";
+import { useProject, useUser } from "@app/context";
import { usePopUp } from "@app/hooks";
import {
useGetSecretApprovalRequestDetails,
@@ -92,7 +92,6 @@ const getReviewedStatusSymbol = (status?: ApprovalStatus) => {
};
type Props = {
- workspaceId: string;
approvalRequestId: string;
onGoBack: () => void;
};
@@ -104,13 +103,9 @@ const reviewFormSchema = z.object({
type TReviewFormSchema = z.infer<typeof reviewFormSchema>;
-export const SecretApprovalRequestChanges = ({
- approvalRequestId,
- onGoBack,
- workspaceId
-}: Props) => {
+export const SecretApprovalRequestChanges = ({ approvalRequestId, onGoBack }: Props) => {
const { user: userSession } = useUser();
- const { currentWorkspace } = useWorkspace();
+ const { projectId } = useProject();
const {
data: secretApprovalRequestDetails,
isSuccess: isSecretApprovalRequestSuccess,
@@ -123,7 +118,7 @@ export const SecretApprovalRequestChanges = ({
);
const { data: secretImports } = useGetSecretImports({
environment: secretApprovalRequestDetails?.environment || "",
- projectId: currentWorkspace.id,
+ projectId,
path: approvalSecretPath
});
@@ -526,7 +521,6 @@ export const SecretApprovalRequestChanges = ({
isMergable={isMergable}
statusChangeByEmail={secretApprovalRequestDetails.statusChangedByUser?.email}
enforcementLevel={secretApprovalRequestDetails.policy.enforcementLevel}
- workspaceId={workspaceId}
/>
</div>
</div>
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/SecretDashboardPage.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/SecretDashboardPage.tsx
index a6ae7be628..9b757e963c 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/SecretDashboardPage.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/SecretDashboardPage.tsx
@@ -25,8 +25,8 @@ import {
ProjectPermissionActions,
ProjectPermissionDynamicSecretActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import {
ProjectPermissionCommitsActions,
@@ -47,13 +47,15 @@ import {
useGetWsTags
} from "@app/hooks/api";
import { useGetProjectSecretsDetails } from "@app/hooks/api/dashboard";
+import { dashboardKeys } from "@app/hooks/api/dashboard/queries";
import { DashboardSecretsOrderBy } from "@app/hooks/api/dashboard/types";
import { useGetFolderCommitsCount } from "@app/hooks/api/folderCommits";
import { OrderByDirection } from "@app/hooks/api/generic/types";
+import { ProjectVersion } from "@app/hooks/api/projects/types";
+import { queryClient } from "@app/hooks/api/reactQuery";
import { PendingAction } from "@app/hooks/api/secretFolders/types";
import { useCreateCommit } from "@app/hooks/api/secrets/mutations";
import { SecretV3RawSanitized } from "@app/hooks/api/types";
-import { ProjectVersion } from "@app/hooks/api/workspace/types";
import { usePathAccessPolicies } from "@app/hooks/usePathAccessPolicies";
import { useResizableColWidth } from "@app/hooks/useResizableColWidth";
import { hasSecretReadValueOrDescribePermission } from "@app/lib/fn/permission";
@@ -94,7 +96,7 @@ const LOADER_TEXT = [
];
const Page = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate({
from: ROUTE_PATHS.SecretManager.SecretDashboardPage.path
});
@@ -142,15 +144,19 @@ const Page = () => {
] as const);
// env slug
- const workspaceId = currentWorkspace?.id || "";
- const projectSlug = currentWorkspace?.slug || "";
+ const projectId = currentProject?.id || "";
+ const projectSlug = currentProject?.slug || "";
const secretPath = (routerQueryParams.secretPath as string) || "/";
useEffect(() => {
- if (isBatchMode && workspaceId && environment && secretPath) {
- loadPendingChanges({ workspaceId, environment, secretPath });
+ if (isBatchMode && projectId && environment && secretPath) {
+ loadPendingChanges({ projectId, environment, secretPath });
}
- }, [isBatchMode, workspaceId, environment, secretPath, loadPendingChanges]);
+ }, [isBatchMode, projectId, environment, secretPath, loadPendingChanges]);
+
+ useEffect(() => {
+ if (isVisible) setIsVisible(false);
+ }, [environment]);
const canReadSecret = hasSecretReadValueOrDescribePermission(
permission,
@@ -183,17 +189,6 @@ const Page = () => {
})
);
- const canReadSecretValue = hasSecretReadValueOrDescribePermission(
- permission,
- ProjectPermissionSecretActions.ReadValue,
- {
- environment,
- secretPath,
- secretName: "*",
- secretTags: ["*"]
- }
- );
-
const canReadSecretImports = permission.can(
ProjectPermissionActions.Read,
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
@@ -240,7 +235,7 @@ const Page = () => {
const { togglePopUp } = usePopUpAction();
useEffect(() => {
- if (!currentWorkspace?.environments.find((env) => env.slug === environment)) {
+ if (!currentProject?.environments.find((env) => env.slug === environment)) {
createNotification({
text: "No environment found with given slug",
type: "error"
@@ -248,11 +243,11 @@ const Page = () => {
navigate({
to: "/projects/secret-management/$projectId/overview",
params: {
- projectId: workspaceId
+ projectId
}
});
}
- }, [currentWorkspace, environment]);
+ }, [currentProject, environment]);
const isResourceTypeFiltered = Object.values(filter.include).some(Boolean);
const {
@@ -262,7 +257,7 @@ const Page = () => {
isFetched
} = useGetProjectSecretsDetails({
environment,
- projectId: workspaceId,
+ projectId,
secretPath,
offset,
limit,
@@ -271,7 +266,6 @@ const Page = () => {
orderDirection,
includeImports: canReadSecretImports && (isResourceTypeFiltered ? filter.include.import : true),
includeFolders: isResourceTypeFiltered ? filter.include.folder : true,
- viewSecretValue: canReadSecretValue,
includeDynamicSecrets:
canReadDynamicSecret && (isResourceTypeFiltered ? filter.include.dynamic : true),
includeSecrets: canReadSecret && (isResourceTypeFiltered ? filter.include.secret : true),
@@ -316,7 +310,7 @@ const Page = () => {
// fetch imported secrets to show user the overriden ones
const { data: importedSecrets } = useGetImportedSecretsSingleEnv({
- projectId: workspaceId,
+ projectId,
environment,
path: secretPath,
options: {
@@ -326,13 +320,13 @@ const Page = () => {
// fetch tags
const { data: tags } = useGetWsTags(
- permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags) ? workspaceId : ""
+ permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags) ? projectId : ""
);
const { pathPolicies, hasPathPolicies } = usePathAccessPolicies({ secretPath, environment });
const { data: boardPolicy } = useGetSecretApprovalPolicyOfABoard({
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -341,12 +335,30 @@ const Page = () => {
const handleCreateCommit = async (changes: PendingChanges, message: string) => {
try {
await createCommit({
- workspaceId,
+ projectId,
environment,
secretPath,
pendingChanges: changes,
message
});
+
+ if (!isProtectedBranch) {
+ pendingChanges.secrets.forEach((secret) => {
+ if (secret.type === "update" && secret.secretValue !== undefined) {
+ queryClient.setQueryData(
+ dashboardKeys.getSecretValue({
+ projectId,
+ environment,
+ secretPath,
+ secretKey: secret.newSecretName ?? secret.secretKey,
+ isOverride: false
+ }),
+ { value: secret.secretValue }
+ );
+ }
+ });
+ }
+
createNotification({
text: isProtectedBranch
? "Requested changes have been sent for review"
@@ -368,7 +380,7 @@ const Page = () => {
fetchNextPage: fetchNextSnapshotList,
hasNextPage: hasNextSnapshotListPage
} = useGetWorkspaceSnapshotList({
- workspaceId,
+ projectId,
directory: secretPath,
environment,
isPaused: !popUp.snapshots.isOpen || !canDoReadRollback,
@@ -381,7 +393,7 @@ const Page = () => {
isFetching: isFolderCommitsCountFetching
} = useGetFolderCommitsCount({
directory: secretPath,
- workspaceId,
+ projectId,
environment,
isPaused: !canReadCommits
});
@@ -391,13 +403,13 @@ const Page = () => {
isPending: isSnapshotCountLoading,
isFetching: isSnapshotCountFetching
} = useGetWsSnapshotCount({
- workspaceId,
+ projectId,
environment,
directory: secretPath,
isPaused: !canDoReadRollback
});
- const isPITEnabled = !currentWorkspace?.showSnapshotsLegacy;
+ const isPITEnabled = !currentProject?.showSnapshotsLegacy;
const changesCount = useMemo(() => {
return isPITEnabled ? folderCommitsCount : snapshotCount;
@@ -416,7 +428,7 @@ const Page = () => {
navigate({
to: "/projects/secret-management/$projectId/commits/$environment/$folderId",
params: {
- projectId: workspaceId,
+ projectId,
folderId,
environment
},
@@ -570,6 +582,9 @@ const Page = () => {
const newChecks = { ...selectedSecrets };
secrets?.forEach((secret) => {
+ // bulk actions don't apply to rotation secrets (move/delete)
+ if (secret.isRotatedSecret) return;
+
if (allRowsSelectedOnPage.isChecked) {
delete newChecks[secret.id];
} else {
@@ -601,7 +616,9 @@ const Page = () => {
return secrets;
}
- const mergedSecrets = [...(secrets || [])];
+ const mergedSecrets = [...(secrets || [])] as (SecretV3RawSanitized & {
+ originalKey?: string;
+ })[];
pendingChanges.secrets.forEach((change) => {
switch (change.type) {
@@ -647,12 +664,13 @@ const Page = () => {
? change.tags?.map((tag) => ({
id: tag.id,
slug: tag.slug,
- projectId: workspaceId,
+ projectId,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
__v: 0
})) || []
- : mergedSecrets[updateIndex].tags
+ : mergedSecrets[updateIndex].tags,
+ originalKey: mergedSecrets[updateIndex].key
};
}
break;
@@ -734,7 +752,7 @@ const Page = () => {
const mergedSecrets = getMergedSecretsWithPending();
const mergedFolders = getMergedFoldersWithPending();
- if (!(currentWorkspace?.version === ProjectVersion.V3))
+ if (!(currentProject?.version === ProjectVersion.V3))
return (
<div className="flex h-full w-full flex-col items-center justify-center px-6 text-mineshaft-50 dark:[color-scheme:dark]">
<SecretV2MigrationSection />
@@ -794,8 +812,6 @@ const Page = () => {
<>
<ActionBar
environment={environment}
- workspaceId={workspaceId}
- projectSlug={projectSlug}
secretPath={secretPath}
isVisible={isVisible}
isBatchMode={isBatchMode}
@@ -957,7 +973,7 @@ const Page = () => {
secretImports={imports}
isFetching={isDetailsFetching}
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
importedSecrets={importedSecrets}
/>
@@ -966,7 +982,7 @@ const Page = () => {
<FolderListView
folders={mergedFolders}
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
onNavigateToFolder={handleResetFilter}
canNavigate={isFetched}
@@ -990,7 +1006,7 @@ const Page = () => {
tags={tags}
isVisible={isVisible}
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
isProtectedBranch={isProtectedBranch}
importedBy={importedBy}
@@ -1001,7 +1017,7 @@ const Page = () => {
<CommitForm
onCommit={handleCreateCommit}
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
isCommitting={isCommitPending}
/>
@@ -1052,9 +1068,9 @@ const Page = () => {
>
<CreateSecretForm
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
- autoCapitalize={currentWorkspace?.autoCapitalization}
+ autoCapitalize={currentProject?.autoCapitalization}
isProtectedBranch={isProtectedBranch}
isBatchMode={isBatchMode}
/>
@@ -1073,10 +1089,10 @@ const Page = () => {
)}
<SecretDropzone
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
isSmaller={isNotEmpty}
- environments={currentWorkspace?.environments}
+ environments={currentProject?.environments}
isProtectedBranch={isProtectedBranch}
/>
<PitDrawer
@@ -1094,7 +1110,7 @@ const Page = () => {
<SnapshotView
snapshotId={snapshotId || ""}
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
secrets={secrets}
folders={folders}
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/SecretMainPage.store.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/SecretMainPage.store.tsx
index 15ee3b9c6b..06fecf169c 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/SecretMainPage.store.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/SecretMainPage.store.tsx
@@ -54,6 +54,7 @@ export interface PendingSecretDelete extends BasePendingChange {
type: PendingAction.Delete;
secretKey: string;
secretValue: string;
+ secretValueHidden: boolean;
}
// Folder-related change types
@@ -97,7 +98,7 @@ export interface PendingChanges {
// Context interface for batch operations
export interface BatchContext {
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
}
@@ -257,8 +258,8 @@ type BatchModeState = {
};
};
-const generateContextKey = (workspaceId: string, environment: string, secretPath: string) => {
- return `${workspaceId}_${environment}_${secretPath}`;
+const generateContextKey = (projectId: string, environment: string, secretPath: string) => {
+ return `${projectId}_${environment}_${secretPath}`;
};
const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState> = (set, get) => ({
@@ -272,7 +273,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
addPendingChange: (change: PendingChange, context: BatchContext) =>
set((state) => {
const contextKey = generateContextKey(
- context.workspaceId,
+ context.projectId,
context.environment,
context.secretPath
);
@@ -408,7 +409,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
const mergedUpdate: PendingSecretUpdate = {
...existingUpdate,
secretKey: existingUpdate.secretKey,
- originalValue: existingUpdate.originalValue,
+ originalValue: change.originalValue,
originalComment: existingUpdate.originalComment,
originalSkipMultilineEncoding: existingUpdate.originalSkipMultilineEncoding,
originalTags: existingUpdate.originalTags,
@@ -551,7 +552,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
const currentChanges =
contextKey ===
generateContextKey(
- state.currentContext?.workspaceId || context.workspaceId,
+ state.currentContext?.projectId || context.projectId,
state.currentContext?.environment || context.environment,
state.currentContext?.secretPath || context.secretPath
)
@@ -568,7 +569,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
removePendingChange: (changeId: string, resourceType: string, context: BatchContext) =>
set((state) => {
const contextKey = generateContextKey(
- context.workspaceId,
+ context.projectId,
context.environment,
context.secretPath
);
@@ -593,7 +594,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
state.currentContext &&
contextKey ===
generateContextKey(
- state.currentContext.workspaceId,
+ state.currentContext.projectId,
state.currentContext.environment,
state.currentContext.secretPath
);
@@ -606,7 +607,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
loadPendingChanges: (context) => {
const contextKey = generateContextKey(
- context.workspaceId,
+ context.projectId,
context.environment,
context.secretPath
);
@@ -626,7 +627,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
clearAllPendingChanges: (context) => {
const contextKey = generateContextKey(
- context.workspaceId,
+ context.projectId,
context.environment,
context.secretPath
);
@@ -641,7 +642,7 @@ const createBatchModeStore: StateCreator<CombinedState, [], [], BatchModeState>
state.currentContext &&
contextKey ===
generateContextKey(
- state.currentContext.workspaceId,
+ state.currentContext.projectId,
state.currentContext.environment,
state.currentContext.secretPath
);
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ActionBar.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ActionBar.tsx
index 9252d71a12..226230c1aa 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ActionBar.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ActionBar.tsx
@@ -55,9 +55,9 @@ import {
ProjectPermissionActions,
ProjectPermissionDynamicSecretActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import {
ProjectPermissionCommitsActions,
@@ -109,9 +109,6 @@ type TSecOverwriteOpt = { update: TParsedEnv; create: TParsedEnv };
type Props = {
// switch the secrets type as it gets decrypted after api call
environment: string;
- // @depreciated will be moving all these details to zustand
- workspaceId: string;
- projectSlug: string;
secretPath?: string;
filter: Filter;
tags?: WsTag[];
@@ -142,8 +139,6 @@ type Props = {
export const ActionBar = ({
environment,
- workspaceId,
- projectSlug,
secretPath = "/",
filter,
tags = [],
@@ -164,6 +159,7 @@ export const ActionBar = ({
hasPathPolicies,
onClearFilters
}: Props) => {
+ const { projectId, currentProject } = useProject();
const { handlePopUpOpen, handlePopUpToggle, handlePopUpClose, popUp } = usePopUp([
"addFolder",
"addDynamicSecret",
@@ -196,7 +192,6 @@ export const ActionBar = ({
const { reset: resetSelectedSecret } = useSelectedSecretActions();
const isMultiSelectActive = Boolean(Object.keys(selectedSecrets).length);
- const { currentWorkspace } = useWorkspace();
const { permission } = useProjectPermission();
const handleFolderCreate = async (folderName: string, description: string | null) => {
@@ -214,7 +209,7 @@ export const ActionBar = ({
};
addPendingChange(pendingFolderCreate, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -227,7 +222,7 @@ export const ActionBar = ({
name: folderName,
path: secretPath,
environment,
- projectId: workspaceId,
+ projectId,
description
});
handlePopUpClose("addFolder");
@@ -247,7 +242,7 @@ export const ActionBar = ({
const handleSecretDownload = async () => {
try {
const { secrets: localSecrets, imports: localImportedSecrets } = await fetchProjectSecrets({
- workspaceId,
+ projectId,
expandSecretReferences: true,
includeImports: true,
environment,
@@ -317,7 +312,7 @@ export const ActionBar = ({
try {
await deleteBatchSecretV3({
secretPath,
- workspaceId,
+ projectId,
environment,
secrets: bulkDeletedSecrets.map(({ key }) => ({ secretKey: key, type: SecretType.Shared }))
});
@@ -348,13 +343,12 @@ export const ActionBar = ({
try {
const secretsToMove = Object.values(selectedSecrets);
const { isDestinationUpdated, isSourceUpdated } = await moveSecrets({
- projectSlug,
shouldOverwrite,
sourceEnvironment: environment,
sourceSecretPath: secretPath,
destinationEnvironment,
destinationSecretPath,
- projectId: workspaceId,
+ projectId,
secretIds: secretsToMove.map((sec) => sec.id)
});
@@ -448,7 +442,7 @@ export const ActionBar = ({
const { secrets: batchSecrets } = await fetchDashboardProjectSecretsByKeys({
secretPath: normalizedPath,
environment,
- projectId: workspaceId,
+ projectId,
keys: batch
});
@@ -566,7 +560,7 @@ export const ActionBar = ({
name: folderName,
path: parentPath,
environment,
- projectId: workspaceId
+ projectId
});
createdFolders.add(fullPath);
@@ -598,7 +592,7 @@ export const ActionBar = ({
Object.entries(groupedCreateSecrets).map(([path, secrets]) =>
createSecretBatch({
secretPath: path,
- workspaceId,
+ projectId,
environment,
secrets
})
@@ -628,7 +622,7 @@ export const ActionBar = ({
Object.entries(groupedUpdateSecrets).map(([path, secrets]) =>
updateSecretBatch({
secretPath: path,
- workspaceId,
+ projectId,
environment,
secrets
})
@@ -638,13 +632,12 @@ export const ActionBar = ({
// Invalidate appropriate queries to refresh UI
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
+ queryClient.invalidateQueries({});
+ dashboardKeys.getDashboardSecrets({ projectId, secretPath });
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
- });
- queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ workspaceId })
+ queryKey: secretApprovalRequestKeys.count({ projectId })
});
// Close the modal and show notification
@@ -677,8 +670,8 @@ export const ActionBar = ({
className="w-2/5"
value={filter.searchFilter}
onChange={onSearchChange}
- environments={[currentWorkspace.environments.find((env) => env.slug === environment)!]}
- projectId={workspaceId}
+ environments={[currentProject.environments.find((env) => env.slug === environment)!]}
+ projectId={projectId}
tags={tags}
/>
<div>
@@ -1134,8 +1127,8 @@ export const ActionBar = ({
{/* all the side triggers from actions like modals etc */}
<CreateSecretImportForm
environment={environment}
- workspaceId={workspaceId}
secretPath={secretPath}
+ projectId={projectId}
onUpgradePlan={() => handlePopUpOpen("upgradePlan")}
isOpen={popUp.addSecretImport.isOpen}
onClose={() => handlePopUpClose("addSecretImport")}
@@ -1144,7 +1137,7 @@ export const ActionBar = ({
<CreateDynamicSecretForm
isOpen={popUp.addDynamicSecret.isOpen}
onToggle={(isOpen) => handlePopUpToggle("addDynamicSecret", isOpen)}
- projectSlug={projectSlug}
+ projectSlug={currentProject.slug}
environments={[{ slug: environment, name: environment, id: "not-used" }]}
secretPath={secretPath}
isSingleEnvironmentMode
@@ -1190,8 +1183,8 @@ export const ActionBar = ({
onToggle={(isOpen) => handlePopUpToggle("replicateFolder", isOpen)}
onParsedEnv={handleParsedEnvMultiFolder}
environment={environment}
- environments={currentWorkspace.environments}
- workspaceId={workspaceId}
+ environments={currentProject.environments}
+ projectId={projectId}
secretPath={secretPath}
/>
{subscription && (
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsElastiCacheInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsElastiCacheInputForm.tsx
index 84cf7f7b5c..e458f347c4 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsElastiCacheInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsElastiCacheInputForm.tsx
@@ -19,7 +19,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
const formSchema = z.object({
provider: z.object({
@@ -63,7 +63,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsIamInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsIamInputForm.tsx
index f9ed9967cd..a2cc036ec2 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsIamInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AwsIamInputForm.tsx
@@ -18,9 +18,10 @@ import { useCreateDynamicSecret } from "@app/hooks/api";
import { useGetServerConfig } from "@app/hooks/api/admin";
import {
DynamicSecretAwsIamAuth,
+ DynamicSecretAwsIamCredentialType,
DynamicSecretProviders
} from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { MetadataForm } from "../../DynamicSecretListView/MetadataForm";
@@ -28,6 +29,9 @@ const formSchema = z.object({
provider: z.discriminatedUnion("method", [
z.object({
method: z.literal(DynamicSecretAwsIamAuth.AccessKey),
+ credentialType: z
+ .nativeEnum(DynamicSecretAwsIamCredentialType)
+ .default(DynamicSecretAwsIamCredentialType.IamUser),
accessKey: z.string().trim().min(1),
secretAccessKey: z.string().trim().min(1),
region: z.string().trim().min(1),
@@ -47,6 +51,9 @@ const formSchema = z.object({
}),
z.object({
method: z.literal(DynamicSecretAwsIamAuth.AssumeRole),
+ credentialType: z
+ .nativeEnum(DynamicSecretAwsIamCredentialType)
+ .default(DynamicSecretAwsIamCredentialType.IamUser),
roleArn: z.string().trim().min(1),
region: z.string().trim().min(1),
awsPath: z.string().trim().optional(),
@@ -65,6 +72,9 @@ const formSchema = z.object({
}),
z.object({
method: z.literal(DynamicSecretAwsIamAuth.IRSA),
+ credentialType: z
+ .nativeEnum(DynamicSecretAwsIamCredentialType)
+ .default(DynamicSecretAwsIamCredentialType.IamUser),
region: z.string().trim().min(1),
awsPath: z.string().trim().optional(),
permissionBoundaryPolicyArn: z.string().trim().optional(),
@@ -112,7 +122,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
@@ -137,13 +147,15 @@ export const AwsIamInputForm = ({
environment: isSingleEnvironmentMode ? environments[0] : undefined,
usernameTemplate: "{{randomUsername}}",
provider: {
- method: DynamicSecretAwsIamAuth.AssumeRole
+ method: DynamicSecretAwsIamAuth.AssumeRole,
+ credentialType: DynamicSecretAwsIamCredentialType.IamUser
}
}
});
const createDynamicSecret = useCreateDynamicSecret();
const method = watch("provider.method");
+ const credentialType = watch("provider.credentialType");
const handleCreateDynamicSecret = async ({
name,
@@ -264,6 +276,39 @@ export const AwsIamInputForm = ({
</FormControl>
)}
/>
+ <Controller
+ name="provider.credentialType"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Credential Type"
+ >
+ <>
+ <Select
+ value={value}
+ onValueChange={(val) => onChange(val)}
+ className="w-full border border-mineshaft-500"
+ position="popper"
+ dropdownContainerClassName="max-w-none"
+ >
+ <SelectItem value={DynamicSecretAwsIamCredentialType.IamUser}>
+ IAM User
+ </SelectItem>
+ <SelectItem value={DynamicSecretAwsIamCredentialType.TemporaryCredentials}>
+ Temporary Credentials
+ </SelectItem>
+ </Select>
+ <div className="mt-1 text-xs text-mineshaft-300">
+ {value === DynamicSecretAwsIamCredentialType.IamUser
+ ? "Creates temporary IAM users with access keys"
+ : "Uses STS to generate temporary credentials from your connection. Duration is controlled by the Default TTL setting above."}
+ </div>
+ </>
+ </FormControl>
+ )}
+ />
{method === DynamicSecretAwsIamAuth.AccessKey && (
<div className="flex items-center space-x-2">
<Controller
@@ -318,15 +363,36 @@ export const AwsIamInputForm = ({
</div>
)}
<div className="flex items-center space-x-2">
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
+ <Controller
+ control={control}
+ name="provider.awsPath"
+ defaultValue="/"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS IAM Path"
+ className="flex-grow"
+ isOptional
+ isError={Boolean(error?.message)}
+ errorText={error?.message}
+ >
+ <Input {...field} />
+ </FormControl>
+ )}
+ />
+ )}
<Controller
control={control}
- name="provider.awsPath"
- defaultValue="/"
+ name="provider.region"
+ defaultValue="us-east-1"
render={({ field, fieldState: { error } }) => (
<FormControl
- label="AWS IAM Path"
- className="flex-grow"
- isOptional
+ label="AWS Region"
+ className={
+ credentialType === DynamicSecretAwsIamCredentialType.TemporaryCredentials
+ ? "w-full"
+ : "flex-grow"
+ }
isError={Boolean(error?.message)}
errorText={error?.message}
>
@@ -334,113 +400,106 @@ export const AwsIamInputForm = ({
</FormControl>
)}
/>
+ </div>
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
+ <>
+ <Controller
+ control={control}
+ name="provider.permissionBoundaryPolicyArn"
+ defaultValue=""
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="IAM User Permission Boundary ARN"
+ isError={Boolean(error?.message)}
+ isOptional
+ errorText={error?.message}
+ helperText="ARN to be attached to the generated user for AWS Permission Boundary."
+ >
+ <Input {...field} />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="provider.userGroups"
+ defaultValue=""
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS IAM Groups"
+ isError={Boolean(error?.message)}
+ isOptional
+ errorText={error?.message}
+ helperText="Generated users will get attached to given groups."
+ >
+ <Input {...field} placeholder="group1,group2" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="provider.policyArns"
+ defaultValue=""
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS Policy ARNs"
+ isError={Boolean(error?.message)}
+ isOptional
+ errorText={error?.message}
+ helperText="Generated users will get attached to given policy arns."
+ >
+ <Input
+ {...field}
+ placeholder="arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess"
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="provider.policyDocument"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS IAM Policy Document"
+ isOptional
+ isError={Boolean(error?.message)}
+ errorText={error?.message}
+ helperText="Generated users will have the inline policy."
+ >
+ <TextArea
+ {...field}
+ reSize="none"
+ rows={3}
+ className="border-mineshaft-600 bg-mineshaft-900 text-sm"
+ />
+ </FormControl>
+ )}
+ />
+ </>
+ )}
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
<Controller
control={control}
- name="provider.region"
- defaultValue="us-east-1"
+ name="usernameTemplate"
+ defaultValue=""
render={({ field, fieldState: { error } }) => (
<FormControl
- label="AWS Region"
- className="flex-grow"
+ label="Username Template"
isError={Boolean(error?.message)}
errorText={error?.message}
>
- <Input {...field} />
+ <Input
+ {...field}
+ value={field.value || undefined}
+ className="border-mineshaft-600 bg-mineshaft-900 text-sm"
+ placeholder="{{randomUsername}}"
+ />
</FormControl>
)}
/>
- </div>
- <Controller
- control={control}
- name="provider.permissionBoundaryPolicyArn"
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="IAM User Permission Boundary ARN"
- isError={Boolean(error?.message)}
- isOptional
- errorText={error?.message}
- helperText="ARN to be attached to the generated user for AWS Permission Boundary."
- >
- <Input {...field} />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="provider.userGroups"
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="AWS IAM Groups"
- isError={Boolean(error?.message)}
- isOptional
- errorText={error?.message}
- helperText="Generated users will get attached to given groups."
- >
- <Input {...field} placeholder="group1,group2" />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="provider.policyArns"
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="AWS Policy ARNs"
- isError={Boolean(error?.message)}
- isOptional
- errorText={error?.message}
- helperText="Generated users will get attached to given policy arns."
- >
- <Input
- {...field}
- placeholder="arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess"
- />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="provider.policyDocument"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="AWS IAM Policy Document"
- isOptional
- isError={Boolean(error?.message)}
- errorText={error?.message}
- helperText="Generated users will have the inline policy."
- >
- <TextArea
- {...field}
- reSize="none"
- rows={3}
- className="border-mineshaft-600 bg-mineshaft-900 text-sm"
- />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="usernameTemplate"
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Username Template"
- isError={Boolean(error?.message)}
- errorText={error?.message}
- >
- <Input
- {...field}
- value={field.value || undefined}
- className="border-mineshaft-600 bg-mineshaft-900 text-sm"
- placeholder="{{randomUsername}}"
- />
- </FormControl>
- )}
- />
- <MetadataForm control={control} name="provider.tags" title="Tags" isValueRequired />
+ )}
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
+ <MetadataForm control={control} name="provider.tags" title="Tags" isValueRequired />
+ )}
{!isSingleEnvironmentMode && (
<Controller
control={control}
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureEntraIdInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureEntraIdInputForm.tsx
index 771523828d..6c4ccd65b2 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureEntraIdInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/AzureEntraIdInputForm.tsx
@@ -18,7 +18,7 @@ import { Tooltip } from "@app/components/v2/Tooltip";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { useGetDynamicSecretProviderData } from "@app/hooks/api/dynamicSecret/queries";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
const formSchema = z.object({
selectedUsers: z.array(
@@ -66,7 +66,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx
index 8f99d368cd..0ef4d092d2 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CassandraInputForm.tsx
@@ -19,7 +19,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -66,7 +66,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CouchbaseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CouchbaseInputForm.tsx
index fd2eecaa62..1b42dc7e02 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CouchbaseInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CouchbaseInputForm.tsx
@@ -24,7 +24,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
// Component for managing scopes and collections within a bucket
@@ -265,7 +265,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx
index abe14d82de..dd169727db 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx
@@ -24,7 +24,7 @@ import { AnimatePresence, motion } from "framer-motion";
import { Modal, ModalContent } from "@app/components/v2";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { AwsElastiCacheInputForm } from "./AwsElastiCacheInputForm";
import { AwsIamInputForm } from "./AwsIamInputForm";
@@ -51,7 +51,7 @@ type Props = {
isOpen?: boolean;
onToggle: (isOpen: boolean) => void;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
secretPath: string;
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ElasticSearchInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ElasticSearchInputForm.tsx
index 51dcea68b0..390909e810 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ElasticSearchInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/ElasticSearchInputForm.tsx
@@ -20,7 +20,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const authMethods = [
@@ -87,7 +87,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GcpIamInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GcpIamInputForm.tsx
index f47273aa18..e7518830d8 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GcpIamInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GcpIamInputForm.tsx
@@ -8,7 +8,7 @@ import { createNotification } from "@app/components/notifications";
import { Button, FilterableSelect, FormControl, Input } from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
const validateTTL = (val: string, ctx: z.RefinementCtx) => {
if (!val) return;
@@ -49,7 +49,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GithubInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GithubInputForm.tsx
index 800bc677a3..acac4e0aa6 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GithubInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/GithubInputForm.tsx
@@ -16,7 +16,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
const formSchema = z.object({
provider: z.object({
@@ -44,7 +44,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsx
index 2b08382468..945e46777d 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/KubernetesInputForm.tsx
@@ -28,7 +28,7 @@ import {
DynamicSecretProviders,
KubernetesDynamicSecretCredentialType
} from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
enum RoleType {
@@ -150,7 +150,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/LdapInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/LdapInputForm.tsx
index f2f5c9233e..62f8cdd967 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/LdapInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/LdapInputForm.tsx
@@ -16,7 +16,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
enum CredentialType {
@@ -89,7 +89,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoAtlasInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoAtlasInputForm.tsx
index 821730b08d..05109e5a3b 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoAtlasInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoAtlasInputForm.tsx
@@ -23,7 +23,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -77,7 +77,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoDBInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoDBInputForm.tsx
index 5a89f4649d..646755a8fc 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoDBInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/MongoDBInputForm.tsx
@@ -18,7 +18,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -67,7 +67,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RabbitMqInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RabbitMqInputForm.tsx
index f80c374d84..1c2db7d2af 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RabbitMqInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RabbitMqInputForm.tsx
@@ -18,7 +18,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -71,7 +71,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RedisInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RedisInputForm.tsx
index 4d0c51194f..06bf4e41a2 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RedisInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/RedisInputForm.tsx
@@ -19,7 +19,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -64,7 +64,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapAseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapAseInputForm.tsx
index 413bbe0b6d..507e678205 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapAseInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapAseInputForm.tsx
@@ -18,7 +18,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -62,7 +62,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapHanaInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapHanaInputForm.tsx
index deea1ada1c..38ddbc7f03 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapHanaInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SapHanaInputForm.tsx
@@ -19,7 +19,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -64,7 +64,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SnowflakeInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SnowflakeInputForm.tsx
index 3120d7cef6..30f01c13f4 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SnowflakeInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SnowflakeInputForm.tsx
@@ -18,7 +18,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
const formSchema = z.object({
@@ -62,7 +62,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx
index 050a51754f..b0c18fbd36 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx
@@ -29,7 +29,7 @@ import {
} from "@app/context/OrgPermissionContext/types";
import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders, SqlProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
import { MetadataForm } from "../../DynamicSecretListView/MetadataForm";
@@ -110,7 +110,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/TotpInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/TotpInputForm.tsx
index 1ec9f8a0cd..63680f524d 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/TotpInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/TotpInputForm.tsx
@@ -13,7 +13,7 @@ import {
} from "@app/components/v2";
import { useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { slugSchema } from "@app/lib/schemas";
enum ConfigType {
@@ -66,7 +66,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsx
index d5443b1edf..ca417adb6e 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VerticaInputForm.tsx
@@ -27,7 +27,7 @@ import {
} from "@app/context/OrgPermissionContext/types";
import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";
import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
const passwordRequirementsSchema = z
.object({
@@ -91,7 +91,7 @@ type Props = {
onCancel: () => void;
secretPath: string;
projectSlug: string;
- environments: WorkspaceEnv[];
+ environments: ProjectEnv[];
isSingleEnvironmentMode?: boolean;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx
index 9bdace648e..68d2d8cd08 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx
@@ -14,7 +14,7 @@ import {
SelectItem
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { useSubscription, useWorkspace } from "@app/context";
+import { useProject, useSubscription } from "@app/context";
import { useCreateSecretImport } from "@app/hooks/api";
const typeSchema = z.object({
@@ -32,7 +32,7 @@ type TFormSchema = z.infer<typeof typeSchema>;
type Props = {
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath?: string;
// modal props
isOpen?: boolean;
@@ -43,7 +43,7 @@ type Props = {
export const CreateSecretImportForm = ({
environment,
- workspaceId,
+ projectId,
secretPath = "/",
isOpen,
onClose,
@@ -57,8 +57,8 @@ export const CreateSecretImportForm = ({
watch,
formState: { isSubmitting }
} = useForm<TFormSchema>({ resolver: zodResolver(typeSchema) });
- const { currentWorkspace } = useWorkspace();
- const environments = currentWorkspace?.environments || [];
+ const { currentProject } = useProject();
+ const environments = currentProject?.environments || [];
const selectedEnvironment = watch("environment");
const { subscription } = useSubscription();
@@ -77,7 +77,7 @@ export const CreateSecretImportForm = ({
await createSecretImport({
environment,
- projectId: workspaceId,
+ projectId,
path: secretPath,
isReplication,
import: {
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx
index 606f23fac8..05f00315d6 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/MoveSecretsModal.tsx
@@ -12,7 +12,7 @@ import {
SelectItem
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
@@ -47,8 +47,8 @@ export const MoveSecretsModal = ({ popUp, handlePopUpToggle, onMoveApproved }: P
formState: { isSubmitting }
} = useForm<TFormSchema>({ resolver: zodResolver(formSchema) });
- const { currentWorkspace } = useWorkspace();
- const environments = currentWorkspace?.environments || [];
+ const { currentProject } = useProject();
+ const environments = currentProject?.environments || [];
const selectedEnvironment = watch("environment");
const handleFormSubmit = (data: TFormSchema) => {
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ReplicateFolderFromBoard/ReplicateFolderFromBoard.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ReplicateFolderFromBoard/ReplicateFolderFromBoard.tsx
index 339612a899..5e4cee9536 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ReplicateFolderFromBoard/ReplicateFolderFromBoard.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/ReplicateFolderFromBoard/ReplicateFolderFromBoard.tsx
@@ -48,7 +48,7 @@ type Props = {
env: Record<string, Record<string, { value: string; comments: string[]; secretPath?: string }>>
) => void;
environments?: { name: string; slug: string }[];
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
};
@@ -64,7 +64,7 @@ type SecretStructure = {
export const ReplicateFolderFromBoard = ({
environments = [],
- workspaceId,
+ projectId,
isOpen,
onToggle,
onParsedEnv
@@ -82,14 +82,14 @@ export const ReplicateFolderFromBoard = ({
const [debouncedEnvCopySecretPath] = useDebounce(envCopySecPath);
const { data: accessibleSecrets } = useGetAccessibleSecrets({
- projectId: workspaceId,
+ projectId,
secretPath: "/",
environment: selectedEnvSlug.slug,
recursive: true,
filterByAction: shouldIncludeValues
? ProjectPermissionSecretActions.ReadValue
: ProjectPermissionSecretActions.DescribeSecret,
- options: { enabled: Boolean(workspaceId) && Boolean(selectedEnvSlug) && isOpen }
+ options: { enabled: Boolean(projectId) && Boolean(selectedEnvSlug) && isOpen }
});
const restructureSecrets = useMemo(() => {
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsx
index c3f5e74eeb..dbccd93e03 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CommitForm/CommitForm.tsx
@@ -13,6 +13,7 @@ import { AnimatePresence, motion } from "framer-motion";
import { Badge, Button, Input, Modal, ModalContent } from "@app/components/v2";
import { PendingAction } from "@app/hooks/api/secretFolders/types";
import { SecretVersionDiffView } from "@app/pages/secret-manager/CommitDetailsPage/components/SecretVersionDiffView";
+import { HIDDEN_SECRET_VALUE_API_MASK } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
import {
PendingChange,
@@ -25,14 +26,14 @@ interface CommitFormProps {
onCommit: (changes: PendingChanges, commitMessage: string) => Promise<void>;
isCommitting?: boolean;
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath: string;
}
interface ResourceChangeProps {
change: PendingChange;
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath: string;
}
@@ -105,7 +106,12 @@ const RenderSecretChanges = ({ onDiscard, change }: RenderResourceProps) => {
version: 1, // placeholder, not used
secretKey: change.newSecretName ? existingSecret.key : undefined,
secretValue:
- change.secretValue !== undefined ? (existingSecret.value ?? "") : undefined,
+ // eslint-disable-next-line no-nested-ternary
+ change.secretValue !== undefined
+ ? change.existingSecret.secretValueHidden
+ ? HIDDEN_SECRET_VALUE_API_MASK
+ : (change.originalValue ?? "")
+ : undefined,
tags: change.tags ? (existingSecret.tags?.map((tag) => tag.slug) ?? []) : undefined,
secretMetadata: change.secretMetadata ? existingSecret.secretMetadata : undefined,
skipMultilineEncoding:
@@ -130,7 +136,7 @@ const RenderSecretChanges = ({ onDiscard, change }: RenderResourceProps) => {
}
if (change.type === PendingAction.Delete) {
- const { secretKey, secretValue } = change;
+ const { secretKey, secretValue, secretValueHidden } = change;
return (
<SecretVersionDiffView
onDiscard={onDiscard}
@@ -143,7 +149,12 @@ const RenderSecretChanges = ({ onDiscard, change }: RenderResourceProps) => {
{
version: 1, // placeholder, not used
secretKey,
- secretValue
+ // eslint-disable-next-line no-nested-ternary
+ secretValue: secretValue
+ ? secretValueHidden
+ ? HIDDEN_SECRET_VALUE_API_MASK
+ : secretValue
+ : undefined
}
]
}}
@@ -237,7 +248,7 @@ const RenderFolderChanges = ({ onDiscard, change }: RenderResourceProps) => {
const ResourceChange: React.FC<ResourceChangeProps> = ({
change,
environment,
- workspaceId,
+ projectId,
secretPath
}) => {
const { removePendingChange } = useBatchModeActions();
@@ -245,7 +256,7 @@ const ResourceChange: React.FC<ResourceChangeProps> = ({
const handleDeletePending = useCallback(
(changeType: string, id: string) => {
removePendingChange(id, changeType, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -272,7 +283,7 @@ export const CommitForm: React.FC<CommitFormProps> = ({
onCommit,
isCommitting = false,
environment,
- workspaceId,
+ projectId,
secretPath
}) => {
const { isBatchMode, pendingChanges, totalChangesCount } = useBatchMode();
@@ -291,7 +302,7 @@ export const CommitForm: React.FC<CommitFormProps> = ({
}
await onCommit(pendingChanges, commitMessage);
clearAllPendingChanges({
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -335,9 +346,7 @@ export const CommitForm: React.FC<CommitFormProps> = ({
<div className="ml-6 mt-0.5 flex items-center gap-3">
<Button
size="sm"
- onClick={() =>
- clearAllPendingChanges({ workspaceId, environment, secretPath })
- }
+ onClick={() => clearAllPendingChanges({ projectId, environment, secretPath })}
isDisabled={totalChangesCount === 0}
variant="outline_bg"
className="px-4 hover:border-red/40 hover:bg-red/[0.1]"
@@ -393,7 +402,7 @@ export const CommitForm: React.FC<CommitFormProps> = ({
key={change.id}
change={change}
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
/>
))}
@@ -414,7 +423,7 @@ export const CommitForm: React.FC<CommitFormProps> = ({
key={change.id}
change={change}
environment={environment}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
/>
))}
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/CompareEnvironments.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/CompareEnvironments.tsx
index c3570bf5ac..be13dbf441 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/CompareEnvironments.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/CompareEnvironments.tsx
@@ -38,7 +38,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
getUserTablePreference,
PreferenceKey,
@@ -49,7 +49,7 @@ import { useGetImportedSecretsAllEnvs } from "@app/hooks/api";
import { useGetProjectSecretsOverview } from "@app/hooks/api/dashboard";
import { DashboardSecretsOrderBy } from "@app/hooks/api/dashboard/types";
import { OrderByDirection } from "@app/hooks/api/generic/types";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import { useResizableColWidth } from "@app/hooks/useResizableColWidth";
import {
useDynamicSecretOverview,
@@ -89,10 +89,10 @@ const DEFAULT_FILTER_STATE = {
const COL_WIDTH_OFFSET = 220;
export const CompareEnvironments = ({ secretPath }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const compareEnvironmentsKey = `compare-environments-${currentWorkspace.id}`;
+ const { currentProject } = useProject();
+ const compareEnvironmentsKey = `compare-environments-${currentProject.id}`;
- const [selectedEnvironments, setSelectedEnvironments] = useState<WorkspaceEnv[]>(() => {
+ const [selectedEnvironments, setSelectedEnvironments] = useState<ProjectEnv[]>(() => {
try {
const storedEnvironments = JSON.parse(localStorage.getItem(compareEnvironmentsKey) ?? "[]");
@@ -104,12 +104,12 @@ export const CompareEnvironments = ({ secretPath }: Props) => {
}
});
- return currentWorkspace.environments.filter((env) => potentialEnvs.includes(env.id));
+ return currentProject.environments.filter((env) => potentialEnvs.includes(env.id));
}
} catch {
// do nothing and proceed
}
- return currentWorkspace.environments.slice(0, 2);
+ return currentProject.environments.slice(0, 2);
});
const [filter, setFilter] = useState<Filter>(DEFAULT_FILTER_STATE);
@@ -133,7 +133,7 @@ export const CompareEnvironments = ({ secretPath }: Props) => {
setUserTablePreference("secretCompareTable", PreferenceKey.PerPage, newPerPage);
};
- const workspaceId = currentWorkspace.id;
+ const projectId = currentProject.id;
const [searchFilter, setSearchFilter] = useState("");
const [debouncedSearchFilter] = useDebounce(searchFilter);
const [debouncedSelectedEnvironments] = useDebounce(selectedEnvironments);
@@ -151,19 +151,19 @@ export const CompareEnvironments = ({ secretPath }: Props) => {
getImportedSecretByKey,
getEnvImportedSecretKeyCount
} = useGetImportedSecretsAllEnvs({
- projectId: workspaceId,
+ projectId,
path: secretPath,
- environments: (currentWorkspace.environments || []).map(({ slug }) => slug)
+ environments: (currentProject.environments || []).map(({ slug }) => slug)
});
const compareEnvironments = selectedEnvironments.length
? selectedEnvironments
- : currentWorkspace.environments;
+ : currentProject.environments;
const isFilteredByResources = Object.values(filter).some(Boolean);
const { isPending: isOverviewLoading, data: overview } = useGetProjectSecretsOverview(
{
- projectId: workspaceId,
+ projectId,
environments: compareEnvironments.map((env) => env.slug),
secretPath,
orderDirection,
@@ -579,12 +579,12 @@ export const CompareEnvironments = ({ secretPath }: Props) => {
<FilterableSelect
value={selectedEnvironments}
onChange={(value) => {
- const selected = value as MultiValue<WorkspaceEnv>;
+ const selected = value as MultiValue<ProjectEnv>;
- setSelectedEnvironments((selected as WorkspaceEnv[]) ?? []);
+ setSelectedEnvironments((selected as ProjectEnv[]) ?? []);
}}
placeholder="Leave blank to compare all environments"
- options={currentWorkspace.environments}
+ options={currentProject.environments}
getOptionValue={(option) => option.slug}
getOptionLabel={(option) => option.name}
isMulti
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretRow.tsx
index 095b503567..7f2efca877 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretRow.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CompareEnvironments/components/SecretRow/SecretRow.tsx
@@ -17,7 +17,7 @@ import {
} from "@app/context/ProjectPermissionContext/types";
import { useToggle } from "@app/hooks";
import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
-import { WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv } from "@app/hooks/api/types";
import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
import { EnvironmentStatus, EnvironmentStatusCell, ResourceNameCell } from "../shared";
@@ -32,7 +32,7 @@ type Props = {
getImportedSecretByKey: (
env: string,
secretName: string
- ) => { secret?: SecretV3RawSanitized; environmentInfo?: WorkspaceEnv } | undefined;
+ ) => { secret?: SecretV3RawSanitized; environmentInfo?: ProjectEnv } | undefined;
colWidth: number;
tableWidth: number;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx
index 9b43d820d8..a1ac9c8cb1 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/CreateSecretForm/CreateSecretForm.tsx
@@ -32,7 +32,7 @@ type TFormSchema = z.infer<typeof typeSchema>;
type Props = {
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath?: string;
// modal props
autoCapitalize?: boolean;
@@ -42,7 +42,7 @@ type Props = {
export const CreateSecretForm = ({
environment,
- workspaceId,
+ projectId,
secretPath = "/",
autoCapitalize = true,
isProtectedBranch = false,
@@ -66,7 +66,7 @@ export const CreateSecretForm = ({
const { permission } = useProjectPermission();
const canReadTags = permission.can(ProjectPermissionActions.Read, ProjectPermissionSub.Tags);
const { data: projectTags, isPending: isTagsLoading } = useGetWsTags(
- canReadTags ? workspaceId : ""
+ canReadTags ? projectId : ""
);
const secretKeyInputRef = useRef<HTMLInputElement>(null);
@@ -80,7 +80,7 @@ export const CreateSecretForm = ({
try {
const parsedSlug = slugSchema.parse(slug);
await createWsTag.mutateAsync({
- workspaceID: workspaceId,
+ projectId,
tagSlug: parsedSlug,
tagColor: ""
});
@@ -106,7 +106,8 @@ export const CreateSecretForm = ({
resourceType: "secret"
};
addPendingChange(pendingSecretCreate, {
- workspaceId,
+ projectId,
+
environment,
secretPath
});
@@ -116,7 +117,7 @@ export const CreateSecretForm = ({
}
await createSecretV3({
environment,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
secretValue: value || "",
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsx
index da90513699..0be3da048e 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsx
@@ -154,20 +154,22 @@ const renderOutputForm = (
}
if (provider === DynamicSecretProviders.AwsIam) {
- const { USERNAME, ACCESS_KEY, SECRET_ACCESS_KEY } = data as {
+ const { USERNAME, ACCESS_KEY, SECRET_ACCESS_KEY, SESSION_TOKEN } = data as {
ACCESS_KEY: string;
SECRET_ACCESS_KEY: string;
- USERNAME: string;
+ USERNAME?: string;
+ SESSION_TOKEN?: string;
};
return (
<div>
- <OutputDisplay label="AWS Username" value={USERNAME} />
+ {USERNAME && <OutputDisplay label="AWS IAM Username" value={USERNAME} />}
<OutputDisplay label="AWS IAM Access Key" value={ACCESS_KEY} />
- <OutputDisplay
- label="AWS IAM Secret Key"
- value={SECRET_ACCESS_KEY}
- helperText="Important: Copy these credentials now. You will not be able to see them again after you close the modal."
- />
+ <OutputDisplay label="AWS IAM Secret Key" value={SECRET_ACCESS_KEY} />
+ {SESSION_TOKEN && <OutputDisplay label="AWS IAM Session Token" value={SESSION_TOKEN} />}
+ <div className="mt-2 text-xs text-mineshaft-300">
+ Important: Copy these credentials now. You will not be able to see them again after you
+ close the modal.
+ </div>
</div>
);
}
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAwsIamForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAwsIamForm.tsx
index 926bd44824..a443a8f510 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAwsIamForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretAwsIamForm.tsx
@@ -7,7 +7,11 @@ import { TtlFormLabel } from "@app/components/features";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Select, SelectItem, TextArea } from "@app/components/v2";
import { useGetServerConfig, useUpdateDynamicSecret } from "@app/hooks/api";
-import { DynamicSecretAwsIamAuth, TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";
+import {
+ DynamicSecretAwsIamAuth,
+ DynamicSecretAwsIamCredentialType,
+ TDynamicSecret
+} from "@app/hooks/api/dynamicSecret/types";
import { slugSchema } from "@app/lib/schemas";
import { MetadataForm } from "../MetadataForm";
@@ -16,6 +20,9 @@ const formSchema = z.object({
inputs: z.discriminatedUnion("method", [
z.object({
method: z.literal(DynamicSecretAwsIamAuth.AccessKey),
+ credentialType: z
+ .nativeEnum(DynamicSecretAwsIamCredentialType)
+ .default(DynamicSecretAwsIamCredentialType.IamUser),
accessKey: z.string().trim().min(1),
secretAccessKey: z.string().trim().min(1),
region: z.string().trim().min(1),
@@ -30,6 +37,9 @@ const formSchema = z.object({
}),
z.object({
method: z.literal(DynamicSecretAwsIamAuth.AssumeRole),
+ credentialType: z
+ .nativeEnum(DynamicSecretAwsIamCredentialType)
+ .default(DynamicSecretAwsIamCredentialType.IamUser),
roleArn: z.string().trim().min(1),
region: z.string().trim().min(1),
awsPath: z.string().trim().optional(),
@@ -43,6 +53,9 @@ const formSchema = z.object({
}),
z.object({
method: z.literal(DynamicSecretAwsIamAuth.IRSA),
+ credentialType: z
+ .nativeEnum(DynamicSecretAwsIamCredentialType)
+ .default(DynamicSecretAwsIamCredentialType.IamUser),
region: z.string().trim().min(1),
awsPath: z.string().trim().optional(),
permissionBoundaryPolicyArn: z.string().trim().optional(),
@@ -78,6 +91,7 @@ const formSchema = z.object({
newName: slugSchema().optional(),
usernameTemplate: z.string().trim().nullable().optional()
});
+
type TForm = z.infer<typeof formSchema>;
type Props = {
@@ -115,6 +129,7 @@ export const EditDynamicSecretAwsIamForm = ({
}
});
const method = watch("inputs.method");
+ const credentialType = watch("inputs.credentialType");
const updateDynamicSecret = useUpdateDynamicSecret();
@@ -235,6 +250,39 @@ export const EditDynamicSecretAwsIamForm = ({
</FormControl>
)}
/>
+ <Controller
+ name="inputs.credentialType"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <FormControl
+ errorText={error?.message}
+ isError={Boolean(error?.message)}
+ label="Credential Type"
+ >
+ <>
+ <Select
+ value={value}
+ onValueChange={(val) => onChange(val)}
+ className="w-full border border-mineshaft-500"
+ position="popper"
+ dropdownContainerClassName="max-w-none"
+ >
+ <SelectItem value={DynamicSecretAwsIamCredentialType.IamUser}>
+ IAM User
+ </SelectItem>
+ <SelectItem value={DynamicSecretAwsIamCredentialType.TemporaryCredentials}>
+ Temporary Credentials
+ </SelectItem>
+ </Select>
+ <div className="mt-1 text-xs text-mineshaft-300">
+ {value === DynamicSecretAwsIamCredentialType.IamUser
+ ? "Creates temporary IAM users with access keys"
+ : "Uses STS to generate temporary credentials from your connection. Duration is controlled by the Default TTL setting above."}
+ </div>
+ </>
+ </FormControl>
+ )}
+ />
{method === DynamicSecretAwsIamAuth.AccessKey && (
<div className="flex items-center space-x-2">
<Controller
@@ -289,14 +337,36 @@ export const EditDynamicSecretAwsIamForm = ({
</div>
)}
<div className="flex items-center space-x-2">
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
+ <Controller
+ control={control}
+ name="inputs.awsPath"
+ defaultValue=""
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS IAM Path"
+ className="flex-grow"
+ isOptional
+ isError={Boolean(error?.message)}
+ errorText={error?.message}
+ >
+ <Input {...field} />
+ </FormControl>
+ )}
+ />
+ )}
<Controller
control={control}
- name="inputs.awsPath"
- defaultValue=""
+ name="inputs.region"
+ defaultValue="us-east-1"
render={({ field, fieldState: { error } }) => (
<FormControl
- label="AWS IAM Path"
- className="flex-grow"
+ label="AWS Region"
+ className={
+ credentialType === DynamicSecretAwsIamCredentialType.TemporaryCredentials
+ ? "w-full"
+ : "flex-grow"
+ }
isError={Boolean(error?.message)}
errorText={error?.message}
>
@@ -304,109 +374,102 @@ export const EditDynamicSecretAwsIamForm = ({
</FormControl>
)}
/>
+ </div>
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
+ <>
+ <Controller
+ control={control}
+ name="inputs.userGroups"
+ defaultValue=""
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS IAM Groups"
+ isError={Boolean(error?.message)}
+ isOptional
+ errorText={error?.message}
+ helperText="Generated users will get attached to given groups."
+ >
+ <Input {...field} placeholder="group1,group2" />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="inputs.permissionBoundaryPolicyArn"
+ defaultValue=""
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="IAM User Permission Boundary ARN"
+ isError={Boolean(error?.message)}
+ isOptional
+ errorText={error?.message}
+ helperText="ARN to be attached to the generated user for AWS Permission Boundary."
+ >
+ <Input {...field} />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="inputs.policyArns"
+ defaultValue="datacenter1"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS Policy ARNs"
+ isError={Boolean(error?.message)}
+ isOptional
+ errorText={error?.message}
+ helperText="Generated users will get attached to given policy arns."
+ >
+ <Input {...field} />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="inputs.policyDocument"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="AWS IAM Policy Document"
+ isOptional
+ isError={Boolean(error?.message)}
+ errorText={error?.message}
+ helperText="Generated users will have the inline policy."
+ >
+ <TextArea
+ {...field}
+ reSize="none"
+ rows={3}
+ className="border-mineshaft-600 bg-mineshaft-900 text-sm"
+ />
+ </FormControl>
+ )}
+ />
+ </>
+ )}
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
<Controller
control={control}
- name="inputs.region"
- defaultValue="us-east-1"
+ name="usernameTemplate"
+ defaultValue=""
render={({ field, fieldState: { error } }) => (
<FormControl
- label="AWS Region"
- className="flex-grow"
+ label="Username Template"
isError={Boolean(error?.message)}
errorText={error?.message}
>
- <Input {...field} />
+ <Input
+ {...field}
+ value={field.value || undefined}
+ className="border-mineshaft-600 bg-mineshaft-900 text-sm"
+ />
</FormControl>
)}
/>
- </div>
- <Controller
- control={control}
- name="inputs.userGroups"
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="AWS IAM Groups"
- isError={Boolean(error?.message)}
- isOptional
- errorText={error?.message}
- helperText="Generated users will get attached to given groups."
- >
- <Input {...field} placeholder="group1,group2" />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="inputs.permissionBoundaryPolicyArn"
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="IAM User Permission Boundary ARN"
- isError={Boolean(error?.message)}
- isOptional
- errorText={error?.message}
- helperText="ARN to be attached to the generated user for AWS Permission Boundary."
- >
- <Input {...field} />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="inputs.policyArns"
- defaultValue="datacenter1"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="AWS Policy ARNs"
- isError={Boolean(error?.message)}
- isOptional
- errorText={error?.message}
- helperText="Generated users will get attached to given policy arns."
- >
- <Input {...field} />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="inputs.policyDocument"
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="AWS IAM Policy Document"
- isOptional
- isError={Boolean(error?.message)}
- errorText={error?.message}
- helperText="Generated users will have the inline policy."
- >
- <TextArea
- {...field}
- reSize="none"
- rows={3}
- className="border-mineshaft-600 bg-mineshaft-900 text-sm"
- />
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="usernameTemplate"
- defaultValue=""
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Username Template"
- isError={Boolean(error?.message)}
- errorText={error?.message}
- >
- <Input
- {...field}
- value={field.value || undefined}
- className="border-mineshaft-600 bg-mineshaft-900 text-sm"
- />
- </FormControl>
- )}
- />
- <MetadataForm control={control} name="inputs.tags" title="Tags" isValueRequired />
+ )}
+ {credentialType !== DynamicSecretAwsIamCredentialType.TemporaryCredentials && (
+ <MetadataForm control={control} name="inputs.tags" title="Tags" isValueRequired />
+ )}
</div>
</div>
<div className="mt-4 flex items-center space-x-4">
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/EnvironmentTabs.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/EnvironmentTabs.tsx
index 66fd3a8785..379708fdcd 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/EnvironmentTabs.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/EnvironmentTabs/EnvironmentTabs.tsx
@@ -1,5 +1,5 @@
import { useState } from "react";
-import { faArrowRightArrowLeft, faEllipsisH, faPlus } from "@fortawesome/free-solid-svg-icons";
+import { faEllipsisH, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate, useParams } from "@tanstack/react-router";
@@ -24,12 +24,12 @@ import { ROUTE_PATHS } from "@app/const/routes";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useSubscription,
- useWorkspace
+ useProject,
+ useSubscription
} from "@app/context";
import { usePopUp } from "@app/hooks";
-import { workspaceKeys } from "@app/hooks/api";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { projectKeys } from "@app/hooks/api";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import { AddEnvironmentModal } from "@app/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal";
import { CompareEnvironments } from "../CompareEnvironments";
@@ -45,7 +45,7 @@ type Props = {
const TABS_TO_SHOW = 5;
export const EnvironmentTabs = ({ secretPath }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const currentEnv = useParams({
from: ROUTE_PATHS.SecretManager.SecretDashboardPage.id,
select: (el) => el.envSlug
@@ -54,8 +54,8 @@ export const EnvironmentTabs = ({ secretPath }: Props) => {
const { subscription } = useSubscription();
const isMoreEnvironmentsAllowed =
- subscription?.environmentLimit && currentWorkspace?.environments
- ? currentWorkspace.environments.length < subscription.environmentLimit
+ subscription?.environmentLimit && currentProject?.environments
+ ? currentProject.environments.length < subscription.environmentLimit
: true;
const [isNavigating, setIsNavigating] = useState(false);
@@ -68,20 +68,20 @@ export const EnvironmentTabs = ({ secretPath }: Props) => {
"upgradePlan"
] as const);
- const selectedIndex = currentWorkspace.environments.findIndex((env) => env.slug === currentEnv);
+ const selectedIndex = currentProject.environments.findIndex((env) => env.slug === currentEnv);
- let tabEnvironments: WorkspaceEnv[];
- let dropdownEnvironments: WorkspaceEnv[];
+ let tabEnvironments: ProjectEnv[];
+ let dropdownEnvironments: ProjectEnv[];
if (selectedIndex < TABS_TO_SHOW) {
- tabEnvironments = currentWorkspace.environments.slice(0, TABS_TO_SHOW);
- dropdownEnvironments = currentWorkspace.environments.slice(TABS_TO_SHOW);
+ tabEnvironments = currentProject.environments.slice(0, TABS_TO_SHOW);
+ dropdownEnvironments = currentProject.environments.slice(TABS_TO_SHOW);
} else {
tabEnvironments = [
- ...currentWorkspace.environments.slice(0, TABS_TO_SHOW - 1),
- currentWorkspace.environments[selectedIndex]
+ ...currentProject.environments.slice(0, TABS_TO_SHOW - 1),
+ currentProject.environments[selectedIndex]
];
- dropdownEnvironments = currentWorkspace.environments
+ dropdownEnvironments = currentProject.environments
.slice(TABS_TO_SHOW - 1)
.filter((env) => env.slug !== currentEnv);
}
@@ -96,7 +96,7 @@ export const EnvironmentTabs = ({ secretPath }: Props) => {
to: ROUTE_PATHS.SecretManager.SecretDashboardPage.path,
params: {
envSlug,
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: (prev) => prev
});
@@ -199,14 +199,15 @@ export const EnvironmentTabs = ({ secretPath }: Props) => {
</Tooltip>
</Tab>
)}
- {currentWorkspace.environments.length > 1 && (
+ {/* scott: removing until we have time to update for fetching secret value */}
+ {/* {currentProject.environments.length > 1 && (
<Tab className="ml-auto" value={COMPARE_ENVIRONMENT_TAB}>
<div className="flex items-center gap-x-2 whitespace-nowrap">
<FontAwesomeIcon icon={faArrowRightArrowLeft} />
Compare Environments
</div>
</Tab>
- )}
+ )} */}
</TabList>
</Tabs>
<Modal
@@ -232,7 +233,7 @@ export const EnvironmentTabs = ({ secretPath }: Props) => {
onOpenChange={(isOpen) => handlePopUpToggle("createEnvironment", isOpen)}
onComplete={async (env) => {
await queryClient.refetchQueries({
- queryKey: workspaceKeys.getWorkspaceById(currentWorkspace.id)
+ queryKey: projectKeys.getProjectById(currentProject.id)
});
handleSelect(env.slug);
}}
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/FolderListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/FolderListView.tsx
index fd65bc639d..e35f62bf78 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/FolderListView.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/FolderListView/FolderListView.tsx
@@ -33,7 +33,7 @@ import { FolderForm } from "../ActionBar/FolderForm";
type Props = {
folders?: TSecretFolder[];
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath?: string;
onNavigateToFolder: (path: string) => void;
canNavigate: boolean;
@@ -42,7 +42,7 @@ type Props = {
export const FolderListView = ({
folders = [],
environment,
- workspaceId,
+ projectId,
secretPath = "/",
onNavigateToFolder,
canNavigate
@@ -89,7 +89,7 @@ export const FolderListView = ({
};
addPendingChange(updatedCreate, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -106,7 +106,7 @@ export const FolderListView = ({
};
addPendingChange(updateChange, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -121,7 +121,7 @@ export const FolderListView = ({
name: newFolderName,
path: secretPath,
environment,
- projectId: workspaceId,
+ projectId,
description: newFolderDescription
});
handlePopUpClose("updateFolder");
@@ -140,7 +140,7 @@ export const FolderListView = ({
const handleDeletePending = (id: string) => {
removePendingChange(id, "folder", {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -161,7 +161,7 @@ export const FolderListView = ({
};
addPendingChange(pendingFolderDelete, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -174,7 +174,7 @@ export const FolderListView = ({
folderId: folderData.id,
path: secretPath,
environment,
- projectId: workspaceId
+ projectId
});
handlePopUpClose("deleteFolder");
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/CopySecretsFromBoard.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/CopySecretsFromBoard.tsx
index 3e09a38573..de62d5856d 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/CopySecretsFromBoard.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/CopySecretsFromBoard.tsx
@@ -46,14 +46,14 @@ type Props = {
onToggle: (isOpen: boolean) => void;
onParsedEnv: (env: Record<string, { value: string; comments: string[] }>) => void;
environments?: { name: string; slug: string }[];
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
};
export const CopySecretsFromBoard = ({
environments = [],
- workspaceId,
+ projectId,
environment,
secretPath,
isOpen,
@@ -81,7 +81,7 @@ export const CopySecretsFromBoard = ({
const { data: accessibleSecrets, isPending: isAccessibleSecretsLoading } =
useGetAccessibleSecrets({
- projectId: workspaceId,
+ projectId,
secretPath: debouncedEnvCopySecretPath,
environment: selectedEnvSlug.slug,
filterByAction: shouldIncludeValues
@@ -89,7 +89,7 @@ export const CopySecretsFromBoard = ({
: ProjectPermissionSecretActions.DescribeSecret,
options: {
enabled:
- Boolean(workspaceId) &&
+ Boolean(projectId) &&
Boolean(selectedEnvSlug) &&
Boolean(debouncedEnvCopySecretPath) &&
isOpen
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/SecretDropzone.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/SecretDropzone.tsx
index d7cb87da77..9799d17ad9 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/SecretDropzone.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretDropzone/SecretDropzone.tsx
@@ -53,7 +53,7 @@ type TSecOverwriteOpt = { update: TParsedEnv; create: TParsedEnv };
type Props = {
isSmaller: boolean;
environments?: { name: string; slug: string }[];
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
isProtectedBranch?: boolean;
@@ -140,7 +140,7 @@ const MatrixImportModalTableRow = ({
export const SecretDropzone = ({
isSmaller,
environments = [],
- workspaceId,
+ projectId,
environment,
secretPath,
isProtectedBranch = false
@@ -196,7 +196,7 @@ export const SecretDropzone = ({
const { secrets: existingSecrets } = await fetchDashboardProjectSecretsByKeys({
secretPath,
environment,
- projectId: workspaceId,
+ projectId,
keys: envSecretKeys
});
@@ -334,7 +334,7 @@ export const SecretDropzone = ({
if (Object.keys(create || {}).length) {
await createSecretBatch({
secretPath,
- workspaceId,
+ projectId,
environment,
secrets: Object.entries(create).map(([secretKey, secData]) => ({
type: SecretType.Shared,
@@ -347,7 +347,7 @@ export const SecretDropzone = ({
if (Object.keys(update || {}).length) {
await updateSecretBatch({
secretPath,
- workspaceId,
+ projectId,
environment,
secrets: Object.entries(update).map(([secretKey, secData]) => ({
type: SecretType.Shared,
@@ -358,13 +358,13 @@ export const SecretDropzone = ({
});
}
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ workspaceId })
+ queryKey: secretApprovalRequestKeys.count({ projectId })
});
handlePopUpClose("confirmUpload");
createNotification({
@@ -464,7 +464,7 @@ export const SecretDropzone = ({
onParsedEnv={handleParsedEnv}
environment={environment}
environments={environments}
- workspaceId={workspaceId}
+ projectId={projectId}
secretPath={secretPath}
isSmaller={isSmaller}
/>
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportItem.tsx
index 44886c21f3..59764de781 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportItem.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportItem.tsx
@@ -20,12 +20,14 @@ import { twMerge } from "tailwind-merge";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
-import { EmptyState, IconButton, SecretInput, TableContainer, Tooltip } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { EmptyState, IconButton, TableContainer, Tooltip } from "@app/components/v2";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useToggle } from "@app/hooks";
import { useResyncSecretReplication } from "@app/hooks/api";
import { TSecretImport } from "@app/hooks/api/types";
+import { SecretImportSecretRow } from "./SecretImportSecretRow";
+
type Props = {
onDelete: () => void;
environment: string;
@@ -35,7 +37,10 @@ type Props = {
importedSecrets: {
key: string;
value?: string;
- overriden: { env: string; secretPath: string };
+ overridden: { env: string; secretPath: string };
+ environment: string;
+ secretPath?: string;
+ isEmpty?: boolean;
}[];
searchTerm: string;
onExpandReplicateSecrets: (id: string) => void;
@@ -82,7 +87,7 @@ export const SecretImportItem = ({
lastReplicated,
importEnv
} = secretImport as TSecretImport;
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [isExpanded, setIsExpanded] = useToggle();
const { attributes, listeners, transform, transition, setNodeRef, isDragging } = useSortable({
id
@@ -118,7 +123,7 @@ export const SecretImportItem = ({
id,
environment,
path: secretPath,
- projectId: currentWorkspace?.id || ""
+ projectId: currentProject?.id || ""
});
createNotification({
text: "Please refresh the dashboard to view changes",
@@ -299,7 +304,6 @@ export const SecretImportItem = ({
<tr>
<td style={{ padding: "0.25rem 1rem" }}>Key</td>
<td style={{ padding: "0.25rem 1rem" }}>Value</td>
- {/* <td style={{ padding: "0.25rem 1rem" }}>Override</td> */}
</tr>
</thead>
<tbody>
@@ -317,18 +321,11 @@ export const SecretImportItem = ({
</td>
</tr>
)}
- {filteredImportedSecrets.map(({ key, value }, index) => (
- <tr key={`${id}-${key}-${index + 1}`}>
- <td className="h-10" style={{ padding: "0.25rem 1rem" }}>
- {key}
- </td>
- <td className="h-10" style={{ padding: "0.25rem 1rem" }}>
- <SecretInput value={value} isReadOnly />
- </td>
- {/* <td className="h-10" style={{ padding: "0.25rem 1rem" }}>
- <EnvFolderIcon env={overriden?.env} secretPath={overriden?.secretPath} />
- </td> */}
- </tr>
+ {filteredImportedSecrets.map((secret, index) => (
+ <SecretImportSecretRow
+ secret={secret}
+ key={`${id}-${secret.key}-${index + 1}`}
+ />
))}
</tbody>
</table>
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportListView.tsx
index e212d6da99..7fbbc94364 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportListView.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportListView.tsx
@@ -18,7 +18,7 @@ import { usePopUp } from "@app/hooks";
import { useDeleteSecretImport, useUpdateSecretImport } from "@app/hooks/api";
import { ReservedFolders } from "@app/hooks/api/secretFolders/types";
import { TSecretImport } from "@app/hooks/api/secretImports/types";
-import { SecretV3RawSanitized, WorkspaceEnv } from "@app/hooks/api/types";
+import { ProjectEnv, SecretV3RawSanitized } from "@app/hooks/api/types";
import { formatReservedPaths } from "@app/lib/fn/string";
import { SecretImportItem } from "./SecretImportItem";
@@ -26,7 +26,7 @@ import { SecretImportItem } from "./SecretImportItem";
const SECRET_IN_DASHBOARD = "Present In Dashboard";
type TImportedSecrets = Array<{
- environmentInfo: WorkspaceEnv;
+ environmentInfo: ProjectEnv;
secretPath: string;
folderId: string;
secrets: SecretV3RawSanitized[];
@@ -64,18 +64,24 @@ export const computeImportedSecretRows = (
const importedSecretEntries: {
key: string;
value?: string;
- overriden: {
+ environment: string;
+ secretPath?: string;
+ overridden: {
env: string;
secretPath: string;
};
+ isEmpty?: boolean;
}[] = [];
- importedSec.secrets.forEach(({ key, value }) => {
+ importedSec.secrets.forEach(({ key, value, env, path, isEmpty }) => {
if (!importedEntry[key]) {
importedSecretEntries.push({
key,
value,
- overriden: overridenSec?.[key]
+ environment: env,
+ secretPath: path,
+ overridden: overridenSec?.[key],
+ isEmpty
});
importedEntry[key] = true;
}
@@ -86,7 +92,7 @@ export const computeImportedSecretRows = (
type Props = {
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath?: string;
secretImports?: TSecretImport[];
isFetching?: boolean;
@@ -98,7 +104,7 @@ type Props = {
export const SecretImportListView = ({
secretImports,
environment,
- workspaceId,
+ projectId,
secretPath,
importedSecrets,
// secrets = [],
@@ -132,7 +138,7 @@ export const SecretImportListView = ({
const { id: secretImportId } = popUp.deleteSecretImport?.data as { id: string };
try {
await deleteSecretImport({
- projectId: workspaceId,
+ projectId,
environment,
path: secretPath,
id: secretImportId
@@ -158,7 +164,7 @@ export const SecretImportListView = ({
const newImportOrder = arrayMove(items, oldIndex, newIndex);
setItems(newImportOrder);
updateSecretImport({
- projectId: workspaceId,
+ projectId,
environment,
path: secretPath,
id: active.id as string,
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportSecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportSecretRow.tsx
new file mode 100644
index 0000000000..fd8c8a4403
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretImportListView/SecretImportSecretRow.tsx
@@ -0,0 +1,68 @@
+import { SecretInput } from "@app/components/v2";
+import { useProject } from "@app/context";
+import { useToggle } from "@app/hooks";
+import { useGetSecretValue } from "@app/hooks/api/dashboard/queries";
+import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
+
+type SecretImportSecretRowProps = {
+ secret: {
+ key: string;
+ value?: string;
+ environment: string;
+ secretPath?: string;
+ isEmpty?: boolean;
+ overridden: { env: string; secretPath: string };
+ };
+};
+
+export const SecretImportSecretRow = ({
+ secret: { key, environment, secretPath = "/", isEmpty }
+}: SecretImportSecretRowProps) => {
+ const [isFieldFocused, setIsFieldFocused] = useToggle();
+
+ const { currentProject } = useProject();
+
+ const canFetchSecretValue = !isEmpty;
+
+ const {
+ data: secretValue,
+ isPending: isPendingSecretValue,
+ isError: isErrorFetchingSecretValue
+ } = useGetSecretValue(
+ {
+ environment,
+ secretPath,
+ secretKey: key,
+ projectId: currentProject.id
+ },
+ {
+ enabled: isFieldFocused && canFetchSecretValue
+ }
+ );
+
+ const isLoadingSecretValue = canFetchSecretValue && isPendingSecretValue;
+
+ const getValue = () => {
+ if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
+
+ if (isErrorFetchingSecretValue) return "Error loading secret value";
+
+ return secretValue?.value || "";
+ };
+
+ return (
+ <tr>
+ <td className="h-10 w-1/2" style={{ padding: "0.25rem 1rem" }}>
+ {key}
+ </td>
+ <td className="h-10 w-1/2" style={{ padding: "0.25rem 1rem" }}>
+ <SecretInput
+ value={getValue()}
+ onFocus={() => setIsFieldFocused.on()}
+ onBlur={() => setIsFieldFocused.off()}
+ isReadOnly
+ />
+ </td>
+ </tr>
+ );
+};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CollapsibleSecretImports.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CollapsibleSecretImports.tsx
index 70010fe81b..a1ed019f12 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CollapsibleSecretImports.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CollapsibleSecretImports.tsx
@@ -4,7 +4,7 @@ import { faFileImport, faKey, faSync, faWarning } from "@fortawesome/free-solid-
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Table, TBody, Td, Th, THead, Tooltip, Tr } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { UsedBySecretSyncs } from "@app/hooks/api/dashboard/types";
enum ItemType {
@@ -44,7 +44,7 @@ export const CollapsibleSecretImports: React.FC<CollapsibleSecretImportsProps> =
secretsToDelete,
onlyReferences
}) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const truncatePath = (path: string, maxLength = 24): string => {
if (path.length <= maxLength) return path;
@@ -62,7 +62,7 @@ export const CollapsibleSecretImports: React.FC<CollapsibleSecretImportsProps> =
const handlePathClick = (item: FlatItem) => {
if (item.type === ItemType.SecretSync) {
window.open(
- `/secret-manager/${currentWorkspace.id}/integrations/secret-syncs/${item.destination}/${item.id}`,
+ `/secret-manager/${currentProject.id}/integrations/secret-syncs/${item.destination}/${item.id}`,
"_blank",
"noopener,noreferrer"
);
@@ -78,7 +78,7 @@ export const CollapsibleSecretImports: React.FC<CollapsibleSecretImportsProps> =
}
const encodedPath = encodeURIComponent(pathToNavigate);
window.open(
- `/secret-manager/${currentWorkspace.id}/secrets/${item.environment.slug}?secretPath=${encodedPath}`,
+ `/secret-manager/${currentProject.id}/secrets/${item.environment.slug}?secretPath=${encodedPath}`,
"_blank"
);
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CreateReminderForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CreateReminderForm.tsx
index 78e79d3738..9dc12a1a11 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CreateReminderForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/CreateReminderForm.tsx
@@ -21,7 +21,7 @@ import {
SelectItem,
TextArea
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useGetWorkspaceUsers } from "@app/hooks/api";
import { dashboardKeys } from "@app/hooks/api/dashboard/queries";
import { useCreateReminder, useDeleteReminder } from "@app/hooks/api/reminders";
@@ -52,7 +52,7 @@ interface ReminderFormProps {
isOpen: boolean;
reminderId?: string;
onOpenChange: () => void;
- workspaceId: string;
+ projectId: string;
environment: string;
secretPath: string;
secretId: string;
@@ -118,8 +118,8 @@ const useReminderForm = (reminderData?: Reminder) => {
// Custom hook for workspace members
const useWorkspaceMembers = () => {
- const { currentWorkspace } = useWorkspace();
- const { data: members = [] } = useGetWorkspaceUsers(currentWorkspace?.id);
+ const { currentProject } = useProject();
+ const { data: members = [] } = useGetWorkspaceUsers(currentProject?.id);
const memberOptions = useMemo(
(): RecipientOption[] =>
@@ -137,7 +137,7 @@ const useWorkspaceMembers = () => {
export const CreateReminderForm = ({
isOpen,
onOpenChange,
- workspaceId,
+ projectId,
environment,
secretPath,
secretId,
@@ -185,12 +185,12 @@ export const CreateReminderForm = ({
const invalidateQueries = () => {
queryClient.invalidateQueries({
queryKey: dashboardKeys.getDashboardSecrets({
- projectId: workspaceId,
+ projectId,
secretPath
})
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
queryKey: reminderKeys.getReminder(secretId)
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx
index 953176ff5b..67404f8789 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretDetailSidebar.tsx
@@ -1,36 +1,27 @@
import { useEffect } from "react";
import { Controller, useFieldArray, useForm } from "react-hook-form";
import { subject } from "@casl/ability";
-import { faCircleQuestion, faEye } from "@fortawesome/free-regular-svg-icons";
+import { faCircleQuestion } from "@fortawesome/free-regular-svg-icons";
import {
- faArrowRotateRight,
faCheckCircle,
faCopy,
- faDesktop,
- faEyeSlash,
faPlus,
faProjectDiagram,
faSearch,
- faServer,
faShare,
faTag,
faTrash,
- faTriangleExclamation,
- faUser
+ faTriangleExclamation
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { zodResolver } from "@hookform/resolvers/zod";
-import { Link, useNavigate } from "@tanstack/react-router";
-import { format } from "date-fns";
-import { twMerge } from "tailwind-merge";
+import { useQueryClient } from "@tanstack/react-query";
+import { Link } from "@tanstack/react-router";
import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
-import {
- hasSecretReference,
- SecretReferenceTree
-} from "@app/components/secrets/SecretReferenceDetails";
+import { SecretReferenceTree } from "@app/components/secrets/SecretReferenceDetails";
import {
Button,
Drawer,
@@ -55,14 +46,18 @@ import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { ProjectPermissionSecretActions } from "@app/context/ProjectPermissionContext/types";
import { getProjectBaseURL } from "@app/helpers/project";
-import { usePopUp } from "@app/hooks";
+import { usePopUp, useToggle } from "@app/hooks";
import { useGetSecretVersion } from "@app/hooks/api";
-import { ActorType } from "@app/hooks/api/auditLogs/enums";
+import {
+ dashboardKeys,
+ fetchSecretValue,
+ useGetSecretValue
+} from "@app/hooks/api/dashboard/queries";
import { useGetSecretAccessList } from "@app/hooks/api/secrets/queries";
import { SecretV3RawSanitized, WsTag } from "@app/hooks/api/types";
import { hasSecretReadValueOrDescribePermission } from "@app/lib/fn/permission";
@@ -70,6 +65,7 @@ import { camelCaseToSpaces } from "@app/lib/fn/string";
import { HIDDEN_SECRET_VALUE } from "./SecretItem";
import { formSchema, SecretActionType, TFormSchema } from "./SecretListView.utils";
+import { SecretVersionItem } from "./SecretVersionItem";
type Props = {
isOpen?: boolean;
@@ -77,7 +73,7 @@ type Props = {
secretPath: string;
onToggle: (isOpen: boolean) => void;
onClose: () => void;
- secret: SecretV3RawSanitized;
+ secret: SecretV3RawSanitized & { originalKey?: string };
onDeleteSecret: () => void;
onSaveSecret: (
orgSec: SecretV3RawSanitized,
@@ -92,7 +88,7 @@ type Props = {
export const SecretDetailSidebar = ({
isOpen,
onToggle,
- secret,
+ secret: originalSecret,
onDeleteSecret,
onSaveSecret,
tags,
@@ -101,16 +97,90 @@ export const SecretDetailSidebar = ({
secretPath,
handleSecretShare
}: Props) => {
+ const { currentProject } = useProject();
+ const [isFieldFocused, setIsFieldFocused] = useToggle();
+ const queryClient = useQueryClient();
+
+ const canFetchSecretValue =
+ Boolean(originalSecret) && !originalSecret.secretValueHidden && !originalSecret.isEmpty;
+
+ const fetchSecretValueParams = {
+ environment,
+ secretPath,
+ secretKey: originalSecret?.originalKey || originalSecret?.key,
+ projectId: currentProject.id,
+ isOverride: Boolean(originalSecret?.idOverride)
+ };
+
+ const {
+ data: secretValueData,
+ isPending: isPendingSecretValue,
+ isError: isErrorFetchingSecretValue
+ } = useGetSecretValue(fetchSecretValueParams, {
+ enabled: canFetchSecretValue && isFieldFocused
+ });
+
+ const isLoadingSecretValue = canFetchSecretValue && isPendingSecretValue;
+ const hasFetchedSecretValue = !canFetchSecretValue || Boolean(secretValueData);
+
+ const secret = {
+ ...originalSecret,
+ value: originalSecret?.value ?? secretValueData?.value,
+ valueOverride: originalSecret?.valueOverride ?? secretValueData?.valueOverride
+ };
+
+ const { permission } = useProjectPermission();
+
+ const canEditSecretValue = permission.can(
+ ProjectPermissionSecretActions.Edit,
+ subject(ProjectPermissionSub.Secrets, {
+ environment,
+ secretPath,
+ secretName: secret.key,
+ secretTags: ["*"]
+ })
+ );
+
+ const getDefaultValue = () => {
+ if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
+
+ if (secret.secretValueHidden) {
+ return canEditSecretValue ? HIDDEN_SECRET_VALUE : "";
+ }
+
+ if (isErrorFetchingSecretValue) return "Error loading secret value...";
+
+ return secret.value || "";
+ };
+
+ const getOverrideDefaultValue = () => {
+ if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
+
+ if (secret.secretValueHidden) {
+ return canEditSecretValue ? HIDDEN_SECRET_VALUE : "";
+ }
+
+ if (isErrorFetchingSecretValue) return "Error loading secret value...";
+
+ return secret.valueOverride || "";
+ };
+
const {
control,
watch,
handleSubmit,
setValue,
reset,
+ getValues,
+ getFieldState,
formState: { isDirty }
} = useForm<TFormSchema>({
resolver: zodResolver(formSchema),
- values: secret,
+ values: {
+ ...secret,
+ valueOverride: getOverrideDefaultValue(),
+ value: getDefaultValue()
+ },
disabled: !secret
});
@@ -119,9 +189,6 @@ export const SecretDetailSidebar = ({
"secretReferenceTree"
] as const);
- const { permission } = useProjectPermission();
- const { currentWorkspace } = useWorkspace();
-
const tagFields = useFieldArray({
control,
name: "tags"
@@ -139,7 +206,6 @@ export const SecretDetailSidebar = ({
{}
);
const selectTagSlugs = selectedTags.map((i) => i.slug);
- const navigate = useNavigate();
const cannotEditSecret = permission.cannot(
ProjectPermissionSecretActions.Edit,
@@ -187,7 +253,7 @@ export const SecretDetailSidebar = ({
});
const { data: secretAccessList, isPending } = useGetSecretAccessList({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
environment,
secretPath,
secretKey
@@ -205,7 +271,16 @@ export const SecretDetailSidebar = ({
};
const handleFormSubmit = async (data: TFormSchema) => {
- await onSaveSecret(secret, { ...secret, ...data }, () => reset());
+ await onSaveSecret(
+ secret,
+ {
+ ...secret,
+ ...data,
+ value: getFieldState("value").isDirty ? data.value : undefined,
+ valueOverride: getFieldState("valueOverride").isDirty ? data.valueOverride : undefined
+ },
+ () => reset()
+ );
};
useEffect(() => {
@@ -218,58 +293,22 @@ export const SecretDetailSidebar = ({
);
}, [secret?.secretReminderRecipients]);
- const getModifiedByIcon = (userType: string | undefined | null) => {
- switch (userType) {
- case ActorType.USER:
- return faUser;
- case ActorType.IDENTITY:
- return faDesktop;
- default:
- return faServer;
- }
- };
+ const fetchValue = async () => {
+ if (secretValueData) return secretValueData.valueOverride ?? secretValueData.value;
- const getModifiedByName = (
- userType: string | undefined | null,
- userName: string | null | undefined
- ) => {
- switch (userType) {
- case ActorType.PLATFORM:
- return "System-generated";
- case ActorType.IDENTITY:
- return userName || "Deleted Identity";
- case ActorType.USER:
- return userName || "Deleted User";
- default:
- return "Unknown";
- }
- };
+ try {
+ const data = await fetchSecretValue(fetchSecretValueParams);
- const getLinkToModifyHistoryEntity = (
- actorId: string,
- actorType: string,
- membershipId: string | null = ""
- ) => {
- switch (actorType) {
- case ActorType.USER:
- return `/projects/secret-management/${currentWorkspace.id}/members/${membershipId}`;
- case ActorType.IDENTITY:
- return `/projects/secret-management/${currentWorkspace.id}/identities/${actorId}`;
- default:
- return null;
- }
- };
+ queryClient.setQueryData(dashboardKeys.getSecretValue(fetchSecretValueParams), data);
- const onModifyHistoryClick = (
- actorId: string | undefined | null,
- actorType: string | undefined | null,
- membershipId: string | undefined | null
- ) => {
- if (actorType && actorId && actorType !== ActorType.PLATFORM) {
- const redirectLink = getLinkToModifyHistoryEntity(actorId, actorType, membershipId);
- if (redirectLink) {
- navigate({ to: redirectLink });
- }
+ return data?.valueOverride ?? data.value;
+ } catch (error) {
+ console.error(error);
+ createNotification({
+ type: "error",
+ text: "Error fetching secret value"
+ });
+ throw error;
}
};
@@ -313,6 +352,7 @@ export const SecretDetailSidebar = ({
title={`Secret – ${secret?.key}`}
className="thin-scrollbar h-full"
cardBodyClassName="pb-0"
+ onOpenAutoFocus={(e) => e.preventDefault()}
>
<form
onSubmit={handleSubmit(handleFormSubmit)}
@@ -356,7 +396,14 @@ export const SecretDetailSidebar = ({
>
<div className="flex items-start gap-x-2">
<InfisicalSecretInput
- isReadOnly={isReadOnly || !isAllowed || secret?.isRotatedSecret}
+ isReadOnly={
+ isReadOnly ||
+ !isAllowed ||
+ secret?.isRotatedSecret ||
+ isLoadingSecretValue ||
+ isErrorFetchingSecretValue
+ }
+ canEditButNotView={secret.secretValueHidden && canEditSecretValue}
environment={environment}
secretPath={secretPath}
key="secret-value"
@@ -364,27 +411,36 @@ export const SecretDetailSidebar = ({
containerClassName="text-bunker-300 w-full hover:border-primary-400/50 border border-mineshaft-600 bg-mineshaft-900 px-2 py-1.5"
{...field}
autoFocus={false}
+ onFocus={() => setIsFieldFocused.on()}
+ onBlur={() => {
+ setIsFieldFocused.off();
+ field.onBlur();
+ }}
/>
<Tooltip
content={
- !currentWorkspace.secretSharing
+ !currentProject.secretSharing
? "This project does not allow secret sharing."
: "You don't have permission to view the secret value."
}
- isDisabled={!secret?.secretValueHidden && currentWorkspace.secretSharing}
+ isDisabled={!secret?.secretValueHidden && currentProject.secretSharing}
>
<Button
- isDisabled={
- secret?.secretValueHidden || !currentWorkspace.secretSharing
- }
+ isDisabled={secret?.secretValueHidden || !currentProject.secretSharing}
className="px-2 py-[0.43rem] font-normal"
variant="outline_bg"
leftIcon={<FontAwesomeIcon icon={faShare} />}
- onClick={() => {
- const value = secret?.valueOverride ?? secret?.value;
- if (value) {
- handleSecretShare(value);
+ onClick={async () => {
+ let value: string | undefined;
+
+ if (hasFetchedSecretValue) {
+ const values = getValues(["value", "valueOverride"]);
+ value = secret.idOverride ? values[1] : values[0];
+ } else {
+ value = await fetchValue();
}
+
+ handleSecretShare(value ?? "");
}}
>
Share
@@ -646,179 +702,21 @@ export const SecretDetailSidebar = ({
<div className="dark flex max-h-[24rem] flex-1 cursor-default flex-col text-sm text-bunker-300">
<div className="mb-0.5 text-mineshaft-400">Version History</div>
<div className="thin-scrollbar flex flex-1 flex-col space-y-2 overflow-y-auto overflow-x-hidden rounded-md border border-mineshaft-600 bg-mineshaft-900 p-4 dark:[color-scheme:dark]">
- {secretVersion?.map(
- ({ createdAt, secretValue, secretValueHidden, version, id, actor }) => (
- <div className="flex flex-row" key={id}>
- <div className="flex w-full flex-col space-y-1">
- <div className="flex items-center">
- <div className="w-10">
- <div className="w-fit rounded-md border border-mineshaft-600 bg-mineshaft-700 px-1 text-sm text-mineshaft-300">
- v{version}
- </div>
- </div>
- <div>{format(new Date(createdAt), "Pp")}</div>
- </div>
- <div className="flex w-full cursor-default">
- <div className="relative w-10">
- <div className="absolute bottom-0 left-3 top-0 mt-0.5 border-l border-mineshaft-400/60" />
- </div>
- <div className="flex w-full cursor-default flex-col">
- {actor && (
- <div className="flex flex-row">
- <div className="flex w-fit flex-row text-sm">
- Modified by:
- <Tooltip content={getModifiedByName(actor.actorType, actor.name)}>
- {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
- <div
- onClick={() =>
- onModifyHistoryClick(
- actor.actorId,
- actor.actorType,
- actor.membershipId
- )
- }
- className="cursor-pointer"
- >
- <FontAwesomeIcon
- icon={getModifiedByIcon(actor.actorType)}
- className="ml-2"
- />
- </div>
- </Tooltip>
- </div>
- </div>
- )}
- <div className="flex flex-row">
- <div className="h-min w-fit rounded-sm bg-primary-500/10 px-1 text-primary-300/70">
- Value:
- </div>
- <div className="group break-all pl-1 font-mono">
- <div className="relative hidden cursor-pointer transition-all duration-200 group-[.show-value]:inline">
- <button
- type="button"
- className="select-none text-left"
- onClick={(e) => {
- if (secretValueHidden) return;
-
- navigator.clipboard.writeText(secretValue || "");
- const target = e.currentTarget;
- target.style.borderBottom = "1px dashed";
- target.style.paddingBottom = "-1px";
-
- // Create and insert popup
- const popup = document.createElement("div");
- popup.className =
- "w-16 flex justify-center absolute top-6 left-0 text-xs text-primary-100 bg-mineshaft-800 px-1 py-0.5 rounded-md border border-primary-500/50";
- popup.textContent = "Copied!";
- target.parentElement?.appendChild(popup);
-
- // Remove popup and border after delay
- setTimeout(() => {
- popup.remove();
- target.style.borderBottom = "none";
- }, 3000);
- }}
- onKeyDown={(e) => {
- if (secretValueHidden) return;
-
- if (e.key === "Enter" || e.key === " ") {
- navigator.clipboard.writeText(secretValue || "");
- const target = e.currentTarget;
- target.style.borderBottom = "1px dashed";
- target.style.paddingBottom = "-1px";
-
- // Create and insert popup
- const popup = document.createElement("div");
- popup.className =
- "w-16 flex justify-center absolute top-6 left-0 text-xs text-primary-100 bg-mineshaft-800 px-1 py-0.5 rounded-md border border-primary-500/50";
- popup.textContent = "Copied!";
- target.parentElement?.appendChild(popup);
-
- // Remove popup and border after delay
- setTimeout(() => {
- popup.remove();
- target.style.borderBottom = "none";
- }, 3000);
- }
- }}
- >
- <span
- className={twMerge(
- secretValueHidden && "text-xs text-bunker-300 opacity-40"
- )}
- >
- {secretValueHidden ? "Hidden" : secretValue}
- </span>
- </button>
- <button
- type="button"
- className="ml-1 cursor-pointer"
- onClick={(e) => {
- e.stopPropagation();
- e.currentTarget
- .closest(".group")
- ?.classList.remove("show-value");
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.stopPropagation();
- e.currentTarget
- .closest(".group")
- ?.classList.remove("show-value");
- }
- }}
- >
- <FontAwesomeIcon icon={faEyeSlash} />
- </button>
- </div>
- <span className="group-[.show-value]:hidden">
- {secretValueHidden
- ? HIDDEN_SECRET_VALUE
- : secretValue?.replace(/./g, "*")}
- <button
- type="button"
- className="ml-1 cursor-pointer"
- onClick={(e) => {
- e.currentTarget
- .closest(".group")
- ?.classList.add("show-value");
- }}
- onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
- e.currentTarget
- .closest(".group")
- ?.classList.add("show-value");
- }
- }}
- >
- <FontAwesomeIcon icon={faEye} />
- </button>
- </span>
- </div>
- </div>
- </div>
- </div>
- </div>
- {!secret?.isRotatedSecret && (
- <div
- className={`flex items-center justify-center ${version === secretVersion.length ? "hidden" : ""}`}
- >
- <Tooltip content="Restore Secret Value">
- <IconButton
- ariaLabel="Restore"
- variant="outline_bg"
- size="sm"
- className="h-8 w-8 rounded-md"
- onClick={() => setValue("value", secretValue, { shouldDirty: true })}
- >
- <FontAwesomeIcon icon={faArrowRotateRight} />
- </IconButton>
- </Tooltip>
- </div>
- )}
- </div>
- )
- )}
+ {secretVersion?.map((version) => (
+ <SecretVersionItem
+ canReadValue={!cannotReadSecretValue}
+ secretVersion={version}
+ secret={secret}
+ currentVersion={secretVersion.length}
+ onRevert={async (versionValue) => {
+ await fetchValue();
+
+ setTimeout(() => {
+ setValue("value", versionValue, { shouldDirty: true });
+ }, 5);
+ }}
+ />
+ ))}
</div>
</div>
<div className="dark flex flex-col text-sm text-bunker-300">
@@ -848,10 +746,10 @@ export const SecretDetailSidebar = ({
>
<Link
to={
- `${getProjectBaseURL(currentWorkspace.type)}/members/$membershipId` as const
+ `${getProjectBaseURL(currentProject.type)}/members/$membershipId` as const
}
params={{
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
membershipId: user.membershipId
}}
className="text-secondary/80 rounded-md border border-mineshaft-600 bg-mineshaft-700 px-1 py-0.5 text-sm hover:text-mineshaft-100"
@@ -882,10 +780,10 @@ export const SecretDetailSidebar = ({
>
<Link
to={
- `${getProjectBaseURL(currentWorkspace.type)}/identities/$identityId` as const
+ `${getProjectBaseURL(currentProject.type)}/identities/$identityId` as const
}
params={{
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
identityId: identity.id
}}
className="text-secondary/80 rounded-md border border-mineshaft-600 bg-mineshaft-700 px-1 py-0.5 text-sm hover:text-mineshaft-100"
@@ -944,26 +842,15 @@ export const SecretDetailSidebar = ({
)}
</div>
<div className="mt-auto flex items-center space-x-2 pb-4">
- <Tooltip
- content={
- hasSecretReference(secret?.value)
- ? undefined
- : "Secret does not contain any references."
- }
- className="z-[100] text-center"
+ <Button
+ className="flex-1"
+ variant="outline_bg"
+ isDisabled={cannotReadSecretValue || secret.isEmpty}
+ leftIcon={<FontAwesomeIcon icon={faProjectDiagram} />}
+ onClick={() => handlePopUpOpen("secretReferenceTree", secretKey)}
>
- <div className="flex-1">
- <Button
- className="w-full"
- variant="outline_bg"
- isDisabled={cannotReadSecretValue || !hasSecretReference(secret?.value)}
- leftIcon={<FontAwesomeIcon icon={faProjectDiagram} />}
- onClick={() => handlePopUpOpen("secretReferenceTree", secretKey)}
- >
- Secret Reference Tree
- </Button>
- </div>
- </Tooltip>
+ Secret Reference Tree
+ </Button>
<Tooltip content="Copy Secret ID" className="z-[100]">
<IconButton
variant="outline_bg"
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem.tsx
index 31cf18a65d..6191e2a186 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem.tsx
@@ -27,8 +27,8 @@ import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { usePopUp, useToggle } from "@app/hooks";
import { SecretV3RawSanitized } from "@app/hooks/api/secrets/types";
@@ -47,6 +47,13 @@ import { faEyeSlash, faKey, faRotate } from "@fortawesome/free-solid-svg-icons";
import { PendingAction } from "@app/hooks/api/secretFolders/types";
import { format } from "date-fns";
import { CreateReminderForm } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/CreateReminderForm";
+import {
+ dashboardKeys,
+ fetchSecretValue,
+ useGetSecretValue
+} from "@app/hooks/api/dashboard/queries";
+import { createNotification } from "@app/components/notifications";
+import { useQueryClient } from "@tanstack/react-query";
import {
FontAwesomeSpriteName,
formSchema,
@@ -56,11 +63,11 @@ import {
import { CollapsibleSecretImports } from "./CollapsibleSecretImports";
import { useBatchModeActions } from "../../SecretMainPage.store";
-export const HIDDEN_SECRET_VALUE = "*****************************";
+export const HIDDEN_SECRET_VALUE = "*************************";
export const HIDDEN_SECRET_VALUE_API_MASK = "<hidden-by-infisical>";
type Props = {
- secret: SecretV3RawSanitized;
+ secret: SecretV3RawSanitized & { originalKey?: string };
onSaveSecret: (
orgSec: SecretV3RawSanitized,
modSec: Omit<SecretV3RawSanitized, "tags"> & { tags?: { id: string }[] },
@@ -91,7 +98,7 @@ type Props = {
export const SecretItem = memo(
({
- secret,
+ secret: originalSecret,
onSaveSecret,
onDeleteSecret,
onDetailViewSecret,
@@ -112,17 +119,51 @@ export const SecretItem = memo(
"editSecret",
"reminder"
] as const);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { permission } = useProjectPermission();
- const { isRotatedSecret } = secret;
const { removePendingChange } = useBatchModeActions();
+ const [isFieldFocused, setIsFieldFocused] = useToggle();
+ const queryClient = useQueryClient();
+
+ const canFetchSecretValue =
+ !originalSecret.secretValueHidden &&
+ !originalSecret.isEmpty &&
+ pendingAction !== PendingAction.Create;
+
+ const fetchSecretValueParams = {
+ environment,
+ secretPath,
+ secretKey: originalSecret.originalKey || originalSecret.key,
+ projectId: currentProject.id,
+ isOverride: Boolean(originalSecret.idOverride)
+ };
+
+ const {
+ data: secretValueData,
+ isPending: isPendingSecretValueData,
+ isError: isErrorFetchingSecretValue
+ } = useGetSecretValue(fetchSecretValueParams, {
+ enabled: canFetchSecretValue && (isVisible || isFieldFocused)
+ });
+
+ const isLoadingSecretValue = canFetchSecretValue && isPendingSecretValueData;
+ const hasFetchedSecretValue = !canFetchSecretValue || Boolean(secretValueData);
+
+ const secret = {
+ ...originalSecret,
+ value: originalSecret.value ?? secretValueData?.value,
+ valueOverride: originalSecret.valueOverride ?? secretValueData?.valueOverride
+ };
+
+ const { isRotatedSecret } = secret;
+
const autoSaveTimeoutRef = useRef<NodeJS.Timeout>();
const isAutoSavingRef = useRef(false);
const handleDeletePending = (pendingSecret: SecretV3RawSanitized) => {
removePendingChange(pendingSecret.id, "secret", {
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
environment,
secretPath
});
@@ -139,10 +180,27 @@ export const SecretItem = memo(
);
const getDefaultValue = () => {
+ if (isLoadingSecretValue) return undefined;
+
+ if (secret.secretValueHidden && !isPending) {
+ return canEditSecretValue ? HIDDEN_SECRET_VALUE : "";
+ }
+
+ if (isErrorFetchingSecretValue) return undefined;
+
+ return secret.value || "";
+ };
+
+ const getOverrideDefaultValue = () => {
+ if (isLoadingSecretValue) return undefined;
+
if (secret.secretValueHidden && !isPending) {
return canEditSecretValue ? HIDDEN_SECRET_VALUE : "";
}
- return secret.valueOverride || secret.value || "";
+
+ if (isErrorFetchingSecretValue) return undefined;
+
+ return secret.valueOverride || "";
};
const {
@@ -154,14 +212,17 @@ export const SecretItem = memo(
reset,
getValues,
trigger,
- formState: { isDirty, isSubmitting, errors }
+ formState: { isDirty, isSubmitting, errors },
+ getFieldState
} = useForm<TFormSchema>({
defaultValues: {
...secret,
+ valueOverride: getOverrideDefaultValue(),
value: getDefaultValue()
},
values: {
...secret,
+ valueOverride: getOverrideDefaultValue(),
value: getDefaultValue()
},
resolver: zodResolver(formSchema)
@@ -255,7 +316,10 @@ export const SecretItem = memo(
);
const isReadOnlySecret =
- isReadOnly || isRotatedSecret || (isPending && pendingAction === PendingAction.Delete);
+ isReadOnly ||
+ isRotatedSecret ||
+ (isPending && pendingAction === PendingAction.Delete) ||
+ isLoadingSecretValue;
const { secretValueHidden } = secret;
@@ -322,12 +386,36 @@ export const SecretItem = memo(
}
};
- const copyTokenToClipboard = () => {
- const [overrideValue, value] = getValues(["value", "valueOverride"]);
- if (isOverridden) {
- navigator.clipboard.writeText(value as string);
+ const fetchValue = async () => {
+ if (secretValueData) return secretValueData;
+
+ try {
+ const data = await fetchSecretValue(fetchSecretValueParams);
+
+ queryClient.setQueryData(dashboardKeys.getSecretValue(fetchSecretValueParams), data);
+
+ return data;
+ } catch (e) {
+ console.error(e);
+ createNotification({
+ type: "error",
+ text: "Failed to fetch secret value"
+ });
+ throw e;
+ }
+ };
+
+ const copyTokenToClipboard = async () => {
+ if (hasFetchedSecretValue) {
+ const [overrideValue, value] = getValues(["value", "valueOverride"]);
+ if (isOverridden) {
+ navigator.clipboard.writeText(value as string);
+ } else {
+ navigator.clipboard.writeText(overrideValue as string);
+ }
} else {
- navigator.clipboard.writeText(overrideValue as string);
+ const data = await fetchValue();
+ navigator.clipboard.writeText((data.valueOverride ?? data.value) as string);
}
setIsSecValueCopied.on();
};
@@ -393,7 +481,7 @@ export const SecretItem = memo(
<Input
autoComplete="off"
isReadOnly={isReadOnly || isRotatedSecret}
- autoCapitalization={currentWorkspace?.autoCapitalization}
+ autoCapitalization={currentProject?.autoCapitalization}
variant="plain"
isDisabled={isOverridden}
placeholder={error?.message}
@@ -410,7 +498,7 @@ export const SecretItem = memo(
tabIndex={0}
role="button"
>
- {secretValueHidden && !isOverridden && !isPending && (
+ {secretValueHidden && !getFieldState("value").isDirty && (
<Tooltip
content={`You do not have access to view the current value${canEditSecretValue && !isRotatedSecret ? ", but you can set a new one" : "."}`}
>
@@ -424,10 +512,18 @@ export const SecretItem = memo(
control={control}
render={({ field }) => (
<SecretInput
+ isLoadingValue={isLoadingSecretValue && Boolean(secret.idOverride)}
+ isErrorLoadingValue={isErrorFetchingSecretValue}
key="value-overriden"
isVisible={isVisible}
- isReadOnly={isReadOnly}
{...field}
+ onFocus={() => {
+ if (secret.idOverride) setIsFieldFocused.on();
+ }}
+ onBlur={() => {
+ setIsFieldFocused.off();
+ field.onBlur();
+ }}
containerClassName="py-1.5 rounded-md transition-all"
/>
)}
@@ -439,6 +535,8 @@ export const SecretItem = memo(
control={control}
render={({ field }) => (
<InfisicalSecretInput
+ isLoadingValue={isLoadingSecretValue}
+ isErrorLoadingValue={isErrorFetchingSecretValue}
isReadOnly={isReadOnlySecret}
key="secret-value"
isVisible={isVisible && (!secretValueHidden || isPending)}
@@ -446,6 +544,13 @@ export const SecretItem = memo(
environment={environment}
secretPath={secretPath}
{...field}
+ onFocus={() => {
+ setIsFieldFocused.on();
+ }}
+ onBlur={() => {
+ setIsFieldFocused.off();
+ field.onBlur();
+ }}
defaultValue={
secretValueHidden && !isPending ? HIDDEN_SECRET_VALUE : undefined
}
@@ -613,7 +718,7 @@ export const SecretItem = memo(
</DropdownMenuContent>
</DropdownMenu>
<ProjectPermissionCan
- I={ProjectPermissionActions.Edit}
+ I={ProjectPermissionActions.Create}
a={subject(ProjectPermissionSub.Secrets, {
environment,
secretPath,
@@ -677,12 +782,24 @@ export const SecretItem = memo(
)}
</ProjectPermissionCan>
<IconButton
- isDisabled={secret.secretValueHidden || !currentWorkspace.secretSharing}
+ isDisabled={secret.secretValueHidden || !currentProject.secretSharing}
className="w-0 overflow-hidden p-0 group-hover:w-5"
variant="plain"
size="md"
ariaLabel="share-secret"
- onClick={() => onShareSecret(secret)}
+ onClick={async () => {
+ if (hasFetchedSecretValue) {
+ onShareSecret(secret);
+ return;
+ }
+
+ const data = await fetchValue();
+
+ onShareSecret({
+ ...secret,
+ ...data
+ });
+ }}
>
<Tooltip content="Share Secret">
<FontAwesomeSymbol
@@ -974,7 +1091,7 @@ export const SecretItem = memo(
<CreateReminderForm
isOpen={popUp.reminder.isOpen}
onOpenChange={() => handlePopUpToggle("reminder")}
- workspaceId={currentWorkspace.id}
+ projectId={currentProject.id}
environment={environment}
secretPath={secretPath}
secretId={secret?.id}
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx
index b98ce31b0e..4fc314bdd4 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretListView.tsx
@@ -37,7 +37,7 @@ import { FontAwesomeSpriteSymbols } from "./SecretListView.utils";
type Props = {
secrets?: SecretV3RawSanitized[];
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath?: string;
tags?: WsTag[];
isVisible?: boolean;
@@ -57,7 +57,7 @@ type Props = {
export const SecretListView = ({
secrets = [],
environment,
- workspaceId,
+ projectId,
secretPath = "/",
tags: wsTags = [],
isVisible,
@@ -93,7 +93,7 @@ export const SecretListView = ({
message:
"You have unsaved changes. If you leave now, your work will be lost. Do you want to continue?",
context: {
- workspaceId,
+ projectId,
environment,
secretPath
}
@@ -140,7 +140,7 @@ export const SecretListView = ({
if (operation === "delete") {
await deleteSecretV3({
environment,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
type,
@@ -161,7 +161,7 @@ export const SecretListView = ({
await updateSecretV3({
environment,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
...(!isRotatedSecret && {
@@ -183,7 +183,7 @@ export const SecretListView = ({
await createSecretV3(
{
environment,
- workspaceId,
+ projectId,
secretPath,
secretKey: key,
secretValue: value || "",
@@ -337,7 +337,7 @@ export const SecretListView = ({
};
addPendingChange(updatedCreate, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -369,7 +369,7 @@ export const SecretListView = ({
};
addPendingChange(updateChange, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -400,27 +400,39 @@ export const SecretListView = ({
}
queryClient.invalidateQueries({
queryKey: dashboardKeys.getDashboardSecrets({
- projectId: workspaceId,
+ projectId,
secretPath
})
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ workspaceId, environment, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({
+ projectId,
+ environment,
+ directory: secretPath
+ })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({
+ projectId,
+ environment,
+ directory: secretPath
+ })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({
+ projectId,
+ environment,
+ directory: secretPath
+ })
});
queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ workspaceId })
+ queryKey: secretApprovalRequestKeys.count({ projectId })
});
if (!isReminderEvent) {
handlePopUpClose("secretDetail");
@@ -450,11 +462,16 @@ export const SecretListView = ({
});
}
},
- [environment, secretPath, isProtectedBranch, isBatchMode, workspaceId, addPendingChange]
+ [environment, secretPath, isProtectedBranch, isBatchMode, projectId, addPendingChange]
);
const handleSecretDelete = useCallback(async () => {
- const { key, id: secretId, value } = popUp.deleteSecret?.data as SecretV3RawSanitized;
+ const {
+ key,
+ id: secretId,
+ value,
+ secretValueHidden
+ } = popUp.deleteSecret?.data as SecretV3RawSanitized;
try {
if (isBatchMode) {
const deleteChange: PendingSecretDelete = {
@@ -463,11 +480,12 @@ export const SecretListView = ({
secretKey: key,
secretValue: value || "",
timestamp: Date.now(),
- resourceType: "secret"
+ resourceType: "secret",
+ secretValueHidden
};
addPendingChange(deleteChange, {
- workspaceId,
+ projectId,
environment,
secretPath
});
@@ -480,25 +498,33 @@ export const SecretListView = ({
await handleSecretOperation("delete", SecretType.Shared, key, { secretId });
// wrap this in another function and then reuse
queryClient.invalidateQueries({
- queryKey: dashboardKeys.getDashboardSecrets({ projectId: workspaceId, secretPath })
+ queryKey: dashboardKeys.getDashboardSecrets({ projectId, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretKeys.getProjectSecret({ workspaceId, environment, secretPath })
+ queryKey: secretKeys.getProjectSecret({ projectId, environment, secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.list({ workspaceId, environment, directory: secretPath })
+ queryKey: secretSnapshotKeys.list({
+ projectId,
+ environment,
+ directory: secretPath
+ })
});
queryClient.invalidateQueries({
- queryKey: secretSnapshotKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: secretSnapshotKeys.count({
+ projectId,
+ environment,
+ directory: secretPath
+ })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.count({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.count({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: commitKeys.history({ workspaceId, environment, directory: secretPath })
+ queryKey: commitKeys.history({ projectId, environment, directory: secretPath })
});
queryClient.invalidateQueries({
- queryKey: secretApprovalRequestKeys.count({ workspaceId })
+ queryKey: secretApprovalRequestKeys.count({ projectId })
});
handlePopUpClose("deleteSecret");
handlePopUpClose("secretDetail");
@@ -521,7 +547,7 @@ export const SecretListView = ({
secretPath,
isProtectedBranch,
isBatchMode,
- workspaceId,
+ projectId,
addPendingChange
]);
@@ -596,19 +622,21 @@ export const SecretListView = ({
</>
}
/>
- <SecretDetailSidebar
- environment={environment}
- secretPath={secretPath}
- isOpen={popUp.secretDetail.isOpen}
- onToggle={(isOpen) => handlePopUpToggle("secretDetail", isOpen)}
- secret={popUp.secretDetail.data as SecretV3RawSanitized}
- onDeleteSecret={() => handlePopUpOpen("deleteSecret", popUp.secretDetail.data)}
- onClose={() => handlePopUpClose("secretDetail")}
- onSaveSecret={handleSaveSecret}
- tags={wsTags}
- onCreateTag={() => handlePopUpOpen("createTag")}
- handleSecretShare={(value: string) => handlePopUpOpen("createSharedSecret", { value })}
- />
+ {popUp.secretDetail.data && (
+ <SecretDetailSidebar
+ environment={environment}
+ secretPath={secretPath}
+ isOpen={popUp.secretDetail.isOpen}
+ onToggle={(isOpen) => handlePopUpToggle("secretDetail", isOpen)}
+ secret={popUp.secretDetail.data as SecretV3RawSanitized}
+ onDeleteSecret={() => handlePopUpOpen("deleteSecret", popUp.secretDetail.data)}
+ onClose={() => handlePopUpClose("secretDetail")}
+ onSaveSecret={handleSaveSecret}
+ tags={wsTags}
+ onCreateTag={() => handlePopUpOpen("createTag")}
+ handleSecretShare={(value: string) => handlePopUpOpen("createSharedSecret", { value })}
+ />
+ )}
<CreateTagModal
isOpen={popUp.createTag.isOpen}
onToggle={(isOpen) => handlePopUpToggle("createTag", isOpen)}
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretVersionItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretVersionItem.tsx
new file mode 100644
index 0000000000..808e549ee3
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretVersionItem.tsx
@@ -0,0 +1,277 @@
+import { useState } from "react";
+import { faEye } from "@fortawesome/free-regular-svg-icons";
+import {
+ faArrowRotateRight,
+ faDesktop,
+ faEyeSlash,
+ faServer,
+ faUser
+} from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { useNavigate } from "@tanstack/react-router";
+import { format } from "date-fns";
+import { twMerge } from "tailwind-merge";
+
+import { createNotification } from "@app/components/notifications";
+import { IconButton, Tooltip } from "@app/components/v2";
+import { useProject } from "@app/context";
+import { ActorType } from "@app/hooks/api/auditLogs/enums";
+import { fetchSecretVersionValue } from "@app/hooks/api/secrets/queries";
+import { SecretV3RawSanitized, SecretVersions } from "@app/hooks/api/secrets/types";
+
+interface SecretVersionItemProps {
+ secretVersion: SecretVersions;
+ secret: SecretV3RawSanitized;
+ currentVersion: number;
+ onRevert: (secretValue: string) => void;
+ canReadValue: boolean;
+}
+
+export const SecretVersionItem = ({
+ secretVersion: { createdAt, version, actor, secretValueHidden },
+ secret,
+ currentVersion,
+ onRevert,
+ canReadValue
+}: SecretVersionItemProps) => {
+ const { currentProject } = useProject();
+
+ const navigate = useNavigate();
+
+ const getModifiedByIcon = (userType: string | undefined | null) => {
+ switch (userType) {
+ case ActorType.USER:
+ return faUser;
+ case ActorType.IDENTITY:
+ return faDesktop;
+ default:
+ return faServer;
+ }
+ };
+
+ const getModifiedByName = (
+ userType: string | undefined | null,
+ userName: string | null | undefined
+ ) => {
+ switch (userType) {
+ case ActorType.PLATFORM:
+ return "System-generated";
+ case ActorType.IDENTITY:
+ return userName || "Deleted Identity";
+ case ActorType.USER:
+ return userName || "Deleted User";
+ default:
+ return "Unknown";
+ }
+ };
+
+ const getLinkToModifyHistoryEntity = (
+ actorId: string,
+ actorType: string,
+ membershipId: string | null = ""
+ ) => {
+ switch (actorType) {
+ case ActorType.USER:
+ return `/projects/secret-management/${currentProject.id}/members/${membershipId}`;
+ case ActorType.IDENTITY:
+ return `/projects/secret-management/${currentProject.id}/identities/${actorId}`;
+ default:
+ return null;
+ }
+ };
+
+ const onModifyHistoryClick = (
+ actorId: string | undefined | null,
+ actorType: string | undefined | null,
+ membershipId: string | undefined | null
+ ) => {
+ if (actorType && actorId && actorType !== ActorType.PLATFORM) {
+ const redirectLink = getLinkToModifyHistoryEntity(actorId, actorType, membershipId);
+ if (redirectLink) {
+ navigate({ to: redirectLink });
+ }
+ }
+ };
+
+ const [secretValue, setSecretValue] = useState<string | null>(null);
+ const [isFetchingValue, setIsFetchingValue] = useState(false);
+ const handleGetSecretValue = async () => {
+ if (secretValue) return secretValue;
+ try {
+ setIsFetchingValue(true);
+ const value = await fetchSecretVersionValue(secret.id, version);
+ setSecretValue(value);
+ return value;
+ } catch (e) {
+ console.error(e);
+ createNotification({
+ type: "error",
+ text: "Failed to fetch secret version value"
+ });
+ throw e;
+ } finally {
+ setIsFetchingValue(false);
+ }
+ };
+
+ const handleCopyValue = async (
+ e: React.MouseEvent<HTMLButtonElement> | React.KeyboardEvent<HTMLButtonElement>
+ ) => {
+ const value = await handleGetSecretValue();
+ navigator.clipboard.writeText(value || "");
+ const target = e.currentTarget;
+ target.style.borderBottom = "1px dashed";
+ target.style.paddingBottom = "-1px";
+
+ // Create and insert popup
+ const popup = document.createElement("div");
+ popup.className =
+ "w-16 flex justify-center absolute top-6 left-0 text-xs text-primary-100 bg-mineshaft-800 px-1 py-0.5 rounded-md border border-primary-500/50";
+ popup.textContent = "Copied!";
+ target.parentElement?.appendChild(popup);
+
+ // Remove popup and border after delay
+ setTimeout(() => {
+ popup.remove();
+ target.style.borderBottom = "none";
+ }, 3000);
+ };
+
+ return (
+ <div className="flex flex-row">
+ <div className="flex w-full flex-col space-y-1">
+ <div className="flex items-center">
+ <div className="w-10">
+ <div className="w-fit rounded-md border border-mineshaft-600 bg-mineshaft-700 px-1 text-sm text-mineshaft-300">
+ v{version}
+ </div>
+ </div>
+ <div>{format(new Date(createdAt), "Pp")}</div>
+ </div>
+ <div className="flex w-full cursor-default">
+ <div className="relative w-10">
+ <div className="absolute bottom-0 left-3 top-0 mt-0.5 border-l border-mineshaft-400/60" />
+ </div>
+ <div className="flex w-full cursor-default flex-col">
+ {actor && (
+ <div className="flex flex-row">
+ <div className="flex w-fit flex-row text-sm">
+ Modified by:
+ <Tooltip content={getModifiedByName(actor.actorType, actor.name)}>
+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
+ <div
+ onClick={() =>
+ onModifyHistoryClick(actor.actorId, actor.actorType, actor.membershipId)
+ }
+ className="cursor-pointer"
+ >
+ <FontAwesomeIcon icon={getModifiedByIcon(actor.actorType)} className="ml-2" />
+ </div>
+ </Tooltip>
+ </div>
+ </div>
+ )}
+ <div className="flex flex-row">
+ <div className="h-min w-fit rounded-sm bg-primary-500/10 px-1 text-primary-300/70">
+ Value:
+ </div>
+ <div className="group break-all pl-1 font-mono">
+ <div className="relative hidden cursor-pointer transition-all duration-200 group-[.show-value]:inline">
+ <button
+ type="button"
+ className="select-none text-left"
+ onClick={async (e) => {
+ if (secretValueHidden) return;
+
+ await handleCopyValue(e);
+ }}
+ onKeyDown={async (e) => {
+ if (secretValueHidden) return;
+
+ if (e.key === "Enter" || e.key === " ") {
+ await handleCopyValue(e);
+ }
+ }}
+ >
+ <span
+ className={twMerge(secretValueHidden && "text-xs text-bunker-300 opacity-40")}
+ >
+ {/* eslint-disable-next-line no-nested-ternary */}
+ {secretValueHidden
+ ? "Hidden"
+ : isFetchingValue
+ ? "****"
+ : ((secretValue || <span className="text-mineshaft-400">EMPTY</span>) ??
+ "Error fetching secret value...")}
+ </span>
+ </button>
+ <button
+ type="button"
+ className="ml-1 cursor-pointer"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.currentTarget.closest(".group")?.classList.remove("show-value");
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.stopPropagation();
+ e.currentTarget.closest(".group")?.classList.remove("show-value");
+ }
+ }}
+ >
+ <FontAwesomeIcon icon={faEyeSlash} />
+ </button>
+ </div>
+ <span className="group-[.show-value]:hidden">
+ ****
+ <button
+ type="button"
+ className="ml-1 cursor-pointer"
+ onClick={async (e) => {
+ e.currentTarget.closest(".group")?.classList.add("show-value");
+ await handleGetSecretValue();
+ }}
+ onKeyDown={async (e) => {
+ if (e.key === "Enter" || e.key === " ") {
+ e.currentTarget.closest(".group")?.classList.add("show-value");
+ await handleGetSecretValue();
+ }
+ }}
+ >
+ <FontAwesomeIcon icon={faEye} />
+ </button>
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ {!secret?.isRotatedSecret && canReadValue && (
+ <div
+ className={`flex items-center justify-center ${version === currentVersion ? "hidden" : ""}`}
+ >
+ <Tooltip content="Restore Secret Value">
+ <IconButton
+ ariaLabel="Restore"
+ variant="outline_bg"
+ size="sm"
+ className="h-8 w-8 rounded-md"
+ onClick={async () => {
+ if (secretValue) {
+ onRevert(secretValue);
+ return;
+ }
+
+ const value = await handleGetSecretValue();
+
+ onRevert(value);
+ }}
+ >
+ <FontAwesomeIcon icon={faArrowRotateRight} />
+ </IconButton>
+ </Tooltip>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationItem.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationItem.tsx
index 77e6eddab7..a2c54a11f8 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationItem.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationItem.tsx
@@ -15,13 +15,13 @@ import { twMerge } from "tailwind-merge";
import { ProjectPermissionCan } from "@app/components/permissions";
import { SecretRotationV2StatusBadge } from "@app/components/secret-rotations-v2/SecretRotationV2StatusBadge";
import { IconButton, Modal, ModalContent, TableContainer, Tag, Tooltip } from "@app/components/v2";
-import { Blur } from "@app/components/v2/Blur";
-import { InfisicalSecretInput } from "@app/components/v2/InfisicalSecretInput";
import { ProjectPermissionSub } from "@app/context";
import { ProjectPermissionSecretRotationActions } from "@app/context/ProjectPermissionContext/types";
import { SECRET_ROTATION_MAP } from "@app/helpers/secretRotationsV2";
import { TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
+import { SecretRotationSecretRow } from "./SecretRotationSecretRow";
+
type Props = {
secretRotation: TSecretRotationV2;
onEdit: () => void;
@@ -209,43 +209,13 @@ export const SecretRotationItem = ({
<tbody>
{secrets.map((secret, index) => {
return (
- <Tooltip
- className="max-w-sm"
- content={
- secret ? undefined : "You do not have permission to view this secret."
- }
- >
- <tr
- // eslint-disable-next-line react/no-array-index-key
- key={`rotation-secret-${secretRotation.id}-${index}`}
- className="h-full last:!border-b-0 hover:bg-mineshaft-700"
- >
- <td className="flex h-full items-center" style={{ padding: "0.5rem 1rem" }}>
- <span className={twMerge(!secret && "blur")}>
- {secret?.key ?? "********"}
- </span>
- </td>
- <td className="col-span-2 h-full w-full" style={{ padding: "0.5rem 1rem" }}>
- {/* eslint-disable-next-line no-nested-ternary */}
- {!secret ? (
- <div className="h-full pl-4 blur">********</div>
- ) : secret.secretValueHidden ? (
- <Blur
- className="py-0"
- tooltipText="You do not have permission to read the value of this secret."
- />
- ) : (
- <InfisicalSecretInput
- isReadOnly
- value={secret.value}
- secretPath={secretRotation.folder.path}
- environment={secretRotation.environment.slug}
- onChange={() => {}}
- />
- )}
- </td>
- </tr>
- </Tooltip>
+ <SecretRotationSecretRow
+ // eslint-disable-next-line react/no-array-index-key
+ key={`rotation-secret-${secretRotation.id}-${index}`}
+ secret={secret}
+ environment={secretRotation.environment.slug}
+ secretPath={secretRotation.folder.path}
+ />
);
})}
</tbody>
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationSecretRow.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationSecretRow.tsx
new file mode 100644
index 0000000000..e8b7788afb
--- /dev/null
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SecretRotationListView/SecretRotationSecretRow.tsx
@@ -0,0 +1,76 @@
+import { twMerge } from "tailwind-merge";
+
+import { SecretInput, Tooltip } from "@app/components/v2";
+import { Blur } from "@app/components/v2/Blur";
+import { useProject } from "@app/context";
+import { useToggle } from "@app/hooks";
+import { useGetSecretValue } from "@app/hooks/api/dashboard/queries";
+import { TSecretRotationV2 } from "@app/hooks/api/secretRotationsV2";
+import { HIDDEN_SECRET_VALUE } from "@app/pages/secret-manager/SecretDashboardPage/components/SecretListView/SecretItem";
+
+interface SecretRotationSecretRowProps {
+ secret: TSecretRotationV2["secrets"][number];
+ secretPath: string;
+ environment: string;
+}
+
+export const SecretRotationSecretRow = ({
+ secret,
+ environment,
+ secretPath
+}: SecretRotationSecretRowProps) => {
+ const [isFieldFocused, setIsFieldFocused] = useToggle();
+
+ const { currentProject } = useProject();
+
+ const { data: secretValue, isPending: isLoadingSecretValue } = useGetSecretValue(
+ {
+ environment,
+ secretPath,
+ secretKey: secret?.key ?? "",
+ projectId: currentProject.id
+ },
+ {
+ enabled: isFieldFocused && Boolean(secret)
+ }
+ );
+
+ const getValue = () => {
+ if (isLoadingSecretValue) return HIDDEN_SECRET_VALUE;
+
+ if (!secretValue) return "Error loading secret value";
+
+ return secretValue.value || "";
+ };
+
+ return (
+ <Tooltip
+ className="max-w-sm"
+ content={secret ? undefined : "You do not have permission to view this secret."}
+ >
+ <tr className="h-full last:!border-b-0 hover:bg-mineshaft-700">
+ <td className="flex h-full items-center" style={{ padding: "0.5rem 1rem" }}>
+ <span className={twMerge(!secret && "blur")}>{secret?.key ?? "********"}</span>
+ </td>
+ <td className="col-span-2 h-full w-full" style={{ padding: "0.5rem 1rem" }}>
+ {/* eslint-disable-next-line no-nested-ternary */}
+ {!secret ? (
+ <div className="h-full pl-4 blur">********</div>
+ ) : secret.secretValueHidden ? (
+ <Blur
+ className="py-0"
+ tooltipText="You do not have permission to read the value of this secret."
+ />
+ ) : (
+ <SecretInput
+ isReadOnly
+ value={getValue()}
+ onFocus={() => setIsFieldFocused.on()}
+ onBlur={() => setIsFieldFocused.off()}
+ />
+ )}
+ </td>
+ </tr>
+ </Tooltip>
+ );
+};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SnapshotView/SnapshotView.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SnapshotView/SnapshotView.tsx
index d286db472e..6bef2d3f6b 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/SnapshotView/SnapshotView.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/SnapshotView/SnapshotView.tsx
@@ -22,7 +22,7 @@ import { renderIcon, SecretItem, TDiffModes, TDiffView } from "./SecretItem";
type Props = {
snapshotId: string;
environment: string;
- workspaceId: string;
+ projectId: string;
secretPath?: string;
secrets?: SecretV3RawSanitized[];
folders?: TSecretFolder[];
@@ -43,7 +43,7 @@ const deepCompareSecrets = (lhs: SecretV3RawSanitized, rhs: SecretV3RawSanitized
export const SnapshotView = ({
snapshotId,
environment,
- workspaceId,
+ projectId,
secretPath,
secrets = [],
folders = [],
@@ -130,7 +130,7 @@ export const SnapshotView = ({
}
try {
await performRollback({
- workspaceId,
+ projectId,
snapshotId: snapshotData.id,
environment,
directory: secretPath
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx
index 09970f6984..0700b33224 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/route.tsx
@@ -10,7 +10,9 @@ import { SecretDashboardPage } from "./SecretDashboardPage";
const SecretDashboardPageQueryParamsSchema = z.object({
secretPath: z.string().catch("/"),
search: z.string().catch(""),
- tags: z.string().catch("")
+ tags: z.string().catch(""),
+ connectionId: z.string().optional(),
+ connectionName: z.string().optional()
});
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/secrets/$envSlug"
diff --git a/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx b/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx
index 51551999e9..c7e9865722 100644
--- a/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx
+++ b/frontend/src/pages/secret-manager/SecretRotationPage/SecretRotationPage.tsx
@@ -40,9 +40,9 @@ import {
import { NoticeBannerV2 } from "@app/components/v2/NoticeBannerV2/NoticeBannerV2";
import {
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { ProjectPermissionSecretRotationActions } from "@app/context/ProjectPermissionContext/types";
import { usePopUp } from "@app/hooks";
@@ -56,7 +56,7 @@ import { TSecretRotationProviderTemplate } from "@app/hooks/api/secretRotation/t
import { CreateRotationForm } from "@app/pages/secret-manager/SecretRotationPage/components/CreateRotationForm";
const Page = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { permission } = useProjectPermission();
const navigate = useNavigate();
@@ -68,7 +68,7 @@ const Page = () => {
"upgradePlan",
"secretRotationV2"
] as const);
- const workspaceId = currentWorkspace?.id || "";
+ const workspaceId = currentProject?.id || "";
const canCreateRotation = permission.can(
ProjectPermissionSecretRotationActions.Create,
ProjectPermissionSub.SecretRotation
@@ -173,7 +173,7 @@ const Page = () => {
<Link
className="text-mineshaft-100 underline decoration-primary underline-offset-2 hover:text-mineshaft-200"
to="/projects/secret-management/$projectId/overview"
- params={{ projectId: currentWorkspace.id }}
+ params={{ projectId: currentProject.id }}
>
Secret Manager Dashboard
</Link>{" "}
@@ -408,7 +408,7 @@ const Page = () => {
<Link
className="text-mineshaft-100 underline decoration-primary underline-offset-2 hover:text-mineshaft-200"
to="/projects/secret-management/$projectId/overview"
- params={{ projectId: currentWorkspace.id }}
+ params={{ projectId: currentProject.id }}
>
Secret Manager Dashboard
</Link>{" "}
@@ -425,7 +425,7 @@ const Page = () => {
onClick={() =>
navigate({
to: "/projects/secret-management/$projectId/overview",
- params: { projectId: currentWorkspace.id }
+ params: { projectId: currentProject.id }
})
}
colorSchema="secondary"
diff --git a/frontend/src/pages/secret-manager/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx b/frontend/src/pages/secret-manager/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx
index e669b88de5..31c8eceb75 100644
--- a/frontend/src/pages/secret-manager/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretRotationPage/components/CreateRotationForm/steps/RotationOutputForm.tsx
@@ -4,7 +4,7 @@ import { z } from "zod";
import { Button, FormControl, Input, Select, SelectItem, Spinner } from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useGetProjectSecrets } from "@app/hooks/api";
const formSchema = z.object({
@@ -22,9 +22,9 @@ type Props = {
};
export const RotationOutputForm = ({ onSubmit, onCancel, outputSchema = {} }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const environments = currentWorkspace?.environments || [];
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const environments = currentProject?.environments || [];
+ const projectId = currentProject?.id || "";
const {
control,
handleSubmit,
@@ -39,7 +39,7 @@ export const RotationOutputForm = ({ onSubmit, onCancel, outputSchema = {} }: Pr
const selectedSecrets = watch("secrets");
const { data: secrets, isPending: isSecretsLoading } = useGetProjectSecrets({
- workspaceId,
+ projectId,
environment,
secretPath
});
diff --git a/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncAuditLogsSection.tsx b/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncAuditLogsSection.tsx
index 58c00db6f6..540ea0a517 100644
--- a/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncAuditLogsSection.tsx
+++ b/frontend/src/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncAuditLogsSection.tsx
@@ -2,7 +2,7 @@ import { faFingerprint } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Link } from "@tanstack/react-router";
-import { useSubscription, useWorkspace } from "@app/context";
+import { useProject, useSubscription } from "@app/context";
import { EventType } from "@app/hooks/api/auditLogs/enums";
import { TSecretSync } from "@app/hooks/api/secretSyncs";
import { LogsSection } from "@app/pages/organization/AuditLogsPage/components/LogsSection";
@@ -19,7 +19,7 @@ type Props = {
export const SecretSyncAuditLogsSection = ({ secretSync }: Props) => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const auditLogsRetentionDays = subscription?.auditLogsRetentionDays ?? 30;
@@ -37,7 +37,7 @@ export const SecretSyncAuditLogsSection = ({ secretSync }: Props) => {
<LogsSection
refetchInterval={4000}
showFilters={false}
- project={currentWorkspace}
+ project={currentProject}
presets={{
eventMetadata: { syncId: secretSync.id },
startDate: new Date(
diff --git a/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx b/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx
index d864d9a444..ad037b1259 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/SettingsPage.tsx
@@ -2,8 +2,8 @@ import { Helmet } from "react-helmet";
import { useTranslation } from "react-i18next";
import { PageHeader, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
-import { ProjectVersion } from "@app/hooks/api/workspace/types";
+import { useProject } from "@app/context";
+import { ProjectVersion } from "@app/hooks/api/projects/types";
import { ProjectGeneralTab } from "@app/pages/project/SettingsPage/components/ProjectGeneralTab";
import { EncryptionTab } from "./components/EncryptionTab";
@@ -13,14 +13,14 @@ import { WorkflowIntegrationTab } from "./components/WorkflowIntegrationSection"
export const SettingsPage = () => {
const { t } = useTranslation();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const tabs = [
{ name: "General", key: "tab-project-general", Component: ProjectGeneralTab },
{ name: "Secrets Management", key: "tab-secret-general", Component: SecretSettingsTab },
{
name: "Encryption",
key: "tab-project-encryption",
- isHidden: currentWorkspace?.version !== ProjectVersion.V3,
+ isHidden: currentProject?.version !== ProjectVersion.V3,
Component: EncryptionTab
},
{
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx
index 648360789b..3bc9ca0ad0 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/AutoCapitalizationSection/AutoCapitalizationSection.tsx
@@ -3,22 +3,22 @@ import { useTranslation } from "react-i18next";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Checkbox } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
-import { useToggleAutoCapitalization } from "@app/hooks/api";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
+import { useUpdateProject } from "@app/hooks/api";
export const AutoCapitalizationSection = () => {
const { t } = useTranslation();
- const { currentWorkspace } = useWorkspace();
- const { mutateAsync } = useToggleAutoCapitalization();
+ const { currentProject } = useProject();
+ const { mutateAsync } = useUpdateProject();
const handleToggleCapitalizationToggle = async (state: boolean) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await mutateAsync({
- workspaceID: currentWorkspace.id,
- state
+ projectId: currentProject.id,
+ autoCapitalization: state
});
const text = `Successfully ${state ? "enabled" : "disabled"} auto capitalization`;
@@ -44,7 +44,7 @@ export const AutoCapitalizationSection = () => {
<Checkbox
id="autoCapitalization"
isDisabled={!isAllowed}
- isChecked={currentWorkspace?.autoCapitalization ?? false}
+ isChecked={currentProject?.autoCapitalization ?? false}
onCheckedChange={(state) => {
handleToggleCapitalizationToggle(state as boolean);
}}
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx
index 5e489ba698..3e749aa0ef 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/BackfillSecretReferenceSection/BackfillSecretReferenceSection.tsx
@@ -1,20 +1,20 @@
import { createNotification } from "@app/components/notifications";
import { Button } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import { useBackfillSecretReference } from "@app/hooks/api";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
export const BackfillSecretReferenceSecretion = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { membership } = useProjectPermission();
const backfillSecretReferences = useBackfillSecretReference();
- if (!currentWorkspace) return null;
+ if (!currentProject) return null;
const handleBackfill = async () => {
if (backfillSecretReferences.isPending) return;
try {
- await backfillSecretReferences.mutateAsync({ projectId: currentWorkspace.id || "" });
+ await backfillSecretReferences.mutateAsync({ projectId: currentProject.id || "" });
createNotification({ text: "Successfully re-indexed secret references", type: "success" });
} catch {
createNotification({ text: "Failed to re-index secret references", type: "error" });
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx
index 68592323e7..23ae0c3f7c 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EncryptionTab/EncryptionTab.tsx
@@ -21,7 +21,7 @@ import {
ProjectPermissionActions,
ProjectPermissionSub,
useOrganization,
- useWorkspace
+ useProject
} from "@app/context";
import { usePopUp, useToggle } from "@app/hooks";
import {
@@ -32,7 +32,7 @@ import {
} from "@app/hooks/api";
import { fetchProjectKmsBackup } from "@app/hooks/api/kms/queries";
import { INTERNAL_KMS_KEY_ID, KmsType } from "@app/hooks/api/kms/types";
-import { Organization, Workspace } from "@app/hooks/api/types";
+import { Organization, Project } from "@app/hooks/api/types";
const formSchema = z.object({
kmsKeyId: z.string()
@@ -44,32 +44,29 @@ const BackupConfirmationModal = ({
isOpen,
onOpenChange,
org,
- workspace
+ project
}: {
isOpen: boolean;
onOpenChange: (state: boolean) => void;
org?: Organization;
- workspace?: Workspace;
+ project?: Project;
}) => {
const [isGeneratingBackup, setGeneratingBackup] = useToggle();
const downloadKmsBackup = async () => {
- if (!workspace || !org) {
+ if (!project || !org) {
return;
}
setGeneratingBackup.on();
try {
- const { secretManager } = await fetchProjectKmsBackup(workspace.id);
+ const { secretManager } = await fetchProjectKmsBackup(project.id);
const [, , kmsFunction] = secretManager.split(".");
const file = secretManager;
const blob = new Blob([file], { type: "text/plain;charset=utf-8" });
- FileSaver.saveAs(
- blob,
- `kms-backup-${org.slug}-${workspace.slug}-${kmsFunction}.infisical.txt`
- );
+ FileSaver.saveAs(blob, `kms-backup-${org.slug}-${project.slug}-${kmsFunction}.infisical.txt`);
onOpenChange(false);
} catch (err) {
@@ -110,20 +107,20 @@ const LoadBackupModal = ({
isOpen,
onOpenChange,
org,
- workspace
+ workspace: project
}: {
isOpen: boolean;
onOpenChange: (state: boolean) => void;
org?: Organization;
- workspace: Workspace;
+ workspace: Project;
}) => {
const fileUploadRef = useRef<HTMLInputElement>(null);
- const { mutateAsync: loadKmsBackup, isPending } = useLoadProjectKmsBackup(workspace.id);
+ const { mutateAsync: loadKmsBackup, isPending } = useLoadProjectKmsBackup(project.id);
const [backupContent, setBackupContent] = useState("");
const [backupFileName, setBackupFileName] = useState("");
const uploadKmsBackup = async () => {
- if (!workspace || !org) {
+ if (!project || !org) {
return;
}
@@ -222,13 +219,13 @@ const LoadBackupModal = ({
export const EncryptionTab = () => {
const { currentOrg } = useOrganization();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: externalKmsList } = useGetExternalKmsList(currentOrg.id);
- const { data: activeKms } = useGetActiveProjectKms(currentWorkspace.id);
+ const { data: activeKms } = useGetActiveProjectKms(currentProject.id);
const { mutateAsync: updateProjectKms, isPending: isUpdatingProjectKms } = useUpdateProjectKms(
- currentWorkspace.id
+ currentProject.id
);
const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp([
"createBackupConfirmation",
@@ -336,13 +333,13 @@ export const EncryptionTab = () => {
isOpen={popUp.createBackupConfirmation.isOpen}
onOpenChange={(state: boolean) => handlePopUpToggle("createBackupConfirmation", state)}
org={currentOrg}
- workspace={currentWorkspace}
+ project={currentProject}
/>
<LoadBackupModal
isOpen={popUp.loadBackup.isOpen}
onOpenChange={(state: boolean) => handlePopUpToggle("loadBackup", state)}
org={currentOrg}
- workspace={currentWorkspace}
+ workspace={currentProject}
/>
</div>
);
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx
index 0832dfe9da..611504a141 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/AddEnvironmentModal.tsx
@@ -4,15 +4,15 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalClose, ModalContent } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateWsEnvironment } from "@app/hooks/api";
-import { WorkspaceEnv } from "@app/hooks/api/workspace/types";
+import { ProjectEnv } from "@app/hooks/api/projects/types";
import { slugSchema } from "@app/lib/schemas";
type Props = {
isOpen: boolean;
onOpenChange: (isOpen: boolean) => void;
- onComplete?: (environment: WorkspaceEnv) => void;
+ onComplete?: (environment: ProjectEnv) => void;
};
const schema = z.object({
@@ -25,11 +25,11 @@ const schema = z.object({
export type FormData = z.infer<typeof schema>;
type ContentProps = {
- onComplete: (environment: WorkspaceEnv) => void;
+ onComplete: (environment: ProjectEnv) => void;
};
const Content = ({ onComplete }: ContentProps) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync, isPending } = useCreateWsEnvironment();
const { control, handleSubmit } = useForm<FormData>({
resolver: zodResolver(schema)
@@ -37,10 +37,10 @@ const Content = ({ onComplete }: ContentProps) => {
const onFormSubmit = async ({ environmentName, environmentSlug }: FormData) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
const env = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
name: environmentName,
slug: environmentSlug
});
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx
index 34acf0c7b0..016266e694 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentSection.tsx
@@ -8,9 +8,9 @@ import { Button, DeleteActionModal } from "@app/components/v2";
import {
ProjectPermissionActions,
ProjectPermissionSub,
+ useProject,
useProjectPermission,
- useSubscription,
- useWorkspace
+ useSubscription
} from "@app/context";
import { useDeleteWsEnvironment } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -21,14 +21,14 @@ import { UpdateEnvironmentModal } from "./UpdateEnvironmentModal";
export const EnvironmentSection = () => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { permission } = useProjectPermission();
const deleteWsEnvironment = useDeleteWsEnvironment();
const isMoreEnvironmentsAllowed =
- subscription?.environmentLimit && currentWorkspace?.environments
- ? currentWorkspace.environments.length < subscription.environmentLimit
+ subscription?.environmentLimit && currentProject?.environments
+ ? currentProject.environments.length < subscription.environmentLimit
: true;
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
@@ -40,10 +40,10 @@ export const EnvironmentSection = () => {
const onEnvDeleteSubmit = async (id: string) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await deleteWsEnvironment.mutateAsync({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
id
});
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx
index 0626db2819..0908d83771 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/EnvironmentTable.tsx
@@ -18,8 +18,8 @@ import {
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useSubscription,
- useWorkspace
+ useProject,
+ useSubscription
} from "@app/context";
import { useUpdateWsEnvironment } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -40,17 +40,17 @@ type Props = {
};
export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { subscription } = useSubscription();
const updateEnvironment = useUpdateWsEnvironment();
const handleReorderEnv = async (id: string, position: number) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await updateEnvironment.mutateAsync({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
id,
position
});
@@ -69,13 +69,13 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
};
const isMoreEnvironmentsAllowed =
- subscription?.environmentLimit && currentWorkspace?.environments
- ? currentWorkspace.environments.length <= subscription.environmentLimit
+ subscription?.environmentLimit && currentProject?.environments
+ ? currentProject.environments.length <= subscription.environmentLimit
: true;
const environmentsOverPlanLimit =
- subscription?.environmentLimit && currentWorkspace?.environments
- ? Math.max(0, currentWorkspace.environments.length - subscription.environmentLimit)
+ subscription?.environmentLimit && currentProject?.environments
+ ? Math.max(0, currentProject.environments.length - subscription.environmentLimit)
: 0;
return (
@@ -89,7 +89,7 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
</Tr>
</THead>
<TBody>
- {currentWorkspace.environments.map(({ name, slug, id }, pos) => (
+ {currentProject.environments.map(({ name, slug, id }, pos) => (
<Tr key={id}>
<Td>{name}</Td>
<Td>{slug}</Td>
@@ -102,15 +102,12 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
<IconButton
className="mr-3 py-2"
onClick={() =>
- handleReorderEnv(
- id,
- Math.min(currentWorkspace.environments.length, pos + 2)
- )
+ handleReorderEnv(id, Math.min(currentProject.environments.length, pos + 2))
}
colorSchema="primary"
variant="plain"
ariaLabel="update"
- isDisabled={pos === currentWorkspace.environments.length - 1 || !isAllowed}
+ isDisabled={pos === currentProject.environments.length - 1 || !isAllowed}
>
<FontAwesomeIcon icon={faArrowDown} />
</IconButton>
@@ -183,7 +180,7 @@ export const EnvironmentTable = ({ handlePopUpOpen }: Props) => {
</Td>
</Tr>
))}
- {currentWorkspace.environments?.length === 0 && (
+ {currentProject.environments?.length === 0 && (
<Tr>
<Td colSpan={3}>
<EmptyState title="No environments found" />
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx
index f40091303c..e2d64ee72f 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/EnvironmentSection/UpdateEnvironmentModal.tsx
@@ -4,7 +4,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useUpdateWsEnvironment } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { slugSchema } from "@app/lib/schemas";
@@ -23,7 +23,7 @@ const schema = z.object({
export type FormData = z.infer<typeof schema>;
export const UpdateEnvironmentModal = ({ popUp, handlePopUpClose, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync, isPending } = useUpdateWsEnvironment();
const { control, handleSubmit, reset } = useForm<FormData>({
resolver: zodResolver(schema),
@@ -34,10 +34,10 @@ export const UpdateEnvironmentModal = ({ popUp, handlePopUpClose, handlePopUpTog
const onFormSubmit = async ({ name, slug }: FormData) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await mutateAsync({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
name,
slug,
id: oldEnvId
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx
index 288500d269..bd8d15887c 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/PointInTimeVersionLimitSection/PointInTimeVersionLimitSection.tsx
@@ -4,9 +4,9 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
+import { useUpdateProject } from "@app/hooks/api";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
-import { useUpdateWorkspaceVersionLimit } from "@app/hooks/api/workspace/queries";
const formSchema = z.object({
pitVersionLimit: z.coerce.number().min(1).max(100)
@@ -15,9 +15,9 @@ const formSchema = z.object({
type TForm = z.infer<typeof formSchema>;
export const PointInTimeVersionLimitSection = () => {
- const { mutateAsync: updatePitVersion } = useUpdateWorkspaceVersionLimit();
+ const { mutateAsync: updateProject } = useUpdateProject();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject, projectId } = useProject();
const { membership } = useProjectPermission();
const {
@@ -27,17 +27,17 @@ export const PointInTimeVersionLimitSection = () => {
} = useForm<TForm>({
resolver: zodResolver(formSchema),
values: {
- pitVersionLimit: currentWorkspace?.pitVersionLimit || 10
+ pitVersionLimit: currentProject?.pitVersionLimit || 10
}
});
- if (!currentWorkspace) return null;
+ if (!currentProject) return null;
const handleVersionLimitSubmit = async ({ pitVersionLimit }: TForm) => {
try {
- await updatePitVersion({
+ await updateProject({
pitVersionLimit,
- projectSlug: currentWorkspace.slug
+ projectId
});
createNotification({
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretDetectionIgnoreValuesSection/SecretDetectionIgnoreValuesSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretDetectionIgnoreValuesSection/SecretDetectionIgnoreValuesSection.tsx
index 5869aa1273..a7c6bbc363 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretDetectionIgnoreValuesSection/SecretDetectionIgnoreValuesSection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretDetectionIgnoreValuesSection/SecretDetectionIgnoreValuesSection.tsx
@@ -7,7 +7,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, IconButton, Input } from "@app/components/v2";
-import { useProjectPermission, useWorkspace } from "@app/context";
+import { useProject, useProjectPermission } from "@app/context";
import { useUpdateProject } from "@app/hooks/api";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
@@ -23,7 +23,7 @@ const formSchema = z.object({
type TForm = z.infer<typeof formSchema>;
export const SecretDetectionIgnoreValuesSection = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { membership } = useProjectPermission();
const { mutateAsync: updateProject } = useUpdateProject();
@@ -45,19 +45,19 @@ export const SecretDetectionIgnoreValuesSection = () => {
});
useEffect(() => {
- const existingIgnoreValues = currentWorkspace?.secretDetectionIgnoreValues || [];
+ const existingIgnoreValues = currentProject?.secretDetectionIgnoreValues || [];
reset({
ignoreValues:
existingIgnoreValues.length > 0
? existingIgnoreValues.map((value) => ({ value }))
: [{ value: "" }] // Show one empty field by default
});
- }, [currentWorkspace?.secretDetectionIgnoreValues, reset]);
+ }, [currentProject?.secretDetectionIgnoreValues, reset]);
const handleIgnoreValuesSubmit = async ({ ignoreValues }: TForm) => {
try {
await updateProject({
- projectID: currentWorkspace.id,
+ projectId: currentProject.id,
secretDetectionIgnoreValues: ignoreValues.map((item) => item.value)
});
@@ -75,7 +75,7 @@ export const SecretDetectionIgnoreValuesSection = () => {
const isAdmin = membership.roles.includes(ProjectMembershipRole.Admin);
- if (!currentWorkspace) return null;
+ if (!currentProject) return null;
return (
<div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx
index 0dd145e415..83639d2041 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSharingSection/SecretSharingSection.tsx
@@ -3,11 +3,11 @@ import { useState } from "react";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Checkbox } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
-import { useUpdateProject } from "@app/hooks/api/workspace/queries";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
+import { useUpdateProject } from "@app/hooks/api/projects/queries";
export const SecretSharingSection = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: updateProject } = useUpdateProject();
const [isLoading, setIsLoading] = useState(false);
@@ -16,13 +16,13 @@ export const SecretSharingSection = () => {
setIsLoading(true);
try {
- if (!currentWorkspace?.id) {
+ if (!currentProject?.id) {
setIsLoading(false);
return;
}
await updateProject({
- projectID: currentWorkspace.id,
+ projectId: currentProject.id,
secretSharing: state
});
@@ -50,7 +50,7 @@ export const SecretSharingSection = () => {
<Checkbox
id="secretSharing"
isDisabled={!isAllowed || isLoading}
- isChecked={currentWorkspace?.secretSharing ?? true}
+ isChecked={currentProject?.secretSharing ?? true}
onCheckedChange={(state) => handleToggle(state as boolean)}
>
This feature enables your project members to securely share secrets.
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSnapshotsLegacySection/SecretSnapshotsLegacySection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSnapshotsLegacySection/SecretSnapshotsLegacySection.tsx
index 69c2bcbfda..90b866e964 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretSnapshotsLegacySection/SecretSnapshotsLegacySection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretSnapshotsLegacySection/SecretSnapshotsLegacySection.tsx
@@ -3,11 +3,11 @@ import { useState } from "react";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Checkbox } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
-import { useUpdateProject } from "@app/hooks/api/workspace/queries";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
+import { useUpdateProject } from "@app/hooks/api/projects/queries";
export const SecretSnapshotsLegacySection = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync: updateProject } = useUpdateProject();
const [isLoading, setIsLoading] = useState(false);
@@ -16,13 +16,13 @@ export const SecretSnapshotsLegacySection = () => {
setIsLoading(true);
try {
- if (!currentWorkspace?.id) {
+ if (!currentProject?.id) {
setIsLoading(false);
return;
}
await updateProject({
- projectID: currentWorkspace.id,
+ projectId: currentProject.id,
showSnapshotsLegacy: state
});
@@ -50,7 +50,7 @@ export const SecretSnapshotsLegacySection = () => {
<Checkbox
id="showSnapshotsLegacy"
isDisabled={!isAllowed || isLoading}
- isChecked={currentWorkspace?.showSnapshotsLegacy ?? false}
+ isChecked={currentProject?.showSnapshotsLegacy ?? false}
onCheckedChange={(state) => handleToggle(state as boolean)}
>
This feature enables your project members to view secret snapshots in the legacy
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx
index 96c667050a..1d4c8e4923 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/AddSecretTagModal.tsx
@@ -4,7 +4,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, FormControl, Input, Modal, ModalClose, ModalContent } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateWsTag } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { slugSchema } from "@app/lib/schemas";
@@ -27,7 +27,7 @@ type Props = {
};
export const AddSecretTagModal = ({ popUp, handlePopUpClose, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const createWsTag = useCreateWsTag();
const {
control,
@@ -40,10 +40,10 @@ export const AddSecretTagModal = ({ popUp, handlePopUpClose, handlePopUpToggle }
const onFormSubmit = async ({ slug }: FormData) => {
try {
- if (!currentWorkspace?.id) return;
+ if (!currentProject?.id) return;
await createWsTag.mutateAsync({
- workspaceID: currentWorkspace?.id,
+ projectId: currentProject?.id,
tagSlug: slug,
tagColor: ""
});
@@ -73,7 +73,7 @@ export const AddSecretTagModal = ({ popUp, handlePopUpClose, handlePopUpToggle }
}}
>
<ModalContent
- title={`Add a tag for ${currentWorkspace?.name ?? ""}`}
+ title={`Add a tag for ${currentProject?.name ?? ""}`}
subTitle="Specify your tag name, and the slug will be created automatically."
>
<form onSubmit={handleSubmit(onFormSubmit)}>
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx
index 26be8eb173..55da0f03bc 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsSection.tsx
@@ -7,8 +7,8 @@ import { Button, DeleteActionModal } from "@app/components/v2";
import {
ProjectPermissionActions,
ProjectPermissionSub,
- useProjectPermission,
- useWorkspace
+ useProject,
+ useProjectPermission
} from "@app/context";
import { usePopUp } from "@app/hooks";
import { useDeleteWsTag } from "@app/hooks/api";
@@ -23,7 +23,7 @@ export const SecretTagsSection = (): JSX.Element => {
"CreateSecretTag",
"deleteTagConfirmation"
] as const);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { permission } = useProjectPermission();
const deleteWsTag = useDeleteWsTag();
@@ -31,7 +31,7 @@ export const SecretTagsSection = (): JSX.Element => {
const onDeleteApproved = async () => {
try {
await deleteWsTag.mutateAsync({
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
tagID: (popUp?.deleteTagConfirmation?.data as DeleteModalData)?.id
});
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsTable.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsTable.tsx
index d0633eb120..15d8ef7cbd 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsTable.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/SecretTagsSection/SecretTagsTable.tsx
@@ -24,7 +24,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import {
getUserTablePreference,
PreferenceKey,
@@ -53,8 +53,8 @@ enum TagsOrderBy {
}
export const SecretTagsTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const { data: tags = [], isPending } = useGetWsTags(currentWorkspace?.id ?? "");
+ const { currentProject } = useProject();
+ const { data: tags = [], isPending } = useGetWsTags(currentProject?.id ?? "");
const {
search,
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx
index 8c8d75f47f..79fc7aafc2 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WebhooksTab/WebhooksTab.tsx
@@ -18,7 +18,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { withProjectPermission } from "@app/hoc";
import { usePopUp } from "@app/hooks";
import {
@@ -35,14 +35,14 @@ export const WebhooksTab = withProjectPermission(
() => {
const { t } = useTranslation();
- const { currentWorkspace } = useWorkspace();
- const workspaceId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
"addWebhook",
"deleteWebhook"
] as const);
- const { data: webhooks, isPending: isWebhooksLoading } = useGetWebhooks(workspaceId);
+ const { data: webhooks, isPending: isWebhooksLoading } = useGetWebhooks(projectId);
// mutation
const { mutateAsync: createWebhook } = useCreateWebhook();
@@ -62,7 +62,7 @@ export const WebhooksTab = withProjectPermission(
try {
await createWebhook({
...data,
- workspaceId
+ projectId
});
handlePopUpClose("addWebhook");
createNotification({
@@ -82,7 +82,7 @@ export const WebhooksTab = withProjectPermission(
try {
await updateWebhook({
webhookId,
- workspaceId,
+ projectId,
isDisabled
});
createNotification({
@@ -103,7 +103,7 @@ export const WebhooksTab = withProjectPermission(
const webhookId = popUp?.deleteWebhook?.data as string;
await deleteWebhook({
webhookId,
- workspaceId
+ projectId
});
handlePopUpClose("deleteWebhook");
createNotification({
@@ -123,7 +123,7 @@ export const WebhooksTab = withProjectPermission(
try {
await testWebhook({
webhookId,
- workspaceId
+ projectId
});
createNotification({
type: "success",
@@ -302,7 +302,7 @@ export const WebhooksTab = withProjectPermission(
</TableContainer>
</div>
<AddWebhookForm
- environments={currentWorkspace?.environments}
+ environments={currentProject?.environments}
isOpen={popUp?.addWebhook?.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("addWebhook", isOpen)}
onCreateWebhook={handleWebhookCreate}
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/WorkflowIntegrationTab.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/WorkflowIntegrationTab.tsx
index 5b5f92bbb9..ce8a3a70c3 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/WorkflowIntegrationTab.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/WorkflowIntegrationTab.tsx
@@ -15,7 +15,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { OrgPermissionActions, OrgPermissionSubjects, useWorkspace } from "@app/context";
+import { OrgPermissionActions, OrgPermissionSubjects, useProject } from "@app/context";
import { usePopUp } from "@app/hooks";
import {
useDeleteProjectWorkflowIntegration,
@@ -47,16 +47,16 @@ export const WorkflowIntegrationTab = () => {
"editIntegration"
] as const);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: slackConfig, isPending: isSlackConfigLoading } =
useGetWorkspaceWorkflowIntegrationConfig({
- workspaceId: currentWorkspace?.id ?? "",
+ projectId: currentProject?.id ?? "",
integration: WorkflowIntegrationPlatform.SLACK
});
const { data: microsoftTeamsConfig, isPending: isMicrosoftTeamsConfigLoading } =
useGetWorkspaceWorkflowIntegrationConfig({
- workspaceId: currentWorkspace?.id ?? "",
+ projectId: currentProject?.id ?? "",
integration: WorkflowIntegrationPlatform.MICROSOFT_TEAMS
});
@@ -66,12 +66,12 @@ export const WorkflowIntegrationTab = () => {
integrationType: WorkflowIntegrationPlatform,
integrationId: string
) => {
- if (!currentWorkspace.id) {
+ if (!currentProject.id) {
return;
}
await deleteIntegration({
- projectId: currentWorkspace?.id ?? "",
+ projectId: currentProject?.id ?? "",
integration: integrationType,
integrationId
});
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/AddWorkflowIntegrationModal.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/AddWorkflowIntegrationModal.tsx
index 8601c1c027..28a3c83d3b 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/AddWorkflowIntegrationModal.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/AddWorkflowIntegrationModal.tsx
@@ -6,7 +6,7 @@ import { AnimatePresence, motion } from "framer-motion";
import { twMerge } from "tailwind-merge";
import { Modal, ModalContent } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useGetWorkspaceWorkflowIntegrationConfig } from "@app/hooks/api";
import { WorkflowIntegrationPlatform } from "@app/hooks/api/workflowIntegrations/types";
@@ -40,14 +40,14 @@ export const AddWorkflowIntegrationModal = ({ isOpen, onToggle }: Props) => {
const [wizardStep, setWizardStep] = useState(WizardSteps.SelectPlatform);
const [selectedPlatform, setSelectedPlatform] = useState<string | null>(null);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: microsoftTeamsConfig } = useGetWorkspaceWorkflowIntegrationConfig({
- workspaceId: currentWorkspace?.id ?? "",
+ projectId: currentProject?.id ?? "",
integration: WorkflowIntegrationPlatform.MICROSOFT_TEAMS
});
const { data: slackConfig } = useGetWorkspaceWorkflowIntegrationConfig({
- workspaceId: currentWorkspace?.id ?? "",
+ projectId: currentProject?.id ?? "",
integration: WorkflowIntegrationPlatform.SLACK
});
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/MicrosoftTeamsIntegrationForm.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/MicrosoftTeamsIntegrationForm.tsx
index aab932b8d7..2bfe8cece8 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/MicrosoftTeamsIntegrationForm.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/MicrosoftTeamsIntegrationForm.tsx
@@ -19,7 +19,7 @@ import {
SelectItem,
Switch
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
ProjectPermissionActions,
ProjectPermissionSub
@@ -95,13 +95,13 @@ type Props = {
};
export const MicrosoftTeamsIntegrationForm = ({ onClose }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: microsoftTeamsConfig } = useGetWorkspaceWorkflowIntegrationConfig({
- workspaceId: currentWorkspace?.id ?? "",
+ projectId: currentProject?.id ?? "",
integration: WorkflowIntegrationPlatform.MICROSOFT_TEAMS
});
const { data: microsoftTeamsIntegrations } = useGetMicrosoftTeamsIntegrations(
- currentWorkspace?.orgId
+ currentProject?.orgId
);
const { mutateAsync: updateProjectMicrosoftTeamsConfig } =
@@ -131,12 +131,12 @@ export const MicrosoftTeamsIntegrationForm = ({ onClose }: Props) => {
const handleIntegrationSave = async (data: TMicrosoftTeamsConfigForm) => {
try {
- if (!currentWorkspace) {
+ if (!currentProject) {
return;
}
await updateProjectMicrosoftTeamsConfig({
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
isAccessRequestNotificationEnabled: data.isAccessRequestNotificationEnabled,
isSecretRequestNotificationEnabled: data.isSecretRequestNotificationEnabled,
...(data.isAccessRequestNotificationEnabled && {
diff --git a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx
index 6bcaa6ac1a..26cae7f61a 100644
--- a/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx
+++ b/frontend/src/pages/secret-manager/SettingsPage/components/WorkflowIntegrationSection/components/SlackIntegrationForm.tsx
@@ -19,7 +19,7 @@ import {
SelectItem,
Switch
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
ProjectPermissionActions,
ProjectPermissionSub
@@ -47,12 +47,12 @@ type Props = {
};
export const SlackIntegrationForm = ({ onClose }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: slackConfig } = useGetWorkspaceWorkflowIntegrationConfig({
- workspaceId: currentWorkspace?.id ?? "",
+ projectId: currentProject?.id ?? "",
integration: WorkflowIntegrationPlatform.SLACK
});
- const { data: workflowIntegrations } = useGetWorkflowIntegrations(currentWorkspace?.orgId);
+ const { data: workflowIntegrations } = useGetWorkflowIntegrations(currentProject?.orgId);
const { mutateAsync: updateProjectSlackConfig } = useUpdateProjectWorkflowIntegrationConfig();
const slackIntegrations = workflowIntegrations?.filter(
@@ -77,13 +77,13 @@ export const SlackIntegrationForm = ({ onClose }: Props) => {
const handleIntegrationSave = async (data: TSlackConfigForm) => {
try {
- if (!currentWorkspace) {
+ if (!currentProject) {
return;
}
await updateProjectSlackConfig({
...data,
- workspaceId: currentWorkspace.id,
+ projectId: currentProject.id,
integration: WorkflowIntegrationPlatform.SLACK,
integrationId: data.slackIntegrationId,
accessRequestChannels: data.accessRequestChannels.filter(Boolean).join(", "),
diff --git a/frontend/src/pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/AwsParameterStoreAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/AwsParameterStoreAuthorizePage.tsx
index e67e1e328a..16493ad0ff 100644
--- a/frontend/src/pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/AwsParameterStoreAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AwsParameterStoreAuthorizePage/AwsParameterStoreAuthorizePage.tsx
@@ -16,7 +16,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
enum AwsAuthType {
@@ -40,7 +40,7 @@ type TForm = z.infer<typeof formSchema>;
export const AWSParameterStoreAuthorizeIntegrationPage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync } = useSaveIntegrationAccessToken();
const { control, handleSubmit, formState, watch } = useForm<TForm>({
@@ -55,7 +55,7 @@ export const AWSParameterStoreAuthorizeIntegrationPage = () => {
const handleFormSubmit = async (data: TForm) => {
try {
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "aws-parameter-store",
...(data.type === AwsAuthType.AssumeRole
? {
@@ -70,7 +70,7 @@ export const AWSParameterStoreAuthorizeIntegrationPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/aws-parameter-store/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/AwsParameterStoreConfigurePage/AwsParamterStoreConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/AwsParameterStoreConfigurePage/AwsParamterStoreConfigurePage.tsx
index bbdd2d71ba..5b5d97f6af 100644
--- a/frontend/src/pages/secret-manager/integrations/AwsParameterStoreConfigurePage/AwsParamterStoreConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AwsParameterStoreConfigurePage/AwsParamterStoreConfigurePage.tsx
@@ -26,7 +26,7 @@ import {
Tabs
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import { useGetIntegrationAuthById } from "@app/hooks/api/integrationAuth";
import { useGetIntegrationAuthAwsKmsKeys } from "@app/hooks/api/integrationAuth/queries";
@@ -77,7 +77,7 @@ export const AWSParameterStoreConfigurePage = () => {
from: ROUTE_PATHS.SecretManager.Integratons.AwsParameterStoreConfigurePage.id,
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: integrationAuth, isPending: isintegrationAuthLoading } = useGetIntegrationAuthById(
(integrationAuthId as string) ?? ""
@@ -97,11 +97,11 @@ export const AWSParameterStoreConfigurePage = () => {
const [kmsKeyId, setKmsKeyId] = useState("");
useEffect(() => {
- if (currentWorkspace) {
- setSelectedSourceEnvironment(currentWorkspace.environments[0].slug);
+ if (currentProject) {
+ setSelectedSourceEnvironment(currentProject.environments[0].slug);
setSelectedAWSRegion(awsRegions[0].slug);
}
- }, [currentWorkspace]);
+ }, [currentProject]);
const { data: integrationAuthAwsKmsKeys, isPending: isIntegrationAuthAwsKmsKeysLoading } =
useGetIntegrationAuthAwsKmsKeys({
@@ -158,7 +158,7 @@ export const AWSParameterStoreConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -226,7 +226,7 @@ export const AWSParameterStoreConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`flyio-environment-${sourceEnvironment.slug}`}
@@ -261,7 +261,7 @@ export const AWSParameterStoreConfigurePage = () => {
</FormControl>
<FormControl label="Path" errorText={pathErrorText} isError={pathErrorText !== ""}>
<Input
- placeholder={`/${currentWorkspace.name
+ placeholder={`/${currentProject.name
.toLowerCase()
.replace(/ /g, "-")}/${selectedSourceEnvironment}/`}
value={path}
diff --git a/frontend/src/pages/secret-manager/integrations/AwsSecretManagerAuthorizePage/AwsSecretManagerAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/AwsSecretManagerAuthorizePage/AwsSecretManagerAuthorizePage.tsx
index bdc18d8dd4..ba250587d9 100644
--- a/frontend/src/pages/secret-manager/integrations/AwsSecretManagerAuthorizePage/AwsSecretManagerAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AwsSecretManagerAuthorizePage/AwsSecretManagerAuthorizePage.tsx
@@ -16,7 +16,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
enum AwsAuthType {
@@ -41,7 +41,7 @@ type TForm = z.infer<typeof formSchema>;
export const AWSSecretManagerAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit, formState, watch } = useForm<TForm>({
resolver: zodResolver(formSchema),
@@ -54,7 +54,7 @@ export const AWSSecretManagerAuthorizePage = () => {
const handleFormSubmit = async (data: TForm) => {
try {
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "aws-secret-manager",
...(data.type === AwsAuthType.AssumeRole
? {
@@ -68,7 +68,7 @@ export const AWSSecretManagerAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/aws-secret-manager/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/AwsSecretManagerConfigurePage/AwsSecretManagerConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/AwsSecretManagerConfigurePage/AwsSecretManagerConfigurePage.tsx
index bd73fc5960..6c82b7edde 100644
--- a/frontend/src/pages/secret-manager/integrations/AwsSecretManagerConfigurePage/AwsSecretManagerConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AwsSecretManagerConfigurePage/AwsSecretManagerConfigurePage.tsx
@@ -30,7 +30,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import { useGetIntegrationAuthById } from "@app/hooks/api/integrationAuth";
import { useGetIntegrationAuthAwsKmsKeys } from "@app/hooks/api/integrationAuth/queries";
@@ -150,7 +150,7 @@ export const AwsSecretManagerConfigurePage = () => {
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: integrationAuth, isPending: isintegrationAuthLoading } = useGetIntegrationAuthById(
(integrationAuthId as string) ?? ""
);
@@ -162,11 +162,11 @@ export const AwsSecretManagerConfigurePage = () => {
});
useEffect(() => {
- if (currentWorkspace) {
- setValue("sourceEnvironment", currentWorkspace.environments[0].slug);
+ if (currentProject) {
+ setValue("sourceEnvironment", currentProject.environments[0].slug);
setValue("awsRegion", awsRegions[0].slug);
}
- }, [currentWorkspace]);
+ }, [currentProject]);
const handleButtonClick = async ({
secretName,
@@ -206,7 +206,7 @@ export const AwsSecretManagerConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -286,7 +286,7 @@ export const AwsSecretManagerConfigurePage = () => {
field.onChange(val);
}}
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
@@ -383,7 +383,7 @@ export const AwsSecretManagerConfigurePage = () => {
isError={Boolean(error)}
>
<Input
- placeholder={`${currentWorkspace.name
+ placeholder={`${currentProject.name
.toLowerCase()
.replace(/ /g, "-")}/${selectedSourceEnvironment}`}
{...field}
diff --git a/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationConfigurePage/AzureAppConfigurationConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationConfigurePage/AzureAppConfigurationConfigurePage.tsx
index 1e107807ec..5fec15b443 100644
--- a/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationConfigurePage/AzureAppConfigurationConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationConfigurePage/AzureAppConfigurationConfigurePage.tsx
@@ -21,11 +21,11 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import { useGetIntegrationAuthById } from "@app/hooks/api/integrationAuth";
import { IntegrationSyncBehavior } from "@app/hooks/api/integrations/types";
-import { useGetWorkspaceById } from "@app/hooks/api/workspace";
+import { useGetWorkspaceById } from "@app/hooks/api/projects";
import { IntegrationsListPageTabs } from "@app/types/integrations";
const schema = z.object({
@@ -84,9 +84,9 @@ export const AzureAppConfigurationConfigurePage = () => {
from: ROUTE_PATHS.SecretManager.Integratons.AzureAppConfigurationsConfigurePage.id,
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
- const { data: workspace } = useGetWorkspaceById(currentWorkspace.id);
+ const { data: workspace } = useGetWorkspaceById(currentProject.id);
const { data: integrationAuth } = useGetIntegrationAuthById((integrationAuthId as string) ?? "");
useEffect(() => {
@@ -133,7 +133,7 @@ export const AzureAppConfigurationConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
diff --git a/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationOauthCallbackPage/AzureAppConfigurationOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationOauthCallbackPage/AzureAppConfigurationOauthCallbackPage.tsx
index d15fea903b..046fac9138 100644
--- a/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationOauthCallbackPage/AzureAppConfigurationOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AzureAppConfigurationOauthCallbackPage/AzureAppConfigurationOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
export const AzureAppConfigurationOauthCallbackPage = () => {
@@ -12,7 +12,7 @@ export const AzureAppConfigurationOauthCallbackPage = () => {
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.AzureAppConfigurationsOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -22,7 +22,7 @@ export const AzureAppConfigurationOauthCallbackPage = () => {
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
code: code as string,
integration: "azure-app-configuration"
});
@@ -30,7 +30,7 @@ export const AzureAppConfigurationOauthCallbackPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/azure-app-configuration/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/AzureDevopsAuthorizePage/AzureDevopsAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/AzureDevopsAuthorizePage/AzureDevopsAuthorizePage.tsx
index 25cc9c6170..4a03c9c3ef 100644
--- a/frontend/src/pages/secret-manager/integrations/AzureDevopsAuthorizePage/AzureDevopsAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AzureDevopsAuthorizePage/AzureDevopsAuthorizePage.tsx
@@ -5,7 +5,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const AzureDevopsAuthorizePage = () => {
@@ -16,7 +16,7 @@ export const AzureDevopsAuthorizePage = () => {
const [devopsOrgName, setDevopsOrgName] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [isLoading, setIsLoading] = useState(false);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const handleButtonClick = async () => {
try {
@@ -31,7 +31,7 @@ export const AzureDevopsAuthorizePage = () => {
localStorage.setItem("azure-devops-org-name", devopsOrgName);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "azure-devops",
accessToken: btoa(`:${apiKey}`) // This is a base64 encoding of the API key without any username
});
@@ -41,7 +41,7 @@ export const AzureDevopsAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/azure-devops/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/AzureDevopsConfigurePage/AzureDevopsConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/AzureDevopsConfigurePage/AzureDevopsConfigurePage.tsx
index b06859e1f1..3d092fa264 100644
--- a/frontend/src/pages/secret-manager/integrations/AzureDevopsConfigurePage/AzureDevopsConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AzureDevopsConfigurePage/AzureDevopsConfigurePage.tsx
@@ -14,13 +14,13 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
useGetIntegrationAuthById
} from "@app/hooks/api/integrationAuth";
-import { useGetWorkspaceById } from "@app/hooks/api/workspace";
+import { useGetWorkspaceById } from "@app/hooks/api/projects";
import { IntegrationsListPageTabs } from "@app/types/integrations";
export const AzureDevopsConfigurePage = () => {
@@ -31,9 +31,9 @@ export const AzureDevopsConfigurePage = () => {
from: ROUTE_PATHS.SecretManager.Integratons.AzureDevopsConfigurePage.id,
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
- const { data: workspace } = useGetWorkspaceById(currentWorkspace.id);
+ const { data: workspace } = useGetWorkspaceById(currentProject.id);
const { data: integrationAuth } = useGetIntegrationAuthById((integrationAuthId as string) ?? "");
const { data: integrationAuthApps } = useGetIntegrationAuthApps({
integrationAuthId: (integrationAuthId as string) ?? "",
@@ -82,7 +82,7 @@ export const AzureDevopsConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
diff --git a/frontend/src/pages/secret-manager/integrations/AzureKeyVaultConfigurePage/AzureKeyVaultConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/AzureKeyVaultConfigurePage/AzureKeyVaultConfigurePage.tsx
index e5ccd3dfae..91f0d54407 100644
--- a/frontend/src/pages/secret-manager/integrations/AzureKeyVaultConfigurePage/AzureKeyVaultConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AzureKeyVaultConfigurePage/AzureKeyVaultConfigurePage.tsx
@@ -11,11 +11,11 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import { useGetIntegrationAuthById } from "@app/hooks/api/integrationAuth";
import { IntegrationSyncBehavior } from "@app/hooks/api/integrations/types";
-import { useGetWorkspaceById } from "@app/hooks/api/workspace";
+import { useGetWorkspaceById } from "@app/hooks/api/projects";
import { IntegrationsListPageTabs } from "@app/types/integrations";
const initialSyncBehaviors = [
@@ -38,9 +38,9 @@ export const AzureKeyVaultConfigurePage = () => {
from: ROUTE_PATHS.SecretManager.Integratons.AzureKeyVaultConfigurePage.id,
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
- const { data: workspace } = useGetWorkspaceById(currentWorkspace.id);
+ const { data: workspace } = useGetWorkspaceById(currentProject.id);
const { data: integrationAuth } = useGetIntegrationAuthById((integrationAuthId as string) ?? "");
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState("");
@@ -90,7 +90,7 @@ export const AzureKeyVaultConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
diff --git a/frontend/src/pages/secret-manager/integrations/AzureKeyVaultOauthCallbackPage/AzureKeyVaultOauthCallback.tsx b/frontend/src/pages/secret-manager/integrations/AzureKeyVaultOauthCallbackPage/AzureKeyVaultOauthCallback.tsx
index ef98d1cba8..90a93edcea 100644
--- a/frontend/src/pages/secret-manager/integrations/AzureKeyVaultOauthCallbackPage/AzureKeyVaultOauthCallback.tsx
+++ b/frontend/src/pages/secret-manager/integrations/AzureKeyVaultOauthCallbackPage/AzureKeyVaultOauthCallback.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
export const AzureKeyVaultOauthCallbackPage = () => {
@@ -12,7 +12,7 @@ export const AzureKeyVaultOauthCallbackPage = () => {
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.AzureKeyVaultOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -22,7 +22,7 @@ export const AzureKeyVaultOauthCallbackPage = () => {
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
code: code as string,
integration: "azure-key-vault"
});
@@ -30,7 +30,7 @@ export const AzureKeyVaultOauthCallbackPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/azure-key-vault/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx
index 10dafdb763..022a8e8d7f 100644
--- a/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/BitbucketConfigurePage/BitbucketConfigurePage.tsx
@@ -16,7 +16,7 @@ import {
Spinner
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreateIntegration,
useGetIntegrationAuthApps,
@@ -96,7 +96,7 @@ export const BitbucketConfigurePage = () => {
from: ROUTE_PATHS.SecretManager.Integratons.BitbucketConfigurePage.id,
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: bitbucketWorkspaces, isPending: isBitbucketWorkspacesLoading } =
useGetIntegrationAuthBitbucketWorkspaces((integrationAuthId as string) ?? "");
@@ -150,7 +150,7 @@ export const BitbucketConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -171,18 +171,18 @@ export const BitbucketConfigurePage = () => {
bitbucketRepo ||
!bitbucketRepos ||
!bitbucketWorkspaces ||
- !currentWorkspace
+ !currentProject
)
return;
reset({
targetRepo: bitbucketRepos[0],
targetWorkspace: bitbucketWorkspaces[0],
- sourceEnvironment: currentWorkspace.environments[0],
+ sourceEnvironment: currentProject.environments[0],
secretPath: "/",
scope: ScopeOptions[0]
});
- }, [bitbucketWorkspaces, bitbucketRepos, currentWorkspace]);
+ }, [bitbucketWorkspaces, bitbucketRepos, currentProject]);
if (isBitbucketWorkspacesLoading || isBitbucketReposLoading)
return (
@@ -217,9 +217,9 @@ export const BitbucketConfigurePage = () => {
value={value}
getOptionLabel={(option) => option.name}
onChange={onChange}
- options={currentWorkspace?.environments}
+ options={currentProject?.environments}
placeholder="Select a project environment"
- isDisabled={!currentWorkspace?.environments.length}
+ isDisabled={!currentProject?.environments.length}
/>
</FormControl>
)}
diff --git a/frontend/src/pages/secret-manager/integrations/BitbucketOauthCallbackPage/BitbucketOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/BitbucketOauthCallbackPage/BitbucketOauthCallbackPage.tsx
index 1e3d302f2e..8b23f46ab1 100644
--- a/frontend/src/pages/secret-manager/integrations/BitbucketOauthCallbackPage/BitbucketOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/BitbucketOauthCallbackPage/BitbucketOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
export const BitbucketOauthCallbackPage = () => {
@@ -11,7 +11,7 @@ export const BitbucketOauthCallbackPage = () => {
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.BitbucketOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -21,7 +21,7 @@ export const BitbucketOauthCallbackPage = () => {
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
code: code as string,
integration: "bitbucket"
});
@@ -29,7 +29,7 @@ export const BitbucketOauthCallbackPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/bitbucket/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/ChecklyAuthorizePage/ChecklyAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/ChecklyAuthorizePage/ChecklyAuthorizePage.tsx
index 5dd711fc06..43521fd2e0 100644
--- a/frontend/src/pages/secret-manager/integrations/ChecklyAuthorizePage/ChecklyAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/ChecklyAuthorizePage/ChecklyAuthorizePage.tsx
@@ -5,13 +5,13 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const ChecklyAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [accessToken, setAccessToken] = useState("");
const [accessTokenErrorText, setAccessTokenErrorText] = useState("");
@@ -28,7 +28,7 @@ export const ChecklyAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "checkly",
accessToken
});
@@ -38,7 +38,7 @@ export const ChecklyAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/checkly/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/ChecklyConfigurePage/ChecklyConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/ChecklyConfigurePage/ChecklyConfigurePage.tsx
index 2e02f7cf2a..e09a1361a1 100644
--- a/frontend/src/pages/secret-manager/integrations/ChecklyConfigurePage/ChecklyConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/ChecklyConfigurePage/ChecklyConfigurePage.tsx
@@ -19,14 +19,14 @@ import {
Tabs
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
useGetIntegrationAuthById,
useGetIntegrationAuthChecklyGroups
} from "@app/hooks/api/integrationAuth";
-import { useGetWorkspaceById } from "@app/hooks/api/workspace";
+import { useGetWorkspaceById } from "@app/hooks/api/projects";
import { IntegrationsListPageTabs } from "@app/types/integrations";
enum TabSections {
@@ -42,7 +42,7 @@ export const ChecklyConfigurePage = () => {
from: ROUTE_PATHS.SecretManager.Integratons.ChecklyConfigurePage.id,
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState("");
const [secretPath, setSecretPath] = useState("/");
@@ -53,7 +53,7 @@ export const ChecklyConfigurePage = () => {
const [isLoading, setIsLoading] = useState(false);
- const { data: workspace } = useGetWorkspaceById(currentWorkspace.id);
+ const { data: workspace } = useGetWorkspaceById(currentProject.id);
const { data: integrationAuth } = useGetIntegrationAuthById((integrationAuthId as string) ?? "");
const { data: integrationAuthApps, isPending: isIntegrationAuthAppsLoading } =
useGetIntegrationAuthApps({
@@ -115,7 +115,7 @@ export const ChecklyConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
diff --git a/frontend/src/pages/secret-manager/integrations/CircleCIAuthorizePage/CircleCIAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/CircleCIAuthorizePage/CircleCIAuthorizePage.tsx
index e64227fc37..088c22e1d1 100644
--- a/frontend/src/pages/secret-manager/integrations/CircleCIAuthorizePage/CircleCIAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CircleCIAuthorizePage/CircleCIAuthorizePage.tsx
@@ -5,7 +5,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const CircleCIAuthorizePage = () => {
@@ -15,7 +15,7 @@ export const CircleCIAuthorizePage = () => {
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [isLoading, setIsLoading] = useState(false);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const handleButtonClick = async () => {
try {
@@ -28,7 +28,7 @@ export const CircleCIAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "circleci",
accessToken: apiKey
});
@@ -38,7 +38,7 @@ export const CircleCIAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/circleci/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx
index f03f35af8a..36777af291 100644
--- a/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CircleCIConfigurePage/CircleCIConfigurePage.tsx
@@ -18,7 +18,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration, useGetIntegrationAuthCircleCIOrganizations } from "@app/hooks/api";
import { CircleCiScope } from "@app/hooks/api/integrationAuth/types";
import { IntegrationsListPageTabs } from "@app/types/integrations";
@@ -45,7 +45,7 @@ type TFormData = z.infer<typeof formSchema>;
export const CircleCIConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync, isPending: isCreatingIntegration } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.CircleConfigurePage.id,
@@ -56,7 +56,7 @@ export const CircleCIConfigurePage = () => {
resolver: zodResolver(formSchema),
defaultValues: {
secretPath: "/",
- sourceEnvironment: currentWorkspace?.environments[0],
+ sourceEnvironment: currentProject?.environments[0],
scope: CircleCiScope.Project
}
});
@@ -105,7 +105,7 @@ export const CircleCIConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -179,9 +179,9 @@ export const CircleCIConfigurePage = () => {
value={value}
getOptionLabel={(option) => option.name}
onChange={onChange}
- options={currentWorkspace?.environments}
+ options={currentProject?.environments}
placeholder="Select a project environment"
- isDisabled={!currentWorkspace?.environments.length}
+ isDisabled={!currentProject?.environments.length}
/>
</FormControl>
)}
diff --git a/frontend/src/pages/secret-manager/integrations/Cloud66AuthorizePage/Cloud66AuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/Cloud66AuthorizePage/Cloud66AuthorizePage.tsx
index 8fc9dd5caa..1a464cadcd 100644
--- a/frontend/src/pages/secret-manager/integrations/Cloud66AuthorizePage/Cloud66AuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/Cloud66AuthorizePage/Cloud66AuthorizePage.tsx
@@ -2,14 +2,14 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const Cloud66AuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
@@ -26,7 +26,7 @@ export const Cloud66AuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "cloud-66",
accessToken: apiKey
});
@@ -36,7 +36,7 @@ export const Cloud66AuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/cloud-66/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/Cloud66ConfigurePage/Cloud66ConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/Cloud66ConfigurePage/Cloud66ConfigurePage.tsx
index 6de5e3bc35..68535d70e3 100644
--- a/frontend/src/pages/secret-manager/integrations/Cloud66ConfigurePage/Cloud66ConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/Cloud66ConfigurePage/Cloud66ConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -28,7 +28,7 @@ export const Cloud66ConfigurePage = () => {
select: (el) => el.integrationAuthId
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: integrationAuth } = useGetIntegrationAuthById((integrationAuthId as string) ?? "");
const { data: integrationAuthApps } = useGetIntegrationAuthApps({
integrationAuthId: (integrationAuthId as string) ?? ""
@@ -40,10 +40,10 @@ export const Cloud66ConfigurePage = () => {
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
- if (currentWorkspace) {
- setSelectedSourceEnvironment(currentWorkspace.environments[0].slug);
+ if (currentProject) {
+ setSelectedSourceEnvironment(currentProject.environments[0].slug);
}
- }, [currentWorkspace]);
+ }, [currentProject]);
useEffect(() => {
if (integrationAuthApps) {
@@ -77,7 +77,7 @@ export const Cloud66ConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -98,7 +98,7 @@ export const Cloud66ConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/CloudflarePagesAuthorizePage/CloudflarePagesAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/CloudflarePagesAuthorizePage/CloudflarePagesAuthorizePage.tsx
index 16feba2836..08a00f2c63 100644
--- a/frontend/src/pages/secret-manager/integrations/CloudflarePagesAuthorizePage/CloudflarePagesAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CloudflarePagesAuthorizePage/CloudflarePagesAuthorizePage.tsx
@@ -2,7 +2,7 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const CloudflarePagesAuthorizePage = () => {
@@ -14,7 +14,7 @@ export const CloudflarePagesAuthorizePage = () => {
const [accountIdErrorText, setAccountIdErrorText] = useState("");
const [isLoading, setIsLoading] = useState(false);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
const handleButtonClick = async () => {
@@ -30,7 +30,7 @@ export const CloudflarePagesAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "cloudflare-pages",
accessId: accountId,
accessToken: accessKey
@@ -43,7 +43,7 @@ export const CloudflarePagesAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/cloudflare-pages/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx
index 1ff6e75d50..69225d9ae6 100644
--- a/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CloudflarePagesConfigurePage/CloudflarePagesConfigurePage.tsx
@@ -14,7 +14,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration, useGetWorkspaceById } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -31,7 +31,7 @@ export const CloudflarePagesConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.CloudflarePagesConfigurePage.id,
@@ -39,7 +39,7 @@ export const CloudflarePagesConfigurePage = () => {
});
const [secretPath, setSecretPath] = useState("/");
- const { data: workspace } = useGetWorkspaceById(currentWorkspace.id);
+ const { data: workspace } = useGetWorkspaceById(currentProject.id);
const { data: integrationAuth } = useGetIntegrationAuthById((integrationAuthId as string) ?? "");
const { data: integrationAuthApps } = useGetIntegrationAuthApps({
integrationAuthId: (integrationAuthId as string) ?? ""
@@ -96,7 +96,7 @@ export const CloudflarePagesConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
diff --git a/frontend/src/pages/secret-manager/integrations/CloudflareWorkersAuthorizePage/CloudflareWorkersAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/CloudflareWorkersAuthorizePage/CloudflareWorkersAuthorizePage.tsx
index e2829c76a8..dd0b16a6ba 100644
--- a/frontend/src/pages/secret-manager/integrations/CloudflareWorkersAuthorizePage/CloudflareWorkersAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CloudflareWorkersAuthorizePage/CloudflareWorkersAuthorizePage.tsx
@@ -2,13 +2,13 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const CloudflareWorkersAuthorizePage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync } = useSaveIntegrationAccessToken();
const [accessKey, setAccessKey] = useState("");
@@ -30,7 +30,7 @@ export const CloudflareWorkersAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "cloudflare-workers",
accessId: accountId,
accessToken: accessKey
@@ -43,7 +43,7 @@ export const CloudflareWorkersAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/cloudflare-workers/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx
index bfc4b766a6..a5d28bb952 100644
--- a/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CloudflareWorkersConfigurePage/CloudflareWorkersConfigurePage.tsx
@@ -6,7 +6,7 @@ import { createNotification } from "@app/components/notifications";
import { Button, Card, CardTitle, FormControl, Select, SelectItem } from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -17,7 +17,7 @@ import { IntegrationsListPageTabs } from "@app/types/integrations";
export const CloudflareWorkersConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.CloudflareWorkersConfigurePage.id,
@@ -29,7 +29,7 @@ export const CloudflareWorkersConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
@@ -69,7 +69,7 @@ export const CloudflareWorkersConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -107,7 +107,7 @@ export const CloudflareWorkersConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/CodefreshAuthorizePage/CodefreshAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/CodefreshAuthorizePage/CodefreshAuthorizePage.tsx
index 02e0d13780..353447fc71 100644
--- a/frontend/src/pages/secret-manager/integrations/CodefreshAuthorizePage/CodefreshAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CodefreshAuthorizePage/CodefreshAuthorizePage.tsx
@@ -2,7 +2,7 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const CodefreshAuthorizePage = () => {
@@ -12,7 +12,7 @@ export const CodefreshAuthorizePage = () => {
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [isLoading, setIsLoading] = useState(false);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const handleButtonClick = async () => {
try {
@@ -25,7 +25,7 @@ export const CodefreshAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "codefresh",
accessToken: apiKey
});
@@ -35,7 +35,7 @@ export const CodefreshAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/codefresh/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/CodefreshConfigurePage/CodefreshConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/CodefreshConfigurePage/CodefreshConfigurePage.tsx
index e99ad4ea81..80a54b621a 100644
--- a/frontend/src/pages/secret-manager/integrations/CodefreshConfigurePage/CodefreshConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/CodefreshConfigurePage/CodefreshConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -23,7 +23,7 @@ export const CodefreshConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.CodefreshConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -35,7 +35,7 @@ export const CodefreshConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetApp, setTargetApp] = useState("");
const [secretPath, setSecretPath] = useState("/");
@@ -73,7 +73,7 @@ export const CodefreshConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -94,7 +94,7 @@ export const CodefreshConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/DatabricksAuthorizePage/DatabricksAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/DatabricksAuthorizePage/DatabricksAuthorizePage.tsx
index 25de9cd24f..0ba804dfcd 100644
--- a/frontend/src/pages/secret-manager/integrations/DatabricksAuthorizePage/DatabricksAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/DatabricksAuthorizePage/DatabricksAuthorizePage.tsx
@@ -5,7 +5,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const DatabricksAuthorizePage = () => {
@@ -17,7 +17,7 @@ export const DatabricksAuthorizePage = () => {
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [instanceURLErrorText, setInstanceURLErrorText] = useState("");
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const handleButtonClick = async () => {
try {
@@ -33,7 +33,7 @@ export const DatabricksAuthorizePage = () => {
}
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "databricks",
url: instanceURL.replace(/\/$/, ""),
accessToken: apiKey
@@ -42,7 +42,7 @@ export const DatabricksAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/databricks/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx
index 0f3d097286..a140a03396 100644
--- a/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/DatabricksConfigurePage/DatabricksConfigurePage.tsx
@@ -20,7 +20,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -32,7 +32,7 @@ export const DatabricksConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync, isPending } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.DatabricksConfigurePage.id,
@@ -49,7 +49,7 @@ export const DatabricksConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetScope, setTargetScope] = useState("");
const [secretPath, setSecretPath] = useState("/");
@@ -89,7 +89,7 @@ export const DatabricksConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -143,7 +143,7 @@ export const DatabricksConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformAuthorizePage/DigitalOceanAppPlatformAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformAuthorizePage/DigitalOceanAppPlatformAuthorizePage.tsx
index 3910dac15e..769881971f 100644
--- a/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformAuthorizePage/DigitalOceanAppPlatformAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformAuthorizePage/DigitalOceanAppPlatformAuthorizePage.tsx
@@ -2,7 +2,7 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const DigitalOceanAppPlatformAuthorizePage = () => {
@@ -12,7 +12,7 @@ export const DigitalOceanAppPlatformAuthorizePage = () => {
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [isLoading, setIsLoading] = useState(false);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const handleButtonClick = async () => {
try {
@@ -25,7 +25,7 @@ export const DigitalOceanAppPlatformAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "digital-ocean-app-platform",
accessToken: apiKey
});
@@ -35,7 +35,7 @@ export const DigitalOceanAppPlatformAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/digital-ocean-app-platform/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformConfigurePage/DigitalOceanAppPlatformConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformConfigurePage/DigitalOceanAppPlatformConfigurePage.tsx
index e88d98976c..2c6f083485 100644
--- a/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformConfigurePage/DigitalOceanAppPlatformConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/DigitalOceanAppPlatformConfigurePage/DigitalOceanAppPlatformConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -23,7 +23,7 @@ export const DigitalOceanAppPlatformConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.DigitalOceanAppPlatformConfigurePage.id,
@@ -36,7 +36,7 @@ export const DigitalOceanAppPlatformConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetApp, setTargetApp] = useState("");
const [secretPath, setSecretPath] = useState("/");
@@ -74,7 +74,7 @@ export const DigitalOceanAppPlatformConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -95,7 +95,7 @@ export const DigitalOceanAppPlatformConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/FlyioAuthorizePage/FlyioAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/FlyioAuthorizePage/FlyioAuthorizePage.tsx
index 5fa42df529..a6d4075495 100644
--- a/frontend/src/pages/secret-manager/integrations/FlyioAuthorizePage/FlyioAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/FlyioAuthorizePage/FlyioAuthorizePage.tsx
@@ -8,7 +8,7 @@ import { useNavigate } from "@tanstack/react-router";
import { z } from "zod";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
const schema = z.object({
@@ -19,7 +19,7 @@ type FormData = z.infer<typeof schema>;
export const FlyioAuthorizePage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit } = useForm<FormData>({
resolver: zodResolver(schema),
@@ -37,7 +37,7 @@ export const FlyioAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "flyio",
accessToken
});
@@ -46,7 +46,7 @@ export const FlyioAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/flyio/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/FlyioConfigurePage/FlyioConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/FlyioConfigurePage/FlyioConfigurePage.tsx
index 0beb61bdf4..c034ce3f11 100644
--- a/frontend/src/pages/secret-manager/integrations/FlyioConfigurePage/FlyioConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/FlyioConfigurePage/FlyioConfigurePage.tsx
@@ -21,7 +21,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -34,7 +34,7 @@ export const FlyioConfigurePage = () => {
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.FlyioConfigurePage.id,
@@ -50,7 +50,7 @@ export const FlyioConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
@@ -88,7 +88,7 @@ export const FlyioConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -144,7 +144,7 @@ export const FlyioConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/GcpSecretManagerAuthorizePage/GcpSecretManagerAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/GcpSecretManagerAuthorizePage/GcpSecretManagerAuthorizePage.tsx
index 044be41c94..1d47db0e12 100644
--- a/frontend/src/pages/secret-manager/integrations/GcpSecretManagerAuthorizePage/GcpSecretManagerAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GcpSecretManagerAuthorizePage/GcpSecretManagerAuthorizePage.tsx
@@ -11,7 +11,7 @@ import { useNavigate } from "@tanstack/react-router";
import { z } from "zod";
import { Button, Card, CardTitle, FormControl, TextArea } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { localStorageService } from "@app/helpers/localStorage";
import { useGetCloudIntegrations, useSaveIntegrationAccessToken } from "@app/hooks/api";
@@ -31,7 +31,7 @@ export const GcpSecretManagerAuthorizePage = () => {
});
const { data: cloudIntegrations } = useGetCloudIntegrations();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync } = useSaveIntegrationAccessToken();
@@ -47,7 +47,7 @@ export const GcpSecretManagerAuthorizePage = () => {
const state = crypto.randomBytes(16).toString("hex");
localStorage.setItem("latestCSRFToken", state);
- localStorageService.setIntegrationProjectId(currentWorkspace.id);
+ localStorageService.setIntegrationProjectId(currentProject.id);
if (!integrationOption.clientId) {
createIntegrationMissingEnvVarsNotification(integrationOption.slug);
@@ -63,7 +63,7 @@ export const GcpSecretManagerAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "gcp-secret-manager",
refreshToken: accessToken
});
@@ -72,7 +72,7 @@ export const GcpSecretManagerAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/gcp-secret-manager/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/GcpSecretManagerConfigurePage/GcpSecretManagerConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/GcpSecretManagerConfigurePage/GcpSecretManagerConfigurePage.tsx
index c4f8403bdd..85af1961f1 100644
--- a/frontend/src/pages/secret-manager/integrations/GcpSecretManagerConfigurePage/GcpSecretManagerConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GcpSecretManagerConfigurePage/GcpSecretManagerConfigurePage.tsx
@@ -26,7 +26,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { usePopUp } from "@app/hooks";
import { useCreateIntegration } from "@app/hooks/api";
import {
@@ -59,7 +59,7 @@ export const GcpSecretManagerConfigurePage = () => {
"confirmIntegration"
] as const);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit, setValue, watch } = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
@@ -69,7 +69,7 @@ export const GcpSecretManagerConfigurePage = () => {
shouldLabel: false,
labelName: "managed-by",
labelValue: "infisical",
- selectedSourceEnvironment: currentWorkspace.environments[0].slug
+ selectedSourceEnvironment: currentProject.environments[0].slug
}
});
@@ -153,7 +153,7 @@ export const GcpSecretManagerConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -241,7 +241,7 @@ export const GcpSecretManagerConfigurePage = () => {
onValueChange={(e) => onChange(e)}
className="w-full"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/GcpSecretManagerOauthCallbackPage/GcpSecretManagerOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/GcpSecretManagerOauthCallbackPage/GcpSecretManagerOauthCallbackPage.tsx
index 67cb0fac59..8e8fd5b0c0 100644
--- a/frontend/src/pages/secret-manager/integrations/GcpSecretManagerOauthCallbackPage/GcpSecretManagerOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GcpSecretManagerOauthCallbackPage/GcpSecretManagerOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
export const GcpSecretManagerOauthCallbackPage = () => {
@@ -12,7 +12,7 @@ export const GcpSecretManagerOauthCallbackPage = () => {
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.GcpSecretManagerOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -22,7 +22,7 @@ export const GcpSecretManagerOauthCallbackPage = () => {
if (state !== localStorage.getItem("latestCSRFToken")) return;
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
code: code as string,
integration: "gcp-secret-manager"
});
@@ -30,7 +30,7 @@ export const GcpSecretManagerOauthCallbackPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/gcp-secret-manager/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/GithubAuthorizePage/GithubAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/GithubAuthorizePage/GithubAuthorizePage.tsx
index 623c5762cf..e4fe73feb8 100644
--- a/frontend/src/pages/secret-manager/integrations/GithubAuthorizePage/GithubAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GithubAuthorizePage/GithubAuthorizePage.tsx
@@ -15,7 +15,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { localStorageService } from "@app/helpers/localStorage";
import { useGetCloudIntegrations } from "@app/hooks/api";
@@ -31,7 +31,7 @@ export const GithubAuthorizePage = () => {
const { data: cloudIntegrations } = useGetCloudIntegrations();
const githubIntegration = cloudIntegrations?.find((integration) => integration.slug === "github");
const [selectedAuthMethod, setSelectedAuthMethod] = useState<AuthMethod>(AuthMethod.APP);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
return (
<div className="flex h-full w-full items-center justify-center">
@@ -84,7 +84,7 @@ export const GithubAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/select-integration-auth",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationSlug: "github"
@@ -102,7 +102,7 @@ export const GithubAuthorizePage = () => {
const state = crypto.randomBytes(16).toString("hex");
localStorage.setItem("latestCSRFToken", state);
- localStorageService.setIntegrationProjectId(currentWorkspace.id);
+ localStorageService.setIntegrationProjectId(currentProject.id);
window.location.assign(
`https://github.com/login/oauth/authorize?client_id=${githubIntegration?.clientId}&response_type=code&scope=repo,admin:org&redirect_uri=${window.location.origin}/integrations/github/oauth2/callback&state=${state}`
);
diff --git a/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx
index aa71c793e5..7dad0d29a7 100644
--- a/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GithubConfigurePage/GithubConfigurePage.tsx
@@ -37,7 +37,7 @@ import {
Tabs
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreateIntegration,
useGetIntegrationAuthApps,
@@ -142,7 +142,7 @@ export const GithubConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.GithubConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -166,7 +166,7 @@ export const GithubConfigurePage = () => {
repoIds: [],
visibility: "all",
shouldEnableDelete: false,
- selectedSourceEnvironment: currentWorkspace.environments[0].slug
+ selectedSourceEnvironment: currentProject.environments[0].slug
}
});
@@ -269,7 +269,7 @@ export const GithubConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -367,7 +367,7 @@ export const GithubConfigurePage = () => {
onValueChange={onChange}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/GithubOauthCallbackPage/GithubOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/GithubOauthCallbackPage/GithubOauthCallbackPage.tsx
index 66520e7f5a..2855539cfe 100644
--- a/frontend/src/pages/secret-manager/integrations/GithubOauthCallbackPage/GithubOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GithubOauthCallbackPage/GithubOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
export const GithubOauthCallbackPage = () => {
@@ -16,7 +16,7 @@ export const GithubOauthCallbackPage = () => {
} = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.GithubOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -29,7 +29,7 @@ export const GithubOauthCallbackPage = () => {
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
code: code as string,
installationId,
integration: "github"
@@ -38,7 +38,7 @@ export const GithubOauthCallbackPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/github/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/GitlabAuthorizePage/GitlabAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/GitlabAuthorizePage/GitlabAuthorizePage.tsx
index 2ce82d97cb..cf77aa3120 100644
--- a/frontend/src/pages/secret-manager/integrations/GitlabAuthorizePage/GitlabAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GitlabAuthorizePage/GitlabAuthorizePage.tsx
@@ -8,7 +8,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { localStorageService } from "@app/helpers/localStorage";
import { useGetCloudIntegrations } from "@app/hooks/api";
@@ -29,7 +29,7 @@ export const GitlabAuthorizePage = () => {
});
const { data: cloudIntegrations } = useGetCloudIntegrations();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const onFormSubmit = ({ gitLabURL }: FormData) => {
if (!cloudIntegrations) return;
@@ -49,12 +49,12 @@ export const GitlabAuthorizePage = () => {
const csrfToken = crypto.randomBytes(16).toString("hex");
localStorage.setItem("latestCSRFToken", csrfToken);
- localStorageService.setIntegrationProjectId(currentWorkspace.id);
+ localStorageService.setIntegrationProjectId(currentProject.id);
const state = `${csrfToken}|${
(gitLabURL as string).trim() === "" ? "" : (gitLabURL as string).trim()
}`;
- localStorageService.setIntegrationProjectId(currentWorkspace.id);
+ localStorageService.setIntegrationProjectId(currentProject.id);
const link = `${baseURL}/oauth/authorize?client_id=${integrationOption.clientId}&redirect_uri=${window.location.origin}/integrations/gitlab/oauth2/callback&response_type=code&state=${state}`;
window.location.assign(link);
diff --git a/frontend/src/pages/secret-manager/integrations/GitlabConfigurePage/GitlabConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/GitlabConfigurePage/GitlabConfigurePage.tsx
index 6fb388b715..13d2081ad6 100644
--- a/frontend/src/pages/secret-manager/integrations/GitlabConfigurePage/GitlabConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GitlabConfigurePage/GitlabConfigurePage.tsx
@@ -26,7 +26,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { usePopUp } from "@app/hooks";
import { useCreateIntegration } from "@app/hooks/api";
import {
@@ -76,7 +76,7 @@ export const GitlabConfigurePage = () => {
const { popUp, handlePopUpOpen, handlePopUpToggle, handlePopUpClose } = usePopUp([
"confirmIntegration"
] as const);
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit, setValue, watch } = useForm<FormData>({
resolver: zodResolver(schema),
@@ -85,7 +85,7 @@ export const GitlabConfigurePage = () => {
secretPath: "/",
secretPrefix: "",
secretSuffix: "",
- selectedSourceEnvironment: currentWorkspace.environments[0].slug,
+ selectedSourceEnvironment: currentProject.environments[0].slug,
initialSyncBehavior: IntegrationSyncBehavior.PREFER_SOURCE
}
});
@@ -177,7 +177,7 @@ export const GitlabConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -267,7 +267,7 @@ export const GitlabConfigurePage = () => {
onValueChange={(e) => onChange(e)}
className="w-full"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/GitlabOauthCallbackPage/GitlabOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/GitlabOauthCallbackPage/GitlabOauthCallbackPage.tsx
index c53cfd628c..e312f04384 100644
--- a/frontend/src/pages/secret-manager/integrations/GitlabOauthCallbackPage/GitlabOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/GitlabOauthCallbackPage/GitlabOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateAppConnection, useUpdateAppConnection } from "@app/hooks/api/appConnections";
import { GitLabConnectionMethod } from "@app/hooks/api/appConnections/types/gitlab-connection";
@@ -14,7 +14,7 @@ export const GitLabOAuthCallbackPage = () => {
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.GitlabOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -65,7 +65,7 @@ export const GitLabOAuthCallbackPage = () => {
});
} else {
appConnection = await createAppConnection({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
...connectionData
});
}
@@ -87,7 +87,7 @@ export const GitLabOAuthCallbackPage = () => {
});
}
})();
- }, [code, state, navigate, createAppConnection, updateAppConnection, currentWorkspace.id]);
+ }, [code, state, navigate, createAppConnection, updateAppConnection, currentProject.id]);
return (
<div className="flex h-screen items-center justify-center">
diff --git a/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx
index ae200968a0..8a8cbbc4c2 100644
--- a/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/HashicorpVaultAuthorizePage/HashicorpVaultAuthorizePage.tsx
@@ -9,7 +9,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, Card, CardBody, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
const formSchema = z.object({
@@ -25,7 +25,7 @@ export const HashicorpVaultAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const {
control,
handleSubmit,
@@ -43,7 +43,7 @@ export const HashicorpVaultAuthorizePage = () => {
const handleFormSubmit = async (formData: TForm) => {
try {
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "hashicorp-vault",
accessId: formData.vaultRoleID,
accessToken: formData.vaultSecretID,
@@ -53,7 +53,7 @@ export const HashicorpVaultAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/hashicorp-vault/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx
index af9af585e8..48b31dd80d 100644
--- a/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/HashicorpVaultConfigurePage/HashicorpVaultConfigurePage.tsx
@@ -25,7 +25,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { isValidPath } from "@app/helpers/string";
import { useCreateIntegration } from "@app/hooks/api";
import { useGetIntegrationAuthById } from "@app/hooks/api/integrationAuth";
@@ -61,7 +61,7 @@ export const HashicorpVaultConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.HashicorpVaultConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -72,8 +72,8 @@ export const HashicorpVaultConfigurePage = () => {
);
const formSchema = useMemo(() => {
- return generateFormSchema(currentWorkspace?.environments.map((env) => env.slug) ?? []);
- }, [currentWorkspace?.environments]);
+ return generateFormSchema(currentProject?.environments.map((env) => env.slug) ?? []);
+ }, [currentProject?.environments]);
const {
control,
@@ -103,7 +103,7 @@ export const HashicorpVaultConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -177,7 +177,7 @@ export const HashicorpVaultConfigurePage = () => {
onValueChange={field.onChange}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`vault-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/HasuraCloudAuthorizePage/HasuraCloudAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/HasuraCloudAuthorizePage/HasuraCloudAuthorizePage.tsx
index 8c29a0c698..e079665620 100644
--- a/frontend/src/pages/secret-manager/integrations/HasuraCloudAuthorizePage/HasuraCloudAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/HasuraCloudAuthorizePage/HasuraCloudAuthorizePage.tsx
@@ -8,7 +8,7 @@ import { useNavigate } from "@tanstack/react-router";
import { z } from "zod";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
const schema = z.object({
@@ -23,7 +23,7 @@ export const HasuraCloudAuthorizePage = () => {
const [isLoading, setIsLoading] = useState(false);
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit } = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
@@ -36,7 +36,7 @@ export const HasuraCloudAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "hasura-cloud",
accessToken
});
@@ -45,7 +45,7 @@ export const HasuraCloudAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/hasura-cloud/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/HasuraCloudConfigurePage/HasuraCloudConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/HasuraCloudConfigurePage/HasuraCloudConfigurePage.tsx
index a42451e8ec..cfcba8058c 100644
--- a/frontend/src/pages/secret-manager/integrations/HasuraCloudConfigurePage/HasuraCloudConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/HasuraCloudConfigurePage/HasuraCloudConfigurePage.tsx
@@ -9,7 +9,7 @@ import { z } from "zod";
import { Button, Card, CardTitle, FormControl, Select, SelectItem } from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -38,7 +38,7 @@ export const HasuraCloudConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.HasuraCloudConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -72,7 +72,7 @@ export const HasuraCloudConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -137,7 +137,7 @@ export const HasuraCloudConfigurePage = () => {
field.onChange(val);
}}
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/HerokuConfigurePage/HerokuConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/HerokuConfigurePage/HerokuConfigurePage.tsx
index c36961ffad..6d00ce873e 100644
--- a/frontend/src/pages/secret-manager/integrations/HerokuConfigurePage/HerokuConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/HerokuConfigurePage/HerokuConfigurePage.tsx
@@ -10,7 +10,7 @@ import { z } from "zod";
import { Button, Card, CardTitle, FormControl, Select, SelectItem } from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
// import { RadioGroup } from "@app/components/v2/RadioGroup";
import { useCreateIntegration } from "@app/hooks/api";
import {
@@ -41,13 +41,13 @@ type FormData = z.infer<typeof schema>;
export const HerokuConfigurePage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit, setValue, watch } = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
secretPath: "/",
initialSyncBehavior: IntegrationSyncBehavior.PREFER_SOURCE,
- selectedSourceEnvironment: currentWorkspace.environments[0].slug
+ selectedSourceEnvironment: currentProject.environments[0].slug
}
});
@@ -100,7 +100,7 @@ export const HerokuConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -158,7 +158,7 @@ export const HerokuConfigurePage = () => {
onValueChange={(e) => onChange(e)}
className="w-full"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/HerokuOauthCallbackPage/HerokuOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/HerokuOauthCallbackPage/HerokuOauthCallbackPage.tsx
index 226f84cc75..91e2b9d88b 100644
--- a/frontend/src/pages/secret-manager/integrations/HerokuOauthCallbackPage/HerokuOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/HerokuOauthCallbackPage/HerokuOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateAppConnection, useUpdateAppConnection } from "@app/hooks/api/appConnections";
import { HerokuConnectionMethod } from "@app/hooks/api/appConnections/types/heroku-connection";
@@ -15,7 +15,7 @@ export const HerokuOAuthCallbackPage = () => {
from: ROUTE_PATHS.SecretManager.Integratons.HerokuOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -67,7 +67,7 @@ export const HerokuOAuthCallbackPage = () => {
});
} else {
appConnection = await createAppConnection({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
...connectionData
});
}
@@ -88,7 +88,7 @@ export const HerokuOAuthCallbackPage = () => {
});
}
})();
- }, [code, state, navigate, createAppConnection, updateAppConnection, currentWorkspace.id]);
+ }, [code, state, navigate, createAppConnection, updateAppConnection, currentProject.id]);
return (
<div className="flex h-screen items-center justify-center">
diff --git a/frontend/src/pages/secret-manager/integrations/LaravelForgeAuthorizePage/LaravelForgeAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/LaravelForgeAuthorizePage/LaravelForgeAuthorizePage.tsx
index d67a6ce1da..c607472c7c 100644
--- a/frontend/src/pages/secret-manager/integrations/LaravelForgeAuthorizePage/LaravelForgeAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/LaravelForgeAuthorizePage/LaravelForgeAuthorizePage.tsx
@@ -2,13 +2,13 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const LaravelForgeAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [serverId, setServerId] = useState("");
@@ -33,7 +33,7 @@ export const LaravelForgeAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "laravel-forge",
accessId: serverId,
accessToken: apiKey
@@ -44,7 +44,7 @@ export const LaravelForgeAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/laravel-forge/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/LaravelForgeConfigurePage/LaravelForgeConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/LaravelForgeConfigurePage/LaravelForgeConfigurePage.tsx
index 91963e7492..55a5ac3602 100644
--- a/frontend/src/pages/secret-manager/integrations/LaravelForgeConfigurePage/LaravelForgeConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/LaravelForgeConfigurePage/LaravelForgeConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -23,7 +23,7 @@ export const LaravelForgeConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.LaravelForgeConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -35,7 +35,7 @@ export const LaravelForgeConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetApp, setTargetApp] = useState("");
const [secretPath, setSecretPath] = useState("/");
@@ -74,7 +74,7 @@ export const LaravelForgeConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -95,7 +95,7 @@ export const LaravelForgeConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/NetlifyConfigurePage/NetlifyConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/NetlifyConfigurePage/NetlifyConfigurePage.tsx
index 7450b5cf0a..40ecc3bc54 100644
--- a/frontend/src/pages/secret-manager/integrations/NetlifyConfigurePage/NetlifyConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/NetlifyConfigurePage/NetlifyConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -30,7 +30,7 @@ export const NetlifyConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.NetlifyConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -42,7 +42,7 @@ export const NetlifyConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetApp, setTargetApp] = useState("");
const [targetEnvironment, setTargetEnvironment] = useState(netlifyEnvironments[0].slug);
@@ -81,7 +81,7 @@ export const NetlifyConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -106,7 +106,7 @@ export const NetlifyConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/NetlifyOauthCallbackPage/NetlifyOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/NetlifyOauthCallbackPage/NetlifyOauthCallbackPage.tsx
index 330984622e..a89318f4f3 100644
--- a/frontend/src/pages/secret-manager/integrations/NetlifyOauthCallbackPage/NetlifyOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/NetlifyOauthCallbackPage/NetlifyOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
export const NetlifyOauthCallbackPage = () => {
@@ -12,7 +12,7 @@ export const NetlifyOauthCallbackPage = () => {
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.NetlifyOuathCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -22,7 +22,7 @@ export const NetlifyOauthCallbackPage = () => {
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
code: code as string,
integration: "netlify"
});
@@ -30,7 +30,7 @@ export const NetlifyOauthCallbackPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/netlify/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/NorthflankAuthorizePage/NorthflankAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/NorthflankAuthorizePage/NorthflankAuthorizePage.tsx
index b203a02dca..005a4914e9 100644
--- a/frontend/src/pages/secret-manager/integrations/NorthflankAuthorizePage/NorthflankAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/NorthflankAuthorizePage/NorthflankAuthorizePage.tsx
@@ -2,13 +2,13 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const NorthflankAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
@@ -25,7 +25,7 @@ export const NorthflankAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "northflank",
accessToken: apiKey
});
@@ -35,7 +35,7 @@ export const NorthflankAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/northflank/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/NorthflankConfigurePage/NorthflankConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/NorthflankConfigurePage/NorthflankConfigurePage.tsx
index 7f01c32ee9..9ff1e18c8c 100644
--- a/frontend/src/pages/secret-manager/integrations/NorthflankConfigurePage/NorthflankConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/NorthflankConfigurePage/NorthflankConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -24,9 +24,9 @@ export const NorthflankConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
const [targetAppId, setTargetAppId] = useState("");
@@ -95,7 +95,7 @@ export const NorthflankConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -116,7 +116,7 @@ export const NorthflankConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx
index 789ea3c49c..b1998cfa4b 100644
--- a/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/OctopusDeployAuthorizePage/OctopusDeployAuthorizePage.tsx
@@ -8,7 +8,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { removeTrailingSlash } from "@app/helpers/string";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
@@ -22,7 +22,7 @@ type TForm = z.infer<typeof formSchema>;
export const OctopusDeployAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync, isPending } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit } = useForm<TForm>({
resolver: zodResolver(formSchema)
@@ -31,7 +31,7 @@ export const OctopusDeployAuthorizePage = () => {
const onSubmit = async ({ instanceUrl, apiKey }: TForm) => {
try {
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "octopus-deploy",
url: removeTrailingSlash(instanceUrl),
accessToken: apiKey
@@ -40,7 +40,7 @@ export const OctopusDeployAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/octopus-deploy/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx
index 458c4a997e..bddd884f4f 100644
--- a/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/OctopusDeployConfigurePage/OctopusDeployConfigurePage.tsx
@@ -16,7 +16,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration, useGetIntegrationAuthApps } from "@app/hooks/api";
import {
useGetIntegrationAuthOctopusDeployScopeValues,
@@ -56,7 +56,7 @@ export const OctopusDeployConfigurePage = () => {
}
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.OctopusDeployCloudConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -137,7 +137,7 @@ export const OctopusDeployConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -153,16 +153,16 @@ export const OctopusDeployConfigurePage = () => {
};
useEffect(() => {
- if (!octopusDeployResources || !octopusDeploySpaces || !currentWorkspace) return;
+ if (!octopusDeployResources || !octopusDeploySpaces || !currentProject) return;
reset({
targetResource: octopusDeployResources[0],
targetSpace: octopusDeploySpaces.find((space) => space.IsDefault),
- sourceEnvironment: currentWorkspace.environments[0],
+ sourceEnvironment: currentProject.environments[0],
secretPath: "/",
scope: OctopusDeployScope.Project
});
- }, [octopusDeploySpaces, octopusDeployResources, currentWorkspace]);
+ }, [octopusDeploySpaces, octopusDeployResources, currentProject]);
if (isLoadingOctopusDeploySpaces || isOctopusDeployResourcesLoading)
return (
@@ -196,9 +196,9 @@ export const OctopusDeployConfigurePage = () => {
value={value}
getOptionLabel={(option) => option.name}
onChange={onChange}
- options={currentWorkspace?.environments}
+ options={currentProject?.environments}
placeholder="Select a project environment"
- isDisabled={!currentWorkspace?.environments.length}
+ isDisabled={!currentProject?.environments.length}
/>
</FormControl>
)}
diff --git a/frontend/src/pages/secret-manager/integrations/QoveryAuthorizePage/QoveryAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/QoveryAuthorizePage/QoveryAuthorizePage.tsx
index 607b1962b6..369046df92 100644
--- a/frontend/src/pages/secret-manager/integrations/QoveryAuthorizePage/QoveryAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/QoveryAuthorizePage/QoveryAuthorizePage.tsx
@@ -5,12 +5,12 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const QoveryAuthorizePage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync } = useSaveIntegrationAccessToken();
const [accessToken, setAccessToken] = useState("");
@@ -28,7 +28,7 @@ export const QoveryAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "qovery",
accessToken
});
@@ -38,7 +38,7 @@ export const QoveryAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/qovery/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/QoveryConfigurePage/QoveryConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/QoveryConfigurePage/QoveryConfigurePage.tsx
index bc0f24c900..977f4fdd10 100644
--- a/frontend/src/pages/secret-manager/integrations/QoveryConfigurePage/QoveryConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/QoveryConfigurePage/QoveryConfigurePage.tsx
@@ -19,7 +19,7 @@ import {
Tabs
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import { useGetIntegrationAuthById } from "@app/hooks/api/integrationAuth";
import {
@@ -55,7 +55,7 @@ enum TabSections {
export const QoveryConfigurePage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync } = useCreateIntegration();
const integrationAuthId = useSearch({
@@ -67,7 +67,7 @@ export const QoveryConfigurePage = () => {
const [scope, setScope] = useState("application");
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
@@ -178,7 +178,7 @@ export const QoveryConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -241,7 +241,7 @@ export const QoveryConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/RailwayAuthorizePage/RailwayAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/RailwayAuthorizePage/RailwayAuthorizePage.tsx
index 5acc04b1b2..c17bd2da00 100644
--- a/frontend/src/pages/secret-manager/integrations/RailwayAuthorizePage/RailwayAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/RailwayAuthorizePage/RailwayAuthorizePage.tsx
@@ -2,13 +2,13 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const RailwayAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
@@ -25,7 +25,7 @@ export const RailwayAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "railway",
accessToken: apiKey
});
@@ -35,7 +35,7 @@ export const RailwayAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/railway/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/RailwayConfigurePage/RailwayConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/RailwayConfigurePage/RailwayConfigurePage.tsx
index 835e592774..1d24f7ce7a 100644
--- a/frontend/src/pages/secret-manager/integrations/RailwayConfigurePage/RailwayConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/RailwayConfigurePage/RailwayConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -25,13 +25,13 @@ export const RailwayConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [targetAppId, setTargetAppId] = useState("");
const [targetEnvironmentId, setTargetEnvironmentId] = useState("");
const [targetServiceId, setTargetServiceId] = useState("");
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
const [isLoading, setIsLoading] = useState(false);
@@ -110,7 +110,7 @@ export const RailwayConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -139,7 +139,7 @@ export const RailwayConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/RenderAuthorizePage/RenderAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/RenderAuthorizePage/RenderAuthorizePage.tsx
index 8be39cb9e5..576400ad1d 100644
--- a/frontend/src/pages/secret-manager/integrations/RenderAuthorizePage/RenderAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/RenderAuthorizePage/RenderAuthorizePage.tsx
@@ -5,13 +5,13 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const RenderAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
@@ -28,7 +28,7 @@ export const RenderAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "render",
accessToken: apiKey
});
@@ -38,7 +38,7 @@ export const RenderAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/render/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/RenderConfigurePage/RenderConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/RenderConfigurePage/RenderConfigurePage.tsx
index 3d156cdac3..4a2ef30d12 100644
--- a/frontend/src/pages/secret-manager/integrations/RenderConfigurePage/RenderConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/RenderConfigurePage/RenderConfigurePage.tsx
@@ -23,7 +23,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -44,13 +44,13 @@ export const RenderConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit, setValue, watch } = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
secretPath: "/",
shouldAutoRedeploy: false,
- selectedSourceEnvironment: currentWorkspace.environments[0].slug
+ selectedSourceEnvironment: currentProject.environments[0].slug
}
});
@@ -106,7 +106,7 @@ export const RenderConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -167,7 +167,7 @@ export const RenderConfigurePage = () => {
onValueChange={(e) => onChange(e)}
className="w-full"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/RundeckAuthorizePage/RundeckAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/RundeckAuthorizePage/RundeckAuthorizePage.tsx
index f67b22b374..8ef2af0549 100644
--- a/frontend/src/pages/secret-manager/integrations/RundeckAuthorizePage/RundeckAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/RundeckAuthorizePage/RundeckAuthorizePage.tsx
@@ -8,7 +8,7 @@ import { useNavigate } from "@tanstack/react-router";
import z from "zod";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
const schema = z.object({
@@ -25,7 +25,7 @@ export const RundeckAuthorizePage = () => {
const [isLoading, setIsLoading] = useState(false);
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { control, handleSubmit } = useForm<FormData>({
resolver: zodResolver(schema),
@@ -40,7 +40,7 @@ export const RundeckAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "rundeck",
accessToken: authToken,
url: rundeckURL.trim()
@@ -50,7 +50,7 @@ export const RundeckAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/rundeck/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/RundeckConfigurePage/RundeckConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/RundeckConfigurePage/RundeckConfigurePage.tsx
index 7c8dada9f3..555a5cc5cc 100644
--- a/frontend/src/pages/secret-manager/integrations/RundeckConfigurePage/RundeckConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/RundeckConfigurePage/RundeckConfigurePage.tsx
@@ -17,7 +17,7 @@ import {
} from "@app/components/v2";
import { SecretPathInput } from "@app/components/v2/SecretPathInput";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import { useGetIntegrationAuthById } from "@app/hooks/api/integrationAuth";
import { IntegrationsListPageTabs } from "@app/types/integrations";
@@ -44,7 +44,7 @@ export const RundeckConfigurePage = () => {
});
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.RundeckConfigurePage.id,
@@ -73,7 +73,7 @@ export const RundeckConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -138,7 +138,7 @@ export const RundeckConfigurePage = () => {
field.onChange(val);
}}
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
@@ -171,7 +171,7 @@ export const RundeckConfigurePage = () => {
isError={Boolean(error)}
>
<Input
- placeholder={`keys/project/${currentWorkspace.name
+ placeholder={`keys/project/${currentProject.name
.toLowerCase()
.replace(/ /g, "-")}/${selectedSourceEnvironment}`}
{...field}
diff --git a/frontend/src/pages/secret-manager/integrations/SelectIntegrationAuthPage/SelectIntegrationAuthPage.tsx b/frontend/src/pages/secret-manager/integrations/SelectIntegrationAuthPage/SelectIntegrationAuthPage.tsx
index d06ab24fb1..b2db178c60 100644
--- a/frontend/src/pages/secret-manager/integrations/SelectIntegrationAuthPage/SelectIntegrationAuthPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/SelectIntegrationAuthPage/SelectIntegrationAuthPage.tsx
@@ -6,7 +6,7 @@ import { useNavigate, useSearch } from "@tanstack/react-router";
import { Button, Card, CardTitle, ContentLoader } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useOrganization, useWorkspace } from "@app/context";
+import { useOrganization, useProject } from "@app/context";
import {
useDuplicateIntegrationAuth,
useGetCloudIntegrations,
@@ -20,7 +20,7 @@ export const SelectIntegrationAuthPage = () => {
const navigate = useNavigate();
const { data: cloudIntegrations } = useGetCloudIntegrations();
const { currentOrg } = useOrganization();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const orgId = currentOrg?.id || "";
const integrationSlug = useSearch({
@@ -50,10 +50,10 @@ export const SelectIntegrationAuthPage = () => {
if (integrationSlug === "github") {
const sameProjectIntegrationAuths = filteredIntegrationAuths.filter(
- (auth) => auth.projectId === currentWorkspace?.id
+ (auth) => auth.projectId === currentProject?.id
);
const differentProjectIntegrationAuths = filteredIntegrationAuths.filter(
- (auth) => auth.projectId !== currentWorkspace?.id
+ (auth) => auth.projectId !== currentProject?.id
);
const installationIds = new Set<string>();
@@ -117,11 +117,11 @@ export const SelectIntegrationAuthPage = () => {
const handleConnectionSelect = async (integrationAuth: IntegrationAuth) => {
if (integrationSlug === "github") {
- if (integrationAuth.projectId === currentWorkspace?.id) {
+ if (integrationAuth.projectId === currentProject?.id) {
navigate({
to: "/projects/secret-management/$projectId/integrations/github/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
@@ -130,14 +130,14 @@ export const SelectIntegrationAuthPage = () => {
} else {
// we create a copy of the existing integration auth from another project to the current project
const newIntegrationAuth = await duplicateIntegrationAuth({
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
integrationAuthId: integrationAuth.id
});
navigate({
to: "/projects/secret-management/$projectId/integrations/github/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: newIntegrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/SupabaseAuthorizePage/SupabaseAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/SupabaseAuthorizePage/SupabaseAuthorizePage.tsx
index 5ec969e118..210efea1c3 100644
--- a/frontend/src/pages/secret-manager/integrations/SupabaseAuthorizePage/SupabaseAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/SupabaseAuthorizePage/SupabaseAuthorizePage.tsx
@@ -2,13 +2,13 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const SupabaseAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
@@ -25,7 +25,7 @@ export const SupabaseAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "supabase",
accessToken: apiKey
});
@@ -35,7 +35,7 @@ export const SupabaseAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/supabase/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/SupabaseConfigurePage/SupabaseConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/SupabaseConfigurePage/SupabaseConfigurePage.tsx
index 333c61a8ec..38183a5adf 100644
--- a/frontend/src/pages/secret-manager/integrations/SupabaseConfigurePage/SupabaseConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/SupabaseConfigurePage/SupabaseConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -22,7 +22,7 @@ import { IntegrationsListPageTabs } from "@app/types/integrations";
export const SupabaseConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.SupabaseConfigurePage.id,
select: (el) => el.integrationAuthId
@@ -34,7 +34,7 @@ export const SupabaseConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
const [targetApp, setTargetApp] = useState("");
@@ -73,7 +73,7 @@ export const SupabaseConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -94,7 +94,7 @@ export const SupabaseConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/TeamcityAuthorizePage/TeamcityAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/TeamcityAuthorizePage/TeamcityAuthorizePage.tsx
index 4698fac598..7ece98cd70 100644
--- a/frontend/src/pages/secret-manager/integrations/TeamcityAuthorizePage/TeamcityAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/TeamcityAuthorizePage/TeamcityAuthorizePage.tsx
@@ -5,14 +5,14 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const TeamcityAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [serverUrl, setServerUrl] = useState("");
@@ -37,7 +37,7 @@ export const TeamcityAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "teamcity",
accessToken: apiKey,
url: serverUrl
@@ -48,7 +48,7 @@ export const TeamcityAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/teamcity/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/TeamcityConfigurePage/TeamcityConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/TeamcityConfigurePage/TeamcityConfigurePage.tsx
index 9291d0d5fd..8e7d0fe973 100644
--- a/frontend/src/pages/secret-manager/integrations/TeamcityConfigurePage/TeamcityConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/TeamcityConfigurePage/TeamcityConfigurePage.tsx
@@ -14,7 +14,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -26,7 +26,7 @@ import { IntegrationsListPageTabs } from "@app/types/integrations";
export const TeamcityConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.TeamcityConfigurePage.id,
@@ -34,7 +34,7 @@ export const TeamcityConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetAppId, setTargetAppId] = useState("");
const [targetBuildConfigId, setTargetBuildConfigId] = useState<string>("");
@@ -92,7 +92,7 @@ export const TeamcityConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -149,7 +149,7 @@ export const TeamcityConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/TerraformCloudAuthorizePage/TerraformCloudAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/TerraformCloudAuthorizePage/TerraformCloudAuthorizePage.tsx
index eac1fa0c0e..4275875c4b 100644
--- a/frontend/src/pages/secret-manager/integrations/TerraformCloudAuthorizePage/TerraformCloudAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/TerraformCloudAuthorizePage/TerraformCloudAuthorizePage.tsx
@@ -5,13 +5,13 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const TerraformCloudAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
@@ -37,7 +37,7 @@ export const TerraformCloudAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "terraform-cloud",
accessId: workspacesId,
accessToken: apiKey
@@ -48,7 +48,7 @@ export const TerraformCloudAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/terraform-cloud/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/TerraformCloudConfigurePage/TerraformCloudConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/TerraformCloudConfigurePage/TerraformCloudConfigurePage.tsx
index a2d73feca6..ba44dfaa47 100644
--- a/frontend/src/pages/secret-manager/integrations/TerraformCloudConfigurePage/TerraformCloudConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/TerraformCloudConfigurePage/TerraformCloudConfigurePage.tsx
@@ -14,7 +14,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -44,7 +44,7 @@ export const TerraformCloudConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.TerraformCloudConfigurePage.id,
@@ -56,7 +56,7 @@ export const TerraformCloudConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetApp, setTargetApp] = useState("");
const [secretPath, setSecretPath] = useState("/");
@@ -107,7 +107,7 @@ export const TerraformCloudConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -160,7 +160,7 @@ export const TerraformCloudConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/TravisCIAuthorizePage/TravisCIAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/TravisCIAuthorizePage/TravisCIAuthorizePage.tsx
index 3323aed7d8..f588493115 100644
--- a/frontend/src/pages/secret-manager/integrations/TravisCIAuthorizePage/TravisCIAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/TravisCIAuthorizePage/TravisCIAuthorizePage.tsx
@@ -2,12 +2,12 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const TravisCIAuthorizePage = () => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { mutateAsync } = useSaveIntegrationAccessToken();
const [apiKey, setApiKey] = useState("");
@@ -25,7 +25,7 @@ export const TravisCIAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "travisci",
accessToken: apiKey
});
@@ -35,7 +35,7 @@ export const TravisCIAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/travisci/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/TravisCIConfigurePage/TravisCIConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/TravisCIConfigurePage/TravisCIConfigurePage.tsx
index 66c3a80223..e71a6ab319 100644
--- a/frontend/src/pages/secret-manager/integrations/TravisCIConfigurePage/TravisCIConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/TravisCIConfigurePage/TravisCIConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -23,7 +23,7 @@ export const TravisCIConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.TravisCIConfigurePage.id,
@@ -36,7 +36,7 @@ export const TravisCIConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [targetApp, setTargetApp] = useState("");
const [secretPath, setSecretPath] = useState("/");
@@ -74,7 +74,7 @@ export const TravisCIConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -95,7 +95,7 @@ export const TravisCIConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/VercelConfigurePage/VercelConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/VercelConfigurePage/VercelConfigurePage.tsx
index 25c209f09f..c2b668f616 100644
--- a/frontend/src/pages/secret-manager/integrations/VercelConfigurePage/VercelConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/VercelConfigurePage/VercelConfigurePage.tsx
@@ -20,7 +20,7 @@ import {
Tooltip
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -52,9 +52,9 @@ export const VercelConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
const [initialSyncBehavior, setInitialSyncBehavior] = useState<IntegrationSyncBehavior>(
@@ -134,7 +134,7 @@ export const VercelConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -206,7 +206,7 @@ export const VercelConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`azure-key-vault-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/integrations/VercelOauthCallbackPage/VercelOauthCallbackPage.tsx b/frontend/src/pages/secret-manager/integrations/VercelOauthCallbackPage/VercelOauthCallbackPage.tsx
index 02fb22eab1..f3b5b05c41 100644
--- a/frontend/src/pages/secret-manager/integrations/VercelOauthCallbackPage/VercelOauthCallbackPage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/VercelOauthCallbackPage/VercelOauthCallbackPage.tsx
@@ -2,7 +2,7 @@ import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useAuthorizeIntegration } from "@app/hooks/api";
export const VercelOauthCallbackPage = () => {
@@ -12,7 +12,7 @@ export const VercelOauthCallbackPage = () => {
const { code, state } = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.VercelOauthCallbackPage.id
});
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
useEffect(() => {
(async () => {
@@ -22,7 +22,7 @@ export const VercelOauthCallbackPage = () => {
localStorage.removeItem("latestCSRFToken");
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
code: code as string,
integration: "vercel"
});
@@ -30,7 +30,7 @@ export const VercelOauthCallbackPage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/vercel/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/WindmillAuthorizePage/WindmillAuthorizePage.tsx b/frontend/src/pages/secret-manager/integrations/WindmillAuthorizePage/WindmillAuthorizePage.tsx
index 36e791e567..3cd3ff335c 100644
--- a/frontend/src/pages/secret-manager/integrations/WindmillAuthorizePage/WindmillAuthorizePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/WindmillAuthorizePage/WindmillAuthorizePage.tsx
@@ -2,14 +2,14 @@ import { useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Button, Card, CardTitle, FormControl, Input } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { isInfisicalCloud } from "@app/helpers/platform";
import { useSaveIntegrationAccessToken } from "@app/hooks/api";
export const WindmillAuthorizePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useSaveIntegrationAccessToken();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [apiKey, setApiKey] = useState("");
const [apiKeyErrorText, setApiKeyErrorText] = useState("");
const [apiUrl, setApiUrl] = useState<string | null>(null);
@@ -68,7 +68,7 @@ export const WindmillAuthorizePage = () => {
setIsLoading(true);
const integrationAuth = await mutateAsync({
- workspaceId: currentWorkspace.id,
+ workspaceId: currentProject.id,
integration: "windmill",
accessToken: apiKey,
url: apiUrl ?? undefined
@@ -79,7 +79,7 @@ export const WindmillAuthorizePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations/windmill/create",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
integrationAuthId: integrationAuth.id
diff --git a/frontend/src/pages/secret-manager/integrations/WindmillConfigurePage/WindmillConfigurePage.tsx b/frontend/src/pages/secret-manager/integrations/WindmillConfigurePage/WindmillConfigurePage.tsx
index 17929b2a3a..7f781c89e6 100644
--- a/frontend/src/pages/secret-manager/integrations/WindmillConfigurePage/WindmillConfigurePage.tsx
+++ b/frontend/src/pages/secret-manager/integrations/WindmillConfigurePage/WindmillConfigurePage.tsx
@@ -11,7 +11,7 @@ import {
SelectItem
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateIntegration } from "@app/hooks/api";
import {
useGetIntegrationAuthApps,
@@ -23,7 +23,7 @@ export const WindmillConfigurePage = () => {
const navigate = useNavigate();
const { mutateAsync } = useCreateIntegration();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const integrationAuthId = useSearch({
from: ROUTE_PATHS.SecretManager.Integratons.WindmillConfigurePage.id,
@@ -36,7 +36,7 @@ export const WindmillConfigurePage = () => {
});
const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState(
- currentWorkspace.environments[0].slug
+ currentProject.environments[0].slug
);
const [secretPath, setSecretPath] = useState("/");
const [targetApp, setTargetApp] = useState("");
@@ -76,7 +76,7 @@ export const WindmillConfigurePage = () => {
navigate({
to: "/projects/secret-management/$projectId/integrations",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
selectedTab: IntegrationsListPageTabs.NativeIntegrations
@@ -97,7 +97,7 @@ export const WindmillConfigurePage = () => {
onValueChange={(val) => setSelectedSourceEnvironment(val)}
className="w-full border border-mineshaft-500"
>
- {currentWorkspace?.environments.map((sourceEnvironment) => (
+ {currentProject?.environments.map((sourceEnvironment) => (
<SelectItem
value={sourceEnvironment.slug}
key={`source-environment-${sourceEnvironment.slug}`}
diff --git a/frontend/src/pages/secret-manager/layout.tsx b/frontend/src/pages/secret-manager/layout.tsx
index 73c3278d07..4ec396aa92 100644
--- a/frontend/src/pages/secret-manager/layout.tsx
+++ b/frontend/src/pages/secret-manager/layout.tsx
@@ -1,9 +1,9 @@
import { createFileRoute } from "@tanstack/react-router";
import { BreadcrumbTypes } from "@app/components/v2";
-import { workspaceKeys } from "@app/hooks/api";
+import { projectKeys } from "@app/hooks/api";
+import { fetchProjectById } from "@app/hooks/api/projects/queries";
import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
-import { fetchWorkspaceById } from "@app/hooks/api/workspace/queries";
import { ProjectSelect } from "@app/layouts/ProjectLayout/components/ProjectSelect";
import { SecretManagerLayout } from "@app/layouts/SecretManagerLayout";
@@ -14,15 +14,15 @@ export const Route = createFileRoute(
beforeLoad: async ({ params, context }) => {
const project = await context.queryClient.ensureQueryData({
- queryKey: workspaceKeys.getWorkspaceById(params.projectId),
- queryFn: () => fetchWorkspaceById(params.projectId)
+ queryKey: projectKeys.getProjectById(params.projectId),
+ queryFn: () => fetchProjectById(params.projectId)
});
await context.queryClient.ensureQueryData({
queryKey: roleQueryKeys.getUserProjectPermissions({
- workspaceId: params.projectId
+ projectId: params.projectId
}),
- queryFn: () => fetchUserProjectPermissions({ workspaceId: params.projectId })
+ queryFn: () => fetchUserProjectPermissions({ projectId: params.projectId })
});
return {
diff --git a/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningScanRow.tsx b/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningScanRow.tsx
index 6dc7ceb35d..804c4d7908 100644
--- a/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningScanRow.tsx
+++ b/frontend/src/pages/secret-scanning/SecretScanningDataSourceByIdPage/components/SecretScanningScanRow.tsx
@@ -18,7 +18,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useToggle } from "@app/hooks";
import {
SecretScanningScanStatus,
@@ -41,7 +41,7 @@ export const SecretScanningScanRow = ({ scan }: Props) => {
resolvedFindings,
type
} = scan;
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const totalFindings = resolvedFindings + unresolvedFindings;
const navigate = useNavigate();
@@ -97,7 +97,7 @@ export const SecretScanningScanRow = ({ scan }: Props) => {
navigate({
to: "/projects/secret-scanning/$projectId/findings",
params: {
- projectId: currentWorkspace.id
+ projectId: currentProject.id
},
search: {
search: `scanId:${id}`
diff --git a/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/components/SecretScanningDataSourcesSection.tsx b/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/components/SecretScanningDataSourcesSection.tsx
index 019ca3467e..03c387440b 100644
--- a/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/components/SecretScanningDataSourcesSection.tsx
+++ b/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/components/SecretScanningDataSourcesSection.tsx
@@ -5,7 +5,7 @@ import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { ProjectPermissionCan } from "@app/components/permissions";
import { CreateSecretScanningDataSourceModal } from "@app/components/secret-scanning";
import { Button, Spinner } from "@app/components/v2";
-import { ProjectPermissionSub, useSubscription, useWorkspace } from "@app/context";
+import { ProjectPermissionSub, useProject, useSubscription } from "@app/context";
import { ProjectPermissionSecretScanningDataSourceActions } from "@app/context/ProjectPermissionContext/types";
import { usePopUp } from "@app/hooks";
import { useListSecretScanningDataSources } from "@app/hooks/api/secretScanningV2";
@@ -20,10 +20,10 @@ export const SecretScanningDataSourcesSection = () => {
const { subscription } = useSubscription();
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: dataSources = [], isPending: isDataSourcesPending } =
- useListSecretScanningDataSources(currentWorkspace.id, {
+ useListSecretScanningDataSources(currentProject.id, {
refetchInterval: 30000,
enabled: subscription.secretScanning
});
diff --git a/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/route.tsx b/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/route.tsx
index b13c99db7e..87b2b43fbc 100644
--- a/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/route.tsx
+++ b/frontend/src/pages/secret-scanning/SecretScanningDataSourcesPage/route.tsx
@@ -1,11 +1,19 @@
import { createFileRoute } from "@tanstack/react-router";
+import { zodValidator } from "@tanstack/zod-adapter";
+import { z } from "zod";
import { SecretScanningDataSourcesPage } from "./SecretScanningDataSourcesPage";
+const SecretScanningDataSourcesPageQueryParamsSchema = z.object({
+ connectionId: z.string().optional(),
+ connectionName: z.string().optional()
+});
+
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources/"
)({
component: SecretScanningDataSourcesPage,
+ validateSearch: zodValidator(SecretScanningDataSourcesPageQueryParamsSchema),
beforeLoad: ({ context }) => {
return {
breadcrumbs: [
diff --git a/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningFindingsSection.tsx b/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningFindingsSection.tsx
index 82ea049f90..4a9cf1ad01 100644
--- a/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningFindingsSection.tsx
+++ b/frontend/src/pages/secret-scanning/SecretScanningFindingsPage/components/SecretScanningFindingsSection.tsx
@@ -2,16 +2,16 @@ import { faArrowUpRightFromSquare, faBookOpen } from "@fortawesome/free-solid-sv
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { ContentLoader } from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useListSecretScanningFindings } from "@app/hooks/api/secretScanningV2";
import { SecretScanningFindingsTable } from "./SecretScanningFindingsTable";
export const SecretScanningFindingsSection = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: findings = [], isPending: isFindingsPending } = useListSecretScanningFindings(
- currentWorkspace.id,
+ currentProject.id,
{
refetchInterval: 30000
}
diff --git a/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/ProjectScanningConfigTab.tsx b/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/ProjectScanningConfigTab.tsx
index e8d3206d8d..4cf9e2b22e 100644
--- a/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/ProjectScanningConfigTab.tsx
+++ b/frontend/src/pages/secret-scanning/SettingsPage/components/ProjectScanningConfigTab/ProjectScanningConfigTab.tsx
@@ -1,16 +1,16 @@
import { faBan } from "@fortawesome/free-solid-svg-icons";
import { AccessRestrictedBanner, ContentLoader, EmptyState } from "@app/components/v2";
-import { useSubscription, useWorkspace } from "@app/context";
+import { useProject, useSubscription } from "@app/context";
import { useGetSecretScanningConfig } from "@app/hooks/api/secretScanningV2";
import { SecretScanningConfigForm } from "./SecretScanningConfigForm";
export const ProjectScanningConfigTab = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { subscription } = useSubscription();
const { data: config, isPending: isConfigPending } = useGetSecretScanningConfig(
- currentWorkspace.id,
+ currentProject.id,
{ enabled: subscription.secretScanning }
);
diff --git a/frontend/src/pages/secret-scanning/layout.tsx b/frontend/src/pages/secret-scanning/layout.tsx
index 38899a2336..13a43f895c 100644
--- a/frontend/src/pages/secret-scanning/layout.tsx
+++ b/frontend/src/pages/secret-scanning/layout.tsx
@@ -1,9 +1,9 @@
import { createFileRoute } from "@tanstack/react-router";
import { BreadcrumbTypes } from "@app/components/v2";
-import { workspaceKeys } from "@app/hooks/api";
+import { projectKeys } from "@app/hooks/api";
+import { fetchProjectById } from "@app/hooks/api/projects/queries";
import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
-import { fetchWorkspaceById } from "@app/hooks/api/workspace/queries";
import { ProjectSelect } from "@app/layouts/ProjectLayout/components/ProjectSelect";
import { SecretScanningLayout } from "@app/layouts/SecretScanningLayout";
@@ -13,15 +13,15 @@ export const Route = createFileRoute(
component: SecretScanningLayout,
beforeLoad: async ({ params, context }) => {
const project = await context.queryClient.ensureQueryData({
- queryKey: workspaceKeys.getWorkspaceById(params.projectId),
- queryFn: () => fetchWorkspaceById(params.projectId)
+ queryKey: projectKeys.getProjectById(params.projectId),
+ queryFn: () => fetchProjectById(params.projectId)
});
await context.queryClient.ensureQueryData({
queryKey: roleQueryKeys.getUserProjectPermissions({
- workspaceId: params.projectId
+ projectId: params.projectId
}),
- queryFn: () => fetchUserProjectPermissions({ workspaceId: params.projectId })
+ queryFn: () => fetchUserProjectPermissions({ projectId: params.projectId })
});
return {
diff --git a/frontend/src/pages/ssh/SettingsPage/components/ProjectSshTab/components/ProjectSshConfigCasSection.tsx b/frontend/src/pages/ssh/SettingsPage/components/ProjectSshTab/components/ProjectSshConfigCasSection.tsx
index 503717326f..7b00b3ea03 100644
--- a/frontend/src/pages/ssh/SettingsPage/components/ProjectSshTab/components/ProjectSshConfigCasSection.tsx
+++ b/frontend/src/pages/ssh/SettingsPage/components/ProjectSshTab/components/ProjectSshConfigCasSection.tsx
@@ -6,7 +6,7 @@ import { z } from "zod";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
import { Button, FormControl, Select, SelectItem } from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import {
useGetProjectSshConfig,
useListWorkspaceSshCas,
@@ -23,9 +23,9 @@ const schema = z
export type FormData = z.infer<typeof schema>;
export const ProjectSshConfigCasSection = () => {
- const { currentWorkspace } = useWorkspace();
- const { data: sshConfig } = useGetProjectSshConfig(currentWorkspace.id);
- const { data: sshCas } = useListWorkspaceSshCas(currentWorkspace.id);
+ const { currentProject } = useProject();
+ const { data: sshConfig } = useGetProjectSshConfig(currentProject.id);
+ const { data: sshCas } = useListWorkspaceSshCas(currentProject.id);
const { mutate: updateProjectSshConfig } = useUpdateProjectSshConfig();
const {
@@ -49,7 +49,7 @@ export const ProjectSshConfigCasSection = () => {
const onFormSubmit = async ({ defaultUserSshCaId, defaultHostSshCaId }: FormData) => {
try {
await updateProjectSshConfig({
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
defaultUserSshCaId: defaultUserSshCaId || undefined,
defaultHostSshCaId: defaultHostSshCaId || undefined
});
diff --git a/frontend/src/pages/ssh/SshCaByIDPage/SshCaByIDPage.tsx b/frontend/src/pages/ssh/SshCaByIDPage/SshCaByIDPage.tsx
index 8bed6e6476..88a8c7f600 100644
--- a/frontend/src/pages/ssh/SshCaByIDPage/SshCaByIDPage.tsx
+++ b/frontend/src/pages/ssh/SshCaByIDPage/SshCaByIDPage.tsx
@@ -15,7 +15,7 @@ import {
Tooltip
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useDeleteSshCa, useGetSshCaById } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -23,9 +23,9 @@ import { SshCaModal } from "../SshCasPage/components/SshCaModal";
import { SshCaDetailsSection, SshCertificateTemplatesSection } from "./components";
const Page = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
- const projectId = currentWorkspace?.id || "";
+ const projectId = currentProject?.id || "";
const caId = useParams({
from: ROUTE_PATHS.Ssh.SshCaByIDPage.id,
select: (el) => el.caId
diff --git a/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateModal.tsx b/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateModal.tsx
index 5c46739316..6e0baa5026 100644
--- a/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateModal.tsx
+++ b/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateModal.tsx
@@ -14,7 +14,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
SshCertTemplateStatus,
useGetSshCertTemplate,
@@ -71,8 +71,8 @@ enum SshCertificateOperation {
}
export const SshCertificateModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const [operation, setOperation] = useState<SshCertificateOperation>(
SshCertificateOperation.SIGN_SSH_KEY
);
diff --git a/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateTemplateModal.tsx b/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateTemplateModal.tsx
index 55d4104ace..17c7a552ee 100644
--- a/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateTemplateModal.tsx
+++ b/frontend/src/pages/ssh/SshCaByIDPage/components/SshCertificateTemplateModal.tsx
@@ -16,7 +16,7 @@ import {
SelectItem,
Switch
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreateSshCertTemplate,
useGetSshCaById,
@@ -77,7 +77,7 @@ type Props = {
};
export const SshCertificateTemplateModal = ({ popUp, handlePopUpToggle, sshCaId }: Props) => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const { data: ca } = useGetSshCaById(sshCaId);
@@ -85,7 +85,7 @@ export const SshCertificateTemplateModal = ({ popUp, handlePopUpToggle, sshCaId
(popUp?.sshCertificateTemplate?.data as { id: string })?.id || ""
);
- const { data: cas } = useListWorkspaceSshCas(currentWorkspace?.id || "");
+ const { data: cas } = useListWorkspaceSshCas(currentProject?.id || "");
const { mutateAsync: createSshCertTemplate } = useCreateSshCertTemplate();
const { mutateAsync: updateSshCertTemplate } = useUpdateSshCertTemplate();
diff --git a/frontend/src/pages/ssh/SshCasPage/components/SshCaModal.tsx b/frontend/src/pages/ssh/SshCasPage/components/SshCaModal.tsx
index 758af52a95..4c8ce4e193 100644
--- a/frontend/src/pages/ssh/SshCasPage/components/SshCaModal.tsx
+++ b/frontend/src/pages/ssh/SshCasPage/components/SshCaModal.tsx
@@ -15,7 +15,7 @@ import {
SelectItem,
TextArea
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useCreateSshCa, useGetSshCaById, useUpdateSshCa } from "@app/hooks/api";
import {
SshCaKeySource,
@@ -54,8 +54,8 @@ export type FormData = z.infer<typeof schema>;
export const SshCaModal = ({ popUp, handlePopUpToggle }: Props) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
const { data: ca } = useGetSshCaById((popUp?.sshCa?.data as { caId: string })?.caId || "");
const { mutateAsync: createMutateAsync } = useCreateSshCa();
diff --git a/frontend/src/pages/ssh/SshCasPage/components/SshCaTable.tsx b/frontend/src/pages/ssh/SshCasPage/components/SshCaTable.tsx
index 37a086f37c..c94f736647 100644
--- a/frontend/src/pages/ssh/SshCasPage/components/SshCaTable.tsx
+++ b/frontend/src/pages/ssh/SshCasPage/components/SshCaTable.tsx
@@ -21,7 +21,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { SshCaStatus, useListWorkspaceSshCas } from "@app/hooks/api";
import { caStatusToNameMap, getCaStatusBadgeVariant } from "@app/hooks/api/ca/constants";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -35,8 +35,8 @@ type Props = {
export const SshCaTable = ({ handlePopUpOpen }: Props) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const { data, isPending } = useListWorkspaceSshCas(currentWorkspace?.id || "");
+ const { currentProject } = useProject();
+ const { data, isPending } = useListWorkspaceSshCas(currentProject?.id || "");
return (
<div>
@@ -63,7 +63,7 @@ export const SshCaTable = ({ handlePopUpOpen }: Props) => {
navigate({
to: "/projects/ssh/$projectId/ca/$caId",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
caId: ca.id
}
})
diff --git a/frontend/src/pages/ssh/SshCertsPage/components/SshCertificatesTable.tsx b/frontend/src/pages/ssh/SshCertsPage/components/SshCertificatesTable.tsx
index c48b407ac6..1ebf3112cf 100644
--- a/frontend/src/pages/ssh/SshCertsPage/components/SshCertificatesTable.tsx
+++ b/frontend/src/pages/ssh/SshCertsPage/components/SshCertificatesTable.tsx
@@ -15,7 +15,7 @@ import {
THead,
Tr
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import { useListWorkspaceSshCertificates } from "@app/hooks/api";
import { getSshCertStatusBadgeDetails } from "./SshCertificatesTable.utils";
@@ -23,12 +23,12 @@ import { getSshCertStatusBadgeDetails } from "./SshCertificatesTable.utils";
const PER_PAGE_INIT = 25;
export const SshCertificatesTable = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const [page, setPage] = useState(1);
const [perPage, setPerPage] = useState(PER_PAGE_INIT);
const { data, isPending } = useListWorkspaceSshCertificates({
- projectId: currentWorkspace?.id || "",
+ projectId: currentProject?.id || "",
offset: (page - 1) * perPage,
limit: perPage
});
diff --git a/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/SshHostGroupDetailsByIDPage.tsx b/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/SshHostGroupDetailsByIDPage.tsx
index 6b43e83240..e030a8fa06 100644
--- a/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/SshHostGroupDetailsByIDPage.tsx
+++ b/frontend/src/pages/ssh/SshHostGroupDetailsByIDPage/SshHostGroupDetailsByIDPage.tsx
@@ -16,7 +16,7 @@ import {
Tooltip
} from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useDeleteSshHostGroup, useGetSshHostGroupById } from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -24,9 +24,9 @@ import { SshHostGroupModal } from "../SshHostsPage/components/SshHostGroupModal"
import { SshHostGroupDetailsSection, SshHostGroupHostsSection } from "./components";
const Page = () => {
- const { currentWorkspace } = useWorkspace();
+ const { currentProject } = useProject();
const navigate = useNavigate();
- const projectId = currentWorkspace?.id || "";
+ const projectId = currentProject?.id || "";
const sshHostGroupId = useParams({
from: ROUTE_PATHS.Ssh.SshHostGroupDetailsByIDPage.id,
select: (el) => el.sshHostGroupId
diff --git a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupModal.tsx b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupModal.tsx
index 84be5a96d7..4905695d48 100644
--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupModal.tsx
+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupModal.tsx
@@ -17,7 +17,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreateSshHostGroup,
useGetSshHostGroupById,
@@ -56,8 +56,8 @@ const schema = z
export type FormData = z.infer<typeof schema>;
export const SshHostGroupModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace.id;
+ const { currentProject } = useProject();
+ const projectId = currentProject.id;
const { data: sshHostGroups } = useListWorkspaceSshHostGroups(projectId);
const { data: members = [] } = useGetWorkspaceUsers(projectId);
const { data: groups = [] } = useListWorkspaceGroups(projectId);
diff --git a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsTable.tsx b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsTable.tsx
index daedabdc91..af3a97dc6a 100644
--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsTable.tsx
+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostGroupsTable.tsx
@@ -28,7 +28,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionActions, ProjectPermissionSub, useProject } from "@app/context";
import { useListWorkspaceSshHostGroups } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -41,8 +41,8 @@ type Props = {
export const SshHostGroupsTable = ({ handlePopUpOpen }: Props) => {
const navigate = useNavigate();
- const { currentWorkspace } = useWorkspace();
- const { data, isPending } = useListWorkspaceSshHostGroups(currentWorkspace?.id || "");
+ const { currentProject } = useProject();
+ const { data, isPending } = useListWorkspaceSshHostGroups(currentProject?.id || "");
return (
<div>
<TableContainer>
@@ -69,7 +69,7 @@ export const SshHostGroupsTable = ({ handlePopUpOpen }: Props) => {
navigate({
to: "/projects/ssh/$projectId/ssh-host-groups/$sshHostGroupId",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
sshHostGroupId: group.id
}
})
@@ -170,7 +170,7 @@ export const SshHostGroupsTable = ({ handlePopUpOpen }: Props) => {
navigate({
to: "/projects/ssh/$projectId/ssh-host-groups/$sshHostGroupId",
params: {
- projectId: currentWorkspace.id,
+ projectId: currentProject.id,
sshHostGroupId: group.id
}
});
diff --git a/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx b/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx
index 5619a75c4c..e1ea75143a 100644
--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx
+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostModal.tsx
@@ -18,7 +18,7 @@ import {
Select,
SelectItem
} from "@app/components/v2";
-import { useWorkspace } from "@app/context";
+import { useProject } from "@app/context";
import {
useCreateSshHost,
useGetSshHostById,
@@ -68,9 +68,9 @@ const schema = z
export type FormData = z.infer<typeof schema>;
export const SshHostModal = ({ popUp, handlePopUpToggle }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const projectId = currentWorkspace?.id || "";
- const { data: sshHosts } = useListWorkspaceSshHosts(currentWorkspace.id);
+ const { currentProject } = useProject();
+ const projectId = currentProject?.id || "";
+ const { data: sshHosts } = useListWorkspaceSshHosts(currentProject.id);
const { data: members = [] } = useGetWorkspaceUsers(projectId);
const { data: groups = [] } = useListWorkspaceGroups(projectId);
const [expandedMappings, setExpandedMappings] = useState<Record<number, boolean>>({});
diff --git a/frontend/src/pages/ssh/SshHostsPage/components/SshHostsTable.tsx b/frontend/src/pages/ssh/SshHostsPage/components/SshHostsTable.tsx
index 62f563ccec..f29f0147e7 100644
--- a/frontend/src/pages/ssh/SshHostsPage/components/SshHostsTable.tsx
+++ b/frontend/src/pages/ssh/SshHostsPage/components/SshHostsTable.tsx
@@ -30,7 +30,7 @@ import {
Tooltip,
Tr
} from "@app/components/v2";
-import { ProjectPermissionSshHostActions, ProjectPermissionSub, useWorkspace } from "@app/context";
+import { ProjectPermissionSshHostActions, ProjectPermissionSub, useProject } from "@app/context";
import { fetchSshHostUserCaPublicKey, useListWorkspaceSshHosts } from "@app/hooks/api";
import { LoginMappingSource } from "@app/hooks/api/sshHost/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -43,8 +43,8 @@ type Props = {
};
export const SshHostsTable = ({ handlePopUpOpen }: Props) => {
- const { currentWorkspace } = useWorkspace();
- const { data, isPending } = useListWorkspaceSshHosts(currentWorkspace?.id || "");
+ const { currentProject } = useProject();
+ const { data, isPending } = useListWorkspaceSshHosts(currentProject?.id || "");
const downloadTxtFile = (filename: string, content: string) => {
const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
diff --git a/frontend/src/pages/ssh/layout.tsx b/frontend/src/pages/ssh/layout.tsx
index 008aca3935..9b1a0057bb 100644
--- a/frontend/src/pages/ssh/layout.tsx
+++ b/frontend/src/pages/ssh/layout.tsx
@@ -1,9 +1,9 @@
import { createFileRoute } from "@tanstack/react-router";
import { BreadcrumbTypes } from "@app/components/v2";
-import { workspaceKeys } from "@app/hooks/api";
+import { projectKeys } from "@app/hooks/api";
+import { fetchProjectById } from "@app/hooks/api/projects/queries";
import { fetchUserProjectPermissions, roleQueryKeys } from "@app/hooks/api/roles/queries";
-import { fetchWorkspaceById } from "@app/hooks/api/workspace/queries";
import { ProjectSelect } from "@app/layouts/ProjectLayout/components/ProjectSelect";
import { SshLayout } from "@app/layouts/SshLayout";
@@ -13,15 +13,15 @@ export const Route = createFileRoute(
component: SshLayout,
beforeLoad: async ({ params, context }) => {
const project = await context.queryClient.ensureQueryData({
- queryKey: workspaceKeys.getWorkspaceById(params.projectId),
- queryFn: () => fetchWorkspaceById(params.projectId)
+ queryKey: projectKeys.getProjectById(params.projectId),
+ queryFn: () => fetchProjectById(params.projectId)
});
await context.queryClient.ensureQueryData({
queryKey: roleQueryKeys.getUserProjectPermissions({
- workspaceId: params.projectId
+ projectId: params.projectId
}),
- queryFn: () => fetchUserProjectPermissions({ workspaceId: params.projectId })
+ queryFn: () => fetchUserProjectPermissions({ projectId: params.projectId })
});
return {
diff --git a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
index 723ed74980..dc0bf3abf5 100644
--- a/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
+++ b/frontend/src/pages/user/PersonalSettingsPage/components/ChangeEmailSection/ChangeEmailSection.tsx
@@ -10,6 +10,7 @@ import { Button, FormControl, Input, Modal, ModalContent } from "@app/components
import { useUser } from "@app/context";
import { useRequestEmailChangeOTP, useUpdateUserEmail } from "@app/hooks/api/users";
import { clearSession } from "@app/hooks/api/users/queries";
+import { AuthMethod } from "@app/hooks/api/users/types";
const emailSchema = z
.object({
@@ -43,6 +44,7 @@ const otpInputProps = {
export const ChangeEmailSection = () => {
const navigate = useNavigate();
const { user } = useUser();
+ const hasEmailAuth = user?.authMethods?.includes(AuthMethod.EMAIL) ?? false;
const [isOTPModalOpen, setIsOTPModalOpen] = useState(false);
const [pendingEmail, setPendingEmail] = useState("");
@@ -177,6 +179,11 @@ export const ChangeEmailSection = () => {
label="New email address"
isError={Boolean(error)}
errorText={error?.message}
+ tooltipText={
+ hasEmailAuth
+ ? "Your email authentication method is currently enabled and will remain active after changing your email."
+ : "Email authentication method will be automatically enabled after changing your email. You may disable email authentication after logging in with your new email if needed."
+ }
>
<Input
{...field}
diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts
index 1f62ba7b90..0b4ea1426d 100644
--- a/frontend/src/routeTree.gen.ts
+++ b/frontend/src/routeTree.gen.ts
@@ -62,6 +62,7 @@ import { Route as organizationIdentityDetailsByIDPageRouteImport } from './pages
import { Route as organizationGroupDetailsByIDPageRouteImport } from './pages/organization/GroupDetailsByIDPage/route'
import { Route as organizationSettingsPageRouteImport } from './pages/organization/SettingsPage/route'
import { Route as organizationSecretSharingPageRouteImport } from './pages/organization/SecretSharingPage/route'
+import { Route as organizationGatewaysRelayRelayListPageRouteImport } from './pages/organization/Gateways/Relay/RelayListPage/route'
import { Route as organizationGatewaysGatewayListPageRouteImport } from './pages/organization/Gateways/GatewayListPage/route'
import { Route as organizationAppConnectionsAppConnectionsPageRouteImport } from './pages/organization/AppConnections/AppConnectionsPage/route'
import { Route as sshLayoutImport } from './pages/ssh/layout'
@@ -82,12 +83,15 @@ import { Route as organizationSettingsPageOauthCallbackPageRouteImport } from '.
import { Route as projectAuditLogsPageRouteSshImport } from './pages/project/AuditLogsPage/route-ssh'
import { Route as projectAccessControlPageRouteSshImport } from './pages/project/AccessControlPage/route-ssh'
import { Route as projectAuditLogsPageRouteSecretScanningImport } from './pages/project/AuditLogsPage/route-secret-scanning'
+import { Route as projectAppConnectionsPageRouteSecretScanningImport } from './pages/project/AppConnectionsPage/route-secret-scanning'
import { Route as projectAccessControlPageRouteSecretScanningImport } from './pages/project/AccessControlPage/route-secret-scanning'
import { Route as projectAuditLogsPageRouteSecretManagerImport } from './pages/project/AuditLogsPage/route-secret-manager'
+import { Route as projectAppConnectionsPageRouteSecretManagerImport } from './pages/project/AppConnectionsPage/route-secret-manager'
import { Route as projectAccessControlPageRouteSecretManagerImport } from './pages/project/AccessControlPage/route-secret-manager'
import { Route as projectAuditLogsPageRouteKmsImport } from './pages/project/AuditLogsPage/route-kms'
import { Route as projectAccessControlPageRouteKmsImport } from './pages/project/AccessControlPage/route-kms'
import { Route as projectAuditLogsPageRouteCertManagerImport } from './pages/project/AuditLogsPage/route-cert-manager'
+import { Route as projectAppConnectionsPageRouteCertManagerImport } from './pages/project/AppConnectionsPage/route-cert-manager'
import { Route as projectAccessControlPageRouteCertManagerImport } from './pages/project/AccessControlPage/route-cert-manager'
import { Route as sshSettingsPageRouteImport } from './pages/ssh/SettingsPage/route'
import { Route as sshSshHostsPageRouteImport } from './pages/ssh/SshHostsPage/route'
@@ -252,6 +256,10 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingImport =
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing',
)()
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysImport =
+ createFileRoute(
+ '/_authenticate/_inject-org-details/_org-layout/organization/relays',
+ )()
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport =
createFileRoute(
'/_authenticate/_inject-org-details/_org-layout/organization/gateways',
@@ -556,6 +564,14 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationRoute,
} as any)
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRoute =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysImport.update({
+ id: '/relays',
+ path: '/relays',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRoute,
+ } as any)
+
const AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport.update({
id: '/gateways',
@@ -762,6 +778,14 @@ const organizationSecretSharingPageRouteRoute =
AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRoute,
} as any)
+const organizationGatewaysRelayRelayListPageRouteRoute =
+ organizationGatewaysRelayRelayListPageRouteImport.update({
+ id: '/',
+ path: '/',
+ getParentRoute: () =>
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRoute,
+ } as any)
+
const organizationGatewaysGatewayListPageRouteRoute =
organizationGatewaysGatewayListPageRouteImport.update({
id: '/',
@@ -920,6 +944,13 @@ const projectAuditLogsPageRouteSecretScanningRoute =
getParentRoute: () => secretScanningLayoutRoute,
} as any)
+const projectAppConnectionsPageRouteSecretScanningRoute =
+ projectAppConnectionsPageRouteSecretScanningImport.update({
+ id: '/app-connections',
+ path: '/app-connections',
+ getParentRoute: () => secretScanningLayoutRoute,
+ } as any)
+
const projectAccessControlPageRouteSecretScanningRoute =
projectAccessControlPageRouteSecretScanningImport.update({
id: '/access-management',
@@ -943,6 +974,13 @@ const projectAuditLogsPageRouteSecretManagerRoute =
getParentRoute: () => secretManagerLayoutRoute,
} as any)
+const projectAppConnectionsPageRouteSecretManagerRoute =
+ projectAppConnectionsPageRouteSecretManagerImport.update({
+ id: '/app-connections',
+ path: '/app-connections',
+ getParentRoute: () => secretManagerLayoutRoute,
+ } as any)
+
const projectAccessControlPageRouteSecretManagerRoute =
projectAccessControlPageRouteSecretManagerImport.update({
id: '/access-management',
@@ -989,6 +1027,13 @@ const projectAuditLogsPageRouteCertManagerRoute =
getParentRoute: () => certManagerLayoutRoute,
} as any)
+const projectAppConnectionsPageRouteCertManagerRoute =
+ projectAppConnectionsPageRouteCertManagerImport.update({
+ id: '/app-connections',
+ path: '/app-connections',
+ getParentRoute: () => certManagerLayoutRoute,
+ } as any)
+
const projectAccessControlPageRouteCertManagerRoute =
projectAccessControlPageRouteCertManagerImport.update({
id: '/access-management',
@@ -2352,6 +2397,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organization/relays': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organization/relays'
+ path: '/relays'
+ fullPath: '/organization/relays'
+ preLoaderRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing': {
id: '/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing'
path: '/secret-sharing'
@@ -2387,6 +2439,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof organizationGatewaysGatewayListPageRouteImport
parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysImport
}
+ '/_authenticate/_inject-org-details/_org-layout/organization/relays/': {
+ id: '/_authenticate/_inject-org-details/_org-layout/organization/relays/'
+ path: '/'
+ fullPath: '/organization/relays/'
+ preLoaderRoute: typeof organizationGatewaysRelayRelayListPageRouteImport
+ parentRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysImport
+ }
'/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing/': {
id: '/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing/'
path: '/'
@@ -2730,6 +2789,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof projectAccessControlPageRouteCertManagerImport
parentRoute: typeof certManagerLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections': {
+ id: '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections'
+ path: '/app-connections'
+ fullPath: '/projects/cert-management/$projectId/app-connections'
+ preLoaderRoute: typeof projectAppConnectionsPageRouteCertManagerImport
+ parentRoute: typeof certManagerLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs': {
id: '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs'
path: '/audit-logs'
@@ -2772,6 +2838,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof projectAccessControlPageRouteSecretManagerImport
parentRoute: typeof secretManagerLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/app-connections': {
+ id: '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/app-connections'
+ path: '/app-connections'
+ fullPath: '/projects/secret-management/$projectId/app-connections'
+ preLoaderRoute: typeof projectAppConnectionsPageRouteSecretManagerImport
+ parentRoute: typeof secretManagerLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/audit-logs': {
id: '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/audit-logs'
path: '/audit-logs'
@@ -2793,6 +2866,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof projectAccessControlPageRouteSecretScanningImport
parentRoute: typeof secretScanningLayoutImport
}
+ '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/app-connections': {
+ id: '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/app-connections'
+ path: '/app-connections'
+ fullPath: '/projects/secret-scanning/$projectId/app-connections'
+ preLoaderRoute: typeof projectAppConnectionsPageRouteSecretScanningImport
+ parentRoute: typeof secretScanningLayoutImport
+ }
'/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/audit-logs': {
id: '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/audit-logs'
path: '/audit-logs'
@@ -3689,6 +3769,21 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteChildren,
)
+interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteChildren {
+ organizationGatewaysRelayRelayListPageRouteRoute: typeof organizationGatewaysRelayRelayListPageRouteRoute
+}
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteChildren: AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteChildren =
+ {
+ organizationGatewaysRelayRelayListPageRouteRoute:
+ organizationGatewaysRelayRelayListPageRouteRoute,
+ }
+
+const AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteWithChildren =
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRoute._addFileChildren(
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteChildren,
+ )
+
interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRouteChildren {
organizationSecretSharingPageRouteRoute: typeof organizationSecretSharingPageRouteRoute
organizationSecretSharingSettingsPageRouteRoute: typeof organizationSecretSharingSettingsPageRouteRoute
@@ -3731,6 +3826,7 @@ interface AuthenticateInjectOrgDetailsOrgLayoutOrganizationRouteChildren {
organizationProjectsPageRouteRoute: typeof organizationProjectsPageRouteRoute
AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutOrganizationSettingsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationSettingsRouteWithChildren
organizationGroupDetailsByIDPageRouteRoute: typeof organizationGroupDetailsByIDPageRouteRoute
@@ -3750,6 +3846,8 @@ const AuthenticateInjectOrgDetailsOrgLayoutOrganizationRouteChildren: Authentica
AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRoute:
AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren,
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRoute:
+ AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRoute:
AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRouteWithChildren,
AuthenticateInjectOrgDetailsOrgLayoutOrganizationSettingsRoute:
@@ -3822,6 +3920,7 @@ interface certManagerLayoutRouteChildren {
certManagerCertificatesPageRouteRoute: typeof certManagerCertificatesPageRouteRoute
certManagerSettingsPageRouteRoute: typeof certManagerSettingsPageRouteRoute
projectAccessControlPageRouteCertManagerRoute: typeof projectAccessControlPageRouteCertManagerRoute
+ projectAppConnectionsPageRouteCertManagerRoute: typeof projectAppConnectionsPageRouteCertManagerRoute
projectAuditLogsPageRouteCertManagerRoute: typeof projectAuditLogsPageRouteCertManagerRoute
AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRouteWithChildren
@@ -3841,6 +3940,8 @@ const certManagerLayoutRouteChildren: certManagerLayoutRouteChildren = {
certManagerSettingsPageRouteRoute: certManagerSettingsPageRouteRoute,
projectAccessControlPageRouteCertManagerRoute:
projectAccessControlPageRouteCertManagerRoute,
+ projectAppConnectionsPageRouteCertManagerRoute:
+ projectAppConnectionsPageRouteCertManagerRoute,
projectAuditLogsPageRouteCertManagerRoute:
projectAuditLogsPageRouteCertManagerRoute,
AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRoute:
@@ -4212,6 +4313,7 @@ interface secretManagerLayoutRouteChildren {
secretManagerSecretRotationPageRouteRoute: typeof secretManagerSecretRotationPageRouteRoute
secretManagerSettingsPageRouteRoute: typeof secretManagerSettingsPageRouteRoute
projectAccessControlPageRouteSecretManagerRoute: typeof projectAccessControlPageRouteSecretManagerRoute
+ projectAppConnectionsPageRouteSecretManagerRoute: typeof projectAppConnectionsPageRouteSecretManagerRoute
projectAuditLogsPageRouteSecretManagerRoute: typeof projectAuditLogsPageRouteSecretManagerRoute
AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsRouteWithChildren
secretManagerSecretDashboardPageRouteRoute: typeof secretManagerSecretDashboardPageRouteRoute
@@ -4233,6 +4335,8 @@ const secretManagerLayoutRouteChildren: secretManagerLayoutRouteChildren = {
secretManagerSettingsPageRouteRoute: secretManagerSettingsPageRouteRoute,
projectAccessControlPageRouteSecretManagerRoute:
projectAccessControlPageRouteSecretManagerRoute,
+ projectAppConnectionsPageRouteSecretManagerRoute:
+ projectAppConnectionsPageRouteSecretManagerRoute,
projectAuditLogsPageRouteSecretManagerRoute:
projectAuditLogsPageRouteSecretManagerRoute,
AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsRoute:
@@ -4290,6 +4394,7 @@ interface secretScanningLayoutRouteChildren {
secretScanningSecretScanningFindingsPageRouteRoute: typeof secretScanningSecretScanningFindingsPageRouteRoute
secretScanningSettingsPageRouteRoute: typeof secretScanningSettingsPageRouteRoute
projectAccessControlPageRouteSecretScanningRoute: typeof projectAccessControlPageRouteSecretScanningRoute
+ projectAppConnectionsPageRouteSecretScanningRoute: typeof projectAppConnectionsPageRouteSecretScanningRoute
projectAuditLogsPageRouteSecretScanningRoute: typeof projectAuditLogsPageRouteSecretScanningRoute
AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRouteWithChildren
projectGroupDetailsByIDPageRouteSecretScanningRoute: typeof projectGroupDetailsByIDPageRouteSecretScanningRoute
@@ -4304,6 +4409,8 @@ const secretScanningLayoutRouteChildren: secretScanningLayoutRouteChildren = {
secretScanningSettingsPageRouteRoute: secretScanningSettingsPageRouteRoute,
projectAccessControlPageRouteSecretScanningRoute:
projectAccessControlPageRouteSecretScanningRoute,
+ projectAppConnectionsPageRouteSecretScanningRoute:
+ projectAppConnectionsPageRouteSecretScanningRoute,
projectAuditLogsPageRouteSecretScanningRoute:
projectAuditLogsPageRouteSecretScanningRoute,
AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRoute:
@@ -4640,11 +4747,13 @@ export interface FileRoutesByFullPath {
'/admin/integrations': typeof adminIntegrationsPageRouteRoute
'/organization/app-connections': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren
'/organization/gateways': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren
+ '/organization/relays': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteWithChildren
'/organization/secret-sharing': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRouteWithChildren
'/organization/settings': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationSettingsRouteWithChildren
'/secret-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutSecretManagerProjectIdRouteWithChildren
'/organization/app-connections/': typeof organizationAppConnectionsAppConnectionsPageRouteRoute
'/organization/gateways/': typeof organizationGatewaysGatewayListPageRouteRoute
+ '/organization/relays/': typeof organizationGatewaysRelayRelayListPageRouteRoute
'/organization/secret-sharing/': typeof organizationSecretSharingPageRouteRoute
'/organization/settings/': typeof organizationSettingsPageRouteRoute
'/organization/groups/$groupId': typeof organizationGroupDetailsByIDPageRouteRoute
@@ -4689,15 +4798,18 @@ export interface FileRoutesByFullPath {
'/projects/ssh/$projectId/overview': typeof sshSshHostsPageRouteRoute
'/projects/ssh/$projectId/settings': typeof sshSettingsPageRouteRoute
'/projects/cert-management/$projectId/access-management': typeof projectAccessControlPageRouteCertManagerRoute
+ '/projects/cert-management/$projectId/app-connections': typeof projectAppConnectionsPageRouteCertManagerRoute
'/projects/cert-management/$projectId/audit-logs': typeof projectAuditLogsPageRouteCertManagerRoute
'/projects/cert-management/$projectId/certificate-templates': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
'/projects/cert-management/$projectId/subscribers': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRouteWithChildren
'/projects/kms/$projectId/access-management': typeof projectAccessControlPageRouteKmsRoute
'/projects/kms/$projectId/audit-logs': typeof projectAuditLogsPageRouteKmsRoute
'/projects/secret-management/$projectId/access-management': typeof projectAccessControlPageRouteSecretManagerRoute
+ '/projects/secret-management/$projectId/app-connections': typeof projectAppConnectionsPageRouteSecretManagerRoute
'/projects/secret-management/$projectId/audit-logs': typeof projectAuditLogsPageRouteSecretManagerRoute
'/projects/secret-management/$projectId/integrations': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsRouteWithChildren
'/projects/secret-scanning/$projectId/access-management': typeof projectAccessControlPageRouteSecretScanningRoute
+ '/projects/secret-scanning/$projectId/app-connections': typeof projectAppConnectionsPageRouteSecretScanningRoute
'/projects/secret-scanning/$projectId/audit-logs': typeof projectAuditLogsPageRouteSecretScanningRoute
'/projects/secret-scanning/$projectId/data-sources': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRouteWithChildren
'/projects/ssh/$projectId/access-management': typeof projectAccessControlPageRouteSshRoute
@@ -4858,6 +4970,7 @@ export interface FileRoutesByTo {
'/secret-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutSecretManagerProjectIdRouteWithChildren
'/organization/app-connections': typeof organizationAppConnectionsAppConnectionsPageRouteRoute
'/organization/gateways': typeof organizationGatewaysGatewayListPageRouteRoute
+ '/organization/relays': typeof organizationGatewaysRelayRelayListPageRouteRoute
'/organization/secret-sharing': typeof organizationSecretSharingPageRouteRoute
'/organization/settings': typeof organizationSettingsPageRouteRoute
'/organization/groups/$groupId': typeof organizationGroupDetailsByIDPageRouteRoute
@@ -4902,12 +5015,15 @@ export interface FileRoutesByTo {
'/projects/ssh/$projectId/overview': typeof sshSshHostsPageRouteRoute
'/projects/ssh/$projectId/settings': typeof sshSettingsPageRouteRoute
'/projects/cert-management/$projectId/access-management': typeof projectAccessControlPageRouteCertManagerRoute
+ '/projects/cert-management/$projectId/app-connections': typeof projectAppConnectionsPageRouteCertManagerRoute
'/projects/cert-management/$projectId/audit-logs': typeof projectAuditLogsPageRouteCertManagerRoute
'/projects/kms/$projectId/access-management': typeof projectAccessControlPageRouteKmsRoute
'/projects/kms/$projectId/audit-logs': typeof projectAuditLogsPageRouteKmsRoute
'/projects/secret-management/$projectId/access-management': typeof projectAccessControlPageRouteSecretManagerRoute
+ '/projects/secret-management/$projectId/app-connections': typeof projectAppConnectionsPageRouteSecretManagerRoute
'/projects/secret-management/$projectId/audit-logs': typeof projectAuditLogsPageRouteSecretManagerRoute
'/projects/secret-scanning/$projectId/access-management': typeof projectAccessControlPageRouteSecretScanningRoute
+ '/projects/secret-scanning/$projectId/app-connections': typeof projectAppConnectionsPageRouteSecretScanningRoute
'/projects/secret-scanning/$projectId/audit-logs': typeof projectAuditLogsPageRouteSecretScanningRoute
'/projects/ssh/$projectId/access-management': typeof projectAccessControlPageRouteSshRoute
'/projects/ssh/$projectId/audit-logs': typeof projectAuditLogsPageRouteSshRoute
@@ -5074,11 +5190,13 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/admin/_admin-layout/integrations': typeof adminIntegrationsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organization/app-connections': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationAppConnectionsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organization/gateways': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationGatewaysRouteWithChildren
+ '/_authenticate/_inject-org-details/_org-layout/organization/relays': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationRelaysRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationSecretSharingRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organization/settings': typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationSettingsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId': typeof AuthenticateInjectOrgDetailsOrgLayoutSecretManagerProjectIdRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/organization/app-connections/': typeof organizationAppConnectionsAppConnectionsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organization/gateways/': typeof organizationGatewaysGatewayListPageRouteRoute
+ '/_authenticate/_inject-org-details/_org-layout/organization/relays/': typeof organizationGatewaysRelayRelayListPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing/': typeof organizationSecretSharingPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organization/settings/': typeof organizationSettingsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/organization/groups/$groupId': typeof organizationGroupDetailsByIDPageRouteRoute
@@ -5128,15 +5246,18 @@ export interface FileRoutesById {
'/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/overview': typeof sshSshHostsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/settings': typeof sshSettingsPageRouteRoute
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/access-management': typeof projectAccessControlPageRouteCertManagerRoute
+ '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections': typeof projectAppConnectionsPageRouteCertManagerRoute
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs': typeof projectAuditLogsPageRouteCertManagerRoute
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificate-templates': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutCertificateTemplatesRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/subscribers': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsCertManagementProjectIdCertManagerLayoutSubscribersRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/access-management': typeof projectAccessControlPageRouteKmsRoute
'/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/audit-logs': typeof projectAuditLogsPageRouteKmsRoute
'/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/access-management': typeof projectAccessControlPageRouteSecretManagerRoute
+ '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/app-connections': typeof projectAppConnectionsPageRouteSecretManagerRoute
'/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/audit-logs': typeof projectAuditLogsPageRouteSecretManagerRoute
'/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/integrations': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretManagementProjectIdSecretManagerLayoutIntegrationsRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/access-management': typeof projectAccessControlPageRouteSecretScanningRoute
+ '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/app-connections': typeof projectAppConnectionsPageRouteSecretScanningRoute
'/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/audit-logs': typeof projectAuditLogsPageRouteSecretScanningRoute
'/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources': typeof AuthenticateInjectOrgDetailsOrgLayoutProjectsSecretScanningProjectIdSecretScanningLayoutDataSourcesRouteWithChildren
'/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/access-management': typeof projectAccessControlPageRouteSshRoute
@@ -5302,11 +5423,13 @@ export interface FileRouteTypes {
| '/admin/integrations'
| '/organization/app-connections'
| '/organization/gateways'
+ | '/organization/relays'
| '/organization/secret-sharing'
| '/organization/settings'
| '/secret-manager/$projectId'
| '/organization/app-connections/'
| '/organization/gateways/'
+ | '/organization/relays/'
| '/organization/secret-sharing/'
| '/organization/settings/'
| '/organization/groups/$groupId'
@@ -5351,15 +5474,18 @@ export interface FileRouteTypes {
| '/projects/ssh/$projectId/overview'
| '/projects/ssh/$projectId/settings'
| '/projects/cert-management/$projectId/access-management'
+ | '/projects/cert-management/$projectId/app-connections'
| '/projects/cert-management/$projectId/audit-logs'
| '/projects/cert-management/$projectId/certificate-templates'
| '/projects/cert-management/$projectId/subscribers'
| '/projects/kms/$projectId/access-management'
| '/projects/kms/$projectId/audit-logs'
| '/projects/secret-management/$projectId/access-management'
+ | '/projects/secret-management/$projectId/app-connections'
| '/projects/secret-management/$projectId/audit-logs'
| '/projects/secret-management/$projectId/integrations'
| '/projects/secret-scanning/$projectId/access-management'
+ | '/projects/secret-scanning/$projectId/app-connections'
| '/projects/secret-scanning/$projectId/audit-logs'
| '/projects/secret-scanning/$projectId/data-sources'
| '/projects/ssh/$projectId/access-management'
@@ -5519,6 +5645,7 @@ export interface FileRouteTypes {
| '/secret-manager/$projectId'
| '/organization/app-connections'
| '/organization/gateways'
+ | '/organization/relays'
| '/organization/secret-sharing'
| '/organization/settings'
| '/organization/groups/$groupId'
@@ -5563,12 +5690,15 @@ export interface FileRouteTypes {
| '/projects/ssh/$projectId/overview'
| '/projects/ssh/$projectId/settings'
| '/projects/cert-management/$projectId/access-management'
+ | '/projects/cert-management/$projectId/app-connections'
| '/projects/cert-management/$projectId/audit-logs'
| '/projects/kms/$projectId/access-management'
| '/projects/kms/$projectId/audit-logs'
| '/projects/secret-management/$projectId/access-management'
+ | '/projects/secret-management/$projectId/app-connections'
| '/projects/secret-management/$projectId/audit-logs'
| '/projects/secret-scanning/$projectId/access-management'
+ | '/projects/secret-scanning/$projectId/app-connections'
| '/projects/secret-scanning/$projectId/audit-logs'
| '/projects/ssh/$projectId/access-management'
| '/projects/ssh/$projectId/audit-logs'
@@ -5733,11 +5863,13 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/admin/_admin-layout/integrations'
| '/_authenticate/_inject-org-details/_org-layout/organization/app-connections'
| '/_authenticate/_inject-org-details/_org-layout/organization/gateways'
+ | '/_authenticate/_inject-org-details/_org-layout/organization/relays'
| '/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing'
| '/_authenticate/_inject-org-details/_org-layout/organization/settings'
| '/_authenticate/_inject-org-details/_org-layout/secret-manager/$projectId'
| '/_authenticate/_inject-org-details/_org-layout/organization/app-connections/'
| '/_authenticate/_inject-org-details/_org-layout/organization/gateways/'
+ | '/_authenticate/_inject-org-details/_org-layout/organization/relays/'
| '/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing/'
| '/_authenticate/_inject-org-details/_org-layout/organization/settings/'
| '/_authenticate/_inject-org-details/_org-layout/organization/groups/$groupId'
@@ -5787,15 +5919,18 @@ export interface FileRouteTypes {
| '/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/overview'
| '/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/settings'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/access-management'
+ | '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificate-templates'
| '/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/subscribers'
| '/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/access-management'
| '/_authenticate/_inject-org-details/_org-layout/projects/kms/$projectId/_kms-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/access-management'
+ | '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/app-connections'
| '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/integrations'
| '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/access-management'
+ | '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/app-connections'
| '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/audit-logs'
| '/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources'
| '/_authenticate/_inject-org-details/_org-layout/projects/ssh/$projectId/_ssh-layout/access-management'
@@ -6156,6 +6291,7 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/organization/projects",
"/_authenticate/_inject-org-details/_org-layout/organization/app-connections",
"/_authenticate/_inject-org-details/_org-layout/organization/gateways",
+ "/_authenticate/_inject-org-details/_org-layout/organization/relays",
"/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing",
"/_authenticate/_inject-org-details/_org-layout/organization/settings",
"/_authenticate/_inject-org-details/_org-layout/organization/groups/$groupId",
@@ -6237,6 +6373,13 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/organization/gateways/"
]
},
+ "/_authenticate/_inject-org-details/_org-layout/organization/relays": {
+ "filePath": "",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organization",
+ "children": [
+ "/_authenticate/_inject-org-details/_org-layout/organization/relays/"
+ ]
+ },
"/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing": {
"filePath": "",
"parent": "/_authenticate/_inject-org-details/_org-layout/organization",
@@ -6268,6 +6411,10 @@ export const routeTree = rootRoute
"filePath": "organization/Gateways/GatewayListPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organization/gateways"
},
+ "/_authenticate/_inject-org-details/_org-layout/organization/relays/": {
+ "filePath": "organization/Gateways/Relay/RelayListPage/route.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/organization/relays"
+ },
"/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing/": {
"filePath": "organization/SecretSharingPage/route.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/organization/secret-sharing"
@@ -6388,6 +6535,7 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificates",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/settings",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/access-management",
+ "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/certificate-templates",
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/subscribers",
@@ -6424,6 +6572,7 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/secret-rotation",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/settings",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/access-management",
+ "/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/app-connections",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/audit-logs",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/integrations",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/secrets/$envSlug",
@@ -6441,6 +6590,7 @@ export const routeTree = rootRoute
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/findings",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/settings",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/access-management",
+ "/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/app-connections",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/audit-logs",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/data-sources",
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/groups/$groupId",
@@ -6547,6 +6697,10 @@ export const routeTree = rootRoute
"filePath": "project/AccessControlPage/route-cert-manager.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/app-connections": {
+ "filePath": "project/AppConnectionsPage/route-cert-manager.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout/audit-logs": {
"filePath": "project/AuditLogsPage/route-cert-manager.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/projects/cert-management/$projectId/_cert-manager-layout"
@@ -6578,6 +6732,10 @@ export const routeTree = rootRoute
"filePath": "project/AccessControlPage/route-secret-manager.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/app-connections": {
+ "filePath": "project/AppConnectionsPage/route-secret-manager.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout/audit-logs": {
"filePath": "project/AuditLogsPage/route-secret-manager.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/projects/secret-management/$projectId/_secret-manager-layout"
@@ -6670,6 +6828,10 @@ export const routeTree = rootRoute
"filePath": "project/AccessControlPage/route-secret-scanning.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout"
},
+ "/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/app-connections": {
+ "filePath": "project/AppConnectionsPage/route-secret-scanning.tsx",
+ "parent": "/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout"
+ },
"/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout/audit-logs": {
"filePath": "project/AuditLogsPage/route-secret-scanning.tsx",
"parent": "/_authenticate/_inject-org-details/_org-layout/projects/secret-scanning/$projectId/_secret-scanning-layout"
diff --git a/frontend/src/routes.ts b/frontend/src/routes.ts
index 70c34edc62..a81e9a619c 100644
--- a/frontend/src/routes.ts
+++ b/frontend/src/routes.ts
@@ -40,7 +40,8 @@ const organizationRoutes = route("/organization", [
"organization/AppConnections/OauthCallbackPage/route.tsx"
)
]),
- route("/gateways", [index("organization/Gateways/GatewayListPage/route.tsx")])
+ route("/gateways", [index("organization/Gateways/GatewayListPage/route.tsx")]),
+ route("/relays", [index("organization/Gateways/Relay/RelayListPage/route.tsx")])
]);
const secretManagerRoutes = route("/projects/secret-management/$projectId", [
@@ -63,6 +64,7 @@ const secretManagerRoutes = route("/projects/secret-management/$projectId", [
]),
route("/audit-logs", "project/AuditLogsPage/route-secret-manager.tsx"),
route("/access-management", "project/AccessControlPage/route-secret-manager.tsx"),
+ route("/app-connections", "project/AppConnectionsPage/route-secret-manager.tsx"),
route("/roles/$roleSlug", "project/RoleDetailsBySlugPage/route-secret-manager.tsx"),
route("/identities/$identityId", "project/IdentityDetailsByIDPage/route-secret-manager.tsx"),
route("/members/$membershipId", "project/MemberDetailsByIDPage/route-secret-manager.tsx"),
@@ -313,6 +315,7 @@ const certManagerRoutes = route("/projects/cert-management/$projectId", [
route("/settings", "cert-manager/SettingsPage/route.tsx"),
route("/audit-logs", "project/AuditLogsPage/route-cert-manager.tsx"),
route("/access-management", "project/AccessControlPage/route-cert-manager.tsx"),
+ route("/app-connections", "project/AppConnectionsPage/route-cert-manager.tsx"),
route("/roles/$roleSlug", "project/RoleDetailsBySlugPage/route-cert-manager.tsx"),
route("/identities/$identityId", "project/IdentityDetailsByIDPage/route-cert-manager.tsx"),
route("/members/$membershipId", "project/MemberDetailsByIDPage/route-cert-manager.tsx"),
@@ -361,6 +364,7 @@ const secretScanningRoutes = route("/projects/secret-scanning/$projectId", [
route("/settings", "secret-scanning/SettingsPage/route.tsx"),
route("/audit-logs", "project/AuditLogsPage/route-secret-scanning.tsx"),
route("/access-management", "project/AccessControlPage/route-secret-scanning.tsx"),
+ route("/app-connections", "project/AppConnectionsPage/route-secret-scanning.tsx"),
route("/roles/$roleSlug", "project/RoleDetailsBySlugPage/route-secret-scanning.tsx"),
route("/identities/$identityId", "project/IdentityDetailsByIDPage/route-secret-scanning.tsx"),
route("/members/$membershipId", "project/MemberDetailsByIDPage/route-secret-scanning.tsx"),
diff --git a/helm-charts/infisical-gateway/Chart.yaml b/helm-charts/infisical-gateway/Chart.yaml
index 2dc9ef7967..02966009cb 100644
--- a/helm-charts/infisical-gateway/Chart.yaml
+++ b/helm-charts/infisical-gateway/Chart.yaml
@@ -15,10 +15,10 @@ type: application
# This is the chart version. This version number should be incremented each time you make changes
# to the chart and its templates, including the app version.
# Versions are expected to follow Semantic Versioning (https://semver.org/)
-version: 1.0.0
+version: 1.0.1
# This is the version number of the application being deployed. This version number should be
# incremented each time you make changes to the application. Versions are not expected to
# follow Semantic Versioning. They should reflect the version the application is using.
# It is recommended to use it with quotes.
-appVersion: "1.0.0"
+appVersion: "1.0.1"
diff --git a/helm-charts/infisical-gateway/values.yaml b/helm-charts/infisical-gateway/values.yaml
index 67874055f4..c8ad11a29b 100644
--- a/helm-charts/infisical-gateway/values.yaml
+++ b/helm-charts/infisical-gateway/values.yaml
@@ -1,6 +1,6 @@
image:
pullPolicy: IfNotPresent
- tag: "0.42.0"
+ tag: "0.42.3"
secret:
# The secret that contains the environment variables to be used by the gateway, such as INFISICAL_API_URL and TOKEN