Skip to content
This repository was archived by the owner on Feb 8, 2024. It is now read-only.
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
20 changes: 20 additions & 0 deletions packages/shared/services/consts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* Copyright 2022 Gravitational, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export const privateKeyEnablingPolicies = [
'hardware_key',
'hardware_key_touch',
] as const;
2 changes: 1 addition & 1 deletion packages/shared/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

export * from './consts';
export * from './types';
6 changes: 6 additions & 0 deletions packages/shared/services/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { privateKeyEnablingPolicies } from './consts';

export type AuthProviderType = 'oidc' | 'saml' | 'github';

export type Auth2faType = 'otp' | 'off' | 'optional' | 'on' | 'webauthn';
Expand Down Expand Up @@ -42,3 +44,7 @@ export type AuthProvider = {
type: AuthProviderType;
url: string;
};

export type PrivateKeyPolicy =
| 'none'
| typeof privateKeyEnablingPolicies[number];
21 changes: 21 additions & 0 deletions packages/shared/utils/errorType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Copyright 2022 Gravitational, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { privateKeyEnablingPolicies } from 'shared/services';

export function isPrivateKeyRequiredError(err: Error) {
return privateKeyEnablingPolicies.some(p => err.message.includes(p));
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { Option } from 'shared/components/Select';

import TextSelectCopy from 'teleport/components/TextSelectCopy';
import useTeleport from 'teleport/useTeleport';
import { generateTshLoginCommand } from 'teleport/lib/util';

import {
Header,
Expand Down Expand Up @@ -71,12 +72,6 @@ export function TestConnection({
() => userOpts[0] || { value: username, label: username }
);

const { hostname, port } = window.document.location;
const host = `${hostname}:${port || '443'}`;
const authSpec =
authType === 'local' ? `--auth=${authType} --user=${username} ` : '';
const tshLoginCmd = `tsh login --proxy=${host} ${authSpec}${clusterId}`;

let $diagnosisStateComponent;
if (attempt.status === 'processing') {
$diagnosisStateComponent = (
Expand Down Expand Up @@ -263,7 +258,14 @@ export function TestConnection({
</Text>
<Box mb={2}>
Log into your Teleport cluster
<TextSelectCopy mt="1" text={tshLoginCmd} />
<TextSelectCopy
mt="1"
text={generateTshLoginCommand({
authType,
username,
clusterId,
})}
/>
</Box>
<Box mb={2}>
Log into your Kubernetes cluster
Expand Down
15 changes: 5 additions & 10 deletions packages/teleport/src/Kubes/ConnectDialog/ConnectDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { Text, Box, ButtonSecondary } from 'design';

import TextSelectCopy from 'teleport/components/TextSelectCopy';
import { AuthType } from 'teleport/services/user';
import { generateTshLoginCommand } from 'teleport/lib/util';

function ConnectDialog(props: Props) {
const {
Expand All @@ -35,15 +36,6 @@ function ConnectDialog(props: Props) {
clusterId,
accessRequestId,
} = props;
const { hostname, port } = window.document.location;
const host = `${hostname}:${port || '443'}`;
const authSpec =
authType === 'local' ? `--auth=${authType} --user=${username} ` : '';
const text = `tsh login --proxy=${host} ${authSpec}${clusterId}`;

const requestIdFlag = accessRequestId
? ` --request-id=${accessRequestId}`
: '';

return (
<Dialog
Expand All @@ -61,7 +53,10 @@ function ConnectDialog(props: Props) {
Step 1
</Text>
{' - Login to Teleport'}
<TextSelectCopy mt="2" text={`${text}${requestIdFlag}`} />
<TextSelectCopy
mt="2"
text={generateTshLoginCommand({ authType, username, clusterId })}
/>
</Box>
<Box mb={4}>
<Text bold as="span">
Expand Down
1 change: 1 addition & 0 deletions packages/teleport/src/Login/Login.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,5 @@ const sample: State = {
clearAttempt: () => null,
isPasswordlessEnabled: false,
primaryAuthType: 'local',
privateKeyPolicyEnabled: false,
};
38 changes: 37 additions & 1 deletion packages/teleport/src/Login/Login.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import React from 'react';
import { render, fireEvent, screen, waitFor } from 'design/utils/testing';
import { privateKeyEnablingPolicies } from 'shared/services/consts';

import auth from 'teleport/services/auth/auth';
import history from 'teleport/services/history';
Expand All @@ -24,9 +25,9 @@ import cfg from 'teleport/config';
import Login from './Login';

beforeEach(() => {
jest.restoreAllMocks();
jest.spyOn(history, 'push').mockImplementation();
jest.spyOn(history, 'getRedirectParam').mockImplementation(() => '/');
jest.resetAllMocks();
});

test('basic rendering', () => {
Expand Down Expand Up @@ -77,3 +78,38 @@ test('login with SSO', () => {
true
);
});

test('login with private key policy enabled through cluster wide', () => {
jest
.spyOn(cfg, 'getPrivateKeyPolicy')
.mockImplementation(() => 'hardware_key');

render(<Login />);

expect(screen.queryByPlaceholderText(/username/i)).not.toBeInTheDocument();
expect(screen.getByText(/login disabled/i)).toBeInTheDocument();
});

test('login with private key policy enabled through role setting', async () => {
// Just needs any of these enabling keywords in error message
jest
.spyOn(auth, 'login')
.mockRejectedValue(new Error(privateKeyEnablingPolicies[0]));

render(<Login />);

// Fill form.
const username = screen.getByPlaceholderText(/username/i);
const password = screen.getByPlaceholderText(/password/i);
fireEvent.change(username, { target: { value: 'username' } });
fireEvent.change(password, { target: { value: '123' } });

// Test logging in with private key error return renders private policy error.
fireEvent.click(screen.getByText('Sign In'));
await waitFor(() => {
expect(auth.login).toHaveBeenCalledWith('username', '123', '');
});

expect(screen.queryByPlaceholderText(/username/i)).not.toBeInTheDocument();
expect(screen.getByText(/login disabled/i)).toBeInTheDocument();
});
2 changes: 2 additions & 0 deletions packages/teleport/src/Login/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export function Login({
clearAttempt,
isPasswordlessEnabled,
primaryAuthType,
privateKeyPolicyEnabled,
}: State) {
return (
<>
Expand All @@ -57,6 +58,7 @@ export function Login({
clearAttempt={clearAttempt}
isPasswordlessEnabled={isPasswordlessEnabled}
primaryAuthType={primaryAuthType}
privateKeyPolicyEnabled={privateKeyPolicyEnabled}
/>
</>
);
Expand Down
22 changes: 21 additions & 1 deletion packages/teleport/src/Login/useLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,27 @@
* limitations under the License.
*/

import { useState } from 'react';
import { useAttempt } from 'shared/hooks';

import { AuthProvider } from 'shared/services';
import { isPrivateKeyRequiredError } from 'shared/utils/errorType';

import history from 'teleport/services/history';
import cfg from 'teleport/config';
import auth, { UserCredentials } from 'teleport/services/auth';

export default function useLogin() {
const [attempt, attemptActions] = useAttempt({ isProcessing: false });
// privateKeyPolicyEnabled can be enabled through cluster wide config,
// or through a role setting.
// Cluster wide config takes precedence and the user will not
// see a login form which prevents login attempts.
// Role setting requires the user to try a successful
// attempt at logging in to determine if private key policy was enabled.
const [privateKeyPolicyEnabled, setPrivateKeyPolicyEnabled] = useState(
cfg.getPrivateKeyPolicy() != 'none'
);

const authProviders = cfg.getAuthProviders();
const auth2faType = cfg.getAuth2faType();
const isLocalAuthEnabled = cfg.getLocalAuthFlag();
Expand All @@ -34,6 +45,10 @@ export default function useLogin() {
.login(email, password, token)
.then(onSuccess)
.catch(err => {
if (isPrivateKeyRequiredError(err)) {
setPrivateKeyPolicyEnabled(true);
return;
}
attemptActions.error(err);
});
}
Expand All @@ -44,6 +59,10 @@ export default function useLogin() {
.loginWithWebauthn(creds)
.then(onSuccess)
.catch(err => {
if (isPrivateKeyRequiredError(err)) {
setPrivateKeyPolicyEnabled(true);
return;
}
attemptActions.error(err);
});
}
Expand All @@ -67,6 +86,7 @@ export default function useLogin() {
clearAttempt: attemptActions.clear,
isPasswordlessEnabled: cfg.isPasswordlessEnabled(),
primaryAuthType: cfg.getPrimaryAuthType(),
privateKeyPolicyEnabled,
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,17 @@ export const SuccessRegister = () => (
export const SuccessReset = () => (
<NewCredentials {...props} success={true} resetMode={true} />
);
export const SuccessAndPrivateKeyEnabledRegister = () => (
<NewCredentials {...props} success={true} privateKeyPolicyEnabled={true} />
);
export const SuccessAndPrivateKeyEnabledReset = () => (
<NewCredentials
{...props}
success={true}
resetMode={true}
privateKeyPolicyEnabled={true}
/>
);

function CardWrapper({ children }) {
return (
Expand Down Expand Up @@ -175,6 +186,7 @@ const props: Props = {
success: false,
finishedRegister: () => null,
recoveryCodes: null,
privateKeyPolicyEnabled: false,
resetToken: {
user: 'john@example.com',
tokenId: 'test123',
Expand Down
10 changes: 10 additions & 0 deletions packages/teleport/src/Welcome/NewCredentials/NewCredentials.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { PrimaryAuthType } from 'shared/services';
import { StepSlider, NewFlow, StepComponentProps } from 'design/StepSlider';

import RecoveryCodes from 'teleport/components/RecoveryCodes';
import { PrivateKeyLoginDisabledCard } from 'teleport/components/PrivateKeyPolicy';

import useToken, { State } from '../useToken';

Expand Down Expand Up @@ -54,6 +55,7 @@ export function NewCredentials(props: State & Props) {
primaryAuthType,
success,
finishedRegister,
privateKeyPolicyEnabled,
} = props;

if (fetchAttempt.status === 'failed') {
Expand All @@ -64,6 +66,14 @@ export function NewCredentials(props: State & Props) {
return null;
}

if (success && privateKeyPolicyEnabled) {
return (
<PrivateKeyLoginDisabledCard
title={resetMode ? 'Reset Complete' : 'Registration Complete'}
/>
);
}

if (success) {
return <RegisterSuccess redirect={redirect} resetMode={resetMode} />;
}
Expand Down
Loading