diff --git a/docs/decisions/2026-11-25-audit-log-rows-show-five-records-and-three-lines-of-a-change.md b/docs/decisions/2026-11-25-audit-log-rows-show-five-records-and-three-lines-of-a-change.md new file mode 100644 index 000000000000..917afd96c580 --- /dev/null +++ b/docs/decisions/2026-11-25-audit-log-rows-show-five-records-and-three-lines-of-a-change.md @@ -0,0 +1,28 @@ +# Audit log rows show at most five records and three lines of a change + +- **Status:** Accepted +- **Revisions:** v1 2026-11-25 (initial) +- **Deciders:** Rohit Jain, design review +- **Guard:** `AuditLogList.test.tsx` ("should cap records and say how many are hidden", "should show an update inline as struck-through old → highlighted new") and `AuditLogList.utils.test.ts` (`MAX_RECORDS`) +- **Related:** #38210, #38290, #38686, #38687 + +## Context +The Audit Logs list renders each field change from the event's `changeDescription`. Some values +are unbounded: a description can run to many paragraphs, and a list-valued field such as +`testCaseResultSummary` can hold dozens of objects. Rendered in full, a single row can fill the +screen and push every other event out of view, which defeats a list meant for scanning. + +## Decision +In a list row (`components/AuditLog/AuditLogList`): +- a list-valued field change shows at most `MAX_RECORDS` = **5** records, followed by + "+ N More" for the rest; +- a text value (a description, or either side of an `old → new` update) is clamped to + **three lines**. + +The full value is not available from the list row. The API (`GET /api/v1/audit/logs`) and the +Export JSON are unchanged and always carry the complete value. + +## Consequences +Rows stay scannable, and the page height no longer depends on the size of one change. An auditor +who needs a value beyond the cap or clamp reads it from the Export or the API. Revisit if the page +gains a per-event detail view (the follow-up in #38210), which is the place to show full values. diff --git a/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.component.tsx b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.component.tsx index c0822d3dce1d..b616c12530ce 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.component.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.component.tsx @@ -11,38 +11,33 @@ * limitations under the License. */ -import { Box, Skeleton, Typography } from '@openmetadata/ui-core-components'; -import { NoSearch } from '@openmetadata/ui-core-components/icons'; -import { compact, startCase } from 'lodash'; import { - FC, - isValidElement, - lazy, - ReactNode, - Suspense, - useCallback, - useMemo, -} from 'react'; + Badge, + Box, + OwnerChip, + Skeleton, + Tag, + TagGroup, + TagList, + Typography, +} from '@openmetadata/ui-core-components'; +import { NoSearch } from '@openmetadata/ui-core-components/icons'; +import classNames from 'classnames'; +import { startCase } from 'lodash'; +import { FC, Fragment, ReactNode, useMemo } from 'react'; import { useTranslation } from 'react-i18next'; import { Link } from 'react-router-dom'; import { EntityType } from '../../enums/entity.enum'; import { - ChangeDescription, - FieldChange, -} from '../../generated/type/changeEvent'; -import { getTextFromHtmlString } from '../../utils/BlockEditorPureUtils'; -import { getRelativeTime } from '../../utils/date-time/DateTimeUtils'; + formatDateTime, + getRelativeTime, +} from '../../utils/date-time/DateTimeUtils'; import { getEntityLinkFromType } from '../../utils/EntityLinkUtils'; import { getEntityName } from '../../utils/EntityNameUtils'; import Fqn from '../../utils/Fqn'; -import { - getDomainPath, - getTagPath, - getTeamsWithFqnPath, - getUserPath, -} from '../../utils/RouterUtils'; +import { toOwnerRef } from '../../utils/Owner/ownerConversionUtils'; +import { getUserPath } from '../../utils/RouterUtils'; import { getSettingsLink } from '../../utils/SettingsModalLinkUtils'; -import { isValidJSONString } from '../../utils/StringUtils'; import NoDataPlaceholder from '../common/EmptyPlaceholder/NoDataPlaceholder'; import NoFilteredResultsPlaceholder from '../common/EmptyPlaceholder/NoFilteredResultsPlaceholder'; import NoSearchResultsPlaceholder from '../common/EmptyPlaceholder/NoSearchResultsPlaceholder'; @@ -51,281 +46,289 @@ import { AuditLogListItemProps, AuditLogListProps, } from './AuditLogList.interface'; +import { + ChangeRef, + ChangeRow, + ChangeValue, + CHANGE_ACTION_STYLES, + EVENT_TYPE_COLORS, + findEntityType, + formatCellValue, + getChangeRows, + getEntityRefLink, + getLineageEdge, + getReadableSummary, + isAuthEvent, + isOwnerRef, + LineageEdge, + REF_DOT_CLASSES, +} from './AuditLogList.utils'; + +/** How a value is drawn: plain, or red/struck (old / removed) and green (new) on an update. */ +type ValueTone = 'plain' | 'before' | 'after'; + +type RecordsValue = Extract; + +const LINK_CLASS = + 'tw:font-semibold tw:text-fg-brand-primary tw:hover:underline'; -const RichTextEditorPreviewerV1 = lazy( - () => import('../common/RichTextEditor/RichTextEditorPreviewerV1') -); - -const getFieldLabel = (name?: string) => { - if (!name) { - return ''; - } - const parts = name.split('.'); +const resolveEntityLabel = ( + log: AuditLogListItemProps['log'], + entityFQN?: string +): string | undefined => { + const entityNameLabel = + getEntityName(log.changeEvent?.entity) || + (log.changeEvent?.entity as { name?: string })?.name; + const splitEntityFqn = entityFQN ? Fqn.split(entityFQN).pop() : undefined; - return startCase(parts[parts.length - 1]); + return ( + entityNameLabel || + splitEntityFqn || + log.changeEvent?.entityFullyQualifiedName || + log.entityId + ); }; -const parseValue = (value: unknown): unknown => { - if (value === null || value === undefined) { - return value; - } - if (typeof value === 'string') { - if (isValidJSONString(value)) { - try { - return JSON.parse(value); - } catch { - return value; - } - } - - return value; +const getEntityHref = ( + log: AuditLogListItemProps['log'], + normalizedType?: EntityType, + entityFQN?: string +): string | undefined => { + if (normalizedType === EntityType.USER) { + const userName = + log.changeEvent?.entity?.name ?? + log.changeEvent?.entity?.fullyQualifiedName ?? + entityFQN ?? + log.userName; + + return userName ? getSettingsLink(getUserPath(userName)) : undefined; } - - return value; -}; - -const formatObjectChangeValue = (parsed: object): string => { - const maybeEntity = parsed as { displayName?: string; name?: string }; - if (maybeEntity.displayName || maybeEntity.name) { - return maybeEntity.displayName ?? maybeEntity.name ?? ''; + if (!normalizedType || !entityFQN) { + return undefined; } - return JSON.stringify(parsed); + return getEntityLinkFromType(entityFQN, normalizedType) || undefined; }; -const formatChangeValue = (value: unknown): string => { - const parsed = parseValue(value); - if (parsed === null || parsed === undefined) { - return ''; - } - if (Array.isArray(parsed)) { - return compact(parsed.map((item) => formatChangeValue(item))).join(', '); +/** Inline values of a change line; lists of objects render below it as records instead. */ +const getLineValues = ( + row: ChangeRow +): { value: ChangeValue; tone: ValueTone }[] => { + if (row.newValue?.type === 'records' || row.oldValue?.type === 'records') { + return []; } - if (typeof parsed === 'string') { - const asText = getTextFromHtmlString(parsed); - - return asText || parsed; + if (row.oldValue && row.newValue) { + return [ + { value: row.oldValue, tone: 'before' }, + { value: row.newValue, tone: 'after' }, + ]; } - if (typeof parsed === 'object') { - return formatObjectChangeValue(parsed); + if (row.newValue) { + return [{ value: row.newValue, tone: 'plain' }]; } - return String(parsed); + return row.oldValue ? [{ value: row.oldValue, tone: 'before' }] : []; }; -interface EntityInfo { - fqn: string; - name: string; - displayName?: string; -} - -const extractEntityInfo = (value: unknown): EntityInfo[] => { - const parsed = parseValue(value); - if (!parsed) { - return []; - } - - const items = Array.isArray(parsed) ? parsed : [parsed]; - - return compact( - items.map((item) => { - if (typeof item === 'object' && item !== null) { - const entity = item as { - fullyQualifiedName?: string; - tagFQN?: string; - fqn?: string; - name?: string; - displayName?: string; - }; - const fqn = - entity.fullyQualifiedName ?? - entity.tagFQN ?? - entity.fqn ?? - entity.name; - if (fqn) { - return { - fqn, - name: entity.name ?? Fqn.split(fqn).pop() ?? fqn, - displayName: entity.displayName, - }; - } - } +const RefValue: FC<{ + refs: ChangeRef[]; + label: string; + isStruck: boolean; +}> = ({ refs, label, isStruck }) => { + const tags = refs.filter((ref) => ref.refKind !== 'entity'); + const entities = refs.filter((ref) => ref.refKind === 'entity'); - return null; - }) + return ( + <> + {tags.length > 0 && ( + + + {tags.map((ref) => ( + + {ref.label} + + ))} + + + )} + {entities.map((ref) => + isOwnerRef(ref) && ref.id ? ( + + ) : ( + + {ref.entityType ? `${ref.label} (${ref.entityType})` : ref.label} + + ) + )} + ); }; -const LINKABLE_FIELD_RESOLVERS: Record string> = { - tags: getTagPath, - dataproducts: (fqn) => getEntityLinkFromType(fqn, EntityType.DATA_PRODUCT), - teams: (fqn) => getSettingsLink(getTeamsWithFqnPath(fqn)), - domain: getDomainPath, - owner: getUserPath, - reviewers: getUserPath, - experts: getUserPath, -}; - -const findLinkableFieldKey = (field: string): string | undefined => - Object.keys(LINKABLE_FIELD_RESOLVERS).find( - (key) => field === key || field.endsWith(`.${key}`) - ); - -const isDescriptionField = (fieldName: string): boolean => - fieldName === 'description' || fieldName.endsWith('.description'); +const InlineCell: FC<{ name: string; value: unknown }> = ({ name, value }) => { + const { t } = useTranslation(); + const cell = formatCellValue(name, value); -const getEntityLinkForField = ( - fieldName: string, - entityInfo: EntityInfo -): string | null => { - const field = fieldName.toLowerCase(); - const matchedKey = findLinkableFieldKey(field); + if (cell.color) { + return ( + + {cell.text} + + ); + } - return matchedKey - ? LINKABLE_FIELD_RESOLVERS[matchedKey](entityInfo.fqn) - : null; + return ( + + {cell.isEmpty ? t('label.empty').toLowerCase() : cell.text} + + ); }; -const renderEntityLinks = ( - fieldName: string, - value: unknown, - keyPrefix: string -): ReactNode[] => { - const entities = extractEntityInfo(value); - if (entities.length === 0) { - const plainValue = formatChangeValue(value); +/** `key value, key value` on one line — keys muted, values formatted by key. */ +const InlineEntries: FC<{ entries: [string, unknown][] }> = ({ entries }) => ( + + {entries.map(([key, entryValue], index) => ( + + {key} + + {index < entries.length - 1 && ( + , + )} + + ))} + +); - return plainValue ? [plainValue] : []; - } +const TEXT_TONE_CLASSES: Record = { + plain: '', + before: 'tw:line-through tw:text-utility-error-700', + after: 'tw:text-utility-success-700', +}; - return entities.map((entity) => { - const link = getEntityLinkForField(fieldName, entity); - const label = entity.displayName ?? entity.name; - const entityKey = `${keyPrefix}-${entity.fqn ?? entity.name}`; +/** + * Long values such as descriptions are cut to three lines so one entry cannot fill the list + * (ADR:2026-11-25-audit-log-rows-show-five-records-and-three-lines-of-a-change). + */ +const TextValue: FC<{ text: string; tone: ValueTone }> = ({ text, tone }) => ( + + {text} + +); - if (link) { +const InlineValue: FC<{ + value: ChangeValue; + tone: ValueTone; + label: string; +}> = ({ value, tone, label }) => { + switch (value.type) { + case 'refs': return ( - - {label} - + ); - } - - return {label}; - }); -}; - -const resolveEntityType = (value?: string): EntityType | undefined => { - if (!value) { - return undefined; + case 'keyValue': + return ; + case 'records': + // Shown as records under the line by `RecordList`. + return null; + default: + return ; } - const normalized = value.toLowerCase(); - - return Object.values(EntityType).find( - (entityType) => entityType.toLowerCase() === normalized - ); }; -const resolveEntityLabel = ( - log: AuditLogListItemProps['log'], - entityFQN?: string -): string | undefined => { - const entityNameLabel = - getEntityName(log.changeEvent?.entity) || - (log.changeEvent?.entity as { name?: string })?.name; - const splitEntityFqn = entityFQN ? Fqn.split(entityFQN).pop() : undefined; +const RecordList: FC<{ value: RecordsValue }> = ({ value }) => { + const { t } = useTranslation(); + const hiddenCount = value.totalCount - value.records.length; return ( - entityNameLabel || - splitEntityFqn || - log.changeEvent?.entityFullyQualifiedName || - log.entityId + + {value.records.map((record, index) => ( +
+ +
+ ))} + {hiddenCount > 0 && ( + + {t('label.plus-count-more', { count: hiddenCount })} + + )} +
); }; -const getAuditLogDisplayInfo = ( - log: AuditLogListItemProps['log'], - systemUserLabel: string -) => { - const userName = log.userName || systemUserLabel; - const eventType = log.eventType ? startCase(log.eventType) : ''; - const entityType = log.entityType ?? log.changeEvent?.entityType; - const entityFQN = - log.entityFQN ?? - log.changeEvent?.entityFullyQualifiedName ?? - log.changeEvent?.entity?.fullyQualifiedName; - const entityLabel = resolveEntityLabel(log, entityFQN); - const normalizedType = resolveEntityType(entityType); - - return { - userName, - eventType, - entityType, - entityFQN, - entityLabel, - normalizedType, - timestamp: log.eventTs, - }; -}; - -const getUserEntityLink = ( - log: AuditLogListItemProps['log'], - entityLabel?: string -): ReactNode | null => { - const userNameForLink = - log.changeEvent?.entity?.name ?? - log.changeEvent?.entity?.fullyQualifiedName ?? - log.userName ?? - entityLabel; - if (!userNameForLink) { - return null; - } - - return ( - - {entityLabel ?? userNameForLink} - +const ChangeLine: FC<{ row: ChangeRow }> = ({ row }) => { + const { t } = useTranslation(); + const action = CHANGE_ACTION_STYLES[row.action]; + const values = getLineValues(row); + const records = [row.newValue, row.oldValue].find( + (value): value is RecordsValue => value?.type === 'records' ); -}; - -const getTypedEntityLink = ( - entityFQN?: string, - normalizedType?: EntityType, - entityLabel?: string -): ReactNode | null => { - if (!normalizedType || !entityFQN) { - return null; - } - const link = getEntityLinkFromType(entityFQN, normalizedType); - if (!link) { - return null; - } return ( - - {entityLabel ?? entityFQN} - +
+
+ + {t(action.labelKey)} + + + {`${row.path || t('label.field')}:`} + + {values.map(({ value, tone }, index) => ( + + {index > 0 && →} + + + ))} +
+ {records && } +
); }; -interface AuditLogItemHeaderProps { - userLink: ReactNode; - eventType: string; - impersonatedBy?: string; -} - -const AuditLogItemHeader: FC = ({ - userLink, - eventType, - impersonatedBy, -}) => { +const AuditLogItemHeader: FC<{ + log: AuditLogListItemProps['log']; + userName: string; + entity: ReactNode; +}> = ({ log, userName, entity }) => { const { t } = useTranslation(); return ( @@ -333,341 +336,186 @@ const AuditLogItemHeader: FC = ({ align="center" data-testid="item-header" direction="row" - gap={1} + gap={2} wrap="wrap"> - {userLink} - – - - {eventType} - - {impersonatedBy && ( - <> - – - - {t('label.impersonated-by-with-colon')} - {' '} + {log.userName ? ( + + {userName} + + ) : ( + {userName} + )} + {log.actorType === 'BOT' && ( + + {t('label.bot')} + + )} + – + {log.eventType && ( + + {startCase(log.eventType)} + + )} + {log.impersonatedBy && ( + + {t('label.impersonated-by-with-colon')}{' '} - {impersonatedBy} + className={LINK_CLASS} + to={getSettingsLink(getUserPath(log.impersonatedBy))}> + {log.impersonatedBy} - + )} + {entity} ); }; -interface AuditLogItemDescriptionProps { - descriptionNodes: ReactNode[]; - eventType: string; - entityLink: ReactNode; -} - -const AuditLogItemDescription: FC = ({ - descriptionNodes, - eventType, - entityLink, -}) => ( -
- {descriptionNodes.length > 0 ? ( -
- {descriptionNodes.map((node, idx) => ( -
- {node} - {idx < descriptionNodes.length - 1 && ( - ; - )} -
- ))} -
+const AuditLogItemEntity: FC<{ + entityLabel: string; + entityFQN?: string; + entityHref?: string; +}> = ({ entityLabel, entityFQN, entityHref }) => ( + + {entityHref ? ( + + {entityLabel} + ) : ( - - - {eventType} - - {entityLink} - + {entityLabel} )} -
+ {entityFQN && entityFQN !== entityLabel && ( + + ({entityFQN}) + + )} + ); -interface AuditLogItemMetaProps { - entityType?: string; - timestamp?: number; -} +const EntityRefLink: FC<{ entityRef: ChangeRef }> = ({ entityRef }) => { + const href = getEntityRefLink(entityRef); + + return href ? ( + + {entityRef.label} + + ) : ( + {entityRef.label} + ); +}; -const AuditLogItemMeta: FC = ({ +const AuditLogItemLineage: FC<{ edge: LineageEdge }> = ({ edge }) => ( + + + → + + +); + +const AuditLogItemMeta: FC<{ entityType?: string; timestamp?: number }> = ({ entityType, timestamp, }) => ( + gap={2} + wrap="wrap"> {entityType && ( {startCase(entityType)} )} {entityType && timestamp && ( - - | - + ); -const AuditLogListItem: FC = ({ log }) => { - const { t } = useTranslation(); - - const { - userName, - eventType, - entityType, - entityFQN, - entityLabel, - normalizedType, - timestamp, - } = getAuditLogDisplayInfo(log, t('label.system')); - - const isLinkableField = useCallback((fieldName?: string): boolean => { - if (!fieldName) { - return false; - } - const field = fieldName.toLowerCase(); - const linkableFields = [ - 'tags', - 'dataproducts', - 'teams', - 'domain', - 'owner', - 'reviewers', - 'experts', - ]; - - return linkableFields.some((f) => field === f || field.endsWith(`.${f}`)); - }, []); +/** What the event happened to: the lineage edge, the changed asset, or nothing for login/logout. */ +const AuditLogItemSubject: FC<{ + log: AuditLogListItemProps['log']; + entityType?: string; + entityFQN?: string; + entityLabel?: string; +}> = ({ log, entityType, entityFQN, entityLabel }) => { + const lineageEdge = getLineageEdge(log); + if (lineageEdge) { + return ; + } + // A login/logout's entity is the actor already shown in the header. + if (!entityLabel || isAuthEvent(log.eventType)) { + return null; + } - const isUserField = useCallback((fieldName?: string): boolean => { - if (!fieldName) { - return false; - } - const field = fieldName.toLowerCase(); - const userFields = ['owner', 'reviewers', 'experts']; - - return userFields.some((f) => field === f || field.endsWith(`.${f}`)); - }, []); - - const renderChangeValue = useCallback( - (change: FieldChange, value: unknown, keyPrefix: string): ReactNode => { - if (!value) { - return null; - } - - const fieldName = change.name ?? ''; - - if (isLinkableField(fieldName)) { - const links = renderEntityLinks(fieldName, value, keyPrefix); - if (links.length > 0) { - const showProfilePic = isUserField(fieldName); - - return ( - - {links.map((link, idx) => { - const entities = extractEntityInfo(value); - const entity = entities[idx]; - - return ( - - {showProfilePic && entity && ( - - )} - {link} - {idx < links.length - 1 && ', '} - - ); - })} - - ); - } - } - - if (isDescriptionField(fieldName)) { - const markdown = - typeof value === 'string' ? value : formatChangeValue(value); - - return ( - {formatChangeValue(value)}}> - - - ); - } - - return {formatChangeValue(value)}; - }, - [isLinkableField, isUserField] + return ( + ); +}; - const getChangeDetails = useCallback( - (changeDescription?: ChangeDescription): ReactNode[] => { - if (!changeDescription) { - return []; - } - - const details: ReactNode[] = []; - const addedLabel = startCase(t('label.added-lowercase')); - const updatedLabel = startCase(t('label.updated-lowercase')); - const removedLabel = startCase(t('label.removed-lowercase')); - const fallbackField = t('label.field', { defaultValue: 'field' }); - - (changeDescription.fieldsAdded ?? []).forEach((change) => { - const label = getFieldLabel(change.name); - const valueNode = renderChangeValue( - change, - change.newValue, - `added-${change.name}` - ); - - details.push( - - - {addedLabel} - {' '} - - {label || fallbackField} - - {valueNode && <>: {valueNode}} - - ); - }); - - (changeDescription.fieldsUpdated ?? []) - .filter((change) => change.name !== 'deleted') - .forEach((change) => { - const label = getFieldLabel(change.name); - const oldValueNode = renderChangeValue( - change, - change.oldValue, - `updated-old-${change.name}` - ); - const newValueNode = renderChangeValue( - change, - change.newValue, - `updated-new-${change.name}` - ); - const hasValueChange = oldValueNode || newValueNode; - - details.push( - - - {updatedLabel} - {' '} - - {label || fallbackField} - - {hasValueChange && ( - <> - : {oldValueNode} - {oldValueNode && newValueNode && ' → '} - {newValueNode} - - )} - - ); - }); - - (changeDescription.fieldsDeleted ?? []).forEach((change) => { - const label = getFieldLabel(change.name); - const valueNode = renderChangeValue( - change, - change.oldValue, - `deleted-${change.name}` - ); - - details.push( - - - {removedLabel} - {' '} - - {label || fallbackField} - - {valueNode && <>: {valueNode}} - - ); - }); - - return details; - }, - [t, renderChangeValue] +const AuditLogListItem: FC = ({ log }) => { + const { t } = useTranslation(); + const entityType = log.entityType ?? log.changeEvent?.entityType; + const entityFQN = + log.entityFQN ?? + log.changeEvent?.entityFullyQualifiedName ?? + log.changeEvent?.entity?.fullyQualifiedName; + const entityLabel = resolveEntityLabel(log, entityFQN); + const userName = log.userName || t('label.system'); + const changeRows = useMemo( + () => getChangeRows(log.changeEvent?.changeDescription), + [log.changeEvent?.changeDescription] ); - - const descriptionNodes = useMemo((): ReactNode[] => { - if (log.summary) { - return [{log.summary}]; - } - if (log.changeEvent?.changeDescription) { - return getChangeDetails(log.changeEvent.changeDescription); - } - - return []; - }, [log, getChangeDetails]); - - const entityLink = useMemo(() => { - if (normalizedType === EntityType.USER) { - const userLinkNode = getUserEntityLink(log, entityLabel); - if (userLinkNode) { - return userLinkNode; - } - } - - const typedLinkNode = getTypedEntityLink( - entityFQN, - normalizedType, - entityLabel - ); - if (typedLinkNode) { - return typedLinkNode; - } - - return ( - {entityLabel ?? entityFQN ?? '--'} - ); - }, [normalizedType, entityFQN, entityLabel, log]); - - // Built per render: `getSettingsLink` reads the current mode and search. - const userLink = log.userName ? ( - - {userName} - - ) : ( - {userName} + const summary = getReadableSummary(log); + const entity = ( + ); return ( @@ -675,7 +523,7 @@ const AuditLogListItem: FC = ({ log }) => { className="tw:p-4 tw:border-b tw:border-primary tw:transition-colors tw:hover:bg-secondary tw:last:border-b-0" data-testid="audit-log-list-item" direction="row" - gap={2}> + gap={3}>
= ({ log }) => { width="32" />
- - - - + + + + {changeRows.length > 0 + ? changeRows.map((row) => ) + : summary && {summary}} + + ); }; +const AuditLogListSkeleton: FC = () => ( +
+ {[1, 2, 3, 4, 5].map((i) => ( + + + + + + + + + ))} +
+); + const AuditLogList: FC = ({ logs, isLoading, @@ -714,34 +579,7 @@ const AuditLogList: FC = ({ const { t } = useTranslation(); if (isLoading) { - return ( -
-
- -
-
- {[1, 2, 3, 4, 5].map((i) => ( - - - - - - - - - ))} -
-
- ); + return ; } if (logs.length === 0) { @@ -758,7 +596,7 @@ const AuditLogList: FC = ({ ] : undefined; - let emptyContent: React.ReactNode; + let emptyContent: ReactNode; if (hasActiveSearch) { emptyContent = ( @@ -796,14 +634,12 @@ const AuditLogList: FC = ({ return (
-
- {logs.map((log, index) => ( - - ))} -
+ {logs.map((log, index) => ( + + ))}
); }; diff --git a/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.test.tsx b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.test.tsx index c81c6df5f169..1e4d89be5dc4 100644 --- a/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.test.tsx +++ b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.test.tsx @@ -11,10 +11,14 @@ * limitations under the License. */ -import { render, screen } from '@testing-library/react'; +import { render, screen, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { ChangeEvent, EventType } from '../../generated/type/changeEvent'; import { AuditLogEntry } from '../../types/auditLogs.interface'; +import { + formatDateTime, + getRelativeTime, +} from '../../utils/date-time/DateTimeUtils'; import AuditLogList from './AuditLogList.component'; // Helper to create partial ChangeEvent mocks without strict type enforcement @@ -54,754 +58,544 @@ const renderWithRouter = (ui: React.ReactElement) => { }; describe('AuditLogList', () => { - const mockLogs: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now() - 60000, - eventType: EventType.EntityCreated, - userName: 'admin', - entityType: 'table', - entityFQN: 'sample_data.ecommerce_db.shopify.orders', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityCreated, - entityType: 'table', - entityFullyQualifiedName: 'sample_data.ecommerce_db.shopify.orders', - entity: { - id: 'table-1', - name: 'orders', - displayName: 'Orders', - fullyQualifiedName: 'sample_data.ecommerce_db.shopify.orders', - }, - changeDescription: { - fieldsAdded: [], - fieldsUpdated: [], - fieldsDeleted: [], - }, - timestamp: Date.now() - 60000, - }), - }, - { - id: 2, - changeEventId: 'event-2', - eventTs: Date.now() - 120000, + const NOW = Date.now(); + const TABLE_FQN = 'sample_data.ecommerce_db.shopify.dim_customer'; + + const updateLog = ( + changeDescription: Partial>, + overrides: Partial = {} + ): AuditLogEntry => ({ + id: 1, + eventTs: NOW, + eventType: EventType.EntityUpdated, + userName: 'admin', + actorType: 'USER', + entityType: 'table', + entityFQN: TABLE_FQN, + summary: 'Server summary that must not win over field changes', + changeEvent: mockChangeEvent({ eventType: EventType.EntityUpdated, - userName: 'test_user', entityType: 'table', - entityFQN: 'sample_data.ecommerce_db.shopify.products', - changeEvent: mockChangeEvent({ - id: 'ce-2', - eventType: EventType.EntityUpdated, - entityType: 'table', - entityFullyQualifiedName: 'sample_data.ecommerce_db.shopify.products', - entity: { - id: 'table-2', - name: 'products', - displayName: 'Products', - fullyQualifiedName: 'sample_data.ecommerce_db.shopify.products', - }, - changeDescription: { - fieldsAdded: [ - { - name: 'tags', - newValue: JSON.stringify([ - { tagFQN: 'PII.Sensitive', name: 'Sensitive' }, - ]), - }, - ], - fieldsUpdated: [], - fieldsDeleted: [], - }, - timestamp: Date.now() - 120000, - }), - }, - ]; - - beforeEach(() => { - jest.clearAllMocks(); + changeDescription: { + fieldsAdded: [], + fieldsUpdated: [], + fieldsDeleted: [], + ...changeDescription, + }, + }), + ...overrides, }); - it('should render loading state with skeleton loaders', () => { - renderWithRouter(); + const createdLog: AuditLogEntry = { + id: 10, + eventTs: NOW - 60000, + eventType: EventType.EntityCreated, + userName: 'admin', + entityType: 'glossary', + entityFQN: 'AuditDemoGlossary', + summary: 'Created glossary: AuditDemoGlossary', + }; - const skeletons = screen.getAllByTestId('skeleton'); + const renderLogs = (logs: AuditLogEntry[]) => + renderWithRouter(); + + it('should render the skeleton while loading, without the loaded list', () => { + renderWithRouter(); - expect(skeletons.length).toBeGreaterThan(0); expect(screen.getByTestId('audit-log-list-skeleton')).toBeInTheDocument(); + expect(screen.getAllByTestId('skeleton').length).toBeGreaterThan(0); // Playwright treats `audit-log-list` as "loaded", so loading must not render it. expect(screen.queryByTestId('audit-log-list')).not.toBeInTheDocument(); }); - it('should render empty state with EmptyPlaceholder when no logs', () => { - renderWithRouter(); + it('should render the empty state when there are no logs', () => { + renderLogs([]); expect(screen.getByTestId('empty-placeholder')).toBeInTheDocument(); }); - it('should render list with items', () => { - renderWithRouter(); - - expect(screen.getByTestId('audit-log-list')).toBeInTheDocument(); - - const listItems = screen.getAllByTestId('audit-log-list-item'); - - expect(listItems).toHaveLength(2); - }); - - it('should display profile pictures for each log entry', () => { - renderWithRouter(); + it('should render one row per log with avatar and user link', () => { + renderLogs([createdLog, updateLog({}, { id: 2, userName: 'test_user' })]); - const profilePictures = screen.getAllByTestId('profile-picture'); - - expect(profilePictures).toHaveLength(2); + expect(screen.getAllByTestId('audit-log-list-item')).toHaveLength(2); + expect(screen.getAllByTestId('profile-picture')).toHaveLength(2); + expect(screen.getByRole('link', { name: 'admin' })).toHaveAttribute( + 'href', + '/users/admin' + ); + expect(screen.getByRole('link', { name: 'test_user' })).toHaveAttribute( + 'href', + '/users/test_user' + ); }); - it('should display user names as links', () => { - renderWithRouter(); - - const adminLink = screen.getByRole('link', { name: 'admin' }); - - expect(adminLink).toHaveAttribute('href', '/users/admin'); - - const testUserLink = screen.getByRole('link', { name: 'test_user' }); - - expect(testUserLink).toHaveAttribute('href', '/users/test_user'); + it.each([ + [EventType.EntityCreated, 'Entity Created'], + [EventType.EntityUpdated, 'Entity Updated'], + [EventType.EntityFieldsChanged, 'Entity Fields Changed'], + [EventType.EntitySoftDeleted, 'Entity Soft Deleted'], + [EventType.EntityDeleted, 'Entity Deleted'], + [EventType.EntityRestored, 'Entity Restored'], + [EventType.EntityLineageAdded, 'Entity Lineage Added'], + [EventType.EntityLineageUpdated, 'Entity Lineage Updated'], + [EventType.EntityLineageDeleted, 'Entity Lineage Deleted'], + [EventType.UserLogin, 'User Login'], + [EventType.UserLogout, 'User Logout'], + ])('should label the %s event as "%s"', (eventType, label) => { + renderLogs([{ id: 1, eventTs: NOW, eventType, userName: 'admin' }]); + + expect(screen.getByTestId('event-type')).toHaveTextContent(label); }); - it('should display event types', () => { - renderWithRouter(); + it('should show the entity type and the exact date-time with the relative time', () => { + renderLogs([createdLog]); - const eventTypes = screen.getAllByTestId('event-type'); - - expect(eventTypes).toHaveLength(2); - expect(eventTypes[0]).toHaveTextContent('Entity Created'); - expect(eventTypes[1]).toHaveTextContent('Entity Updated'); + expect(screen.getByTestId('entity-type-badge')).toHaveTextContent( + 'Glossary' + ); + expect(screen.getByTestId('timestamp')).toHaveTextContent( + `${formatDateTime(createdLog.eventTs)} · ${getRelativeTime( + createdLog.eventTs + )}` + ); }); - it('should display entity type badges', () => { - renderWithRouter(); - - const entityTypeBadges = screen.getAllByTestId('entity-type-badge'); + it('should show the bot badge and the impersonating user', () => { + renderLogs([ + updateLog( + { fieldsAdded: [{ name: 'description', newValue: 'x' }] }, + { userName: 'ingestion-bot', actorType: 'BOT', impersonatedBy: 'jane' } + ), + ]); - expect(entityTypeBadges).toHaveLength(2); - expect(entityTypeBadges[0]).toHaveTextContent('Table'); + expect(screen.getByTestId('bot-badge')).toHaveTextContent('label.bot'); + expect(screen.getByTestId('impersonated-by')).toHaveTextContent('jane'); + expect(screen.getByRole('link', { name: 'jane' })).toHaveAttribute( + 'href', + '/users/jane' + ); }); - it('should display relative timestamps', () => { - renderWithRouter(); - - const timestamps = screen.getAllByTestId('timestamp'); + it('should show the summary for events without field changes', () => { + renderLogs([createdLog]); - expect(timestamps).toHaveLength(2); + expect(screen.getByTestId('description-content')).toHaveTextContent( + 'Created glossary: AuditDemoGlossary' + ); + expect(screen.queryByTestId('change-row')).not.toBeInTheDocument(); + // The entity name is its FQN, so the FQN is not repeated beside it. + expect(screen.getByTestId('affected-entity')).toHaveTextContent( + 'AuditDemoGlossary' + ); + expect(screen.queryByTestId('affected-entity-fqn')).not.toBeInTheDocument(); }); - it('should render tag links when tags are added', () => { - const logsWithTags: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'table', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [ - { - name: 'tags', - newValue: JSON.stringify([ - { tagFQN: 'PII.Sensitive', name: 'Sensitive' }, - ]), - }, - ], - fieldsUpdated: [], - fieldsDeleted: [], + it('should show the affected asset with its link and FQN, and the column path', () => { + renderLogs([ + updateLog({ + fieldsAdded: [ + { + name: 'columns.customer_id.tags', + newValue: JSON.stringify([ + { tagFQN: 'PII.Sensitive', name: 'Sensitive' }, + ]), }, - timestamp: Date.now(), - }), - }, - ]; - - renderWithRouter(); - - const tagLink = screen.getByRole('link', { name: 'Sensitive' }); - - expect(tagLink).toHaveAttribute('href', '/tags/PII.Sensitive'); - }); - - it('should render data product links when data products are added', () => { - const logsWithDataProduct: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'table', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [ - { - name: 'dataProducts', - newValue: JSON.stringify([ - { - fullyQualifiedName: 'sales-dp', - name: 'Sales Data Product', - displayName: 'Sales Data Product', - }, - ]), - }, - ], - fieldsUpdated: [], - fieldsDeleted: [], - }, - timestamp: Date.now(), - }), - }, - ]; + ], + }), + ]); - renderWithRouter( - + expect(screen.getByRole('link', { name: 'dim_customer' })).toHaveAttribute( + 'href', + `/table/${TABLE_FQN}` + ); + expect(screen.getByTestId('affected-entity-fqn')).toHaveTextContent( + `(${TABLE_FQN})` + ); + expect(screen.getByTestId('change-action')).toHaveTextContent( + 'label.added' + ); + expect(screen.getByTestId('change-field-path')).toHaveTextContent( + 'Columns › customer_id › Tags:' + ); + expect(screen.getByTestId('description-content')).toHaveTextContent( + 'PII.Sensitive' + ); + expect(screen.getByTestId('description-content')).not.toHaveTextContent( + 'Server summary' ); - - const dpLink = screen.getByRole('link', { name: 'Sales Data Product' }); - - expect(dpLink).toHaveAttribute('href', '/dataProduct/sales-dp'); }); - it('should render domain links when domain is updated', () => { - const logsWithDomain: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'table', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [ + it('should render tags, tiers, glossary terms and domains as core Tags', () => { + renderLogs([ + updateLog({ + fieldsAdded: [ + { + name: 'tags', + newValue: JSON.stringify([ + { tagFQN: 'Tier.Tier1', name: 'Tier1' }, + { tagFQN: 'PII.Sensitive', name: 'Sensitive' }, + { tagFQN: 'Business.Revenue', source: 'Glossary' }, + ]), + }, + { + name: 'domains', + newValue: JSON.stringify([ { - name: 'domain', - newValue: JSON.stringify({ - fullyQualifiedName: 'Engineering', - name: 'Engineering', - displayName: 'Engineering Domain', - }), + type: 'domain', + name: 'Customer360', + fullyQualifiedName: 'Customer360', + displayName: 'Customer 360', }, - ], - fieldsUpdated: [], - fieldsDeleted: [], + ]), }, - timestamp: Date.now(), - }), - }, - ]; - - renderWithRouter(); + ], + }), + ]); - const domainLink = screen.getByRole('link', { name: 'Engineering Domain' }); + const tags = screen.getAllByRole('row'); - expect(domainLink).toHaveAttribute('href', '/domain/Engineering'); + expect(tags.map((tag) => tag.textContent)).toEqual([ + 'Tier1', + 'PII.Sensitive', + 'Business.Revenue', + 'Customer 360', + ]); + expect(screen.queryByTestId('change-ref')).not.toBeInTheDocument(); }); - it('should render owner links when owner is added', () => { - const logsWithOwner: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'table', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [ + it('should show added and removed owners with the core OwnerChip', () => { + renderLogs([ + updateLog({ + fieldsAdded: [ + { + name: 'owners', + newValue: JSON.stringify([ + { id: 'u-1', type: 'user', name: 'admin' }, + ]), + }, + ], + fieldsDeleted: [ + { + name: 'owners', + oldValue: JSON.stringify([ { - name: 'owner', - newValue: JSON.stringify({ - fullyQualifiedName: 'john_doe', - name: 'john_doe', - displayName: 'John Doe', - }), + id: 't-1', + type: 'team', + name: 'Engineering', + displayName: 'Engineering Team', }, - ], - fieldsUpdated: [], - fieldsDeleted: [], + ]), }, - timestamp: Date.now(), - }), - }, - ]; - - renderWithRouter(); + ], + }), + ]); - const ownerLink = screen.getByRole('link', { name: 'John Doe' }); + const actions = screen.getAllByTestId('change-action'); - expect(ownerLink).toHaveAttribute('href', '/users/john_doe'); + expect(actions[0]).toHaveTextContent('label.added'); + expect(actions[1]).toHaveTextContent('label.removed'); + expect(screen.getByTestId('admin')).toHaveTextContent('admin'); + expect( + screen.getByTestId('Engineering Team').closest('.tw\\:line-through') + ).not.toBeNull(); + expect( + screen.getByTestId('admin').closest('.tw\\:line-through') + ).toBeNull(); + expect(screen.queryByTestId('change-ref')).not.toBeInTheDocument(); }); - it('should render profile picture for owner field changes', () => { - const logsWithOwner: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'table', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [ + it('should show other entity references as linked chips with their type', () => { + renderLogs([ + updateLog({ + fieldsAdded: [ + { + name: 'dashboards', + newValue: JSON.stringify([ { - name: 'owner', - newValue: JSON.stringify({ - fullyQualifiedName: 'john_doe', - name: 'john_doe', - displayName: 'John Doe', - }), + id: 'd-1', + type: 'dashboard', + name: 'sales', + fullyQualifiedName: 'looker.sales', }, - ], - fieldsUpdated: [], - fieldsDeleted: [], + ]), }, - timestamp: Date.now(), - }), - }, - ]; - - renderWithRouter(); + ], + }), + ]); - const profilePictures = screen.getAllByTestId('profile-picture'); + const chip = screen.getByTestId('change-ref'); - expect(profilePictures.length).toBeGreaterThanOrEqual(2); + expect(chip).toHaveTextContent('sales (dashboard)'); + expect(chip).toHaveAttribute('href', '/dashboard/looker.sales'); }); - it('should render teams links when teams are added', () => { - const logsWithTeams: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'user', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'user', - changeDescription: { - fieldsAdded: [ - { - name: 'teams', - newValue: JSON.stringify([ - { - fullyQualifiedName: 'Engineering', - name: 'Engineering', - displayName: 'Engineering Team', - }, - ]), - }, - ], - fieldsUpdated: [], - fieldsDeleted: [], + it('should show an update inline as struck-through old → highlighted new', () => { + renderLogs([ + updateLog({ + fieldsUpdated: [ + { + name: 'columns.customer_id.description', + oldValue: '

The ID of the customer.

', + newValue: 'Unique customer identifier.', }, - timestamp: Date.now(), - }), - }, - ]; - - renderWithRouter(); + ], + }), + ]); - const teamLink = screen.getByRole('link', { name: 'Engineering Team' }); + const row = screen.getByTestId('change-row'); - expect(teamLink).toHaveAttribute( - 'href', - '/settings/members/teams/Engineering' + expect(row).toHaveTextContent( + 'Columns › customer_id › Description:The ID of the customer.→Unique customer identifier.' ); - }); - - it('should display summary when available', () => { - const logsWithSummary: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityCreated, - userName: 'admin', - entityType: 'table', - summary: 'Created table orders with 5 columns', - }, - ]; - renderWithRouter(); + const [before, after] = within(row).getAllByTestId('change-text'); - expect( - screen.getByText('Created table orders with 5 columns') - ).toBeInTheDocument(); + expect(before).toHaveTextContent('The ID of the customer.'); + expect(before).toHaveClass('tw:line-through'); + expect(after).toHaveTextContent('Unique customer identifier.'); + // Long descriptions are cut to three lines on both sides of the change. + expect(before).toHaveClass('tw:line-clamp-3'); + expect(after).toHaveClass('tw:line-clamp-3'); }); - it('should display System for logs without userName', () => { - const systemLogs: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - entityType: 'table', - }, - ]; - - renderWithRouter(); + it('should keep false as a real new value and unquote quoted column names', () => { + renderLogs([ + updateLog({ + fieldsUpdated: [ + { name: 'disabled', oldValue: true, newValue: false }, + { + name: 'columns."order.id".dataType', + oldValue: 'INT', + newValue: 'BIGINT', + }, + ], + }), + ]); - const profilePictures = screen.getAllByTestId('profile-picture'); + const [disabledRow, dataTypeRow] = screen.getAllByTestId('change-row'); - expect(profilePictures[0]).toHaveTextContent('label.system'); + expect(disabledRow).toHaveTextContent('Disabled:true→false'); + expect(dataTypeRow).toHaveTextContent( + 'Columns › order.id › Data Type:INT→BIGINT' + ); }); - it('should render multiple field changes', () => { - const logsWithMultipleChanges: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'table', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [ - { - name: 'tags', - newValue: JSON.stringify([ - { tagFQN: 'PII.Sensitive', name: 'Sensitive' }, - ]), - }, - ], - fieldsUpdated: [ + it('should show one inline record per object in a list', () => { + const resultTime = 1795564824021; + renderLogs([ + updateLog({ + fieldsUpdated: [ + { + name: 'testCaseResultSummary', + newValue: JSON.stringify([ { - name: 'description', - oldValue: 'Old description', - newValue: 'New description', + status: 'Aborted', + timestamp: resultTime, + testCaseName: 'orders_row_count', }, - ], - fieldsDeleted: [], + ]), }, - timestamp: Date.now(), - }), - }, - ]; + ], + }), + ]); - renderWithRouter( - + expect(screen.getByTestId('change-row')).toHaveTextContent( + 'Test Case Result Summary:' ); - const listItem = screen.getByTestId('audit-log-list-item'); + const record = screen.getByTestId('change-record'); - expect(listItem.textContent).toMatch(/Tags/i); - expect(listItem.textContent).toMatch(/Description/i); + expect(record).toHaveTextContent( + `statusAborted,timestamp${formatDateTime( + resultTime + )},testCaseNameorders_row_count` + ); }); - it('should render field deletions', () => { - const logsWithDeletions: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'table', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [], - fieldsUpdated: [], - fieldsDeleted: [ - { - name: 'tags', - oldValue: JSON.stringify([ - { tagFQN: 'PII.Sensitive', name: 'Sensitive' }, - ]), - }, - ], + it('should show only the new records, without an arrow, when both sides are lists', () => { + renderLogs([ + updateLog({ + fieldsUpdated: [ + { + name: 'testCaseResultSummary', + oldValue: JSON.stringify([ + { status: 'Failed', testCaseName: 'old_case' }, + ]), + newValue: JSON.stringify([ + { status: 'Success', testCaseName: 'new_case' }, + ]), }, - timestamp: Date.now(), - }), - }, - ]; + ], + }), + ]); - renderWithRouter( - - ); + const row = screen.getByTestId('change-row'); - expect(screen.getByText(/Tags/i)).toBeInTheDocument(); + expect(row).not.toHaveTextContent('→'); + expect(screen.getByTestId('change-record')).toHaveTextContent('new_case'); + expect(row).not.toHaveTextContent('old_case'); }); - it('should render reviewers links when reviewers are added', () => { - const logsWithReviewers: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'glossaryTerm', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'glossaryTerm', - changeDescription: { - fieldsAdded: [ - { - name: 'reviewers', - newValue: JSON.stringify([ - { - fullyQualifiedName: 'jane_doe', - name: 'jane_doe', - displayName: 'Jane Doe', - }, - ]), - }, - ], - fieldsUpdated: [], - fieldsDeleted: [], - }, - timestamp: Date.now(), - }), - }, - ]; - - renderWithRouter( - - ); - - const reviewerLink = screen.getByRole('link', { name: 'Jane Doe' }); + it('should cap records and say how many are hidden', () => { + const rows = Array.from({ length: 7 }, (_, index) => ({ + name: `row-${index}`, + })); + renderLogs([ + updateLog({ + fieldsAdded: [{ name: 'results', newValue: JSON.stringify(rows) }], + }), + ]); - expect(reviewerLink).toHaveAttribute('href', '/users/jane_doe'); + expect(screen.getAllByTestId('change-record')).toHaveLength(5); + expect(screen.getByText('label.plus-count-more')).toBeInTheDocument(); }); - it('should render experts links when experts are added', () => { - const logsWithExperts: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'domain', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'domain', - changeDescription: { - fieldsAdded: [ - { - name: 'experts', - newValue: JSON.stringify([ - { - fullyQualifiedName: 'expert_user', - name: 'expert_user', - displayName: 'Expert User', - }, - ]), - }, - ], - fieldsUpdated: [], - fieldsDeleted: [], + it('should render an object inline as key value pairs', () => { + renderLogs([ + updateLog({ + fieldsUpdated: [ + { + name: 'pipelineStatus', + newValue: JSON.stringify({ + runId: 'b7f39045-3277-417e-98e8-dbac25cf4544', + config: {}, + pipelineState: 'success', + }), }, - timestamp: Date.now(), - }), - }, - ]; - - renderWithRouter(); + ], + }), + ]); - const expertLink = screen.getByRole('link', { name: 'Expert User' }); + const row = screen.getByTestId('change-row'); - expect(expertLink).toHaveAttribute('href', '/users/expert_user'); + expect(row).toHaveTextContent( + 'Pipeline Status:runIdb7f39045…,configlabel.empty,pipelineStatesuccess' + ); }); - it('should render profile pictures for reviewers', () => { - const logsWithReviewers: AuditLogEntry[] = [ - { - id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'glossaryTerm', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'glossaryTerm', - changeDescription: { - fieldsAdded: [ - { - name: 'reviewers', - newValue: JSON.stringify([ - { - fullyQualifiedName: 'reviewer1', - name: 'reviewer1', - displayName: 'Reviewer One', - }, - ]), - }, - ], - fieldsUpdated: [], - fieldsDeleted: [], - }, - timestamp: Date.now(), - }), - }, - ]; + it('should fall back to the summary when the only change is the deleted flag', () => { + renderLogs([ + updateLog( + { + fieldsUpdated: [{ name: 'deleted', oldValue: false, newValue: true }], + }, + { + eventType: EventType.EntitySoftDeleted, + summary: 'Soft deleted table: svc.db.schema.orders', + } + ), + ]); - renderWithRouter( - + expect(screen.getByTestId('description-content')).toHaveTextContent( + 'Soft deleted table: svc.db.schema.orders' ); - - const profilePictures = screen.getAllByTestId('profile-picture'); - - expect(profilePictures.length).toBeGreaterThanOrEqual(2); + expect(screen.queryByTestId('change-row')).not.toBeInTheDocument(); }); - it('should render field updates with old and new values', () => { - const logsWithUpdates: AuditLogEntry[] = [ + it('should show a lineage edge as linked from → to, without the raw summary', () => { + renderLogs([ { id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityUpdated, + eventTs: NOW, + eventType: EventType.EntityLineageAdded, userName: 'admin', - entityType: 'table', + entityType: 'lineage', + entityFQN: 'svc.db.schema.customer--upstream-->svc.db.schema.orders', + summary: 'entityLineageAdded', changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'table', - changeDescription: { - fieldsAdded: [], - fieldsUpdated: [ - { - name: 'owner', - oldValue: JSON.stringify({ - fullyQualifiedName: 'old_owner', - name: 'old_owner', - displayName: 'Old Owner', - }), - newValue: JSON.stringify({ - fullyQualifiedName: 'new_owner', - name: 'new_owner', - displayName: 'New Owner', - }), - }, - ], - fieldsDeleted: [], - }, - timestamp: Date.now(), + eventType: EventType.EntityLineageAdded, + entityType: 'lineage', + entity: JSON.stringify({ + fromEntity: { + type: 'table', + name: 'customer', + fullyQualifiedName: 'svc.db.schema.customer', + }, + toEntity: { + type: 'table', + name: 'orders', + fullyQualifiedName: 'svc.db.schema.orders', + }, + }), }), }, - ]; - - renderWithRouter(); + ]); - expect(screen.getByRole('link', { name: 'Old Owner' })).toBeInTheDocument(); - expect(screen.getByRole('link', { name: 'New Owner' })).toBeInTheDocument(); + expect(screen.getByTestId('affected-entity')).toHaveTextContent( + 'customer→orders' + ); + expect(screen.getByRole('link', { name: 'customer' })).toHaveAttribute( + 'href', + '/table/svc.db.schema.customer' + ); + expect(screen.getByRole('link', { name: 'orders' })).toHaveAttribute( + 'href', + '/table/svc.db.schema.orders' + ); + expect(screen.getByTestId('description-content')).toBeEmptyDOMElement(); }); - it('should render entity link for table entity type', () => { - const logsWithTable: AuditLogEntry[] = [ + it('should not repeat the actor as the affected entity on login events', () => { + renderLogs([ { id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), - eventType: EventType.EntityCreated, + eventTs: NOW, + eventType: EventType.UserLogin, userName: 'admin', - entityType: 'table', - entityFQN: 'sample_data.ecommerce_db.shopify.orders', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityCreated, - entityType: 'table', - entityFullyQualifiedName: 'sample_data.ecommerce_db.shopify.orders', - entity: { - id: 'table-1', - name: 'orders', - displayName: 'Orders Table', - fullyQualifiedName: 'sample_data.ecommerce_db.shopify.orders', - }, - changeDescription: { - fieldsAdded: [], - fieldsUpdated: [], - fieldsDeleted: [], - }, - timestamp: Date.now(), - }), + entityType: 'user', + entityFQN: 'admin', + summary: 'User logged in', }, - ]; + ]); - renderWithRouter(); + expect(screen.getByText('User logged in')).toBeInTheDocument(); + expect(screen.queryByTestId('affected-entity')).not.toBeInTheDocument(); + }); - const entityLink = screen.getByRole('link', { name: 'Orders Table' }); + it('should link a user entity to its profile', () => { + renderLogs([ + updateLog( + { fieldsAdded: [{ name: 'displayName', newValue: 'John Doe' }] }, + { + entityType: 'user', + entityFQN: 'john_doe', + changeEvent: mockChangeEvent({ + entityType: 'user', + entity: { + id: 'u-1', + name: 'john_doe', + displayName: 'John Doe', + fullyQualifiedName: 'john_doe', + }, + changeDescription: { + fieldsAdded: [{ name: 'displayName', newValue: 'John Doe' }], + fieldsUpdated: [], + fieldsDeleted: [], + }, + }), + } + ), + ]); - expect(entityLink).toHaveAttribute( - 'href', - '/table/sample_data.ecommerce_db.shopify.orders' - ); + expect( + within(screen.getByTestId('affected-entity')).getByRole('link', { + name: 'John Doe', + }) + ).toHaveAttribute('href', '/users/john_doe'); }); - it('should render user entity link', () => { - const logsWithUser: AuditLogEntry[] = [ + it('should display System for logs without userName', () => { + renderLogs([ { id: 1, - changeEventId: 'event-1', - eventTs: Date.now(), + eventTs: NOW, eventType: EventType.EntityUpdated, - userName: 'admin', - entityType: 'user', - changeEvent: mockChangeEvent({ - id: 'ce-1', - eventType: EventType.EntityUpdated, - entityType: 'user', - entity: { - id: 'user-1', - name: 'john_doe', - displayName: 'John Doe', - fullyQualifiedName: 'john_doe', - }, - changeDescription: { - fieldsAdded: [], - fieldsUpdated: [], - fieldsDeleted: [], - }, - timestamp: Date.now(), - }), + entityType: 'table', }, - ]; + ]); - renderWithRouter(); - - const entityLink = screen.getByRole('link', { name: 'John Doe' }); - - expect(entityLink).toHaveAttribute('href', '/users/john_doe'); + expect(screen.getByTestId('profile-picture')).toHaveTextContent( + 'label.system' + ); }); }); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.utils.test.ts b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.utils.test.ts new file mode 100644 index 000000000000..0816ce18e1cb --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.utils.test.ts @@ -0,0 +1,478 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { NO_DATA_PLACEHOLDER } from '../../constants/constants'; +import { ChangeEvent, EventType } from '../../generated/type/changeEvent'; +import { AuditLogEntry } from '../../types/auditLogs.interface'; +import { formatDateTime } from '../../utils/date-time/DateTimeUtils'; +import { + EVENT_TYPE_COLORS, + formatCellValue, + getChangeRows, + getEntityRefLink, + getFieldPath, + getLineageEdge, + getReadableSummary, + getStatusColor, + isAuthEvent, + MAX_RECORDS, + parseChangeValue, + toChangeValue, +} from './AuditLogList.utils'; + +const lineageLog = (entity: unknown): AuditLogEntry => ({ + eventType: EventType.EntityLineageAdded, + changeEvent: { entity } as unknown as ChangeEvent, +}); + +describe('AuditLogList.utils', () => { + describe('EVENT_TYPE_COLORS', () => { + // Event types the audit log never records (AuditLogRepository.SUPPORTED_EVENT_TYPES). + // A new EventType must be added here or given a colour, so the list stays a decision. + const NOT_AUDITED = new Set([ + EventType.EntityNoChange, + EventType.LogicalTestCaseAdded, + EventType.OntologyChangeSetApplied, + EventType.OntologyImported, + EventType.OntologyRelationshipTypeUpdated, + EventType.PostCreated, + EventType.PostUpdated, + EventType.ThreadCreated, + EventType.ThreadUpdated, + ]); + + it('should colour every event type the audit log records', () => { + const uncoloured = Object.values(EventType).filter( + (type) => !NOT_AUDITED.has(type) && !EVENT_TYPE_COLORS[type] + ); + + expect(uncoloured).toEqual([]); + }); + }); + + describe('isAuthEvent', () => { + it.each([ + [EventType.UserLogin, true], + [EventType.UserLogout, true], + [EventType.EntityUpdated, false], + [undefined, false], + ])('should treat %s as auth event: %s', (eventType, expected) => { + expect(isAuthEvent(eventType)).toBe(expected); + }); + }); + + describe('getFieldPath', () => { + it.each([ + [undefined, ''], + ['', ''], + ['description', 'Description'], + ['testCaseResultSummary', 'Test Case Result Summary'], + ['columns.customer_id.tags', 'Columns › customer_id › Tags'], + ['columns."order.id".dataType', 'Columns › order.id › Data Type'], + [ + 'columns.address.street_name.description', + 'Columns › address › street_name › Description', + ], + ])('should turn %s into "%s"', (name, expected) => { + expect(getFieldPath(name)).toBe(expected); + }); + }); + + describe('parseChangeValue', () => { + it('should parse JSON strings and leave everything else untouched', () => { + expect(parseChangeValue('[{"name":"a"}]')).toEqual([{ name: 'a' }]); + expect(parseChangeValue('{"a":1}')).toEqual({ a: 1 }); + expect(parseChangeValue('plain text')).toBe('plain text'); + expect(parseChangeValue(false)).toBe(false); + expect(parseChangeValue(undefined)).toBeUndefined(); + }); + }); + + describe('toChangeValue', () => { + it.each([[undefined], [null], [''], ['[]']])( + 'should return nothing for an empty value (%s)', + (raw) => { + expect(toChangeValue(raw)).toBeUndefined(); + } + ); + + it('should keep false and 0 as real values', () => { + expect(toChangeValue(false)).toEqual({ type: 'text', text: 'false' }); + expect(toChangeValue(0)).toEqual({ type: 'text', text: '0' }); + }); + + it('should strip HTML from text values', () => { + expect(toChangeValue('

The ID of the customer.

')).toEqual({ + type: 'text', + text: 'The ID of the customer.', + }); + }); + + it('should decode HTML entities and keep paragraphs apart', () => { + expect( + toChangeValue('

Orders & returns

Second line

') + ).toEqual({ type: 'text', text: 'Orders & returns Second line' }); + }); + + it.each([ + ['map'], + ['array>'], + ['a < b and c > d'], + ])('should keep non-HTML angle-bracket text "%s" as is', (raw) => { + expect(toChangeValue(raw)).toEqual({ type: 'text', text: raw }); + }); + + it('should treat a list of columns as records, not references', () => { + expect(toChangeValue([{ name: 'id', dataType: 'INT' }])).toEqual({ + type: 'records', + records: [{ name: 'id', dataType: 'INT' }], + totalCount: 1, + }); + }); + + it('should classify tiers, classification tags and glossary terms', () => { + expect( + toChangeValue( + JSON.stringify([ + { tagFQN: 'Tier.Tier1', name: 'Tier1' }, + { tagFQN: 'PII.Sensitive', name: 'Sensitive' }, + { tagFQN: 'Business.Revenue', source: 'Glossary' }, + ]) + ) + ).toEqual({ + type: 'refs', + refs: [ + { fqn: 'Tier.Tier1', refKind: 'tier', label: 'Tier1' }, + { + fqn: 'PII.Sensitive', + refKind: 'classification', + label: 'PII.Sensitive', + }, + { + fqn: 'Business.Revenue', + refKind: 'glossary', + label: 'Business.Revenue', + }, + ], + }); + }); + + it('should classify domains and data products apart from other entity references', () => { + expect( + toChangeValue([ + { type: 'domain', name: 'Customer360', displayName: 'Customer 360' }, + { + type: 'dataProduct', + name: 'sales', + fullyQualifiedName: 'Sales.sales', + }, + { id: 'u-1', type: 'user', name: 'admin' }, + ]) + ).toMatchObject({ + type: 'refs', + refs: [ + { + fqn: 'Customer360', + entityType: 'domain', + refKind: 'domain', + label: 'Customer 360', + }, + { + fqn: 'Sales.sales', + entityType: 'dataProduct', + refKind: 'domain', + label: 'sales', + }, + { + fqn: 'admin', + entityType: 'user', + refKind: 'entity', + label: 'admin', + }, + ], + }); + }); + + it('should treat a single reference object as a one-item list', () => { + expect( + toChangeValue({ id: 't-1', type: 'team', name: 'Engineering' }) + ).toMatchObject({ + type: 'refs', + refs: [ + { + id: 't-1', + name: 'Engineering', + fqn: 'Engineering', + entityType: 'team', + refKind: 'entity', + label: 'Engineering', + }, + ], + }); + }); + + it('should keep the first records of a list of objects and its full count', () => { + const rows = Array.from({ length: MAX_RECORDS + 2 }, (_, index) => ({ + status: 'Success', + index, + })); + const value = toChangeValue(JSON.stringify(rows)); + + expect(value).toEqual({ + type: 'records', + records: rows.slice(0, MAX_RECORDS), + totalCount: MAX_RECORDS + 2, + }); + }); + + it('should turn a plain object into key-value entries', () => { + expect(toChangeValue('{"runId":"r-1","config":{}}')).toEqual({ + type: 'keyValue', + entries: [ + ['runId', 'r-1'], + ['config', {}], + ], + }); + }); + + it('should join a list of plain values as text', () => { + expect(toChangeValue(['a', 'b', 3])).toEqual({ + type: 'text', + text: 'a, b, 3', + }); + }); + }); + + describe('getChangeRows', () => { + it('should return no rows without a change description', () => { + expect(getChangeRows(undefined)).toEqual([]); + }); + + it('should list added, updated and removed fields in that order', () => { + const rows = getChangeRows({ + fieldsAdded: [ + { name: 'columns.id.tags', newValue: '[{"tagFQN":"PII.Sensitive"}]' }, + ], + fieldsUpdated: [ + { name: 'description', oldValue: 'old', newValue: 'new' }, + ], + fieldsDeleted: [ + { name: 'owners', oldValue: '[{"type":"user","name":"bob"}]' }, + ], + }); + + expect( + rows.map(({ key, action, path }) => ({ key, action, path })) + ).toEqual([ + { + key: 'added-columns.id.tags', + action: 'added', + path: 'Columns › id › Tags', + }, + { key: 'updated-description', action: 'updated', path: 'Description' }, + { key: 'removed-owners', action: 'removed', path: 'Owners' }, + ]); + }); + + it('should read only the side of the change that matters for its action', () => { + const [added, updated, removed] = getChangeRows({ + fieldsAdded: [{ name: 'a', oldValue: 'ignored', newValue: 'new-a' }], + fieldsUpdated: [{ name: 'b', oldValue: 'old-b', newValue: 'new-b' }], + fieldsDeleted: [{ name: 'c', oldValue: 'old-c', newValue: 'ignored' }], + }); + + expect(added.oldValue).toBeUndefined(); + expect(added.newValue).toEqual({ type: 'text', text: 'new-a' }); + expect(updated.oldValue).toEqual({ type: 'text', text: 'old-b' }); + expect(updated.newValue).toEqual({ type: 'text', text: 'new-b' }); + expect(removed.oldValue).toEqual({ type: 'text', text: 'old-c' }); + expect(removed.newValue).toBeUndefined(); + }); + + it('should drop the deleted flag, which the event badge already shows', () => { + expect( + getChangeRows({ + fieldsAdded: [], + fieldsUpdated: [{ name: 'deleted', oldValue: false, newValue: true }], + fieldsDeleted: [], + }) + ).toEqual([]); + }); + }); + + describe('getStatusColor', () => { + it.each([ + ['Success', 'success'], + ['PASSED', 'success'], + ['Failed', 'error'], + ['error', 'error'], + ['Aborted', 'warning'], + ['partialSuccess', 'warning'], + ['Unknown', 'gray'], + ])('should colour %s as %s', (status, color) => { + expect(getStatusColor(status)).toBe(color); + }); + }); + + describe('formatCellValue', () => { + it('should show the placeholder for missing values', () => { + expect(formatCellValue('status', null)).toEqual({ + text: NO_DATA_PLACEHOLDER, + }); + expect(formatCellValue('status', '')).toEqual({ + text: NO_DATA_PLACEHOLDER, + }); + }); + + it('should format epoch milliseconds under a time-like key', () => { + const timestamp = 1795564824021; + + expect(formatCellValue('timestamp', timestamp)).toEqual({ + text: formatDateTime(timestamp), + }); + expect(formatCellValue('endDate', timestamp)).toEqual({ + text: formatDateTime(timestamp), + }); + }); + + it('should not read small numbers under a time-like key as dates', () => { + expect(formatCellValue('executionTime', 42)).toEqual({ text: '42' }); + }); + + it('should colour status and state values', () => { + expect(formatCellValue('status', 'Aborted')).toEqual({ + text: 'Aborted', + color: 'warning', + }); + expect(formatCellValue('pipelineState', 'success')).toEqual({ + text: 'success', + color: 'success', + }); + }); + + it('should name the items of a list and flag empty structures', () => { + expect( + formatCellValue('status', [ + { name: 'OpenMetadata' }, + { displayName: 'Sales' }, + ]) + ).toEqual({ text: 'OpenMetadata, Sales' }); + expect(formatCellValue('config', {})).toEqual({ + text: '', + isEmpty: true, + }); + expect(formatCellValue('items', [])).toEqual({ text: '', isEmpty: true }); + expect(formatCellValue('config', { retries: 3 })).toEqual({ + text: '{"retries":3}', + }); + }); + + it('should shorten UUIDs and leave other strings whole', () => { + expect( + formatCellValue('runId', 'b7f39045-3277-417e-98e8-dbac25cf4544') + ).toEqual({ text: 'b7f39045…' }); + expect(formatCellValue('initiator', 'ingestion-bot')).toEqual({ + text: 'ingestion-bot', + }); + }); + }); + + describe('getEntityRefLink', () => { + it.each([ + [{ entityType: 'user', fqn: 'john_doe' }, '/users/john_doe'], + [ + { entityType: 'team', fqn: 'Engineering' }, + '/settings/members/teams/Engineering', + ], + [ + { entityType: 'table', fqn: 'svc.db.schema.orders' }, + '/table/svc.db.schema.orders', + ], + [{ entityType: 'notAnEntity', fqn: 'x' }, undefined], + [{ fqn: 'x' }, undefined], + ])('should link %o to %s', (ref, expected) => { + expect( + getEntityRefLink({ label: ref.fqn, refKind: 'entity', ...ref }) + ).toBe(expected); + }); + }); + + describe('getLineageEdge', () => { + const edge = { + fromEntity: { + type: 'table', + name: 'customer', + fullyQualifiedName: 'svc.db.s.customer', + }, + toEntity: { + type: 'table', + name: 'orders', + fullyQualifiedName: 'svc.db.s.orders', + }, + }; + + it('should read both endpoints from an object or a JSON string', () => { + const expected = { + from: { + fqn: 'svc.db.s.customer', + entityType: 'table', + refKind: 'entity', + label: 'customer', + }, + to: { + fqn: 'svc.db.s.orders', + entityType: 'table', + refKind: 'entity', + label: 'orders', + }, + }; + + expect(getLineageEdge(lineageLog(edge))).toMatchObject(expected); + expect(getLineageEdge(lineageLog(JSON.stringify(edge)))).toMatchObject( + expected + ); + }); + + it('should return nothing when an endpoint is missing', () => { + expect( + getLineageEdge(lineageLog({ fromEntity: edge.fromEntity })) + ).toBeUndefined(); + expect( + getLineageEdge({ eventType: EventType.EntityUpdated }) + ).toBeUndefined(); + }); + }); + + describe('getReadableSummary', () => { + it('should hide a summary that only repeats the event type', () => { + expect( + getReadableSummary({ + eventType: EventType.EntityLineageAdded, + summary: 'entityLineageAdded', + }) + ).toBeUndefined(); + }); + + it('should keep a real summary', () => { + expect( + getReadableSummary({ + eventType: EventType.EntityCreated, + summary: 'Created glossary: AuditDemoGlossary', + }) + ).toBe('Created glossary: AuditDemoGlossary'); + expect( + getReadableSummary({ eventType: EventType.EntityCreated }) + ).toBeUndefined(); + }); + }); +}); diff --git a/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.utils.ts b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.utils.ts new file mode 100644 index 000000000000..78df5550fa39 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/components/AuditLog/AuditLogList.utils.ts @@ -0,0 +1,434 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BadgeColors } from '@openmetadata/ui-core-components'; +import { isNil, isPlainObject, startCase } from 'lodash'; +import { NO_DATA_PLACEHOLDER } from '../../constants/constants'; +import { EntityType } from '../../enums/entity.enum'; +import { + ChangeDescription, + EventType, + FieldChange, +} from '../../generated/type/changeEvent'; +import { AuditLogEntry } from '../../types/auditLogs.interface'; +import { formatDateTime } from '../../utils/date-time/DateTimeUtils'; +import { getEntityLinkFromType } from '../../utils/EntityLinkUtils'; +import Fqn from '../../utils/Fqn'; +import { getTeamsWithFqnPath, getUserPath } from '../../utils/RouterUtils'; +import { getSettingsLink } from '../../utils/SettingsModalLinkUtils'; +import { isValidJSONString } from '../../utils/StringUtils'; + +export type ChangeAction = 'added' | 'updated' | 'removed'; + +/** Tags, tiers, glossary terms and domains render as core `Tag`s; other references as entity chips. */ +export type ChangeRefKind = + | 'tier' + | 'classification' + | 'glossary' + | 'domain' + | 'entity'; + +export interface ChangeRef { + /** Entity id of a referenced user, team or entity; tags have none. */ + id?: string; + name?: string; + label: string; + fqn: string; + refKind: ChangeRefKind; + /** Entity type of an entity reference (`user`, `team`, `domain`, ...). */ + entityType?: string; +} + +export type ChangeValue = + | { type: 'refs'; refs: ChangeRef[] } + | { + type: 'records'; + records: Record[]; + totalCount: number; + } + | { type: 'keyValue'; entries: [string, unknown][] } + | { type: 'text'; text: string }; + +export interface ChangeRow { + key: string; + action: ChangeAction; + name: string; + path: string; + oldValue?: ChangeValue; + newValue?: ChangeValue; +} + +export interface CellValue { + text: string; + color?: BadgeColors; + isEmpty?: boolean; +} + +// ADR:2026-11-25-audit-log-rows-show-five-records-and-three-lines-of-a-change +export const MAX_RECORDS = 5; + +const UUID_PREVIEW_LENGTH = 8; + +/** + * Colour per audited event type — the server records exactly these + * (`AuditLogRepository.SUPPORTED_EVENT_TYPES`); anything else renders gray. + */ +export const EVENT_TYPE_COLORS: Partial> = { + [EventType.EntityCreated]: 'success', + [EventType.EntityUpdated]: 'blue', + [EventType.EntityFieldsChanged]: 'blue', + [EventType.EntitySoftDeleted]: 'warning', + [EventType.EntityDeleted]: 'error', + [EventType.EntityRestored]: 'success', + [EventType.EntityLineageAdded]: 'indigo', + [EventType.EntityLineageUpdated]: 'indigo', + [EventType.EntityLineageDeleted]: 'indigo', + [EventType.UserLogin]: 'blue-light', + [EventType.UserLogout]: 'blue-light', +}; + +export const CHANGE_ACTION_STYLES: Record< + ChangeAction, + { labelKey: string; className: string } +> = { + added: { labelKey: 'label.added', className: 'tw:text-utility-success-700' }, + updated: { labelKey: 'label.updated', className: 'tw:text-utility-blue-700' }, + removed: { + labelKey: 'label.removed', + className: 'tw:text-utility-error-700', + }, +}; + +/** Dot colour that tells the kinds of `Tag` apart. */ +export const REF_DOT_CLASSES: Partial> = { + tier: 'tw:text-utility-purple-500', + classification: 'tw:text-utility-blue-500', + glossary: 'tw:text-utility-success-500', + domain: 'tw:text-utility-orange-500', +}; + +const DOMAIN_REF_TYPES = new Set([ + EntityType.DOMAIN, + EntityType.DATA_PRODUCT, +]); + +const STATUS_COLORS: [RegExp, BadgeColors][] = [ + [/^(success|successful|passed|completed)$/, 'success'], + [/^(failed|failure|error)$/, 'error'], + [/^(aborted|queued|running|partialsuccess|pending)$/, 'warning'], +]; + +const UUID_PATTERN = + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +// Epoch-millisecond values only — avoids formatting small counts under a "time" key as 1970 dates. +const MIN_EPOCH_MS = 1e11; + +export interface LineageEdge { + from: ChangeRef; + to: ChangeRef; +} + +export const isAuthEvent = (eventType?: string) => + eventType === EventType.UserLogin || eventType === EventType.UserLogout; + +/** + * `columns.customer_id.tags` → "Columns › customer_id › Tags". Inner segments are entity + * names, so they stay verbatim apart from FQN quoting (`columns."order.id".tags`). + */ +export const getFieldPath = (name?: string): string => { + if (!name) { + return ''; + } + const parts = Fqn.split(name).map((part) => Fqn.unquoteName(part)); + if (parts.length === 1) { + return startCase(parts[0]); + } + const [first, ...rest] = parts; + const last = rest.pop(); + + return [startCase(first), ...rest, startCase(last)].join(' › '); +}; + +export const parseChangeValue = (value: unknown): unknown => { + if (typeof value !== 'string' || !isValidJSONString(value)) { + return value; + } + try { + return JSON.parse(value); + } catch { + return value; + } +}; + +const isRefObject = (value: unknown): value is Record => { + if (!isPlainObject(value)) { + return false; + } + const object = value as Record; + const hasName = + typeof object.name === 'string' || + typeof object.fullyQualifiedName === 'string'; + + return ( + typeof object.tagFQN === 'string' || + (typeof object.type === 'string' && hasName) + ); +}; + +const getTagRefKind = (tagFQN: string, source?: unknown): ChangeRefKind => { + if (tagFQN.startsWith('Tier.')) { + return 'tier'; + } + + return source === 'Glossary' ? 'glossary' : 'classification'; +}; + +const toChangeRef = (object: Record): ChangeRef => { + const name = object.name as string | undefined; + const displayName = object.displayName as string | undefined; + if (typeof object.tagFQN === 'string') { + const refKind = getTagRefKind(object.tagFQN, object.source); + + return { + fqn: object.tagFQN, + refKind, + label: + refKind === 'tier' + ? displayName || name || object.tagFQN + : object.tagFQN, + }; + } + const fqn = (object.fullyQualifiedName as string | undefined) ?? name ?? ''; + const entityType = object.type as string; + + return { + id: object.id as string | undefined, + name, + fqn, + entityType, + refKind: DOMAIN_REF_TYPES.has(entityType) ? 'domain' : 'entity', + label: displayName || name || fqn, + }; +}; + +// Closing block tags become spaces so `

a

b

` reads "a b", not "ab". +const BLOCK_END_PATTERN = /<\/(p|div|li|h[1-6])>|/gi; + +// Only rich-text markup or an entity marks a value as HTML; a type such as `map` +// would otherwise be parsed as an element and vanish from the audit log. +const HTML_MARKUP_PATTERN = + /<\/?(p|div|span|br|li|ul|ol|h[1-6]|strong|em|b|i|u|s|a|code|pre|blockquote|table|tr|td|th)(\s[^>]*)?\/?>|&(#\d+|#x[\da-f]+|[a-z]+);/i; + +/** Plain text of an HTML value, with entities such as `&` decoded; other text is kept as is. */ +const toPlainText = (value: string): string => { + if (!HTML_MARKUP_PATTERN.test(value)) { + return value; + } + const html = value.replace(BLOCK_END_PATTERN, ' '); + const text = new DOMParser().parseFromString(html, 'text/html').body + .textContent; + + return text?.replace(/\s+/g, ' ').trim() || value; +}; + +const toTextValue = (value: unknown): string => { + if (typeof value === 'string') { + return toPlainText(value); + } + if (Array.isArray(value)) { + return value.map(toTextValue).filter(Boolean).join(', '); + } + + return isPlainObject(value) ? JSON.stringify(value) : String(value); +}; + +const toArrayValue = (values: unknown[]): ChangeValue | undefined => { + if (values.length === 0) { + return undefined; + } + if (values.every(isRefObject)) { + return { type: 'refs', refs: values.map(toChangeRef) }; + } + if (values.every(isPlainObject)) { + return { + type: 'records', + records: (values as Record[]).slice(0, MAX_RECORDS), + totalCount: values.length, + }; + } + + return { type: 'text', text: toTextValue(values) }; +}; + +/** Classifies a raw field value into the shape the list renders; `undefined` when there is nothing to show. */ +export const toChangeValue = (raw: unknown): ChangeValue | undefined => { + const value = parseChangeValue(raw); + if (isNil(value) || value === '') { + return undefined; + } + if (Array.isArray(value)) { + return toArrayValue(value); + } + if (isRefObject(value)) { + return { type: 'refs', refs: [toChangeRef(value)] }; + } + if (isPlainObject(value)) { + return { + type: 'keyValue', + entries: Object.entries(value as Record), + }; + } + + return { type: 'text', text: toTextValue(value) }; +}; + +const toChangeRow = (action: ChangeAction, change: FieldChange): ChangeRow => { + const name = change.name ?? ''; + + return { + key: `${action}-${name}`, + action, + name, + path: getFieldPath(name), + oldValue: action === 'added' ? undefined : toChangeValue(change.oldValue), + newValue: action === 'removed' ? undefined : toChangeValue(change.newValue), + }; +}; + +/** The `deleted` flag change is the soft-delete/restore event itself, already shown by its badge and summary. */ +export const getChangeRows = ( + changeDescription?: ChangeDescription +): ChangeRow[] => { + if (!changeDescription) { + return []; + } + + return [ + ...(changeDescription.fieldsAdded ?? []).map((change) => + toChangeRow('added', change) + ), + ...(changeDescription.fieldsUpdated ?? []) + .filter((change) => change.name !== 'deleted') + .map((change) => toChangeRow('updated', change)), + ...(changeDescription.fieldsDeleted ?? []).map((change) => + toChangeRow('removed', change) + ), + ]; +}; + +export const getStatusColor = (value: string): BadgeColors => + STATUS_COLORS.find(([pattern]) => pattern.test(value.toLowerCase()))?.[1] ?? + 'gray'; + +const getItemName = (item: unknown): string => { + if (!isPlainObject(item)) { + return String(item); + } + const named = item as { displayName?: string; name?: string }; + + return named.displayName ?? named.name ?? JSON.stringify(item); +}; + +const isEpochTimestamp = (key: string, value: unknown): value is number => + typeof value === 'number' && /time|date/i.test(key) && value > MIN_EPOCH_MS; + +const isStatusValue = (key: string, value: unknown): value is string => + typeof value === 'string' && /status|state/i.test(key); + +const getStructuredText = (value: unknown[] | object): string => { + if (Array.isArray(value)) { + return value.map(getItemName).join(', '); + } + + return Object.keys(value).length ? JSON.stringify(value) : ''; +}; + +const formatScalar = (value: unknown): CellValue => { + const text = String(value); + + return UUID_PATTERN.test(text) + ? { text: `${text.slice(0, UUID_PREVIEW_LENGTH)}…` } + : { text }; +}; + +/** Formats one inline `key value` pair, inferring timestamps, statuses and ids from the key. */ +export const formatCellValue = (key: string, value: unknown): CellValue => { + if (isNil(value) || value === '') { + return { text: NO_DATA_PLACEHOLDER }; + } + if (isEpochTimestamp(key, value)) { + return { text: formatDateTime(value) }; + } + if (isStatusValue(key, value)) { + return { text: value, color: getStatusColor(value) }; + } + if (Array.isArray(value) || isPlainObject(value)) { + const text = getStructuredText(value as unknown[] | object); + + return text ? { text } : { text: '', isEmpty: true }; + } + + return formatScalar(value); +}; + +export const findEntityType = (value?: string): EntityType | undefined => { + const normalized = value?.toLowerCase(); + + return normalized + ? Object.values(EntityType).find( + (entityType) => entityType.toLowerCase() === normalized + ) + : undefined; +}; + +export const isOwnerRef = (ref: ChangeRef): boolean => + ref.entityType === EntityType.USER || ref.entityType === EntityType.TEAM; + +/** Href for a referenced user, team or entity; `undefined` when it has no page. */ +export const getEntityRefLink = (ref: ChangeRef): string | undefined => { + switch (ref.entityType) { + case EntityType.USER: + return getSettingsLink(getUserPath(ref.fqn)); + case EntityType.TEAM: + return getSettingsLink(getTeamsWithFqnPath(ref.fqn)); + default: { + const entityType = findEntityType(ref.entityType); + + return ( + (entityType && getEntityLinkFromType(ref.fqn, entityType)) || undefined + ); + } + } +}; + +/** + * A lineage event's "entity" is the edge (`a--upstream-->b`); its change event carries the + * two endpoints as `fromEntity` / `toEntity`, sometimes still as a JSON string. + */ +export const getLineageEdge = (log: AuditLogEntry): LineageEdge | undefined => { + const entity = parseChangeValue(log.changeEvent?.entity) as + | { fromEntity?: unknown; toEntity?: unknown } + | undefined; + if (!isRefObject(entity?.fromEntity) || !isRefObject(entity?.toEntity)) { + return undefined; + } + + return { + from: toChangeRef(entity.fromEntity), + to: toChangeRef(entity.toEntity), + }; +}; + +/** The server's summary for lineage events is the bare event type, which says nothing. */ +export const getReadableSummary = (log: AuditLogEntry): string | undefined => + log.summary && log.summary !== log.eventType ? log.summary : undefined;