Merge branch '1.9.x' into feat/impersonation-location-url-params-v2

This commit is contained in:
Harsh Mahajan authored and GitHub committed 2026-06-07 13:00:17 +05:30
commit 1573cc0aeb
22 files changed
+899 -2945

No files matched your search

+1
View File
@@ -39,6 +39,7 @@ $console = [
'membershipsMfa' => true,
'membershipsUserId' => true,
'membershipsUserPhone' => true,
'membershipsUserAccessedAt' => true,
'mockNumbers' => [],
'invites' => System::getEnv('_APP_CONSOLE_INVITES', 'enabled') === 'enabled',
'limit' => (System::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled') === 'enabled') ? 1 : 0, // limit signup to 1 user
+5 -11
View File
@@ -222,12 +222,6 @@ $register->set('pools', function () {
'multiple' => false,
'schemes' => ['redis'],
],
'consumer' => [
'type' => 'consumer',
'dsns' => $fallbackForRedis,
'multiple' => false,
'schemes' => ['redis'],
],
'pubsub' => [
'type' => 'pubsub',
'dsns' => $fallbackForRedis,
@@ -344,11 +338,8 @@ $register->set('pools', function () {
// PubSub workers hold one long-lived subscribed connection and also need
// spare capacity for publishes from the same process.
// Consumer pools lease one connection per consume coroutine for the
// lifetime of the worker, plus headroom for queue-size reads.
$connectionPoolSize = match ($type) {
'pubsub' => max(2, $poolSize),
'consumer' => $poolSize + 2,
default => $poolSize,
};
@@ -372,9 +363,12 @@ $register->set('pools', function () {
default => null
};
case 'publisher':
case 'consumer':
// Publishers never block on receive, so one connection backs both broker slots.
return match ($dsn->getScheme()) {
'redis' => new Queue\Broker\Redis(new Queue\Connection\Redis($dsn->getHost(), $dsn->getPort())),
'redis' => (function () use ($dsn) {
$connection = new Queue\Connection\Redis($dsn->getHost(), $dsn->getPort());
return new Queue\Broker\Redis($connection, $connection);
})(),
default => null
};
case 'cache':
+10 -26
View File
@@ -12,9 +12,10 @@ use Utopia\Database\Validator\Authorization;
use Utopia\Logger\Log;
use Utopia\Logger\Logger;
use Utopia\Platform\Service;
use Utopia\Pools\Group;
use Utopia\Queue\Adapter\Swoole;
use Utopia\Queue\Broker\Pool as BrokerPool;
use Utopia\Queue\Broker\Redis as BrokerRedis;
use Utopia\Queue\Connection\Locking;
use Utopia\Queue\Connection\Redis as RedisConnection;
use Utopia\Queue\Server;
use Utopia\Span\Span;
use Utopia\System\System;
@@ -38,22 +39,6 @@ $container->set('project', fn () => new Document([]), []);
$container->set('log', fn () => new Log(), []);
$container->set('consumer', function (Group $pools) {
return new BrokerPool(consumer: $pools->get('consumer'));
}, ['pools']);
$container->set('consumerDatabases', function (BrokerPool $consumer) {
return $consumer;
}, ['consumer']);
$container->set('consumerMigrations', function (BrokerPool $consumer) {
return $consumer;
}, ['consumer']);
$container->set('consumerStatsUsage', function (BrokerPool $consumer) {
return $consumer;
}, ['consumer']);
$container->set('certificates', function () {
$email = System::getEnv('_APP_EMAIL_CERTIFICATES', System::getEnv('_APP_SYSTEM_SECURITY_EMAIL_ADDRESS'));
if (empty($email)) {
@@ -80,16 +65,15 @@ if (\str_starts_with($workerName, 'databases')) {
$queueName = System::getEnv('_APP_QUEUE_NAME', 'v1-' . strtolower($workerName));
}
/** @var \Utopia\Pools\Group $pools */
$pools = $container->get('pools');
$redisHost = System::getEnv('_APP_REDIS_HOST', 'redis');
$redisPort = (int) System::getEnv('_APP_REDIS_PORT', 6379);
// Each consume coroutine leases its own broker connection from the pool for
// the lifetime of its consume loop, so concurrent coroutines never share a
// connection. The publisher side backs the queue-depth telemetry gauge.
// A dedicated connection drives the blocking receive loop; a lock-guarded one
// serializes acks/publishes from the per-message coroutines.
$adapter = new Swoole(
new BrokerPool(
publisher: $pools->get('consumer'),
consumer: $pools->get('consumer'),
new BrokerRedis(
receive: new RedisConnection($redisHost, $redisPort),
commands: new Locking(new RedisConnection($redisHost, $redisPort)),
),
System::getEnv('_APP_WORKERS_NUM', 1),
$queueName,
+2 -2
View File
@@ -78,11 +78,11 @@
"utopia-php/logger": "0.8.*",
"utopia-php/messaging": "1.0.*",
"utopia-php/migration": "1.*",
"utopia-php/platform": "1.0.0-rc4",
"utopia-php/platform": "1.0.0-rc5",
"utopia-php/pools": "1.*",
"utopia-php/span": "1.1.*",
"utopia-php/preloader": "0.2.*",
"utopia-php/queue": "0.19.*",
"utopia-php/queue": "0.20.*",
"utopia-php/servers": "0.4.*",
"utopia-php/registry": "0.5.*",
"utopia-php/storage": "2.*",
Generated
+15 -257
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "5cc3d8a63a229bf9363c4baa8d985f7c",
"content-hash": "182aa10ce3b77b8cf38eefc25944e939",
"packages": [
{
"name": "adhocore/jwt",
@@ -1703,137 +1703,6 @@
},
"time": "2025-09-24T15:06:41+00:00"
},
{
"name": "paragonie/random_compat",
"version": "v9.99.100",
"source": {
"type": "git",
"url": "https://github.com/paragonie/random_compat.git",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a",
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a",
"shasum": ""
},
"require": {
"php": ">= 7"
},
"require-dev": {
"phpunit/phpunit": "4.*|5.*",
"vimeo/psalm": "^1"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
},
"type": "library",
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https://paragonie.com"
}
],
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"polyfill",
"pseudorandom",
"random"
],
"support": {
"email": "info@paragonie.com",
"issues": "https://github.com/paragonie/random_compat/issues",
"source": "https://github.com/paragonie/random_compat"
},
"time": "2020-10-15T08:29:30+00:00"
},
{
"name": "php-amqplib/php-amqplib",
"version": "v3.7.4",
"source": {
"type": "git",
"url": "https://github.com/php-amqplib/php-amqplib.git",
"reference": "381b6f7c600e0e0c7463cdd7f7a1a3bc6268e5fd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-amqplib/php-amqplib/zipball/381b6f7c600e0e0c7463cdd7f7a1a3bc6268e5fd",
"reference": "381b6f7c600e0e0c7463cdd7f7a1a3bc6268e5fd",
"shasum": ""
},
"require": {
"ext-mbstring": "*",
"ext-sockets": "*",
"php": "^7.2||^8.0",
"phpseclib/phpseclib": "^2.0|^3.0"
},
"conflict": {
"php": "7.4.0 - 7.4.1"
},
"replace": {
"videlalvaro/php-amqplib": "self.version"
},
"require-dev": {
"ext-curl": "*",
"nategood/httpful": "^0.2.20",
"phpunit/phpunit": "^7.5|^9.5",
"squizlabs/php_codesniffer": "^3.6"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"psr-4": {
"PhpAmqpLib\\": "PhpAmqpLib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"LGPL-2.1-or-later"
],
"authors": [
{
"name": "Alvaro Videla",
"role": "Original Maintainer"
},
{
"name": "Raúl Araya",
"email": "nubeiro@gmail.com",
"role": "Maintainer"
},
{
"name": "Luke Bakken",
"email": "luke@bakken.io",
"role": "Maintainer"
},
{
"name": "Ramūnas Dronga",
"email": "github@ramuno.lt",
"role": "Maintainer"
}
],
"description": "Formerly videlalvaro/php-amqplib. This library is a pure PHP implementation of the AMQP protocol. It's been tested against RabbitMQ.",
"homepage": "https://github.com/php-amqplib/php-amqplib/",
"keywords": [
"message",
"queue",
"rabbitmq"
],
"support": {
"issues": "https://github.com/php-amqplib/php-amqplib/issues",
"source": "https://github.com/php-amqplib/php-amqplib/tree/v3.7.4"
},
"time": "2025-11-23T17:00:56+00:00"
},
{
"name": "php-http/discovery",
"version": "1.20.0",
@@ -1994,116 +1863,6 @@
],
"time": "2023-11-25T22:23:28+00:00"
},
{
"name": "phpseclib/phpseclib",
"version": "3.0.52",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "2adaefc83df2ec548558307690f376dd7d4f4fce"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/2adaefc83df2ec548558307690f376dd7d4f4fce",
"reference": "2adaefc83df2ec548558307690f376dd7d4f4fce",
"shasum": ""
},
"require": {
"paragonie/constant_time_encoding": "^1|^2|^3",
"paragonie/random_compat": "^1.4|^2.0|^9.99.99",
"php": ">=5.6.1"
},
"require-dev": {
"phpunit/phpunit": "*"
},
"suggest": {
"ext-dom": "Install the DOM extension to load XML formatted public keys.",
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations."
},
"type": "library",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib3\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/3.0.52"
},
"funding": [
{
"url": "https://github.com/terrafrost",
"type": "github"
},
{
"url": "https://www.patreon.com/phpseclib",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib",
"type": "tidelift"
}
],
"time": "2026-04-27T07:02:15+00:00"
},
{
"name": "psr/clock",
"version": "1.0.0",
@@ -4774,16 +4533,16 @@
},
{
"name": "utopia-php/platform",
"version": "1.0.0-rc4",
"version": "1.0.0-rc5",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/platform.git",
"reference": "455c84f8d1cdaec6fc2c39587a78aa5ef263ddd0"
"reference": "edf46c6e9c62af1cec1cbd1386a84c730d76a9f8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/platform/zipball/455c84f8d1cdaec6fc2c39587a78aa5ef263ddd0",
"reference": "455c84f8d1cdaec6fc2c39587a78aa5ef263ddd0",
"url": "https://api.github.com/repos/utopia-php/platform/zipball/edf46c6e9c62af1cec1cbd1386a84c730d76a9f8",
"reference": "edf46c6e9c62af1cec1cbd1386a84c730d76a9f8",
"shasum": ""
},
"require": {
@@ -4792,7 +4551,7 @@
"php": ">=8.3",
"utopia-php/cli": "0.23.*",
"utopia-php/http": "^2.0@RC",
"utopia-php/queue": "^0.19",
"utopia-php/queue": "^0.20",
"utopia-php/servers": "0.4.*"
},
"require-dev": {
@@ -4819,9 +4578,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/platform/issues",
"source": "https://github.com/utopia-php/platform/tree/1.0.0-rc4"
"source": "https://github.com/utopia-php/platform/tree/1.0.0-rc5"
},
"time": "2026-06-02T20:19:26+00:00"
"time": "2026-06-04T13:00:46+00:00"
},
{
"name": "utopia-php/pools",
@@ -4977,21 +4736,20 @@
},
{
"name": "utopia-php/queue",
"version": "0.19.0",
"version": "0.20.0",
"source": {
"type": "git",
"url": "https://github.com/utopia-php/queue.git",
"reference": "cd4248af69006b2568c3486a675f27cb21191859"
"reference": "d4da9e8d4a8879eb529ec1cda6b93cad2cf8d940"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/utopia-php/queue/zipball/cd4248af69006b2568c3486a675f27cb21191859",
"reference": "cd4248af69006b2568c3486a675f27cb21191859",
"url": "https://api.github.com/repos/utopia-php/queue/zipball/d4da9e8d4a8879eb529ec1cda6b93cad2cf8d940",
"reference": "d4da9e8d4a8879eb529ec1cda6b93cad2cf8d940",
"shasum": ""
},
"require": {
"php": ">=8.3",
"php-amqplib/php-amqplib": "^3.7",
"php": ">=8.4",
"utopia-php/di": "0.3.*",
"utopia-php/lock": "0.2.*",
"utopia-php/pools": "1.*",
@@ -5038,9 +4796,9 @@
],
"support": {
"issues": "https://github.com/utopia-php/queue/issues",
"source": "https://github.com/utopia-php/queue/tree/0.19.0"
"source": "https://github.com/utopia-php/queue/tree/0.20.0"
},
"time": "2026-06-02T20:12:18+00:00"
"time": "2026-06-04T12:33:31+00:00"
},
{
"name": "utopia-php/registry",
@@ -809,6 +809,10 @@ class Builds extends Action
$streamLog = \str_replace('{APPWRITE_LINEBREAK_PLACEHOLDER}', "\n", $streamLog);
$streamParts = \explode(' ', $streamLog, 2);
if (! isset($streamParts[1])) {
continue;
}
// TODO: use part[0] as timestamp when switching to dbForLogs for build logs
$currentLogs .= $streamParts[1];
@@ -172,6 +172,7 @@ class Get extends Action
'userPhone' => $auths['membershipsUserPhone'] ?? false,
'userName' => $auths['membershipsUserName'] ?? false,
'userMFA' => $auths['membershipsMfa'] ?? false,
'userAccessedAt' => $auths['membershipsUserAccessedAt'] ?? false,
]),
Response::MODEL_POLICY_MEMBERSHIP_PRIVACY,
],
@@ -55,6 +55,7 @@ class Update extends Action
->param('userPhone', null, new Boolean(), 'Set to true if you want make user phone number visible to all team members, or false to hide it.', optional: true)
->param('userName', null, new Boolean(), 'Set to true if you want make user name visible to all team members, or false to hide it.', optional: true)
->param('userMFA', null, new Boolean(), 'Set to true if you want make user MFA status visible to all team members, or false to hide it.', optional: true)
->param('userAccessedAt', null, new Boolean(), 'Set to true if you want make user last access time visible to all team members, or false to hide it.', optional: true)
->inject('response')
->inject('dbForPlatform')
->inject('project')
@@ -69,6 +70,7 @@ class Update extends Action
?bool $userPhone,
?bool $userName,
?bool $userMFA,
?bool $userAccessedAt,
Response $response,
Database $dbForPlatform,
Document $project,
@@ -92,6 +94,9 @@ class Update extends Action
if ($userMFA !== null) {
$auths['membershipsMfa'] = $userMFA;
}
if ($userAccessedAt !== null) {
$auths['membershipsUserAccessedAt'] = $userAccessedAt;
}
$updates = new Document([
'auths' => $auths,
@@ -81,6 +81,7 @@ class Get extends Action
'mfa' => $project->getAttribute('auths', [])['membershipsMfa'] ?? true,
'userId' => $project->getAttribute('auths', [])['membershipsUserId'] ?? true,
'userPhone' => $project->getAttribute('auths', [])['membershipsUserPhone'] ?? true,
'userAccessedAt' => $project->getAttribute('auths', [])['membershipsUserAccessedAt'] ?? false,
];
$roles = $authorization->getRoles();
@@ -130,6 +131,10 @@ class Get extends Action
$membership->setAttribute('userPhone', $memberUser->getAttribute('phone'));
}
if ($membershipsPrivacy['userAccessedAt']) {
$membership->setAttribute('userAccessedAt', $memberUser->getAttribute('accessedAt'));
}
$membership->setAttribute('teamName', $team->getAttribute('name'));
$response->dynamic($membership, Response::MODEL_MEMBERSHIP);
@@ -130,6 +130,7 @@ class XList extends Action
'mfa' => $project->getAttribute('auths', [])['membershipsMfa'] ?? true,
'userId' => $project->getAttribute('auths', [])['membershipsUserId'] ?? true,
'userPhone' => $project->getAttribute('auths', [])['membershipsUserPhone'] ?? true,
'userAccessedAt' => $project->getAttribute('auths', [])['membershipsUserAccessedAt'] ?? false,
];
$roles = $authorization->getRoles();
@@ -180,6 +181,10 @@ class XList extends Action
$membership->setAttribute('userPhone', $memberUser->getAttribute('phone'));
}
if ($membershipsPrivacy['userAccessedAt']) {
$membership->setAttribute('userAccessedAt', $memberUser->getAttribute('accessedAt'));
}
$membership->setAttribute('teamName', $team->getAttribute('name'));
return $membership;
+2 -6
View File
@@ -10,8 +10,6 @@ use Utopia\Database\Document;
use Utopia\Database\Exception\Structure;
use Utopia\Platform\Action;
use Utopia\Queue\Message;
use Utopia\Queue\Result\Commit;
use Utopia\Queue\Result\NoCommit;
use Utopia\System\System;
class Audits extends Action
@@ -51,12 +49,11 @@ class Audits extends Action
/**
* @param Message $message
* @param callable(Document): \Utopia\Audit\Audit $getAudit
* @return Commit|NoCommit
* @throws Throwable
* @throws \Utopia\Database\Exception
* @throws Structure
*/
public function action(Message $message, callable $getAudit): Commit|NoCommit
public function action(Message $message, callable $getAudit): void
{
$payload = $message->getPayload();
@@ -148,7 +145,7 @@ class Audits extends Action
}
if (!$shouldProcessBatch) {
return new NoCommit();
return;
}
foreach ($this->logs as $sequence => $projectLogs) {
@@ -168,6 +165,5 @@ class Audits extends Action
}
$this->lastTriggeredTime = time();
return new Commit();
}
}
@@ -58,6 +58,7 @@ class V26 extends Filter
$content['authMembershipsMfa'] = $auths->getAttribute('membershipsMfa', false);
$content['authMembershipsUserId'] = $auths->getAttribute('membershipsUserId', false);
$content['authMembershipsUserPhone'] = $auths->getAttribute('membershipsUserPhone', false);
$content['authMembershipsUserAccessedAt'] = $auths->getAttribute('membershipsUserAccessedAt', false);
$content['authInvalidateSessions'] = $auths->getAttribute('invalidateSessions', false);
$content['description'] = $raw->getAttribute('description', '');
@@ -78,6 +78,41 @@ class Account extends Model
'default' => false,
'example' => true,
])
->addRule('emailCanonical', [
'type' => self::TYPE_STRING,
'description' => 'Canonical form of the user email address.',
'required' => false,
'default' => '',
'example' => 'john@appwrite.io',
])
->addRule('emailIsFree', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is from a free email provider.',
'required' => false,
'default' => null,
'example' => true,
])
->addRule('emailIsDisposable', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is from a disposable email provider.',
'required' => false,
'default' => null,
'example' => false,
])
->addRule('emailIsCorporate', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is from a corporate domain.',
'required' => false,
'default' => null,
'example' => true,
])
->addRule('emailIsCanonical', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is in its canonical form.',
'required' => false,
'default' => null,
'example' => true,
])
->addRule('phoneVerification', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Phone verification status.',
@@ -88,6 +88,12 @@ class Membership extends Model
'default' => false,
'example' => false,
])
->addRule('userAccessedAt', [
'type' => self::TYPE_DATETIME,
'description' => 'Most recent access date in ISO 8601 format. Show this attribute by toggling membership privacy in the Console.',
'default' => '',
'example' => self::TYPE_DATETIME_EXAMPLE,
])
->addRule('roles', [
'type' => self::TYPE_STRING,
'description' => 'User list of roles',
@@ -44,6 +44,12 @@ class PolicyMembershipPrivacy extends PolicyBase
'description' => 'Whether user MFA status is visible in memberships.',
'default' => false,
'example' => true,
])
->addRule('userAccessedAt', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether user last access time is visible in memberships.',
'default' => false,
'example' => true,
]);
}
@@ -108,6 +108,41 @@ class User extends Model
'default' => false,
'example' => true,
])
->addRule('emailCanonical', [
'type' => self::TYPE_STRING,
'description' => 'Canonical form of the user email address.',
'required' => false,
'default' => '',
'example' => 'john@appwrite.io',
])
->addRule('emailIsFree', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is from a free email provider.',
'required' => false,
'default' => null,
'example' => true,
])
->addRule('emailIsDisposable', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is from a disposable email provider.',
'required' => false,
'default' => null,
'example' => false,
])
->addRule('emailIsCorporate', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is from a corporate domain.',
'required' => false,
'default' => null,
'example' => true,
])
->addRule('emailIsCanonical', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether the user email is in its canonical form.',
'required' => false,
'default' => null,
'example' => true,
])
->addRule('phoneVerification', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Phone verification status.',
+5 -5
View File
@@ -43,11 +43,11 @@ trait AccountBase
$this->assertNotEmpty($response['body']['accessedAt']);
$this->assertArrayHasKey('targets', $response['body']);
$this->assertEquals($email, $response['body']['targets'][0]['identifier']);
$this->assertArrayNotHasKey('emailCanonical', $response['body']);
$this->assertArrayNotHasKey('emailIsFree', $response['body']);
$this->assertArrayNotHasKey('emailIsDisposable', $response['body']);
$this->assertArrayNotHasKey('emailIsCorporate', $response['body']);
$this->assertArrayNotHasKey('emailIsCanonical', $response['body']);
$this->assertEquals($email, $response['body']['emailCanonical']);
$this->assertIsBool($response['body']['emailIsFree']);
$this->assertIsBool($response['body']['emailIsDisposable']);
$this->assertIsBool($response['body']['emailIsCorporate']);
$this->assertIsBool($response['body']['emailIsCanonical']);
/**
* Test for FAILURE
File diff suppressed because it is too large. Load diff
@@ -34,6 +34,7 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
'userPhone' => false,
'userName' => false,
'userMFA' => false,
'userAccessedAt' => false,
]);
$this->assertSame(200, $response['headers']['status-code']);
@@ -42,6 +43,7 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
$this->assertFalse($response['body']['authMembershipsUserPhone']);
$this->assertFalse($response['body']['authMembershipsUserName']);
$this->assertFalse($response['body']['authMembershipsMfa']);
$this->assertFalse($response['body']['authMembershipsUserAccessedAt']);
// Step 2: Setup two users
$user1Email = 'user1_' . uniqid() . '@localhost.test';
@@ -123,6 +125,28 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
'cookie' => 'a_session_' . $projectId . '=' . $user1Session,
];
// Also sign in as user2 and make a request so accessedAt is populated before privacy is enabled
$session2 = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $projectId,
], [
'email' => $user2Email,
'password' => $password,
]);
$this->assertSame(201, $session2['headers']['status-code']);
$user2Session = $session2['cookies']['a_session_' . $projectId];
$client2Headers = [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $projectId,
'cookie' => 'a_session_' . $projectId . '=' . $user2Session,
];
// Make a request as user2 to ensure accessedAt is updated
$this->client->call(Client::METHOD_GET, '/account', $client2Headers);
$response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamId . '/memberships', $clientHeaders);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertSame(2, $response['body']['total']);
@@ -134,6 +158,7 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
$this->assertSame('', $membership['userPhone']);
$this->assertSame('', $membership['userId']);
$this->assertFalse($membership['mfa']);
$this->assertSame('', $membership['userAccessedAt']);
}
// Step 5: Update privacy to true
@@ -143,6 +168,7 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
'userPhone' => true,
'userName' => true,
'userMFA' => true,
'userAccessedAt' => true,
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertTrue($response['body']['authMembershipsUserId']);
@@ -150,6 +176,7 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
$this->assertTrue($response['body']['authMembershipsUserPhone']);
$this->assertTrue($response['body']['authMembershipsUserName']);
$this->assertTrue($response['body']['authMembershipsMfa']);
$this->assertTrue($response['body']['authMembershipsUserAccessedAt']);
// Step 6: List memberships with privacy enabled - user details exposed
$response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamId . '/memberships', $clientHeaders);
@@ -168,6 +195,7 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
$this->assertSame($user1Email, $membershipsByUser[$user1Id]['userEmail']);
$this->assertSame($user1Phone, $membershipsByUser[$user1Id]['userPhone']);
$this->assertFalse($membershipsByUser[$user1Id]['mfa']);
$this->assertNotEmpty($membershipsByUser[$user1Id]['userAccessedAt']);
$this->assertArrayHasKey($user2Id, $membershipsByUser);
$this->assertSame($user2Id, $membershipsByUser[$user2Id]['userId']);
@@ -175,5 +203,6 @@ final class PoliciesMembershipPrivacyIntegrationTest extends Scope
$this->assertSame($user2Email, $membershipsByUser[$user2Id]['userEmail']);
$this->assertSame($user2Phone, $membershipsByUser[$user2Id]['userPhone']);
$this->assertFalse($membershipsByUser[$user2Id]['mfa']);
$this->assertNotEmpty($membershipsByUser[$user2Id]['userAccessedAt']);
}
}
+14 -1
View File
@@ -1016,7 +1016,20 @@ trait StorageBase
$this->assertEquals(200, $cachedPreview['headers']['status-code']);
$this->assertEquals('image/png', $cachedPreview['headers']['content-type']);
$this->assertStringStartsWith('private, max-age=', $cachedPreview['headers']['cache-control']);
$this->assertEquals($preview['body'], $cachedPreview['body']);
$this->assertNotEmpty($cachedPreview['body']);
$cachedPreviewAgain = $this->client->call(
Client::METHOD_GET,
'/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview',
$headers,
$params
);
$this->assertEquals(200, $cachedPreviewAgain['headers']['status-code']);
$this->assertEquals('image/png', $cachedPreviewAgain['headers']['content-type']);
$this->assertStringStartsWith('private, max-age=', $cachedPreviewAgain['headers']['cache-control']);
$this->assertEquals('hit', $cachedPreviewAgain['headers']['x-appwrite-cache']);
$this->assertEquals($cachedPreview['body'], $cachedPreviewAgain['body']);
}
public function testFilePreviewZstdCompression(): void
+15
View File
@@ -337,6 +337,11 @@ trait UsersBase
$this->assertEquals($body['status'], true);
$this->assertGreaterThan('2000-01-01 00:00:00', $body['registration']);
$this->assertEquals($body['labels'], []);
$this->assertEquals('cristiano.ronaldo@manchester-united.co.uk', $body['emailCanonical']);
$this->assertEquals(false, $body['emailIsFree']);
$this->assertEquals(false, $body['emailIsDisposable']);
$this->assertEquals(true, $body['emailIsCorporate']);
$this->assertEquals(true, $body['emailIsCanonical']);
/**
* Test Create with Custom ID for SUCCESS
@@ -751,6 +756,11 @@ trait UsersBase
}
}
$this->assertNotNull($user1, 'user1 should exist in user list');
$this->assertArrayHasKey('emailCanonical', $user1);
$this->assertArrayHasKey('emailIsFree', $user1);
$this->assertArrayHasKey('emailIsDisposable', $user1);
$this->assertArrayHasKey('emailIsCorporate', $user1);
$this->assertArrayHasKey('emailIsCanonical', $user1);
// This test ensures that by default, endpoints dont support select queries
// If we add select query to this endpoint, you will need to remove this test
@@ -1092,6 +1102,11 @@ trait UsersBase
$this->assertNotEmpty($user['body']['email']);
$this->assertEquals($user['body']['status'], true);
$this->assertGreaterThan('2000-01-01 00:00:00', $user['body']['registration']);
$this->assertArrayHasKey('emailCanonical', $user['body']);
$this->assertArrayHasKey('emailIsFree', $user['body']);
$this->assertArrayHasKey('emailIsDisposable', $user['body']);
$this->assertArrayHasKey('emailIsCorporate', $user['body']);
$this->assertArrayHasKey('emailIsCanonical', $user['body']);
$sessions = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/sessions', array_merge([
'content-type' => 'application/json',
@@ -0,0 +1,593 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Platform\Modules\Project\OAuth2;
use Appwrite\Event\Event as QueueEvent;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Apple\Update as AppleUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Auth0\Update as Auth0Update;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Authentik\Update as AuthentikUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Base;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Dropbox\Update as DropboxUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\FusionAuth\Update as FusionAuthUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Gitlab\Update as GitlabUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Google\Update as GoogleUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Keycloak\Update as KeycloakUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Microsoft\Update as MicrosoftUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Oidc\Update as OidcUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\Okta\Update as OktaUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\PaypalSandbox\Update as PaypalSandboxUpdate;
use Appwrite\Platform\Modules\Project\Http\Project\OAuth2\TradeshiftSandbox\Update as TradeshiftSandboxUpdate;
use Appwrite\Utopia\Response;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
final class OAuth2ProviderTest extends TestCase
{
public function testProviderRegistryIsExplicitAndComplete(): void
{
$actions = Base::getProviderActions();
$ids = \array_keys($actions);
\sort($ids);
$expected = [
'amazon', 'apple', 'auth0', 'authentik', 'autodesk', 'bitbucket',
'bitly', 'box', 'dailymotion', 'discord', 'disqus', 'dropbox',
'etsy', 'facebook', 'figma', 'fusionauth', 'github', 'gitlab',
'google', 'keycloak', 'kick', 'linkedin', 'microsoft', 'notion',
'oidc', 'okta', 'paypal', 'paypalSandbox', 'podio', 'salesforce',
'slack', 'spotify', 'stripe', 'tradeshift', 'tradeshiftBox',
'twitch', 'wordpress', 'x', 'yahoo', 'yandex', 'zoho', 'zoom',
];
\sort($expected);
$this->assertSame($expected, $ids);
$this->assertArrayNotHasKey('mock', $actions);
$this->assertArrayNotHasKey('mock-unverified', $actions);
$this->assertSame(PaypalSandboxUpdate::class, $actions['paypalSandbox']);
$this->assertSame(TradeshiftSandboxUpdate::class, $actions['tradeshiftBox']);
foreach ($actions as $providerId => $actionClass) {
$this->assertSame($providerId, $actionClass::getProviderId());
}
}
/**
* @param class-string<Base> $actionClass
* @param array<int, string> $expectedIds
*/
#[DataProvider('providerParameters')]
public function testProviderParameterMetadata(string $actionClass, array $expectedIds): void
{
$parameters = $actionClass::getParameters();
$ids = \array_column($parameters, '$id');
$this->assertSame($expectedIds, $ids);
foreach ($parameters as $parameter) {
$this->assertArrayHasKey('$id', $parameter);
$this->assertArrayHasKey('name', $parameter);
$this->assertArrayHasKey('example', $parameter);
$this->assertArrayHasKey('hint', $parameter);
$this->assertNotSame('', $parameter['$id']);
$this->assertNotSame('', $parameter['name']);
}
}
public static function providerParameters(): \Iterator
{
yield 'default provider' => [Base::getProviderActions()['amazon'], ['clientId', 'clientSecret']];
yield 'custom id and secret names' => [DropboxUpdate::class, ['appKey', 'appSecret']];
yield 'apple' => [AppleUpdate::class, ['serviceId', 'keyId', 'teamId', 'p8File']];
yield 'auth0' => [Auth0Update::class, ['clientId', 'clientSecret', 'endpoint']];
yield 'authentik' => [AuthentikUpdate::class, ['clientId', 'clientSecret', 'endpoint']];
yield 'fusionauth' => [FusionAuthUpdate::class, ['clientId', 'clientSecret', 'endpoint']];
yield 'gitlab' => [GitlabUpdate::class, ['applicationId', 'secret', 'endpoint']];
yield 'google' => [GoogleUpdate::class, ['clientId', 'clientSecret', 'prompt']];
yield 'keycloak' => [KeycloakUpdate::class, ['clientId', 'clientSecret', 'endpoint', 'realmName']];
yield 'microsoft' => [MicrosoftUpdate::class, ['applicationId', 'applicationSecret', 'tenant']];
yield 'oidc' => [OidcUpdate::class, ['clientId', 'clientSecret', 'wellKnownURL', 'authorizationURL', 'tokenURL', 'userInfoURL']];
yield 'okta' => [OktaUpdate::class, ['clientId', 'clientSecret', 'domain', 'authorizationServerId']];
}
/**
* @param class-string<Base> $actionClass
*/
#[DataProvider('plainProviders')]
public function testPlainProviderReadResponsesUseProviderSpecificFieldNames(
string $providerId,
string $actionClass,
string $idField,
string $secretField
): void {
$action = new $actionClass();
$response = $action->buildReadResponse($this->project([
$providerId . 'Enabled' => true,
$providerId . 'Appid' => 'stored-id',
$providerId . 'Secret' => 'stored-secret',
]));
$this->assertSame($providerId, $response->getAttribute('$id'));
$this->assertTrue($response->getAttribute('enabled'));
$this->assertSame('stored-id', $response->getAttribute($idField));
$this->assertSame('', $response->getAttribute($secretField));
if ($idField !== 'clientId') {
$this->assertFalse($response->offsetExists('clientId'));
}
if ($secretField !== 'clientSecret') {
$this->assertFalse($response->offsetExists('clientSecret'));
}
}
public static function plainProviders(): \Iterator
{
$actions = Base::getProviderActions();
yield 'amazon' => ['amazon', $actions['amazon'], 'clientId', 'clientSecret'];
yield 'dailymotion' => ['dailymotion', $actions['dailymotion'], 'apiKey', 'apiSecret'];
yield 'bitbucket' => ['bitbucket', $actions['bitbucket'], 'key', 'secret'];
yield 'dropbox' => ['dropbox', DropboxUpdate::class, 'appKey', 'appSecret'];
yield 'etsy' => ['etsy', $actions['etsy'], 'keyString', 'sharedSecret'];
yield 'facebook' => ['facebook', $actions['facebook'], 'appId', 'appSecret'];
yield 'notion' => ['notion', $actions['notion'], 'oauthClientId', 'oauthClientSecret'];
yield 'paypal' => ['paypal', $actions['paypal'], 'clientId', 'secretKey'];
yield 'salesforce' => ['salesforce', $actions['salesforce'], 'customerKey', 'customerSecret'];
yield 'stripe' => ['stripe', $actions['stripe'], 'clientId', 'apiSecretKey'];
yield 'tradeshift' => ['tradeshift', $actions['tradeshift'], 'oauth2ClientId', 'oauth2ClientSecret'];
yield 'x' => ['x', $actions['x'], 'customerKey', 'secretKey'];
}
public function testAppleReadResponseHidesP8FileAndExposesNonSecretFields(): void
{
$response = (new AppleUpdate())->buildReadResponse($this->project([
'appleEnabled' => true,
'appleAppid' => 'ip.appwrite.app.web',
'appleSecret' => \json_encode([
'p8' => 'private-key',
'keyID' => 'KEY123',
'teamID' => 'TEAM123',
]),
]));
$this->assertSame('apple', $response->getAttribute('$id'));
$this->assertTrue($response->getAttribute('enabled'));
$this->assertSame('ip.appwrite.app.web', $response->getAttribute('serviceId'));
$this->assertSame('KEY123', $response->getAttribute('keyId'));
$this->assertSame('TEAM123', $response->getAttribute('teamId'));
$this->assertSame('', $response->getAttribute('p8File'));
$this->assertFalse($response->offsetExists('clientId'));
$this->assertFalse($response->offsetExists('clientSecret'));
}
/**
* @param class-string<Base> $actionClass
* @param array<string, mixed> $storedSecret
* @param array<string, mixed> $expected
*/
#[DataProvider('jsonBackedReadResponses')]
public function testJsonBackedReadResponsesExposeOnlyNonSecretExtras(
string $providerId,
string $actionClass,
array $storedSecret,
array $expected
): void {
$response = (new $actionClass())->buildReadResponse($this->project([
$providerId . 'Enabled' => true,
$providerId . 'Appid' => 'stored-id',
$providerId . 'Secret' => \json_encode($storedSecret),
]));
$this->assertSame($providerId, $response->getAttribute('$id'));
$this->assertSame('stored-id', $response->getAttribute($actionClass::getClientIdParamName()));
$this->assertSame('', $response->getAttribute($actionClass::getClientSecretParamName()));
foreach ($expected as $key => $value) {
$this->assertSame($value, $response->getAttribute($key));
}
}
public static function jsonBackedReadResponses(): \Iterator
{
yield 'auth0' => ['auth0', Auth0Update::class, ['clientSecret' => 'secret', 'auth0Domain' => 'example.us.auth0.com'], ['endpoint' => 'example.us.auth0.com']];
yield 'authentik' => ['authentik', AuthentikUpdate::class, ['clientSecret' => 'secret', 'authentikDomain' => 'example.authentik.com'], ['endpoint' => 'example.authentik.com']];
yield 'fusionauth' => ['fusionauth', FusionAuthUpdate::class, ['clientSecret' => 'secret', 'fusionAuthDomain' => 'example.fusionauth.io'], ['endpoint' => 'example.fusionauth.io']];
yield 'gitlab' => ['gitlab', GitlabUpdate::class, ['clientSecret' => 'secret', 'endpoint' => 'https://gitlab.example.com'], ['endpoint' => 'https://gitlab.example.com']];
yield 'google' => ['google', GoogleUpdate::class, ['clientSecret' => 'secret', 'prompt' => ['select_account']], ['prompt' => ['select_account']]];
yield 'keycloak' => ['keycloak', KeycloakUpdate::class, ['clientSecret' => 'secret', 'keycloakDomain' => 'keycloak.example.com', 'keycloakRealm' => 'appwrite-realm'], ['endpoint' => 'keycloak.example.com', 'realmName' => 'appwrite-realm']];
yield 'microsoft' => ['microsoft', MicrosoftUpdate::class, ['clientSecret' => 'secret', 'tenantID' => 'common'], ['tenant' => 'common']];
yield 'oidc' => ['oidc', OidcUpdate::class, ['clientSecret' => 'secret', 'wellKnownEndpoint' => 'https://idp.example/.well-known/openid-configuration', 'authorizationEndpoint' => '', 'tokenEndpoint' => '', 'userInfoEndpoint' => ''], ['wellKnownURL' => 'https://idp.example/.well-known/openid-configuration', 'authorizationURL' => '', 'tokenURL' => '', 'userInfoURL' => '']];
yield 'okta' => ['okta', OktaUpdate::class, ['clientSecret' => 'secret', 'oktaDomain' => 'trial-6400025.okta.com', 'authorizationServerId' => 'aus123'], ['domain' => 'trial-6400025.okta.com', 'authorizationServerId' => 'aus123']];
}
public function testInvalidStoredJsonReturnsEmptyExtras(): void
{
$response = (new Auth0Update())->buildReadResponse($this->project([
'auth0Enabled' => false,
'auth0Appid' => 'stored-id',
'auth0Secret' => '{not-json',
]));
$this->assertSame('stored-id', $response->getAttribute('clientId'));
$this->assertSame('', $response->getAttribute('clientSecret'));
$this->assertSame('', $response->getAttribute('endpoint'));
}
public function testApplePartialUpdatesMergeStoredSecretFields(): void
{
$result = $this->runHandle(
new AppleUpdate(),
$this->project([
'appleEnabled' => false,
'appleAppid' => 'ip.appwrite.app.seed',
'appleSecret' => \json_encode([
'p8' => 'old-p8',
'keyID' => 'OLDKEY',
'teamID' => 'OLDTEAM',
]),
]),
[null, 'NEWKEY', null, null, false],
);
$stored = \json_decode($result['updatedProject']->getAttribute('oAuthProviders')['appleSecret'], true);
$this->assertSame('ip.appwrite.app.seed', $result['updatedProject']->getAttribute('oAuthProviders')['appleAppid']);
$this->assertSame('old-p8', $stored['p8']);
$this->assertSame('NEWKEY', $stored['keyID']);
$this->assertSame('OLDTEAM', $stored['teamID']);
$this->assertSame('NEWKEY', $result['response']->getAttribute('keyId'));
$this->assertSame('', $result['response']->getAttribute('p8File'));
}
/**
* @param class-string<Base> $actionClass
* @param array<string, mixed> $initialSecret
* @param array<int, mixed> $args
* @param array<string, mixed> $expectedSecret
* @param array<string, mixed> $expectedResponse
*/
#[DataProvider('partialJsonMergeScenarios')]
public function testPartialJsonBackedUpdatesPreserveExistingFields(
string $providerId,
string $actionClass,
array $initialSecret,
array $args,
array $expectedSecret,
array $expectedResponse
): void {
$result = $this->runHandle(
new $actionClass(),
$this->project([
$providerId . 'Enabled' => false,
$providerId . 'Appid' => 'seed-id',
$providerId . 'Secret' => \json_encode($initialSecret),
]),
$args,
);
$stored = \json_decode($result['updatedProject']->getAttribute('oAuthProviders')[$providerId . 'Secret'], true);
foreach ($expectedSecret as $key => $value) {
$this->assertSame($value, $stored[$key]);
}
foreach ($expectedResponse as $key => $value) {
$this->assertSame($value, $result['response']->getAttribute($key));
}
}
public static function partialJsonMergeScenarios(): \Iterator
{
yield 'auth0 endpoint only' => [
'auth0',
Auth0Update::class,
['clientSecret' => 'old-secret', 'auth0Domain' => 'old.us.auth0.com'],
[null, null, 'new.us.auth0.com', false],
['clientSecret' => 'old-secret', 'auth0Domain' => 'new.us.auth0.com'],
['clientId' => 'seed-id', 'clientSecret' => '', 'endpoint' => 'new.us.auth0.com'],
];
yield 'authentik client only' => [
'authentik',
AuthentikUpdate::class,
['clientSecret' => 'old-secret', 'authentikDomain' => 'old.authentik.com'],
['rotated-id', null, null, false],
['clientSecret' => 'old-secret', 'authentikDomain' => 'old.authentik.com'],
['clientId' => 'rotated-id', 'endpoint' => 'old.authentik.com'],
];
yield 'fusionauth secret only' => [
'fusionauth',
FusionAuthUpdate::class,
['clientSecret' => 'old-secret', 'fusionAuthDomain' => 'old.fusionauth.io'],
[null, 'new-secret', null, false],
['clientSecret' => 'new-secret', 'fusionAuthDomain' => 'old.fusionauth.io'],
['clientId' => 'seed-id', 'endpoint' => 'old.fusionauth.io'],
];
yield 'gitlab endpoint only' => [
'gitlab',
GitlabUpdate::class,
['clientSecret' => 'old-secret', 'endpoint' => 'https://old.gitlab.example'],
[null, null, 'https://new.gitlab.example', false],
['clientSecret' => 'old-secret', 'endpoint' => 'https://new.gitlab.example'],
['applicationId' => 'seed-id', 'endpoint' => 'https://new.gitlab.example'],
];
yield 'keycloak realm only' => [
'keycloak',
KeycloakUpdate::class,
['clientSecret' => 'old-secret', 'keycloakDomain' => 'keycloak.example.com', 'keycloakRealm' => 'old-realm'],
[null, null, null, 'new-realm', false],
['clientSecret' => 'old-secret', 'keycloakDomain' => 'keycloak.example.com', 'keycloakRealm' => 'new-realm'],
['clientId' => 'seed-id', 'endpoint' => 'keycloak.example.com', 'realmName' => 'new-realm'],
];
yield 'microsoft tenant only' => [
'microsoft',
MicrosoftUpdate::class,
['clientSecret' => 'old-secret', 'tenantID' => 'organizations'],
[null, null, 'common', false],
['clientSecret' => 'old-secret', 'tenantID' => 'common'],
['applicationId' => 'seed-id', 'tenant' => 'common'],
];
yield 'okta authorization server only' => [
'okta',
OktaUpdate::class,
['clientSecret' => 'old-secret', 'oktaDomain' => 'trial-6400025.okta.com', 'authorizationServerId' => 'old-server'],
[null, null, null, 'new-server', false],
['clientSecret' => 'old-secret', 'oktaDomain' => 'trial-6400025.okta.com', 'authorizationServerId' => 'new-server'],
['clientId' => 'seed-id', 'domain' => 'trial-6400025.okta.com', 'authorizationServerId' => 'new-server'],
];
}
public function testOidcAcceptsWellKnownMode(): void
{
$result = $this->runHandle(new OidcUpdate(), $this->project(), [
'oidc-client',
'oidc-secret',
'https://idp.example/.well-known/openid-configuration',
null,
null,
null,
true,
]);
$stored = \json_decode($result['updatedProject']->getAttribute('oAuthProviders')['oidcSecret'], true);
$this->assertSame('https://idp.example/.well-known/openid-configuration', $stored['wellKnownEndpoint']);
$this->assertTrue($result['response']->getAttribute('enabled'));
$this->assertSame('https://idp.example/.well-known/openid-configuration', $result['response']->getAttribute('wellKnownURL'));
}
public function testOidcAcceptsDiscoveryUrlMode(): void
{
$result = $this->runHandle(new OidcUpdate(), $this->project(), [
'oidc-client',
'oidc-secret',
null,
'https://idp.example/oauth2/authorize',
'https://idp.example/oauth2/token',
'https://idp.example/oauth2/userinfo',
true,
]);
$stored = \json_decode($result['updatedProject']->getAttribute('oAuthProviders')['oidcSecret'], true);
$this->assertSame('https://idp.example/oauth2/authorize', $stored['authorizationEndpoint']);
$this->assertSame('https://idp.example/oauth2/token', $stored['tokenEndpoint']);
$this->assertSame('https://idp.example/oauth2/userinfo', $stored['userInfoEndpoint']);
$this->assertTrue($result['response']->getAttribute('enabled'));
}
public function testOidcRejectsEnableWithIncompleteDiscoveryConfig(): void
{
$this->expectException(Exception::class);
$this->runHandle(
new OidcUpdate(),
$this->project(),
[
'oidc-client',
'oidc-secret',
null,
'https://idp.example/oauth2/authorize',
null,
'https://idp.example/oauth2/userinfo',
true,
],
assertQueueParam: false,
);
}
public function testOidcCanSwitchFromWellKnownToDiscoveryMode(): void
{
$result = $this->runHandle(
new OidcUpdate(),
$this->project([
'oidcEnabled' => false,
'oidcAppid' => 'oidc-client',
'oidcSecret' => \json_encode([
'clientSecret' => 'oidc-secret',
'wellKnownEndpoint' => 'https://old.example/.well-known/openid-configuration',
'authorizationEndpoint' => '',
'tokenEndpoint' => '',
'userInfoEndpoint' => '',
]),
]),
[
null,
null,
'',
'https://idp.example/oauth2/authorize',
'https://idp.example/oauth2/token',
'https://idp.example/oauth2/userinfo',
true,
],
);
$stored = \json_decode($result['updatedProject']->getAttribute('oAuthProviders')['oidcSecret'], true);
$this->assertSame('', $stored['wellKnownEndpoint']);
$this->assertSame('https://idp.example/oauth2/authorize', $stored['authorizationEndpoint']);
$this->assertTrue($result['response']->getAttribute('enabled'));
}
public function testGooglePromptRulesAndBackwardCompatibleSecretStorage(): void
{
$result = $this->runHandle(
new GoogleUpdate(),
$this->project([
'googleEnabled' => false,
'googleAppid' => 'google-client',
'googleSecret' => 'legacy-plain-secret',
]),
[null, null, ['none'], false],
);
$stored = \json_decode($result['updatedProject']->getAttribute('oAuthProviders')['googleSecret'], true);
$this->assertSame('legacy-plain-secret', $stored['clientSecret']);
$this->assertSame(['none'], $stored['prompt']);
$this->assertSame(['none'], $result['response']->getAttribute('prompt'));
}
public function testGoogleRejectsEmptyPrompt(): void
{
$this->expectException(Exception::class);
$this->runHandle(
new GoogleUpdate(),
$this->project(),
[
'google-client',
'google-secret',
[],
false,
],
assertQueueParam: false,
);
}
public function testGoogleRejectsNoneWithOtherPrompts(): void
{
$this->expectException(Exception::class);
$this->runHandle(
new GoogleUpdate(),
$this->project(),
[
'google-client',
'google-secret',
['none', 'consent'],
false,
],
assertQueueParam: false,
);
}
public function testOktaRequiresDomainWhenEnabling(): void
{
$this->expectException(Exception::class);
$this->runHandle(
new OktaUpdate(),
$this->project(),
[
'okta-client',
'okta-secret',
'',
null,
true,
],
assertQueueParam: false,
);
}
public function testOktaCanEnableWithStoredDomain(): void
{
$result = $this->runHandle(
new OktaUpdate(),
$this->project([
'oktaEnabled' => false,
'oktaAppid' => 'okta-client',
'oktaSecret' => \json_encode([
'clientSecret' => 'okta-secret',
'oktaDomain' => 'trial-6400025.okta.com',
'authorizationServerId' => '',
]),
]),
[null, null, null, null, true],
);
$this->assertTrue($result['response']->getAttribute('enabled'));
$this->assertSame('trial-6400025.okta.com', $result['response']->getAttribute('domain'));
}
/**
* @param array<string, mixed> $oAuthProviders
*/
private function project(array $oAuthProviders = []): Document
{
return new Document([
'$id' => 'project-test',
'oAuthProviders' => $oAuthProviders,
]);
}
/**
* @param array<int, mixed> $args
* @return array{updatedProject: Document, response: Document}
*/
private function runHandle(Base $action, Document $project, array $args, bool $assertQueueParam = true): array
{
$updatedProject = null;
$responseDocument = null;
$dbForPlatform = $this->createStub(Database::class);
$dbForPlatform
->method('updateDocument')
->willReturnCallback(function (string $collection, string $id, Document $updates) use ($project, &$updatedProject): Document {
$this->assertSame('projects', $collection);
$this->assertSame('project-test', $id);
$updatedProject = new Document($project->getArrayCopy());
$updatedProject->setAttribute('oAuthProviders', $updates->getAttribute('oAuthProviders', []));
return $updatedProject;
});
$authorization = $this->createStub(Authorization::class);
$authorization
->method('skip')
->willReturnCallback(fn (callable $callback): mixed => $callback());
$response = $this->createStub(Response::class);
$response
->method('dynamic')
->willReturnCallback(function (Document $document) use (&$responseDocument): void {
$responseDocument = $document;
});
$queueForEvents = $this->getMockBuilder(QueueEvent::class)
->disableOriginalConstructor()
->onlyMethods(['setParam'])
->getMock();
$queueForEvents
->expects($assertQueueParam ? $this->once() : $this->atMost(1))
->method('setParam')
->with('providerId', $action::getProviderId());
$handle = [$action, 'handle'];
$this->assertIsCallable($handle);
$handle(...[
...$args,
$response,
$dbForPlatform,
$project,
$authorization,
$queueForEvents,
]);
$this->assertInstanceOf(Document::class, $updatedProject);
$this->assertInstanceOf(Document::class, $responseDocument);
return [
'updatedProject' => $updatedProject,
'response' => $responseDocument,
];
}
}