-
Notifications
You must be signed in to change notification settings - Fork 402
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(2fa): implementing backend code for recovery codes
- Loading branch information
1 parent
4e71064
commit 9f02ecf
Showing
9 changed files
with
253 additions
and
4 deletions.
There are no files selected for viewing
10 changes: 10 additions & 0 deletions
10
infra/migrations/1725497930423_alter-table-users-add-mfa-totp-recovery-codes.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
exports.up = (pgm) => { | ||
pgm.addColumns('users', { | ||
totp_recovery_codes: { | ||
type: 'varchar(416)', | ||
notNull: false, | ||
}, | ||
}); | ||
}; | ||
|
||
exports.down = false; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -87,7 +87,7 @@ describe('POST /api/v1/sessions', () => { | |
expect(responseBody).toStrictEqual({ | ||
name: 'ValidationError', | ||
message: 'O duplo fator de autenticação está habilitado para esta conta.', | ||
action: 'Refaça a requisição enviando o código TOTP.', | ||
action: 'Refaça a requisição enviando o código TOTP ou um código de recuperação.', | ||
status_code: 400, | ||
key: 'totp', | ||
error_id: responseBody.error_id, | ||
|
@@ -197,6 +197,166 @@ describe('POST /api/v1/sessions', () => { | |
expect(uuidVersion(responseBody.request_id)).toBe(4); | ||
}); | ||
|
||
test('Using a valid email and password with TOTP enabled and sending a valid recovery code', async () => { | ||
const usersRequestBuilder = new RequestBuilder('/api/v1/users'); | ||
const defaultUser = await orchestrator.createUser({ | ||
email: '[email protected]', | ||
password: 'ValidRecoveryCode', | ||
}); | ||
|
||
await orchestrator.activateUser(defaultUser); | ||
await usersRequestBuilder.setUser(defaultUser); | ||
|
||
const totp_secret = otp.createSecret(); | ||
const totp = otp.createTotp(totp_secret).generate(); | ||
|
||
let { response, responseBody } = await usersRequestBuilder.patch(`/${defaultUser.username}`, { | ||
totp_secret, | ||
totp, | ||
}); | ||
|
||
const recoveryCode = responseBody.totp_recovery_codes[Math.floor(Math.random() * 10)]; | ||
|
||
response = await fetch(`${orchestrator.webserverUrl}/api/v1/sessions`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
email: '[email protected]', | ||
password: 'ValidRecoveryCode', | ||
totp_recovery_code: recoveryCode, | ||
}), | ||
}); | ||
|
||
responseBody = await response.json(); | ||
|
||
expect.soft(response.status).toBe(201); | ||
expect(responseBody.token.length).toBe(96); | ||
expect(uuidVersion(responseBody.id)).toBe(4); | ||
expect(Date.parse(responseBody.expires_at)).not.toBeNaN(); | ||
expect(Date.parse(responseBody.created_at)).not.toBeNaN(); | ||
expect(Date.parse(responseBody.updated_at)).not.toBeNaN(); | ||
|
||
const sessionObjectInDatabase = await session.findOneById(responseBody.id); | ||
expect(sessionObjectInDatabase.user_id).toBe(defaultUser.id); | ||
|
||
const parsedCookiesFromResponse = orchestrator.parseSetCookies(response); | ||
expect(parsedCookiesFromResponse.session_id.name).toBe('session_id'); | ||
expect(parsedCookiesFromResponse.session_id.value).toBe(responseBody.token); | ||
expect(parsedCookiesFromResponse.session_id.maxAge).toBe(60 * 60 * 24 * 30); | ||
expect(parsedCookiesFromResponse.session_id.path).toBe('/'); | ||
expect(parsedCookiesFromResponse.session_id.httpOnly).toBe(true); | ||
}); | ||
|
||
test('Using a valid email and password with TOTP enabled and sending an invalid recovery code', async () => { | ||
const usersRequestBuilder = new RequestBuilder('/api/v1/users'); | ||
const defaultUser = await orchestrator.createUser({ | ||
email: '[email protected]', | ||
password: 'ValidPasswordAndInvalidRecoveryCode', | ||
}); | ||
|
||
await orchestrator.activateUser(defaultUser); | ||
await usersRequestBuilder.setUser(defaultUser); | ||
|
||
const totp_secret = otp.createSecret(); | ||
const totp = otp.createTotp(totp_secret).generate(); | ||
|
||
await usersRequestBuilder.patch(`/${defaultUser.username}`, { | ||
totp_secret, | ||
totp, | ||
}); | ||
|
||
const response = await fetch(`${orchestrator.webserverUrl}/api/v1/sessions`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
email: '[email protected]', | ||
password: 'ValidPasswordAndInvalidTotp', | ||
totp_recovery_code: otp.makeCode(), | ||
}), | ||
}); | ||
|
||
const responseBody = await response.json(); | ||
|
||
expect(response.status).toBe(401); | ||
expect(responseBody).toStrictEqual({ | ||
name: 'UnauthorizedError', | ||
message: 'O código de recuperação informado já foi usado ou é inválido.', | ||
action: 'Verifique se os dados enviados estão corretos.', | ||
status_code: 401, | ||
error_id: responseBody.error_id, | ||
request_id: responseBody.request_id, | ||
error_location_code: 'CONTROLLER:SESSIONS:POST_HANDLER:MFA:TOTP:INVALID_RECOVERY_CODE', | ||
}); | ||
|
||
expect(uuidVersion(responseBody.error_id)).toBe(4); | ||
expect(uuidVersion(responseBody.request_id)).toBe(4); | ||
}); | ||
|
||
test('Using a valid email and password with TOTP enabled and sending a valid, but already used, recovery code', async () => { | ||
const usersRequestBuilder = new RequestBuilder('/api/v1/users'); | ||
const defaultUser = await orchestrator.createUser({ | ||
email: '[email protected]', | ||
password: 'ReusedRecoveryCodeTotp', | ||
}); | ||
|
||
await orchestrator.activateUser(defaultUser); | ||
await usersRequestBuilder.setUser(defaultUser); | ||
|
||
const totp_secret = otp.createSecret(); | ||
const totp = otp.createTotp(totp_secret).generate(); | ||
|
||
let { response, responseBody } = await usersRequestBuilder.patch(`/${defaultUser.username}`, { | ||
totp_secret, | ||
totp, | ||
}); | ||
|
||
const recoveryCode = responseBody.totp_recovery_codes[Math.floor(Math.random() * 10)]; | ||
|
||
await fetch(`${orchestrator.webserverUrl}/api/v1/sessions`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
email: '[email protected]', | ||
password: 'ReusedRecoveryCodeTotp', | ||
totp_recovery_code: recoveryCode, | ||
}), | ||
}); | ||
|
||
response = await fetch(`${orchestrator.webserverUrl}/api/v1/sessions`, { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/json', | ||
}, | ||
body: JSON.stringify({ | ||
email: '[email protected]', | ||
password: 'ReusedRecoveryCodeTotp', | ||
totp_recovery_code: recoveryCode, | ||
}), | ||
}); | ||
|
||
responseBody = await response.json(); | ||
|
||
expect(response.status).toBe(401); | ||
expect(responseBody).toStrictEqual({ | ||
name: 'UnauthorizedError', | ||
message: 'O código de recuperação informado já foi usado ou é inválido.', | ||
action: 'Verifique se os dados enviados estão corretos.', | ||
status_code: 401, | ||
error_id: responseBody.error_id, | ||
request_id: responseBody.request_id, | ||
error_location_code: 'CONTROLLER:SESSIONS:POST_HANDLER:MFA:TOTP:INVALID_RECOVERY_CODE', | ||
}); | ||
|
||
expect(uuidVersion(responseBody.error_id)).toBe(4); | ||
expect(uuidVersion(responseBody.request_id)).toBe(4); | ||
}); | ||
|
||
test('Using a valid email and password, but user lost the feature "create:session"', async () => { | ||
const defaultUser = await orchestrator.createUser({ | ||
email: '[email protected]', | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters