Skip to content

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

feat: move parameters to envs.ts and create a transaction with select for update to avoid concurrency

adilsonc87283fde60e
diff --git a/backend/e2e-test/routes/v1/user-activation.spec.ts b/backend/e2e-test/routes/v1/user-activation.spec.ts
index b376d9cfb4..c1fa9698bb 100644
--- a/backend/e2e-test/routes/v1/user-activation.spec.ts
+++ b/backend/e2e-test/routes/v1/user-activation.spec.ts
@@ -28,7 +28,7 @@ const mintJwt = (orgId: string) =>
const callActivation = (orgId: string) =>
testServer.inject({
- method: "GET",
+ method: "POST",
url: "/api/v1/user-activation/secrets",
headers: { authorization: `Bearer ${mintJwt(orgId)}` }
});
diff --git a/backend/src/db/migrations/20260702120000_create-user-secret-activation.ts b/backend/src/db/migrations/20260702120000_create-user-secret-activation.ts
index d0ea192fad..894b286546 100644
--- a/backend/src/db/migrations/20260702120000_create-user-secret-activation.ts
+++ b/backend/src/db/migrations/20260702120000_create-user-secret-activation.ts
@@ -12,9 +12,6 @@ export async function up(knex: Knex): Promise<void> {
t.datetime("returnedAfterThreeDaysAt");
t.datetime("returnedAfterSevenDaysAt");
- t.datetime("createdAt").notNullable().defaultTo(knex.fn.now());
- t.datetime("updatedAt").notNullable().defaultTo(knex.fn.now());
-
t.uuid("userId").notNullable();
t.foreign("userId").references("id").inTable(TableName.Users).onDelete("CASCADE");
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts
index c769a37649..dbfdb0a0ea 100644
--- a/backend/src/lib/config/env.ts
+++ b/backend/src/lib/config/env.ts
@@ -238,6 +238,22 @@ const envSchema = z
CONTENTFUL_ENVIRONMENT: zpStr(z.string().optional().default("master")),
// GitHub API token for upgrade path tool
GITHUB_API_TOKEN: zpStr(z.string().optional()),
+ // Secrets activation nudge tuning. Gates whether the member-invite activation banner shows and
+ // how long after the first secret the follow-up nudges appear.
+ SECRETS_ACTIVATION_ORG_MAX_AGE_MONTHS: z.coerce.number().default(2),
+ SECRETS_ACTIVATION_ORG_MAX_MEMBERS: z.coerce.number().default(5),
+ SECRETS_ACTIVATION_FIRST_NUDGE_DELAY: zpStr(
+ z
+ .string()
+ .default("3d")
+ .transform((val) => ms(val))
+ ),
+ SECRETS_ACTIVATION_SECOND_NUDGE_DELAY: zpStr(
+ z
+ .string()
+ .default("7d")
+ .transform((val) => ms(val))
+ ),
// jwt options
AUTH_SECRET: zpStr(z.string()).default(process.env.JWT_AUTH_SECRET), // for those still using old JWT_AUTH_SECRET
JWT_AUTH_LIFETIME: zpStr(z.string().default("10d")),
diff --git a/backend/src/services/user-activation/user-activation-dal.ts b/backend/src/services/user-activation/user-activation-dal.ts
index 6dcd3ff3d3..6fc67707a1 100644
--- a/backend/src/services/user-activation/user-activation-dal.ts
+++ b/backend/src/services/user-activation/user-activation-dal.ts
@@ -1,5 +1,8 @@
+import { Knex } from "knex";
+
import { TDbClient } from "@app/db";
import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
import { ormify } from "@app/lib/knex";
export type TUserActivationDALFactory = ReturnType<typeof userActivationDALFactory>;
@@ -7,5 +10,15 @@ export type TUserActivationDALFactory = ReturnType<typeof userActivationDALFacto
export const userActivationDALFactory = (db: TDbClient) => {
const userActivationOrm = ormify(db, TableName.UserSecretActivation);
- return userActivationOrm;
+ // Locking read for use inside a transaction: concurrent activation checks for the same
+ // (userId, orgId) serialize on the row instead of racing the read-modify-write.
+ const findOneForUpdate = async (filter: { userId: string; orgId: string }, tx: Knex) => {
+ try {
+ return await tx(TableName.UserSecretActivation).where(filter).forUpdate().first("*");
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindOneForUpdate - UserActivation" });
+ }
+ };
+
+ return { ...userActivationOrm, findOneForUpdate };
};
diff --git a/backend/src/services/user-activation/user-activation-service.ts b/backend/src/services/user-activation/user-activation-service.ts
index 844dd47dd3..a191e2f658 100644
--- a/backend/src/services/user-activation/user-activation-service.ts
+++ b/backend/src/services/user-activation/user-activation-service.ts
@@ -1,42 +1,21 @@
import { OrganizationActionScope } from "@app/db/schemas";
import { OrgPermissionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { getConfig } from "@app/lib/config/env";
import { TOrgDALFactory } from "@app/services/org/org-dal";
-import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TUserActivationDALFactory } from "./user-activation-dal";
import { TGetSecretsActivationStatusDTO } from "./user-activation-types";
-
-const DAY_IN_MS = 24 * 60 * 60 * 1000;
-const ORG_MAX_AGE_MONTHS = 2;
-const ORG_MAX_MEMBERS = 5;
-const RETURNED_AFTER_THREE_DAYS_MS = 3 * DAY_IN_MS;
-const RETURNED_AFTER_SEVEN_DAYS_MS = 7 * DAY_IN_MS;
+import { TActivationRecord, TSecretsActivationStatus } from "./user-activation-types";
type TUserActivationServiceFactoryDep = {
userActivationDAL: TUserActivationDALFactory;
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
orgDAL: Pick<TOrgDALFactory, "findById" | "countAllOrgMembers">;
- secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "findByUserId">;
};
export type TUserActivationServiceFactory = ReturnType<typeof userActivationServiceFactory>;
-type TActivationRecord = {
- firstSecretCreatedAt?: Date | null;
- returnedAfterThreeDaysAt?: Date | null;
- returnedAfterSevenDaysAt?: Date | null;
-};
-
-type TSecretsActivationStatus = {
- shouldShowActivation: boolean;
- stage: "FIRST_SECRET" | "THREE_DAYS" | "SEVEN_DAYS" | null;
- activation: {
- firstSecretCreatedAt: Date | null;
- returnedAfterThreeDaysAt: Date | null;
- returnedAfterSevenDaysAt: Date | null;
- } | null;
-};
export const userActivationServiceFactory = ({
userActivationDAL,
@@ -58,6 +37,7 @@ export const userActivationServiceFactory = ({
actorAuthMethod
}: TGetSecretsActivationStatusDTO): Promise<TSecretsActivationStatus> => {
const noActivation: TSecretsActivationStatus = { shouldShowActivation: false, stage: null, activation: null };
+ const appCfg = getConfig();
// 1. The caller must be able to invite other members to the org.
const { permission } = await permissionService.getOrgPermission({
@@ -70,56 +50,71 @@ export const userActivationServiceFactory = ({
});
if (!permission.can(OrgPermissionActions.Create, OrgPermissionSubjects.Member)) return noActivation;
- // 2. The org must be younger than 2 months.
+ // 2. The org must be young enough (SECRETS_ACTIVATION_ORG_MAX_AGE_MONTHS).
const org = await orgDAL.findById(actorOrgId);
if (!org) return noActivation;
const orgAgeCutoff = new Date();
- orgAgeCutoff.setMonth(orgAgeCutoff.getMonth() - ORG_MAX_AGE_MONTHS);
+ orgAgeCutoff.setMonth(orgAgeCutoff.getMonth() - appCfg.SECRETS_ACTIVATION_ORG_MAX_AGE_MONTHS);
if (org.createdAt.getTime() < orgAgeCutoff.getTime()) return noActivation;
- // 3. The org must have fewer than 5 users.
+ // 3. The org must have fewer than SECRETS_ACTIVATION_ORG_MAX_MEMBERS users.
const memberCount = await orgDAL.countAllOrgMembers(actorOrgId);
- if (memberCount >= ORG_MAX_MEMBERS) return noActivation;
-
- const existingActivation = await userActivationDAL.findOne({ userId: actorId, orgId: actorOrgId });
- const now = new Date();
-
- // First interaction: creating the row is itself the signal that this is the user's first action,
- // so we stamp firstSecretCreatedAt. This also covers orgs that predate the feature.
- if (!existingActivation) {
- const createdActivation = await userActivationDAL.create({
- userId: actorId,
- orgId: actorOrgId,
- firstSecretCreatedAt: now
- });
- return { shouldShowActivation: true, stage: "FIRST_SECRET", activation: toActivation(createdActivation) };
- }
-
- // if the row was created and the firstSecretCreatedAt is not set, it means the user has not created a secret yet
- if (!existingActivation.firstSecretCreatedAt) {
- existingActivation.firstSecretCreatedAt = now;
- await userActivationDAL.updateById(existingActivation.id, existingActivation);
-
- return { shouldShowActivation: true, stage: "FIRST_SECRET", activation: toActivation(existingActivation) };
- }
-
- const elapsedMs = now.getTime() - existingActivation.firstSecretCreatedAt.getTime();
-
- if (!existingActivation.returnedAfterThreeDaysAt && elapsedMs >= RETURNED_AFTER_THREE_DAYS_MS) {
- const updatedActivation = await userActivationDAL.updateById(existingActivation.id, {
- returnedAfterThreeDaysAt: now
- });
- return { shouldShowActivation: true, stage: "THREE_DAYS", activation: toActivation(updatedActivation) };
- }
-
- if (!existingActivation.returnedAfterSevenDaysAt && elapsedMs >= RETURNED_AFTER_SEVEN_DAYS_MS) {
- const updatedActivation = await userActivationDAL.updateById(existingActivation.id, {
- returnedAfterSevenDaysAt: now
- });
- return { shouldShowActivation: true, stage: "SEVEN_DAYS", activation: toActivation(updatedActivation) };
- }
-
- return { shouldShowActivation: false, stage: null, activation: toActivation(existingActivation) };
+ if (memberCount >= appCfg.SECRETS_ACTIVATION_ORG_MAX_MEMBERS) return noActivation;
+
+ // Read-modify-write under a row lock so concurrent activation checks for the same
+ // (userId, orgId) can't double-stamp a stage or lose an update. FOR UPDATE can't lock a row
+ // that doesn't exist yet, so the first-interaction insert still goes through ON CONFLICT
+ // (upsert) to stay safe against a concurrent first request.
+ return userActivationDAL.transaction(async (tx): Promise<TSecretsActivationStatus> => {
+ const existingActivation = await userActivationDAL.findOneForUpdate(
+ { userId: actorId, orgId: actorOrgId },
+ tx
+ );
+ const now = new Date();
+
+ // First interaction: creating the row is itself the signal that this is the user's first
+ // action, so we stamp firstSecretCreatedAt. This also covers orgs that predate the feature.
+ if (!existingActivation) {
+ const [createdActivation] = await userActivationDAL.upsert(
+ [{ userId: actorId, orgId: actorOrgId, firstSecretCreatedAt: now }],
+ ["userId", "orgId"],
+ tx
+ );
+ return { shouldShowActivation: true, stage: "FIRST_SECRET", activation: toActivation(createdActivation) };
+ }
+
+ // Row exists but firstSecretCreatedAt was never set: treat this call as the first action.
+ if (!existingActivation.firstSecretCreatedAt) {
+ const updatedActivation = await userActivationDAL.updateById(
+ existingActivation.id,
+ { firstSecretCreatedAt: now },
+ tx
+ );
+ return { shouldShowActivation: true, stage: "FIRST_SECRET", activation: toActivation(updatedActivation) };
+ }
+
+ const elapsedMs = now.getTime() - existingActivation.firstSecretCreatedAt.getTime();
+
+ if (!existingActivation.returnedAfterThreeDaysAt && elapsedMs >= appCfg.SECRETS_ACTIVATION_FIRST_NUDGE_DELAY) {
+ const updatedActivation = await userActivationDAL.updateById(
+ existingActivation.id,
+ { returnedAfterThreeDaysAt: now },
+ tx
+ );
+ return { shouldShowActivation: true, stage: "THREE_DAYS", activation: toActivation(updatedActivation) };
+ }
+
+ if (!existingActivation.returnedAfterSevenDaysAt && elapsedMs >= appCfg.SECRETS_ACTIVATION_SECOND_NUDGE_DELAY) {
+ const updatedActivation = await userActivationDAL.updateById(
+ existingActivation.id,
+ { returnedAfterSevenDaysAt: now },
+ tx
+ );
+ return { shouldShowActivation: true, stage: "SEVEN_DAYS", activation: toActivation(updatedActivation) };
+ }
+
+ return { shouldShowActivation: false, stage: null, activation: toActivation(existingActivation) };
+ });
};
return {
diff --git a/backend/src/services/user-activation/user-activation-types.ts b/backend/src/services/user-activation/user-activation-types.ts
index a54a2a4a68..539f2bd9f0 100644
--- a/backend/src/services/user-activation/user-activation-types.ts
+++ b/backend/src/services/user-activation/user-activation-types.ts
@@ -6,3 +6,20 @@ export type TGetSecretsActivationStatusDTO = {
actorOrgId: string;
actorAuthMethod: ActorAuthMethod;
};
+
+
+export type TActivationRecord = {
+ firstSecretCreatedAt?: Date | null;
+ returnedAfterThreeDaysAt?: Date | null;
+ returnedAfterSevenDaysAt?: Date | null;
+};
+
+export type TSecretsActivationStatus = {
+ shouldShowActivation: boolean;
+ stage: "FIRST_SECRET" | "THREE_DAYS" | "SEVEN_DAYS" | null;
+ activation: {
+ firstSecretCreatedAt: Date | null;
+ returnedAfterThreeDaysAt: Date | null;
+ returnedAfterSevenDaysAt: Date | null;
+ } | null;
+};
\ No newline at end of file