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
feat: add actor_id filter to audit logs
Tre Dubravad1a0de5450db
diff --git a/backend/src/ee/routes/v1/deprecated-project-router.ts b/backend/src/ee/routes/v1/deprecated-project-router.tsindex 6c4175f840..d4e279533d 100644--- a/backend/src/ee/routes/v1/deprecated-project-router.ts+++ b/backend/src/ee/routes/v1/deprecated-project-router.ts@@ -6,7 +6,7 @@ import { ApiDocsTags, AUDIT_LOGS, PROJECTS } from "@app/lib/api-docs";import { getLastMidnightDateISO, removeTrailingSlash } from "@app/lib/fn";import { readLimit } from "@app/server/config/rateLimiter";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";export const registerDeprecatedProjectRouter = async (server: FastifyZodProvider) => {server.route({@@ -118,7 +118,8 @@ export const registerDeprecatedProjectRouter = async (server: FastifyZodProviderendDate: z.string().datetime().optional().describe(AUDIT_LOGS.EXPORT.endDate),offset: z.coerce.number().default(0).describe(AUDIT_LOGS.EXPORT.offset),limit: z.coerce.number().max(1000).default(20).describe(AUDIT_LOGS.EXPORT.limit),- actor: z.string().optional().describe(AUDIT_LOGS.EXPORT.actor)+ actor: z.string().optional().describe(AUDIT_LOGS.EXPORT.actor),+ actorType: z.nativeEnum(ActorType).optional().describe(AUDIT_LOGS.EXPORT.actorType)}).superRefine((el, ctx) => {if (el.endDate && el.startDate) {@@ -186,6 +187,7 @@ export const registerDeprecatedProjectRouter = async (server: FastifyZodProviderendDate: req.query.endDate || new Date().toISOString(),startDate: req.query.startDate || getLastMidnightDateISO(),auditLogActorId: req.query.actor,+ actorType: req.query.actorType,eventType: req.query.eventType ? [req.query.eventType] : undefined}});diff --git a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.tsindex a673364297..a11141db50 100644--- a/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts+++ b/backend/src/ee/services/audit-log/audit-log-clickhouse-dal.ts@@ -7,7 +7,7 @@ import { DatabaseError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { ActorType } from "@app/services/auth/auth-type";-import { EventType, filterableSecretEvents } from "./audit-log-types";+import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, filterableSecretEvents } from "./audit-log-types";type TAuditLogWithProjectName = TAuditLogs & { projectName: string | null };@@ -88,8 +88,14 @@ export const clickhouseAuditLogDALFactory = (clickhouseClient: ClickHouseClient,// Optional: actor ID filter - queries the actorMetadata JSON fieldif (arg.actorId) {- conditions.push("JSONExtractString(actorMetadata, 'userId') = {actorId:String}");- params.actorId = arg.actorId;+ const metadataKey = arg.actorType+ ? ACTOR_TYPE_TO_METADATA_ID_KEY[arg.actorType]+ : ACTOR_TYPE_TO_METADATA_ID_KEY[ActorType.USER];+ if (metadataKey) {+ conditions.push("JSONExtractString(actorMetadata, {actorMetaKey:String}) = {actorId:String}");+ params.actorMetaKey = metadataKey;+ params.actorId = arg.actorId;+ }}// Optional: event type filterdiff --git a/backend/src/ee/services/audit-log/audit-log-dal.ts b/backend/src/ee/services/audit-log/audit-log-dal.tsindex 7a986a2d39..b2204553e4 100644--- a/backend/src/ee/services/audit-log/audit-log-dal.ts+++ b/backend/src/ee/services/audit-log/audit-log-dal.ts@@ -11,7 +11,7 @@ import { logger } from "@app/lib/logger";import { QueueName } from "@app/queue";import { ActorType } from "@app/services/auth/auth-type";-import { EventType, filterableSecretEvents } from "./audit-log-types";+import { ACTOR_TYPE_TO_METADATA_ID_KEY, EventType, filterableSecretEvents } from "./audit-log-types";export interface TAuditLogDALFactory extends Omit<TOrmify<TableName.AuditLog>, "find"> {pruneAuditLog: () => Promise<void>;@@ -93,7 +93,12 @@ export const auditLogDALFactory = (db: TDbClient) => {// Special case: Filter by actor IDif (actorId) {- void sqlQuery.whereRaw(`"actorMetadata" @> jsonb_build_object('userId', ?::text)`, [actorId]);+ const metadataKey = actorType+ ? ACTOR_TYPE_TO_METADATA_ID_KEY[actorType]+ : ACTOR_TYPE_TO_METADATA_ID_KEY[ActorType.USER];+ if (metadataKey) {+ void sqlQuery.whereRaw(`"actorMetadata" @> jsonb_build_object(?::text, ?::text)`, [metadataKey, actorId]);+ }}// Special case: Filter by key/value pairs in eventMetadata fielddiff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 9944150db2..accccf87f5 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -698,6 +698,16 @@ export enum EventType {PKI_SIGNER_SIGN = "pki-signer-sign"}+export const ACTOR_TYPE_TO_METADATA_ID_KEY: Partial<Record<ActorType, string>> = {+ [ActorType.USER]: "userId",+ [ActorType.IDENTITY]: "identityId",+ [ActorType.KMIP_CLIENT]: "clientId",+ [ActorType.SERVICE]: "serviceId",+ [ActorType.ACME_PROFILE]: "profileId",+ [ActorType.ACME_ACCOUNT]: "accountId",+ [ActorType.EST_ACCOUNT]: "profileId"+};+export const filterableSecretEvents: EventType[] = [EventType.GET_SECRET,EventType.DELETE_SECRETS,diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex 9e88646fdf..3597d712ba 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -1417,7 +1417,10 @@ export const AUDIT_LOGS = {endDate: "The date to end the export at.",offset: "The offset to start from. If you enter 10, it will start from the 10th audit log.",limit: "The number of audit logs to return.",- actor: "The actor to filter the audit logs by."+ actor:+ "The ID of a specific actor to filter audit logs by. For user actors this is the userId; for identity actors this is the identityId. When filtering non-user actor types, the actorType parameter must also be provided.",+ actorType:+ "The type of actor to filter audit logs by. Must be provided when the actor parameter targets a non-user actor type (e.g. identity, kmipClient)."}} as const;diff --git a/backend/src/server/routes/v1/organization-router.ts b/backend/src/server/routes/v1/organization-router.tsindex df29ea6676..50e64b6bb1 100644--- a/backend/src/server/routes/v1/organization-router.ts+++ b/backend/src/server/routes/v1/organization-router.ts@@ -149,7 +149,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {.object({projectId: z.string().optional().describe(AUDIT_LOGS.EXPORT.projectId),environment: z.string().optional().describe(AUDIT_LOGS.EXPORT.environment),- actorType: z.nativeEnum(ActorType).optional(),+ actorType: z.nativeEnum(ActorType).optional().describe(AUDIT_LOGS.EXPORT.actorType),secretPath: z.string().optional()diff --git a/docs/documentation/platform/audit-logs.mdx b/docs/documentation/platform/audit-logs.mdxindex ea6b09fa30..10cf678850 100644--- a/docs/documentation/platform/audit-logs.mdx+++ b/docs/documentation/platform/audit-logs.mdx@@ -16,7 +16,7 @@ Infisical provides audit logs for security and compliance teams to monitor inforWith the Audit Log functionality, teams can:- **Track** 40+ different events;-- **Filter** audit logs by event, actor, source, date or any combination of these filters;+- **Filter** audit logs by event, actor, specific user or identity, source, date or any combination of these filters;- **Inspect** extensive metadata in the event of any suspicious activity or incident review.diff --git a/frontend/src/hooks/api/auditLogs/index.tsx b/frontend/src/hooks/api/auditLogs/index.tsxindex b69c251208..15eb64c94a 100644--- a/frontend/src/hooks/api/auditLogs/index.tsx+++ b/frontend/src/hooks/api/auditLogs/index.tsx@@ -1 +1,2 @@export * from "./queries";+export * from "./useAuditLogActorSuggestions";diff --git a/frontend/src/hooks/api/auditLogs/queries.tsx b/frontend/src/hooks/api/auditLogs/queries.tsxindex 5e25d81043..006ae37ae7 100644--- a/frontend/src/hooks/api/auditLogs/queries.tsx+++ b/frontend/src/hooks/api/auditLogs/queries.tsx@@ -1,16 +1,14 @@-import { useInfiniteQuery, useQuery } from "@tanstack/react-query";+import { useInfiniteQuery } from "@tanstack/react-query";import { apiRequest } from "@app/config/request";import { onRequestError } from "@app/hooks/api/reactQuery";import { TReactQueryOptions } from "@app/types/reactQuery";-import { Actor, AuditLog, TGetAuditLogsFilter } from "./types";+import { AuditLog, TGetAuditLogsFilter } from "./types";export const auditLogKeys = {getAuditLogs: (projectId: string | null, filters: TGetAuditLogsFilter) =>- [{ projectId, filters }, "audit-logs"] as const,- getAuditLogActorFilterOpts: (projectId: string) =>- [{ projectId }, "audit-log-actor-filters"] as const+ [{ projectId, filters }, "audit-logs"] as const};export const useGetAuditLogs = (@@ -55,15 +53,3 @@ export const useGetAuditLogs = (...options});};--export const useGetAuditLogActorFilterOpts = (projectId: string) => {- return useQuery({- queryKey: auditLogKeys.getAuditLogActorFilterOpts(projectId),- queryFn: async () => {- const { data } = await apiRequest.get<{ actors: Actor[] }>(- `/api/v1/projects/${projectId}/audit-logs/filters/actors`- );- return data.actors;- }- });-};diff --git a/frontend/src/hooks/api/auditLogs/useAuditLogActorSuggestions.ts b/frontend/src/hooks/api/auditLogs/useAuditLogActorSuggestions.tsnew file mode 100644index 0000000000..f2e9097d64--- /dev/null+++ b/frontend/src/hooks/api/auditLogs/useAuditLogActorSuggestions.ts@@ -0,0 +1,54 @@+import { useMemo } from "react";+import { useQuery } from "@tanstack/react-query";++import { useOrganization } from "@app/context";+import { orgIdentityQuery } from "@app/hooks/api/orgIdentity/queries";+import { fetchOrgUsers } from "@app/hooks/api/users/queries";+import { userKeys } from "@app/hooks/api/users/query-keys";++import { ActorType } from "./enums";++type ActorSuggestion = { value: string; label: string };++type UseAuditLogActorSuggestionsResult = {+ suggestions: ActorSuggestion[];+ isLoading: boolean;+};++export const useAuditLogActorSuggestions = (+ actorType?: ActorType+): UseAuditLogActorSuggestionsResult => {+ const { currentOrg } = useOrganization();+ const orgId = currentOrg?.id ?? "";++ const { data: orgUsers = [], isLoading: isLoadingUsers } = useQuery({+ queryKey: userKeys.getOrgUsers(orgId),+ queryFn: () => fetchOrgUsers(orgId),+ enabled: Boolean(orgId) && (!actorType || actorType === ActorType.USER)+ });++ const { data: orgIdentities, isLoading: isLoadingIdentities } = useQuery({+ ...orgIdentityQuery.list({ limit: 100 }),+ enabled: actorType === ActorType.IDENTITY+ });++ const suggestions = useMemo<ActorSuggestion[]>(() => {+ switch (actorType) {+ case ActorType.IDENTITY:+ return (orgIdentities?.identities ?? []).map((identity) => ({+ label: `${identity.name} (${identity.id})`,+ value: identity.id+ }));+ case undefined:+ case ActorType.USER:+ return orgUsers.map((orgUser) => ({+ label: `${orgUser.user.email || orgUser.user.username} (${orgUser.user.id})`,+ value: orgUser.user.id+ }));+ default:+ return [];+ }+ }, [actorType, orgUsers, orgIdentities]);++ return { suggestions, isLoading: isLoadingIdentities || isLoadingUsers };+};diff --git a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsxindex 4f4a263da6..26ba3c689a 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/AuditSearchFilter.tsx@@ -5,6 +5,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { Tooltip } from "@app/components/v2";import { eventToNameMap, userAgentTypeToNameMap } from "@app/hooks/api/auditLogs/constants";import { ActorType, EventType, UserAgentType } from "@app/hooks/api/auditLogs/enums";+import { useAuditLogActorSuggestions } from "@app/hooks/api/auditLogs/useAuditLogActorSuggestions";export interface AppliedFilter {property: string;@@ -35,6 +36,11 @@ const FILTER_PROPERTIES: FilterProperty[] = [hints: "user, identity, unknownUser, ...",suggestions: Object.values(ActorType).map((val) => ({ value: val, label: val }))},+ {+ key: "actor_id",+ displayLabel: "actor id",+ hints: "filter by specific user or identity ID"+ },{key: "source",hints: "web, cli, k8-operator, terraform, ...",@@ -64,6 +70,10 @@ type Props = {};export const AuditSearchFilter = ({ filters, onFiltersChange, hasProjectContext }: Props) => {+ const currentActorType = filters.find((f) => f.property === "actor")?.value as+ | ActorType+ | undefined;+ const { suggestions: actorIdSuggestions } = useAuditLogActorSuggestions(currentActorType);const [isOpen, setIsOpen] = useState(false);const [query, setQuery] = useState("");const [highlightedIndex, setHighlightedIndex] = useState(-1);@@ -84,15 +94,14 @@ export const AuditSearchFilter = ({ filters, onFiltersChange, hasProjectContexthasProjectContext || filters.some((filter) => filter.property === "project");const valueSuggestions = useMemo(() => {- if (!propertyDef?.suggestions) return [];- if (!typedValue) return propertyDef.suggestions;+ const suggestions = propertyKey === "actor_id" ? actorIdSuggestions : propertyDef?.suggestions;+ if (!suggestions?.length) return [];+ if (!typedValue) return suggestions;const lower = typedValue.toLowerCase();- return propertyDef.suggestions.filter(- (suggestion) =>- suggestion.value.toLowerCase().includes(lower) ||- suggestion.label.toLowerCase().includes(lower)+ return suggestions.filter(+ (s) => s.value.toLowerCase().includes(lower) || s.label.toLowerCase().includes(lower));- }, [propertyDef, typedValue]);+ }, [propertyKey, propertyDef, actorIdSuggestions, typedValue]);const filteredProperties = useMemo(() =>@@ -214,7 +223,10 @@ export const AuditSearchFilter = ({ filters, onFiltersChange, hasProjectContextconst showPropertyDropdown = isOpen && !isTypingValue;const showSuggestionDropdown =- isOpen && isTypingValue && !isFreetext && valueSuggestions.length > 0;+ isOpen &&+ isTypingValue &&+ valueSuggestions.length > 0 &&+ (propertyKey === "actor_id" || !isFreetext);const dropdownRowClass = (active: boolean) =>`flex w-full items-center gap-3 px-3 py-1.5 text-sm transition-colors ${@@ -253,19 +265,36 @@ export const AuditSearchFilter = ({ filters, onFiltersChange, hasProjectContext</span>);+ const actorIdMismatch = useMemo(() => {+ const actorIdFilter = filters.find((f) => f.property === "actor_id");+ // Only warn for values picked from suggestions (they have a label)+ if (!actorIdFilter?.label) return false;+ return !actorIdSuggestions.some((s) => s.value === actorIdFilter.value);+ }, [filters, actorIdSuggestions]);++ const getChipWarning = (filter: AppliedFilter): string | null => {+ if (!hasProjectFilter && PROJECT_DEPENDENT_KEYS.has(filter.property)) {+ return "Requires a project ID filter to take effect";+ }+ if (filter.property === "actor_id" && actorIdMismatch) {+ return "This ID does not match the selected actor type and may not return results";+ }+ return null;+ };+const renderChip = (filter: AppliedFilter, index: number) => {- const isOrphaned = !hasProjectFilter && PROJECT_DEPENDENT_KEYS.has(filter.property);+ const warning = getChipWarning(filter);const chip = (<spankey={`${filter.property}-${filter.value}`}className={`inline-flex shrink-0 items-center gap-1 rounded-md border px-2.5 py-1 font-mono text-xs ${- isOrphaned+ warning? "border-yellow-700/60 bg-yellow-900/20": "border-mineshaft-500 bg-mineshaft-700"}`}>- {isOrphaned && <FontAwesomeIcon icon={faWarning} className="h-2.5 w-2.5 text-yellow-600" />}+ {warning && <FontAwesomeIcon icon={faWarning} className="h-2.5 w-2.5 text-yellow-600" />}<buttontype="button"className="text-bunker-200 transition-colors hover:text-mineshaft-100"@@ -290,13 +319,9 @@ export const AuditSearchFilter = ({ filters, onFiltersChange, hasProjectContext</span>);- if (isOrphaned) {+ if (warning) {return (- <Tooltip- key={`${filter.property}-${filter.value}`}- content="Requires a project ID filter to take effect"- size="sm"- >+ <Tooltip key={`${filter.property}-${filter.value}`} content={warning} size="sm">{chip}</Tooltip>);@@ -418,6 +443,7 @@ export const appliedFiltersToLogFilter = (eventType: EventType[];userAgentType?: UserAgentType;actorType?: ActorType;+ actor?: string;projectId?: string;environment?: string;secretPath?: string;@@ -454,6 +480,9 @@ export const appliedFiltersToLogFilter = (case "secret_key":result.secretKey = value;break;+ case "actor_id":+ result.actor = value;+ break;default:break;}@@ -466,12 +495,14 @@ export const logFilterToAppliedFilters = (filter: {eventType?: EventType[];userAgentType?: UserAgentType;actorType?: ActorType;+ actor?: string;}): AppliedFilter[] => {const chips: AppliedFilter[] = [];filter.eventType?.forEach((eventType) => chips.push({ property: "event", value: eventType }));if (filter.userAgentType) chips.push({ property: "source", value: filter.userAgentType });if (filter.actorType) chips.push({ property: "actor", value: filter.actorType });+ if (filter.actor) chips.push({ property: "actor_id", value: filter.actor });return chips;};diff --git a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsxindex 42800b8c99..72e1b0a40a 100644--- a/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx+++ b/frontend/src/pages/organization/AuditLogsPage/components/LogsSection.tsx@@ -125,7 +125,7 @@ const LogsSectionComponent = ({refetchInterval={refetchInterval}filter={{eventMetadata: logFilter?.eventMetadata,- actor: logFilter?.actor,+ actor: searchDerived.actor || logFilter?.actor,projectId: project?.id || searchDerived.projectId || logFilter?.project?.id,actorType: searchDerived.actorType || presets?.actorType,eventType: