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.
This commit is contained in:
harsh-sikarwar committed 2026-08-08 17:51:40 +05:30
1 parent 9dc8897499
commit 477653c848
11 files changed
+365 -1

No files matched your search

+2
View File
@@ -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;
}
}
+1
View File
@@ -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,81 @@
<?php
namespace Appwrite\Platform\Modules\Users\Http\Users\MFA\Challenges;
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\Document;
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: '/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);
}
}
@@ -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());
+1
View File
@@ -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,60 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model;
class MFAChallengeSecret extends Model
{
public function __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.',
'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,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();
+104
View File
@@ -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..)