diff --git a/app/init/models.php b/app/init/models.php index d3b776b2bd..59da71b356 100644 --- a/app/init/models.php +++ b/app/init/models.php @@ -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()); diff --git a/src/Appwrite/Auth/MFA/Challenge/Custom.php b/src/Appwrite/Auth/MFA/Challenge/Custom.php new file mode 100644 index 0000000000..3dd7bfceba --- /dev/null +++ b/src/Appwrite/Auth/MFA/Challenge/Custom.php @@ -0,0 +1,27 @@ +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; + } +} diff --git a/src/Appwrite/Auth/MFA/Type.php b/src/Appwrite/Auth/MFA/Type.php index d1e267965a..38236a4635 100644 --- a/src/Appwrite/Auth/MFA/Type.php +++ b/src/Appwrite/Auth/MFA/Type.php @@ -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 { diff --git a/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php b/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php index 06c8cc3118..83d0a5112c 100644 --- a/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php +++ b/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Create.php @@ -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') diff --git a/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Update.php b/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Update.php index 5f6b7a1186..f34deb2ab9 100644 --- a/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Update.php +++ b/src/Appwrite/Platform/Modules/Account/Http/Account/MFA/Challenges/Update.php @@ -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 }); diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php b/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php new file mode 100644 index 0000000000..f11db67cf1 --- /dev/null +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php @@ -0,0 +1,81 @@ +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: '/docs/references/users/get-mfa-challenge.md', + 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) { + throw new Exception(Exception::USER_INVALID_TOKEN); + } + + $document = new Document([ + '$id' => $challenge->getId(), + '$createdAt' => $challenge->getCreatedAt(), + 'userId' => $challenge->getAttribute('userId'), + 'expire' => $challenge->getAttribute('expire'), + 'secret' => $challenge->getAttribute('code'), + ]); + + $response->dynamic($document, Response::MODEL_MFA_CHALLENGE_SECRET); + } +} diff --git a/src/Appwrite/Platform/Modules/Users/Services/Http.php b/src/Appwrite/Platform/Modules/Users/Services/Http.php index 3d763c8cfa..3dff6f65a2 100644 --- a/src/Appwrite/Platform/Modules/Users/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Users/Services/Http.php @@ -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()); diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index b5d85efc9e..ec2a4ac978 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -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 diff --git a/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php b/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php new file mode 100644 index 0000000000..ecdba9291d --- /dev/null +++ b/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php @@ -0,0 +1,60 @@ +addRule('$id', [ + 'type' => self::TYPE_STRING, + 'description' => 'Token ID.', + 'default' => '', + 'example' => 'bb8ea5c16897e', + ]) + ->addRule('$createdAt', [ + 'type' => self::TYPE_DATETIME, + 'description' => 'Token creation date in ISO 8601 format.', + 'default' => '', + 'example' => self::TYPE_DATETIME_EXAMPLE, + ]) + ->addRule('userId', [ + 'type' => self::TYPE_STRING, + 'description' => 'User ID.', + 'default' => '', + 'example' => '5e5ea5c168bb8', + ]) + ->addRule('expire', [ + 'type' => self::TYPE_DATETIME, + 'description' => 'Token expiration date in ISO 8601 format.', + 'default' => '', + 'example' => self::TYPE_DATETIME_EXAMPLE, + ]) + ->addRule('secret', [ + 'type' => self::TYPE_STRING, + 'description' => 'Challenge secret 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; + } +} diff --git a/tests/e2e/Services/Account/AccountCustomClientTest.php b/tests/e2e/Services/Account/AccountCustomClientTest.php index 4ab8ba537a..7a51beadf8 100644 --- a/tests/e2e/Services/Account/AccountCustomClientTest.php +++ b/tests/e2e/Services/Account/AccountCustomClientTest.php @@ -4271,6 +4271,91 @@ 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']); + $challengeId = $challenge['body']['$id']; + $userId = $challenge['body']['userId']; + + // Server SDK reads the raw secret via the server-only endpoint + $secretResponse = $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, $secretResponse['headers']['status-code']); + $this->assertNotEmpty($secretResponse['body']['secret']); + $secret = $secretResponse['body']['secret']; + + // Test SUCCESS: Verify with the correct secret + $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' => $secret + ]); + + $this->assertEquals(200, $verification['headers']['status-code']); + $this->assertArrayHasKey('factors', $verification['body']); + $this->assertContains('custom', $verification['body']['factors']); + + // 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' => $secret + ]); + + $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(); diff --git a/tests/e2e/Services/Users/UsersBase.php b/tests/e2e/Services/Users/UsersBase.php index b1cd43c85c..0745e85b2a 100644 --- a/tests/e2e/Services/Users/UsersBase.php +++ b/tests/e2e/Services/Users/UsersBase.php @@ -629,6 +629,110 @@ 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']); + $challengeId = $challenge['body']['$id']; + + /** + * Test for SUCCESS: server (API key) can read the secret + */ + $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']['secret']); + + /** + * 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']); + } + /** * Tests all optional parameters of createUser (email, phone, anonymous..)