8000 Show sub-resource events in Admin events tabs by ahus1 · Pull Request #55120 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion js/apps/admin-ui/src/client-scopes/EditClientScope.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,18 @@ export default function EditClientScope() {
title={<TabTitleText>{t("adminEvents")}</TabTitleText>}
{...eventsTab}
>
<AdminEvents resourcePath={`*client-scopes/${id}`} />
<AdminEvents
resourcePath={[
`client-scopes/${id}`,
`client-scopes/${id}/*`,
// Events of changing the realm default scopes
`default-default-client-scopes/${id}`,
`default-optional-client-scopes/${id}`,
// Events of assigning the scope to a client
`clients/*/default-client-scopes/${id}`,
`clients/*/optional-client-scopes/${id}`,
]}
/>
</Tab>
)}
</RoutableTabs>
Expand Down
7 changes: 6 additions & 1 deletion js/apps/admin-ui/src/clients/ClientDetails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -827,7 +827,12 @@ export default function ClientDetails() {
eventKey="adminEvents"
title={<TabTitleText>{t("adminEvents")}</TabTitleText>}
>
<AdminEvents resourcePath={`clients/${client.id}`} />
<AdminEvents
resourcePath={[
`clients/${client.id}`,
`clients/${client.id}/*`,
]}
/>
</Tab>
</Tabs>
</Tab>
Expand Down
97 changes: 85 additions & 12 deletions js/apps/admin-ui/src/events/AdminEvents.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,36 @@ const DetailCell = (event: AdminEventRepresentation) => (
</DescriptionList>
);

// The server matches the path with SQL LIKE, so `_` and `%` in names are wildcards as well.
// A `\` in a name can't be matched at all, as the server doesn't escape it (see keycloak/keycloak#55126).
// Returns a check that treats `_` and `%` literally and `*` as the wildcard, or undefined when the server already matches exactly.
function literalMatcher(pattern: string | undefined) {
if (!pattern || !/[_%]/.test(pattern)) {
return undefined;
}
const regex = new RegExp(
`^${pattern
.split("*")
.map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
.join(".*")}$`,
);
return (path: string) => regex.test(path);
}

type AdminEventsProps = {
resourcePath?: string;
/**
* Resource path(s) to restrict the events to. The server accepts only one pattern per request,
* so multiple paths (for example an exact path plus its sub-resources) are queried separately and merged.
*/
resourcePath?: string | string[];
};

export const AdminEvents = ({ resourcePath }: AdminEventsProps) => {
export const AdminEvents = ({
resourcePath: resourcePathProp,
}: AdminEventsProps) => {
const { adminClient } = useAdminClient();
const resourcePaths = ([] as string[]).concat(resourcePathProp ?? []);
const resourcePath = resourcePaths[0];

const { t } = useTranslation();
const { realm } = useRealm();
Expand Down Expand Up @@ -176,15 +200,63 @@ export const AdminEvents = ({ resourcePath }: AdminEventsProps) => {
[],
);

function loader(first?: number, max?: number) {
return adminClient.realms.findAdminEvents({
resourcePath,
// The admin client wants 'dateFrom' and 'dateTo' to be Date objects, however it cannot actually handle them so we need to cast to any.
...(activeFilters as any),
realm,
first,
max,
});
async function loader(first?: number, max?: number) {
const find = (path: string | undefined, first?: number, max?: number) =>
adminClient.realms.findAdminEvents({
resourcePath: path,
// The admin client wants 'dateFrom' and 'dateTo' to be Date objects, however it cannot actually handle them so we need to cast to any.
...(activeFilters as any),
realm,
first,
max,
});

if (
resourcePaths.length <= 1 &&
!resourcePaths.some((path) => literalMatcher(path))
) {
return find(resourcePath, first, max);
}

// Rows that are filtered out don't count, so continue reading until enough rows are found.
const findMatching = async (path: string | undefined, needed?: number) => {
const matchPath = literalMatcher(path);
if (!matchPath) {
return find(path, 0, needed);
}
const pageSize = Math.max(needed ?? 100, 100);
const matching: Awaited<ReturnType<typeof find>> = [];
for (let offset = 0; ; offset += pageSize) {
const page = await find(path, offset, pageSize);
matching.push(
...page.filter((event) => matchPath(event.resourcePath!)),
);
if (page.length < pageSize || (needed && matching.length >= needed)) {
return matching;
}
}
};

// Each query must return enough rows to fill the requested page after merging.
// Known limitation: events with the same timestamp can be cut differently per query at a page boundary,
// so an event can repeat or be skipped between pages. A single backend request would avoid this, see keycloak/keycloak#55126.
const skip = first ?? 0;
const results = await Promise.all(
resourcePaths.map((path) =>
findMatching(path, max === undefined ? undefined : skip + max),
),
);
// Patterns can overlap when names contain wildcards, so the same event may be returned more than once.
const unique = new Map(
results.flat().map((event) => [event.id ?? JSON.stringify(event), event]),
);
const merged = [...unique.values()].sort(
(a, b) =>
(b.time ?? 0) - (a.time ?? 0) || (a.id ?? "").localeCompare(b.id ?? ""),
Comment thread
ahus1 marked this conversation as resolved.
Resolved
);
return max === undefined
? merged.slice(skip)
: merged.slice(skip, skip + max);
}

function submitSearch() {
Expand Down Expand Up @@ -288,7 +360,8 @@ export const AdminEvents = ({ resourcePath }: AdminEventsProps) => {
10000 )}
{!adminEventsEnabled && <EventsBanners type="adminEvents" />}
<KeycloakDataTable
key={key}
// Remount to reload when the resource paths change.
key={`${key}-${resourcePaths.join("|")}`}
loader={loader}
detailColumns={[
{
Expand Down
10 changes: 8 additions & 2 deletions js/apps/admin-ui/src/groups/GroupsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,14 @@ export default function GroupsSection({ orgId }: { orgId?: string } = {}) {
<AdminEvents
resourcePath={
isOrganization
? `organizations/${orgId}/groups/${id}`
: `groups/${id}`
? [
`organizations/${orgId}/groups/${id}`,
`organizations/${orgId}/groups/${id}/role-mappings/*`,
]
: [
`groups/${id}`,
`groups/${id}/role-mappings/*`,
]
}
/>
</Tab>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -932,7 +932,10 @@ export default function DetailSettings() {
{...eventsTab}
>
<AdminEvents
resourcePath={`identity-provider/instances/${alias}`}
resourcePath={[
`identity-provider/instances/${alias}`,
`identity-provider/instances/${alias}/*`,
]}
/>
</Tab>
)}
Expand Down
10 changes: 8 additions & 2 deletions js/apps/admin-ui/src/organizations/DetailOrganization.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,19 @@ export default function DetailOrganization() {
eventKey="adminEvents"
title={<TabTitleText>{t("adminEvents")}</TabTitleText>}
>
<AdminEvents resourcePath={`organizations/${id}`} />
<AdminEvents resourcePath={[`organizations/${id}`]} />
</Tab>
<Tab
eventKey="membershipEvents"
title={<TabTitleText>{t("membershipEvents")}</TabTitleText>}
>
<AdminEvents resourcePath={`organizations/${id}/members`} />
<AdminEvents
resourcePath={[
`organizations/${id}/members`,
`organizations/${id}/members/*`,
`organizations/${id}/invitations/*`,
]}
/>
</Tab>
</Tabs>
</Tab>
Expand Down
19 changes: 18 additions & 1 deletion js/apps/admin-ui/src/realm-roles/RealmRoleTabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,24 @@ export default function RealmRoleTabs() {
title={<TabTitleText>{t("adminEvents")}</TabTitleText>}
{...eventsTab}
>
<AdminEvents resourcePath={`roles-by-id/${id}`} />
{clientId ? (
// The name is only known once the role is loaded.
roleName && (
<AdminEvents
resourcePath={[
`clients/${clientId}/roles/${roleName}`,
// Only the sub-resources that record events (composites), as role names can contain "/" and "/*" would match other roles.
`clients/${clientId}/roles/${roleName}/composites`,
`roles-by-id/${id}`,
`roles-by-id/${id}/*`,
]}
/>
)
) : (
<AdminEvents
resourcePath={[`roles-by-id/${id}`, `roles-by-id/${id}/*`]}
/>
)}
</Tab>
)}
</RoutableTabs>
Expand Down
7 changes: 6 additions & 1 deletion js/apps/admin-ui/src/user/EditUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,12 @@ export default function EditUser() {
eventKey="adminEvents"
title={<TabTitleText>{t("adminEvents")}</TabTitleText>}
>
<AdminEvents resourcePath={`users/${user.id}*`} />
<AdminEvents
resourcePath={[
`users/${user.id}`,
`users/${user.id}/*`,
]}
/>
</Tab>
</Tabs>
</Tab>
Expand Down
Loading
Loading
0