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 6 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
7 changes: 6 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,9 @@ 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 +142,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
209 changes: 209 additions & 0 deletions web/packages/teleport/src/Console/DocumentDb/ConnectDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/**
* 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 { Danger } from 'design/Alert';
import { requiredField } from 'shared/components/Validation/rules';
import { useAsync } from 'shared/hooks/useAsync';

import { useTeleport } from 'teleport';
import { Database } from 'teleport/services/databases';
import { DbConnectData } from 'teleport/lib/term/tty';

export function ConnectDialog(props: {
clusterId: string;
serviceName: string;
onClose(): void;
onConnect(data: DbConnectData): void;
}) {
// Fetch database information to pre-fill the connection parameters.
const ctx = useTeleport();
const [attempt, getDatabase] = useAsync(
useCallback(async () => {
const response = await ctx.resourceService.fetchUnifiedResources(
props.clusterId,
{
query: `name == "${props.serviceName}"`,
kinds: ['db'],
sort: { fieldName: 'name', dir: 'ASC' },
limit: 1,
}
);

// 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 response.agents[0];
}, [props.clusterId, ctx.resourceService, props.serviceName])
);

useEffect(() => {
void getDatabase();
}, [getDatabase]);

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

{attempt.status === 'error' && <Danger children={attempt.statusText} />}
{(attempt.status === '' || attempt.status === 'processing') && (
<Box textAlign="center" m={10}>
<Indicator />
</Box>
)}
{attempt.status === 'success' && (
<ConnectForm
db={attempt.data}
onConnect={props.onConnect}
onClose={props.onClose}
/>
)}
</Dialog>
);
}

function ConnectForm(props: {
db: Database;
onConnect(data: DbConnectData): void;
onClose(): void;
}) {
const dbUserOpts = props.db.users?.map(user => ({
value: user,
label: user,
}));
const dbNamesOpts = props.db.names?.map(name => ({
value: name,
label: name,
}));
const dbRolesOpts = props.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 = () => {
props.onConnect({
serviceName: props.db.name,
protocol: props.db.protocol,
dbName: selectedName.value,
dbUser: selectedUser.value,
dbRoles: 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}
/>
Copy link
Contributor

Choose a reason for hiding this comment

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

It might be confusing to users what role selection does.

We should do either or both of the following:

  • have a hint/info tooltip that explains a) if no roles are selected, all allowed database roles will be provisioned on connection. b) otherwise, only selected databased roles will be provisioned.
  • select all roles in the box by default

I would also move role selection below database name selection. I might even put database name selection before user selection. WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think selecting all roles initially might be better here. We can also always enforce at least one selected (when there are options available).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

About the wildcard for roles, we don't have enough information to decide when to show this box. This would be a combination of the database having auto-user provisioning enabled and not having DAC configured on their selected roles (correct me if I need to include anything here). So, for now, only showing when the roles are available might not cover all scenarios, but it will work for the most part. WDYT?

Also worth mentioning that currently, the database roles information is not available. The web handler changes will add this.

Copy link
Contributor

Choose a reason for hiding this comment

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

just some facts

  • database roles do not support wildcard
  • database roles section is a very niche feature (like I mentioned, even the requestor of this feature might not be using it at the moment)
  • database roles and DAC permissions are mutually exclusive

So for simplicity, we could just leave this part out.

If we want to keep it:

So, for now, only showing when the roles are available might not cover all scenarios, but it will work for the most part.

this should be ok, also it's backend's responsibility to make sure the calculation is correct so we don't build more logic in frontend

I think selecting all roles initially might be better here.

I think this would be easiest as well.

We can also always enforce at least one selected (when there are options available).

IMHO not necessary

)}
<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={props.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%;
`;
Loading
Loading