Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Synthetics] introduce new spaces field for synthetics api keys #211816

Merged
merged 7 commits into from
Feb 21, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import * as t from 'io-ts';

export const APIKeyCodec = t.type({
spaces: t.array(t.string),
});

export type SyntheticsProjectAPIKey = t.TypeOf<typeof APIKeyCodec>;
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,28 @@ import React, { useEffect } from 'react';
import { i18n } from '@kbn/i18n';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { EuiComboBox, EuiFormRow } from '@elastic/eui';
import { Controller, useFormContext } from 'react-hook-form';
import { Controller, FieldValues, Path, useFormContext } from 'react-hook-form';
import { ALL_SPACES_ID } from '@kbn/security-plugin/public';

import { ClientPluginsStart } from '../../../../../plugin';
import { PrivateLocation } from '../../../../../../common/runtime_types';

export const NAMESPACES_NAME = 'spaces';
interface SpaceSelectorProps {
module: 'location' | 'apiKey';
}

export const SpaceSelector: React.FC = () => {
export const SpaceSelector = <T extends FieldValues>({ module }: SpaceSelectorProps) => {
const NAMESPACES_NAME = 'spaces' as Path<T>;
const { services } = useKibana<ClientPluginsStart>();
const [spacesList, setSpacesList] = React.useState<Array<{ id: string; label: string }>>([]);
const data = services.spaces?.ui.useSpaces();

const HELP_TEXT = module === 'location' ? LOCATION_HELP_TEXT : API_KEY_HELP_TEXT;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of passing the module name, I'd just pass the help text. That way the parent components can be responsible for defining the content.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Done ✅


const {
control,
formState: { isSubmitted },
trigger,
} = useFormContext<PrivateLocation>();
} = useFormContext<T>();
const { isTouched, error } = control.getFieldState(NAMESPACES_NAME);

const showFieldInvalid = (isSubmitted || isTouched) && !!error;
Expand Down Expand Up @@ -122,6 +126,13 @@ const SPACES_LABEL = i18n.translate('xpack.synthetics.privateLocation.spacesLabe
defaultMessage: 'Spaces ',
});

const HELP_TEXT = i18n.translate('xpack.synthetics.privateLocation.spacesHelpText', {
defaultMessage: 'Select the spaces where this location will be available.',
const LOCATION_HELP_TEXT = i18n.translate(
'xpack.synthetics.privateLocation.locationSpacesHelpText',
{
defaultMessage: 'Select the spaces where this location will be available.',
}
);

const API_KEY_HELP_TEXT = i18n.translate('xpack.synthetics.privateLocation.apiKeySpacesHelpText', {
defaultMessage: 'Select the spaces where this API key will be available.',
});
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const LocationForm = ({ privateLocations }: { privateLocations: PrivateLo
<EuiSpacer />
<BrowserMonitorCallout />
<EuiSpacer />
<SpaceSelector />
<SpaceSelector module="location" />
</EuiForm>
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ describe('<ProjectAPIKeys />', () => {
});

it('shows appropriate content when user does not have correct uptime save permissions', () => {
// const apiKey = 'sampleApiKey';
render(<ProjectAPIKeys />, {
state,
core: makeUptimePermissionsCore({ save: false }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,53 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import React, { useEffect, useState } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { EuiText, EuiLink, EuiEmptyPrompt, EuiSwitch, EuiSpacer } from '@elastic/eui';
import { EuiText, EuiLink, EuiEmptyPrompt, EuiSwitch, EuiSpacer, EuiForm } from '@elastic/eui';
import { SpacesContextProps } from '@kbn/spaces-plugin/public';
import { i18n } from '@kbn/i18n';
import { useFetcher } from '@kbn/observability-shared-plugin/public';
import { IHttpFetchError, ResponseErrorBody } from '@kbn/core-http-browser';
import { ALL_SPACES_ID } from '@kbn/security-plugin/public';
import { FormProvider } from 'react-hook-form';
import { HelpCommands } from './help_commands';
import { LoadingState } from '../../monitors_page/overview/overview/monitor_detail_flyout';
import { fetchProjectAPIKey } from '../../../state/monitor_management/api';
import { ClientPluginsStart } from '../../../../../plugin';
import { ApiKeyBtn } from './api_key_btn';
import { useEnablement } from '../../../hooks';
import { SpaceSelector } from '../components/spaces_select';
import { useFormWrapped } from '../../../../../hooks/use_form_wrapped';

const syntheticsTestRunDocsLink =
'https://www.elastic.co/guide/en/observability/current/synthetic-run-tests.html';

const getEmptyFunctionComponent: React.FC<SpacesContextProps> = ({ children }) => <>{children}</>;

export const ProjectAPIKeys = () => {
const { loading: enablementLoading, canManageApiKeys } = useEnablement();
const [apiKey, setApiKey] = useState<string | undefined>(undefined);
const [loadAPIKey, setLoadAPIKey] = useState(false);
const [accessToElasticManagedLocations, setAccessToElasticManagedLocations] = useState(true);

const { spaces: spacesApi } = useKibana<ClientPluginsStart>().services;

const ContextWrapper = useMemo(
() =>
spacesApi ? spacesApi.ui.components.getSpacesContextProvider : getEmptyFunctionComponent,
[spacesApi]
);

const form = useFormWrapped({
mode: 'onSubmit',
reValidateMode: 'onChange',
shouldFocusError: true,
defaultValues: {
apiKey,
spaces: [ALL_SPACES_ID],
},
});

const kServices = useKibana<ClientPluginsStart>().services;
const canSaveIntegrations: boolean =
!!kServices?.fleet?.authz.integrations.writeIntegrationPolicies;
Expand All @@ -35,7 +60,10 @@ export const ProjectAPIKeys = () => {

const { data, loading, error } = useFetcher(async () => {
if (loadAPIKey) {
return fetchProjectAPIKey(accessToElasticManagedLocations && Boolean(canUsePublicLocations));
return fetchProjectAPIKey(
accessToElasticManagedLocations && Boolean(canUsePublicLocations),
form.getValues()?.spaces
);
}
return null;
// FIXME: Dario thinks there is a better way to do this but
Expand Down Expand Up @@ -69,64 +97,67 @@ export const ProjectAPIKeys = () => {
}

return (
<>
<EuiEmptyPrompt
style={{ maxWidth: '50%' }}
title={<h2>{GET_API_KEY_GENERATE}</h2>}
body={
canSave && canManageApiKeys ? (
<>
<EuiText>
{GET_API_KEY_LABEL_DESCRIPTION}{' '}
{!canSaveIntegrations ? `${API_KEY_DISCLAIMER} ` : ''}
<EuiLink
data-test-subj="syntheticsProjectAPIKeysLink"
href={syntheticsTestRunDocsLink}
external
target="_blank"
>
{LEARN_MORE_LABEL}
</EuiLink>
</EuiText>
<EuiSpacer />
<EuiSwitch
label={i18n.translate('xpack.synthetics.features.elasticManagedLocations', {
defaultMessage: 'Elastic managed locations enabled',
})}
checked={accessToElasticManagedLocations && Boolean(canUsePublicLocations)}
onChange={() => {
setAccessToElasticManagedLocations(!accessToElasticManagedLocations);
}}
disabled={!canUsePublicLocations}
/>
</>
) : (
<>
<EuiText>
{GET_API_KEY_REDUCED_PERMISSIONS_LABEL}{' '}
<EuiLink
data-test-subj="syntheticsProjectAPIKeysLink"
href={syntheticsTestRunDocsLink}
external
target="_blank"
>
{LEARN_MORE_LABEL}
</EuiLink>
</EuiText>
</>
)
}
actions={
<ApiKeyBtn
loading={loading}
setLoadAPIKey={setLoadAPIKey}
apiKey={apiKey}
isDisabled={!canSave || !canManageApiKeys}
/>
}
/>
{apiKey && <HelpCommands apiKey={apiKey} />}
</>
<ContextWrapper>
<FormProvider {...form}>
<EuiEmptyPrompt
style={{ maxWidth: '50%' }}
title={<h2>{GET_API_KEY_GENERATE}</h2>}
body={
canSave && canManageApiKeys ? (
<EuiForm component="form" noValidate>
<EuiText>
{GET_API_KEY_LABEL_DESCRIPTION}{' '}
{!canSaveIntegrations ? `${API_KEY_DISCLAIMER} ` : ''}
<EuiLink
data-test-subj="syntheticsProjectAPIKeysLink"
href={syntheticsTestRunDocsLink}
external
target="_blank"
>
{LEARN_MORE_LABEL}
</EuiLink>
</EuiText>
<EuiSpacer />
<EuiSwitch
label={i18n.translate('xpack.synthetics.features.elasticManagedLocations', {
defaultMessage: 'Elastic managed locations enabled',
})}
checked={accessToElasticManagedLocations && Boolean(canUsePublicLocations)}
onChange={() => {
setAccessToElasticManagedLocations(!accessToElasticManagedLocations);
}}
disabled={!canUsePublicLocations}
/>
<SpaceSelector module="apiKey" />
</EuiForm>
) : (
<>
<EuiText>
{GET_API_KEY_REDUCED_PERMISSIONS_LABEL}{' '}
<EuiLink
data-test-subj="syntheticsProjectAPIKeysLink"
href={syntheticsTestRunDocsLink}
external
target="_blank"
>
{LEARN_MORE_LABEL}
</EuiLink>
</EuiText>
</>
)
}
actions={
<ApiKeyBtn
loading={loading}
setLoadAPIKey={setLoadAPIKey}
apiKey={apiKey}
isDisabled={!canSave || !canManageApiKeys}
/>
}
/>
{apiKey && <HelpCommands apiKey={apiKey} />}
</FormProvider>
</ContextWrapper>
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,12 @@ export const updateMonitorAPI = async ({
};

export const fetchProjectAPIKey = async (
accessToElasticManagedLocations: boolean
accessToElasticManagedLocations: boolean,
spaces: string[]
): Promise<ProjectAPIKeyResponse> => {
return await apiService.get(SYNTHETICS_API_URLS.SYNTHETICS_PROJECT_APIKEY, {
accessToElasticManagedLocations,
spaces,
});
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,10 @@ class ApiService {
const { version, spaceId, ...queryParams } = params;
const response = await this._http!.fetch<T>({
path: this.parseApiUrl(apiUrl, spaceId),
query: queryParams,
query: {
...queryParams,
spaces: queryParams.spaces ? JSON.stringify(queryParams.spaces) : undefined,
},
version,
...(options ?? {}),
...(spaceId ? { prependBasePath: false } : {}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const getAPIKeySyntheticsRoute: SyntheticsRestApiRouteFactory = () => ({
path: SYNTHETICS_API_URLS.SYNTHETICS_PROJECT_APIKEY,
validate: {
query: schema.object({
spaces: schema.maybe(schema.arrayOf(schema.string())),
accessToElasticManagedLocations: schema.maybe(schema.boolean()),
}),
},
Expand All @@ -29,7 +30,7 @@ export const getAPIKeySyntheticsRoute: SyntheticsRestApiRouteFactory = () => ({
server,
response,
}): Promise<ProjectAPIKeyResponse | IKibanaResponse> => {
const { accessToElasticManagedLocations } = request.query;
const { accessToElasticManagedLocations, spaces } = request.query;

if (accessToElasticManagedLocations) {
const elasticManagedLocationsEnabled =
Expand All @@ -52,6 +53,7 @@ export const getAPIKeySyntheticsRoute: SyntheticsRestApiRouteFactory = () => ({
request,
server,
accessToElasticManagedLocations,
spaces,
});

return { apiKey };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,12 @@ export const generateProjectAPIKey = async ({
server,
request,
accessToElasticManagedLocations = true,
spaces = [ALL_SPACES_ID],
}: {
server: SyntheticsServerSetup;
request: KibanaRequest;
accessToElasticManagedLocations?: boolean;
spaces?: string[];
}): Promise<SecurityCreateApiKeyResponse | null> => {
const { security } = server;
const isApiKeysEnabled = await security.authc.apiKeys?.areAPIKeysEnabled();
Expand All @@ -138,7 +140,7 @@ export const generateProjectAPIKey = async ({
kibana: [
{
base: [],
spaces: [ALL_SPACES_ID],
spaces,
feature: {
uptime: [accessToElasticManagedLocations ? 'all' : 'minimal_all'],
},
Expand Down