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] api-key plugin #191926

Merged
merged 48 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
1f7e40b
Prepare api-key plugin configuration
yansavitski Sep 2, 2024
345225a
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Sep 2, 2024
e4b19ba
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Sep 2, 2024
7e33030
WIP
joemcelroy Sep 2, 2024
b1a8356
api keys plugin working
joemcelroy Sep 2, 2024
df937a1
WIP
joemcelroy Sep 2, 2024
67b8364
implement API for API Key generation
joemcelroy Sep 3, 2024
245d4cb
fix privilege
joemcelroy Sep 3, 2024
9f256cd
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Sep 5, 2024
25c3260
Add get api route
yansavitski Sep 8, 2024
e2024d7
Update validity route
yansavitski Sep 16, 2024
07c80e7
Add apikeyfrom component and api search hook
yansavitski Sep 16, 2024
9734255
Use dispatch for state and apiKey
yansavitski Sep 17, 2024
69792d1
Merge branch 'main' of github.com:elastic/kibana into onboarding-api-…
yansavitski Sep 17, 2024
703261c
Use plugin
yansavitski Sep 17, 2024
53f6263
Fix PR comments
yansavitski Sep 23, 2024
ecb4ea2
Merge branch 'main' of github.com:elastic/kibana into onboarding-api-…
yansavitski Sep 23, 2024
fedef8b
[CI] Auto-commit changed files from 'node scripts/lint_packages --fix'
kibanamachine Sep 23, 2024
46d30a3
[CI] Auto-commit changed files from 'node scripts/yarn_deduplicate'
kibanamachine Sep 23, 2024
20db7e8
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Sep 23, 2024
07661b2
add visibility for api key
joemcelroy Sep 23, 2024
677a365
added FTRs + fixes to flows
joemcelroy Sep 24, 2024
129b383
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Sep 26, 2024
e942537
update to package
joemcelroy Sep 26, 2024
40e9973
moving to a package
joemcelroy Sep 27, 2024
4d962fe
updates to package move
joemcelroy Sep 27, 2024
7ea3563
fix prettier
joemcelroy Sep 27, 2024
8c4e331
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Sep 27, 2024
3c25c83
update api form design
joemcelroy Sep 27, 2024
65a8d4e
add form field
joemcelroy Sep 27, 2024
9e31a77
[CI] Auto-commit changed files from 'node scripts/generate codeowners'
kibanamachine Sep 27, 2024
074e9a1
[CI] Auto-commit changed files from 'node scripts/notice'
kibanamachine Sep 27, 2024
e281ce3
fix ts issues
joemcelroy Sep 30, 2024
4a2da8f
fix i18n issues
joemcelroy Sep 30, 2024
6b4f4ee
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Sep 30, 2024
f1680c2
Merge branch 'onboarding-api-plugin' of github.com:yansavitski/kibana…
joemcelroy Sep 30, 2024
c93db2d
[CI] Auto-commit changed files from 'node scripts/notice'
kibanamachine Sep 30, 2024
265379c
[CI] Auto-commit changed files from 'node scripts/lint_ts_projects --…
kibanamachine Sep 30, 2024
bb5fa80
fix jest configs
joemcelroy Sep 30, 2024
dc203dd
update ftrs
joemcelroy Sep 30, 2024
aedde54
update readme
joemcelroy Sep 30, 2024
740a89b
resolve conflicts
joemcelroy Sep 30, 2024
fcf24f3
fix typo
joemcelroy Sep 30, 2024
c0a950d
Merge remote-tracking branch 'upstream/main' into onboarding-api-plugin
joemcelroy Oct 1, 2024
3ce5e0b
added provider; toggle visibility of apiKey; implement code sample up…
joemcelroy Oct 1, 2024
f25dcec
updates based on feedback
joemcelroy Oct 1, 2024
cd87f44
[CI] Auto-commit changed files from 'node scripts/generate codeowners'
kibanamachine Oct 1, 2024
b7029a8
[CI] Auto-commit changed files from 'node scripts/lint_ts_projects --…
kibanamachine Oct 1, 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
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,7 @@ packages/kbn-search-errors @elastic/kibana-data-discovery
examples/search_examples @elastic/kibana-data-discovery
x-pack/plugins/search_homepage @elastic/search-kibana
packages/kbn-search-index-documents @elastic/search-kibana
x-pack/plugins/search_api_keys @elastic/search-kibana
x-pack/plugins/search_indices @elastic/search-kibana
x-pack/plugins/search_inference_endpoints @elastic/search-kibana
x-pack/plugins/search_notebooks @elastic/search-kibana
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,7 @@
"@kbn/screenshotting-example-plugin": "link:x-pack/examples/screenshotting_example",
"@kbn/screenshotting-plugin": "link:x-pack/plugins/screenshotting",
"@kbn/screenshotting-server": "link:packages/kbn-screenshotting-server",
"@kbn/search-api-keys": "link:x-pack/plugins/search_api_keys",
"@kbn/search-api-panels": "link:packages/kbn-search-api-panels",
"@kbn/search-assistant": "link:x-pack/plugins/search_assistant",
"@kbn/search-connectors": "link:packages/kbn-search-connectors",
Expand Down
2 changes: 2 additions & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -1474,6 +1474,8 @@
"@kbn/screenshotting-plugin/*": ["x-pack/plugins/screenshotting/*"],
"@kbn/screenshotting-server": ["packages/kbn-screenshotting-server"],
"@kbn/screenshotting-server/*": ["packages/kbn-screenshotting-server/*"],
"@kbn/search-api-keys": ["x-pack/plugins/search_api_keys"],
"@kbn/search-api-keys/*": ["x-pack/plugins/search_api_keys/*"],
"@kbn/search-api-panels": ["packages/kbn-search-api-panels"],
"@kbn/search-api-panels/*": ["packages/kbn-search-api-panels/*"],
"@kbn/search-assistant": ["x-pack/plugins/search_assistant"],
Expand Down
1 change: 1 addition & 0 deletions x-pack/.i18nrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
"xpack.screenshotting": "plugins/screenshotting",
"xpack.searchHomepage": "plugins/search_homepage",
"xpack.searchIndices": "plugins/search_indices",
"xpack.searchApiKeys": "plugins/search_api_keys",
"xpack.searchNotebooks": "plugins/search_notebooks",
"xpack.searchPlayground": "plugins/search_playground",
"xpack.searchInferenceEndpoints": "plugins/search_inference_endpoints",
Expand Down
3 changes: 3 additions & 0 deletions x-pack/plugins/search_api_keys/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Search API Keys

The Search API Keys plugin is a shared components and utilities to simplify managing the API Keys experience for elasticsearch users across stack and serverless search solutions.
10 changes: 10 additions & 0 deletions x-pack/plugins/search_api_keys/common/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* 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.
*/

export const PLUGIN_ID = 'searchApiKeys';
export const PLUGIN_NAME = 'searchApiKeys';
export const PLUGIN_PATH = '/app/api_key';
25 changes: 25 additions & 0 deletions x-pack/plugins/search_api_keys/common/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* 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.
*/

export enum APIRoutes {
API_KEYS = '/internal/search_api_keys',
API_KEY_VALIDITY = '/internal/search_api_keys/validity',
}

export interface APIKey {
id: string;
name: string;
expiration?: number;
invalidated?: boolean;
}

export interface APIKeyCreationResponse extends Pick<APIKey, 'id' | 'name' | 'expiration'> {
api_key: string;
encoded: string;
}

export type GetApiKeyResponse = APIKey;
15 changes: 15 additions & 0 deletions x-pack/plugins/search_api_keys/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/*
* 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.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../../..',
roots: ['<rootDir>/x-pack/plugins/search_playground'],
yansavitski marked this conversation as resolved.
Show resolved Hide resolved
coverageDirectory: '<rootDir>/target/kibana-coverage/jest/x-pack/plugins/search_playground',
coverageReporters: ['text', 'html'],
collectCoverageFrom: ['<rootDir>/x-pack/plugins/search_playground/{public,server}/**/*.{ts,tsx}'],
};
23 changes: 23 additions & 0 deletions x-pack/plugins/search_api_keys/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"type": "plugin",
"id": "@kbn/search-api-keys",
"owner": "@elastic/search-kibana",
"plugin": {
"id": "searchApiKeys",
"server": true,
"browser": true,
"configPath": [
"xpack",
"searchApiKeys"
],
"requiredPlugins": [
"kibanaReact",
],
"optionalPlugins": [
"cloud",
"console",
"usageCollection",
],
"requiredBundles": []
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* 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 { ApiKeyFlyout } from '@kbn/security-api-key-management';
import React from 'react';
import { useCurrentUser } from '../hooks/use_current_user';

interface ApiKeyFlyoutWrapperProps {
onClose: () => void;
onSuccess: (apiKey: { id: string; encoded: string }) => void;
}

export const ApiKeyFlyoutWrapper: React.FC<ApiKeyFlyoutWrapperProps> = ({ onClose, onSuccess }) => {
const user = useCurrentUser();

return <ApiKeyFlyout onCancel={onClose} onSuccess={onSuccess} currentUser={user} />;
};
83 changes: 83 additions & 0 deletions x-pack/plugins/search_api_keys/public/components/api_key_form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* 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 React, { useCallback, useState } from 'react';
import {
EuiButton,
EuiButtonIcon,
EuiCode,
EuiFlexGroup,
EuiFlexItem,
EuiTitle,
useEuiTheme,
} from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { i18n } from '@kbn/i18n';
import { ApiKeyFlyoutWrapper } from './api_key_flyout_wrapper';
import { useSearchApiKey, Status } from '../hooks/use_search_api_key';

export const ApiKeyForm = () => {
const { euiTheme } = useEuiTheme();
const [showFlyout, setShowFlyout] = useState(false);
const { apiKey, status, handleSaveKey } = useSearchApiKey();
const handleAddToClipboard = useCallback(
() => apiKey && navigator.clipboard.writeText(apiKey),
[apiKey]
);

return (
<EuiFlexGroup alignItems="center" gutterSize="s" justifyContent="flexStart" responsive={false}>
<EuiFlexItem grow={0}>
<EuiTitle size="xxxs" css={{ whiteSpace: 'nowrap' }}>
<h6>
<FormattedMessage id="xpack.searchIndices.apiKeyForm.title" defaultMessage="API Key" />
yansavitski marked this conversation as resolved.
Show resolved Hide resolved
</h6>
</EuiTitle>
</EuiFlexItem>
{apiKey && (
<>
<EuiFlexItem grow={0}>
<EuiCode language="text" color="success" css={{ color: euiTheme.colors.successText }}>
{status === Status.showHiddenKey ? '•'.repeat(30) : apiKey}
yansavitski marked this conversation as resolved.
Show resolved Hide resolved
</EuiCode>
</EuiFlexItem>
{status === Status.showPreviewKey && (
<EuiFlexItem grow={0}>
<EuiButtonIcon
iconType="copy"
color="success"
onClick={handleAddToClipboard}
aria-label={i18n.translate('xpack.searchIndices.apiKeyForm.copyButton', {
yansavitski marked this conversation as resolved.
Show resolved Hide resolved
defaultMessage: 'Copy button',
})}
/>
</EuiFlexItem>
)}
</>
)}
{status === Status.showCreateButton && (
<EuiFlexItem grow={0}>
<EuiButton
color="warning"
size="s"
iconSide="left"
iconType="key"
onClick={() => setShowFlyout(true)}
>
<FormattedMessage
id="xpack.searchIndices.apiKeyForm.createButton"
yansavitski marked this conversation as resolved.
Show resolved Hide resolved
defaultMessage="Create an API Key"
/>
</EuiButton>
{showFlyout && (
<ApiKeyFlyoutWrapper onClose={() => setShowFlyout(false)} onSuccess={handleSaveKey} />
)}
</EuiFlexItem>
)}
</EuiFlexGroup>
);
};
29 changes: 29 additions & 0 deletions x-pack/plugins/search_api_keys/public/hooks/use_current_user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* 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 { useState, useEffect } from 'react';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { AuthenticatedUser } from '@kbn/core-security-common';

export const useCurrentUser = () => {
const { security } = useKibana().services;
const [user, setUser] = useState<AuthenticatedUser | undefined>(undefined);

useEffect(() => {
const getCurrentUser = async () => {
try {
const authenticatedUser = await security!.authc.getCurrentUser();
setUser(authenticatedUser);
} catch {
setUser(undefined);
}
};
getCurrentUser();
}, [security]);

return user;
};
136 changes: 136 additions & 0 deletions x-pack/plugins/search_api_keys/public/hooks/use_search_api_key.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* 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 { useEffect, useCallback, useReducer } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { APIKeyCreationResponse, APIRoutes } from '../../common/types';

const API_KEY_STORAGE_KEY = 'searchApiKey';

export enum Status {
loading = 'loading',
showCreateButton = 'showCreateButton',
showHiddenKey = 'showHiddenKey',
showPreviewKey = 'showPreviewKey',
}

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

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

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

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 'CLEAR_API_KEY':
return { ...state, apiKey: null, status: Status.showCreateButton };
default:
return state;
}
};

export const useSearchApiKey = () => {
const { http } = useKibana().services;
const [state, dispatch] = useReducer(reducer, initialState);
const handleSaveKey = 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.showPreviewKey });
}, []);
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) {
yansavitski marked this conversation as resolved.
Show resolved Hide resolved
dispatch({ type: 'SET_STATUS', status: Status.showCreateButton });
} else {
throw err;
}
}
},
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,
});
}
},
});

useEffect(() => {
(async () => {
try {
const storedKey = sessionStorage.getItem(API_KEY_STORAGE_KEY);

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',
});
}
} else {
await createApiKey();
}
} catch (e) {
throw e;
}
})();
}, [validateApiKey, createApiKey]);

return {
apiKey: state.apiKey,
handleSaveKey,
status: state.status,
};
};
Loading