Skip to content

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

add audit logs for audit log page

adilson812ac93c5835
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 9c30f1838a..7cb96c9757 100644
--- a/backend/src/ee/services/audit-log/audit-log-service.ts
+++ b/backend/src/ee/services/audit-log/audit-log-service.ts
@@ -4,9 +4,10 @@ import { requestContext } from "@fastify/request-context";
import { ActionProjectType, OrganizationActionScope, TUsers } from "@app/db/schemas";
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
-import { BadRequestError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
+import { TGenericPermission } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
import { NotificationType } from "@app/services/notification/notification-types";
@@ -145,6 +146,84 @@ export const auditLogServiceFactory = ({
return auditLogQueue.pushToLog(el);
};
+ const checkAuditLogReadPermission = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId
+ }: TGenericPermission & { projectId?: string }) => {
+ if (projectId) {
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.Any
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionAuditLogsActions.Read,
+ ProjectPermissionSub.AuditLogs
+ );
+ return;
+ }
+
+ const { permission } = await permissionService.getOrgPermission({
+ scope: OrganizationActionScope.Any,
+ actor,
+ actorId,
+ orgId: actorOrgId,
+ actorAuthMethod,
+ actorOrgId
+ });
+ ForbiddenError.from(permission).throwUnlessCan(OrgPermissionAuditLogsActions.Read, OrgPermissionSubjects.AuditLogs);
+ };
+
+ const recordViewAuditLogDetails: TAuditLogServiceFactory["recordViewAuditLogDetails"] = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId,
+ auditLogId,
+ auditLogInfo
+ }) => {
+ await checkAuditLogReadPermission({ actor, actorId, actorAuthMethod, actorOrgId, projectId });
+ await createAuditLog({
+ ...auditLogInfo,
+ orgId: actorOrgId,
+ projectId,
+ event: {
+ type: EventType.VIEW_AUDIT_LOG_DETAILS,
+ metadata: { auditLogId }
+ }
+ });
+ };
+
+ const trackAuditLogDetailsViewForOrg: TAuditLogServiceFactory["trackAuditLogDetailsViewForOrg"] = async ({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ auditLogId,
+ auditLogInfo
+ }) => {
+ const row = await auditLogDAL.findById(auditLogId);
+ if (!row || row.orgId !== actorOrgId) {
+ throw new NotFoundError({ message: "Audit log not found" });
+ }
+ await recordViewAuditLogDetails({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId: row.projectId ?? undefined,
+ auditLogId,
+ auditLogInfo
+ });
+ };
+
const getAuditLogPostgresStorageStatus: TAuditLogServiceFactory["getAuditLogPostgresStorageStatus"] = async ({
actorAuthMethod,
actorId,
@@ -261,6 +340,8 @@ export const auditLogServiceFactory = ({
return {
createAuditLog,
+ recordViewAuditLogDetails,
+ trackAuditLogDetailsViewForOrg,
listAuditLogs,
getAuditLogPostgresStorageStatus,
checkPostgresAuditLogVolumeMigrationAlert
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 64f6d1a3d0..d617cc1017 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -30,7 +30,7 @@ import { SshCertTemplateStatus } from "@app/ee/services/ssh-certificate-template
import { TLoginMapping } from "@app/ee/services/ssh-host/ssh-host-types";
import { SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
import { AsymmetricKeyAlgorithm, SigningAlgorithm } from "@app/lib/crypto/sign/types";
-import { TOrgPermission, TProjectPermission } from "@app/lib/types";
+import { TGenericPermission, TOrgPermission, TProjectPermission } from "@app/lib/types";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TCreateAppConnectionDTO, TUpdateAppConnectionDTO } from "@app/services/app-connection/app-connection-types";
import { ActorType } from "@app/services/auth/auth-type";
@@ -96,8 +96,23 @@ export type TCreateAuditLogDTO = {
projectId?: string;
} & BaseAuthData;
+export type AuditLogInfo = Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor">;
+
+export type TRecordViewAuditLogDetailsDTO = TGenericPermission & {
+ projectId?: string;
+ auditLogId: string;
+ auditLogInfo: AuditLogInfo;
+};
+
+export type TTrackAuditLogDetailsViewForOrgDTO = TGenericPermission & {
+ auditLogId: string;
+ auditLogInfo: AuditLogInfo;
+};
+
export type TAuditLogServiceFactory = {
createAuditLog: (data: TCreateAuditLogDTO) => Promise<void>;
+ recordViewAuditLogDetails: (arg: TRecordViewAuditLogDetailsDTO) => Promise<void>;
+ trackAuditLogDetailsViewForOrg: (arg: TTrackAuditLogDetailsViewForOrgDTO) => Promise<void>;
listAuditLogs: (arg: TListProjectAuditLogDTO) => Promise<
{
event: {
@@ -129,8 +144,6 @@ export type TAuditLogServiceFactory = {
checkPostgresAuditLogVolumeMigrationAlert: () => Promise<void>;
};
-export type AuditLogInfo = Pick<TCreateAuditLogDTO, "userAgent" | "userAgentType" | "ipAddress" | "actor">;
-
interface BaseAuthData {
ipAddress?: string;
userAgent?: string;
@@ -681,6 +694,8 @@ export enum EventType {
ACCESS_APPROVAL_REQUEST_REVIEW = "access-approval-request-review",
ACCESS_APPROVAL_REQUEST_REVOKE = "access-approval-request-revoke",
ACCESS_APPROVAL_REQUEST_UPDATE = "access-approval-request-update",
+ VIEW_AUDIT_LOGS = "view-audit-logs",
+ VIEW_AUDIT_LOG_DETAILS = "view-audit-log-details",
// PKI ACME
CREATE_ACME_ACCOUNT = "create-acme-account",
@@ -4797,6 +4812,18 @@ interface ViewSecretManagementInsightsSummaryEvent {
};
}
+interface ViewAuditLogsEvent {
+ type: EventType.VIEW_AUDIT_LOGS;
+ metadata?: Record<string, unknown>;
+}
+
+interface ViewAuditLogDetailsEvent {
+ type: EventType.VIEW_AUDIT_LOG_DETAILS;
+ metadata: {
+ auditLogId: string;
+ };
+}
+
interface ProjectRoleCreateEvent {
type: EventType.CREATE_PROJECT_ROLE;
metadata: {
@@ -6611,6 +6638,8 @@ export type Event =
| ViewSecretManagementInsightsAccessLocationsEvent
| ViewInsightsAuthMethodsEvent
| ViewSecretManagementInsightsSummaryEvent
+ | ViewAuditLogsEvent
+ | ViewAuditLogDetailsEvent
| ProjectRoleCreateEvent
| ProjectRoleUpdateEvent
| ProjectRoleDeleteEvent
diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.ts
index 82c6716af2..c07a27b0cd 100644
--- a/backend/src/server/routes/v1/organization-router.ts
+++ b/backend/src/server/routes/v1/organization-router.ts
@@ -240,6 +240,18 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
handler: async (req) => {
+ if (req.query.offset === 0) {
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: req.query.projectId,
+ event: {
+ type: EventType.VIEW_AUDIT_LOGS,
+ metadata: {}
+ }
+ });
+ }
+
const auditLogs = await server.services.auditLog.listAuditLogs({
filter: {
...req.query,
@@ -291,6 +303,41 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/audit-logs/:auditLogId/track-view",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ operationId: "trackOrganizationAuditLogView",
+ tags: [ApiDocsTags.AuditLogs],
+ description:
+ "Record that the current actor expanded a specific audit log entry. Emits a VIEW_AUDIT_LOG_DETAILS audit event. The frontend dedupes per-log within a session so this should be called at most once per (actor, log) per session.",
+ params: z.object({
+ auditLogId: z.string().trim().uuid()
+ }),
+ response: {
+ 200: z.object({
+ tracked: z.boolean()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ await server.services.auditLog.trackAuditLogDetailsViewForOrg({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ auditLogId: req.params.auditLogId,
+ auditLogInfo: req.auditLogInfo
+ });
+
+ return { tracked: true };
+ }
+ });
+
server.route({
method: "GET",
url: "/:organizationId/users",
diff --git a/frontend/src/hooks/api/auditLogs/index.tsx b/frontend/src/hooks/api/auditLogs/index.tsx
index 15eb64c94a..65254d74d3 100644
--- a/frontend/src/hooks/api/auditLogs/index.tsx
+++ b/frontend/src/hooks/api/auditLogs/index.tsx
@@ -1,2 +1,3 @@
+export * from "./mutations";
export * from "./queries";
export * from "./useAuditLogActorSuggestions";
diff --git a/frontend/src/hooks/api/auditLogs/mutations.tsx b/frontend/src/hooks/api/auditLogs/mutations.tsx
new file mode 100644
index 0000000000..e42ebcc873
--- /dev/null
+++ b/frontend/src/hooks/api/auditLogs/mutations.tsx
@@ -0,0 +1,15 @@
+import { useMutation } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+type TrackAuditLogViewInput = { auditLogId: string };
+
+export const useTrackAuditLogView = () =>
+ useMutation({
+ mutationFn: async ({ auditLogId }: TrackAuditLogViewInput) => {
+ const { data } = await apiRequest.post<{ tracked: boolean }>(
+ `/api/v1/organization/audit-logs/${auditLogId}/track-view`
+ );
+ return data;
+ }
+ });
diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx
index a42847cc96..86faf32555 100644
--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx
+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsTableRow.tsx
@@ -1,3 +1,4 @@
+import { useEffect, useRef } from "react";
import { faCaretDown, faCaretRight } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { InfoIcon } from "lucide-react";
@@ -6,6 +7,7 @@ import { Td, Tooltip, Tr } from "@app/components/v2";
import { formatDateTime, Timezone } from "@app/helpers/datetime";
import { useToggle } from "@app/hooks";
import { ActorType } from "@app/hooks/api/auditLogs/enums";
+import { useTrackAuditLogView } from "@app/hooks/api/auditLogs/mutations";
import { AuditLog } from "@app/hooks/api/auditLogs/types";
type Props = {
@@ -40,6 +42,15 @@ const Tag = ({ label, value }: TagProps) => {
export const LogsTableRow = ({ auditLog, rowNumber, timezone }: Props) => {
const [isOpen, setIsOpen] = useToggle();
+ const { mutate: trackView } = useTrackAuditLogView();
+ const hasTrackedRef = useRef(false);
+
+ useEffect(() => {
+ if (isOpen && !hasTrackedRef.current) {
+ hasTrackedRef.current = true;
+ trackView({ auditLogId: auditLog.id });
+ }
+ }, [isOpen, auditLog.id, trackView]);
return (
<>