mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
Merge pull request #13148 from harsh-sikarwar/feat-custom-mfa-challenge-factor
feat: add custom MFA challenge factor
This commit is contained in:
11 files changed
+387
-1
No files matched your search
@@ -106,6 +106,7 @@ use Appwrite\Utopia\Response\Model\Message;
|
||||
use Appwrite\Utopia\Response\Model\Metric;
|
||||
use Appwrite\Utopia\Response\Model\MetricBreakdown;
|
||||
use Appwrite\Utopia\Response\Model\MFAChallenge;
|
||||
use Appwrite\Utopia\Response\Model\MFAChallengeSecret;
|
||||
use Appwrite\Utopia\Response\Model\MFAFactors;
|
||||
use Appwrite\Utopia\Response\Model\MFARecoveryCodes;
|
||||
use Appwrite\Utopia\Response\Model\MFAType;
|
||||
@@ -512,6 +513,7 @@ Response::setModel(new ConsoleOAuth2ProviderList());
|
||||
Response::setModel(new ConsoleKeyScope());
|
||||
Response::setModel(new ConsoleKeyScopeList());
|
||||
Response::setModel(new MFAChallenge());
|
||||
Response::setModel(new MFAChallengeSecret());
|
||||
Response::setModel(new MFARecoveryCodes());
|
||||
Response::setModel(new MFAType());
|
||||
Response::setModel(new MFAFactors());
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Auth\MFA\Challenge;
|
||||
|
||||
use Appwrite\Auth\MFA\Challenge;
|
||||
use Appwrite\Auth\MFA\Type;
|
||||
use Utopia\Database\Document;
|
||||
|
||||
class Custom extends Challenge
|
||||
{
|
||||
public static function verify(Document $challenge, string $otp): bool
|
||||
{
|
||||
return $challenge->getAttribute('code') === $otp;
|
||||
}
|
||||
|
||||
public static function challenge(Document $challenge, Document $user, string $otp): bool
|
||||
{
|
||||
if (
|
||||
$challenge->isSet('type') &&
|
||||
$challenge->getAttribute('type') === Type::CUSTOM
|
||||
) {
|
||||
return self::verify($challenge, $otp);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ abstract class Type
|
||||
public const EMAIL = 'email';
|
||||
public const PHONE = 'phone';
|
||||
public const RECOVERY_CODE = 'recoveryCode';
|
||||
public const CUSTOM = 'custom';
|
||||
|
||||
public function setLabel(string $label): self
|
||||
{
|
||||
|
||||
@@ -94,7 +94,7 @@ class Create extends Action
|
||||
])
|
||||
->label('abuse-limit', 10)
|
||||
->label('abuse-key', 'url:{url},userId:{userId}')
|
||||
->param('factor', '', new WhiteList([Type::EMAIL, Type::PHONE, Type::TOTP, Type::RECOVERY_CODE]), 'Factor used for verification. Must be one of following: `' . Type::EMAIL . '`, `' . Type::PHONE . '`, `' . Type::TOTP . '`, `' . Type::RECOVERY_CODE . '`.', enum: new Enum(name: 'AuthenticationFactor'))
|
||||
->param('factor', '', new WhiteList([Type::EMAIL, Type::PHONE, Type::TOTP, Type::RECOVERY_CODE, Type::CUSTOM]), 'Factor used for verification. Must be one of following: `' . Type::EMAIL . '`, `' . Type::PHONE . '`, `' . Type::TOTP . '`, `' . Type::RECOVERY_CODE . '`, `' . Type::CUSTOM . '`.', enum: new Enum(name: 'AuthenticationFactor'))
|
||||
->inject('response')
|
||||
->inject('dbForProject')
|
||||
->inject('user')
|
||||
|
||||
@@ -133,6 +133,7 @@ class Update extends Action
|
||||
Type::PHONE => Challenge\Phone::challenge($challenge, $user, $otp),
|
||||
Type::EMAIL => Challenge\Email::challenge($challenge, $user, $otp),
|
||||
Type::RECOVERY_CODE => $recoveryCodeChallenge($challenge, $user, $otp),
|
||||
Type::CUSTOM => Challenge\Custom::challenge($challenge, $user, $otp),
|
||||
default => false
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Users\Http\Users\MFA\Challenges;
|
||||
|
||||
use Appwrite\Auth\MFA\Type;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Platform\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Validator\UID;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\Validator\Text;
|
||||
|
||||
class Get extends Action
|
||||
{
|
||||
use HTTP;
|
||||
|
||||
public static function getName(): string
|
||||
{
|
||||
return 'getUserMFAChallenge';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->setHttpMethod(Action::HTTP_REQUEST_METHOD_GET)
|
||||
->setHttpPath('/v1/users/:userId/mfa/challenges/:challengeId')
|
||||
->desc('Get MFA challenge')
|
||||
->groups(['api', 'users'])
|
||||
->label('scope', 'users.read')
|
||||
->label('usage.metric', 'users.{scope}.requests.read')
|
||||
->label('sdk', [
|
||||
new Method(
|
||||
namespace: 'users',
|
||||
group: 'mfa',
|
||||
name: 'getMFAChallenge',
|
||||
description: 'Get a custom MFA challenge for a user, including the code to be delivered through your own channel.',
|
||||
auth: [AuthType::ADMIN, AuthType::KEY],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
model: Response::MODEL_MFA_CHALLENGE_SECRET,
|
||||
),
|
||||
]
|
||||
),
|
||||
])
|
||||
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
|
||||
->param('challengeId', '', new Text(256), 'ID of the challenge.')
|
||||
->inject('response')
|
||||
->inject('dbForProject')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(string $userId, string $challengeId, Response $response, Database $dbForProject): void
|
||||
{
|
||||
$user = $dbForProject->getDocument('users', $userId);
|
||||
|
||||
if ($user->isEmpty()) {
|
||||
throw new Exception(Exception::USER_NOT_FOUND);
|
||||
}
|
||||
|
||||
$challenge = $dbForProject->getDocument('challenges', $challengeId);
|
||||
|
||||
if (
|
||||
$challenge->isEmpty()
|
||||
|| $challenge->getAttribute('userId') !== $userId
|
||||
|| $challenge->getAttribute('type') !== Type::CUSTOM
|
||||
) {
|
||||
throw new Exception(Exception::USER_INVALID_TOKEN);
|
||||
}
|
||||
|
||||
$response->dynamic($challenge, Response::MODEL_MFA_CHALLENGE_SECRET);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use Appwrite\Platform\Modules\Users\Http\Users\Labels\Update as UpdateLabels;
|
||||
use Appwrite\Platform\Modules\Users\Http\Users\MD5\Create as CreateMD5User;
|
||||
use Appwrite\Platform\Modules\Users\Http\Users\Memberships\XList as ListMemberships;
|
||||
use Appwrite\Platform\Modules\Users\Http\Users\MFA\Authenticators\Delete as DeleteAuthenticator;
|
||||
use Appwrite\Platform\Modules\Users\Http\Users\MFA\Challenges\Get as GetMFAChallenge;
|
||||
use Appwrite\Platform\Modules\Users\Http\Users\MFA\Factors\XList as ListFactors;
|
||||
use Appwrite\Platform\Modules\Users\Http\Users\MFA\RecoveryCodes\Create as CreateRecoveryCodes;
|
||||
use Appwrite\Platform\Modules\Users\Http\Users\MFA\RecoveryCodes\Get as GetRecoveryCodes;
|
||||
@@ -109,6 +110,7 @@ class Http extends Service
|
||||
// MFA
|
||||
$this->addAction(UpdateMFA::getName(), new UpdateMFA());
|
||||
$this->addAction(ListFactors::getName(), new ListFactors());
|
||||
$this->addAction(GetMFAChallenge::getName(), new GetMFAChallenge());
|
||||
$this->addAction(GetRecoveryCodes::getName(), new GetRecoveryCodes());
|
||||
$this->addAction(CreateRecoveryCodes::getName(), new CreateRecoveryCodes());
|
||||
$this->addAction(UpdateRecoveryCodes::getName(), new UpdateRecoveryCodes());
|
||||
|
||||
@@ -134,6 +134,7 @@ class Response extends SwooleResponse
|
||||
public const MODEL_MFA_FACTORS = 'mfaFactors';
|
||||
public const MODEL_MFA_OTP = 'mfaTotp';
|
||||
public const MODEL_MFA_CHALLENGE = 'mfaChallenge';
|
||||
public const MODEL_MFA_CHALLENGE_SECRET = 'mfaChallengeSecret';
|
||||
public const MODEL_MFA_RECOVERY_CODES = 'mfaRecoveryCodes';
|
||||
|
||||
// Users password algos
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Response\Model;
|
||||
|
||||
use Appwrite\Utopia\Response;
|
||||
|
||||
class MFAChallengeSecret extends MFAChallenge
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this
|
||||
->addRule('code', [
|
||||
'type' => self::TYPE_STRING,
|
||||
'description' => 'Challenge code to be delivered to the end user through a custom channel.',
|
||||
'default' => '',
|
||||
'example' => '446372',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Name
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return 'MFA Challenge Secret';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Type
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return Response::MODEL_MFA_CHALLENGE_SECRET;
|
||||
}
|
||||
}
|
||||
@@ -4271,6 +4271,115 @@ final class AccountCustomClientTest extends Scope
|
||||
$this->assertEquals(401, $verification3['headers']['status-code']);
|
||||
}
|
||||
|
||||
public function testMFACustomChallenge(): void
|
||||
{
|
||||
$projectId = $this->getProject()['$id'];
|
||||
$apiKey = $this->getProject()['apiKey'];
|
||||
|
||||
// Create custom factor challenge using existing authenticated session
|
||||
$challenge = $this->client->call(Client::METHOD_POST, '/account/mfa/challenge', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'factor' => 'custom'
|
||||
]);
|
||||
|
||||
$this->assertEquals(201, $challenge['headers']['status-code']);
|
||||
$this->assertNotEmpty($challenge['body']['$id']);
|
||||
// The challenge code must never be exposed on the client-facing create response
|
||||
$this->assertArrayNotHasKey('code', $challenge['body']);
|
||||
$challengeId = $challenge['body']['$id'];
|
||||
$userId = $challenge['body']['userId'];
|
||||
|
||||
// Test FAILURE: a client session (no API key) must not be able to read the code
|
||||
$clientCodeResponse = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/' . $challengeId, array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertEquals(401, $clientCodeResponse['headers']['status-code']);
|
||||
|
||||
// Server SDK reads the raw code via the server-only endpoint
|
||||
$codeResponse = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/' . $challengeId, [
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
'x-appwrite-key' => $apiKey,
|
||||
]);
|
||||
|
||||
$this->assertEquals(200, $codeResponse['headers']['status-code']);
|
||||
$this->assertNotEmpty($codeResponse['body']['code']);
|
||||
$code = $codeResponse['body']['code'];
|
||||
|
||||
// Test FAILURE: verifying with a random/incorrect otp before the real one is used
|
||||
$wrongFirst = $this->client->call(Client::METHOD_PUT, '/account/mfa/challenge', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'challengeId' => $challengeId,
|
||||
'otp' => 'random-incorrect-code'
|
||||
]);
|
||||
|
||||
$this->assertEquals(401, $wrongFirst['headers']['status-code']);
|
||||
|
||||
// Test SUCCESS: Verify with the correct code
|
||||
$verification = $this->client->call(Client::METHOD_PUT, '/account/mfa/challenge', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'challengeId' => $challengeId,
|
||||
'otp' => $code
|
||||
]);
|
||||
|
||||
$this->assertEquals(200, $verification['headers']['status-code']);
|
||||
$this->assertArrayHasKey('factors', $verification['body']);
|
||||
$this->assertContains('custom', $verification['body']['factors']);
|
||||
// The session response must never leak the MFA secret back to a non-privileged/non-key caller
|
||||
$this->assertArrayHasKey('secret', $verification['body']);
|
||||
$this->assertEmpty($verification['body']['secret']);
|
||||
|
||||
// Test that the challenge was consumed (can't verify the same one twice)
|
||||
$reuse = $this->client->call(Client::METHOD_PUT, '/account/mfa/challenge', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'challengeId' => $challengeId,
|
||||
'otp' => $code
|
||||
]);
|
||||
|
||||
$this->assertEquals(401, $reuse['headers']['status-code']);
|
||||
|
||||
// Test FAILURE: Invalid otp
|
||||
$challenge2 = $this->client->call(Client::METHOD_POST, '/account/mfa/challenge', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'factor' => 'custom'
|
||||
]);
|
||||
|
||||
$this->assertEquals(201, $challenge2['headers']['status-code']);
|
||||
|
||||
$verification2 = $this->client->call(Client::METHOD_PUT, '/account/mfa/challenge', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'challengeId' => $challenge2['body']['$id'],
|
||||
'otp' => 'wrong-secret-123'
|
||||
]);
|
||||
|
||||
$this->assertEquals(401, $verification2['headers']['status-code']);
|
||||
|
||||
// Test FAILURE: Nonexistent challengeId
|
||||
$verification3 = $this->client->call(Client::METHOD_PUT, '/account/mfa/challenge', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'challengeId' => 'nonexistent-challenge-id',
|
||||
'otp' => '123456'
|
||||
]);
|
||||
|
||||
$this->assertEquals(401, $verification3['headers']['status-code']);
|
||||
}
|
||||
|
||||
public function testRegenerateMFARecoveryCodesRequiresRecentChallenge(): void
|
||||
{
|
||||
$data = $this->createFreshAccountWithSession();
|
||||
|
||||
@@ -629,6 +629,135 @@ trait UsersBase
|
||||
$this->assertEquals(204, $response['headers']['status-code']);
|
||||
}
|
||||
|
||||
public function testGetMFAChallenge(): void
|
||||
{
|
||||
$projectId = $this->getProject()['$id'];
|
||||
|
||||
$user = $this->client->call(Client::METHOD_POST, '/users', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'userId' => ID::unique(),
|
||||
'email' => \uniqid() . '@appwrite.io',
|
||||
'password' => 'password',
|
||||
'name' => 'MFA Challenge User',
|
||||
]);
|
||||
|
||||
$this->assertEquals(201, $user['headers']['status-code']);
|
||||
$userId = $user['body']['$id'];
|
||||
|
||||
$session = $this->client->call(Client::METHOD_POST, '/users/' . $userId . '/sessions', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertEquals(201, $session['headers']['status-code']);
|
||||
$sessionSecret = $session['body']['secret'];
|
||||
|
||||
$challenge = $this->client->call(Client::METHOD_POST, '/account/mfa/challenge', [
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
'x-appwrite-session' => $sessionSecret,
|
||||
], [
|
||||
'factor' => 'custom'
|
||||
]);
|
||||
|
||||
$this->assertEquals(201, $challenge['headers']['status-code']);
|
||||
$this->assertArrayNotHasKey('code', $challenge['body']);
|
||||
$challengeId = $challenge['body']['$id'];
|
||||
|
||||
/**
|
||||
* Test for SUCCESS: server (API key) can read the code
|
||||
*/
|
||||
$response = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/' . $challengeId, array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertEquals(200, $response['headers']['status-code']);
|
||||
$this->assertEquals($challengeId, $response['body']['$id']);
|
||||
$this->assertEquals($userId, $response['body']['userId']);
|
||||
$this->assertNotEmpty($response['body']['code']);
|
||||
|
||||
/**
|
||||
* Test for FAILURE: a client session (not a server key) must be rejected
|
||||
*/
|
||||
$response = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/' . $challengeId, [
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
'x-appwrite-session' => $sessionSecret,
|
||||
]);
|
||||
|
||||
$this->assertEquals(401, $response['headers']['status-code']);
|
||||
|
||||
/**
|
||||
* Test for FAILURE: a challenge belonging to a different user must not be readable
|
||||
*/
|
||||
$otherUser = $this->client->call(Client::METHOD_POST, '/users', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()), [
|
||||
'userId' => ID::unique(),
|
||||
'email' => \uniqid() . '@appwrite.io',
|
||||
'password' => 'password',
|
||||
'name' => 'Other User',
|
||||
]);
|
||||
|
||||
$this->assertEquals(201, $otherUser['headers']['status-code']);
|
||||
$otherUserId = $otherUser['body']['$id'];
|
||||
|
||||
$response = $this->client->call(Client::METHOD_GET, '/users/' . $otherUserId . '/mfa/challenges/' . $challengeId, array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertEquals(401, $response['headers']['status-code']);
|
||||
|
||||
/**
|
||||
* Test for FAILURE: nonexistent challengeId
|
||||
*/
|
||||
$response = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/nonexistent', array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertEquals(401, $response['headers']['status-code']);
|
||||
|
||||
/**
|
||||
* Test for FAILURE: nonexistent userId
|
||||
*/
|
||||
$response = $this->client->call(Client::METHOD_GET, '/users/nonexistent/mfa/challenges/' . $challengeId, array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertEquals(404, $response['headers']['status-code']);
|
||||
|
||||
/**
|
||||
* Test for FAILURE: a non-custom challenge (e.g. totp) must not be readable,
|
||||
* even with valid ownership and a valid API key. Native factors deliver their
|
||||
* own code out of band (email/SMS); this endpoint only exists to hand the
|
||||
* 'custom' factor's code to the developer's own delivery mechanism.
|
||||
*/
|
||||
$totpChallenge = $this->client->call(Client::METHOD_POST, '/account/mfa/challenge', [
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
'x-appwrite-session' => $sessionSecret,
|
||||
], [
|
||||
'factor' => 'totp'
|
||||
]);
|
||||
|
||||
$this->assertEquals(201, $totpChallenge['headers']['status-code']);
|
||||
$totpChallengeId = $totpChallenge['body']['$id'];
|
||||
|
||||
$response = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/' . $totpChallengeId, array_merge([
|
||||
'content-type' => 'application/json',
|
||||
'x-appwrite-project' => $projectId,
|
||||
], $this->getHeaders()));
|
||||
|
||||
$this->assertEquals(401, $response['headers']['status-code']);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Tests all optional parameters of createUser (email, phone, anonymous..)
|
||||
|
||||
Reference in new issue
Block a user