Skip to content
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"react-monaco-editor": "^0.43.0",
"react-redux": "^8.0.5",
"react-router-dom": "^6.3.0",
"sm-crypto": "0.5.3",
"sql-formatter": "^12.2.2",
"typescript": "^5.0.2",
"use-resize-observer": "^9.0.2",
Expand Down
40 changes: 40 additions & 0 deletions scripts/sm2_interop_check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#!/usr/bin/env node
/**
* Cross-check SM2 interop between sm-crypto (frontend) and a fixture
* ciphertext shape expected by backend (C1C3C2, optional leading 04).
*/
const { sm2 } = require('sm-crypto');

const keypair = sm2.generateKeyPairHex();
const password = 'SqleLoginPass#123';
const cipherMode = 1; // C1C3C2
const cipher = sm2.doEncrypt(password, keypair.publicKey, cipherMode);
const plain = sm2.doDecrypt(cipher, keypair.privateKey, cipherMode);

if (plain !== password) {
console.error('sm-crypto roundtrip failed');
process.exit(1);
}
if (cipher.startsWith('04')) {
console.error('unexpected leading 04 from sm-crypto doEncrypt');
process.exit(1);
}
if (!keypair.publicKey.startsWith('04')) {
console.error('public key should start with 04');
process.exit(1);
}

console.log(
JSON.stringify(
{
ok: true,
public_key: keypair.publicKey,
private_key: keypair.privateKey,
encrypted_password: cipher,
encrypted_password_with_04: `04${cipher}`,
cipher_len: cipher.length,
},
null,
2
)
);
24 changes: 24 additions & 0 deletions src/api/common.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2387,6 +2387,30 @@ export interface IUserLoginReqV1 {
password?: string;

username?: string;

encrypted_password?: string;

key_id?: string;
}

export interface ILoginEncryptionResDataV1 {
enable?: boolean;

algorithm?: string;

cipher_mode?: string;

public_key?: string;

key_id?: string;
}

export interface IGetLoginEncryptionResV1 {
code?: number;

message?: string;

data?: ILoginEncryptionResDataV1;
}

export interface IUserLoginResV1 {
Expand Down
5 changes: 4 additions & 1 deletion src/api/user/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import {
IGetUsersResV1,
ICreateUserReqV1,
IUpdateUserReqV1,
IUpdateOtherUserPasswordReqV1
IUpdateOtherUserPasswordReqV1,
IGetLoginEncryptionResV1
} from '../common.d';

export interface ILoginV1Params extends IUserLoginReqV1 {}
Expand Down Expand Up @@ -132,3 +133,5 @@ export interface IUpdateOtherUserPasswordV1Return extends IBaseRes {}
export interface ILoginV2Params extends IUserLoginReqV1 {}

export interface ILoginV2Return extends IBaseRes {}

export interface IGetLoginEncryptionV1Return extends IGetLoginEncryptionResV1 {}
11 changes: 10 additions & 1 deletion src/api/user/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ import {
IUpdateOtherUserPasswordV1Params,
IUpdateOtherUserPasswordV1Return,
ILoginV2Params,
ILoginV2Return
ILoginV2Return,
IGetLoginEncryptionV1Return
} from './index.d';

class UserService extends ServiceBase {
Expand Down Expand Up @@ -265,6 +266,14 @@ class UserService extends ServiceBase {
const paramsData = this.cloneDeep(params);
return this.post<ILoginV2Return>('/v2/login', paramsData, options);
}

public getLoginEncryptionV1(options?: AxiosRequestConfig) {
return this.get<IGetLoginEncryptionV1Return>(
'/v1/login/encryption',
undefined,
options
);
}
}

export default new UserService();
9 changes: 9 additions & 0 deletions src/locale/en-US/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,13 @@ export default {
powered: 'Action SQLe',
pageTitle: 'SQL Audit Platform',
login: 'Login',
otherMethod: 'Other login methods',

userAgreementTips: 'I have read and agree to the',
userAgreement: 'User Agreement',

errorMessage: {
userAgreement: 'Please read and agree to the user agreement first',
encryptFailed: 'Failed to encrypt login password, please try again later',
},
};
1 change: 1 addition & 0 deletions src/locale/zh-CN/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default {

errorMessage: {
userAgreement: '请先阅读并同意用户协议',
encryptFailed: '登录密码加密失败,请稍后重试',
},

oauth: {
Expand Down
89 changes: 87 additions & 2 deletions src/page/Login/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { useDispatch, useSelector } from 'react-redux';
import useNavigate from '../../hooks/useNavigate';
import { getHrefByText } from '../../testUtils/customQuery';
import * as loginEncryption from '../../utils/loginEncryption';

jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
Expand Down Expand Up @@ -48,6 +49,7 @@ describe('Login', () => {
})
);
mockGetOauth2Tips();
mockGetLoginEncryption({ enable: false });
jest.useFakeTimers();
useLocationMock.mockReturnValue({
pathname: '/login',
Expand Down Expand Up @@ -94,6 +96,16 @@ describe('Login', () => {
return spy;
};

const mockGetLoginEncryption = (data: {
enable?: boolean;
public_key?: string;
key_id?: string;
}) => {
const spy = jest.spyOn(user, 'getLoginEncryptionV1');
spy.mockImplementation(() => resolveThreeSecond(data));
return spy;
};

test('should render login form', async () => {
const { container } = renderWithTheme(<Login />);
expect(container).toMatchSnapshot();
Expand Down Expand Up @@ -127,6 +139,7 @@ describe('Login', () => {
fireEvent.click(screen.getByText('login.login'));

await act(async () => jest.advanceTimersByTime(0));
await act(async () => jest.advanceTimersByTime(3000));

expect(request).toBeCalledTimes(1);
expect(request).toBeCalledWith({
Expand All @@ -148,6 +161,78 @@ describe('Login', () => {
expect(navigateSpy).toBeCalledWith('home');
});

test('should send encrypted password and never plaintext when encryption enabled', async () => {
const request = mockRequest();
mockGetLoginEncryption({
enable: true,
public_key: '04public',
key_id: 'kid-1',
});
const encryptSpy = jest
.spyOn(loginEncryption, 'encryptLoginPassword')
.mockReturnValue({
encrypted_password: 'cipher-text',
key_id: 'kid-1',
});

renderWithThemeAndRouter(<Login />);
fireEvent.input(screen.getByPlaceholderText('common.username'), {
target: { value: 'root' },
});
fireEvent.input(screen.getByPlaceholderText('common.password'), {
target: { value: '123456' },
});
fireEvent.click(screen.getByText('login.userAgreementTips'));
fireEvent.click(screen.getByText('login.login'));

await act(async () => jest.advanceTimersByTime(0));
await act(async () => jest.advanceTimersByTime(3000));

expect(encryptSpy).toBeCalledWith('123456', {
enable: true,
public_key: '04public',
key_id: 'kid-1',
});
expect(request).toBeCalledTimes(1);
expect(request).toBeCalledWith({
username: 'root',
encrypted_password: 'cipher-text',
key_id: 'kid-1',
});
const payload = request.mock.calls[0][0];
expect(payload.password).toBeUndefined();
});

test('should not call login when encrypt failed', async () => {
const request = mockRequest();
mockGetLoginEncryption({
enable: true,
public_key: '04public',
key_id: 'kid-1',
});
jest.spyOn(loginEncryption, 'encryptLoginPassword').mockImplementation(() => {
throw new loginEncryption.LoginEncryptionError('encrypt password failed');
});

renderWithThemeAndRouter(<Login />);
fireEvent.input(screen.getByPlaceholderText('common.username'), {
target: { value: 'root' },
});
fireEvent.input(screen.getByPlaceholderText('common.password'), {
target: { value: '123456' },
});
fireEvent.click(screen.getByText('login.userAgreementTips'));
fireEvent.click(screen.getByText('login.login'));

await act(async () => jest.advanceTimersByTime(0));
await act(async () => jest.advanceTimersByTime(3000));

expect(request).not.toBeCalled();
expect(
screen.getByText('login.errorMessage.encryptFailed')
).toBeInTheDocument();
});

test('click oauth login button will jump to `/v1/oauth2/link`', async () => {
renderWithTheme(<Login />);
await act(async () => jest.advanceTimersByTime(3000));
Expand Down Expand Up @@ -188,7 +273,7 @@ describe('Login', () => {

fireEvent.click(screen.getByText('login.login'));
await act(async () => jest.advanceTimersByTime(0));

await act(async () => jest.advanceTimersByTime(3000));
await act(async () => jest.advanceTimersByTime(3000));

expect(navigateSpy).toBeCalledTimes(1);
Expand Down Expand Up @@ -227,7 +312,7 @@ describe('Login', () => {
fireEvent.click(screen.getByText('login.login'));

await act(async () => jest.advanceTimersByTime(0));

await act(async () => jest.advanceTimersByTime(3000));
await act(async () => jest.advanceTimersByTime(3000));

expect(navigateSpy).toBeCalledTimes(1);
Expand Down
71 changes: 50 additions & 21 deletions src/page/Login/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,43 @@ import { useLocation } from 'react-router-dom';
import { getCookie } from '../../utils/Common';
import { IReduxState } from '../../store';
import useNavigate from '../../hooks/useNavigate';
import { IUserLoginReqV1 } from '../../api/common.d';
import {
encryptLoginPassword,
} from '../../utils/loginEncryption';

const Login = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
const { t } = useTranslation();
const location = useLocation();

const login = (formData: {
const buildLoginPayload = async (
username: string,
password: string
): Promise<IUserLoginReqV1 | null> => {
try {
const encRes = await user.getLoginEncryptionV1();
const encryption = encRes.data?.data ?? {};
if (!encryption.enable) {
return {
username,
password,
};
}
const encrypted = encryptLoginPassword(password, encryption);
return {
username,
encrypted_password: encrypted.encrypted_password,
key_id: encrypted.key_id,
};
} catch (error) {
message.error(t('login.errorMessage.encryptFailed'));
return null;
}
};

const login = async (formData: {
username: string;
password: string;
userAgreement: boolean;
Expand All @@ -39,29 +68,29 @@ const Login = () => {
return;
}
/* FITRUE_isEE */
user
.loginV2({
username: formData.username,
password: formData.password,
})
.then((res) => {
if (res.data.code === ResponseCode.SUCCESS) {
const params = new URLSearchParams(location.search);
dispatch(
updateToken({ token: getCookie(SQLE_COOKIE_TOKEN_KEY_NAME) })
);
const target = params.get(SQLE_REDIRECT_KEY_PARAMS_NAME);
if (target) {
if (target === '/sqlQuery') {
navigate(`sqlQuery?${OPEN_CLOUD_BEAVER_URL_PARAM_NAME}=true`);
} else {
navigate(target);
}
const payload = await buildLoginPayload(
formData.username,
formData.password
);
if (!payload) {
return;
}
user.loginV2(payload).then((res) => {
if (res.data.code === ResponseCode.SUCCESS) {
const params = new URLSearchParams(location.search);
dispatch(updateToken({ token: getCookie(SQLE_COOKIE_TOKEN_KEY_NAME) }));
const target = params.get(SQLE_REDIRECT_KEY_PARAMS_NAME);
if (target) {
if (target === '/sqlQuery') {
navigate(`sqlQuery?${OPEN_CLOUD_BEAVER_URL_PARAM_NAME}=true`);
} else {
navigate('home');
navigate(target);
}
} else {
navigate('home');
}
});
}
});
};
const { run: getOauth2Tips, data: oauthConfig } = useRequest(
() => configuration.getOauth2Tips().then((res) => res.data?.data ?? {}),
Expand Down
19 changes: 19 additions & 0 deletions src/types/sm-crypto.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
declare module 'sm-crypto' {
export const sm2: {
doEncrypt: (
msg: string | number[],
publicKey: string,
cipherMode?: number
) => string;
doDecrypt: (
encryptData: string,
privateKey: string,
cipherMode?: number,
options?: { output?: 'string' | 'array' }
) => string | number[];
generateKeyPairHex: (
random?: string | number | object
) => { publicKey: string; privateKey: string };
verifyPublicKey: (publicKey: string) => boolean;
};
}
Loading
Loading