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
feat(db): add role-based access grants for analytics schema ## Context
Maidul Islam0c1487749447
diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 8852bf7183..95ea48a179 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -33,7 +33,7 @@"@fastify/swagger-ui": "^3.1.0","@gitbeaker/rest": "^42.5.0","@google-cloud/kms": "^4.5.0",- "@infisical/pg-view-generator": "^1.0.0",+ "@infisical/pg-view-generator": "^1.1.0","@infisical/quic": "^1.0.8","@modelcontextprotocol/sdk": "^1.24.3","@node-saml/passport-saml": "^5.1.0",@@ -12660,9 +12660,9 @@}},"node_modules/@infisical/pg-view-generator": {- "version": "1.0.0",- "resolved": "https://registry.npmjs.org/@infisical/pg-view-generator/-/pg-view-generator-1.0.0.tgz",- "integrity": "sha512-PlA5vujGtwx0KFhNqSUB8b9t9bn9ggpWdM2/qkFL85eDx86Mfmr6P76bBdfEHpjbddVO3+n1Ad5QDp/YB+1Nyg==",+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/@infisical/pg-view-generator/-/pg-view-generator-1.1.0.tgz",+ "integrity": "sha512-HHcCavCmZrWokGU6BxiXPOqLkUnPUpKP9xUyUz+Khtv3SNsPj5jlqgc5vki0pAU4sj3JbMhecF0K7e83Hp9S4g==","license": "MIT","dependencies": {"js-yaml": "^4.1.0"diff --git a/backend/package.json b/backend/package.jsonindex 8bb1f007b0..2b158d1f86 100644--- a/backend/package.json+++ b/backend/package.json@@ -145,7 +145,7 @@"@fastify/swagger-ui": "^3.1.0","@gitbeaker/rest": "^42.5.0","@google-cloud/kms": "^4.5.0",- "@infisical/pg-view-generator": "^1.0.0",+ "@infisical/pg-view-generator": "^1.1.0","@infisical/quic": "^1.0.8","@modelcontextprotocol/sdk": "^1.24.3","@node-saml/passport-saml": "^5.1.0",diff --git a/backend/src/auto-start-migrations.ts b/backend/src/auto-start-migrations.tsindex f531dbdc4a..ccfeed67ec 100644--- a/backend/src/auto-start-migrations.ts+++ b/backend/src/auto-start-migrations.ts@@ -8,7 +8,12 @@ import { Logger } from "pino";import { applyJitter, delay } from "@app/lib/delay";-import { acquireSanitizedSchemaLock, createSanitizedSchema, dropSanitizedSchema } from "./db/sanitized-schema";+import {+ acquireSanitizedSchemaLock,+ createSanitizedSchema,+ dropSanitizedSchema,+ grantSanitizedSchemaAccess+} from "./db/sanitized-schema";import { PgSqlLock } from "./keystore/keystore";const SANITIZED_SCHEMA_ERROR = "SANITIZED_SCHEMA_ERROR";@@ -322,19 +327,23 @@ export const runMigrations = async ({ applicationDb, auditLogDb, logger }: TArgslogger.info("No migrations pending: Skipping migration process.");if (generateSanitizedSchema) {+ const sanitizedSchemaRole = process.env.SANITIZED_SCHEMA_ROLE;try {await applicationDb.transaction(async (tx) => {const isLocked = await acquireSanitizedSchemaLock({ db: tx, logger });if (isLocked) {await dropSanitizedSchema({ db: tx, logger });await createSanitizedSchema({ db: tx, logger });+ if (sanitizedSchemaRole) {+ await grantSanitizedSchemaAccess({ db: tx, logger, role: sanitizedSchemaRole });+ }logger.info("Finished sanitized schema generation.");}});} catch (err) {logger.error(- { err, errorId: SANITIZED_SCHEMA_ERROR, phase: "drop" },- `${SANITIZED_SCHEMA_ERROR}: Failed to drop and recreate sanitized schema`+ { err, errorId: SANITIZED_SCHEMA_ERROR, phase: "recreate" },+ `${SANITIZED_SCHEMA_ERROR}: Failed to recreate sanitized schema`);}}@@ -370,6 +379,7 @@ export const runMigrations = async ({ applicationDb, auditLogDb, logger }: TArgs}// Use startup lock to ensure only one instance runs migrations at a time+ // Workflow: drop views → run migrations → recreate views → grant accessawait withStartupLock(applicationDb, logger, async () => {if (generateSanitizedSchema) await dropSanitizedSchema({ db: applicationDb, logger });await applicationDb.migrate.latest(migrationConfig);@@ -378,8 +388,12 @@ export const runMigrations = async ({ applicationDb, auditLogDb, logger }: TArgs// we create the sanitized schema after migrations to avoid conflicts with the migrationsif (generateSanitizedSchema) {+ const sanitizedSchemaRole = process.env.SANITIZED_SCHEMA_ROLE;try {await createSanitizedSchema({ db: applicationDb, logger });+ if (sanitizedSchemaRole) {+ await grantSanitizedSchemaAccess({ db: applicationDb, logger, role: sanitizedSchemaRole });+ }logger.info("Finished sanitized schema generation.");} catch (err) {logger.error(diff --git a/backend/src/db/sanitized-schema.ts b/backend/src/db/sanitized-schema.tsindex f6373c2ea1..c16483cbde 100644--- a/backend/src/db/sanitized-schema.ts+++ b/backend/src/db/sanitized-schema.ts@@ -4,7 +4,7 @@ import { Logger } from "pino";import { PgSqlLock } from "@app/keystore/keystore";-const SANITIZED_SCHEMA = "infisical-sanitized";+const SANITIZED_SCHEMA = "analytics";type TArgs = {db: Knex;@@ -65,3 +65,16 @@ export const createSanitizedSchema = async ({ db, logger }: TArgs): Promise<voidawait db.raw(sql);logger.info("Created sanitized schema and views");};++type TGrantArgs = TArgs & {+ role: string;+};++export const grantSanitizedSchemaAccess = async ({ db, logger, role }: TGrantArgs): Promise<void> => {+ // eslint-disable-next-line import/no-extraneous-dependencies+ const { generateGrantReadAccessSQL } = await import("@infisical/pg-view-generator");++ const sql = generateGrantReadAccessSQL(SANITIZED_SCHEMA, role);+ await db.raw(sql);+ logger.info(`Granted read access on sanitized schema to role: ${role}`);+};diff --git a/backend/src/db/sanitized-schema.yaml b/backend/src/db/sanitized-schema.yamlindex 5ce2e40127..47fb817bd9 100644--- a/backend/src/db/sanitized-schema.yaml+++ b/backend/src/db/sanitized-schema.yaml@@ -1358,3 +1358,20 @@ tables:- envId- type- url+ - name: audit_logs+ source: public.audit_logs+ columns:+ - id+ - actor+ - actorMetadata+ - ipAddress+ - eventType+ - eventMetadata+ - userAgent+ - userAgentType+ - expiresAt+ - createdAt+ - updatedAt+ - orgId+ - projectId+ - projectNamediff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex 1ee8032e3c..1dc00cefb2 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -89,6 +89,9 @@ const envSchema = zGENERATE_SANITIZED_SCHEMA: zodStrBool.default("false").describe("Generate sanitized schema with views after migrations"),+ SANITIZED_SCHEMA_ROLE: zpStr(+ z.string().describe("PostgreSQL role to grant read access to the sanitized schema").optional()+ ),MAX_LEASE_LIMIT: z.coerce.number().default(10000),DB_ROOT_CERT: zpStr(z.string().describe("Postgres database base64-encoded CA cert").optional()),DB_HOST: zpStr(z.string().describe("Postgres database host").optional()),