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
import { IdentityAuthMethod, TableName } from "@app/db/schemas";
import { identityCredentialAlertDALFactory } from "./identity-credential-alert-dal";
// Records the query builder calls so we can assert which identities a scan is allowed to return.
// This is the enforcement point for the permission boundary of a project-owned identity: an
// org-scoped alert only ever checks org-level identity permission, so it must never surface the
// credential metadata of an identity whose reads are gated by a project (see
// getUniversalAuthClientSecrets in identity-ua-service).
const buildDAL = () => {
const calls = {
join: [] as unknown[][],
where: [] as unknown[][],
whereNull: [] as unknown[],
whereRaw: [] as unknown[][],
// Calls made inside a `.where((builder) => ...)` group.
groupedWhereNull: [] as unknown[],
groupedOrWhere: [] as unknown[][],
// Calls made on the subquery passed to `.whereNotExists(...)`.
notExists: [] as { from: unknown; whereRaw: unknown[][] }[]
};
const group = {
whereNull: (col: unknown) => {
calls.groupedWhereNull.push(col);
return group;
},
orWhere: (...args: unknown[]) => {
calls.groupedOrWhere.push(args);
return group;
}
};
const chain = {
join: (...args: unknown[]) => {
calls.join.push(args);
return chain;
},
where: (...args: unknown[]) => {
if (typeof args[0] === "function") {
(args[0] as (builder: typeof group) => void)(group);
return chain;
}
calls.where.push(args);
return chain;
},
whereNull: (col: unknown) => {
calls.whereNull.push(col);
return chain;
},
whereRaw: (...args: unknown[]) => {
calls.whereRaw.push(args);
return chain;
},
whereNotExists: (cb: (sub: unknown) => void) => {
const entry = { from: undefined as unknown, whereRaw: [] as unknown[][] };
const sub = {
select: () => sub,
from: (table: unknown) => {
entry.from = table;
return sub;
},
whereRaw: (...args: unknown[]) => {
entry.whereRaw.push(args);
return sub;
}
};
cb(sub);
calls.notExists.push(entry);
return chain;
},
orderByRaw: () => chain,
select: async () => []
};
const db = {
replicaNode: () => () => chain,
ref: (col: string) => ({ withSchema: () => ({ as: () => col }) }),
raw: (sql: string) => sql
} as never;
return { dal: identityCredentialAlertDALFactory(db), calls };
};
const scanArgs = {
orgId: "org-1",
alertBeforeInterval: "30 days",
leadInterval: "1 day",
asOf: new Date("2026-01-01T00:00:00Z")
};
describe("identity credential alert dal", () => {
test("an org-scoped scan excludes project-owned identities", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringUaClientSecrets(scanArgs);
expect(calls.whereNull).toContainEqual(`${TableName.Identity}.projectId`);
// No project membership join: the scan spans the whole org.
expect(calls.where.some((args) => args[0] === "projectMembership.scope")).toBe(false);
});
test("a scan only returns identities the alert's organization owns", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringUaClientSecrets(scanArgs);
// Org membership alone is not enough: a root-org identity added to a sub-organization is a
// member there, but the sub-organization cannot see its credentials, so an org-wide alert in
// the sub-organization must not surface them.
expect(calls.where).toContainEqual([`${TableName.Membership}.scopeOrgId`, "org-1"]);
expect(calls.where).toContainEqual([`${TableName.Identity}.orgId`, "org-1"]);
});
test("every bound `asOf` timestamp is explicitly cast", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringUaClientSecrets(scanArgs);
// An untyped bind on the left of `+ interval` makes Postgres resolve the operator to
// `interval + interval`, so the whole predicate fails to type-check at parse time and the scan
// throws instead of returning targets.
const asOfBindings = calls.whereRaw.filter((args) =>
((args[1] as unknown[]) ?? []).some((binding) => binding instanceof Date)
);
expect(asOfBindings.length).toBeGreaterThan(0);
asOfBindings.forEach(([sql]) => {
expect(sql).toContain("?::timestamptz");
});
});
test("the expiry expression clamps clientSecretTTL into a range interval arithmetic can hold", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringUaClientSecrets(scanArgs);
// Under a hash-join plan this predicate is a scan-level filter on the whole table, evaluated
// before the identity/org joins narrow it. An unclamped `clientSecretTTL * interval '1 second'`
// therefore overflows on any other tenant's out-of-range row and aborts the entire scan.
const expirySql = calls.whereRaw.map(([sql]) => sql as string).filter((sql) => sql.includes("clientSecretTTL"));
expect(expirySql.length).toBeGreaterThan(0);
expirySql.forEach((sql) => {
expect(sql).toContain(`LEAST(GREATEST(${TableName.IdentityUaClientSecret}."clientSecretTTL", 0), 315360000)`);
expect(sql).not.toContain("* interval '1 second'");
});
});
test("a project-scoped scan keeps org-level identities but only its own project's identities", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringUaClientSecrets({ ...scanArgs, projectId: "proj-1" });
expect(calls.where).toContainEqual(["projectMembership.scopeProjectId", "proj-1"]);
// Membership in the project is not sufficient on its own: an identity owned by another project
// stays out even when it has been shared into this one.
expect(calls.groupedWhereNull).toContainEqual(`${TableName.Identity}.projectId`);
expect(calls.groupedOrWhere).toContainEqual([`${TableName.Identity}.projectId`, "proj-1"]);
expect(calls.whereNull).not.toContainEqual(`${TableName.Identity}.projectId`);
});
test("a Token Auth scan only considers live Token Auth tokens", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringTokenAuthTokens(scanArgs);
expect(calls.where).toContainEqual([`${TableName.IdentityAccessToken}.authMethod`, IdentityAuthMethod.TOKEN_AUTH]);
expect(calls.where).toContainEqual([`${TableName.IdentityAccessToken}.isAccessTokenRevoked`, false]);
expect(calls.where).toContainEqual([`${TableName.IdentityAccessToken}.accessTokenTTL`, ">", 0]);
});
test("a Token Auth scan skips tokens revoked through a per-token revocation marker", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringTokenAuthTokens(scanArgs);
// POST /auth/token/revoke only writes the marker and leaves isAccessTokenRevoked false, so the
// flag alone would keep alerting on a token nobody can use until it expires.
expect(calls.notExists).toContainEqual({
from: TableName.IdentityAccessTokenRevocation,
whereRaw: [
["?? = ??::uuid", [`${TableName.IdentityAccessTokenRevocation}.id`, `${TableName.IdentityAccessToken}.id`]]
]
});
});
test("a Token Auth token expires at its creation time plus its clamped stored TTL, not its max TTL", async () => {
const { dal, calls } = buildDAL();
await dal.findExpiringTokenAuthTokens(scanArgs);
const expirySql = calls.whereRaw.map(([sql]) => sql as string).filter((sql) => sql.includes("make_interval"));
expect(expirySql.length).toBeGreaterThan(0);
expirySql.forEach((sql) => {
expect(sql).toContain(`${TableName.IdentityAccessToken}."createdAt"`);
expect(sql).toContain(`LEAST(GREATEST(${TableName.IdentityAccessToken}."accessTokenTTL", 0), 315360000)`);
expect(sql).not.toContain('"accessTokenMaxTTL"');
expect(sql).toContain("?::timestamptz");
});
});
test("a Token Auth scan applies the same identity visibility rules as the client secret scan", async () => {
const orgScan = buildDAL();
await orgScan.dal.findExpiringTokenAuthTokens(scanArgs);
expect(orgScan.calls.where).toContainEqual([`${TableName.Membership}.scopeOrgId`, "org-1"]);
expect(orgScan.calls.where).toContainEqual([`${TableName.Identity}.orgId`, "org-1"]);
expect(orgScan.calls.whereNull).toContainEqual(`${TableName.Identity}.projectId`);
const projectScan = buildDAL();
await projectScan.dal.findExpiringTokenAuthTokens({ ...scanArgs, projectId: "proj-1", identityId: "ident-1" });
expect(projectScan.calls.where).toContainEqual(["projectMembership.scopeProjectId", "proj-1"]);
expect(projectScan.calls.groupedOrWhere).toContainEqual([`${TableName.Identity}.projectId`, "proj-1"]);
expect(projectScan.calls.where).toContainEqual([`${TableName.IdentityAccessToken}.identityId`, "ident-1"]);
});
});