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
20 changes: 20 additions & 0 deletions web/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;
1 change: 1 addition & 0 deletions web/packages/shared/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +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 web/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];
6 changes: 6 additions & 0 deletions web/packages/shared/utils/errorType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
* limitations under the License.
*/

import { privateKeyEnablingPolicies } from 'shared/services';

export function isPrivateKeyRequiredError(err: Error) {
return privateKeyEnablingPolicies.some(p => err.message.includes(p));
}

// getErrMessage first checks if the error is of type Error
// before attempting to access the error message field.
// Used with try catch blocks, where the error caught
Expand Down
36 changes: 36 additions & 0 deletions web/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 Down Expand Up @@ -78,6 +79,41 @@ test('login with SSO', () => {
);
});

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();
});

describe('test MOTD', () => {
test('show motd only if motd is set', async () => {
// default login form
Expand Down
20 changes: 19 additions & 1 deletion web/packages/teleport/src/Login/useLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,23 @@
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();
Expand All @@ -48,6 +58,10 @@ export default function useLogin() {
.login(email, password, token)
.then(onSuccess)
.catch(err => {
if (isPrivateKeyRequiredError(err)) {
setPrivateKeyPolicyEnabled(true);
return;
}
attemptActions.error(err);
});
}
Expand All @@ -58,6 +72,10 @@ export default function useLogin() {
.loginWithWebauthn(creds)
.then(onSuccess)
.catch(err => {
if (isPrivateKeyRequiredError(err)) {
setPrivateKeyPolicyEnabled(true);
return;
}
attemptActions.error(err);
});
}
Expand All @@ -81,7 +99,7 @@ export default function useLogin() {
clearAttempt: attemptActions.clear,
isPasswordlessEnabled: cfg.isPasswordlessEnabled(),
primaryAuthType: cfg.getPrimaryAuthType(),
privateKeyPolicyEnabled: false,
privateKeyPolicyEnabled,
motd,
showMotd,
acknowledgeMotd,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ test('story.SuccessReset', () => {
const { container } = render(<story.SuccessReset />);
expect(container.firstChild).toMatchSnapshot();
});
test('story.SuccessAndPrivateKeyEnabledRegister', () => {
const { container } = render(<story.SuccessAndPrivateKeyEnabledRegister />);
expect(container.firstChild).toMatchSnapshot();
});
test('story.SuccessAndPrivateKeyEnabledReset', () => {
const { container } = render(<story.SuccessAndPrivateKeyEnabledReset />);
expect(container.firstChild).toMatchSnapshot();
});
test('story.SuccessRegisterDashboard', () => {
const { container } = render(<story.SuccessRegisterDashboard />);
expect(container.firstChild).toMatchSnapshot();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,19 @@ export const SuccessReset = () =>
resetMode: true,
});

export const SuccessAndPrivateKeyEnabledRegister = () =>
renderNewCredentials({
success: true,
privateKeyPolicyEnabled: true,
});

export const SuccessAndPrivateKeyEnabledReset = () =>
renderNewCredentials({
success: true,
resetMode: true,
privateKeyPolicyEnabled: true,
});

export const SuccessRegisterDashboard = () =>
renderNewCredentials({
success: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { makeTestUserContext } from 'teleport/User/testHelpers/makeTestUserConte
const attempt: Attempt = { status: '' };
const failedAttempt: Attempt = { status: 'failed' };
const processingAttempt: Attempt = { status: 'processing' };
const successAttempt: Attempt = { status: 'success', statusText: 'hey' };

const resetToken: ResetToken = {
tokenId: 'tokenId',
Expand Down Expand Up @@ -79,9 +80,32 @@ test.each(nullCases)('renders $attempt as null', testCase => {
expect(container).toBeEmptyDOMElement();
});

test('renders Reset Complete for success and private key policy enabled during reset', () => {
const props = makeProps();
props.fetchAttempt = successAttempt;
props.success = true;
props.privateKeyPolicyEnabled = true;
props.resetMode = true;
render(<NewCredentials {...props} />);

expect(screen.getByText(/Reset Complete/i)).toBeInTheDocument();
});

test('renders Registration Complete for success and private key policy enabled during registration', () => {
const props = makeProps();
props.fetchAttempt = { status: 'success' };
props.success = true;
props.privateKeyPolicyEnabled = true;
props.resetMode = false;
render(<NewCredentials {...props} />);

expect(screen.getByText(/Registration Complete/i)).toBeInTheDocument();
});

test('renders Register Success on success', () => {
const props = makeProps();
props.fetchAttempt = { status: 'success' };
props.privateKeyPolicyEnabled = false;
props.recoveryCodes = undefined;
props.success = true;
render(<NewCredentials {...props} />);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { OnboardCard } from 'design/Onboard/OnboardCard';
import { Box } from 'design';

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

import { loginFlows } from 'teleport/Welcome/NewCredentials/constants';
Expand Down Expand Up @@ -60,6 +61,7 @@ export function NewCredentials(props: NewCredentialsProps) {
primaryAuthType,
success,
finishedRegister,
privateKeyPolicyEnabled,
isDashboard,
displayOnboardingQuestionnaire = false,
setDisplayOnboardingQuestionnaire = false,
Expand All @@ -84,6 +86,14 @@ export function NewCredentials(props: NewCredentialsProps) {
return null;
}

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

if (
success &&
!resetMode &&
Expand Down
Loading