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

Database access through WebUI #49979

Merged
merged 14 commits into from
Dec 16, 2024
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
5 changes: 4 additions & 1 deletion web/packages/teleport/src/Console/Console.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import usePageTitle from './usePageTitle';
import useTabRouting from './useTabRouting';
import useOnExitConfirmation from './useOnExitConfirmation';
import useKeyboardNav from './useKeyboardNav';
import DocumentDb from './DocumentDb';

const POLL_INTERVAL = 5000; // every 5 sec

Expand Down Expand Up @@ -77,7 +78,7 @@ export default function Console() {
return consoleCtx.refreshParties();
}

const disableNewTab = storeDocs.getNodeDocuments().length > 0;
const disableNewTab = storeDocs.getNodeDocuments().length > 0 || storeDocs.getDbDocuments().length > 0;
const $docs = documents.map(doc => (
<MemoizedDocument doc={doc} visible={doc.id === activeDocId} key={doc.id} />
));
Expand Down Expand Up @@ -139,6 +140,8 @@ function MemoizedDocument(props: { doc: stores.Document; visible: boolean }) {
return <DocumentNodes doc={doc} visible={visible} />;
case 'kubeExec':
return <DocumentKubeExec doc={doc} visible={visible} />;
case 'db':
return <DocumentDb doc={doc} visible={visible} />;
default:
return <DocumentBlank doc={doc} visible={visible} />;
}
Expand Down
202 changes: 202 additions & 0 deletions web/packages/teleport/src/Console/DocumentDb/ConnectDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
/**
* Teleport
* Copyright (C) 2024 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 React, { useCallback, useEffect, useState } from 'react';
import Dialog, {
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from 'design/Dialog';
import {
Box,
ButtonPrimary,
ButtonSecondary,
Flex,
Indicator,
} from 'design';

import Validation from 'shared/components/Validation';
import { Option } from 'shared/components/Select';
import { FieldSelect, FieldSelectCreatable } from 'shared/components/FieldSelect';
import { Database } from 'teleport/services/databases';
import { useTeleport } from 'teleport';
import { useUnifiedResourcesFetch } from 'shared/components/UnifiedResources';
import { Danger } from 'design/Alert';
import { requiredField } from 'shared/components/Validation/rules';

type Props = {
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
clusterId: string;
serviceName: string;
onClose(): void;
onConnect: onConnectCallback;
};

type onConnectCallback = (
name: string,
protocol: string,
dbName: string,
dbUser: string,
dbRoles: string[],
) => void;
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved

function DbConnectDialog({ clusterId, serviceName, onClose, onConnect }: Props) {
// Fetch database information to pre-fill the connection parameters.
const ctx = useTeleport();
const {
fetch: unifiedFetch,
attempt,
resources,
} = useUnifiedResourcesFetch({
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
fetchFunc: useCallback(
async (_, signal) => {
const response = await ctx.resourceService.fetchUnifiedResources(
clusterId,
{
query: `name == "${serviceName}"`,
sort: { fieldName: 'name', dir: 'ASC'},
limit: 1,
},
signal
);


// TODO(gabrielcorado): Handle scenarios where there is conflict on the name.
if (response.agents.length !== 1 || response.agents[0].kind !== 'db') {
throw new Error('Unable to retrieve database information.');
}

return { agents: response.agents };
},
[clusterId, serviceName]
)
})
useEffect(() => { unifiedFetch({clear: true})}, [])


return (
<Dialog
gzdunek marked this conversation as resolved.
Show resolved Hide resolved
dialogCss={dialogCss}
disableEscapeKeyDown={false}
onClose={onClose}
open={true}
>
<DialogHeader mb={4}>
<DialogTitle>Connect To Database</DialogTitle>
</DialogHeader>

{attempt.status === 'failed' && <Danger children={attempt.statusText} />}
{(attempt.status === '' || attempt.status === 'processing') && (
<Box textAlign="center" m={10}>
<Indicator />
</Box>
)}
{attempt.status === 'success' && <DbConnectDialogForm db={resources[0]} onConnect={onConnect} onClose={onClose} />}
</Dialog>
);
}

type FormProps = {
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
db: Database;
onConnect: onConnectCallback;
onClose(): void;
};

function DbConnectDialogForm({ db, onConnect, onClose }: FormProps) {
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
const dbUserOpts = db.users?.map(user => ({value: user, label: user}));
const dbNamesOpts = db.names?.map(name => ({value: name, label: name}));
const dbRolesOpts = db.roles?.map(role => ({value: role, label: role}));

const [selectedName, setSelectedName] = useState<Option>(dbNamesOpts?.[0]);
const [selectedUser, setSelectedUser] = useState<Option>(dbUserOpts?.[0]);
const [selectedRoles, setSelectedRoles] = useState<readonly Option[]>();

const dbConnect = () => {
onConnect(db.name, db.protocol, selectedName.value, selectedUser.value, selectedRoles?.map((role) => role.value));
};

return (
<Validation>
{({ validator }) => (
<form>
<DialogContent minHeight="240px" flex="0 0 auto">
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
<FieldSelectCreatable
Copy link
Contributor

Choose a reason for hiding this comment

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

how do we handle wildcard? if no wildcard, it shouldn't be Creatable in my option.

isDisabled={dbUserOpts?.length == 1} will disable if single wildcard?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

When we have a wildcard, the fields will be empty, and users must type it out.

Screenshot 2024-12-13 at 11 26 10

Setting to disable will prevent them from changing the roles (I'm not sure if this will be desired).

Copy link
Contributor

@greedy52 greedy52 Dec 13, 2024

Choose a reason for hiding this comment

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

i must have missed it. Where is the logic to remove wildcard from db users?

label="Database user"
menuPosition="fixed"
onChange={option => setSelectedUser(option as Option)}
value={selectedUser}
options={dbUserOpts}
isDisabled={dbUserOpts?.length == 1}
formatCreateLabel={userInput => `Use "${userInput}" database user`}
rule={requiredField('Database user is required')}
/>
{dbRolesOpts?.length > 0 && <FieldSelect
label="Database roles"
menuPosition="fixed"
isMulti={true}
onChange={setSelectedRoles}
value={selectedRoles}
options={dbRolesOpts}
/> }
<FieldSelectCreatable
label="Database name"
menuPosition="fixed"
onChange={option => setSelectedName(option as Option)}
value={selectedName}
options={dbNamesOpts}
isDisabled={dbNamesOpts?.length == 1}
greedy52 marked this conversation as resolved.
Show resolved Hide resolved
formatCreateLabel={userInput => `Use "${userInput}" database name`}
rule={requiredField('Database name is required')}
/>
</DialogContent>
<DialogFooter>
<Flex alignItems="center" justifyContent="space-between">
<ButtonSecondary
type="button"
width="45%"
size="large"
onClick={onClose}
>
Close
</ButtonSecondary>
<ButtonPrimary
type="submit"
width="45%"
size="large"
onClick={e => {
e.preventDefault();
validator.validate() && dbConnect();
}}
>
Connect
</ButtonPrimary>
</Flex>
</DialogFooter>
</form>
)}
</Validation>
);
}

const dialogCss = () => `
min-height: 200px;
max-width: 600px;
width: 100%;
`;

export default DbConnectDialog;
gabrielcorado marked this conversation as resolved.
Show resolved Hide resolved
Loading
Loading