Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(agent-vault): tell a deleted service from a deleted variable on save
Scott Wilsone34706558396
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 8b12d460ac..19e3fb63aa 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -1370,6 +1370,40 @@ describe("Agent Vault V1 Router", async () => {expect(resolved?.credential).toEqual({ type: "basic", username: "second-user", password: "the-pass" });});+ test("an update whose service is deleted while it waits is a 404, not a deleted variable", async () => {+ const bundle = await createAccessBundle("variables-deleted-service");+ const created = await inject("POST", servicesUrl(bundle.id), {+ name: "doomed",+ hostPattern: "doomed.example.com",+ credential: { type: "passthrough" }+ });+ expect(created.statusCode).toBe(200);+ const { service } = JSON.parse(created.payload) as { service: { id: string } };+ const url = `${servicesUrl(bundle.id)}/${service.id}`;++ // The update reads the service, then waits on the bundle lock, which a delete doesn't take.+ const trx = await testDb.transaction();+ try {+ const { rows } = await trx.raw("select pg_backend_pid() as pid");+ await trx("agent_vault_access_bundles").where({ id: bundle.id }).forUpdate().first();++ const pending = inject("PATCH", url, {+ substitutions: [{ placeholder: "__ORG__", surfaces: ["header"], value: "org-42" }]+ });+ await waitUntilBlockedBy(rows[0].pid);++ expect((await inject("DELETE", url)).statusCode).toBe(200);+ await trx.commit();++ const refused = await pending;+ expect(refused.statusCode).toBe(404);+ expect(JSON.parse(refused.payload).message).toBe(`Service with ID '${service.id}' not found`);+ } catch (err) {+ if (!trx.isCompleted()) await trx.rollback();+ throw err;+ }+ });+test("deleting a bundle takes its variables and every reference to them", async () => {const bundle = await createAccessBundle("variables-bundle-delete");const variable = await createVariable(bundle.id, { key: "TOKEN", value: "t" });diff --git a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex df377fbf9e..55ca2f3eec 100644--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts@@ -21,7 +21,7 @@ import {} from "@app/ee/services/permission/project-permission";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";-import { hasPostgresErrorCode } from "@app/lib/errors/postgres";+import { hasPostgresConstraintViolation, hasPostgresErrorCode } from "@app/lib/errors/postgres";import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";@@ -559,6 +559,10 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundconst VARIABLE_DELETED_DURING_SAVE_MESSAGE ="A variable this service uses was deleted while it was being saved. Check its variable references and save again.";+ // Every other foreign key a save can trip names a row the save wrote itself or, on update, the service, which+ // a delete removes without taking the bundle lock. So only this one means a variable went away.+ const VARIABLE_REFERENCE_VARIABLE_FOREIGN_KEY = "agent_vault_service_variable_references_variableid_foreign";+const CREDENTIAL_CHANGED_DURING_SAVE_MESSAGE ="This service's credential was changed by another save while this one was in progress. Reload the service and save again.";@@ -907,7 +911,13 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundif (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });}- if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {+ if (+ hasPostgresConstraintViolation(+ err,+ DatabaseErrorCode.ForeignKeyViolation,+ VARIABLE_REFERENCE_VARIABLE_FOREIGN_KEY+ )+ ) {throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });}throw err;@@ -1240,9 +1250,18 @@ export const agentVaultAccessBundleServiceFactory = (deps: TAgentVaultAccessBundif (isUniqueViolation(err)) {throw new BadRequestError({ message: `A service named '${name}' already exists in this access bundle` });}- if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {+ if (+ hasPostgresConstraintViolation(+ err,+ DatabaseErrorCode.ForeignKeyViolation,+ VARIABLE_REFERENCE_VARIABLE_FOREIGN_KEY+ )+ ) {throw new BadRequestError({ message: VARIABLE_DELETED_DURING_SAVE_MESSAGE });}+ if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {+ throw new NotFoundError({ message: `Service with ID '${serviceId}' not found` });+ }throw err;}diff --git a/backend/src/lib/errors/postgres.test.ts b/backend/src/lib/errors/postgres.test.tsnew file mode 100644index 0000000000..742e4faee8--- /dev/null+++ b/backend/src/lib/errors/postgres.test.ts@@ -0,0 +1,43 @@+import { DatabaseErrorCode } from "@app/lib/error-codes";++import { DatabaseError } from "./index";+import { hasPostgresConstraintViolation, hasPostgresErrorCode } from "./postgres";++describe("hasPostgresConstraintViolation", () => {+ const foreignKeyViolation = (constraint: string) =>+ new DatabaseError({+ name: "Insert rows",+ error: Object.assign(new Error("violates foreign key constraint"), {+ code: DatabaseErrorCode.ForeignKeyViolation,+ constraint+ })+ });++ test("finds the constraint under the DatabaseError a DAL wraps the driver error in", () => {+ const err = foreignKeyViolation("orders_customerid_foreign");+ expect(hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)).toBe(true);+ expect(+ hasPostgresConstraintViolation(err, DatabaseErrorCode.ForeignKeyViolation, "orders_customerid_foreign")+ ).toBe(true);+ });++ test("tells one foreign key from another", () => {+ expect(+ hasPostgresConstraintViolation(+ foreignKeyViolation("orders_customerid_foreign"),+ DatabaseErrorCode.ForeignKeyViolation,+ "orders_productid_foreign"+ )+ ).toBe(false);+ });++ test("matches only under the code asked for", () => {+ expect(+ hasPostgresConstraintViolation(+ foreignKeyViolation("orders_customerid_foreign"),+ DatabaseErrorCode.UniqueViolation,+ "orders_customerid_foreign"+ )+ ).toBe(false);+ });+});diff --git a/backend/src/lib/errors/postgres.ts b/backend/src/lib/errors/postgres.tsindex 46a9e71b5a..efcb5bc34a 100644--- a/backend/src/lib/errors/postgres.ts+++ b/backend/src/lib/errors/postgres.ts@@ -17,21 +17,36 @@ const MAX_CAUSE_DEPTH = 5;* DALs wrap the driver error in a `DatabaseError` (sometimes more than one layer deep), so the pg* error code is never on the outermost error.*/-export const hasPostgresErrorCode = (err: unknown, code: PostgresErrorCode | DatabaseErrorCode): boolean => {+const findPostgresError = (+ err: unknown,+ code: PostgresErrorCode | DatabaseErrorCode+): { code: string; constraint?: unknown } | undefined => {let current = err;for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth += 1) {- if (typeof current !== "object" || current === null) return false;+ if (typeof current !== "object" || current === null) return undefined;- if ("code" in current && (current as { code?: unknown }).code === code) return true;+ if ("code" in current && (current as { code?: unknown }).code === code) {+ return current as { code: string; constraint?: unknown };+ }const next =("error" in current && (current as { error?: unknown }).error) ||("cause" in current && (current as { cause?: unknown }).cause);- if (!next || next === current) return false;+ if (!next || next === current) return undefined;current = next;}- return false;+ return undefined;};++export const hasPostgresErrorCode = (err: unknown, code: PostgresErrorCode | DatabaseErrorCode): boolean =>+ Boolean(findPostgresError(err, code));++/** For a transaction that can trip more than one constraint of a kind, where the code alone can't say which. */+export const hasPostgresConstraintViolation = (+ err: unknown,+ code: PostgresErrorCode | DatabaseErrorCode,+ constraint: string+): boolean => findPostgresError(err, code)?.constraint === constraint;