Skip to content

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

batch token deletion/insertion on daily job

Thiago Araujo da Silva97e06ce0b71b
diff --git a/backend/src/services/auth-token/auth-token-dal.ts b/backend/src/services/auth-token/auth-token-dal.ts
index 65b5fba827..30f71f1fb8 100644
--- a/backend/src/services/auth-token/auth-token-dal.ts
+++ b/backend/src/services/auth-token/auth-token-dal.ts
@@ -37,6 +37,26 @@ export const tokenDALFactory = (db: TDbClient) => {
}
};
+ // Bulk-deletes tokens for many (type, userId, orgId) tuples in a single query.
+ // Used to refresh a batch of tokens without opening one transaction per user.
+ // Note: tuples with a null orgId are not matched (composite IN ignores NULL rows).
+ const deleteTokensForUsers = async (
+ tuples: { type: string; userId: string; orgId: string }[],
+ tx?: Knex
+ ): Promise<void> => {
+ if (!tuples.length) return;
+ try {
+ await (tx || db)(TableName.AuthTokens)
+ .whereIn(
+ ["type", "userId", "orgId"],
+ tuples.map(({ type, userId, orgId }) => [type, userId, orgId])
+ )
+ .delete();
+ } catch (error) {
+ throw new DatabaseError({ error, name: "DeleteTokensForUsers" });
+ }
+ };
+
const decrementTriesField = async ({ userId, type }: TDeleteTokenForUserDALDTO): Promise<void> => {
try {
await db(TableName.AuthTokens).where({ userId, type }).decrement("triesLeft", 1);
@@ -126,6 +146,7 @@ export const tokenDALFactory = (db: TDbClient) => {
...authOrm,
findTokenSessions,
deleteTokenForUser,
+ deleteTokensForUsers,
decrementTriesField,
findOneTokenSession,
insertTokenSession,
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index 1449687746..50253279be 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -5,6 +5,7 @@ import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, ForbiddenRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
+import { chunkArray } from "@app/lib/fn/array";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
@@ -15,6 +16,7 @@ import { TUserDALFactory } from "../user/user-dal";
import { TTokenDALFactory } from "./auth-token-dal";
import {
TCreateTokenForUserDTO,
+ TCreateTokensForUsersResult,
TEmailSignupOtpPayload,
TIssueAuthTokenDTO,
TokenType,
@@ -40,6 +42,10 @@ type TAuthTokenServiceFactoryDep = {
export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
+// Per-chunk size for createTokensForUsers. Each insert row binds ~5 values, so a chunk
+// of this size stays well under Postgres's ~65k bind-parameter limit for a single statement.
+const CREATE_TOKENS_CHUNK_SIZE = 1000;
+
const generateSixDigitToken = (): string => String(crypto.randomInt(10 ** 5, 10 ** 6 - 1));
const generateRandomHex = (size: number): string => crypto.randomBytes(size).toString("hex");
@@ -136,6 +142,63 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
return token;
};
+ /**
+ * Batched variant of createTokenForUser: refreshes tokens for many users using
+ * bulk deletes/inserts (one transaction per chunk) instead of one transaction per
+ * user. This avoids exhausting the connection pool when called for a large set of
+ * users (e.g. the daily invited-user reminder job).
+ *
+ * Work is processed in chunks so a single multi-row INSERT / composite IN can't grow
+ * past Postgres's bind-parameter ceiling, and chunks run sequentially so pool usage
+ * stays at one connection at a time. Token hashing is CPU-bound and does not hold a
+ * DB connection, so it runs up front per chunk in parallel. Each entry must include
+ * an orgId.
+ */
+ const createTokensForUsers = async (
+ entries: (TCreateTokenForUserDTO & { orgId: string })[]
+ ): Promise<TCreateTokensForUsersResult> => {
+ if (!entries.length) return [];
+ const appCfg = getConfig();
+
+ const result: TCreateTokensForUsersResult = [];
+
+ for (const chunk of chunkArray(entries, CREATE_TOKENS_CHUNK_SIZE)) {
+ // eslint-disable-next-line no-await-in-loop
+ const prepared = await Promise.all(
+ chunk.map(async (entry) => {
+ const { token, ...tkCfg } = getTokenConfig(entry.type);
+ const tokenHash = await crypto.hashing().createHash(token, appCfg.SALT_ROUNDS);
+ return { entry, token, tokenHash, tkCfg };
+ })
+ );
+
+ // eslint-disable-next-line no-await-in-loop
+ await tokenDAL.transaction(async (tx) => {
+ await tokenDAL.deleteTokensForUsers(
+ prepared.map(({ entry }) => ({ type: entry.type, userId: entry.userId, orgId: entry.orgId })),
+ tx
+ );
+ await tokenDAL.insertMany(
+ prepared.map(({ entry, tokenHash, tkCfg }) => ({
+ tokenHash,
+ expiresAt: tkCfg.expiresAt,
+ type: entry.type,
+ userId: entry.userId,
+ orgId: entry.orgId,
+ triesLeft: tkCfg?.triesLeft,
+ aliasId: entry.aliasId,
+ payload: entry.payload
+ })),
+ tx
+ );
+ });
+
+ result.push(...prepared.map(({ entry, token }) => ({ userId: entry.userId, orgId: entry.orgId, token })));
+ }
+
+ return result;
+ };
+
const DUMMY_HASH = "$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy";
const validateTokenForUser = async ({
type,
@@ -486,6 +549,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
return {
createTokenForUser,
+ createTokensForUsers,
validateTokenForUser,
getUserTokenSession,
clearTokenSessionById,
diff --git a/backend/src/services/auth-token/auth-token-types.ts b/backend/src/services/auth-token/auth-token-types.ts
index 23ef0f3d16..299f6f1862 100644
--- a/backend/src/services/auth-token/auth-token-types.ts
+++ b/backend/src/services/auth-token/auth-token-types.ts
@@ -21,6 +21,12 @@ export type TCreateTokenForUserDTO = {
payload?: string;
};
+export type TCreateTokensForUsersResult = {
+ userId: string;
+ orgId?: string;
+ token: string;
+}[];
+
export type TCreateOrgInviteTokenDTO = {
userId: string;
orgId: string;
diff --git a/backend/src/services/org/org-service.ts b/backend/src/services/org/org-service.ts
index 20ba40b98e..e137976360 100644
--- a/backend/src/services/org/org-service.ts
+++ b/backend/src/services/org/org-service.ts
@@ -1282,44 +1282,54 @@ export const orgServiceFactory = ({
const orgCache: Record<string, { name: string; id: string } | undefined> = {};
const notifiedUsers: string[] = [];
- await Promise.all(
- invitedUsers.map(async (invitedUser) => {
- let org = orgCache[invitedUser.scopeOrgId];
- if (!org) {
- org = await requestMemoize(requestMemoKeys.orgFindById(invitedUser.scopeOrgId), () =>
- orgDAL.findById(invitedUser.scopeOrgId)
- );
- orgCache[invitedUser.scopeOrgId] = org;
- }
+ const resolvedInvites: { invitedUser: (typeof invitedUsers)[number]; org: { name: string; id: string } }[] = [];
+ for (const invitedUser of invitedUsers) {
+ let org = orgCache[invitedUser.scopeOrgId];
+ if (!org) {
+ // eslint-disable-next-line no-await-in-loop
+ org = await requestMemoize(requestMemoKeys.orgFindById(invitedUser.scopeOrgId), () =>
+ orgDAL.findById(invitedUser.scopeOrgId)
+ );
+ orgCache[invitedUser.scopeOrgId] = org;
+ }
- if (!org || !invitedUser.actorUserId) return;
+ if (org && invitedUser.actorUserId && invitedUser.inviteEmail) {
+ resolvedInvites.push({ invitedUser, org });
+ }
+ }
- const token = await tokenService.createTokenForUser({
- type: TokenType.TOKEN_EMAIL_ORG_INVITATION,
- userId: invitedUser.actorUserId,
- orgId: org.id
- });
+ const tokens = await tokenService.createTokensForUsers(
+ resolvedInvites.map(({ invitedUser, org }) => ({
+ type: TokenType.TOKEN_EMAIL_ORG_INVITATION,
+ userId: invitedUser.actorUserId as string,
+ orgId: org.id
+ }))
+ );
+ const tokenByUserOrg = new Map(tokens.map((t) => [`${t.userId}:${t.orgId}`, t.token]));
- if (invitedUser.inviteEmail) {
- await delayMs(Math.max(0, applyJitter(0, 2000)));
-
- try {
- await smtpService.sendMail({
- template: SmtpTemplates.OrgInvite,
- subjectLine: `Reminder: You have been invited to ${org.name} on Infisical`,
- recipients: [invitedUser.inviteEmail],
- substitutions: {
- organizationName: org.name,
- email: invitedUser.inviteEmail,
- organizationId: org.id.toString(),
- token,
- callback_url: `${appCfg.SITE_URL}/signupinvite`
- }
- });
- notifiedUsers.push(invitedUser.id);
- } catch (err) {
- logger.error(err, `daily-resource-cleanup: notify invited users failed to send email`);
- }
+ await Promise.all(
+ resolvedInvites.map(async ({ invitedUser, org }) => {
+ const token = tokenByUserOrg.get(`${invitedUser.actorUserId}:${org.id}`);
+ if (!token) return;
+
+ await delayMs(Math.max(0, applyJitter(0, 2000)));
+
+ try {
+ await smtpService.sendMail({
+ template: SmtpTemplates.OrgInvite,
+ subjectLine: `Reminder: You have been invited to ${org.name} on Infisical`,
+ recipients: [invitedUser.inviteEmail as string],
+ substitutions: {
+ organizationName: org.name,
+ email: invitedUser.inviteEmail,
+ organizationId: org.id.toString(),
+ token,
+ callback_url: `${appCfg.SITE_URL}/signupinvite`
+ }
+ });
+ notifiedUsers.push(invitedUser.id);
+ } catch (err) {
+ logger.error(err, `daily-resource-cleanup: notify invited users failed to send email`);
}
})
);