import type ClientRepresentation from "@keycloak/keycloak-admin-client/lib/defs/clientRepresentation"; import React, { useState, KeyboardEvent, useMemo, useRef } from "react"; import { useTranslation } from "react-i18next"; import { FormGroup, Select, SelectVariant, SelectOption, PageSection, ActionGroup, Button, Switch, ExpandableSection, TextInput, ButtonVariant, InputGroup, Toolbar, ToolbarGroup, ToolbarItem, Divider, } from "@patternfly/react-core"; import { Controller, useFormContext } from "react-hook-form"; import { FormAccess } from "../../components/form-access/FormAccess"; import { HelpItem } from "../../components/help-enabler/HelpItem"; import { FormPanel } from "../../components/scroll-form/FormPanel"; import type UserRepresentation from "@keycloak/keycloak-admin-client/lib/defs/userRepresentation"; import type RoleRepresentation from "@keycloak/keycloak-admin-client/lib/defs/roleRepresentation"; import type AccessTokenRepresentation from "@keycloak/keycloak-admin-client/lib/defs/accessTokenAuthorization"; import { useAdminClient, useFetch } from "../../context/auth/AdminClient"; import type ResourceEvaluation from "@keycloak/keycloak-admin-client/lib/defs/resourceEvaluation"; import { useRealm } from "../../context/realm-context/RealmContext"; import { KeyBasedAttributeInput } from "./KeyBasedAttributeInput"; import { defaultContextAttributes } from "../utils"; import type EvaluationResultRepresentation from "@keycloak/keycloak-admin-client/lib/defs/evaluationResultRepresentation"; import type ResourceRepresentation from "@keycloak/keycloak-admin-client/lib/defs/resourceRepresentation"; import type ScopeRepresentation from "@keycloak/keycloak-admin-client/lib/defs/scopeRepresentation"; import type { KeyValueType } from "../../components/key-value-form/key-value-convert"; import { TableComposable, Th, Thead, Tr } from "@patternfly/react-table"; import { AuthorizationEvaluateResource } from "./AuthorizationEvaluateResource"; import { SearchIcon } from "@patternfly/react-icons"; import { ListEmptyState } from "../../components/list-empty-state/ListEmptyState"; import { KeycloakTextInput } from "../../components/keycloak-text-input/KeycloakTextInput"; import { useAccess } from "../../context/access/Access"; import { ForbiddenSection } from "../../ForbiddenSection"; import { AuthorizationDataModal } from "./AuthorizationDataModal"; import "./auth-evaluate.css"; interface EvaluateFormInputs extends Omit { alias: string; authScopes: string[]; context: { attributes: Record[]; }; resources: Record[]; client: ClientRepresentation; user: UserRepresentation; } export type AttributeType = { key: string; name: string; custom?: boolean; values?: { [key: string]: string; }[]; }; type ClientSettingsProps = { client: ClientRepresentation; save: () => void; }; export type AttributeForm = Omit< EvaluateFormInputs, "context" | "resources" > & { context: { attributes?: KeyValueType[]; }; resources?: KeyValueType[]; }; type Props = ClientSettingsProps & EvaluationResultRepresentation; enum ResultsFilter { All = "ALL", StatusDenied = "STATUS_DENIED", StatusPermitted = "STATUS_PERMITTED", } function filterResults( results: EvaluationResultRepresentation[], filter: ResultsFilter ) { switch (filter) { case ResultsFilter.StatusPermitted: return results.filter(({ status }) => status === "PERMIT"); case ResultsFilter.StatusDenied: return results.filter(({ status }) => status === "DENY"); default: return results; } } export const AuthorizationEvaluate = ({ client }: Props) => { const form = useFormContext(); const { control, reset, trigger } = form; const { t } = useTranslation("clients"); const adminClient = useAdminClient(); const realm = useRealm(); const [clientsDropdownOpen, setClientsDropdownOpen] = useState(false); const [scopesDropdownOpen, setScopesDropdownOpen] = useState(false); const [userDropdownOpen, setUserDropdownOpen] = useState(false); const [roleDropdownOpen, setRoleDropdownOpen] = useState(false); const [isExpanded, setIsExpanded] = useState(false); const [applyToResourceType, setApplyToResourceType] = useState(false); const [resources, setResources] = useState([]); const [scopes, setScopes] = useState([]); const [evaluateResults, setEvaluateResults] = useState< EvaluationResultRepresentation[] >([]); const [access, setAccess] = useState(); const [showEvaluateResults, setShowEvaluateResults] = useState(false); const searchQueryRef = useRef(""); const [searchQuery, setSearchQuery] = useState(""); const [filterDropdownOpen, setFilterDropdownOpen] = useState(false); const [key, setKey] = useState(0); const refresh = () => { setKey(key + 1); }; const [filter, setFilter] = useState(ResultsFilter.All); const [clients, setClients] = useState([]); const [clientRoles, setClientRoles] = useState([]); const [users, setUsers] = useState([]); const filteredResources = useMemo( () => filterResults(evaluateResults, filter).filter( ({ resource }) => resource?.name?.includes(searchQuery) ?? false ), [evaluateResults, filter, searchQuery] ); const { hasAccess } = useAccess(); if (!hasAccess("view-users")) return ; useFetch( () => Promise.all([ adminClient.clients.find(), adminClient.roles.find(), adminClient.users.find(), ]), ([clients, roles, users]) => { setClients(clients); setClientRoles(roles); setUsers(users); }, [] ); useFetch( () => Promise.all([ adminClient.clients.listResources({ id: client.id!, }), adminClient.clients.listAllScopes({ id: client.id!, }), ]), ([resources, scopes]) => { setResources(resources); setScopes(scopes); }, [key, filter] ); const evaluate = async () => { if (!(await trigger())) { return; } const formValues = form.getValues(); const keys = formValues.resources.map(({ key }) => key); const resEval: ResourceEvaluation = { roleIds: formValues.roleIds ?? [], clientId: formValues.client.id!, userId: formValues.user.id!, resources: formValues.resources.filter((resource) => keys.includes(resource.name!) ), entitlements: false, context: { attributes: Object.fromEntries( formValues.context.attributes .filter((item) => item.key || item.value !== "") .map(({ key, value }) => [key, value]) ), }, }; const evaluation = await adminClient.clients.evaluateResource( { id: client.id!, realm: realm.realm }, resEval ); setEvaluateResults(evaluation.results); setAccess(evaluation.rpt); setShowEvaluateResults(true); return evaluateResults; }; const confirmSearchQuery = () => { setSearchQuery(searchQueryRef.current); }; const handleKeyDown = (e: KeyboardEvent) => { if (e.key === "Enter") { confirmSearchQuery(); } }; const handleInputChange = (value: string) => { searchQueryRef.current = value; }; const noEvaluatedData = evaluateResults.length === 0; const noFilteredData = filteredResources.length === 0; return showEvaluateResults ? ( {!noFilteredData && ( {t("resource")} {t("overallResults")} {t("scopes")} {filteredResources.map((resource, rowIndex) => ( ))} )} {(noFilteredData || noEvaluatedData) && ( <> )} ) : ( } fieldId="client" > ( )} /> } fieldId="user" > ( )} /> } fieldId="realmRole" > ( )} /> } > {!applyToResourceType ? ( } helperTextInvalid={t("common:required")} fieldId="resourcesAndAuthScopes" > ((item) => ({ name: item.name!, key: item._id!, }))} resources={resources} name="resources" /> ) : ( <> } fieldId="client" > } fieldId="authScopes" > ( )} /> )} setIsExpanded(!isExpanded)} isExpanded={isExpanded} > } helperTextInvalid={t("common:required")} fieldId="contextualAttributes" > ); };