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
add index for revokation
Thiago Araujo da Silva94e7f136d226
diff --git a/backend/src/db/migrations/20260822120000_add-auth-token-session-lookup-indexes.ts b/backend/src/db/migrations/20260822120000_add-auth-token-session-lookup-indexes.tsnew file mode 100644index 0000000000..f451fd57dd--- /dev/null+++ b/backend/src/db/migrations/20260822120000_add-auth-token-session-lookup-indexes.ts@@ -0,0 +1,80 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++// auth_token_sessions carries a row per user session, so it is one of the largest tables on an+// instance, and until now the primary key was its only index. Every lookup keyed on `id` rides that+// PK (session validation on each authenticated request, refresh rotation, revoking one session), but+// three filter shapes had nothing to use and seq-scanned the whole table:+//+// {userAgent} revokeSessionsByUserAgent, the only handle OAuth client revocation has+// on the tokens a client issued. Two of its callers run inside a+// transaction, so the scan also held a pooled connection for its duration.+// {userId, ip, userAgent} getUserTokenSession, on every login and every RFC 8693 token exchange.+// {userId} listing a user's sessions, and revoking all of them.+//+// The second index covers both of the userId shapes: the three-column lookup uses all of it, and the+// userId-only lookups use its leftmost column. userAgent trails rather than leads it so that the+// userAgent-only delete keeps its own tighter single-column index, which measured consistently faster+// for that query than sharing a userAgent-leading composite.+const USER_AGENT_INDEX = "idx_auth_token_sessions_user_agent";+const USER_SESSION_INDEX = "idx_auth_token_sessions_user_id_ip_user_agent";+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds++export async function up(knex: Knex): Promise<void> {+ // statement_timeout / lock_timeout are session-local, so every statement here has to run on the+ // same pooled connection as the CREATE INDEX CONCURRENTLY calls they are meant to govern.+ const connection = await knex.client.acquireConnection();+ const raw = (sql: string) => knex.raw(sql).connection(connection);++ // A cancelled or failed CREATE INDEX CONCURRENTLY leaves behind an INVALID index that+ // IF NOT EXISTS would happily skip over, so drop it before retrying.+ const dropIfInvalid = async (indexName: string) => {+ const invalid = await raw(+ `SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid WHERE c.relname = '${indexName}' AND NOT i.indisvalid`+ );+ if (invalid.rows.length > 0) {+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${indexName}"`);+ }+ };++ try {+ const stmtResult = await raw("SHOW statement_timeout");+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;+ const lockResult = await raw("SHOW lock_timeout");+ const originalLockTimeout = lockResult.rows[0].lock_timeout;++ try {+ await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);+ await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);++ if (await knex.schema.hasColumn(TableName.AuthTokenSession, "userAgent")) {+ await dropIfInvalid(USER_AGENT_INDEX);+ await raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${USER_AGENT_INDEX}"+ ON ${TableName.AuthTokenSession} ("userAgent")+ `);++ await dropIfInvalid(USER_SESSION_INDEX);+ await raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${USER_SESSION_INDEX}"+ ON ${TableName.AuthTokenSession} ("userId", "ip", "userAgent")+ `);+ }+ } finally {+ await raw(`SET statement_timeout = '${originalStatementTimeout}'`);+ await raw(`SET lock_timeout = '${originalLockTimeout}'`);+ }+ } finally {+ await knex.client.releaseConnection(connection);+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${USER_AGENT_INDEX}"`);+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${USER_SESSION_INDEX}"`);+}++const config = { transaction: false };+export { config };diff --git a/backend/src/server/routes/v1/oauth-router.ts b/backend/src/server/routes/v1/oauth-router.tsindex e7f5d317c9..a81a5287f3 100644--- a/backend/src/server/routes/v1/oauth-router.ts+++ b/backend/src/server/routes/v1/oauth-router.ts@@ -106,12 +106,6 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {},schema: {operationId: "listOauthClients",- querystring: z.object({- grantType: z- .nativeEnum(OauthGrantType)- .optional()- .describe("Return only applications registered for this grant type.")- }),response: {200: z.object({clients: SanitizedOauthClientSchema.array()@@ -120,7 +114,7 @@ export const registerOAuthRouter = async (server: FastifyZodProvider) => {},onRequest: verifyAuth([AuthMode.JWT]),handler: async (req) => {- const clients = await server.services.oauthClient.listOauthClients(req.permission, req.query.grantType);+ const clients = await server.services.oauthClient.listOauthClients(req.permission);return { clients };}});diff --git a/backend/src/services/oauth-client/oauth-client-service.ts b/backend/src/services/oauth-client/oauth-client-service.tsindex 5a76c12fa0..8e0e4cdcb3 100644--- a/backend/src/services/oauth-client/oauth-client-service.ts+++ b/backend/src/services/oauth-client/oauth-client-service.ts@@ -323,14 +323,12 @@ export const oauthClientServiceFactory = ({return { client: sanitizeOauthClient(client), clientSecret };};- // The SSO page passes `grantType` to show which applications depend on the org's OIDC issuer.- const listOauthClients = async (actor: OrgServiceActor, grantType?: OauthGrantType) => {+ const listOauthClients = async (actor: OrgServiceActor) => {await checkOauthClientPermission(actor, OrgPermissionActions.Read);const clients = await oauthClientDAL.find({ orgId: actor.orgId });- const filtered = grantType ? clients.filter((client) => getGrantTypes(client).includes(grantType)) : clients;- return filtered.map(sanitizeOauthClient);+ return clients.map(sanitizeOauthClient);};const getOauthClientById = async (clientDbId: string, actor: OrgServiceActor) => {diff --git a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txtindex 18f5ad62c4..419c87e193 100644--- a/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt+++ b/docs/.vale/styles/config/vocabularies/Infisical/any-case/accept.txt@@ -151,6 +151,8 @@ I(?i)liveness(?i)lookups(?i)loopback+(?i)middleware+(?i)middleware's(?i)misconfiguration(?i)misconfigurations(?i)misconfigured@@ -181,6 +183,7 @@ I(?i)reachability(?i)redeployment(?i)redeployments+(?i)replayable(?i)repo(?i)repos(?i)requesterdiff --git a/frontend/src/hooks/api/oauthClients/mutations.tsx b/frontend/src/hooks/api/oauthClients/mutations.tsxindex e25f2792c8..335f399c5f 100644--- a/frontend/src/hooks/api/oauthClients/mutations.tsx+++ b/frontend/src/hooks/api/oauthClients/mutations.tsx@@ -24,7 +24,7 @@ export const useCreateOauthClient = () => {},onSuccess: ({ client }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.allLists(client.orgId)+ queryKey: oauthClientKeys.list(client.orgId)});}});@@ -42,7 +42,7 @@ export const useUpdateOauthClient = () => {},onSuccess: ({ orgId }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.allLists(orgId)+ queryKey: oauthClientKeys.list(orgId)});}});@@ -59,7 +59,7 @@ export const useDeleteOauthClient = () => {},onSuccess: ({ orgId }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.allLists(orgId)+ queryKey: oauthClientKeys.list(orgId)});}});@@ -76,7 +76,7 @@ export const useRotateOauthClientSecret = () => {},onSuccess: ({ client }) => {queryClient.invalidateQueries({- queryKey: oauthClientKeys.allLists(client.orgId)+ queryKey: oauthClientKeys.list(client.orgId)});}});diff --git a/frontend/src/hooks/api/oauthClients/queries.tsx b/frontend/src/hooks/api/oauthClients/queries.tsxindex b540e8a467..07b268b839 100644--- a/frontend/src/hooks/api/oauthClients/queries.tsx+++ b/frontend/src/hooks/api/oauthClients/queries.tsx@@ -2,24 +2,19 @@ import { useQuery } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";-import { OauthGrantType, TOauthAuthorizeInfo, TOauthClient } from "./types";+import { TOauthAuthorizeInfo, TOauthClient } from "./types";export const oauthClientKeys = {- allLists: (orgId: string) => [{ orgId }, "oauth-clients"] as const,- list: (orgId: string, grantType?: OauthGrantType) =>- [...oauthClientKeys.allLists(orgId), grantType ?? ""] as const,+ list: (orgId: string) => [{ orgId }, "oauth-clients"] as const,authorizeInfo: (clientId: string, redirectUri: string, scope?: string) =>["oauth-authorize-info", clientId, redirectUri, scope ?? ""] as const};-// The SSO page passes `grantType` to show which applications depend on the org's OIDC issuer.-export const useGetOauthClients = (orgId: string, grantType?: OauthGrantType) => {+export const useGetOauthClients = (orgId: string) => {return useQuery({- queryKey: oauthClientKeys.list(orgId, grantType),+ queryKey: oauthClientKeys.list(orgId),queryFn: async () => {- const { data } = await apiRequest.get<{ clients: TOauthClient[] }>("/api/v1/oauth/clients", {- params: grantType ? { grantType } : undefined- });+ const { data } = await apiRequest.get<{ clients: TOauthClient[] }>("/api/v1/oauth/clients");return data.clients;},enabled: Boolean(orgId)