Skip to content
Merged
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;
};
95 changes: 95 additions & 0 deletions web/packages/teleport/src/Apps/AddApp/useAddApp.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/**
* Teleport
* Copyright (C) 2025 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { renderHook, waitFor } from '@testing-library/react';

import { ContextProvider } from 'teleport/index';
import { userContext } from 'teleport/Main/fixtures';
import { ProxyRequiresUpgrade } from 'teleport/services/version/unsupported';
import TeleportContext from 'teleport/teleportContext';

import useAddApp from './useAddApp';

const ctx = new TeleportContext();

beforeEach(() => {
ctx.storeUser.setState({ ...userContext });
jest
.spyOn(ctx.joinTokenService, 'fetchJoinToken')
.mockResolvedValue(tokenResp);
});

afterEach(() => {
jest.resetAllMocks();
});

test('create token without labels', async () => {
jest
.spyOn(ctx.joinTokenService, 'fetchJoinTokenV2')
.mockResolvedValue(tokenResp);

const wrapper = ({ children }) => (
<ContextProvider ctx={ctx}>{children}</ContextProvider>
);

let { result } = renderHook(() => useAddApp(ctx), { wrapper });

await waitFor(() => {
expect(result.current.token).not.toBeUndefined();
});

expect(ctx.joinTokenService.fetchJoinTokenV2).toHaveBeenCalledTimes(1);
expect(ctx.joinTokenService.fetchJoinToken).not.toHaveBeenCalled();
expect(result.current.token).toEqual(tokenResp);
});

test('create token without labels with v1 fallback', async () => {
jest
.spyOn(ctx.joinTokenService, 'fetchJoinTokenV2')
.mockRejectedValueOnce(new Error(ProxyRequiresUpgrade));

const wrapper = ({ children }) => (
<ContextProvider ctx={ctx}>{children}</ContextProvider>
);

let { result } = renderHook(() => useAddApp(ctx), { wrapper });

await waitFor(() => {
expect(result.current.token).not.toBeUndefined();
});

expect(ctx.joinTokenService.fetchJoinTokenV2).toHaveBeenCalledTimes(1);
expect(ctx.joinTokenService.fetchJoinToken).toHaveBeenCalledTimes(1);
expect(result.current.token).toEqual(tokenResp);
});

const tokenResp = {
allow: undefined,
bot_name: undefined,
content: undefined,
expiry: null,
expiryText: '',
gcp: undefined,
id: undefined,
isStatic: undefined,
method: undefined,
internalResourceId: 'abc',
roles: ['Application'],
safeName: undefined,
suggestedLabels: [],
};
Loading