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

[v17] WebDiscover: supports defining labels for Discover flows with single resource enroll #51038

Open
wants to merge 3 commits into
base: lisa/v17/backend-labels
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
48 changes: 41 additions & 7 deletions web/packages/teleport/src/Apps/AddApp/AddApp.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,50 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { useState } from 'react';

import { JoinToken } from 'teleport/services/joinToken';

import { AddApp } from './AddApp';

export default {
title: 'Teleport/Apps/Add',
title: 'Teleport/Discover/Application/Web',
};

export const Created = () => (
<AddApp {...props} attempt={{ status: 'success' }} />
);
export const CreatedWithoutLabels = () => {
const [token, setToken] = useState<JoinToken>();

return (
<AddApp
{...props}
attempt={{ status: 'success' }}
token={token}
createToken={() => {
setToken(props.token);
return Promise.resolve(true);
}}
/>
);
};

export const CreatedWithLabels = () => {
const [token, setToken] = useState<JoinToken>();

export const Loaded = () => {
return <AddApp {...props} />;
return (
<AddApp
{...props}
attempt={{ status: 'success' }}
labels={[
{ name: 'env', value: 'staging' },
{ name: 'fruit', value: 'apple' },
]}
token={token}
createToken={() => {
setToken(props.token);
return Promise.resolve(true);
}}
/>
);
};

export const Processing = () => (
Expand Down Expand Up @@ -72,8 +104,10 @@ const props = {
createJoinToken: () => Promise.resolve(null),
version: '5.0.0-dev',
reset: () => null,
labels: [],
setLabels: () => null,
attempt: {
status: '',
status: 'success',
statusText: '',
} as any,
token: {
Expand Down
4 changes: 4 additions & 0 deletions web/packages/teleport/src/Apps/AddApp/AddApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ export function AddApp({
setAutomatic,
isAuthTypeLocal,
token,
labels,
setLabels,
}: State & Props) {
return (
<Dialog
Expand Down Expand Up @@ -82,6 +84,8 @@ export function AddApp({
onCreate={createToken}
attempt={attempt}
token={token}
labels={labels}
setLabels={setLabels}
/>
)}
{!automatic && (
Expand Down
23 changes: 18 additions & 5 deletions web/packages/teleport/src/Apps/AddApp/Automatically.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { act } from '@testing-library/react';

import { fireEvent, render, screen } from 'design/utils/testing';

import { Automatically, createAppBashCommand } from './Automatically';
Expand All @@ -33,12 +31,14 @@ test('render command only after form submit', async () => {
roles: [],
content: '',
};
render(
const { rerender } = render(
<Automatically
token={token}
attempt={{ status: 'success' }}
onClose={() => {}}
onCreate={() => Promise.resolve(true)}
labels={[]}
setLabels={() => null}
token={null}
/>
);

Expand All @@ -56,8 +56,21 @@ test('render command only after form submit', async () => {
target: { value: 'https://gravitational.com' },
});

rerender(
<Automatically
attempt={{ status: 'success' }}
onClose={() => {}}
onCreate={() => Promise.resolve(true)}
labels={[]}
setLabels={() => null}
token={token}
/>
);

// click button
act(() => screen.getByRole('button', { name: /Generate Script/i }).click());
fireEvent.click(screen.getByRole('button', { name: /Generate Script/i }));

await screen.findByText(/Regenerate Script/i);

// after form submission should show the command
cmd = createAppBashCommand(token.id, 'app-name', 'https://gravitational.com');
Expand Down
70 changes: 35 additions & 35 deletions web/packages/teleport/src/Apps/AddApp/Automatically.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { KeyboardEvent, useEffect, useState } from 'react';

import {
Alert,
Box,
ButtonPrimary,
ButtonSecondary,
Flex,
Expand All @@ -33,50 +34,40 @@ import { Attempt } from 'shared/hooks/useAttemptNext';

import TextSelectCopy from 'teleport/components/TextSelectCopy';
import cfg from 'teleport/config';
import { LabelsCreater } from 'teleport/Discover/Shared';
import { ResourceLabelTooltip } from 'teleport/Discover/Shared/ResourceLabelTooltip';
import { ResourceLabel } from 'teleport/services/agents';

import { State } from './useAddApp';

export function Automatically(props: Props) {
const { onClose, attempt, token } = props;
const { onClose, attempt, token, labels, setLabels } = props;

const [name, setName] = useState('');
const [uri, setUri] = useState('');
const [cmd, setCmd] = useState('');

useEffect(() => {
if (name && uri) {
if (name && uri && token) {
const cmd = createAppBashCommand(token.id, name, uri);
setCmd(cmd);
}
}, [token]);

function handleRegenerate(validator: Validator) {
function onGenerateScript(validator: Validator) {
if (!validator.validate()) {
return;
}

props.onCreate(name, uri);
}

function handleGenerate(validator: Validator) {
if (!validator.validate()) {
return;
}

const cmd = createAppBashCommand(token.id, name, uri);
setCmd(cmd);
}

function handleEnterPress(
e: KeyboardEvent<HTMLInputElement>,
validator: Validator
) {
if (e.key === 'Enter') {
if (cmd) {
handleRegenerate(validator);
} else {
handleGenerate(validator);
}
onGenerateScript(validator);
}
}

Expand All @@ -96,6 +87,7 @@ export function Automatically(props: Props) {
mr="3"
onKeyPress={e => handleEnterPress(e, validator)}
onChange={e => setName(e.target.value.toLowerCase())}
disabled={attempt.status === 'processing'}
/>
<FieldInput
rule={requiredAppUri}
Expand All @@ -105,8 +97,25 @@ export function Automatically(props: Props) {
placeholder="https://localhost:4000"
onKeyPress={e => handleEnterPress(e, validator)}
onChange={e => setUri(e.target.value)}
disabled={attempt.status === 'processing'}
/>
</Flex>
<Box mt={-3} mb={3}>
<Flex alignItems="center" gap={1} mb={2} mt={4}>
<Text bold>Add Labels (Optional)</Text>
<ResourceLabelTooltip
toolTipPosition="top"
resourceKind="app"
/>
</Flex>
<LabelsCreater
labels={labels}
setLabels={setLabels}
isLabelOptional={true}
disableBtns={attempt.status === 'processing'}
noDuplicateKey={true}
/>
</Box>
{!cmd && (
<Text mb="3">
Teleport can automatically set up application access. Provide
Expand Down Expand Up @@ -136,24 +145,13 @@ export function Automatically(props: Props) {
)}
</DialogContent>
<DialogFooter>
{!cmd && (
<ButtonPrimary
mr="3"
disabled={attempt.status === 'processing'}
onClick={() => handleGenerate(validator)}
>
Generate Script
</ButtonPrimary>
)}
{cmd && (
<ButtonPrimary
mr="3"
disabled={attempt.status === 'processing'}
onClick={() => handleRegenerate(validator)}
>
Regenerate
</ButtonPrimary>
)}
<ButtonPrimary
mr="3"
disabled={attempt.status === 'processing'}
onClick={() => onGenerateScript(validator)}
>
{cmd ? 'Regenerate Script' : 'Generate Script'}
</ButtonPrimary>
<ButtonSecondary
disabled={attempt.status === 'processing'}
onClick={onClose}
Expand Down Expand Up @@ -271,4 +269,6 @@ type Props = {
onCreate(name: string, uri: string): Promise<any>;
token: State['token'];
attempt: Attempt;
labels: ResourceLabel[];
setLabels(r: ResourceLabel[]): void;
};
22 changes: 19 additions & 3 deletions web/packages/teleport/src/Apps/AddApp/useAddApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { useEffect, useState } from 'react';

import useAttempt from 'shared/hooks/useAttemptNext';

import { ResourceLabel } from 'teleport/services/agents';
import type { JoinToken } from 'teleport/services/joinToken';
import TeleportContext from 'teleport/teleportContext';

Expand All @@ -31,14 +32,27 @@ export default function useAddApp(ctx: TeleportContext) {
const isEnterprise = ctx.isEnterprise;
const [automatic, setAutomatic] = useState(isEnterprise);
const [token, setToken] = useState<JoinToken>();
const [labels, setLabels] = useState<ResourceLabel[]>([]);

useEffect(() => {
createToken();
}, []);
// We don't want to create token on first render
// which defaults to the automatic tab because
// user may want to add labels.
if (!automatic) {
setLabels([]);
// When switching to manual tab, token can be re-used
// if token was already generated from automatic tab.
if (!token) {
createToken();
}
}
}, [automatic]);

function createToken() {
return run(() =>
ctx.joinTokenService.fetchJoinToken({ roles: ['App'] }).then(setToken)
ctx.joinTokenService
.fetchJoinToken({ roles: ['App'], suggestedLabels: labels })
.then(setToken)
);
}

Expand All @@ -52,6 +66,8 @@ export default function useAddApp(ctx: TeleportContext) {
isAuthTypeLocal,
isEnterprise,
token,
labels,
setLabels,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const Success = () => <Component />;
Success.parameters = {
msw: {
handlers: [
http.post(cfg.api.awsAppAccessPath, () =>
http.post(cfg.api.awsAppAccess.createV2, () =>
HttpResponse.json({ name: 'app-1' })
),
],
Expand All @@ -59,7 +59,10 @@ export const Loading = () => {
Loading.parameters = {
msw: {
handlers: [
http.post(cfg.api.awsAppAccessPath, async () => await delay('infinite')),
http.post(
cfg.api.awsAppAccess.createV2,
async () => await delay('infinite')
),
],
},
};
Expand All @@ -68,7 +71,7 @@ export const Failed = () => <Component />;
Failed.parameters = {
msw: {
handlers: [
http.post(cfg.api.awsAppAccessPath, () =>
http.post(cfg.api.awsAppAccess.createV2, () =>
HttpResponse.json(
{
message: 'Some kind of error message',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,13 @@ import {
DiscoverEventResource,
userEventService,
} from 'teleport/services/userEvent';
import { ProxyRequiresUpgrade } from 'teleport/services/version/unsupported';
import TeleportContext from 'teleport/teleportContext';

import { CreateAppAccess } from './CreateAppAccess';

beforeEach(() => {
jest.spyOn(integrationService, 'createAwsAppAccess').mockResolvedValue(app);
jest.spyOn(integrationService, 'createAwsAppAccessV2').mockResolvedValue(app);
jest
.spyOn(userEventService, 'captureDiscoverEvent')
.mockResolvedValue(undefined as never);
Expand All @@ -60,6 +61,25 @@ test('create app access', async () => {
renderCreateAppAccess(ctx, discoverCtx);
await screen.findByText(/bash/i);

await userEvent.click(screen.getByRole('button', { name: /next/i }));
await screen.findByText(/aws-console/i);
expect(integrationService.createAwsAppAccessV2).toHaveBeenCalledTimes(1);
});

test('create app access with v1 endpoint', async () => {
jest
.spyOn(integrationService, 'createAwsAppAccessV2')
.mockRejectedValueOnce(new Error(ProxyRequiresUpgrade));
jest.spyOn(integrationService, 'createAwsAppAccess').mockResolvedValue(app);

const { ctx, discoverCtx } = getMockedContexts();

renderCreateAppAccess(ctx, discoverCtx);
await screen.findByText(/bash/i);

await userEvent.click(screen.getByRole('button', { name: /next/i }));
await screen.findByText(ProxyRequiresUpgrade);

await userEvent.click(screen.getByRole('button', { name: /next/i }));
await screen.findByText(/aws-console/i);
expect(integrationService.createAwsAppAccess).toHaveBeenCalledTimes(1);
Expand Down
Loading
Loading