From 477653c848ff53bea2ebfe8bab1db57950ba1c1e Mon Sep 17 00:00:00 2001 From: harsh-sikarwar Date: Sat, 8 Aug 2026 17:51:40 +0530 Subject: [PATCH 1/4] feat: add custom MFA challenge factor Adds a fifth MFA factor, `custom`, so developers can implement arbitrary second-factor flows through the server SDK -- the same pattern as the existing custom sign-in flow (users.createToken / users.createSession), applied to 2FA. - Register Type::CUSTOM alongside email/phone/totp/recoveryCode - Add Challenge/Custom.php, modeled on Challenge/Email.php (compares stored code to submitted otp, no live generation) - Account/Http/Account/MFA/Challenges/{Create,Update}.php: accept and verify the custom factor through the existing whitelist/match - New server-only endpoint: GET /v1/users/:userId/mfa/challenges/:challengeId (Users/Http/Users/MFA/Challenges/Get.php), scoped to users.read so only an API key can read a challenge's raw secret, and checks the challenge's userId to prevent cross-user access - New MFAChallengeSecret response model, kept separate from the client-facing MFAChallenge model so raw secrets never leak into the Create/Update responses Tests: testMFACustomChallenge (AccountCustomClientTest) covers the client-facing happy/failure paths; testGetMFAChallenge (UsersBase) covers the server-only endpoint including the session-vs-API-key rejection and cross-user rejection cases. --- app/init/models.php | 2 + src/Appwrite/Auth/MFA/Challenge/Custom.php | 27 +++++ src/Appwrite/Auth/MFA/Type.php | 1 + .../Http/Account/MFA/Challenges/Create.php | 2 +- .../Http/Account/MFA/Challenges/Update.php | 1 + .../Users/Http/Users/MFA/Challenges/Get.php | 81 ++++++++++++++ .../Platform/Modules/Users/Services/Http.php | 2 + src/Appwrite/Utopia/Response.php | 1 + .../Response/Model/MFAChallengeSecret.php | 60 ++++++++++ .../Account/AccountCustomClientTest.php | 85 ++++++++++++++ tests/e2e/Services/Users/UsersBase.php | 104 ++++++++++++++++++ 11 files changed, 365 insertions(+), 1 deletion(-) create mode 100644 src/Appwrite/Auth/MFA/Challenge/Custom.php create mode 100644 src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php create mode 100644 src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php 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..) From ffe62dd73996f53636fc17862af877b35c2f7180 Mon Sep 17 00:00:00 2001 From: harsh-sikarwar Date: Sat, 8 Aug 2026 18:11:32 +0530 Subject: [PATCH 2/4] fix: restrict getMFAChallenge to custom challenges The endpoint checked challenge ownership but not challenge type, so a users.read API key that learned any pending challengeId (e.g. email or phone) could read that challenge's code -- the same field native factors use to store the OTP already delivered to the user. This endpoint exists solely to hand the custom factor's secret to the developer's own delivery mechanism, so it must refuse anything else. Adds a regression test creating a totp challenge and asserting the endpoint rejects it. Found by Greptile review. --- .../Users/Http/Users/MFA/Challenges/Get.php | 7 +++++- tests/e2e/Services/Users/UsersBase.php | 24 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) 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 index f11db67cf1..97ca994dac 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php @@ -2,6 +2,7 @@ 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; @@ -64,7 +65,11 @@ class Get extends Action $challenge = $dbForProject->getDocument('challenges', $challengeId); - if ($challenge->isEmpty() || $challenge->getAttribute('userId') !== $userId) { + if ( + $challenge->isEmpty() + || $challenge->getAttribute('userId') !== $userId + || $challenge->getAttribute('type') !== Type::CUSTOM + ) { throw new Exception(Exception::USER_INVALID_TOKEN); } diff --git a/tests/e2e/Services/Users/UsersBase.php b/tests/e2e/Services/Users/UsersBase.php index 0745e85b2a..1be5c70edb 100644 --- a/tests/e2e/Services/Users/UsersBase.php +++ b/tests/e2e/Services/Users/UsersBase.php @@ -731,6 +731,30 @@ trait UsersBase ], $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 secret out of band (email/SMS); this endpoint only exists to hand the + * 'custom' factor's secret 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']); } From 6a55ae49f41890805fd1b894ba0873e9252aea04 Mon Sep 17 00:00:00 2001 From: harsh-sikarwar Date: Sat, 8 Aug 2026 22:49:37 +0530 Subject: [PATCH 3/4] refactor: address review feedback on getMFAChallenge - Return the raw challenge Document from the server-only endpoint instead of manually rebuilding it, aliasing code -> secret first. Response models already filter to only their declared rules, so the manual reconstruction was redundant. - Replace the /docs/references/... markdown path in the SDK Method description with an inline string. Every other inline-description endpoint in this codebase (Console/Variables/Get.php, Console/Scopes/*, Project OAuth2 config, etc.) is internal/admin-only and has no public docs page -- same situation here, so no markdown file should be referenced. This also fixes the CI spec-generation failure, which was failing because that file never existed. - MFAChallengeSecret now extends MFAChallenge and only adds the `secret` rule, instead of duplicating all four base fields. Mirrors the EphemeralKey/Key relationship already in this codebase. - Extend testMFACustomChallenge per review: assert a client session (no API key) gets 401 from the server endpoint, assert an incorrect otp is rejected before the real one is used, and assert the verify response's `secret` field comes back empty for a non-privileged caller (Session already marks it `sensitive`; this proves it). Verified the label() set on Get.php against RecoveryCodes/Get.php -- no audits.* labels needed since those only apply to users.write (mutating) endpoints, and this one is users.read. --- .../Users/Http/Users/MFA/Challenges/Get.php | 13 ++------- .../Response/Model/MFAChallengeSecret.php | 29 ++----------------- .../Account/AccountCustomClientTest.php | 22 ++++++++++++++ 3 files changed, 28 insertions(+), 36 deletions(-) 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 index 97ca994dac..a6b16fa59d 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php @@ -10,7 +10,6 @@ use Appwrite\SDK\Method; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; use Utopia\Database\Database; -use Utopia\Database\Document; use Utopia\Database\Validator\UID; use Utopia\Platform\Scope\HTTP; use Utopia\Validator\Text; @@ -38,7 +37,7 @@ class Get extends Action namespace: 'users', group: 'mfa', name: 'getMFAChallenge', - description: '/docs/references/users/get-mfa-challenge.md', + description: 'Get a custom MFA challenge for a user, including the secret to be delivered through your own channel.', auth: [AuthType::ADMIN, AuthType::KEY], responses: [ new SDKResponse( @@ -73,14 +72,8 @@ class Get extends Action 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'), - ]); + $challenge->setAttribute('secret', $challenge->getAttribute('code')); - $response->dynamic($document, Response::MODEL_MFA_CHALLENGE_SECRET); + $response->dynamic($challenge, Response::MODEL_MFA_CHALLENGE_SECRET); } } diff --git a/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php b/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php index ecdba9291d..952c2ff9f3 100644 --- a/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php +++ b/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php @@ -3,37 +3,14 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model; -class MFAChallengeSecret extends Model +class MFAChallengeSecret extends MFAChallenge { public function __construct() { + parent::__construct(); + $this - ->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.', diff --git a/tests/e2e/Services/Account/AccountCustomClientTest.php b/tests/e2e/Services/Account/AccountCustomClientTest.php index 7a51beadf8..df2f7c3871 100644 --- a/tests/e2e/Services/Account/AccountCustomClientTest.php +++ b/tests/e2e/Services/Account/AccountCustomClientTest.php @@ -4289,6 +4289,14 @@ final class AccountCustomClientTest extends Scope $challengeId = $challenge['body']['$id']; $userId = $challenge['body']['userId']; + // Test FAILURE: a client session (no API key) must not be able to read the secret + $clientSecretResponse = $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, $clientSecretResponse['headers']['status-code']); + // 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', @@ -4300,6 +4308,17 @@ final class AccountCustomClientTest extends Scope $this->assertNotEmpty($secretResponse['body']['secret']); $secret = $secretResponse['body']['secret']; + // 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 secret $verification = $this->client->call(Client::METHOD_PUT, '/account/mfa/challenge', array_merge([ 'content-type' => 'application/json', @@ -4312,6 +4331,9 @@ final class AccountCustomClientTest extends Scope $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([ From 69c01a4b9d00835d8dad0dd3582cc2f07f6ef975 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Sat, 8 Aug 2026 20:32:11 +0200 Subject: [PATCH 4/4] fix(mfa): expose challenge code directly in response model instead of aliasing to secret Co-Authored-By: Claude Fable 5 --- .../Users/Http/Users/MFA/Challenges/Get.php | 4 +--- .../Response/Model/MFAChallengeSecret.php | 4 ++-- .../Account/AccountCustomClientTest.php | 24 ++++++++++--------- tests/e2e/Services/Users/UsersBase.php | 9 +++---- 4 files changed, 21 insertions(+), 20 deletions(-) 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 index a6b16fa59d..e1d40b548e 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/MFA/Challenges/Get.php @@ -37,7 +37,7 @@ class Get extends Action namespace: 'users', group: 'mfa', name: 'getMFAChallenge', - description: 'Get a custom MFA challenge for a user, including the secret to be delivered through your own channel.', + 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( @@ -72,8 +72,6 @@ class Get extends Action throw new Exception(Exception::USER_INVALID_TOKEN); } - $challenge->setAttribute('secret', $challenge->getAttribute('code')); - $response->dynamic($challenge, Response::MODEL_MFA_CHALLENGE_SECRET); } } diff --git a/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php b/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php index 952c2ff9f3..1f56027e19 100644 --- a/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php +++ b/src/Appwrite/Utopia/Response/Model/MFAChallengeSecret.php @@ -11,9 +11,9 @@ class MFAChallengeSecret extends MFAChallenge parent::__construct(); $this - ->addRule('secret', [ + ->addRule('code', [ 'type' => self::TYPE_STRING, - 'description' => 'Challenge secret to be delivered to the end user through a custom channel.', + 'description' => 'Challenge code to be delivered to the end user through a custom channel.', 'default' => '', 'example' => '446372', ]); diff --git a/tests/e2e/Services/Account/AccountCustomClientTest.php b/tests/e2e/Services/Account/AccountCustomClientTest.php index df2f7c3871..1dfcd1f965 100644 --- a/tests/e2e/Services/Account/AccountCustomClientTest.php +++ b/tests/e2e/Services/Account/AccountCustomClientTest.php @@ -4286,27 +4286,29 @@ final class AccountCustomClientTest extends Scope $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 secret - $clientSecretResponse = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/' . $challengeId, array_merge([ + // 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, $clientSecretResponse['headers']['status-code']); + $this->assertEquals(401, $clientCodeResponse['headers']['status-code']); - // Server SDK reads the raw secret via the server-only endpoint - $secretResponse = $this->client->call(Client::METHOD_GET, '/users/' . $userId . '/mfa/challenges/' . $challengeId, [ + // 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, $secretResponse['headers']['status-code']); - $this->assertNotEmpty($secretResponse['body']['secret']); - $secret = $secretResponse['body']['secret']; + $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([ @@ -4319,13 +4321,13 @@ final class AccountCustomClientTest extends Scope $this->assertEquals(401, $wrongFirst['headers']['status-code']); - // Test SUCCESS: Verify with the correct secret + // 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' => $secret + 'otp' => $code ]); $this->assertEquals(200, $verification['headers']['status-code']); @@ -4341,7 +4343,7 @@ final class AccountCustomClientTest extends Scope 'x-appwrite-project' => $projectId, ], $this->getHeaders()), [ 'challengeId' => $challengeId, - 'otp' => $secret + 'otp' => $code ]); $this->assertEquals(401, $reuse['headers']['status-code']); diff --git a/tests/e2e/Services/Users/UsersBase.php b/tests/e2e/Services/Users/UsersBase.php index 1be5c70edb..d63d4fda9d 100644 --- a/tests/e2e/Services/Users/UsersBase.php +++ b/tests/e2e/Services/Users/UsersBase.php @@ -663,10 +663,11 @@ trait UsersBase ]); $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 secret + * 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', @@ -676,7 +677,7 @@ trait UsersBase $this->assertEquals(200, $response['headers']['status-code']); $this->assertEquals($challengeId, $response['body']['$id']); $this->assertEquals($userId, $response['body']['userId']); - $this->assertNotEmpty($response['body']['secret']); + $this->assertNotEmpty($response['body']['code']); /** * Test for FAILURE: a client session (not a server key) must be rejected @@ -735,8 +736,8 @@ trait UsersBase /** * 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 secret out of band (email/SMS); this endpoint only exists to hand the - * 'custom' factor's secret to the developer's own delivery mechanism. + * 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',