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

[Search] [Onboarding] Search api key refactor #199790

Merged
merged 26 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
d2a9aba
Move mutation queries to hooks
yansavitski Nov 5, 2024
b058ff3
Refactor initialise key logic
yansavitski Nov 8, 2024
b141975
Move values out of provider to a more suitable place
yansavitski Nov 8, 2024
680ddb3
Call init only once
yansavitski Nov 8, 2024
037c52a
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 12, 2024
225010c
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 12, 2024
e6160af
Fix code types
yansavitski Nov 12, 2024
17a8cf1
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 13, 2024
daa8575
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 13, 2024
cdb097c
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 13, 2024
97d28d2
Prevent multiple call for creatApiKey
yansavitski Nov 13, 2024
40eb962
Remove skip label from api test
yansavitski Nov 14, 2024
7c9470d
Remove skip label from flaky test and add fix for it
yansavitski Nov 14, 2024
3f5e7c5
Wrap api test in its own describe
yansavitski Nov 14, 2024
2326d66
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 18, 2024
dcdb718
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 19, 2024
b444ad1
Merge branch 'main' into search-api-key-refactor
elasticmachine Nov 22, 2024
16917a5
Skip flaky
yansavitski Nov 24, 2024
e875d79
Merge branch 'search-api-key-refactor' of github.com:yansavitski/kiba…
yansavitski Nov 24, 2024
0489287
Merge branch 'main' into search-api-key-refactor
yansavitski Nov 25, 2024
7413ced
Merge branch 'main' of github.com:elastic/kibana into search-api-key-…
yansavitski Nov 26, 2024
bc89f68
Add check privileges more than viewer role
yansavitski Nov 27, 2024
2808c45
Merge branch 'search-api-key-refactor' of github.com:yansavitski/kiba…
yansavitski Nov 27, 2024
f4e6218
Check firstly if user has privileges to create api key
yansavitski Nov 27, 2024
7a47972
Add test to show no privileges
yansavitski Nov 27, 2024
16db427
Merge branch 'main' into search-api-key-refactor
yansavitski Nov 27, 2024
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
Expand Up @@ -23,30 +23,31 @@ import { ApiKeyFlyoutWrapper } from './api_key_flyout_wrapper';
import { useSearchApiKey } from '../hooks/use_search_api_key';
import { Status } from '../constants';

const API_KEY_MASK = '•'.repeat(60);

interface ApiKeyFormProps {
hasTitle?: boolean;
}

export const ApiKeyForm: React.FC<ApiKeyFormProps> = ({ hasTitle = true }) => {
const [showFlyout, setShowFlyout] = useState(false);
const { apiKey, status, updateApiKey, toggleApiKeyVisibility, displayedApiKey, apiKeyIsVisible } =
useSearchApiKey();
const { apiKey, status, updateApiKey, toggleApiKeyVisibility } = useSearchApiKey();

const titleLocale = i18n.translate('searchApiKeysComponents.apiKeyForm.title', {
defaultMessage: 'API Key',
});

if (apiKey && displayedApiKey) {
if (apiKey) {
return (
<FormInfoField
label={hasTitle ? titleLocale : undefined}
value={displayedApiKey}
value={status === Status.showPreviewKey ? apiKey : API_KEY_MASK}
copyValue={apiKey}
dataTestSubj="apiKeyFormAPIKey"
copyValueDataTestSubj="APIKeyButtonCopy"
actions={[
<EuiButtonIcon
iconType={apiKeyIsVisible ? 'eyeClosed' : 'eye'}
iconType={status === Status.showPreviewKey ? 'eyeClosed' : 'eye'}
color="text"
onClick={toggleApiKeyVisibility}
data-test-subj="showAPIKeyButton"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* 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", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { useMutation } from '@tanstack/react-query';
import type { APIKeyCreationResponse } from '@kbn/search-api-keys-server/types';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { APIRoutes } from '../types';

export const useCreateApiKey = ({
onSuccess,
onError,
}: {
onSuccess(key: APIKeyCreationResponse): void;
onError(err: XMLHttpRequest): void;
}) => {
const { http } = useKibana().services;
const { mutateAsync: createApiKey } = useMutation<APIKeyCreationResponse | undefined>({
mutationFn: async () => {
try {
if (!http?.post) {
throw new Error('HTTP service is unavailable');
}

return await http.post<APIKeyCreationResponse>(APIRoutes.API_KEYS);
} catch (err) {
onError(err);
}
},
onSuccess: (receivedApiKey) => {
if (receivedApiKey) {
onSuccess(receivedApiKey);
}
},
});

return createApiKey;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* 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", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { useMutation } from '@tanstack/react-query';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { APIRoutes } from '../types';

export const useValidateApiKey = (): ((id: string) => Promise<boolean>) => {
const { http } = useKibana().services;
const { mutateAsync: validateApiKey } = useMutation(async (id: string) => {
try {
if (!http?.post) {
throw new Error('HTTP service is unavailable');
}

const response = await http.post<{ isValid: boolean }>(APIRoutes.API_KEY_VALIDITY, {
body: JSON.stringify({ id }),
});

return response.isValid;
} catch (err) {
return false;
}
});

return validateApiKey;
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,176 +7,109 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import React, { useCallback, useReducer, createContext, useEffect } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { APIKeyCreationResponse } from '@kbn/search-api-keys-server/types';
import { APIRoutes } from '../types';
import React, { useCallback, createContext, useState, useMemo, useRef } from 'react';
import { useCreateApiKey } from '../hooks/use_create_api_key';
import { Status } from '../constants';
import { useValidateApiKey } from '../hooks/use_validate_api_key';

const API_KEY_STORAGE_KEY = 'searchApiKey';
const API_KEY_MASK = '•'.repeat(60);

interface ApiKeyState {
status: Status;
apiKey: string | null;
}

interface APIKeyContext {
displayedApiKey: string | null;
apiKey: string | null;
toggleApiKeyVisibility: () => void;
updateApiKey: ({ id, encoded }: { id: string; encoded: string }) => void;
status: Status;
apiKeyIsVisible: boolean;
initialiseKey: () => void;
}

type Action =
| { type: 'SET_API_KEY'; apiKey: string; status: Status }
| { type: 'SET_STATUS'; status: Status }
| { type: 'CLEAR_API_KEY' }
| { type: 'TOGGLE_API_KEY_VISIBILITY' };

const initialState: ApiKeyState = {
apiKey: null,
status: Status.uninitialized,
};

const reducer = (state: ApiKeyState, action: Action): ApiKeyState => {
switch (action.type) {
case 'SET_API_KEY':
return { ...state, apiKey: action.apiKey, status: action.status };
case 'SET_STATUS':
return { ...state, status: action.status };
case 'TOGGLE_API_KEY_VISIBILITY':
return {
...state,
status:
state.status === Status.showHiddenKey ? Status.showPreviewKey : Status.showHiddenKey,
};
case 'CLEAR_API_KEY':
return { ...state, apiKey: null, status: Status.showCreateButton };
default:
return state;
}
};

export const ApiKeyContext = createContext<APIKeyContext>({
displayedApiKey: null,
apiKey: null,
toggleApiKeyVisibility: () => {},
updateApiKey: () => {},
status: Status.uninitialized,
apiKeyIsVisible: false,
initialiseKey: () => {},
});

export const SearchApiKeyProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
const { http } = useKibana().services;
const [state, dispatch] = useReducer(reducer, initialState);

const isInitialising = useRef(false);
const [apiKey, setApiKey] = useState<string | null>(null);
const [status, setStatus] = useState<Status>(Status.uninitialized);
const updateApiKey = useCallback(({ id, encoded }: { id: string; encoded: string }) => {
sessionStorage.setItem(API_KEY_STORAGE_KEY, JSON.stringify({ id, encoded }));
dispatch({ type: 'SET_API_KEY', apiKey: encoded, status: Status.showHiddenKey });
}, []);
const handleShowKeyVisibility = useCallback(() => {
dispatch({ type: 'TOGGLE_API_KEY_VISIBILITY' });
setApiKey(encoded);
setStatus(Status.showHiddenKey);
}, []);
const initialiseKey = useCallback(() => {
dispatch({ type: 'SET_STATUS', status: Status.loading });
const toggleApiKeyVisibility = useCallback(() => {
setStatus((prevStatus) =>
prevStatus === Status.showHiddenKey ? Status.showPreviewKey : Status.showHiddenKey
);
}, []);
const { mutateAsync: validateApiKey } = useMutation(async (id: string) => {
try {
if (!http?.post) {
throw new Error('HTTP service is unavailable');
}

const response = await http.post<{ isValid: boolean }>(APIRoutes.API_KEY_VALIDITY, {
body: JSON.stringify({ id }),
});

return response.isValid;
} catch (err) {
return false;
}
});
const { mutateAsync: createApiKey } = useMutation<APIKeyCreationResponse | undefined>({
mutationFn: async () => {
try {
if (!http?.post) {
throw new Error('HTTP service is unavailable');
}

return await http.post<APIKeyCreationResponse>(APIRoutes.API_KEYS);
} catch (err) {
if (err.response?.status === 400) {
dispatch({ type: 'SET_STATUS', status: Status.showCreateButton });
} else if (err.response?.status === 403) {
dispatch({ type: 'SET_STATUS', status: Status.showUserPrivilegesError });
} else {
throw err;
}
}
},
const validateApiKey = useValidateApiKey();
const createApiKey = useCreateApiKey({
onSuccess: (receivedApiKey) => {
if (receivedApiKey) {
sessionStorage.setItem(
API_KEY_STORAGE_KEY,
JSON.stringify({ id: receivedApiKey.id, encoded: receivedApiKey.encoded })
);
dispatch({
type: 'SET_API_KEY',
apiKey: receivedApiKey.encoded,
status: Status.showHiddenKey,
});
setApiKey(receivedApiKey.encoded);
setStatus(Status.showHiddenKey);
}
},
onError: (err) => {
if (err.response?.status === 400) {
setStatus(Status.showCreateButton);
} else if (err.response?.status === 403) {
setStatus(Status.showUserPrivilegesError);
} else {
throw err;
}
},
});
const initialiseKey = useCallback(async () => {
if (status !== Status.uninitialized || isInitialising.current) {
return;
}

useEffect(() => {
const initialiseApiKey = async () => {
try {
if (state.status === Status.loading) {
const storedKey = sessionStorage.getItem(API_KEY_STORAGE_KEY);
isInitialising.current = true;

try {
setStatus(Status.loading);
const storedKey = sessionStorage.getItem(API_KEY_STORAGE_KEY);

if (storedKey) {
const { id, encoded } = JSON.parse(storedKey);
if (storedKey) {
const { id, encoded } = JSON.parse(storedKey);

if (await validateApiKey(id)) {
dispatch({
type: 'SET_API_KEY',
apiKey: encoded,
status: Status.showHiddenKey,
});
} else {
sessionStorage.removeItem(API_KEY_STORAGE_KEY);
dispatch({
type: 'CLEAR_API_KEY',
});
await createApiKey();
}
} else {
await createApiKey();
}
if (await validateApiKey(id)) {
setApiKey(encoded);
setStatus(Status.showHiddenKey);
} else {
sessionStorage.removeItem(API_KEY_STORAGE_KEY);
setApiKey(null);
setStatus(Status.showCreateButton);
await createApiKey();
}
} catch (e) {
dispatch({ type: 'CLEAR_API_KEY' });
} else {
await createApiKey();
}
};

initialiseApiKey();
}, [state.status, createApiKey, validateApiKey]);

const value: APIKeyContext = {
displayedApiKey: state.status === Status.showPreviewKey ? state.apiKey : API_KEY_MASK,
apiKey: state.apiKey,
toggleApiKeyVisibility: handleShowKeyVisibility,
updateApiKey,
status: state.status,
apiKeyIsVisible: state.status === Status.showPreviewKey,
initialiseKey,
};
} catch (e) {
setApiKey(null);
setStatus(Status.showCreateButton);
} finally {
isInitialising.current = false;
}
}, [status, createApiKey, validateApiKey]);

const value: APIKeyContext = useMemo(
() => ({
apiKey,
toggleApiKeyVisibility,
updateApiKey,
status,
initialiseKey,
}),
[apiKey, status, toggleApiKeyVisibility, updateApiKey, initialiseKey]
);

return <ApiKeyContext.Provider value={value}>{children}</ApiKeyContext.Provider>;
};
Original file line number Diff line number Diff line change
Expand Up @@ -60,25 +60,17 @@ export const AddDocumentsCodeExample = ({
generateSampleDocument(codeSampleMappings, `Example text ${num}`)
);
}, [codeSampleMappings]);
const { apiKey, apiKeyIsVisible } = useSearchApiKey();
const { apiKey } = useSearchApiKey();
const codeParams: IngestCodeSnippetParameters = useMemo(() => {
return {
indexName,
elasticsearchURL: elasticsearchUrl,
sampleDocuments,
indexHasMappings,
mappingProperties: codeSampleMappings,
apiKey: apiKeyIsVisible && apiKey ? apiKey : undefined,
apiKey: apiKey || undefined,
};
}, [
indexName,
elasticsearchUrl,
sampleDocuments,
codeSampleMappings,
indexHasMappings,
apiKeyIsVisible,
apiKey,
]);
}, [indexName, elasticsearchUrl, sampleDocuments, codeSampleMappings, indexHasMappings, apiKey]);

return (
<EuiPanel
Expand Down
Loading