Skip to content

Commit 31fe638

Browse files
fix(accounts): show JSON import password errors under the password field (#47802)
## **Description** When a JSON keystore import fails because the password is missing or wrong, the error was shown under the JSON file picker. The password field is where the user needs to act, so the error now appears under the password field. The keystore decrypt step (`ethereumjs-wallet`) throws the same `Key derivation failed - possibly wrong passphrase` error for a missing password and a wrong password, so the message is shown as "The password is missing or incorrect." That message is only applied to JSON imports. Private key imports keep their existing error placement. File errors, such as a file that is not a keystore, still appear under the file picker. No functional change to how imports are performed. This only changes where and how the error is shown. ## **Changelog** CHANGELOG entry: Fixed JSON account import showing a wrong-password error under the file picker instead of the password field ## **Related issues** Fixes: ## **Manual testing steps** 1. Go to the account list and open the add account flow, then choose Import account. 2. Select the JSON file option. 3. Select `test/e2e/import-utc-json/test-json-import-account-file.json` from the repo. 4. Enter `wrongpassword` in the password field and click Import. 5. Verify "The password is missing or incorrect." appears under the password field, the password field is outlined in the error color, and no error appears under the file picker. 6. Clear the password field and click Import. Verify the same error appears under the password field. 7. Enter `foobarbazqux` and click Import. Verify the account imports. 8. Select a file that is not a keystore, such as a plain text file. Verify the error appears under the file picker and not under the password field. ## **Screenshots/Recordings** ### **Before** ### **After** https://github.com/user-attachments/assets/eccb7ebf-4321-4262-86e8-147b4644cfec https://github.com/user-attachments/assets/382036a9-5a92-4062-aa1d-1437199f472d ## **Pre-merge author checklist** - [ ] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [ ] I've completed the PR template to the best of my ability - [x] I’ve included tests if applicable - [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [ ] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **Pre-merge reviewer checklist** - [ ] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [ ] I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > UI-only error placement and messaging for JSON import; no change to import logic beyond how passphrase failures are interpreted for display. > > **Overview** > JSON keystore import errors about missing or wrong passwords are now routed to the **password field** instead of the file picker, with clearer copy depending on whether the user left the password blank, entered one on the first try, or retried after a blank failure. > > The import flow tracks blank-password failures for JSON imports when the backend reports a generic passphrase/MAC error, and **`JsonImportView`** splits password vs file validation messages with appropriate **`role="alert"`** / **`aria-describedby`** wiring. Non-password JSON errors stay on the file control; private-key import errors keep their existing placement but gain alert semantics on the field help text. > > New locale strings and unit tests cover the password messaging and accessibility behavior. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 13d651c. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent a24446b commit 31fe638

7 files changed

Lines changed: 245 additions & 3 deletions

File tree

‎app/_locales/en/messages.json‎

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎app/_locales/en_GB/messages.json‎

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎ui/components/multichain/import-account/import-account.js‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ export const ImportAccount = ({ onActionComplete }) => {
4545

4646
const [type, setType] = useState(importTypes[0].id);
4747
const [importErrorMessage, setImportErrorMessage] = useState();
48+
const [jsonBlankPasswordFailed, setJsonBlankPasswordFailed] = useState(false);
4849

4950
async function importAccount(strategy, importArgs) {
5051
const loadingMessage = getLoadingMessage(strategy);
@@ -67,6 +68,7 @@ export const ImportAccount = ({ onActionComplete }) => {
6768
if (selectedAccount) {
6869
trackImportEvent(strategy, true);
6970
setImportErrorMessage();
71+
setJsonBlankPasswordFailed(false);
7072
onActionComplete(true);
7173
} else {
7274
setImportErrorMessage(t('importAccountError'));
@@ -76,6 +78,21 @@ export const ImportAccount = ({ onActionComplete }) => {
7678
const message = getErrorMessage(error);
7779
trackImportEvent(strategy, false);
7880

81+
// A V3 keystore reports a failed MAC check as a passphrase error for both
82+
// a missing password and a wrong one, so there is no code to match on.
83+
if (strategy === 'json' && message.includes('passphrase')) {
84+
const submittedPassword = importArgs[1] ?? '';
85+
if (submittedPassword === '') {
86+
setJsonBlankPasswordFailed(true);
87+
setImportErrorMessage(t('jsonImportPasswordRequired'));
88+
} else if (jsonBlankPasswordFailed) {
89+
setImportErrorMessage(t('jsonImportPasswordIncorrect'));
90+
} else {
91+
setImportErrorMessage(t('jsonImportPasswordIncorrectOrOptional'));
92+
}
93+
return false;
94+
}
95+
7996
if (handleKeyringControllerError(error)) {
8097
return false;
8198
}
@@ -233,6 +250,7 @@ export const ImportAccount = ({ onActionComplete }) => {
233250
data-testid={`import-account-type-${id}`}
234251
onClick={() => {
235252
setImportErrorMessage();
253+
setJsonBlankPasswordFailed(false);
236254
setType(id);
237255
}}
238256
>
@@ -266,6 +284,11 @@ export const ImportAccount = ({ onActionComplete }) => {
266284
setImportErrorMessage();
267285
onActionComplete(confirmed);
268286
}}
287+
onClearImportError={() => setImportErrorMessage()}
288+
onJsonFileChange={() => {
289+
setImportErrorMessage();
290+
setJsonBlankPasswordFailed(false);
291+
}}
269292
importErrorMessage={importErrorMessage}
270293
/>
271294
)}

‎ui/components/multichain/import-account/import-account.test.tsx‎

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,116 @@ describe('ImportAccount', () => {
340340
});
341341
});
342342

343+
describe('JSON import password errors', () => {
344+
const rejectWithPassphraseError = () => {
345+
mockedActions.importNewAccount.mockReturnValue((() =>
346+
Promise.reject(
347+
new Error('Key derivation failed - possibly wrong passphrase'),
348+
)) as unknown as ReturnType<typeof actions.importNewAccount>);
349+
};
350+
351+
const selectJsonFile = async () => {
352+
fireEvent.click(
353+
screen.getByRole('button', { name: messages.jsonFile.message }),
354+
);
355+
fireEvent.change(screen.getByTestId('file-input'), {
356+
target: { files: [new File(['{}'], 'test.json')] },
357+
});
358+
await waitFor(() => {
359+
expect(getImportButton()).not.toBeDisabled();
360+
});
361+
};
362+
363+
it('tells the user a blank attempt needs a password', async () => {
364+
rejectWithPassphraseError();
365+
const { getByLabelText, queryByText } = renderImportAccount();
366+
367+
await selectJsonFile();
368+
fireEvent.click(getImportButton());
369+
370+
await waitFor(() => {
371+
expect(
372+
queryByText(messages.jsonImportPasswordRequired.message),
373+
).toBeInTheDocument();
374+
});
375+
expect(
376+
getByLabelText(messages.enterOptionalPassword.message),
377+
).toHaveAttribute('aria-describedby', 'json-password-error');
378+
379+
fireEvent.change(getByLabelText(messages.enterOptionalPassword.message), {
380+
target: { value: 'a' },
381+
});
382+
383+
expect(
384+
queryByText(messages.jsonImportPasswordRequired.message),
385+
).not.toBeInTheDocument();
386+
});
387+
388+
it('says a typed password did not work after a blank attempt failed', async () => {
389+
rejectWithPassphraseError();
390+
const { getByLabelText, queryByText } = renderImportAccount();
391+
392+
await selectJsonFile();
393+
fireEvent.click(getImportButton());
394+
395+
await waitFor(() => {
396+
expect(
397+
queryByText(messages.jsonImportPasswordRequired.message),
398+
).toBeInTheDocument();
399+
});
400+
401+
fireEvent.change(getByLabelText(messages.enterOptionalPassword.message), {
402+
target: { value: 'wrong-password' },
403+
});
404+
fireEvent.click(getImportButton());
405+
406+
await waitFor(() => {
407+
expect(
408+
queryByText(messages.jsonImportPasswordIncorrect.message),
409+
).toBeInTheDocument();
410+
});
411+
expect(
412+
queryByText(messages.jsonImportPasswordIncorrectOrOptional.message),
413+
).not.toBeInTheDocument();
414+
});
415+
416+
it('mentions a blank password when the first attempt already had one', async () => {
417+
rejectWithPassphraseError();
418+
const { getByLabelText, queryByText } = renderImportAccount();
419+
420+
await selectJsonFile();
421+
fireEvent.change(getByLabelText(messages.enterOptionalPassword.message), {
422+
target: { value: 'wrong-password' },
423+
});
424+
fireEvent.click(getImportButton());
425+
426+
await waitFor(() => {
427+
expect(
428+
queryByText(messages.jsonImportPasswordIncorrectOrOptional.message),
429+
).toBeInTheDocument();
430+
});
431+
});
432+
433+
it('does not show a passphrase failure from a private key import under the password field', async () => {
434+
rejectWithPassphraseError();
435+
const { getByLabelText, queryByText } = renderImportAccount();
436+
437+
fireEvent.change(getByLabelText(messages.enterYourPrivateKey.message), {
438+
target: { value: '0xabcdef1234567890' },
439+
});
440+
fireEvent.click(getImportButton());
441+
442+
await waitFor(() => {
443+
expect(
444+
queryByText('Key derivation failed - possibly wrong passphrase'),
445+
).toBeInTheDocument();
446+
});
447+
expect(
448+
queryByText(messages.jsonImportPasswordRequired.message),
449+
).not.toBeInTheDocument();
450+
});
451+
});
452+
343453
describe('KeyringController error handling', () => {
344454
it('handles KeyringController errors by trimming the prefix and displaying warning', async () => {
345455
const keyringError = new Error(
@@ -365,7 +475,7 @@ describe('ImportAccount', () => {
365475
await waitFor(() => {
366476
expect(
367477
queryByText('The account you are trying to import is a duplicate'),
368-
).toBeInTheDocument();
478+
).toHaveAttribute('role', 'alert');
369479
});
370480
});
371481

‎ui/components/multichain/import-account/json.js‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ import BottomButtons from './bottom-buttons';
2727
export default function JsonImportSubview({
2828
importAccountFunc,
2929
onActionComplete,
30+
onClearImportError,
31+
onJsonFileChange,
3032
importErrorMessage,
3133
}) {
3234
const t = useI18nContext();
@@ -37,8 +39,18 @@ export default function JsonImportSubview({
3739
const [errorMessage, setErrorMessage] = useState();
3840

3941
const isPrimaryDisabled = fileContents === '';
40-
const fileError = errorMessage ?? importErrorMessage;
42+
const passwordErrors = [
43+
t('jsonImportPasswordRequired'),
44+
t('jsonImportPasswordIncorrect'),
45+
t('jsonImportPasswordIncorrectOrOptional'),
46+
];
47+
const passwordError = passwordErrors.includes(importErrorMessage)
48+
? importErrorMessage
49+
: undefined;
50+
const fileError =
51+
errorMessage ?? (passwordError ? undefined : importErrorMessage);
4152
const fileErrorId = 'json-file-error';
53+
const passwordErrorId = 'json-password-error';
4254

4355
function handleKeyPress(event) {
4456
if (!isPrimaryDisabled && event.key === 'Enter') {
@@ -74,6 +86,7 @@ export default function JsonImportSubview({
7486
onLoad={(event) => {
7587
setErrorMessage();
7688
setFileContents(event.target.result);
89+
onJsonFileChange?.();
7790
}}
7891
style={{
7992
position: 'absolute',
@@ -94,7 +107,11 @@ export default function JsonImportSubview({
94107
</Text>
95108
</label>
96109
{fileError ? (
97-
<HelpText id={fileErrorId} severity={HelpTextSeverity.Danger}>
110+
<HelpText
111+
id={fileErrorId}
112+
role="alert"
113+
severity={HelpTextSeverity.Danger}
114+
>
98115
{fileError}
99116
</HelpText>
100117
) : null}
@@ -117,12 +134,21 @@ export default function JsonImportSubview({
117134
id="json-password-box"
118135
size={TextFieldSize.Lg}
119136
placeholder={t('enterOptionalPassword')}
137+
helpText={passwordError}
138+
helpTextProps={
139+
passwordError ? { id: passwordErrorId, role: 'alert' } : undefined
140+
}
141+
isError={Boolean(passwordError)}
120142
value={password}
121143
onChange={(event) => {
122144
setPassword(event.target.value);
145+
if (passwordError) {
146+
onClearImportError?.();
147+
}
123148
}}
124149
inputProps={{
125150
'aria-label': t('enterOptionalPassword'),
151+
'aria-describedby': passwordError ? passwordErrorId : undefined,
126152
onKeyPress: handleKeyPress,
127153
}}
128154
type={showPassword ? TextFieldType.Text : TextFieldType.Password}
@@ -159,6 +185,14 @@ JsonImportSubview.propTypes = {
159185
* Executes when the key is imported
160186
*/
161187
onActionComplete: PropTypes.func.isRequired,
188+
/**
189+
* Clears the import error shown under the password field
190+
*/
191+
onClearImportError: PropTypes.func,
192+
/**
193+
* Resets password-attempt state when a different file is chosen
194+
*/
195+
onJsonFileChange: PropTypes.func,
162196
/**
163197
* Import error message
164198
*/

‎ui/components/multichain/import-account/json.test.tsx‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,54 @@ describe('Json', () => {
104104
expect(mockImportFunc).toHaveBeenCalledWith('json', ['0', 'password']);
105105
});
106106
});
107+
108+
it('shows a missing or incorrect password under the password field', () => {
109+
const { getByLabelText, getByTestId, getByText } = renderWithProvider(
110+
<Json
111+
importAccountFunc={mockImportFunc}
112+
onActionComplete={mockOnActionComplete}
113+
importErrorMessage={messages.jsonImportPasswordRequired.message}
114+
/>,
115+
mockStore,
116+
);
117+
118+
expect(
119+
getByText(messages.jsonImportPasswordRequired.message),
120+
).toHaveAttribute('id', 'json-password-error');
121+
expect(
122+
getByText(messages.jsonImportPasswordRequired.message),
123+
).toHaveAttribute('role', 'alert');
124+
expect(
125+
getByLabelText(messages.enterOptionalPassword.message),
126+
).toHaveAttribute('aria-describedby', 'json-password-error');
127+
expect(
128+
getByLabelText(messages.enterOptionalPassword.message),
129+
).toHaveAttribute('aria-invalid', 'true');
130+
expect(getByTestId('file-input')).not.toHaveAttribute(
131+
'aria-invalid',
132+
'true',
133+
);
134+
});
135+
136+
it('keeps a file error on the JSON file input', () => {
137+
const { getByTestId, getByText } = renderWithProvider(
138+
<Json
139+
importAccountFunc={mockImportFunc}
140+
onActionComplete={mockOnActionComplete}
141+
importErrorMessage="Not a V3 wallet"
142+
/>,
143+
mockStore,
144+
);
145+
146+
expect(getByText('Not a V3 wallet')).toHaveAttribute(
147+
'id',
148+
'json-file-error',
149+
);
150+
expect(getByText('Not a V3 wallet')).toHaveAttribute('role', 'alert');
151+
expect(getByTestId('file-input')).toHaveAttribute(
152+
'aria-describedby',
153+
'json-file-error',
154+
);
155+
expect(getByTestId('file-input')).toHaveAttribute('aria-invalid', 'true');
156+
});
107157
});

‎ui/components/multichain/import-account/private-key.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ export default function PrivateKeyImportView({
4242
size={TextFieldSize.Lg}
4343
autoFocus
4444
helpText={importErrorMessage}
45+
helpTextProps={importErrorMessage ? { role: 'alert' } : undefined}
4546
isError={Boolean(importErrorMessage)}
4647
placeholder={t('enterYourPrivateKey')}
4748
value={privateKey}

0 commit comments

Comments
 (0)