Skip to content

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

refactor service

adilsondd79435e2568
diff --git a/backend/src/ee/services/audit-log/audit-log-service.ts b/backend/src/ee/services/audit-log/audit-log-service.ts
index 2b64e0d4e3..bdba2885fe 100644
--- a/backend/src/ee/services/audit-log/audit-log-service.ts
+++ b/backend/src/ee/services/audit-log/audit-log-service.ts
@@ -112,7 +112,7 @@ export const auditLogServiceFactory = ({
// add all cases in which project id or org id cannot be added
if (
data.event.type !== EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH &&
- data.event.type !== EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH_FAILED
+ data.event.type !== EventType.LOGIN_IDENTITY_UA_AUTH_FAILED
) {
if (!data.projectId && !data.orgId)
throw new BadRequestError({ message: "Must specify either project id or org id" });
diff --git a/backend/src/lib/errors/index.ts b/backend/src/lib/errors/index.ts
index 134e0c2f9d..7cc4063fe5 100644
--- a/backend/src/lib/errors/index.ts
+++ b/backend/src/lib/errors/index.ts
@@ -41,10 +41,18 @@ export class UnauthorizedError extends Error {
error: unknown;
- constructor({ name, error, message }: { message?: string; name?: string; error?: unknown } = {}) {
+ detail?: Record<string, unknown>;
+
+ constructor({
+ name,
+ error,
+ message,
+ detail
+ }: { message?: string; name?: string; error?: unknown; detail?: Record<string, unknown> } = {}) {
super(message ?? "You are not allowed to access this resource");
this.name = name || "UnauthorizedError";
this.error = error;
+ this.detail = detail;
}
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index edb1f22105..7aabdfd7bb 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1873,8 +1873,7 @@ export const registerRoutes = async (
licenseService,
keyStore,
orgDAL,
- membershipIdentityDAL,
- auditLogService
+ membershipIdentityDAL
});
const identityKubernetesAuthService = identityKubernetesAuthServiceFactory({
diff --git a/backend/src/server/routes/v1/identity-universal-auth-router.ts b/backend/src/server/routes/v1/identity-universal-auth-router.ts
index 25c8ae80fe..875ee31b84 100644
--- a/backend/src/server/routes/v1/identity-universal-auth-router.ts
+++ b/backend/src/server/routes/v1/identity-universal-auth-router.ts
@@ -3,12 +3,13 @@ import { z } from "zod";
import { IdentityAuthMethod, IdentityUaClientSecretsSchema, IdentityUniversalAuthsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { ApiDocsTags, UNIVERSAL_AUTH } from "@app/lib/api-docs";
+import { UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { slugSchema } from "@app/server/lib/schemas";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
-import { AuthMode } from "@app/services/auth/auth-type";
+import { ActorType, AuthMode } from "@app/services/auth/auth-type";
import { TIdentityTrustedIp } from "@app/services/identity/identity-types";
import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
@@ -53,56 +54,76 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {
}
},
handler: async (req) => {
- const {
- identityUa,
- accessToken,
- identityAccessToken,
- validClientSecretInfo,
- identity,
- accessTokenTTL,
- accessTokenMaxTTL
- } = await server.services.identityUa.login({
- ...req.body,
- ip: req.realIp,
- userAgent: req.auditLogInfo.userAgent,
- userAgentType: req.auditLogInfo.userAgentType
- });
-
- await server.services.auditLog.createAuditLog({
- ...req.auditLogInfo,
- orgId: identity.orgId,
- event: {
- type: EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH,
- metadata: {
- clientSecretId: validClientSecretInfo.id,
- identityId: identityUa.identityId,
- identityAccessTokenId: identityAccessToken.id,
- identityUniversalAuthId: identityUa.id
- }
- }
- });
+ try {
+ const {
+ identityUa,
+ accessToken,
+ identityAccessToken,
+ validClientSecretInfo,
+ identity,
+ accessTokenTTL,
+ accessTokenMaxTTL
+ } = await server.services.identityUa.login({
+ ...req.body,
+ ip: req.realIp,
+ userAgent: req.auditLogInfo.userAgent,
+ userAgentType: req.auditLogInfo.userAgentType
+ });
- void server.services.telemetry
- .sendPostHogEvents({
- event: PostHogEventTypes.MachineIdentityLogin,
- distinctId: `identity-${identityUa.identityId}`,
- organizationId: identity.orgId,
- properties: {
- identityId: identityUa.identityId,
- orgId: identity.orgId,
- authMethod: IdentityAuthMethod.UNIVERSAL_AUTH
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: identity.orgId,
+ event: {
+ type: EventType.LOGIN_IDENTITY_UNIVERSAL_AUTH,
+ metadata: {
+ clientSecretId: validClientSecretInfo.id,
+ identityId: identityUa.identityId,
+ identityAccessTokenId: identityAccessToken.id,
+ identityUniversalAuthId: identityUa.id
+ }
}
- })
- .catch((error) => {
- logger.error(error, `Failed to send telemetry event [identityId=${identityUa.identityId}]`);
});
- return {
- accessToken,
- tokenType: "Bearer" as const,
- expiresIn: accessTokenTTL,
- accessTokenMaxTTL
- };
+ void server.services.telemetry
+ .sendPostHogEvents({
+ event: PostHogEventTypes.MachineIdentityLogin,
+ distinctId: `identity-${identityUa.identityId}`,
+ organizationId: identity.orgId,
+ properties: {
+ identityId: identityUa.identityId,
+ orgId: identity.orgId,
+ authMethod: IdentityAuthMethod.UNIVERSAL_AUTH
+ }
+ })
+ .catch((error) => {
+ logger.error(error, `Failed to send telemetry event [identityId=${identityUa.identityId}]`);
+ });
+
+ return {
+ accessToken,
+ tokenType: "Bearer" as const,
+ expiresIn: accessTokenTTL,
+ accessTokenMaxTTL
+ };
+ } catch (error) {
+ if (error instanceof UnauthorizedError && error.detail) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ actor: { type: ActorType.UNKNOWN_USER, metadata: {} },
+ orgId: error.detail.orgId as string | undefined,
+ event: {
+ type: EventType.LOGIN_IDENTITY_UA_AUTH_FAILED,
+ metadata: {
+ clientId: req.body.clientId,
+ identityId: (error.detail.identityId as string) ?? null,
+ reason: error.detail.reason as string,
+ message: error.message
+ }
+ }
+ });
+ }
+ throw error;
+ }
}
});
diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.ts
index a0149e897a..361214457a 100644
--- a/backend/src/services/identity-ua/identity-ua-service.ts
+++ b/backend/src/services/identity-ua/identity-ua-service.ts
@@ -2,7 +2,6 @@ import { ForbiddenError, subject } from "@casl/ability";
import { requestContext } from "@fastify/request-context";
import { AccessScope, ActionProjectType, IdentityAuthMethod, OrganizationActionScope } from "@app/db/schemas";
-import { EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
import { OrgPermissionIdentityActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
import {
@@ -38,7 +37,6 @@ import { TIdentityUaDALFactory } from "./identity-ua-dal";
import {
TAttachUaDTO,
TClearUaLockoutsDTO,
- TCreateLoginFailedAuditLogDTO,
TCreateUaClientSecretDTO,
TGetUaClientSecretsDTO,
TGetUaDTO,
@@ -62,7 +60,6 @@ type TIdentityUaServiceFactoryDep = {
TKeyStoreFactory,
"setItemWithExpiry" | "getItem" | "deleteItem" | "getKeysByPattern" | "deleteItems" | "acquireLock"
>;
- auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
};
export type TIdentityUaServiceFactory = ReturnType<typeof identityUaServiceFactory>;
@@ -81,46 +78,16 @@ export const identityUaServiceFactory = ({
licenseService,
orgDAL,
keyStore,
- identityDAL,
- auditLogService
+ identityDAL
}: TIdentityUaServiceFactoryDep) => {
- const createLoginFailedAuditLog = async ({
- message,
- clientId,
- identityId,
- reason,
- orgId,
- ip,
- userAgent,
- userAgentType
- }: TCreateLoginFailedAuditLogDTO): Promise<void> => {
- await auditLogService.createAuditLog({
- actor: { type: ActorType.UNKNOWN_USER, metadata: {} },
- orgId,
- ipAddress: ip,
- userAgent,
- userAgentType,
- event: {
- type: EventType.LOGIN_IDENTITY_UA_AUTH_FAILED,
- metadata: { clientId, identityId, reason, message }
- }
- });
- };
-
- const login = async ({ clientId, clientSecret, ip, organizationSlug, userAgent, userAgentType }: TLoginUaDTO) => {
+ const login = async ({ clientId, clientSecret, ip, organizationSlug }: TLoginUaDTO) => {
const appCfg = getConfig();
const identityUa = await identityUaDAL.findOne({ clientId });
if (!identityUa) {
- await createLoginFailedAuditLog({
+ throw new UnauthorizedError({
message: "Invalid credentials",
- clientId,
- identityId: null,
- reason: "client_id_not_found",
- ip,
- userAgent,
- userAgentType
+ detail: { reason: "client_id_not_found", identityId: null }
});
- throw new UnauthorizedError({ message: "Invalid credentials" });
}
const identity = await identityDAL.findById(identityUa.identityId);
@@ -146,18 +113,9 @@ export const identityUaServiceFactory = ({
}
if (lockout && lockout.lockedOut) {
- await createLoginFailedAuditLog({
- message: "This identity auth method is temporarily locked, please try again later",
- clientId,
- identityId: identityUa.identityId,
- reason: "temporarily_locked",
- orgId: identity.orgId,
- ip,
- userAgent,
- userAgentType
- });
throw new UnauthorizedError({
- message: "This identity auth method is temporarily locked, please try again later"
+ message: "This identity auth method is temporarily locked, please try again later",
+ detail: { reason: "temporarily_locked", identityId: identityUa.identityId, orgId: identity.orgId }
});
}
@@ -200,18 +158,9 @@ export const identityUaServiceFactory = ({
}
if (lockout.lockedOut) {
- await createLoginFailedAuditLog({
- message: "This identity auth method is temporarily locked, please try again later",
- clientId,
- identityId: identityUa.identityId,
- reason: "temporarily_locked",
- orgId: identity.orgId,
- ip,
- userAgent,
- userAgentType
- });
throw new UnauthorizedError({
- message: "This identity auth method is temporarily locked, please try again later"
+ message: "This identity auth method is temporarily locked, please try again later",
+ detail: { reason: "temporarily_locked", identityId: identityUa.identityId, orgId: identity.orgId }
});
}
@@ -240,17 +189,10 @@ export const identityUaServiceFactory = ({
}
}
- await createLoginFailedAuditLog({
+ throw new UnauthorizedError({
message: "Invalid credentials",
- clientId,
- identityId: identityUa.identityId,
- reason: "invalid_client_secret",
- orgId: identity.orgId,
- ip,
- userAgent,
- userAgentType
+ detail: { reason: "invalid_client_secret", identityId: identityUa.identityId, orgId: identity.orgId }
});
- throw new UnauthorizedError({ message: "Invalid credentials" });
} else if (lockout) {
// If credentials are valid, clear any existing lockout record
await keyStore.deleteItem(LOCKOUT_KEY);
@@ -268,17 +210,10 @@ export const identityUaServiceFactory = ({
isClientSecretRevoked: true
});
- await createLoginFailedAuditLog({
+ throw new UnauthorizedError({
message: "Access denied due to expired client secret",
- clientId,
- identityId: identityUa.identityId,
- reason: "client_secret_expired",
- orgId: identity.orgId,
- ip,
- userAgent,
- userAgentType
+ detail: { reason: "client_secret_expired", identityId: identityUa.identityId, orgId: identity.orgId }
});
- throw new UnauthorizedError({ message: "Access denied due to expired client secret" });
}
}
@@ -288,17 +223,14 @@ export const identityUaServiceFactory = ({
await identityUaClientSecretDAL.updateById(validClientSecretInfo.id, {
isClientSecretRevoked: true
});
- await createLoginFailedAuditLog({
+ throw new UnauthorizedError({
message: "Access denied due to client secret usage limit reached",
- clientId,
- identityId: identityUa.identityId,
- reason: "client_secret_usage_limit_reached",
- orgId: identity.orgId,
- ip,
- userAgent,
- userAgentType
+ detail: {
+ reason: "client_secret_usage_limit_reached",
+ identityId: identityUa.identityId,
+ orgId: identity.orgId
+ }
});
- throw new UnauthorizedError({ message: "Access denied due to client secret usage limit reached" });
}
const accessTokenTTLParams =
@@ -330,18 +262,9 @@ export const identityUaServiceFactory = ({
});
if (!subOrgMembership) {
- await createLoginFailedAuditLog({
- message: `Identity not authorized to access sub organization ${organizationSlug}`,
- clientId,
- identityId: identityUa.identityId,
- reason: "sub_org_not_authorized",
- orgId: identity.orgId,
- ip,
- userAgent,
- userAgentType
- });
throw new UnauthorizedError({
- message: `Identity not authorized to access sub organization ${organizationSlug}`
+ message: `Identity not authorized to access sub organization ${organizationSlug}`,
+ detail: { reason: "sub_org_not_authorized", identityId: identityUa.identityId, orgId: identity.orgId }
});
}
diff --git a/backend/src/services/identity-ua/identity-ua-types.ts b/backend/src/services/identity-ua/identity-ua-types.ts
index 4c9713557c..da9e66bf74 100644
--- a/backend/src/services/identity-ua/identity-ua-types.ts
+++ b/backend/src/services/identity-ua/identity-ua-types.ts
@@ -71,14 +71,3 @@ export type TGetUniversalAuthClientSecretByIdDTO = {
identityId: string;
clientSecretId: string;
} & Omit<TProjectPermission, "projectId">;
-
-export type TCreateLoginFailedAuditLogDTO = {
- message: string;
- clientId: string;
- identityId: string | null;
- reason: string;
- orgId?: string;
- ip?: string;
- userAgent?: string;
- userAgentType?: UserAgentType;
-};