Realm settings(keys): add hmac provider details (#860)

This commit is contained in:
Jenny 2021-07-16 04:22:08 -04:00 committed by GitHub
parent bcc3a84bb0
commit b5da41c651
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 453 additions and 298 deletions

View file

@ -47,6 +47,13 @@ describe("Realm settings", () => {
cy.getId("rs-keys-tab").click();
cy.getId("rs-providers-tab").click();
cy.getId("provider-name-link").contains("test_aes-generated").click();
sidebarPage.goToRealmSettings();
cy.getId("rs-keys-tab").click();
cy.getId("rs-providers-tab").click();
cy.getId("provider-name-link").contains("test_hmac-generated").click();
cy.wait(["@keysFetch"]);
return this;

View file

@ -1,297 +0,0 @@
import React, { useState } from "react";
import {
AlertVariant,
Button,
ButtonVariant,
Form,
FormGroup,
Modal,
ModalVariant,
Select,
SelectOption,
SelectVariant,
Switch,
TextInput,
} from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { Controller, useForm } from "react-hook-form";
import { useAdminClient } from "../context/auth/AdminClient";
import { useAlerts } from "../components/alert/Alerts";
import type ComponentRepresentation from "keycloak-admin/lib/defs/componentRepresentation";
import { HelpItem } from "../components/help-enabler/HelpItem";
import { useServerInfo } from "../context/server-info/ServerInfoProvider";
type HMACGeneratedModalProps = {
providerType: string;
handleModalToggle: () => void;
refresh: () => void;
open: boolean;
};
export const HMACGeneratedModal = ({
providerType,
handleModalToggle,
open,
refresh,
}: HMACGeneratedModalProps) => {
const { t } = useTranslation("realm-settings");
const serverInfo = useServerInfo();
const adminClient = useAdminClient();
const { addAlert } = useAlerts();
const { handleSubmit, control } = useForm({});
const [isKeySizeDropdownOpen, setIsKeySizeDropdownOpen] = useState(false);
const [isEllipticCurveDropdownOpen, setIsEllipticCurveDropdownOpen] =
useState(false);
const allComponentTypes =
serverInfo.componentTypes?.["org.keycloak.keys.KeyProvider"] ?? [];
const save = async (component: ComponentRepresentation) => {
try {
await adminClient.components.create({
...component,
parentId: component.parentId,
providerId: providerType,
providerType: "org.keycloak.keys.KeyProvider",
});
handleModalToggle();
addAlert(t("saveProviderSuccess"), AlertVariant.success);
refresh();
} catch (error) {
addAlert(
t("saveProviderError", {
error: error.response?.data?.errorMessage || error,
}),
AlertVariant.danger
);
}
};
return (
<Modal
className="add-provider-modal"
variant={ModalVariant.medium}
title={t("addProvider")}
isOpen={open}
onClose={handleModalToggle}
actions={[
<Button
data-testid="add-provider-button"
key="confirm"
variant="primary"
type="submit"
form="add-provider"
>
{t("common:Add")}
</Button>,
<Button
id="modal-cancel"
key="cancel"
variant={ButtonVariant.link}
onClick={() => {
handleModalToggle!();
}}
>
{t("common:cancel")}
</Button>,
]}
>
<Form
isHorizontal
id="add-provider"
className="pf-u-mt-lg"
onSubmit={handleSubmit(save!)}
>
<FormGroup
label={t("consoleDisplayName")}
fieldId="kc-console-display-name"
labelIcon={
<HelpItem
helpText="realm-settings-help:displayName"
forLabel={t("loginTheme")}
forID="kc-console-display-name"
/>
}
>
<Controller
name="name"
control={control}
defaultValue={providerType}
render={({ onChange }) => (
<TextInput
aria-label={t("consoleDisplayName")}
defaultValue={providerType}
onChange={(value) => {
onChange(value);
}}
data-testid="display-name-input"
></TextInput>
)}
/>
</FormGroup>
<FormGroup
label={t("common:enabled")}
fieldId="kc-enabled"
labelIcon={
<HelpItem
helpText={t("realm-settings-help:enabled")}
forLabel={t("enabled")}
forID="kc-enabled"
/>
}
>
<Controller
name="config.enabled"
control={control}
defaultValue={["true"]}
render={({ onChange, value }) => (
<Switch
id="kc-enabled"
label={t("common:on")}
labelOff={t("common:off")}
isChecked={value[0] === "true"}
data-testid={
value[0] === "true"
? "internationalization-enabled"
: "internationalization-disabled"
}
onChange={(value) => {
onChange([value + ""]);
}}
/>
)}
/>
</FormGroup>
<FormGroup
label={t("active")}
fieldId="kc-active"
labelIcon={
<HelpItem
helpText="realm-settings-help:active"
forLabel={t("active")}
forID="kc-active"
/>
}
>
<Controller
name="config.active"
control={control}
defaultValue={["true"]}
render={({ onChange, value }) => (
<Switch
id="kc-active"
label={t("common:on")}
labelOff={t("common:off")}
isChecked={value[0] === "true"}
data-testid={
value[0] === "true"
? "internationalization-enabled"
: "internationalization-disabled"
}
onChange={(value) => {
onChange([value + ""]);
}}
/>
)}
/>
</FormGroup>
{providerType === "hmac-generated" && (
<>
<FormGroup
label={t("secretSize")}
fieldId="kc-aes-keysize"
labelIcon={
<HelpItem
helpText="realm-settings-help:secretSize"
forLabel={t("emailTheme")}
forID="kc-email-theme"
/>
}
>
<Controller
name="config.secretSize"
control={control}
defaultValue={["64"]}
render={({ onChange, value }) => (
<Select
toggleId="kc-aes-keysize"
onToggle={() =>
setIsKeySizeDropdownOpen(!isKeySizeDropdownOpen)
}
onSelect={(_, value) => {
onChange([value + ""]);
setIsKeySizeDropdownOpen(false);
}}
selections={[value + ""]}
isOpen={isKeySizeDropdownOpen}
variant={SelectVariant.single}
aria-label={t("aesKeySize")}
data-testid="select-secret-size"
>
{allComponentTypes[2].properties[3].options!.map(
(item, idx) => (
<SelectOption
selected={item === value}
key={`email-theme-${idx}`}
value={item}
/>
)
)}
</Select>
)}
/>
</FormGroup>
<FormGroup
label={t("algorithm")}
fieldId="kc-algorithm"
labelIcon={
<HelpItem
helpText="realm-settings-help:algorithm"
forLabel={t("algorithm")}
forID="kc-algorithm"
/>
}
>
<Controller
name="config.algorithm"
control={control}
defaultValue={["HS-256"]}
render={({ onChange, value }) => (
<Select
toggleId="kc-elliptic"
onToggle={() =>
setIsEllipticCurveDropdownOpen(
!isEllipticCurveDropdownOpen
)
}
onSelect={(_, value) => {
onChange([value + ""]);
setIsEllipticCurveDropdownOpen(false);
}}
selections={[value + ""]}
variant={SelectVariant.single}
aria-label={t("emailTheme")}
isOpen={isEllipticCurveDropdownOpen}
placeholderText="Select one..."
data-testid="select-email-theme"
>
{allComponentTypes[2].properties[4].options!.map(
(p, idx) => (
<SelectOption
selected={p === value}
key={`email-theme-${idx}`}
value={p}
></SelectOption>
)
)}
</Select>
)}
/>
</FormGroup>
</>
)}
</Form>
</Modal>
);
};

View file

@ -39,7 +39,7 @@ import { useRealm } from "../context/realm-context/RealmContext";
import { Link, useRouteMatch } from "react-router-dom";
import { AESGeneratedModal } from "./key-providers/aes-generated/AESGeneratedModal";
import { JavaKeystoreModal } from "./JavaKeystoreModal";
import { HMACGeneratedModal } from "./HMACGeneratedModal";
import { HMACGeneratedModal } from "./key-providers/hmac-generated/HMACGeneratedModal";
import { ECDSAGeneratedModal } from "./ECDSAGeneratedModal";
import { RSAModal } from "./RSAModal";
import { RSAGeneratedModal } from "./RSAGeneratedModal";

View file

@ -0,0 +1,402 @@
import React, { useState } from "react";
import {
ActionGroup,
AlertVariant,
Button,
FormGroup,
PageSection,
Select,
SelectOption,
SelectVariant,
Switch,
TextInput,
ValidatedOptions,
} from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { Controller, useForm } from "react-hook-form";
import type ComponentRepresentation from "keycloak-admin/lib/defs/componentRepresentation";
import { HelpItem } from "../../../components/help-enabler/HelpItem";
import { useServerInfo } from "../../../context/server-info/ServerInfoProvider";
import { useAdminClient, useFetch } from "../../../context/auth/AdminClient";
import { useParams, useRouteMatch } from "react-router-dom";
import { FormAccess } from "../../../components/form-access/FormAccess";
import { ViewHeader } from "../../../components/view-header/ViewHeader";
import { convertToFormValues } from "../../../util";
import { useAlerts } from "../../../components/alert/Alerts";
type HMACGeneratedFormProps = {
handleModalToggle?: () => void;
refresh?: () => void;
editMode?: boolean;
providerType?: string;
};
export interface MatchParams {
providerType: string;
}
export const HMACGeneratedForm = ({
editMode,
providerType,
handleModalToggle,
refresh,
}: HMACGeneratedFormProps) => {
const { t } = useTranslation("realm-settings");
const serverInfo = useServerInfo();
const [isKeySizeDropdownOpen, setIsKeySizeDropdownOpen] = useState(false);
const [isEllipticCurveDropdownOpen, setIsEllipticCurveDropdownOpen] =
useState(false);
const adminClient = useAdminClient();
const { addAlert } = useAlerts();
const { id } = useParams<{ id: string }>();
const providerId =
useRouteMatch<MatchParams>("/:providerType?")?.params.providerType;
const save = async (component: ComponentRepresentation) => {
try {
if (id) {
await adminClient.components.update(
{ id },
{
...component,
parentId: component.parentId,
providerId: providerType,
providerType: "org.keycloak.keys.KeyProvider",
}
);
addAlert(t("saveProviderSuccess"), AlertVariant.success);
} else {
await adminClient.components.create({
...component,
parentId: component.parentId,
providerId: providerType,
providerType: "org.keycloak.keys.KeyProvider",
});
handleModalToggle?.();
addAlert(t("saveProviderSuccess"), AlertVariant.success);
refresh?.();
}
} catch (error) {
addAlert(
t("saveProviderError", {
error: error.response?.data?.errorMessage || error,
}),
AlertVariant.danger
);
}
};
const form = useForm<ComponentRepresentation>({ mode: "onChange" });
const setupForm = (component: ComponentRepresentation) => {
form.reset();
Object.entries(component).map(([key, value]) => {
if (
key === "config" &&
component.config?.secretSize &&
component.config?.active &&
component.config?.algorithm
) {
form.setValue("config.secretSize", value.secretSize[0]);
form.setValue("config.active", value.active[0]);
form.setValue("config.algorithm", value.active[0]);
convertToFormValues(value, "config", form.setValue);
}
form.setValue(key, value);
});
};
useFetch(
async () => {
if (editMode) return await adminClient.components.findOne({ id: id });
},
(result) => {
if (result) {
setupForm(result);
}
},
[]
);
const allComponentTypes =
serverInfo.componentTypes?.["org.keycloak.keys.KeyProvider"] ?? [];
const hmacSecretSizeOptions = allComponentTypes[2].properties[3].options;
const hmacAlgorithmOptions = allComponentTypes[2].properties[4].options;
return (
<FormAccess
isHorizontal
id="add-provider"
className="pf-u-mt-lg"
role="manage-realm"
onSubmit={form.handleSubmit(save)}
>
{editMode && (
<FormGroup
label={t("providerId")}
labelIcon={
<HelpItem
helpText="client-scopes-help:mapperName"
forLabel={t("common:name")}
forID={t("common:helpLabel", { label: t("common:name") })}
/>
}
fieldId="id"
isRequired
validated={
form.errors.name ? ValidatedOptions.error : ValidatedOptions.default
}
helperTextInvalid={t("common:required")}
>
<TextInput
ref={form.register()}
id="id"
type="text"
name="id"
isReadOnly={editMode}
aria-label={t("consoleDisplayName")}
defaultValue={id}
data-testid="display-name-input"
/>
</FormGroup>
)}
<FormGroup
label={t("common:name")}
labelIcon={
<HelpItem
helpText="client-scopes-help:mapperName"
forLabel={t("common:name")}
forID={t("common:helpLabel", { label: t("common:name") })}
/>
}
fieldId="name"
isRequired
validated={
form.errors.name ? ValidatedOptions.error : ValidatedOptions.default
}
helperTextInvalid={t("common:required")}
>
{!editMode && (
<Controller
name="name"
control={form.control}
defaultValue={providerType}
render={({ onChange, value }) => {
return (
<TextInput
id="name"
type="text"
aria-label={t("consoleDisplayName")}
defaultValue={providerType}
value={value}
onChange={(value) => onChange(value)}
data-testid="display-name-input"
/>
);
}}
/>
)}
{editMode && (
<>
<TextInput
ref={form.register()}
type="text"
id="name"
name="name"
defaultValue={providerId}
validated={
form.errors.name
? ValidatedOptions.error
: ValidatedOptions.default
}
/>
</>
)}
</FormGroup>
<FormGroup
label={t("common:enabled")}
fieldId="kc-enabled"
labelIcon={
<HelpItem
helpText={t("realm-settings-help:enabled")}
forLabel={t("enabled")}
forID={t("common:helpLabel", { label: t("enabled") })}
/>
}
>
<Controller
name="config.enabled"
control={form.control}
defaultValue={["true"]}
render={({ onChange, value }) => (
<Switch
id="kc-enabled-switch"
label={t("common:on")}
labelOff={t("common:off")}
isChecked={value[0] === "true"}
data-testid={value[0] === "true" ? "enabled" : "disabled"}
onChange={(value) => {
onChange([value.toString()]);
}}
/>
)}
/>
</FormGroup>
<FormGroup
label={t("active")}
fieldId="kc-active"
labelIcon={
<HelpItem
helpText="realm-settings-help:active"
forLabel={t("active")}
forID={t("common:helpLabel", { label: t("active") })}
/>
}
>
<Controller
name="config.active"
control={form.control}
defaultValue={["true"]}
render={({ onChange, value }) => {
return (
<Switch
id="kc-active-switch"
label={t("common:on")}
labelOff={t("common:off")}
isChecked={value[0] === "true"}
data-testid={value[0] === "true" ? "active" : "passive"}
onChange={(value) => {
onChange([value.toString()]);
}}
/>
);
}}
/>
</FormGroup>
<FormGroup
label={t("secretSize")}
fieldId="kc-hmac-keysize"
labelIcon={
<HelpItem
helpText="realm-settings-help:secretSize"
forLabel={t("secretSize")}
forID={t("common:helpLabel", { label: t("secretSize") })}
/>
}
>
<Controller
name="config.secretSize"
control={form.control}
defaultValue={["64"]}
render={({ onChange, value }) => (
<Select
toggleId="kc-hmac-keysize"
onToggle={(isExpanded) => setIsKeySizeDropdownOpen(isExpanded)}
onSelect={(_, value) => {
onChange([value.toString()]);
setIsKeySizeDropdownOpen(false);
}}
selections={[value.toString()]}
isOpen={isKeySizeDropdownOpen}
variant={SelectVariant.single}
aria-label={t("hmacKeySize")}
data-testid="select-secret-size"
>
{hmacSecretSizeOptions!.map((item) => (
<SelectOption
selected={item === value}
key={item}
value={item}
/>
))}
</Select>
)}
/>
</FormGroup>
<FormGroup
label={t("algorithm")}
fieldId="kc-algorithm"
labelIcon={
<HelpItem
helpText="realm-settings-help:algorithm"
forLabel={t("algorithm")}
forID={t("common:helpLabel", { label: t("algorithm") })}
/>
}
>
<Controller
name="config.algorithm"
control={form.control}
defaultValue={["HS-256"]}
render={({ onChange, value }) => (
<Select
toggleId="kc-elliptic"
onToggle={(isExpanded) =>
setIsEllipticCurveDropdownOpen(isExpanded)
}
onSelect={(_, value) => {
onChange([value.toString()]);
setIsEllipticCurveDropdownOpen(false);
}}
selections={[value.toString()]}
variant={SelectVariant.single}
aria-label={t("emailTheme")}
isOpen={isEllipticCurveDropdownOpen}
placeholderText="Select one..."
data-testid="select-email-theme"
>
{hmacAlgorithmOptions!.map((p, idx) => (
<SelectOption
selected={p === value}
key={`email-theme-${idx}`}
value={p}
></SelectOption>
))}
</Select>
)}
/>
</FormGroup>
<ActionGroup className="kc-hmac-form-buttons">
<Button
className="kc-hmac-form-save-button"
data-testid="add-provider-button"
variant="primary"
type="submit"
>
{t("common:save")}
</Button>
<Button
className="kc-hmac-form-cancel-button"
onClick={(!editMode && handleModalToggle) || undefined}
variant="link"
>
{t("common:cancel")}
</Button>
</ActionGroup>
</FormAccess>
);
};
export const HMACGeneratedSettings = () => {
const { t } = useTranslation("realm-settings");
const providerId = useRouteMatch<MatchParams>(
"/:realm/realm-settings/keys/:id?/:providerType?/settings"
)?.params.providerType;
return (
<>
<ViewHeader titleKey={t("editProvider")} subKey={providerId} />
<PageSection variant="light">
<HMACGeneratedForm providerType={providerId} editMode />
</PageSection>
</>
);
};

View file

@ -0,0 +1,36 @@
import React from "react";
import { Modal, ModalVariant } from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { HMACGeneratedForm } from "./HMACGeneratedForm";
type HMACGeneratedModalProps = {
providerType: string;
handleModalToggle: () => void;
refresh: () => void;
open: boolean;
};
export const HMACGeneratedModal = ({
providerType,
handleModalToggle,
open,
refresh,
}: HMACGeneratedModalProps) => {
const { t } = useTranslation("realm-settings");
return (
<Modal
className="add-provider-modal"
variant={ModalVariant.medium}
title={t("addProvider")}
isOpen={open}
onClose={handleModalToggle}
>
<HMACGeneratedForm
providerType={providerType}
handleModalToggle={handleModalToggle}
refresh={refresh}
/>
</Modal>
);
};

View file

@ -37,6 +37,7 @@ import {
import { AddOpenIdConnect } from "./identity-providers/add/AddOpenIdConnect";
import { DetailSettings } from "./identity-providers/add/DetailSettings";
import { AESGeneratedSettings } from "./realm-settings/key-providers/aes-generated/AESGeneratedForm";
import { HMACGeneratedSettings } from "./realm-settings/key-providers/hmac-generated/HMACGeneratedForm";
export type RouteDef = BreadcrumbsRoute & {
access: AccessType;
@ -190,6 +191,12 @@ export const routes: RoutesFn = (t: TFunction) => [
breadcrumb: t("realm-settings:editProvider"),
access: "view-realm",
},
{
path: "/:realm/realm-settings/keys/:id?/hmac-generated/settings",
component: HMACGeneratedSettings,
breadcrumb: t("realm-settings:editProvider"),
access: "view-realm",
},
{
path: "/:realm/authentication",
component: AuthenticationSection,