From 7e567de8fea907caa22b9f270c8f76cc0eee9dc2 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:31:27 +0530 Subject: [PATCH 01/38] fix(deployments): canonicalize the root directory an artifact indexes into MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `providerRootDirectory` reached the jobs-service through `trim($subdir, '/')`, which strips slashes but not dots. `docs`, `docs/` and `/docs` all canonicalized to `docs`, while `./docs` survived verbatim as an artifact subdir naming a path segment that does not exist in the extracted tree. `.` and `./` were worse: they collapsed to a non-empty `.`, so the repository-root case emitted a subdir instead of omitting one. Canonicalize on the consume side, in `Deployments::rootDirectory()`. Every remote-source build funnels through `submit()`, so one choke point covers new writes, rows already holding `./docs`, webhooks, duplicates and templates without a migration. Drop whole `.` segments rather than trimming the character. The builds worker's `ltrim($path, '.')` turned `.github` into `github` — a silent wrong-directory build — and left `../etc` traversal intact. Both worker call sites now share the canonicalizer, and the jobs-service hand-off passes the canonicalized value instead of re-reading the raw attribute, which also closes a mismatch where the template push committed at a space-stripped path but sent the space-bearing one. `..` segments are dropped rather than resolved, so a subdir cannot escape the tree it indexes into. --- src/Appwrite/Deployment/Deployments.php | 29 +++++++- .../Modules/Functions/Workers/Builds.php | 12 +-- tests/unit/Deployment/DeploymentsTest.php | 74 ++++++++++++++++++- 3 files changed, 101 insertions(+), 14 deletions(-) diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 1112a4bab2..79db97a904 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -293,6 +293,31 @@ readonly class Deployments return $this->dbForProject->getDocument('deployments', $deploymentId)->getAttribute('status', ''); } + /** + * Canonicalize a root directory into the subdirectory path an artifact can + * match against a tree: no leading `./`, no surrounding slashes, `''` for + * the repository root. + * + * The console's directory picker and every shipped site template write the + * path with a `./` prefix (`./astro/starter`), while a hand-typed one is + * usually bare (`docs`) and sometimes trailing-slashed (`docs/`). All three + * name the same directory, so all three must produce the same subdir. + * + * Dropping whole `.` segments rather than trimming the character keeps a + * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. + * `..` segments are dropped for the same reason a subdir cannot escape the + * tree it indexes into. + */ + public static function rootDirectory(string $rootDirectory): string + { + $segments = \array_filter( + \explode('/', $rootDirectory), + fn (string $segment) => $segment !== '' && $segment !== '.' && $segment !== '..', + ); + + return \implode('/', $segments); + } + /** * The build command for a deployment: its buildCommands, wrapped for * sites with the framework's env and bundle commands. @@ -385,12 +410,12 @@ readonly class Deployments // - otherwise: the deployment's uploaded tarball, fetched from Appwrite // over a presigned GET (manual upload / duplicate). if (isset($source['clone'])) { - $subdir = \trim($source['subdir'] ?? '', '/'); + $subdir = self::rootDirectory($source['subdir'] ?? ''); $sourceArtifacts = [ new CloneArtifact(id: 'source', in: $source['clone'], out: 'source', ref: $source['ref'] ?? '', subdir: $subdir, headers: $source['headers'] ?? []), ]; } elseif ($source !== null) { - $subdir = \trim($source['subdir'] ?? '', '/'); + $subdir = self::rootDirectory($source['subdir'] ?? ''); $sourceArtifacts = [ new DownloadArtifact(id: 'source', in: $source['url'], out: 'source.tar.gz', headers: $source['headers'] ?? []), new UnarchiveArtifact(id: 'extract', in: 'source.tar.gz', out: 'source', subdir: $subdir !== '' ? $subdir : null, strip: true, depends: 'source'), diff --git a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php index eee89f1a5d..7a7ae264bb 100644 --- a/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php +++ b/src/Appwrite/Platform/Modules/Functions/Workers/Builds.php @@ -275,10 +275,7 @@ class Builds extends Action try { // VCS and VCS+Temaplte $tmpDirectory = '/tmp/builds/' . $deploymentId . '/code'; - $rootDirectory = $resource->getAttribute('providerRootDirectory', ''); - $rootDirectory = \rtrim($rootDirectory, '/'); - $rootDirectory = \ltrim($rootDirectory, '.'); - $rootDirectory = \ltrim($rootDirectory, '/'); + $rootDirectory = Deployments::rootDirectory($resource->getAttribute('providerRootDirectory', '')); $owner = $providerAdapter->getOwnerName($providerInstallationId); $repositoryName = $providerAdapter->getRepositoryName($providerRepositoryId); @@ -333,10 +330,7 @@ class Builds extends Action $templateReferenceType = $template->getAttribute('referenceType', ''); $templateReferenceValue = $template->getAttribute('referenceValue', ''); - $templateRootDirectory = $template->getAttribute('rootDirectory', ''); - $templateRootDirectory = \rtrim($templateRootDirectory, '/'); - $templateRootDirectory = \ltrim($templateRootDirectory, '.'); - $templateRootDirectory = \ltrim($templateRootDirectory, '/'); + $templateRootDirectory = Deployments::rootDirectory($template->getAttribute('rootDirectory', '')); if (! empty($templateRepositoryName) && ! empty($templateOwnerName) && ! empty($templateReferenceType) && ! empty($templateReferenceValue)) { // Clone template repo @@ -403,7 +397,7 @@ class Builds extends Action $cloneOwner, $cloneRepository, $ref, - $resource->getAttribute('providerRootDirectory', ''), + $rootDirectory, ); Console::execute('rm -rf ' . \escapeshellarg('/tmp/builds/' . $deploymentId), '', $stdout, $stderr); diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index de41f435d3..9f04c67a04 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -6,6 +6,7 @@ namespace Tests\Unit\Deployment; use Appwrite\Deployment\Deployments; use Appwrite\Extend\Exception; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Utopia\Config\Config; use Utopia\Database\Document; @@ -35,6 +36,32 @@ final class DeploymentsTest extends TestCase ); } + public static function rootDirectories(): \Iterator + { + yield 'repository root' => ['', '']; + yield 'dot' => ['.', '']; + yield 'dot slash' => ['./', '']; + yield 'bare' => ['docs', 'docs']; + yield 'trailing slash' => ['docs/', 'docs']; + yield 'dot slash prefix' => ['./docs', 'docs']; + yield 'dot slash prefix and trailing slash' => ['./docs/', 'docs']; + yield 'leading slash' => ['/docs', 'docs']; + yield 'nested' => ['docs/nested', 'docs/nested']; + yield 'nested with prefix and trailing slash' => ['./docs/nested/', 'docs/nested']; + yield 'shipped site template' => ['./astro/starter', 'astro/starter']; + yield 'hidden directory' => ['.github', '.github']; + yield 'dot-prefixed name' => ['..foo', '..foo']; + yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; + yield 'traversal' => ['../etc', 'etc']; + yield 'embedded traversal' => ['./docs/../../etc', 'docs/etc']; + } + + #[DataProvider('rootDirectories')] + public function testRootDirectoryCanonicalizes(string $rootDirectory, string $expected): void + { + $this->assertSame($expected, Deployments::rootDirectory($rootDirectory)); + } + public function testFunctionCommandIsDeploymentBuildCommands(): void { $resource = new Document(['$collection' => 'functions']); @@ -128,7 +155,7 @@ final class DeploymentsTest extends TestCase $this->assertSame(['users.read'], Deployments::scopes($site)); } - private function buildPayload(array $vars): array + private function buildPayload(array $vars, ?array $source = null): array { // Presigned-URL and ephemeral-key signing both run before the // variables are assembled, and refuse an empty key. @@ -150,9 +177,50 @@ final class DeploymentsTest extends TestCase ]), new Document(['$id' => 'deployment1', 'buildCommands' => 'npm install']), ['apiHostname' => 'localhost'], + $source, ); } + private function artifact(array $payload, string $id): object + { + foreach ($payload['artifacts'] as $artifact) { + if ($artifact->id === $id) { + return $artifact; + } + } + + $this->fail("No '{$id}' artifact in the payload"); + } + + public function testPayloadUnarchivesFromCanonicalSubdirectory(): void + { + $payload = $this->buildPayload([], ['url' => 'https://example.com/x.tar.gz', 'subdir' => './docs/nested/']); + + $this->assertSame('docs/nested', $this->artifact($payload, 'extract')->subdir); + } + + #[DataProvider('repositoryRoots')] + public function testPayloadOmitsSubdirectoryForRepositoryRoot(string $rootDirectory): void + { + $payload = $this->buildPayload([], ['url' => 'https://example.com/x.tar.gz', 'subdir' => $rootDirectory]); + + $this->assertNull($this->artifact($payload, 'extract')->subdir); + } + + public static function repositoryRoots(): \Iterator + { + yield 'empty' => ['']; + yield 'dot' => ['.']; + yield 'dot slash' => ['./']; + } + + public function testPayloadClonesFromCanonicalSubdirectory(): void + { + $payload = $this->buildPayload([], ['clone' => 'https://example.com/r.git', 'ref' => 'main', 'subdir' => './docs']); + + $this->assertSame('docs', $this->artifact($payload, 'source')->subdir); + } + public function testPayloadRefusesVariableKeyTheClusterWouldRefuse(): void { try { @@ -178,8 +246,8 @@ final class DeploymentsTest extends TestCase final readonly class ExposedDeployments extends Deployments { - public static function submitPayload(Document $project, Document $resource, Document $deployment, array $platform): array + public static function submitPayload(Document $project, Document $resource, Document $deployment, array $platform, ?array $source = null): array { - return static::payload($project, $resource, $deployment, $platform); + return static::payload($project, $resource, $deployment, $platform, $source); } } From cdefa07dc538f76b7f6e60daa668c7695c2228d2 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:31:33 +0530 Subject: [PATCH 02/38] fix(vcs): record the root directory on webhook deployments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shared deployment document carried every other `provider*` field but not `providerRootDirectory`, so a push-triggered deployment persisted an empty root directory. The build itself was correct — the root directory is passed separately — but duplicating such a deployment reads the value back off the source document, so a redeploy silently built from the repository root. The trait is shared by GitHub, GitLab, Gitea, Bitbucket and Origin. --- src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php index d9e123764f..5f863dd65c 100644 --- a/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php +++ b/src/Appwrite/Platform/Modules/VCS/Http/GitHub/Deployment.php @@ -391,6 +391,7 @@ trait Deployment 'providerCommitUrl' => $providerCommitUrl, 'providerCommentId' => \strval($latestCommentId), 'providerBranch' => $providerBranch, + 'providerRootDirectory' => $resource->getAttribute('providerRootDirectory', ''), 'activate' => $activate, ]); From 922f601f3e71037e70627686ec4144427fdf09e6 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:39:17 +0530 Subject: [PATCH 03/38] fix(deployments): refuse a root directory that leaves the repository MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dropping `..` segments made `docs/../x` build `docs/x`, which is neither the directory the caller named nor the one POSIX would resolve — and if both exist, the wrong application deploys with no warning. Resolving the segment instead would let the subdir climb out of the tree it indexes into. Refuse the path instead. The failure is the owner's to fix, so it joins the refused-variable-key case in carrying its reason into the build log rather than a generic internal error. --- app/config/errors.php | 5 +++++ src/Appwrite/Deployment/Deployments.php | 26 +++++++++++++++++------ src/Appwrite/Extend/Exception.php | 1 + tests/unit/Deployment/DeploymentsTest.php | 24 +++++++++++++++++++-- 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/app/config/errors.php b/app/config/errors.php index dc0cccc6d1..f01d4bf0b7 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -734,6 +734,11 @@ return [ 'description' => 'Deployment with the requested ID could not be found.', 'code' => 404, ], + Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY => [ + 'name' => Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, + 'description' => 'Root directory must stay inside the repository. Remove the ".." segments, then retry the deployment.', + 'code' => 400, + ], Exception::DEPLOYMENT_INVALID_FILE_SIZE => [ 'name' => Exception::DEPLOYMENT_INVALID_FILE_SIZE, 'description' => 'The deployment file size is either not valid or exceeds the maximum allowed size. Please check the file or the value of the _APP_COMPUTE_SIZE_LIMIT environment variable.', diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 79db97a904..e1996c8be3 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -223,10 +223,11 @@ readonly class Deployments try { $this->jobs->create(...static::payload($this->project, $resource, $deployment, $this->platform, $source)); } catch (\Throwable $error) { - // A refused variable key is the owner's to fix, so the build log - // carries the actual reason; anything else stays a generic - // internal error. - $buildLogs = $error instanceof Exception && $error->getType() === Exception::VARIABLE_INVALID_KEY + // A refused variable key or root directory is the owner's to fix, + // so the build log carries the actual reason; anything else stays a + // generic internal error. + $owned = [Exception::VARIABLE_INVALID_KEY, Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY]; + $buildLogs = $error instanceof Exception && \in_array($error->getType(), $owned, true) ? "\n" . $error->getMessage() . "\n" : "\nAn internal error occurred while building. Please try again, and contact support if the problem persists.\n"; @@ -305,16 +306,27 @@ readonly class Deployments * * Dropping whole `.` segments rather than trimming the character keeps a * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. - * `..` segments are dropped for the same reason a subdir cannot escape the - * tree it indexes into. + * + * A `..` segment is refused rather than dropped or resolved. Dropping it + * would silently build `docs/x` for a `docs/../x` that names `x`, and + * resolving it would let the subdir climb out of the tree it indexes into. + * + * @throws Exception when a segment would leave the repository */ public static function rootDirectory(string $rootDirectory): string { $segments = \array_filter( \explode('/', $rootDirectory), - fn (string $segment) => $segment !== '' && $segment !== '.' && $segment !== '..', + fn (string $segment) => $segment !== '' && $segment !== '.', ); + if (\in_array('..', $segments, true)) { + throw new Exception( + Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, + 'Root directory ' . \json_encode($rootDirectory) . ' must stay inside the repository. Remove the ".." segments, then retry the deployment.' + ); + } + return \implode('/', $segments); } diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index 7c4fe95295..a25ee9397d 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -191,6 +191,7 @@ class Exception extends \Exception /** Deployments */ public const string DEPLOYMENT_NOT_FOUND = 'deployment_not_found'; public const string DEPLOYMENT_INVALID_FILE_SIZE = 'deployment_invalid_file_size'; + public const string DEPLOYMENT_INVALID_ROOT_DIRECTORY = 'deployment_invalid_root_directory'; /** Builds */ public const string BUILD_NOT_FOUND = 'build_not_found'; diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index 9f04c67a04..aee91f6b6d 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -52,8 +52,6 @@ final class DeploymentsTest extends TestCase yield 'hidden directory' => ['.github', '.github']; yield 'dot-prefixed name' => ['..foo', '..foo']; yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; - yield 'traversal' => ['../etc', 'etc']; - yield 'embedded traversal' => ['./docs/../../etc', 'docs/etc']; } #[DataProvider('rootDirectories')] @@ -62,6 +60,28 @@ final class DeploymentsTest extends TestCase $this->assertSame($expected, Deployments::rootDirectory($rootDirectory)); } + #[DataProvider('escapingRootDirectories')] + public function testRootDirectoryRefusesSegmentLeavingTheRepository(string $rootDirectory): void + { + try { + Deployments::rootDirectory($rootDirectory); + $this->fail('Expected the root directory to be refused before job submission'); + } catch (Exception $error) { + $this->assertSame(Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, $error->getType()); + } + } + + public static function escapingRootDirectories(): \Iterator + { + yield 'parent' => ['..']; + yield 'parent path' => ['../etc']; + yield 'parent path with prefix' => ['./../etc']; + // Dropping the segment would silently build 'docs/x'; resolving it, + // 'x'. Neither is the directory the caller named. + yield 'interior parent' => ['docs/../x']; + yield 'escaping interior parent' => ['./docs/../../etc']; + } + public function testFunctionCommandIsDeploymentBuildCommands(): void { $resource = new Document(['$collection' => 'functions']); From 88ed9ab46bd93bf8094639dfa3f54d1959e0b0bd Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:39:24 +0530 Subject: [PATCH 04/38] test(vcs): cover a nested root directory through push and duplicate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Builds a function from './docs/nested/' — the form the console's directory picker writes — over the Gitea suite, the only live-VCS suite CI boots. Covers both halves observably: the push-created deployment must execute the nested entrypoint, and duplicating it must reach 'ready'. A duplicate reads the root directory back off the source deployment, so a regression that stops persisting it builds from the repository root, where the auto-init README is the only file and no entrypoint exists. --- .../VCSGitea/VCSGiteaConsoleClientTest.php | 83 ++++++++++++++++++- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index abd16dc7fa..5b7d99902c 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -110,6 +110,80 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-v2'), 30000, 1000); } + public function testCreateDeploymentFromNestedRootDirectory(): void + { + $projectId = $this->getProject()['$id']; + $installationId = $this->createInstallationHelper()['$id']; + + $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ + 'name' => 'function-' . \uniqid(), + 'auto_init' => true, + 'default_branch' => 'main', + 'private' => false, + ]); + $this->assertEquals(201, $repository['headers']['status-code'], \json_encode($repository['body'])); + $repositoryName = $repository['body']['name']; + + $workdir = \sys_get_temp_dir() . '/vcs-gitea-' . \uniqid(); + $endpoint = System::getEnv('_APP_VCS_GITEA_ENDPOINT', 'http://gitea:3000'); + $remote = \str_replace('://', '://' . self::GITEA_USERNAME . ':' . self::GITEA_PASSWORD . '@', $endpoint) + . '/' . self::GITEA_USERNAME . '/' . $repositoryName . '.git'; + + $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); + $this->writeFunctionHelper($workdir, 'gitea-nested-v1', 'docs/nested'); + $this->gitHelper('git add docs && git commit -m "Add nested function"', $workdir); + $this->gitHelper('git push origin main', $workdir); + + // The console's directory picker writes the path in this form; it names + // the same directory as 'docs/nested'. + $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'functionId' => ID::unique(), + 'name' => 'Gitea nested VCS', + 'execute' => [Role::any()->toString()], + 'runtime' => 'node-22', + 'entrypoint' => 'index.js', + 'timeout' => 15, + 'installationId' => $installationId, + 'providerRepositoryId' => (string) $repository['body']['id'], + 'providerBranch' => 'main', + 'providerRootDirectory' => './docs/nested/', + ]); + $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); + $functionId = $function['body']['$id']; + + $knownIds = $this->listDeploymentIdsHelper($functionId); + + $this->writeFunctionHelper($workdir, 'gitea-nested-v2', 'docs/nested'); + $this->gitHelper('git add docs && git commit -m "Update nested function"', $workdir); + $this->gitHelper('git push origin main', $workdir); + + $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2'), 30000, 1000); + + // A push-created deployment must persist the root directory it built + // from, since duplicating one reads the value back off this document. + $webhookDeployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $webhookDeploymentId, \array_merge([ + 'x-appwrite-project' => $projectId, + ], $this->getHeaders())); + $this->assertEquals(200, $webhookDeployment['headers']['status-code']); + $this->assertEquals('./docs/nested/', $webhookDeployment['body']['providerRootDirectory']); + + $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'deploymentId' => $webhookDeploymentId, + ]); + $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); + + // Building from the repository root instead would fail outright: the + // root holds only the auto-init README, no entrypoint. + $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); + } + public function testClosePullRequestRemovesAuthorization(): void { /** @@ -374,9 +448,14 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertSame(0, $exitCode, "Git command failed: {$command}\n" . \implode("\n", $output)); } - private function writeFunctionHelper(string $workdir, string $output): void + private function writeFunctionHelper(string $workdir, string $output, string $path = ''): void { - \file_put_contents($workdir . '/index.js', "module.exports = async (context) => context.res.send('{$output}');\n"); + $directory = $workdir . ($path === '' ? '' : '/' . $path); + if (! \is_dir($directory)) { + \mkdir($directory, 0o777, true); + } + + \file_put_contents($directory . '/index.js', "module.exports = async (context) => context.res.send('{$output}');\n"); } private function waitForDeploymentReadyHelper(string $functionId, string $deploymentId): void From 7e7702494244934ab15f6d4d0056e1a1166a5168 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 16:50:11 +0530 Subject: [PATCH 05/38] test(vcs): prove the persisted root directory through the duplicate build The deployment response model does not expose providerRootDirectory, so reading it off the body asserted on a key that is never returned. Duplicating the push-created deployment proves the same thing through behavior: the duplicate reads the root directory back off the deployment it copies, so it only reaches 'ready' if the push persisted one. Also deploy explicitly before pushing, so the nested entrypoint is observed executing on a deployment the test activated rather than one it assumed was active. --- .../VCSGitea/VCSGiteaConsoleClientTest.php | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index 5b7d99902c..ff84f95872 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -154,6 +154,19 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); $functionId = $function['body']['$id']; + $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/vcs', \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'type' => 'branch', + 'reference' => 'main', + 'activate' => true, + ]); + $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); + + $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1'), 30000, 1000); + $knownIds = $this->listDeploymentIdsHelper($functionId); $this->writeFunctionHelper($workdir, 'gitea-nested-v2', 'docs/nested'); @@ -161,16 +174,11 @@ final class VCSGiteaConsoleClientTest extends Scope $this->gitHelper('git push origin main', $workdir); $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2'), 30000, 1000); - - // A push-created deployment must persist the root directory it built - // from, since duplicating one reads the value back off this document. - $webhookDeployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $webhookDeploymentId, \array_merge([ - 'x-appwrite-project' => $projectId, - ], $this->getHeaders())); - $this->assertEquals(200, $webhookDeployment['headers']['status-code']); - $this->assertEquals('./docs/nested/', $webhookDeployment['body']['providerRootDirectory']); + // A duplicate reads the root directory back off the deployment it + // copies, so this only builds if the push-created deployment persisted + // one. Building from the repository root instead fails outright: the + // root holds only the auto-init README, no entrypoint. $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, @@ -179,8 +187,6 @@ final class VCSGiteaConsoleClientTest extends Scope ]); $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); - // Building from the repository root instead would fail outright: the - // root holds only the auto-init README, no entrypoint. $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); } From c56c4ed8ead3fa2c2c05fb68e03437a993110ebc Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 17:17:54 +0530 Subject: [PATCH 06/38] fix(deployments): leave a parent segment for the extractor to resolve MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refusing `..` added a failure mode where there was none: `trim($subdir, '/')` has always passed a parent segment through untouched, so `docs/../x` reaches the extractor today and resolves to the directory it names. Rejecting it before job submission turns a working deployment into a 400. Canonicalize the forms that actually diverge — empty and `.` segments — and leave the rest of the path as given. Dropping `..` instead would silently build `docs/x`, which is the reason it was singled out in the first place. --- app/config/errors.php | 5 ----- src/Appwrite/Deployment/Deployments.php | 24 +++++++--------------- src/Appwrite/Extend/Exception.php | 1 - tests/unit/Deployment/DeploymentsTest.php | 25 +++-------------------- 4 files changed, 10 insertions(+), 45 deletions(-) diff --git a/app/config/errors.php b/app/config/errors.php index f01d4bf0b7..dc0cccc6d1 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -734,11 +734,6 @@ return [ 'description' => 'Deployment with the requested ID could not be found.', 'code' => 404, ], - Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY => [ - 'name' => Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, - 'description' => 'Root directory must stay inside the repository. Remove the ".." segments, then retry the deployment.', - 'code' => 400, - ], Exception::DEPLOYMENT_INVALID_FILE_SIZE => [ 'name' => Exception::DEPLOYMENT_INVALID_FILE_SIZE, 'description' => 'The deployment file size is either not valid or exceeds the maximum allowed size. Please check the file or the value of the _APP_COMPUTE_SIZE_LIMIT environment variable.', diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index e1996c8be3..5e634f5238 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -223,11 +223,10 @@ readonly class Deployments try { $this->jobs->create(...static::payload($this->project, $resource, $deployment, $this->platform, $source)); } catch (\Throwable $error) { - // A refused variable key or root directory is the owner's to fix, - // so the build log carries the actual reason; anything else stays a - // generic internal error. - $owned = [Exception::VARIABLE_INVALID_KEY, Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY]; - $buildLogs = $error instanceof Exception && \in_array($error->getType(), $owned, true) + // A refused variable key is the owner's to fix, so the build log + // carries the actual reason; anything else stays a generic + // internal error. + $buildLogs = $error instanceof Exception && $error->getType() === Exception::VARIABLE_INVALID_KEY ? "\n" . $error->getMessage() . "\n" : "\nAn internal error occurred while building. Please try again, and contact support if the problem persists.\n"; @@ -307,11 +306,9 @@ readonly class Deployments * Dropping whole `.` segments rather than trimming the character keeps a * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. * - * A `..` segment is refused rather than dropped or resolved. Dropping it - * would silently build `docs/x` for a `docs/../x` that names `x`, and - * resolving it would let the subdir climb out of the tree it indexes into. - * - * @throws Exception when a segment would leave the repository + * `..` is left alone. Dropping it would silently build `docs/x` for a + * `docs/../x` that names `x`, and resolving it here would duplicate what + * the extractor already does with the path it is handed. */ public static function rootDirectory(string $rootDirectory): string { @@ -320,13 +317,6 @@ readonly class Deployments fn (string $segment) => $segment !== '' && $segment !== '.', ); - if (\in_array('..', $segments, true)) { - throw new Exception( - Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, - 'Root directory ' . \json_encode($rootDirectory) . ' must stay inside the repository. Remove the ".." segments, then retry the deployment.' - ); - } - return \implode('/', $segments); } diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index a25ee9397d..7c4fe95295 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -191,7 +191,6 @@ class Exception extends \Exception /** Deployments */ public const string DEPLOYMENT_NOT_FOUND = 'deployment_not_found'; public const string DEPLOYMENT_INVALID_FILE_SIZE = 'deployment_invalid_file_size'; - public const string DEPLOYMENT_INVALID_ROOT_DIRECTORY = 'deployment_invalid_root_directory'; /** Builds */ public const string BUILD_NOT_FOUND = 'build_not_found'; diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index aee91f6b6d..ad66431dab 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -51,6 +51,9 @@ final class DeploymentsTest extends TestCase yield 'shipped site template' => ['./astro/starter', 'astro/starter']; yield 'hidden directory' => ['.github', '.github']; yield 'dot-prefixed name' => ['..foo', '..foo']; + // Left for the extractor to resolve; dropping it would build 'docs/x'. + yield 'parent' => ['docs/../x', 'docs/../x']; + yield 'parent with prefix' => ['./docs/../x', 'docs/../x']; yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; } @@ -60,28 +63,6 @@ final class DeploymentsTest extends TestCase $this->assertSame($expected, Deployments::rootDirectory($rootDirectory)); } - #[DataProvider('escapingRootDirectories')] - public function testRootDirectoryRefusesSegmentLeavingTheRepository(string $rootDirectory): void - { - try { - Deployments::rootDirectory($rootDirectory); - $this->fail('Expected the root directory to be refused before job submission'); - } catch (Exception $error) { - $this->assertSame(Exception::DEPLOYMENT_INVALID_ROOT_DIRECTORY, $error->getType()); - } - } - - public static function escapingRootDirectories(): \Iterator - { - yield 'parent' => ['..']; - yield 'parent path' => ['../etc']; - yield 'parent path with prefix' => ['./../etc']; - // Dropping the segment would silently build 'docs/x'; resolving it, - // 'x'. Neither is the directory the caller named. - yield 'interior parent' => ['docs/../x']; - yield 'escaping interior parent' => ['./docs/../../etc']; - } - public function testFunctionCommandIsDeploymentBuildCommands(): void { $resource = new Document(['$collection' => 'functions']); From ff7d4f7ffa38f1e760f996eecdf1252d7ffad767 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 17:31:30 +0530 Subject: [PATCH 07/38] chore: trim the root directory comments to the surrounding density --- src/Appwrite/Deployment/Deployments.php | 19 ++++--------------- .../VCSGitea/VCSGiteaConsoleClientTest.php | 8 ++------ tests/unit/Deployment/DeploymentsTest.php | 1 - 3 files changed, 6 insertions(+), 22 deletions(-) diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 5e634f5238..a3c983fbd9 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -294,21 +294,10 @@ readonly class Deployments } /** - * Canonicalize a root directory into the subdirectory path an artifact can - * match against a tree: no leading `./`, no surrounding slashes, `''` for - * the repository root. - * - * The console's directory picker and every shipped site template write the - * path with a `./` prefix (`./astro/starter`), while a hand-typed one is - * usually bare (`docs`) and sometimes trailing-slashed (`docs/`). All three - * name the same directory, so all three must produce the same subdir. - * - * Dropping whole `.` segments rather than trimming the character keeps a - * hidden directory intact — `ltrim('.github', '.')` would deploy `github`. - * - * `..` is left alone. Dropping it would silently build `docs/x` for a - * `docs/../x` that names `x`, and resolving it here would duplicate what - * the extractor already does with the path it is handed. + * Resolve the path forms a caller may store - '', '.', './docs', 'docs/' - + * to the plain subdirectory an artifact matches against a tree. Whole '.' + * segments go, not the character: ltrim('.github', '.') would deploy + * 'github'. '..' is left for the extractor to resolve. */ public static function rootDirectory(string $rootDirectory): string { diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index ff84f95872..29a5c9f317 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -134,8 +134,6 @@ final class VCSGiteaConsoleClientTest extends Scope $this->gitHelper('git add docs && git commit -m "Add nested function"', $workdir); $this->gitHelper('git push origin main', $workdir); - // The console's directory picker writes the path in this form; it names - // the same directory as 'docs/nested'. $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, @@ -175,10 +173,8 @@ final class VCSGiteaConsoleClientTest extends Scope $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); - // A duplicate reads the root directory back off the deployment it - // copies, so this only builds if the push-created deployment persisted - // one. Building from the repository root instead fails outright: the - // root holds only the auto-init README, no entrypoint. + // A duplicate reads the root directory off the deployment it copies, so + // this only builds if the push persisted one. $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index ad66431dab..197ffcb85a 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -51,7 +51,6 @@ final class DeploymentsTest extends TestCase yield 'shipped site template' => ['./astro/starter', 'astro/starter']; yield 'hidden directory' => ['.github', '.github']; yield 'dot-prefixed name' => ['..foo', '..foo']; - // Left for the extractor to resolve; dropping it would build 'docs/x'. yield 'parent' => ['docs/../x', 'docs/../x']; yield 'parent with prefix' => ['./docs/../x', 'docs/../x']; yield 'nested hidden directory' => ['./.github/actions', '.github/actions']; From 8dd9227c1ce3d03d4c2e5e676c77d6c77f6325d8 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Wed, 9 Sep 2026 17:37:50 +0530 Subject: [PATCH 08/38] test(vcs): group the nested root directory assertions --- tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index 29a5c9f317..b48ebc0ab7 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -112,6 +112,9 @@ final class VCSGiteaConsoleClientTest extends Scope public function testCreateDeploymentFromNestedRootDirectory(): void { + /** + * Test for SUCCESS + */ $projectId = $this->getProject()['$id']; $installationId = $this->createInstallationHelper()['$id']; From 9d4363d869457a717a9db80b7c78f094e889b452 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Mon, 14 Sep 2026 11:32:27 +0530 Subject: [PATCH 09/38] fix(deployments): preserve source roots on legacy redeployments --- src/Appwrite/Deployment/Deployments.php | 2 + .../Http/Deployments/Duplicate/Create.php | 3 +- .../Http/Deployments/Duplicate/Create.php | 3 +- .../VCSGitea/VCSGiteaConsoleClientTest.php | 93 ++++++++++++-- tests/unit/Deployment/DeploymentsTest.php | 115 ++++++++++++++++++ 5 files changed, 203 insertions(+), 13 deletions(-) diff --git a/src/Appwrite/Deployment/Deployments.php b/src/Appwrite/Deployment/Deployments.php index 3cc4cef5b1..4459522724 100644 --- a/src/Appwrite/Deployment/Deployments.php +++ b/src/Appwrite/Deployment/Deployments.php @@ -162,6 +162,8 @@ readonly class Deployments string $ref, string $rootDirectory = '', ): Document { + $deployment->setAttribute('providerRootDirectory', $rootDirectory); + if ($vcs->supportsRepositoryArchives()) { return $this->createFromUrl( $resource, diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php index 5f98bbf24a..412fd7c45c 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php @@ -164,7 +164,8 @@ class Create extends Action $owner, $repository, $ref, - $deployment->getAttribute('providerRootDirectory', ''), + // Older connected deployments did not snapshot their source root. + $deployment->getAttribute('providerRootDirectory') ?? $function->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php index f9a81f494e..ab648640ac 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php @@ -189,7 +189,8 @@ class Create extends Action $owner, $repository, $ref, - $deployment->getAttribute('providerRootDirectory', ''), + // Older connected deployments did not snapshot their source root. + $deployment->getAttribute('providerRootDirectory') ?? $site->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index f55e863118..ad69a917d4 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -4,13 +4,20 @@ declare(strict_types=1); namespace Tests\E2E\Services\VCSGitea; +use Appwrite\Database\Factory; use Appwrite\Tests\Async\Exceptions\Critical; use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; +use Utopia\Cache\Adapter\Pool as CachePool; +use Utopia\Cache\Adapter\Sharding; +use Utopia\Cache\Cache; +use Utopia\Config\Config; +use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; +use Utopia\Database\Validator\Authorization; use Utopia\System\System; final class VCSGiteaConsoleClientTest extends Scope @@ -116,6 +123,10 @@ final class VCSGiteaConsoleClientTest extends Scope * Test for SUCCESS */ $projectId = $this->getProject()['$id']; + $headers = \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()); $installationId = $this->createInstallationHelper()['$id']; $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ @@ -133,8 +144,10 @@ final class VCSGiteaConsoleClientTest extends Scope . '/' . self::GITEA_USERNAME . '/' . $repositoryName . '.git'; $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); - $this->writeFunctionHelper($workdir, 'gitea-nested-v1', 'docs/nested'); - $this->gitHelper('git add docs && git commit -m "Add nested function"', $workdir); + \mkdir($workdir . '/docs/nested', 0o777, true); + \file_put_contents($workdir . '/index.js', "module.exports = async (context) => context.res.send('gitea-root:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); + \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v1:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); + $this->gitHelper('git add index.js docs && git commit -m "Add nested function"', $workdir); $this->gitHelper('git push origin main', $workdir); $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ @@ -166,27 +179,82 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1'), 30000, 1000); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1:./docs/nested/'), 30000, 1000); $knownIds = $this->listDeploymentIdsHelper($functionId); - $this->writeFunctionHelper($workdir, 'gitea-nested-v2', 'docs/nested'); + \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v2:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); $this->gitHelper('git add docs && git commit -m "Update nested function"', $workdir); $this->gitHelper('git push origin main', $workdir); $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $webhookDeploymentId), 30000, 1000); - // A duplicate reads the root directory off the deployment it copies, so - // this only builds if the push persisted one. - $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ + // Upgrade fixture: deployments created before source roots were saved + // have NULL here. This metadata has no public update endpoint. + $seed = function (?string $root) use ($projectId, $webhookDeploymentId) { + global $register; + $pools = $register->get('pools'); + $cache = new Cache(new Sharding(\array_map( + fn (string $name) => new CachePool($pools->get($name)), + Config::getParam('pools-cache', []), + ))); + $authorization = new Authorization(); + $factory = new Factory($pools, $cache, $authorization); + + $authorization->skip(function () use ($factory, $projectId, $webhookDeploymentId, $root) { + $project = $factory->platform()->getDocument('projects', $projectId); + $database = $factory->project($project); + $database->updateDocument('deployments', $webhookDeploymentId, new Document([ + 'providerRootDirectory' => $root, + ])); + $database->purgeCachedDocument('deployments', $webhookDeploymentId); + $this->assertSame($root, $database->getDocument('deployments', $webhookDeploymentId)->getAttribute('providerRootDirectory')); + }); + }; + if (\Swoole\Coroutine::getCid() >= 0) { + $seed(null); + } else { + \Swoole\Coroutine\run(fn () => $seed(null)); + } + + $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ 'deploymentId' => $webhookDeploymentId, ]); $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $duplicate['body']['$id']), 30000, 1000); + + // The healed deployment must retain its source root after settings change. + $updated = $this->client->call(Client::METHOD_PUT, '/functions/' . $functionId, $headers, [ + 'name' => 'Gitea nested VCS', + 'execute' => [Role::any()->toString()], + 'providerRootDirectory' => 'missing', + ]); + $this->assertEquals(200, $updated['headers']['status-code'], \json_encode($updated['body'])); + $this->assertSame('missing', $updated['body']['providerRootDirectory']); + + $preserved = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ + 'deploymentId' => $duplicate['body']['$id'], + ]); + $this->assertEquals(202, $preserved['headers']['status-code'], \json_encode($preserved['body'])); + $this->waitForDeploymentReadyHelper($functionId, $preserved['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $preserved['body']['$id']), 30000, 1000); + + // An explicit empty snapshot names the repository root, even when the + // function now points elsewhere. It must not take the legacy fallback. + if (\Swoole\Coroutine::getCid() >= 0) { + $seed(''); + } else { + \Swoole\Coroutine\run(fn () => $seed('')); + } + $root = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ + 'deploymentId' => $webhookDeploymentId, + ]); + $this->assertEquals(202, $root['headers']['status-code'], \json_encode($root['body'])); + $this->waitForDeploymentReadyHelper($functionId, $root['body']['$id']); + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-root:', $root['body']['$id']), 30000, 1000); } public function testClosePullRequestRemovesAuthorization(): void @@ -522,7 +590,7 @@ final class VCSGiteaConsoleClientTest extends Scope return $response['body']['deployments'] ?? []; } - private function assertExecutionOutputHelper(string $functionId, string $output): void + private function assertExecutionOutputHelper(string $functionId, string $output, ?string $deploymentId = null): void { $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', \array_merge([ 'content-type' => 'application/json', @@ -534,6 +602,9 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(201, $execution['headers']['status-code'], \json_encode($execution['body'])); $this->assertEquals('completed', $execution['body']['status'] ?? '', \json_encode($execution['body'])); $this->assertEquals($output, $execution['body']['responseBody'] ?? ''); + if ($deploymentId !== null) { + $this->assertSame($deploymentId, $execution['body']['deploymentId']); + } } private function buildGiteaState(string $projectId, string $success, string $failure): string diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index 197ffcb85a..a662753694 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -6,13 +6,65 @@ namespace Tests\Unit\Deployment; use Appwrite\Deployment\Deployments; use Appwrite\Extend\Exception; +use OpenRuntimes\Orchestrator\Jobs; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use Psr\Http\Client\ClientInterface; +use Psr\Http\Message\RequestInterface; +use Psr\Http\Message\ResponseInterface; use Utopia\Config\Config; +use Utopia\Database\Database; use Utopia\Database\Document; +use Utopia\Psr7\Response; +use Utopia\Psr7\Stream; +use Utopia\VCS\Adapter\Git\GitHub; final class DeploymentsTest extends TestCase { + public static function sources(): \Iterator + { + yield 'archive subdirectory' => [true, 'functions/api']; + yield 'archive root' => [true, '']; + yield 'clone subdirectory' => [false, 'functions/api']; + yield 'clone root' => [false, '']; + } + + #[DataProvider('sources')] + public function testCreateVcsDeploymentPersistsSourceRoot(bool $archives, string $root): void + { + $previousKey = \getenv('_APP_OPENSSL_KEY_V1'); + \putenv('_APP_OPENSSL_KEY_V1=unit-test-key'); + + try { + $database = new VcsDeploymentDatabase(); + $client = new VcsBuildClient(); + $deployments = new Deployments(new Jobs($client), $database, new Document(['$id' => 'project', 'region' => 'default']), ['apiHostname' => 'localhost']); + + $deployment = $deployments->createFromVcs( + new Document([ + '$id' => 'function', + '$collection' => 'functions', + 'runtime' => \array_key_first(Config::getParam('runtimes-v2')), + 'providerRootDirectory' => 'changed/function/setting', + ]), + new Document(['$id' => 'deployment', 'buildCommands' => 'npm ci']), + new VcsRepository($archives), + 'owner', + 'repository', + 'commit', + $root, + ); + + $this->assertSame('waiting', $deployment->getAttribute('status')); + $this->assertSame($root, $database->getDocument('deployments', 'deployment')->getAttribute('providerRootDirectory')); + $this->assertSame($root, $client->payload['environment']['APPWRITE_VCS_ROOT_DIRECTORY']); + $artifacts = \array_column($client->payload['artifacts'], null, 'id'); + $this->assertSame($root, $artifacts[$archives ? 'extract' : 'source']['subdir'] ?? ''); + } finally { + \putenv($previousKey === false ? '_APP_OPENSSL_KEY_V1' : '_APP_OPENSSL_KEY_V1=' . $previousKey); + } + } + public function testSiteCommandIncludesFrameworkAndDeploymentCommands(): void { Config::setParam('frameworks', [ @@ -251,3 +303,66 @@ final readonly class ExposedDeployments extends Deployments return static::payload($project, $resource, $deployment, $platform, $source); } } + +final class VcsDeploymentDatabase extends Database +{ + private Document $deployment; + + public function __construct() + { + } + + public function createDocument(string $collection, Document $document): Document + { + $this->deployment = clone $document; + $this->deployment->setAttribute('$sequence', '1'); + + return clone $this->deployment; + } + + public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE, ?callable $onNext = null, ?callable $onError = null): int + { + $this->deployment->setAttributes($updates->getArrayCopy()); + + return 1; + } + + public function getDocument(string $collection, string $id, array $queries = [], bool $forUpdate = false): Document + { + return clone $this->deployment; + } +} + +final class VcsBuildClient implements ClientInterface +{ + public array $payload = []; + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->payload = \json_decode((string) $request->getBody(), true, flags: JSON_THROW_ON_ERROR); + + return new Response(202, body: new Stream('{"id":"build","status":"accepted"}')); + } +} + +final class VcsRepository extends GitHub +{ + public function __construct(private bool $archives) + { + } + + public function supportsRepositoryArchives(): bool + { + return $this->archives; + } + + public function getRepositoryPresignedUrl(string $owner, string $repositoryName, string $ref = '', string $format = 'tarball'): string + { + return 'https://vcs.example/source.tar.gz'; + } + + public function getRepositoryCloneUrl(string $owner, string $repositoryName): string + { + return 'https://vcs.example/source.git'; + } +} From 053e693cf3767cfb5f63f1b7fef9ff699131bd07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 12:53:27 +0200 Subject: [PATCH 10/38] feat(policies): add password pwned project policy Adds a `password-pwned` project policy, disabled by default, that checks new passwords against the Have I Been Pwned range API using k-anonymity. Only the first five characters of the SHA-1 hash leave the server. When enabled, breached passwords are rejected with `password_pwned` on account create, account password update, account recovery update, users create, and users password update. Hashed imports are unaffected. The check fails open when the service is unreachable. The endpoint is configurable via `_APP_PWNED_PASSWORDS_ENDPOINT`; the dev and CI `.env` points it at a new mock range route so automated tests never contact the real service. Co-Authored-By: Claude Fable 5.1 --- .env | 1 + app/config/errors.php | 5 + app/config/variables.php | 9 + app/controllers/api/account.php | 22 ++ app/controllers/mock.php | 32 ++ app/init/models.php | 2 + docker-compose.yml | 1 + src/Appwrite/Auth/Validator/PasswordPwned.php | 129 ++++++++ src/Appwrite/Extend/Exception.php | 1 + .../Organization/Http/Projects/Create.php | 1 + .../Project/Http/Project/Policies/Get.php | 8 + .../Project/Policies/PasswordPwned/Update.php | 85 +++++ .../Project/Http/Project/Policies/XList.php | 4 + .../Modules/Project/Services/Http.php | 2 + .../Modules/Projects/Http/Projects/Create.php | 1 + src/Appwrite/Platform/Modules/Users/Base.php | 9 + .../Users/Http/Users/Password/Update.php | 9 + src/Appwrite/Utopia/Response.php | 1 + .../Utopia/Response/Model/PolicyList.php | 1 + .../Response/Model/PolicyPasswordPwned.php | 34 ++ tests/e2e/Services/Project/PoliciesBase.php | 72 ++++ .../PoliciesPasswordPwnedIntegrationTest.php | 311 ++++++++++++++++++ .../unit/Auth/Validator/PasswordPwnedTest.php | 156 +++++++++ 23 files changed, 896 insertions(+) create mode 100644 src/Appwrite/Auth/Validator/PasswordPwned.php create mode 100644 src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php create mode 100644 src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php create mode 100644 tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php create mode 100644 tests/unit/Auth/Validator/PasswordPwnedTest.php diff --git a/.env b/.env index a09c1da12d..12b71fab58 100644 --- a/.env +++ b/.env @@ -175,6 +175,7 @@ _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET= _APP_PROJECT_REGIONS=default _APP_GEO_SECRET=your-secret-key _APP_GEO_ENDPOINT=http://appwrite-geo/v1 +_APP_PWNED_PASSWORDS_ENDPOINT=http://localhost/v1/mock/tests/general/pwned-passwords _APP_VCS_GITHUB_APP_ID= _APP_VCS_GITHUB_APP_NAME= _APP_VCS_GITHUB_CLIENT_ID= diff --git a/app/config/errors.php b/app/config/errors.php index b8669b0890..438edfa9df 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -271,6 +271,11 @@ return [ 'description' => 'The password you are trying to use contains references to your name, email, phone or userID. For your security, please choose a different password and try again.', 'code' => 400, ], + Exception::USER_PASSWORD_PWNED => [ + 'name' => Exception::USER_PASSWORD_PWNED, + 'description' => 'The password you are trying to use has been exposed in a known data breach. For your security, please choose a different password and try again.', + 'code' => 400, + ], Exception::USER_SESSION_NOT_FOUND => [ 'name' => Exception::USER_SESSION_NOT_FOUND, 'description' => 'The current user session could not be found.', diff --git a/app/config/variables.php b/app/config/variables.php index 4421d51ba0..1245758fca 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -483,6 +483,15 @@ return [ 'required' => false, 'question' => '', 'filter' => 'token' + ], + [ + 'name' => '_APP_PWNED_PASSWORDS_ENDPOINT', + 'description' => 'Endpoint of the Have I Been Pwned range API used by the password pwned project policy. Only the first five characters of a password SHA-1 hash are sent to this endpoint. Defaults to the public Have I Been Pwned service.', + 'introduction' => 'TBD', + 'default' => 'https://api.pwnedpasswords.com/range', + 'required' => false, + 'question' => '', + 'filter' => '' ] ], ], diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 4bad06ca4e..2c66365cb2 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -7,6 +7,7 @@ use Appwrite\Auth\Validator\EmailWhitelist; use Appwrite\Auth\Validator\Password; use Appwrite\Auth\Validator\PasswordDictionary; use Appwrite\Auth\Validator\PasswordHistory; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PasswordStrength; use Appwrite\Auth\Validator\PersonalData; use Appwrite\Auth\Validator\Phone; @@ -361,6 +362,13 @@ Http::post('/v1/account') } } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $passwordHistory = $project->getAttribute('auths', [])['passwordHistory'] ?? 0; @@ -3483,6 +3491,13 @@ Http::patch('/v1/account/password') } } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $user @@ -4137,6 +4152,13 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $sessions = $profile->getAttribute('sessions', []); diff --git a/app/controllers/mock.php b/app/controllers/mock.php index 9d91cccde4..6470b4eafa 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -501,3 +501,35 @@ Http::shutdown() $response->dynamic(new Document(['result' => \implode(',', $methods) . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK); }); + +Http::get('/v1/mock/tests/general/pwned-passwords/:prefix') + ->desc('Pwned Passwords range') + ->groups(['mock']) + ->label('scope', 'public') + ->label('docs', false) + ->label('mock', true) + ->param('prefix', '', new Text(5, 5), 'First five characters of the SHA-1 password hash.') + ->inject('response') + ->action(function (string $prefix, Response $response) { + // Mirrors the Have I Been Pwned range API: every leaked hash sharing the + // requested prefix comes back as `SUFFIX:COUNT`, one per line. + $leaked = [ + 'Password123!' => 12345, + 'Summer2024!' => 678, + 'letmein1234' => 9, + ]; + + $prefix = \strtoupper($prefix); + $lines = []; + foreach ($leaked as $password => $count) { + $hash = \strtoupper(\sha1($password)); + if (\str_starts_with($hash, $prefix)) { + $lines[] = \substr($hash, 5) . ':' . $count; + } + } + + // Padded entries carry a count of 0 and must never be treated as a breach + $lines[] = \str_repeat('0', 35) . ':0'; + + $response->text(\implode("\r\n", $lines)); + }); diff --git a/app/init/models.php b/app/init/models.php index 9dcfc5ef07..296b496ede 100644 --- a/app/init/models.php +++ b/app/init/models.php @@ -181,6 +181,7 @@ use Appwrite\Utopia\Response\Model\PolicyMFAFactors; use Appwrite\Utopia\Response\Model\PolicyPasswordDictionary; use Appwrite\Utopia\Response\Model\PolicyPasswordHistory; use Appwrite\Utopia\Response\Model\PolicyPasswordPersonalData; +use Appwrite\Utopia\Response\Model\PolicyPasswordPwned; use Appwrite\Utopia\Response\Model\PolicyPasswordStrength; use Appwrite\Utopia\Response\Model\PolicySessionAlert; use Appwrite\Utopia\Response\Model\PolicySessionDuration; @@ -473,6 +474,7 @@ Response::setModel(new PolicyPasswordDictionary()); Response::setModel(new PolicyPasswordHistory()); Response::setModel(new PolicyPasswordStrength()); Response::setModel(new PolicyPasswordPersonalData()); +Response::setModel(new PolicyPasswordPwned()); Response::setModel(new PolicySessionAlert()); Response::setModel(new PolicySessionDuration()); Response::setModel(new PolicySessionInvalidation()); diff --git a/docker-compose.yml b/docker-compose.yml index 333bcd9e61..8c9f5446f8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -254,6 +254,7 @@ services: - _APP_MIGRATION_HOST - _APP_GEO_SECRET - _APP_GEO_ENDPOINT + - _APP_PWNED_PASSWORDS_ENDPOINT - _APP_LIMIT_DATABASE_BATCH - _APP_DOCUMENTSDB - _APP_VECTORSDB diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php new file mode 100644 index 0000000000..656ec9283b --- /dev/null +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -0,0 +1,129 @@ +endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/'); + $this->client = $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + } + + /** + * Get Description. + * + * Returns validator description + * + * @return string + */ + public function getDescription(): string + { + return 'Password must not have been exposed in a known data breach.'; + } + + /** + * Is valid. + * + * @param mixed $value + * + * @return bool + */ + public function isValid($value): bool + { + if (!parent::isValid($value)) { + return false; + } + + if ($this->allowEmpty && \strlen($value) === 0) { + return true; + } + + $hash = \strtoupper(\sha1($value)); + $prefix = \substr($hash, 0, self::PREFIX_LENGTH); + $suffix = \substr($hash, self::PREFIX_LENGTH); + + try { + $response = $this->client + ->addHeader('Add-Padding', 'true') + ->fetch($this->endpoint . '/' . $prefix); + } catch (\Throwable) { + return true; + } + + if ($response->getStatusCode() !== 200) { + return true; + } + + // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches + foreach (\explode("\n", $response->text()) as $line) { + $line = \trim($line); + if ($line === '') { + continue; + } + + $separator = \strpos($line, ':'); + if ($separator === false) { + continue; + } + + $candidate = \strtoupper(\substr($line, 0, $separator)); + $count = (int) \substr($line, $separator + 1); + + if ($candidate === $suffix && $count > 0) { + return false; + } + } + + return true; + } + + /** + * Is array + * + * Function will return true if object is array. + * + * @return bool + */ + public function isArray(): bool + { + return false; + } + + /** + * Get Type + * + * Returns validator type. + * + * @return string + */ + public function getType(): string + { + return self::TYPE_STRING; + } +} diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index b9af9cecb4..cb58ced5db 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -83,6 +83,7 @@ class Exception extends \Exception public const string USER_NOT_FOUND = 'user_not_found'; public const string USER_PASSWORD_RECENTLY_USED = 'password_recently_used'; public const string USER_PASSWORD_PERSONAL_DATA = 'password_personal_data'; + public const string USER_PASSWORD_PWNED = 'password_pwned'; public const string USER_EMAIL_ALREADY_EXISTS = 'user_email_already_exists'; public const string USER_EMAIL_DISPOSABLE = 'user_email_disposable'; public const string USER_EMAIL_FREE = 'user_email_free'; diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index 94e246a7ee..6d2b5c2037 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -91,6 +91,7 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, + 'passwordPwned' => false, 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php index a88237c360..fa943764b0 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php @@ -79,6 +79,7 @@ class Get extends Action 'password-history' => Response::MODEL_POLICY_PASSWORD_HISTORY, 'password-strength' => Response::MODEL_POLICY_PASSWORD_STRENGTH, 'password-personal-data' => Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA, + 'password-pwned' => Response::MODEL_POLICY_PASSWORD_PWNED, 'session-alert' => Response::MODEL_POLICY_SESSION_ALERT, 'session-duration' => Response::MODEL_POLICY_SESSION_DURATION, 'session-invalidation' => Response::MODEL_POLICY_SESSION_INVALIDATION, @@ -134,6 +135,13 @@ class Get extends Action ]), Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA, ], + 'password-pwned' => [ + new Document([ + '$id' => 'password-pwned', + 'enabled' => $auths['passwordPwned'] ?? false, + ]), + Response::MODEL_POLICY_PASSWORD_PWNED, + ], 'session-alert' => [ new Document([ '$id' => 'session-alert', diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php new file mode 100644 index 0000000000..79a02f5423 --- /dev/null +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -0,0 +1,85 @@ +setHttpMethod(Action::HTTP_REQUEST_METHOD_PATCH) + ->setHttpPath('/v1/project/policies/password-pwned') + ->desc('Update password pwned policy') + ->groups(['api', 'project']) + ->label('scope', ['policies.write', 'project.policies.write']) + ->label('event', 'projects.[projectId].policies.[policy].update') + ->label('audits.event', 'projects.[projectId].policies.[policy].update') + ->label('audits.resource', 'project/{response.$id}') + ->label('sdk', new Method( + namespace: 'project', + group: 'policies', + name: 'updatePasswordPwnedPolicy', + description: <<param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true if you want password change to block passwords exposed in known data breaches, or false to allow them. When changing this policy, existing passwords remain valid.') + ->inject('response') + ->inject('dbForPlatform') + ->inject('project') + ->inject('authorization') + ->inject('queueForEvents') + ->callback($this->action(...)); + } + + public function action( + bool $enabled, + Response $response, + Database $dbForPlatform, + Document $project, + Authorization $authorization, + Event $queueForEvents, + ): void { + $auths = $project->getAttribute('auths', []); + $auths['passwordPwned'] = $enabled; + + $updates = new Document([ + 'auths' => $auths, + ]); + + $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); + $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); + + $queueForEvents + ->setParam('projectId', $project->getId()) + ->setParam('policy', 'password-pwned'); + + $response->dynamic($project, Response::MODEL_PROJECT); + } +} diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php index 0bcf3ffcbc..83693cff33 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php @@ -116,6 +116,10 @@ class XList extends Action '$id' => 'password-personal-data', 'enabled' => $auths['personalDataCheck'] ?? false, ]), + new Document([ + '$id' => 'password-pwned', + 'enabled' => $auths['passwordPwned'] ?? false, + ]), new Document([ '$id' => 'session-alert', 'enabled' => $auths['sessionAlerts'] ?? false, diff --git a/src/Appwrite/Platform/Modules/Project/Services/Http.php b/src/Appwrite/Platform/Modules/Project/Services/Http.php index 0cdf4238ee..3e180afc84 100644 --- a/src/Appwrite/Platform/Modules/Project/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Project/Services/Http.php @@ -91,6 +91,7 @@ use Appwrite\Platform\Modules\Project\Http\Project\Policies\MFAFactors\Update as use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordDictionary\Update as UpdatePasswordDictionaryPolicy; use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordHistory\Update as UpdatePasswordHistoryPolicy; use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPersonalData\Update as UpdatePasswordPersonalDataPolicy; +use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPwned\Update as UpdatePasswordPwnedPolicy; use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordStrength\Update as UpdatePasswordStrengthPolicy; use Appwrite\Platform\Modules\Project\Http\Project\Policies\SessionAlert\Update as UpdateSessionAlertPolicy; use Appwrite\Platform\Modules\Project\Http\Project\Policies\SessionDuration\Update as UpdateSessionDurationPolicy; @@ -184,6 +185,7 @@ class Http extends Service $this->addAction(UpdatePasswordHistoryPolicy::getName(), new UpdatePasswordHistoryPolicy()); $this->addAction(UpdatePasswordStrengthPolicy::getName(), new UpdatePasswordStrengthPolicy()); $this->addAction(UpdatePasswordPersonalDataPolicy::getName(), new UpdatePasswordPersonalDataPolicy()); + $this->addAction(UpdatePasswordPwnedPolicy::getName(), new UpdatePasswordPwnedPolicy()); $this->addAction(UpdateSessionAlertPolicy::getName(), new UpdateSessionAlertPolicy()); $this->addAction(UpdateSessionDurationPolicy::getName(), new UpdateSessionDurationPolicy()); $this->addAction(UpdateSessionInvalidationPolicy::getName(), new UpdateSessionInvalidationPolicy()); diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php index f65ca3eae9..1606990885 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -88,6 +88,7 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, + 'passwordPwned' => false, 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Users/Base.php b/src/Appwrite/Platform/Modules/Users/Base.php index 232d4fd52d..a251925e55 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\Users; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PersonalData; use Appwrite\Extend\Exception; use Appwrite\Hooks\Hooks; @@ -18,6 +19,7 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Query; use Utopia\Emails\Email; +use Utopia\System\System; class Base extends Action { @@ -147,6 +149,13 @@ class Base extends Action ]); if (!$isHashed && !empty($password)) { + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($plaintextPassword)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $plaintextPassword, &$user, true]); } diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index 53651bb885..52647cd924 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -4,6 +4,7 @@ namespace Appwrite\Platform\Modules\Users\Http\Users\Password; use Appwrite\Auth\Validator\PasswordDictionary; use Appwrite\Auth\Validator\PasswordHistory; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PasswordStrength; use Appwrite\Auth\Validator\PersonalData; use Appwrite\Event\Event; @@ -22,6 +23,7 @@ use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Validator\UID; use Utopia\Platform\Scope\HTTP; +use Utopia\System\System; use Utopia\Validator; use Utopia\Validator\AllOf; @@ -84,6 +86,13 @@ class Update extends Action } } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'), allowEmpty: true); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + if (\strlen($password) === 0) { $user ->setAttribute('password', '') diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index 140314d326..6a9f667d6b 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -264,6 +264,7 @@ class Response extends SwooleResponse public const MODEL_POLICY_PASSWORD_HISTORY = 'policyPasswordHistory'; public const MODEL_POLICY_PASSWORD_STRENGTH = 'policyPasswordStrength'; public const MODEL_POLICY_PASSWORD_PERSONAL_DATA = 'policyPasswordPersonalData'; + public const MODEL_POLICY_PASSWORD_PWNED = 'policyPasswordPwned'; public const MODEL_POLICY_SESSION_ALERT = 'policySessionAlert'; public const MODEL_POLICY_SESSION_DURATION = 'policySessionDuration'; public const MODEL_POLICY_SESSION_INVALIDATION = 'policySessionInvalidation'; diff --git a/src/Appwrite/Utopia/Response/Model/PolicyList.php b/src/Appwrite/Utopia/Response/Model/PolicyList.php index 894324a5d4..808e93c815 100644 --- a/src/Appwrite/Utopia/Response/Model/PolicyList.php +++ b/src/Appwrite/Utopia/Response/Model/PolicyList.php @@ -34,6 +34,7 @@ class PolicyList extends Model Response::MODEL_POLICY_PASSWORD_HISTORY, Response::MODEL_POLICY_PASSWORD_STRENGTH, Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA, + Response::MODEL_POLICY_PASSWORD_PWNED, Response::MODEL_POLICY_SESSION_ALERT, Response::MODEL_POLICY_SESSION_DURATION, Response::MODEL_POLICY_SESSION_INVALIDATION, diff --git a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php new file mode 100644 index 0000000000..f20511bb0b --- /dev/null +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -0,0 +1,34 @@ + 'password-pwned', + ]; + + public function __construct() + { + parent::__construct(); + + $this->addRule('enabled', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether password pwned policy is enabled.', + 'default' => false, + 'example' => true, + ]); + } + + public function getName(): string + { + return 'Policy Password Pwned'; + } + + public function getType(): string + { + return Response::MODEL_POLICY_PASSWORD_PWNED; + } +} diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index 43cbe1a53e..7382d65763 100644 --- a/tests/e2e/Services/Project/PoliciesBase.php +++ b/tests/e2e/Services/Project/PoliciesBase.php @@ -17,6 +17,7 @@ trait PoliciesBase 'password-history' => ['total'], 'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'], 'password-personal-data' => ['enabled'], + 'password-pwned' => ['enabled'], 'session-alert' => ['enabled'], 'session-duration' => ['duration'], 'session-invalidation' => ['enabled'], @@ -635,6 +636,70 @@ trait PoliciesBase $this->assertSame(401, $response['headers']['status-code']); } + // ========================================================================= + // Password Pwned Policy + // ========================================================================= + + public function testUpdatePasswordPwnedPolicyEnable(): void + { + $response = $this->updatePasswordPwnedPolicy(true); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(200, $policy['headers']['status-code']); + $this->assertSame(true, $policy['body']['enabled']); + + // Cleanup + $this->updatePasswordPwnedPolicy(false); + } + + public function testUpdatePasswordPwnedPolicyDisable(): void + { + $this->updatePasswordPwnedPolicy(true); + + $response = $this->updatePasswordPwnedPolicy(false); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(200, $policy['headers']['status-code']); + $this->assertSame(false, $policy['body']['enabled']); + } + + public function testUpdatePasswordPwnedPolicyDisabledByDefault(): void + { + $policy = $this->getPolicy('password-pwned'); + + $this->assertSame(200, $policy['headers']['status-code']); + $this->assertSame('password-pwned', $policy['body']['$id']); + $this->assertSame(false, $policy['body']['enabled']); + } + + public function testUpdatePasswordPwnedPolicyInvalidType(): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), [ + 'enabled' => 'not-a-boolean', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + } + + public function testUpdatePasswordPwnedPolicyMissingParam(): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []); + + $this->assertSame(400, $response['headers']['status-code']); + } + + public function testUpdatePasswordPwnedPolicyWithoutAuth(): void + { + $response = $this->updatePasswordPwnedPolicy(true, false); + + $this->assertSame(401, $response['headers']['status-code']); + } + // ========================================================================= // Session Alert Policy // ========================================================================= @@ -1329,6 +1394,13 @@ trait PoliciesBase ]); } + protected function updatePasswordPwnedPolicy(bool $enabled, bool $authenticated = true): mixed + { + return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), [ + 'enabled' => $enabled, + ]); + } + protected function updateSessionAlertPolicy(bool $enabled, bool $authenticated = true): mixed { return $this->client->call(Client::METHOD_PATCH, '/project/policies/session-alert', $this->buildHeaders($authenticated), [ diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php new file mode 100644 index 0000000000..5b0c62d6e7 --- /dev/null +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -0,0 +1,311 @@ +updatePolicy(false); + + /** + * Test for SUCCESS + */ + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_off_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Pwned Off User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + $this->assertNotEmpty($user['body']['$id']); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $user['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + } + + public function testCreateUserWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_on_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Pwned On User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_clean_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Clean User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + // Importing an already hashed password never exposes the plaintext, so the policy cannot apply + $response = $this->client->call(Client::METHOD_POST, '/users/sha', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_hashed_' . \uniqid() . '@localhost.test', + 'password' => \sha1(self::PWNED_PASSWORD), + 'passwordVersion' => 'sha1', + 'name' => 'Hashed User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + $this->updatePolicy(false); + } + + public function testUpdateUserPasswordWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_update_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Update User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + $userId = $user['body']['$id']; + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [ + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [ + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + // Clearing the password is not a password to check + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [ + 'password' => '', + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $this->updatePolicy(false); + } + + public function testCreateAccountWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_account_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Pwned Account', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_account_clean_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Clean Account', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + $this->updatePolicy(false); + } + + public function testUpdateAccountPasswordWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + $email = 'pwned_session_' . \uniqid() . '@localhost.test'; + $password = $this->cleanPassword(); + + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $password, + 'name' => 'Session Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $headers = \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session['cookies']['a_session_' . $this->getProject()['$id']], + ]); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => self::PWNED_PASSWORD, + 'oldPassword' => $password, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $this->cleanPassword(), + 'oldPassword' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $this->updatePolicy(false); + } + + public function testUpdateAccountRecoveryWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + $email = 'pwned_recovery_' . \uniqid() . '@localhost.test'; + + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $this->cleanPassword(), + 'name' => 'Recovery Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + $userId = $account['body']['$id']; + + $recovery = $this->client->call(Client::METHOD_POST, '/account/recovery', $this->clientHeaders(), [ + 'email' => $email, + 'url' => 'http://localhost/recovery', + ]); + + $this->assertSame(201, $recovery['headers']['status-code']); + + $lastEmail = $this->getLastEmailByAddress($email, function ($email) { + $this->assertStringContainsString('Password Reset', (string) $email['subject']); + }); + $secret = $this->extractQueryParamsFromEmailLink($lastEmail['html'])['secret']; + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [ + 'userId' => $userId, + 'secret' => $secret, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [ + 'userId' => $userId, + 'secret' => $secret, + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $this->updatePolicy(false); + } + + private function updatePolicy(bool $enabled): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->serverHeaders(), [ + 'enabled' => $enabled, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + } + + /** + * @return array + */ + private function serverHeaders(): array + { + return \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()); + } + + /** + * @return array + */ + private function clientHeaders(): array + { + return [ + 'origin' => 'http://localhost', + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ]; + } + + private function cleanPassword(): string + { + return 'Clean-' . \uniqid() . '-Pw!'; + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php new file mode 100644 index 0000000000..ae74d6b461 --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -0,0 +1,156 @@ +range([self::LEAKED => 42])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertFalse($validator->isValid(self::LEAKED)); + } + + public function testCleanPasswordIsAccepted(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid('never-leaked-' . \uniqid())); + } + + public function testPaddedEntryWithZeroCountIsNotABreach(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 0])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testSuffixComparisonIgnoresCase(): void + { + $adapter = new RangeAdapter(body: \strtolower($this->range([self::LEAKED => 3]))); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertFalse($validator->isValid(self::LEAKED)); + } + + public function testOnlyHashPrefixLeavesTheServer(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('https://breaches.test/range/', new Client($adapter)); + + $validator->isValid(self::LEAKED); + + $hash = \strtoupper(\sha1(self::LEAKED)); + $this->assertCount(1, $adapter->requests); + $this->assertSame('https://breaches.test/range/' . \substr($hash, 0, 5), $adapter->requests[0]['url']); + $this->assertSame('GET', $adapter->requests[0]['method']); + $this->assertSame('true', $adapter->requests[0]['headers']['add-padding'] ?? null); + } + + public function testUnreachableServiceSkipsTheCheck(): void + { + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testUnexpectedStatusSkipsTheCheck(): void + { + $adapter = new RangeAdapter(statusCode: 503, body: $this->range([self::LEAKED => 42])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testBasePasswordRulesStillApply(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertFalse($validator->isValid('short')); + $this->assertFalse($validator->isValid(\str_repeat('p', 257))); + $this->assertFalse($validator->isValid('')); + $this->assertCount(0, $adapter->requests); + } + + public function testAllowEmptySkipsTheLookup(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter), allowEmpty: true); + + $this->assertTrue($validator->isValid('')); + $this->assertCount(0, $adapter->requests); + } + + public function testEmptyEndpointFallsBackToDefault(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('', new Client($adapter)); + + $validator->isValid(self::LEAKED); + + $this->assertStringStartsWith(PasswordPwned::ENDPOINT . '/', $adapter->requests[0]['url']); + } + + /** + * Builds a range response body the way the Have I Been Pwned API does: + * one `SUFFIX:COUNT` line per leaked hash, CRLF separated, plus padding. + * + * @param array $leaked password => breach count + */ + private function range(array $leaked): string + { + $lines = []; + foreach ($leaked as $password => $count) { + $lines[] = \substr(\strtoupper(\sha1((string) $password)), 5) . ':' . $count; + } + $lines[] = \str_repeat('0', 35) . ':0'; + + return \implode("\r\n", $lines); + } +} + +final class RangeAdapter implements Adapter +{ + /** @var array}> */ + public array $requests = []; + + public function __construct( + private int $statusCode = 200, + private string $body = '', + private ?\Throwable $failure = null, + ) { + } + + public function send( + string $url, + string $method, + mixed $body, + array $headers, + RequestOptions $options, + ?callable $chunkCallback = null + ): Response { + $this->requests[] = ['url' => $url, 'method' => $method, 'headers' => $headers]; + + if ($this->failure !== null) { + throw $this->failure; + } + + return new Response($this->statusCode, $this->body, []); + } +} From 9f2bc7d374cf73d923086ea058493868da86012a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 13:16:30 +0200 Subject: [PATCH 11/38] feat(policies): configurable pwned policy and anonymous conversion coverage Extends the `password-pwned` policy with options, all optional on update and preserving the others when omitted: - `forceReset` (default false): when true, signing in with a breached password fails with `user_password_reset_required` until it is reset. - `failClosed` (default true): reject the password with the new `general_pwned_passwords_unavailable` (503) when the breach service cannot be reached; when false the check is skipped. - `threshold` (default 1): minimum breach count before rejection. - `endpoint` (default empty): project-level range API endpoint, falling back to `_APP_PWNED_PASSWORDS_ENDPOINT`, then the public service. Validated as a public http(s) URL like webhook URLs. The validator is now built from the policy and registered as the `pwnedPasswords` request resource, caching range responses per prefix and endpoint for an hour through the cache library. Anonymous accounts setting their first password through the email or phone update endpoints now go through the same policies as account creation: strength, dictionary, personal data, pwned, and history. Existing passwords are only verified, never re-validated. Co-Authored-By: Claude Fable 5.1 --- app/config/errors.php | 5 + app/controllers/api/account.php | 103 +++- app/init/registers.php | 1 + app/init/resources/request.php | 5 + src/Appwrite/Auth/Validator/PasswordPwned.php | 99 +++- src/Appwrite/Extend/Exception.php | 1 + .../Organization/Http/Projects/Create.php | 8 +- .../Project/Http/Project/Policies/Get.php | 11 +- .../Project/Policies/PasswordPwned/Update.php | 50 +- .../Project/Http/Project/Policies/XList.php | 11 +- .../Modules/Projects/Http/Projects/Create.php | 8 +- src/Appwrite/Platform/Modules/Users/Base.php | 9 - .../Modules/Users/Http/Users/Create.php | 9 +- .../Users/Http/Users/Password/Update.php | 11 +- .../Response/Model/PolicyPasswordPwned.php | 37 +- tests/e2e/Services/Project/PoliciesBase.php | 103 +++- .../PoliciesPasswordPwnedIntegrationTest.php | 500 +++++++++++++++++- .../unit/Auth/Validator/PasswordPwnedTest.php | 127 ++++- 18 files changed, 970 insertions(+), 128 deletions(-) diff --git a/app/config/errors.php b/app/config/errors.php index 438edfa9df..70153f2e99 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -69,6 +69,11 @@ return [ 'description' => 'Phone provider is not configured. Please check the _APP_SMS_PROVIDER environment variable of your Appwrite server.', 'code' => 503, ], + Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE => [ + 'name' => Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, + 'description' => 'The breached password service could not be reached, so the password could not be verified. Please try again later.', + 'code' => 503, + ], Exception::GENERAL_ARGUMENT_INVALID => [ 'name' => Exception::GENERAL_ARGUMENT_INVALID, 'description' => 'The request contains one or more invalid arguments. Please refer to the endpoint documentation.', diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 2c66365cb2..7ddc1c1d10 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -317,7 +317,8 @@ Http::post('/v1/account') ->inject('authorization') ->inject('hooks') ->inject('plan') - ->action(function (string $userId, string $email, string $password, string $name, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Authorization $authorization, Hooks $hooks, array $plan) { + ->inject('pwnedPasswords') + ->action(function (string $userId, string $email, string $password, string $name, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Authorization $authorization, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords) { $email = \strtolower($email); if ('console' === $project->getId()) { @@ -362,11 +363,8 @@ Http::post('/v1/account') } } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); @@ -988,7 +986,8 @@ Http::post('/v1/account/sessions/email') ->inject('domainVerification') ->inject('cookieDomain') ->inject('authorization') - ->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Geo $geo, Event $queueForEvents, Bus $bus, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) { + ->inject('pwnedPasswords') + ->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Geo $geo, Event $queueForEvents, Bus $bus, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization, PasswordPwned $pwnedPasswords) { $email = \strtolower($email); $protocol = $request->getProtocol(); @@ -1008,6 +1007,10 @@ Http::post('/v1/account/sessions/email') $user->setAttributes($profile->getArrayCopy()); + if ($pwnedPasswords->isEnabled() && $pwnedPasswords->isForceReset() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $duration = $project->getAttribute('auths', [])['duration'] ?? TOKEN_EXPIRATION_LOGIN_LONG; @@ -3462,7 +3465,8 @@ Http::patch('/v1/account/password') ->inject('store') ->inject('proofForPassword') ->inject('proofForToken') - ->action(function (string $password, string $oldPassword, Response $response, User $user, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken) { + ->inject('pwnedPasswords') + ->action(function (string $password, string $oldPassword, Response $response, User $user, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, PasswordPwned $pwnedPasswords) { $userProofForPassword = ProofsPassword::createHash($user->getAttribute('hash'), $user->getAttribute('hashOptions')); // Check old password only if its an existing user. if (!empty($user->getAttribute('passwordUpdate')) && !$userProofForPassword->verify($oldPassword, $user->getAttribute('password'))) { // Double check user password @@ -3491,11 +3495,8 @@ Http::patch('/v1/account/password') } } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); @@ -3561,7 +3562,9 @@ Http::patch('/v1/account/email') ->inject('plan') ->inject('proofForPassword') ->inject('authorization') - ->action(function (string $email, string $password, ?\DateTime $requestTimestamp, Response $response, User $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, array $plan, ProofsPassword $proofForPassword, Authorization $authorization) { + ->inject('passwordsDictionary') + ->inject('pwnedPasswords') + ->action(function (string $email, string $password, ?\DateTime $requestTimestamp, Response $response, User $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, array $plan, ProofsPassword $proofForPassword, Authorization $authorization, array $passwordsDictionary, PasswordPwned $pwnedPasswords) { // passwordUpdate will be empty if the user has never set a password $passwordUpdate = $user->getAttribute('passwordUpdate'); @@ -3574,6 +3577,30 @@ Http::patch('/v1/account/email') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + if (empty($passwordUpdate)) { + // First password for an anonymous account: apply the same policies as account creation + $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); + if (!$strength->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $strength->getDescription()); + } + + $dictionary = new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false); + if (!$dictionary->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $dictionary->getDescription()); + } + + if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) { + $personalDataValidator = new PersonalData($user->getId(), $email, $user->getAttribute('name'), $user->getAttribute('phone')); + if (!$personalDataValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA); + } + } + + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $oldEmail = $user->getAttribute('email'); @@ -3639,8 +3666,11 @@ Http::patch('/v1/account/email') ; if (empty($passwordUpdate)) { + $newPassword = $proofForPassword->hash($password); + $historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0; $user - ->setAttribute('password', $proofForPassword->hash($password)) + ->setAttribute('password', $newPassword) + ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -3703,7 +3733,9 @@ Http::patch('/v1/account/phone') ->inject('hooks') ->inject('proofForPassword') ->inject('authorization') - ->action(function (string $phone, string $password, Response $response, Document $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, ProofsPassword $proofForPassword, Authorization $authorization) { + ->inject('passwordsDictionary') + ->inject('pwnedPasswords') + ->action(function (string $phone, string $password, Response $response, Document $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, ProofsPassword $proofForPassword, Authorization $authorization, array $passwordsDictionary, PasswordPwned $pwnedPasswords) { // passwordUpdate will be empty if the user has never set a password $passwordUpdate = $user->getAttribute('passwordUpdate'); @@ -3716,6 +3748,30 @@ Http::patch('/v1/account/phone') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + if (empty($passwordUpdate)) { + // First password for an anonymous account: apply the same policies as account creation + $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); + if (!$strength->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $strength->getDescription()); + } + + $dictionary = new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false); + if (!$dictionary->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $dictionary->getDescription()); + } + + if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) { + $personalDataValidator = new PersonalData($user->getId(), $user->getAttribute('email'), $user->getAttribute('name'), $phone); + if (!$personalDataValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA); + } + } + + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $target = $authorization->skip(fn () => $dbForProject->findOne('targets', [ @@ -3734,8 +3790,11 @@ Http::patch('/v1/account/phone') ; if (empty($passwordUpdate)) { + $newPassword = $proofForPassword->hash($password); + $historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0; $user - ->setAttribute('password', $proofForPassword->hash($password)) + ->setAttribute('password', $newPassword) + ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -4120,7 +4179,8 @@ Http::put('/v1/account/recovery') ->inject('proofForPassword') ->inject('proofForToken') ->inject('authorization') - ->action(function (string $userId, string $secret, string $password, Response $response, User $user, Database $dbForProject, Document $project, Event $queueForEvents, Hooks $hooks, ProofsPassword $proofForPassword, ProofsToken $proofForToken, Authorization $authorization) { + ->inject('pwnedPasswords') + ->action(function (string $userId, string $secret, string $password, Response $response, User $user, Database $dbForProject, Document $project, Event $queueForEvents, Hooks $hooks, ProofsPassword $proofForPassword, ProofsToken $proofForToken, Authorization $authorization, PasswordPwned $pwnedPasswords) { /** @var Appwrite\Utopia\Database\Documents\User $profile */ $profile = $dbForProject->getDocument('users', $userId); @@ -4152,11 +4212,8 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); diff --git a/app/init/registers.php b/app/init/registers.php index 22d49647cb..3c7c39c697 100644 --- a/app/init/registers.php +++ b/app/init/registers.php @@ -35,6 +35,7 @@ if (!Http::isProduction()) { // Useful for existing tests involving webhooks PublicDomain::allow(['request-catcher-sms']); PublicDomain::allow(['request-catcher-webhook']); + PublicDomain::allow(['localhost']); // Lets the pwned passwords policy point at the mock range endpoint } $register->set('pools', function () { diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 7f4d949e77..430f73cbff 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -3,6 +3,7 @@ use Ahc\Jwt\JWT; use Ahc\Jwt\JWTException; use Appwrite\Auth\Key; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; use Appwrite\Deployment\Deployments; @@ -673,6 +674,10 @@ return function (Container $context): void { return; }, ['user', 'store', 'proofForToken']); + $context->set('pwnedPasswords', function (Document $project, Cache $cache) { + return new PasswordPwned($project->getAttribute('auths', [])['passwordPwned'] ?? [], $cache, System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + }, ['project', 'cache']); + $context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) { if ($project->isEmpty() || $project->getId() === 'console') { return $dbForPlatform; diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index 656ec9283b..8d1cbf4fa8 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -2,32 +2,50 @@ namespace Appwrite\Auth\Validator; +use Appwrite\Extend\Exception; +use Utopia\Cache\Cache; use Utopia\Fetch\Client; /** * Validates that a password has not been exposed in a known data breach. * - * Uses the Have I Been Pwned range API with k-anonymity: only the first five - * characters of the SHA-1 hash leave the server, and the returned candidate - * suffixes are compared locally. When the breach service cannot be reached the - * check is skipped, so an outage of the third party never blocks sign-ups or - * password changes. + * Configured from the project's `password-pwned` policy. Uses the Have I Been + * Pwned range API with k-anonymity: only the first five characters of the + * SHA-1 hash leave the server, and the returned suffixes are compared locally. + * Range responses are cached per prefix so repeated checks do not hit the + * service again. */ class PasswordPwned extends Password { public const ENDPOINT = 'https://api.pwnedpasswords.com/range'; + public const CACHE_TTL = 3600; // seconds private const PREFIX_LENGTH = 5; private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds + protected bool $enabled; protected string $endpoint; + protected int $threshold; + protected bool $forceReset; + protected bool $failClosed; + protected ?Cache $cache; protected Client $client; - public function __construct(?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false) + /** + * @param array $policy the project's `passwordPwned` auth settings + * @param ?string $endpoint server-wide endpoint, used when the policy sets none + */ + public function __construct(array $policy = [], ?Cache $cache = null, ?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false) { parent::__construct($allowEmpty); - $this->endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/'); + + $this->enabled = (bool) ($policy['enabled'] ?? false); + $this->endpoint = \rtrim(($policy['endpoint'] ?? '') ?: ($endpoint ?: self::ENDPOINT), '/'); + $this->threshold = \max(1, (int) ($policy['threshold'] ?? 1)); + $this->forceReset = (bool) ($policy['forceReset'] ?? false); + $this->failClosed = (bool) ($policy['failClosed'] ?? true); + $this->cache = $cache; $this->client = $client ?? (new Client()) ->setConnectTimeout(self::CONNECT_TIMEOUT) ->setTimeout(self::REQUEST_TIMEOUT) @@ -35,6 +53,22 @@ class PasswordPwned extends Password ->setUserAgent('Appwrite'); } + /** + * Whether the project enforces the policy at all. + */ + public function isEnabled(): bool + { + return $this->enabled; + } + + /** + * Whether a breached password blocks sign-in until it is reset. + */ + public function isForceReset(): bool + { + return $this->forceReset; + } + /** * Get Description. * @@ -53,6 +87,7 @@ class PasswordPwned extends Password * @param mixed $value * * @return bool + * @throws Exception when the breach service is unreachable and the policy fails closed */ public function isValid($value): bool { @@ -68,39 +103,65 @@ class PasswordPwned extends Password $prefix = \substr($hash, 0, self::PREFIX_LENGTH); $suffix = \substr($hash, self::PREFIX_LENGTH); + $breaches = $this->range($prefix); + + if ($breaches === null) { + if ($this->failClosed) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + return true; + } + + return ($breaches[$suffix] ?? 0) < $this->threshold; + } + + /** + * Breach counts for every known hash sharing the prefix, from cache or the service. + * + * @return ?array hash suffix => breach count, null when the service could not be reached + */ + private function range(string $prefix): ?array + { + $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix; + + if ($this->cache !== null) { + $cached = $this->cache->load($key, self::CACHE_TTL); + if (\is_array($cached)) { + return $cached; + } + } + try { $response = $this->client ->addHeader('Add-Padding', 'true') ->fetch($this->endpoint . '/' . $prefix); } catch (\Throwable) { - return true; + return null; } if ($response->getStatusCode() !== 200) { - return true; + return null; } // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches + $breaches = []; foreach (\explode("\n", $response->text()) as $line) { $line = \trim($line); - if ($line === '') { - continue; - } - $separator = \strpos($line, ':'); - if ($separator === false) { + if ($line === '' || $separator === false) { continue; } - $candidate = \strtoupper(\substr($line, 0, $separator)); $count = (int) \substr($line, $separator + 1); - - if ($candidate === $suffix && $count > 0) { - return false; + if ($count > 0) { + $breaches[\strtoupper(\substr($line, 0, $separator))] = $count; } } - return true; + $this->cache?->save($key, $breaches); + + return $breaches; } /** diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index cb58ced5db..d44d5803b3 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -48,6 +48,7 @@ class Exception extends \Exception public const string GENERAL_RESOURCE_LOCKED = 'general_resource_locked'; public const string GENERAL_SMTP_DISABLED = 'general_smtp_disabled'; public const string GENERAL_PHONE_DISABLED = 'general_phone_disabled'; + public const string GENERAL_PWNED_PASSWORDS_UNAVAILABLE = 'general_pwned_passwords_unavailable'; public const string GENERAL_ARGUMENT_INVALID = 'general_argument_invalid'; public const string GENERAL_COLUMN_QUERY_LIMIT_EXCEEDED = 'general_column_query_limit_exceeded'; public const string GENERAL_ATTRIBUTE_QUERY_LIMIT_EXCEEDED = 'general_attribute_query_limit_exceeded'; diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index 6d2b5c2037..2361d6a31d 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -91,7 +91,13 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, - 'passwordPwned' => false, + 'passwordPwned' => [ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php index fa943764b0..98e2654925 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php @@ -136,10 +136,15 @@ class Get extends Action Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA, ], 'password-pwned' => [ - new Document([ + new Document(\array_merge([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', - 'enabled' => $auths['passwordPwned'] ?? false, - ]), + ])), Response::MODEL_POLICY_PASSWORD_PWNED, ], 'session-alert' => [ diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php index 79a02f5423..9aef08278d 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -11,8 +11,14 @@ use Appwrite\Utopia\Response; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Validator\Authorization; +use Utopia\Domains\Validator\PublicDomain; use Utopia\Platform\Scope\HTTP; +use Utopia\Validator\AnyOf; use Utopia\Validator\Boolean; +use Utopia\Validator\Multiple; +use Utopia\Validator\Range; +use Utopia\Validator\URL; +use Utopia\Validator\WhiteList; class Update extends Action { @@ -39,7 +45,7 @@ class Update extends Action group: 'policies', name: 'updatePasswordPwnedPolicy', description: <<param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true if you want password change to block passwords exposed in known data breaches, or false to allow them. When changing this policy, existing passwords remain valid.') + ->param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true to block passwords exposed in known data breaches, or false to allow them. When changing this policy, existing passwords remain valid.', optional: true) + ->param('endpoint', null, new AnyOf([new WhiteList([''], true), new Multiple([new URL(['http', 'https']), new PublicDomain()], Multiple::TYPE_STRING)], AnyOf::TYPE_STRING), 'Custom endpoint of a Have I Been Pwned compatible range API, for example a self-hosted mirror. Pass an empty string to use the server default.', optional: true) + ->param('threshold', null, new Range(1, PHP_INT_MAX), 'Minimum number of known breaches a password must appear in before it is rejected. Default is 1.', optional: true) + ->param('forceReset', null, new Boolean(), 'Whether signing in with a breached password is blocked until the password is reset. Default is false, which allows the sign-in.', optional: true) + ->param('failClosed', null, new Boolean(), 'Whether passwords are rejected when the breach service cannot be reached. Default is true. Set to false to skip the check instead.', optional: true) ->inject('response') ->inject('dbForPlatform') ->inject('project') @@ -59,7 +69,11 @@ class Update extends Action } public function action( - bool $enabled, + ?bool $enabled, + ?string $endpoint, + ?int $threshold, + ?bool $forceReset, + ?bool $failClosed, Response $response, Database $dbForPlatform, Document $project, @@ -67,13 +81,33 @@ class Update extends Action Event $queueForEvents, ): void { $auths = $project->getAttribute('auths', []); - $auths['passwordPwned'] = $enabled; + $auths['passwordPwned'] = \array_merge([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], $auths['passwordPwned'] ?? []); - $updates = new Document([ + if ($enabled !== null) { + $auths['passwordPwned']['enabled'] = $enabled; + } + if ($endpoint !== null) { + $auths['passwordPwned']['endpoint'] = $endpoint; + } + if ($threshold !== null) { + $auths['passwordPwned']['threshold'] = $threshold; + } + if ($forceReset !== null) { + $auths['passwordPwned']['forceReset'] = $forceReset; + } + if ($failClosed !== null) { + $auths['passwordPwned']['failClosed'] = $failClosed; + } + + $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document([ 'auths' => $auths, - ]); - - $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); + ]))); $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); $queueForEvents diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php index 83693cff33..8d5d85ec50 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php @@ -116,10 +116,15 @@ class XList extends Action '$id' => 'password-personal-data', 'enabled' => $auths['personalDataCheck'] ?? false, ]), - new Document([ + new Document(\array_merge([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', - 'enabled' => $auths['passwordPwned'] ?? false, - ]), + ])), new Document([ '$id' => 'session-alert', 'enabled' => $auths['sessionAlerts'] ?? false, diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php index 1606990885..9182796e9a 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -88,7 +88,13 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, - 'passwordPwned' => false, + 'passwordPwned' => [ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Users/Base.php b/src/Appwrite/Platform/Modules/Users/Base.php index a251925e55..232d4fd52d 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -2,7 +2,6 @@ namespace Appwrite\Platform\Modules\Users; -use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PersonalData; use Appwrite\Extend\Exception; use Appwrite\Hooks\Hooks; @@ -19,7 +18,6 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Query; use Utopia\Emails\Email; -use Utopia\System\System; class Base extends Action { @@ -149,13 +147,6 @@ class Base extends Action ]); if (!$isHashed && !empty($password)) { - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($plaintextPassword)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } - } - $hooks->trigger('passwordValidator', [$dbForProject, $project, $plaintextPassword, &$user, true]); } diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php index 16bb0ece33..e81b3f1f71 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php @@ -3,8 +3,10 @@ namespace Appwrite\Platform\Modules\Users\Http\Users; use Appwrite\Auth\Validator\PasswordDictionary; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PasswordStrength; use Appwrite\Auth\Validator\Phone; +use Appwrite\Extend\Exception; use Appwrite\Hooks\Hooks; use Appwrite\Platform\Action; use Appwrite\Platform\Modules\Users\Base; @@ -66,11 +68,16 @@ class Create extends Base ->inject('dbForProject') ->inject('hooks') ->inject('plan') + ->inject('pwnedPasswords') ->callback($this->action(...)); } - public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan): void + public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords): void { + if (!empty($password) && $pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + $plaintext = new Plaintext(); $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan); diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index 52647cd924..05cbf45f28 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -23,7 +23,6 @@ use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Validator\UID; use Utopia\Platform\Scope\HTTP; -use Utopia\System\System; use Utopia\Validator; use Utopia\Validator\AllOf; @@ -68,10 +67,11 @@ class Update extends Action ->inject('dbForProject') ->inject('queueForEvents') ->inject('hooks') + ->inject('pwnedPasswords') ->callback($this->action(...)); } - public function action(string $userId, string $password, Response $response, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks): void + public function action(string $userId, string $password, Response $response, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, PasswordPwned $pwnedPasswords): void { $user = $dbForProject->getDocument('users', $userId); @@ -86,11 +86,8 @@ class Update extends Action } } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'), allowEmpty: true); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if (\strlen($password) > 0 && $pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } if (\strlen($password) === 0) { diff --git a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php index f20511bb0b..fb258a8ebb 100644 --- a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -14,12 +14,37 @@ class PolicyPasswordPwned extends PolicyBase { parent::__construct(); - $this->addRule('enabled', [ - 'type' => self::TYPE_BOOLEAN, - 'description' => 'Whether password pwned policy is enabled.', - 'default' => false, - 'example' => true, - ]); + $this + ->addRule('enabled', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether password pwned policy is enabled.', + 'default' => false, + 'example' => true, + ]) + ->addRule('endpoint', [ + 'type' => self::TYPE_STRING, + 'description' => 'Custom endpoint of a Have I Been Pwned compatible range API. Empty when the server default is used.', + 'default' => '', + 'example' => 'https://api.pwnedpasswords.com/range', + ]) + ->addRule('threshold', [ + 'type' => self::TYPE_INTEGER, + 'description' => 'Minimum number of known breaches a password must appear in before it is rejected.', + 'default' => 1, + 'example' => 1, + ]) + ->addRule('forceReset', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether signing in with a breached password is blocked until the password is reset.', + 'default' => false, + 'example' => false, + ]) + ->addRule('failClosed', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether passwords are rejected when the breach service cannot be reached. When false, the check is skipped instead.', + 'default' => true, + 'example' => true, + ]); } public function getName(): string diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index 7382d65763..b06dd0b791 100644 --- a/tests/e2e/Services/Project/PoliciesBase.php +++ b/tests/e2e/Services/Project/PoliciesBase.php @@ -17,7 +17,7 @@ trait PoliciesBase 'password-history' => ['total'], 'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'], 'password-personal-data' => ['enabled'], - 'password-pwned' => ['enabled'], + 'password-pwned' => ['enabled', 'endpoint', 'threshold', 'forceReset', 'failClosed'], 'session-alert' => ['enabled'], 'session-duration' => ['duration'], 'session-invalidation' => ['enabled'], @@ -642,7 +642,7 @@ trait PoliciesBase public function testUpdatePasswordPwnedPolicyEnable(): void { - $response = $this->updatePasswordPwnedPolicy(true); + $response = $this->updatePasswordPwnedPolicy(['enabled' => true]); $this->assertSame(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); @@ -650,16 +650,20 @@ trait PoliciesBase $policy = $this->getPolicy('password-pwned'); $this->assertSame(200, $policy['headers']['status-code']); $this->assertSame(true, $policy['body']['enabled']); + $this->assertSame('', $policy['body']['endpoint']); + $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['forceReset']); + $this->assertSame(true, $policy['body']['failClosed']); // Cleanup - $this->updatePasswordPwnedPolicy(false); + $this->updatePasswordPwnedPolicy(['enabled' => false]); } public function testUpdatePasswordPwnedPolicyDisable(): void { - $this->updatePasswordPwnedPolicy(true); + $this->updatePasswordPwnedPolicy(['enabled' => true]); - $response = $this->updatePasswordPwnedPolicy(false); + $response = $this->updatePasswordPwnedPolicy(['enabled' => false]); $this->assertSame(200, $response['headers']['status-code']); @@ -675,27 +679,86 @@ trait PoliciesBase $this->assertSame(200, $policy['headers']['status-code']); $this->assertSame('password-pwned', $policy['body']['$id']); $this->assertSame(false, $policy['body']['enabled']); + $this->assertSame('', $policy['body']['endpoint']); + $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['forceReset']); + $this->assertSame(true, $policy['body']['failClosed']); + } + + public function testUpdatePasswordPwnedPolicyOptionPreservesOtherOptions(): void + { + $response = $this->updatePasswordPwnedPolicy([ + 'endpoint' => 'https://example.com/range', + 'threshold' => 5, + 'forceReset' => true, + 'failClosed' => false, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $response = $this->updatePasswordPwnedPolicy(['enabled' => true]); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(true, $policy['body']['enabled']); + $this->assertSame('https://example.com/range', $policy['body']['endpoint']); + $this->assertSame(5, $policy['body']['threshold']); + $this->assertSame(true, $policy['body']['forceReset']); + $this->assertSame(false, $policy['body']['failClosed']); + + // Cleanup + $this->resetPasswordPwnedPolicy(); + } + + public function testUpdatePasswordPwnedPolicyEmptyBody(): void + { + $this->resetPasswordPwnedPolicy(); + + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(false, $policy['body']['enabled']); + $this->assertSame('', $policy['body']['endpoint']); + $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['forceReset']); + $this->assertSame(true, $policy['body']['failClosed']); } public function testUpdatePasswordPwnedPolicyInvalidType(): void { - $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), [ - 'enabled' => 'not-a-boolean', - ]); + foreach (['enabled', 'forceReset', 'failClosed'] as $option) { + $response = $this->updatePasswordPwnedPolicy([$option => 'not-a-boolean']); + + $this->assertSame(400, $response['headers']['status-code'], $option); + } + + $response = $this->updatePasswordPwnedPolicy(['threshold' => 'not-a-number']); $this->assertSame(400, $response['headers']['status-code']); } - public function testUpdatePasswordPwnedPolicyMissingParam(): void + public function testUpdatePasswordPwnedPolicyInvalidThreshold(): void { - $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []); + $response = $this->updatePasswordPwnedPolicy(['threshold' => 0]); $this->assertSame(400, $response['headers']['status-code']); } + public function testUpdatePasswordPwnedPolicyInvalidEndpoint(): void + { + foreach (['not-a-url', 'ftp://example.com/range', 'http://192.168.1.1/range'] as $endpoint) { + $response = $this->updatePasswordPwnedPolicy(['endpoint' => $endpoint]); + + $this->assertSame(400, $response['headers']['status-code'], $endpoint); + } + } + public function testUpdatePasswordPwnedPolicyWithoutAuth(): void { - $response = $this->updatePasswordPwnedPolicy(true, false); + $response = $this->updatePasswordPwnedPolicy(['enabled' => true], false); $this->assertSame(401, $response['headers']['status-code']); } @@ -1394,10 +1457,22 @@ trait PoliciesBase ]); } - protected function updatePasswordPwnedPolicy(bool $enabled, bool $authenticated = true): mixed + /** + * @param array $params + */ + protected function updatePasswordPwnedPolicy(array $params, bool $authenticated = true): mixed { - return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), [ - 'enabled' => $enabled, + return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), $params); + } + + protected function resetPasswordPwnedPolicy(): void + { + $this->updatePasswordPwnedPolicy([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, ]); } diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 5b0c62d6e7..94eedc7852 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -19,12 +19,19 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope use ProjectCustom; use SideServer; - // Reported as breached by the mock range endpoint + // Reported as breached by the mock range endpoint, 12345 and 9 times respectively private const PWNED_PASSWORD = 'Password123!'; + private const RARELY_PWNED_PASSWORD = 'letmein1234'; + + // The mock range endpoint the stack already uses through _APP_PWNED_PASSWORDS_ENDPOINT + private const MOCK_ENDPOINT = 'http://localhost/v1/mock/tests/general/pwned-passwords'; + + // Nothing listens here, so lookups fail + private const DEAD_ENDPOINT = 'http://localhost:1/range'; public function testCreateUserWithPolicyDisabled(): void { - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); /** * Test for SUCCESS @@ -48,7 +55,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope public function testCreateUserWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); /** * Test for FAILURE @@ -88,12 +95,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testUpdateUserPasswordWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ 'userId' => ID::unique(), @@ -131,12 +138,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(200, $response['headers']['status-code']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testCreateAccountWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); /** * Test for FAILURE @@ -164,12 +171,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testUpdateAccountPasswordWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); $email = 'pwned_session_' . \uniqid() . '@localhost.test'; $password = $this->cleanPassword(); @@ -215,12 +222,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(200, $response['headers']['status-code']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testUpdateAccountRecoveryWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); $email = 'pwned_recovery_' . \uniqid() . '@localhost.test'; @@ -269,15 +276,478 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(200, $response['headers']['status-code']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } - private function updatePolicy(bool $enabled): void + public function testThreshold(): void { - $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->serverHeaders(), [ - 'enabled' => $enabled, + $this->updatePolicy(['enabled' => true, 'threshold' => 10]); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_rare_' . \uniqid() . '@localhost.test', + 'password' => self::RARELY_PWNED_PASSWORD, + 'name' => 'Rarely Pwned User', ]); + $this->assertSame(201, $response['headers']['status-code']); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_often_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Often Pwned User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + $this->updatePolicy(['enabled' => false, 'threshold' => 1]); + } + + public function testCustomEndpoint(): void + { + $this->updatePolicy(['enabled' => true, 'endpoint' => self::MOCK_ENDPOINT]); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_endpoint_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Endpoint User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_endpoint_clean_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Endpoint Clean User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + // An empty endpoint falls back to the server configuration + $this->updatePolicy(['endpoint' => '']); + + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_fallback_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Fallback User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + $this->updatePolicy(['enabled' => false]); + } + + public function testFailClosed(): void + { + $this->updatePolicy(['enabled' => true, 'endpoint' => self::DEAD_ENDPOINT, 'failClosed' => true]); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_outage_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Outage User', + ]); + + $this->assertSame(503, $response['headers']['status-code']); + $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); + + $response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_outage_account_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Outage Account', + ]); + + $this->assertSame(503, $response['headers']['status-code']); + $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); + + // Forced reset needs the lookup, so sign-in fails closed as well + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_outage_signin_' . \uniqid() . '@localhost.test'; + $password = $this->cleanPassword(); + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $password, + 'name' => 'Outage Sign In User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + + $this->updatePolicy(['enabled' => true, 'forceReset' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(503, $response['headers']['status-code']); + $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $this->updatePolicy(['failClosed' => false]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_outage_open_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Outage Open User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'forceReset' => false, 'failClosed' => true]); + } + + public function testForceResetOnSignIn(): void + { + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_signin_' . \uniqid() . '@localhost.test'; + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Sign In User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + + /** + * Test for SUCCESS + */ + $this->updatePolicy(['enabled' => true, 'forceReset' => false]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + /** + * Test for FAILURE + */ + $this->updatePolicy(['forceReset' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(412, $response['headers']['status-code']); + $this->assertSame('user_password_reset_required', $response['body']['type']); + + // A wrong password is still reported as such, not as a reset + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => 'wrong-' . self::PWNED_PASSWORD, + ]); + + $this->assertSame(401, $response['headers']['status-code']); + $this->assertSame('user_invalid_credentials', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $password = $this->cleanPassword(); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $user['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $this->updatePolicy(['enabled' => false, 'forceReset' => false]); + } + + public function testUpdateAnonymousAccountEmail(): void + { + $this->updatePolicy(['enabled' => true]); + + $headers = $this->anonymousHeaders(); + $email = 'pwned_anonymous_' . \uniqid() . '@localhost.test'; + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + // Strength policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 12]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => 'Short1!x', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 8]); + + // Dictionary policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => 'football', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => false]); + + // Personal data policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => \explode('@', $email)[0] . '-Pw!', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_personal_data', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => false]); + + /** + * Test for SUCCESS + */ + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 1]); + + $password = $this->cleanPassword(); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertSame($email, $response['body']['email']); + + // The first password entered the history, so it cannot be reused + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $password, + 'oldPassword' => $password, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_recently_used', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 0]); + $this->updatePolicy(['enabled' => false]); + } + + public function testUpdateAnonymousAccountPhone(): void + { + $this->updatePolicy(['enabled' => true]); + + $headers = $this->anonymousHeaders(); + $phone = '+15' . \random_int(100000000, 999999999); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => 'short', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + // Dictionary policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => 'football', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => false]); + + // Personal data policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => 'pw-' . \substr($phone, 1) . '!', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_personal_data', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => false]); + + /** + * Test for SUCCESS + */ + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 1]); + + $password = $this->cleanPassword(); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertSame($phone, $response['body']['phone']); + + // The first password entered the history, so it cannot be reused + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $password, + 'oldPassword' => $password, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_recently_used', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 0]); + $this->updatePolicy(['enabled' => false]); + } + + public function testUpdateAccountEmailWithExistingPassword(): void + { + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_existing_' . \uniqid() . '@localhost.test'; + + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Existing Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $projectId = $this->getProject()['$id']; + $headers = \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ]); + + // Policies tightened after the password was set only apply to new passwords + $this->updatePolicy(['enabled' => true]); + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 20]); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => 'pwned_existing_new_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => 'pwned_existing_wrong_' . \uniqid() . '@localhost.test', + 'password' => 'wrong-' . self::PWNED_PASSWORD, + ]); + + $this->assertSame(401, $response['headers']['status-code']); + $this->assertSame('user_invalid_credentials', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 8]); + $this->updatePolicy(['enabled' => false]); + } + + /** + * Client headers carrying a fresh anonymous session. + * + * @return array + */ + private function anonymousHeaders(): array + { + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/anonymous', $this->clientHeaders()); + + $this->assertSame(201, $session['headers']['status-code']); + + $projectId = $this->getProject()['$id']; + + return \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ]); + } + + /** + * @param array $params + */ + private function updatePolicy(array $params): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->serverHeaders(), $params); + $this->assertSame(200, $response['headers']['status-code']); } diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index ae74d6b461..a4b14707d9 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -5,7 +5,10 @@ declare(strict_types=1); namespace Tests\Unit\Auth\Validator; use Appwrite\Auth\Validator\PasswordPwned; +use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; +use Utopia\Cache\Adapter\Memory; +use Utopia\Cache\Cache; use Utopia\Fetch\Adapter; use Utopia\Fetch\Client; use Utopia\Fetch\Options\Request as RequestOptions; @@ -14,11 +17,28 @@ use Utopia\Fetch\Response; final class PasswordPwnedTest extends TestCase { private const LEAKED = 'Password123!'; + private const ENDPOINT = 'https://breaches.test/range'; + + public function testDisabledByDefault(): void + { + $validator = new PasswordPwned(); + + $this->assertFalse($validator->isEnabled()); + $this->assertFalse($validator->isForceReset()); + } + + public function testPolicyFlags(): void + { + $validator = new PasswordPwned(['enabled' => true, 'forceReset' => true]); + + $this->assertTrue($validator->isEnabled()); + $this->assertTrue($validator->isForceReset()); + } public function testLeakedPasswordIsRejected(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertFalse($validator->isValid(self::LEAKED)); } @@ -26,7 +46,7 @@ final class PasswordPwnedTest extends TestCase public function testCleanPasswordIsAccepted(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertTrue($validator->isValid('never-leaked-' . \uniqid())); } @@ -34,7 +54,7 @@ final class PasswordPwnedTest extends TestCase public function testPaddedEntryWithZeroCountIsNotABreach(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 0])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertTrue($validator->isValid(self::LEAKED)); } @@ -42,45 +62,104 @@ final class PasswordPwnedTest extends TestCase public function testSuffixComparisonIgnoresCase(): void { $adapter = new RangeAdapter(body: \strtolower($this->range([self::LEAKED => 3]))); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertFalse($validator->isValid(self::LEAKED)); } + public function testThresholdToleratesRareBreaches(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 9])); + + $this->assertTrue($this->validator(['threshold' => 10], $adapter)->isValid(self::LEAKED)); + $this->assertFalse($this->validator(['threshold' => 9], $adapter)->isValid(self::LEAKED)); + } + public function testOnlyHashPrefixLeavesTheServer(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('https://breaches.test/range/', new Client($adapter)); + $validator = $this->validator([], $adapter); $validator->isValid(self::LEAKED); $hash = \strtoupper(\sha1(self::LEAKED)); $this->assertCount(1, $adapter->requests); - $this->assertSame('https://breaches.test/range/' . \substr($hash, 0, 5), $adapter->requests[0]['url']); + $this->assertSame(self::ENDPOINT . '/' . \substr($hash, 0, 5), $adapter->requests[0]['url']); $this->assertSame('GET', $adapter->requests[0]['method']); $this->assertSame('true', $adapter->requests[0]['headers']['add-padding'] ?? null); } - public function testUnreachableServiceSkipsTheCheck(): void + public function testRangeIsCachedPerPrefix(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $cache = new Cache(new Memory()); + + $first = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); + $second = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); + + $this->assertFalse($first->isValid(self::LEAKED)); + $this->assertFalse($second->isValid(self::LEAKED)); + $this->assertCount(1, $adapter->requests); + } + + public function testCacheIsScopedToEndpoint(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $cache = new Cache(new Memory()); + + (new PasswordPwned([], $cache, 'https://one.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned([], $cache, 'https://two.test/range', new Client($adapter)))->isValid(self::LEAKED); + + $this->assertCount(2, $adapter->requests); + } + + public function testUnreachableServiceFailsClosedByDefault(): void { $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); + + try { + $validator->isValid(self::LEAKED); + $this->fail('Expected the check to fail closed'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + + public function testUnexpectedStatusFailsClosedByDefault(): void + { + $adapter = new RangeAdapter(statusCode: 503, body: ''); + $validator = $this->validator([], $adapter); + + $this->expectException(Exception::class); + + $validator->isValid(self::LEAKED); + } + + public function testUnreachableServiceSkipsTheCheckWhenFailingOpen(): void + { + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $validator = $this->validator(['failClosed' => false], $adapter); $this->assertTrue($validator->isValid(self::LEAKED)); } - public function testUnexpectedStatusSkipsTheCheck(): void + public function testFailedLookupIsNotCached(): void { - $adapter = new RangeAdapter(statusCode: 503, body: $this->range([self::LEAKED => 42])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $cache = new Cache(new Memory()); + $validator = new PasswordPwned(['failClosed' => false], $cache, self::ENDPOINT, new Client($adapter)); - $this->assertTrue($validator->isValid(self::LEAKED)); + $validator->isValid(self::LEAKED); + $validator->isValid(self::LEAKED); + + $this->assertCount(2, $adapter->requests); } public function testBasePasswordRulesStillApply(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertFalse($validator->isValid('short')); $this->assertFalse($validator->isValid(\str_repeat('p', 257))); @@ -91,20 +170,32 @@ final class PasswordPwnedTest extends TestCase public function testAllowEmptySkipsTheLookup(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter), allowEmpty: true); + $validator = new PasswordPwned([], null, self::ENDPOINT, new Client($adapter), allowEmpty: true); $this->assertTrue($validator->isValid('')); $this->assertCount(0, $adapter->requests); } - public function testEmptyEndpointFallsBackToDefault(): void + public function testEndpointPrecedence(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('', new Client($adapter)); + $prefix = \substr(\strtoupper(\sha1(self::LEAKED)), 0, 5); - $validator->isValid(self::LEAKED); + (new PasswordPwned(['endpoint' => 'https://policy.test/range/'], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['endpoint' => ''], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned([], null, '', new Client($adapter)))->isValid(self::LEAKED); - $this->assertStringStartsWith(PasswordPwned::ENDPOINT . '/', $adapter->requests[0]['url']); + $this->assertSame('https://policy.test/range/' . $prefix, $adapter->requests[0]['url']); + $this->assertSame('https://server.test/range/' . $prefix, $adapter->requests[1]['url']); + $this->assertSame(PasswordPwned::ENDPOINT . '/' . $prefix, $adapter->requests[2]['url']); + } + + /** + * @param array $policy + */ + private function validator(array $policy, RangeAdapter $adapter): PasswordPwned + { + return new PasswordPwned($policy, null, self::ENDPOINT, new Client($adapter)); } /** From 5e95e07613cf55594eab9364c018f0a231cb5289 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 13:29:30 +0200 Subject: [PATCH 12/38] feat(users): record and expose whether a password is known to be breached Adds a nullable `passwordPwned` boolean to the users collection, with an index, and exposes it on the User and Account models. It is null until a password has been checked by the pwned policy, false when the last check was clean, and true when the last check found the password in a breach. The flag is written wherever the policy checks a password: account and user creation, password updates, recovery, anonymous conversions, and password sign-in. Sign-in records the outcome whether or not a reset is forced, and an unreachable service leaves the stored value untouched. Setting a password without a check, clearing it, or importing a hash resets the flag to null. Users can be listed by the flag through `Query::equal` and `isNull`. The attribute and index are created by the V25 migration. Co-Authored-By: Claude Fable 5.1 --- app/config/collections/common.php | 18 ++ app/controllers/api/account.php | 40 ++- src/Appwrite/Auth/Validator/PasswordPwned.php | 47 ++- src/Appwrite/Migration/Version/V25.php | 16 + src/Appwrite/Platform/Modules/Users/Base.php | 3 +- .../Modules/Users/Http/Users/Create.php | 5 +- .../Users/Http/Users/Password/Update.php | 6 +- .../Database/Validator/Queries/Users.php | 1 + .../Utopia/Response/Model/Account.php | 7 + src/Appwrite/Utopia/Response/Model/User.php | 7 + .../PoliciesPasswordPwnedIntegrationTest.php | 281 ++++++++++++++++++ .../unit/Auth/Validator/PasswordPwnedTest.php | 43 ++- 12 files changed, 438 insertions(+), 36 deletions(-) diff --git a/app/config/collections/common.php b/app/config/collections/common.php index cd491d1e79..92eefb88b2 100644 --- a/app/config/collections/common.php +++ b/app/config/collections/common.php @@ -397,6 +397,17 @@ return [ 'array' => false, 'filters' => [], ], + [ + '$id' => ID::custom('passwordPwned'), + 'type' => Database::VAR_BOOLEAN, + 'format' => '', + 'size' => 0, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ], [ '$id' => ID::custom('emailIsCorporate'), 'type' => Database::VAR_BOOLEAN, @@ -488,6 +499,13 @@ return [ 'lengths' => [], 'orders' => [Database::ORDER_ASC], ], + [ + '$id' => ID::custom('_key_passwordPwned'), + 'type' => Database::INDEX_KEY, + 'attributes' => ['passwordPwned'], + 'lengths' => [], + 'orders' => [Database::ORDER_ASC], + ], [ '$id' => ID::custom('_key_search'), 'type' => Database::INDEX_FULLTEXT, diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 7ddc1c1d10..3286b78f85 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -363,7 +363,8 @@ Http::post('/v1/account') } } - if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -443,6 +444,7 @@ Http::post('/v1/account') 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], + 'passwordPwned' => $passwordPwned, ]); $user->removeAttribute('$sequence'); @@ -1007,10 +1009,6 @@ Http::post('/v1/account/sessions/email') $user->setAttributes($profile->getArrayCopy()); - if ($pwnedPasswords->isEnabled() && $pwnedPasswords->isForceReset() && !$pwnedPasswords->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); - } - $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $duration = $project->getAttribute('auths', [])['duration'] ?? TOKEN_EXPIRATION_LOGIN_LONG; @@ -1050,6 +1048,20 @@ Http::post('/v1/account/sessions/email') $authorization->addRole(Role::user($user->getId())->toString()); + // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in + $passwordPwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); + + if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { + $user->setAttribute('passwordPwned', $passwordPwned); + $dbForProject->updateDocument('users', $user->getId(), new Document([ + 'passwordPwned' => $passwordPwned, + ])); + } + + if ($passwordPwned && $pwnedPasswords->isForceReset()) { + throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); + } + // Re-hash if not using recommended algo if ($user->getAttribute('hash') !== $proofForPassword->getHash()->getName()) { $proofForPasswordUpdated = new ProofsPassword(); @@ -3495,7 +3507,8 @@ Http::patch('/v1/account/password') } } - if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3504,6 +3517,7 @@ Http::patch('/v1/account/password') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()); @@ -3577,6 +3591,7 @@ Http::patch('/v1/account/email') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + $passwordPwned = null; if (empty($passwordUpdate)) { // First password for an anonymous account: apply the same policies as account creation $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); @@ -3596,7 +3611,8 @@ Http::patch('/v1/account/email') } } - if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } } @@ -3671,6 +3687,7 @@ Http::patch('/v1/account/email') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -3748,6 +3765,7 @@ Http::patch('/v1/account/phone') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + $passwordPwned = null; if (empty($passwordUpdate)) { // First password for an anonymous account: apply the same policies as account creation $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); @@ -3767,7 +3785,8 @@ Http::patch('/v1/account/phone') } } - if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } } @@ -3795,6 +3814,7 @@ Http::patch('/v1/account/phone') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -4212,7 +4232,8 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } - if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -4224,6 +4245,7 @@ Http::put('/v1/account/recovery') [ 'password' => $newPassword, 'passwordHistory' => $history, + 'passwordPwned' => $passwordPwned, 'passwordUpdate' => DateTime::now(), 'hash' => $proofForPassword->getHash()->getName(), 'hashOptions' => $proofForPassword->getHash()->getOptions(), diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index 8d1cbf4fa8..e0ca9ce919 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -81,6 +81,37 @@ class PasswordPwned extends Password return 'Password must not have been exposed in a known data breach.'; } + /** + * Whether the password appears in at least `threshold` known breaches. + * + * Returns null when the policy is disabled, or when the service could not + * be reached and the answer is not required by a fail-closed policy. + * + * @throws Exception when the answer is required, the policy fails closed, and the service is unreachable + */ + public function check(string $password, bool $required = true): ?bool + { + if (!$this->enabled) { + return null; + } + + $hash = \strtoupper(\sha1($password)); + $prefix = \substr($hash, 0, self::PREFIX_LENGTH); + $suffix = \substr($hash, self::PREFIX_LENGTH); + + $breaches = $this->range($prefix); + + if ($breaches === null) { + if ($required && $this->failClosed) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + return null; + } + + return ($breaches[$suffix] ?? 0) >= $this->threshold; + } + /** * Is valid. * @@ -99,21 +130,7 @@ class PasswordPwned extends Password return true; } - $hash = \strtoupper(\sha1($value)); - $prefix = \substr($hash, 0, self::PREFIX_LENGTH); - $suffix = \substr($hash, self::PREFIX_LENGTH); - - $breaches = $this->range($prefix); - - if ($breaches === null) { - if ($this->failClosed) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } - - return true; - } - - return ($breaches[$suffix] ?? 0) < $this->threshold; + return $this->check($value) !== true; } /** diff --git a/src/Appwrite/Migration/Version/V25.php b/src/Appwrite/Migration/Version/V25.php index fb3b4352b1..d0531ffd5e 100644 --- a/src/Appwrite/Migration/Version/V25.php +++ b/src/Appwrite/Migration/Version/V25.php @@ -240,6 +240,22 @@ class V25 extends Migration } break; + case 'users': + try { + $this->createAttributeFromCollection($this->dbForProject, $id, 'passwordPwned'); + } catch (Throwable $th) { + Console::warning("Failed to create attribute \"passwordPwned\" in collection {$id}: {$th->getMessage()}"); + } + + try { + $this->createIndexFromCollection($this->dbForProject, $id, '_key_passwordPwned'); + } catch (Throwable $th) { + Console::warning("Failed to create index \"_key_passwordPwned\" from {$id}: {$th->getMessage()}"); + } + + $this->dbForProject->purgeCachedCollection($id); + break; + case 'identities': try { $this->createAttributeFromCollection($this->dbForProject, $id, 'photo'); diff --git a/src/Appwrite/Platform/Modules/Users/Base.php b/src/Appwrite/Platform/Modules/Users/Base.php index 232d4fd52d..bd48b7b015 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -21,7 +21,7 @@ use Utopia\Emails\Email; class Base extends Action { - protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan): Document + protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan, ?bool $passwordPwned = null): Document { $name = $name ?? ''; $plaintextPassword = $password; @@ -144,6 +144,7 @@ class Base extends Action 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], + 'passwordPwned' => $passwordPwned, ]); if (!$isHashed && !empty($password)) { diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php index e81b3f1f71..5fa213f83c 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php @@ -74,13 +74,14 @@ class Create extends Base public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords): void { - if (!empty($password) && $pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + $passwordPwned = empty($password) ? null : $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } $plaintext = new Plaintext(); - $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan); + $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan, $passwordPwned); $response ->setStatusCode(Response::STATUS_CODE_CREATED) diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index 05cbf45f28..aba1363d92 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -86,7 +86,8 @@ class Update extends Action } } - if (\strlen($password) > 0 && $pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + $passwordPwned = \strlen($password) === 0 ? null : $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -97,6 +98,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), + 'passwordPwned' => null, 'passwordUpdate' => $user->getAttribute('passwordUpdate'), ])); $queueForEvents->setParam('userId', $user->getId()); @@ -127,6 +129,7 @@ class Update extends Action $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $hasher->getName()) ->setAttribute('hashOptions', $hasher->getOptions()); @@ -134,6 +137,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), 'passwordHistory' => $user->getAttribute('passwordHistory'), + 'passwordPwned' => $user->getAttribute('passwordPwned'), 'passwordUpdate' => $user->getAttribute('passwordUpdate'), 'hash' => $user->getAttribute('hash'), 'hashOptions' => $user->getAttribute('hashOptions'), diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php index e38cd6c397..e2e721c8c2 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php @@ -13,6 +13,7 @@ class Users extends Base 'registration', 'emailVerification', 'phoneVerification', + 'passwordPwned', 'labels', 'impersonator', 'accessedAt', diff --git a/src/Appwrite/Utopia/Response/Model/Account.php b/src/Appwrite/Utopia/Response/Model/Account.php index 769284d714..c716c24649 100644 --- a/src/Appwrite/Utopia/Response/Model/Account.php +++ b/src/Appwrite/Utopia/Response/Model/Account.php @@ -113,6 +113,13 @@ class Account extends Model 'default' => null, 'example' => true, ]) + ->addRule('passwordPwned', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', + 'required' => false, + 'default' => null, + 'example' => false, + ]) ->addRule('phoneVerification', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Phone verification status.', diff --git a/src/Appwrite/Utopia/Response/Model/User.php b/src/Appwrite/Utopia/Response/Model/User.php index da1f7fe5fc..91d4ca7e54 100644 --- a/src/Appwrite/Utopia/Response/Model/User.php +++ b/src/Appwrite/Utopia/Response/Model/User.php @@ -143,6 +143,13 @@ class User extends Model 'default' => null, 'example' => true, ]) + ->addRule('passwordPwned', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', + 'required' => false, + 'default' => null, + 'example' => false, + ]) ->addRule('phoneVerification', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Phone verification status.', diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 94eedc7852..2a78a4ae3c 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -9,6 +9,7 @@ use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; use Utopia\Database\Helpers\ID; +use Utopia\Database\Query; /** * The stack points `_APP_PWNED_PASSWORDS_ENDPOINT` at the mock range endpoint in @@ -723,6 +724,286 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->updatePolicy(['enabled' => false]); } + public function testPasswordPwnedFlag(): void + { + // Policy off: nothing is known about the password + $this->updatePolicy(['enabled' => false]); + + $emailA = 'pwned_flag_a_' . \uniqid() . '@localhost.test'; + + $userA = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $emailA, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Flag User A', + ]); + + $this->assertSame(201, $userA['headers']['status-code']); + $this->assertArrayHasKey('passwordPwned', $userA['body']); + $this->assertNull($userA['body']['passwordPwned']); + + // Policy on: a clean password is recorded as clean + $this->updatePolicy(['enabled' => true]); + + $userB = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_flag_b_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Flag User B', + ]); + + $this->assertSame(201, $userB['headers']['status-code']); + $this->assertFalse($userB['body']['passwordPwned']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userB['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // A hashed import never sees the plaintext, so nothing is known + $userC = $this->client->call(Client::METHOD_POST, '/users/sha', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_flag_c_' . \uniqid() . '@localhost.test', + 'password' => \sha1(self::PWNED_PASSWORD), + 'passwordVersion' => 'sha1', + 'name' => 'Flag User C', + ]); + + $this->assertSame(201, $userC['headers']['status-code']); + $this->assertNull($userC['body']['passwordPwned']); + + // Signing in records a breached password, on the users and the account API + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $emailA, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userA['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['passwordPwned']); + + $projectId = $this->getProject()['$id']; + $response = $this->client->call(Client::METHOD_GET, '/account', \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ])); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['passwordPwned']); + + // Listing users can filter on the flag + $ids = fn (array $response) => \array_column($response['body']['users'], '$id'); + + $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ + 'queries' => [ + Query::equal('passwordPwned', [true])->toString(), + Query::orderDesc('$createdAt')->toString(), + Query::limit(100)->toString(), + ], + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertContains($userA['body']['$id'], $ids($response)); + $this->assertNotContains($userB['body']['$id'], $ids($response)); + $this->assertNotContains($userC['body']['$id'], $ids($response)); + + $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ + 'queries' => [ + Query::equal('passwordPwned', [false])->toString(), + Query::orderDesc('$createdAt')->toString(), + Query::limit(100)->toString(), + ], + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertContains($userB['body']['$id'], $ids($response)); + $this->assertNotContains($userA['body']['$id'], $ids($response)); + $this->assertNotContains($userC['body']['$id'], $ids($response)); + + $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ + 'queries' => [ + Query::isNull('passwordPwned')->toString(), + Query::orderDesc('$createdAt')->toString(), + Query::limit(100)->toString(), + ], + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertContains($userC['body']['$id'], $ids($response)); + $this->assertNotContains($userA['body']['$id'], $ids($response)); + $this->assertNotContains($userB['body']['$id'], $ids($response)); + + // A clean password clears the flag + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userA['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // Without the policy a new password is unknown again + $this->updatePolicy(['enabled' => false]); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userA['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNull($response['body']['passwordPwned']); + + // Clearing the password clears the flag + $this->updatePolicy(['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userB['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => '', + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNull($response['body']['passwordPwned']); + + $this->updatePolicy(['enabled' => false]); + } + + public function testPasswordPwnedFlagOnAccount(): void + { + $this->updatePolicy(['enabled' => true]); + + $email = 'pwned_flag_account_' . \uniqid() . '@localhost.test'; + $password = $this->cleanPassword(); + + /** + * Test for SUCCESS + */ + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $password, + 'name' => 'Flag Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + $this->assertFalse($account['body']['passwordPwned']); + + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $projectId = $this->getProject()['$id']; + $headers = \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ]); + + $response = $this->client->call(Client::METHOD_GET, '/account', $headers); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $this->cleanPassword(), + 'oldPassword' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // Recovery records the new password too + $recovery = $this->client->call(Client::METHOD_POST, '/account/recovery', $this->clientHeaders(), [ + 'email' => $email, + 'url' => 'http://localhost/recovery', + ]); + + $this->assertSame(201, $recovery['headers']['status-code']); + + $lastEmail = $this->getLastEmailByAddress($email, function ($email) { + $this->assertStringContainsString('Password Reset', (string) $email['subject']); + }); + $secret = $this->extractQueryParamsFromEmailLink($lastEmail['html'])['secret']; + + $response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [ + 'userId' => $account['body']['$id'], + 'secret' => $secret, + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $account['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // Anonymous conversions record the first password + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $this->anonymousHeaders(), [ + 'email' => 'pwned_flag_anonymous_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + /** + * Test for FAILURE + */ + // A forced reset still records the breach before blocking the sign-in + $this->updatePolicy(['enabled' => false]); + + $emailD = 'pwned_flag_d_' . \uniqid() . '@localhost.test'; + + $userD = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $emailD, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Flag User D', + ]); + + $this->assertSame(201, $userD['headers']['status-code']); + $this->assertNull($userD['body']['passwordPwned']); + + $this->updatePolicy(['enabled' => true, 'forceReset' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $emailD, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(412, $response['headers']['status-code']); + $this->assertSame('user_password_reset_required', $response['body']['type']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['passwordPwned']); + + // An outage with a fail-open policy leaves the recorded state untouched and lets the sign-in through + $this->updatePolicy(['endpoint' => self::DEAD_ENDPOINT, 'failClosed' => false]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $emailD, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['passwordPwned']); + + // Filtering on an attribute outside the whitelist is rejected + $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ + 'queries' => [Query::equal('passwordHistory', ['x'])->toString()], + ]); + + $this->assertSame(400, $response['headers']['status-code']); + + $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'forceReset' => false, 'failClosed' => true]); + } + /** * Client headers carrying a fresh anonymous session. * diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index a4b14707d9..92ebe47b5f 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -35,6 +35,33 @@ final class PasswordPwnedTest extends TestCase $this->assertTrue($validator->isForceReset()); } + public function testDisabledPolicyNeverChecks(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $validator = new PasswordPwned(['enabled' => false], null, self::ENDPOINT, new Client($adapter)); + + $this->assertNull($validator->check(self::LEAKED)); + $this->assertTrue($validator->isValid(self::LEAKED)); + $this->assertCount(0, $adapter->requests); + } + + public function testCheckReportsBreachState(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $validator = $this->validator([], $adapter); + + $this->assertTrue($validator->check(self::LEAKED)); + $this->assertFalse($validator->check('never-leaked-' . \uniqid())); + } + + public function testCheckNotRequiredReturnsUnknownOnOutage(): void + { + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $validator = $this->validator(['failClosed' => true], $adapter); + + $this->assertNull($validator->check(self::LEAKED, required: false)); + } + public function testLeakedPasswordIsRejected(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); @@ -107,8 +134,8 @@ final class PasswordPwnedTest extends TestCase $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - (new PasswordPwned([], $cache, 'https://one.test/range', new Client($adapter)))->isValid(self::LEAKED); - (new PasswordPwned([], $cache, 'https://two.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['enabled' => true], $cache, 'https://one.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['enabled' => true], $cache, 'https://two.test/range', new Client($adapter)))->isValid(self::LEAKED); $this->assertCount(2, $adapter->requests); } @@ -148,7 +175,7 @@ final class PasswordPwnedTest extends TestCase { $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); $cache = new Cache(new Memory()); - $validator = new PasswordPwned(['failClosed' => false], $cache, self::ENDPOINT, new Client($adapter)); + $validator = new PasswordPwned(['enabled' => true, 'failClosed' => false], $cache, self::ENDPOINT, new Client($adapter)); $validator->isValid(self::LEAKED); $validator->isValid(self::LEAKED); @@ -170,7 +197,7 @@ final class PasswordPwnedTest extends TestCase public function testAllowEmptySkipsTheLookup(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned([], null, self::ENDPOINT, new Client($adapter), allowEmpty: true); + $validator = new PasswordPwned(['enabled' => true], null, self::ENDPOINT, new Client($adapter), allowEmpty: true); $this->assertTrue($validator->isValid('')); $this->assertCount(0, $adapter->requests); @@ -181,9 +208,9 @@ final class PasswordPwnedTest extends TestCase $adapter = new RangeAdapter(body: ''); $prefix = \substr(\strtoupper(\sha1(self::LEAKED)), 0, 5); - (new PasswordPwned(['endpoint' => 'https://policy.test/range/'], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); - (new PasswordPwned(['endpoint' => ''], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); - (new PasswordPwned([], null, '', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['enabled' => true, 'endpoint' => 'https://policy.test/range/'], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['enabled' => true, 'endpoint' => ''], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['enabled' => true], null, '', new Client($adapter)))->isValid(self::LEAKED); $this->assertSame('https://policy.test/range/' . $prefix, $adapter->requests[0]['url']); $this->assertSame('https://server.test/range/' . $prefix, $adapter->requests[1]['url']); @@ -195,7 +222,7 @@ final class PasswordPwnedTest extends TestCase */ private function validator(array $policy, RangeAdapter $adapter): PasswordPwned { - return new PasswordPwned($policy, null, self::ENDPOINT, new Client($adapter)); + return new PasswordPwned(\array_merge(['enabled' => true], $policy), null, self::ENDPOINT, new Client($adapter)); } /** From e28411b69dc88dafa849bc104192d6eaa6083e4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 13:39:13 +0200 Subject: [PATCH 13/38] refactor(users): rename the passwordPwned user attribute to pwned The project policy key, validator, and resource keep their names; only the users collection attribute, its index, the model rule, the query whitelist, and the local variables change. Co-Authored-By: Claude Fable 5.1 --- app/config/collections/common.php | 6 +-- app/controllers/api/account.php | 44 +++++++++---------- src/Appwrite/Migration/Version/V25.php | 8 ++-- src/Appwrite/Platform/Modules/Users/Base.php | 4 +- .../Modules/Users/Http/Users/Create.php | 6 +-- .../Users/Http/Users/Password/Update.php | 10 ++--- .../Database/Validator/Queries/Users.php | 2 +- .../Utopia/Response/Model/Account.php | 2 +- src/Appwrite/Utopia/Response/Model/User.php | 2 +- .../PoliciesPasswordPwnedIntegrationTest.php | 42 +++++++++--------- 10 files changed, 63 insertions(+), 63 deletions(-) diff --git a/app/config/collections/common.php b/app/config/collections/common.php index 92eefb88b2..c8dcd43351 100644 --- a/app/config/collections/common.php +++ b/app/config/collections/common.php @@ -398,7 +398,7 @@ return [ 'filters' => [], ], [ - '$id' => ID::custom('passwordPwned'), + '$id' => ID::custom('pwned'), 'type' => Database::VAR_BOOLEAN, 'format' => '', 'size' => 0, @@ -500,9 +500,9 @@ return [ 'orders' => [Database::ORDER_ASC], ], [ - '$id' => ID::custom('_key_passwordPwned'), + '$id' => ID::custom('_key_pwned'), 'type' => Database::INDEX_KEY, - 'attributes' => ['passwordPwned'], + 'attributes' => ['pwned'], 'lengths' => [], 'orders' => [Database::ORDER_ASC], ], diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 3286b78f85..ba1b22516d 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -363,8 +363,8 @@ Http::post('/v1/account') } } - $passwordPwned = $pwnedPasswords->check($password); - if ($passwordPwned) { + $pwned = $pwnedPasswords->check($password); + if ($pwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -444,7 +444,7 @@ Http::post('/v1/account') 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], - 'passwordPwned' => $passwordPwned, + 'pwned' => $pwned, ]); $user->removeAttribute('$sequence'); @@ -1049,16 +1049,16 @@ Http::post('/v1/account/sessions/email') $authorization->addRole(Role::user($user->getId())->toString()); // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in - $passwordPwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); + $pwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); - if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { - $user->setAttribute('passwordPwned', $passwordPwned); + if ($pwned !== null && $pwned !== $user->getAttribute('pwned')) { + $user->setAttribute('pwned', $pwned); $dbForProject->updateDocument('users', $user->getId(), new Document([ - 'passwordPwned' => $passwordPwned, + 'pwned' => $pwned, ])); } - if ($passwordPwned && $pwnedPasswords->isForceReset()) { + if ($pwned && $pwnedPasswords->isForceReset()) { throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); } @@ -3507,8 +3507,8 @@ Http::patch('/v1/account/password') } } - $passwordPwned = $pwnedPasswords->check($password); - if ($passwordPwned) { + $pwned = $pwnedPasswords->check($password); + if ($pwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3517,7 +3517,7 @@ Http::patch('/v1/account/password') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) - ->setAttribute('passwordPwned', $passwordPwned) + ->setAttribute('pwned', $pwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()); @@ -3591,7 +3591,7 @@ Http::patch('/v1/account/email') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } - $passwordPwned = null; + $pwned = null; if (empty($passwordUpdate)) { // First password for an anonymous account: apply the same policies as account creation $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); @@ -3611,8 +3611,8 @@ Http::patch('/v1/account/email') } } - $passwordPwned = $pwnedPasswords->check($password); - if ($passwordPwned) { + $pwned = $pwnedPasswords->check($password); + if ($pwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } } @@ -3687,7 +3687,7 @@ Http::patch('/v1/account/email') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) - ->setAttribute('passwordPwned', $passwordPwned) + ->setAttribute('pwned', $pwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -3765,7 +3765,7 @@ Http::patch('/v1/account/phone') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } - $passwordPwned = null; + $pwned = null; if (empty($passwordUpdate)) { // First password for an anonymous account: apply the same policies as account creation $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); @@ -3785,8 +3785,8 @@ Http::patch('/v1/account/phone') } } - $passwordPwned = $pwnedPasswords->check($password); - if ($passwordPwned) { + $pwned = $pwnedPasswords->check($password); + if ($pwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } } @@ -3814,7 +3814,7 @@ Http::patch('/v1/account/phone') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) - ->setAttribute('passwordPwned', $passwordPwned) + ->setAttribute('pwned', $pwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -4232,8 +4232,8 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } - $passwordPwned = $pwnedPasswords->check($password); - if ($passwordPwned) { + $pwned = $pwnedPasswords->check($password); + if ($pwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -4245,7 +4245,7 @@ Http::put('/v1/account/recovery') [ 'password' => $newPassword, 'passwordHistory' => $history, - 'passwordPwned' => $passwordPwned, + 'pwned' => $pwned, 'passwordUpdate' => DateTime::now(), 'hash' => $proofForPassword->getHash()->getName(), 'hashOptions' => $proofForPassword->getHash()->getOptions(), diff --git a/src/Appwrite/Migration/Version/V25.php b/src/Appwrite/Migration/Version/V25.php index d0531ffd5e..549f9c476b 100644 --- a/src/Appwrite/Migration/Version/V25.php +++ b/src/Appwrite/Migration/Version/V25.php @@ -242,15 +242,15 @@ class V25 extends Migration case 'users': try { - $this->createAttributeFromCollection($this->dbForProject, $id, 'passwordPwned'); + $this->createAttributeFromCollection($this->dbForProject, $id, 'pwned'); } catch (Throwable $th) { - Console::warning("Failed to create attribute \"passwordPwned\" in collection {$id}: {$th->getMessage()}"); + Console::warning("Failed to create attribute \"pwned\" in collection {$id}: {$th->getMessage()}"); } try { - $this->createIndexFromCollection($this->dbForProject, $id, '_key_passwordPwned'); + $this->createIndexFromCollection($this->dbForProject, $id, '_key_pwned'); } catch (Throwable $th) { - Console::warning("Failed to create index \"_key_passwordPwned\" from {$id}: {$th->getMessage()}"); + Console::warning("Failed to create index \"_key_pwned\" from {$id}: {$th->getMessage()}"); } $this->dbForProject->purgeCachedCollection($id); diff --git a/src/Appwrite/Platform/Modules/Users/Base.php b/src/Appwrite/Platform/Modules/Users/Base.php index bd48b7b015..92c8ffe6ea 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -21,7 +21,7 @@ use Utopia\Emails\Email; class Base extends Action { - protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan, ?bool $passwordPwned = null): Document + protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan, ?bool $pwned = null): Document { $name = $name ?? ''; $plaintextPassword = $password; @@ -144,7 +144,7 @@ class Base extends Action 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], - 'passwordPwned' => $passwordPwned, + 'pwned' => $pwned, ]); if (!$isHashed && !empty($password)) { diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php index 5fa213f83c..838495a521 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php @@ -74,14 +74,14 @@ class Create extends Base public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords): void { - $passwordPwned = empty($password) ? null : $pwnedPasswords->check($password); - if ($passwordPwned) { + $pwned = empty($password) ? null : $pwnedPasswords->check($password); + if ($pwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } $plaintext = new Plaintext(); - $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan, $passwordPwned); + $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan, $pwned); $response ->setStatusCode(Response::STATUS_CODE_CREATED) diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index aba1363d92..822fc51606 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -86,8 +86,8 @@ class Update extends Action } } - $passwordPwned = \strlen($password) === 0 ? null : $pwnedPasswords->check($password); - if ($passwordPwned) { + $pwned = \strlen($password) === 0 ? null : $pwnedPasswords->check($password); + if ($pwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -98,7 +98,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), - 'passwordPwned' => null, + 'pwned' => null, 'passwordUpdate' => $user->getAttribute('passwordUpdate'), ])); $queueForEvents->setParam('userId', $user->getId()); @@ -129,7 +129,7 @@ class Update extends Action $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) - ->setAttribute('passwordPwned', $passwordPwned) + ->setAttribute('pwned', $pwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $hasher->getName()) ->setAttribute('hashOptions', $hasher->getOptions()); @@ -137,7 +137,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), 'passwordHistory' => $user->getAttribute('passwordHistory'), - 'passwordPwned' => $user->getAttribute('passwordPwned'), + 'pwned' => $user->getAttribute('pwned'), 'passwordUpdate' => $user->getAttribute('passwordUpdate'), 'hash' => $user->getAttribute('hash'), 'hashOptions' => $user->getAttribute('hashOptions'), diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php index e2e721c8c2..9762a51b8b 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php @@ -13,7 +13,7 @@ class Users extends Base 'registration', 'emailVerification', 'phoneVerification', - 'passwordPwned', + 'pwned', 'labels', 'impersonator', 'accessedAt', diff --git a/src/Appwrite/Utopia/Response/Model/Account.php b/src/Appwrite/Utopia/Response/Model/Account.php index c716c24649..b6375f98f5 100644 --- a/src/Appwrite/Utopia/Response/Model/Account.php +++ b/src/Appwrite/Utopia/Response/Model/Account.php @@ -113,7 +113,7 @@ class Account extends Model 'default' => null, 'example' => true, ]) - ->addRule('passwordPwned', [ + ->addRule('pwned', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', 'required' => false, diff --git a/src/Appwrite/Utopia/Response/Model/User.php b/src/Appwrite/Utopia/Response/Model/User.php index 91d4ca7e54..d76eefb446 100644 --- a/src/Appwrite/Utopia/Response/Model/User.php +++ b/src/Appwrite/Utopia/Response/Model/User.php @@ -143,7 +143,7 @@ class User extends Model 'default' => null, 'example' => true, ]) - ->addRule('passwordPwned', [ + ->addRule('pwned', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', 'required' => false, diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 2a78a4ae3c..19c018b66b 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -739,8 +739,8 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userA['headers']['status-code']); - $this->assertArrayHasKey('passwordPwned', $userA['body']); - $this->assertNull($userA['body']['passwordPwned']); + $this->assertArrayHasKey('pwned', $userA['body']); + $this->assertNull($userA['body']['pwned']); // Policy on: a clean password is recorded as clean $this->updatePolicy(['enabled' => true]); @@ -753,12 +753,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userB['headers']['status-code']); - $this->assertFalse($userB['body']['passwordPwned']); + $this->assertFalse($userB['body']['pwned']); $response = $this->client->call(Client::METHOD_GET, '/users/' . $userB['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['passwordPwned']); + $this->assertFalse($response['body']['pwned']); // A hashed import never sees the plaintext, so nothing is known $userC = $this->client->call(Client::METHOD_POST, '/users/sha', $this->serverHeaders(), [ @@ -770,7 +770,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userC['headers']['status-code']); - $this->assertNull($userC['body']['passwordPwned']); + $this->assertNull($userC['body']['pwned']); // Signing in records a breached password, on the users and the account API $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ @@ -783,7 +783,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $userA['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['passwordPwned']); + $this->assertTrue($response['body']['pwned']); $projectId = $this->getProject()['$id']; $response = $this->client->call(Client::METHOD_GET, '/account', \array_merge($this->clientHeaders(), [ @@ -791,14 +791,14 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ])); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['passwordPwned']); + $this->assertTrue($response['body']['pwned']); // Listing users can filter on the flag $ids = fn (array $response) => \array_column($response['body']['users'], '$id'); $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ 'queries' => [ - Query::equal('passwordPwned', [true])->toString(), + Query::equal('pwned', [true])->toString(), Query::orderDesc('$createdAt')->toString(), Query::limit(100)->toString(), ], @@ -811,7 +811,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ 'queries' => [ - Query::equal('passwordPwned', [false])->toString(), + Query::equal('pwned', [false])->toString(), Query::orderDesc('$createdAt')->toString(), Query::limit(100)->toString(), ], @@ -824,7 +824,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ 'queries' => [ - Query::isNull('passwordPwned')->toString(), + Query::isNull('pwned')->toString(), Query::orderDesc('$createdAt')->toString(), Query::limit(100)->toString(), ], @@ -841,7 +841,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['passwordPwned']); + $this->assertFalse($response['body']['pwned']); // Without the policy a new password is unknown again $this->updatePolicy(['enabled' => false]); @@ -851,7 +851,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertNull($response['body']['passwordPwned']); + $this->assertNull($response['body']['pwned']); // Clearing the password clears the flag $this->updatePolicy(['enabled' => true]); @@ -861,7 +861,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertNull($response['body']['passwordPwned']); + $this->assertNull($response['body']['pwned']); $this->updatePolicy(['enabled' => false]); } @@ -884,7 +884,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $account['headers']['status-code']); - $this->assertFalse($account['body']['passwordPwned']); + $this->assertFalse($account['body']['pwned']); $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -901,7 +901,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/account', $headers); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['passwordPwned']); + $this->assertFalse($response['body']['pwned']); $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ 'password' => $this->cleanPassword(), @@ -909,7 +909,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['passwordPwned']); + $this->assertFalse($response['body']['pwned']); // Recovery records the new password too $recovery = $this->client->call(Client::METHOD_POST, '/account/recovery', $this->clientHeaders(), [ @@ -935,7 +935,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $account['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['passwordPwned']); + $this->assertFalse($response['body']['pwned']); // Anonymous conversions record the first password $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $this->anonymousHeaders(), [ @@ -944,7 +944,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['passwordPwned']); + $this->assertFalse($response['body']['pwned']); /** * Test for FAILURE @@ -962,7 +962,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userD['headers']['status-code']); - $this->assertNull($userD['body']['passwordPwned']); + $this->assertNull($userD['body']['pwned']); $this->updatePolicy(['enabled' => true, 'forceReset' => true]); @@ -977,7 +977,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['passwordPwned']); + $this->assertTrue($response['body']['pwned']); // An outage with a fail-open policy leaves the recorded state untouched and lets the sign-in through $this->updatePolicy(['endpoint' => self::DEAD_ENDPOINT, 'failClosed' => false]); @@ -992,7 +992,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['passwordPwned']); + $this->assertTrue($response['body']['pwned']); // Filtering on an attribute outside the whitelist is rejected $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ From 81b6bdea54e5033fd9181475e613e8de7f3a79d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 13:39:29 +0200 Subject: [PATCH 14/38] Revert "refactor(users): rename the passwordPwned user attribute to pwned" This reverts commit e28411b69dc88dafa849bc104192d6eaa6083e4d. --- app/config/collections/common.php | 6 +-- app/controllers/api/account.php | 44 +++++++++---------- src/Appwrite/Migration/Version/V25.php | 8 ++-- src/Appwrite/Platform/Modules/Users/Base.php | 4 +- .../Modules/Users/Http/Users/Create.php | 6 +-- .../Users/Http/Users/Password/Update.php | 10 ++--- .../Database/Validator/Queries/Users.php | 2 +- .../Utopia/Response/Model/Account.php | 2 +- src/Appwrite/Utopia/Response/Model/User.php | 2 +- .../PoliciesPasswordPwnedIntegrationTest.php | 42 +++++++++--------- 10 files changed, 63 insertions(+), 63 deletions(-) diff --git a/app/config/collections/common.php b/app/config/collections/common.php index c8dcd43351..92eefb88b2 100644 --- a/app/config/collections/common.php +++ b/app/config/collections/common.php @@ -398,7 +398,7 @@ return [ 'filters' => [], ], [ - '$id' => ID::custom('pwned'), + '$id' => ID::custom('passwordPwned'), 'type' => Database::VAR_BOOLEAN, 'format' => '', 'size' => 0, @@ -500,9 +500,9 @@ return [ 'orders' => [Database::ORDER_ASC], ], [ - '$id' => ID::custom('_key_pwned'), + '$id' => ID::custom('_key_passwordPwned'), 'type' => Database::INDEX_KEY, - 'attributes' => ['pwned'], + 'attributes' => ['passwordPwned'], 'lengths' => [], 'orders' => [Database::ORDER_ASC], ], diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index ba1b22516d..3286b78f85 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -363,8 +363,8 @@ Http::post('/v1/account') } } - $pwned = $pwnedPasswords->check($password); - if ($pwned) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -444,7 +444,7 @@ Http::post('/v1/account') 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], - 'pwned' => $pwned, + 'passwordPwned' => $passwordPwned, ]); $user->removeAttribute('$sequence'); @@ -1049,16 +1049,16 @@ Http::post('/v1/account/sessions/email') $authorization->addRole(Role::user($user->getId())->toString()); // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in - $pwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); + $passwordPwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); - if ($pwned !== null && $pwned !== $user->getAttribute('pwned')) { - $user->setAttribute('pwned', $pwned); + if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { + $user->setAttribute('passwordPwned', $passwordPwned); $dbForProject->updateDocument('users', $user->getId(), new Document([ - 'pwned' => $pwned, + 'passwordPwned' => $passwordPwned, ])); } - if ($pwned && $pwnedPasswords->isForceReset()) { + if ($passwordPwned && $pwnedPasswords->isForceReset()) { throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); } @@ -3507,8 +3507,8 @@ Http::patch('/v1/account/password') } } - $pwned = $pwnedPasswords->check($password); - if ($pwned) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3517,7 +3517,7 @@ Http::patch('/v1/account/password') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) - ->setAttribute('pwned', $pwned) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()); @@ -3591,7 +3591,7 @@ Http::patch('/v1/account/email') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } - $pwned = null; + $passwordPwned = null; if (empty($passwordUpdate)) { // First password for an anonymous account: apply the same policies as account creation $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); @@ -3611,8 +3611,8 @@ Http::patch('/v1/account/email') } } - $pwned = $pwnedPasswords->check($password); - if ($pwned) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } } @@ -3687,7 +3687,7 @@ Http::patch('/v1/account/email') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) - ->setAttribute('pwned', $pwned) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -3765,7 +3765,7 @@ Http::patch('/v1/account/phone') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } - $pwned = null; + $passwordPwned = null; if (empty($passwordUpdate)) { // First password for an anonymous account: apply the same policies as account creation $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); @@ -3785,8 +3785,8 @@ Http::patch('/v1/account/phone') } } - $pwned = $pwnedPasswords->check($password); - if ($pwned) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } } @@ -3814,7 +3814,7 @@ Http::patch('/v1/account/phone') $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) - ->setAttribute('pwned', $pwned) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -4232,8 +4232,8 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } - $pwned = $pwnedPasswords->check($password); - if ($pwned) { + $passwordPwned = $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -4245,7 +4245,7 @@ Http::put('/v1/account/recovery') [ 'password' => $newPassword, 'passwordHistory' => $history, - 'pwned' => $pwned, + 'passwordPwned' => $passwordPwned, 'passwordUpdate' => DateTime::now(), 'hash' => $proofForPassword->getHash()->getName(), 'hashOptions' => $proofForPassword->getHash()->getOptions(), diff --git a/src/Appwrite/Migration/Version/V25.php b/src/Appwrite/Migration/Version/V25.php index 549f9c476b..d0531ffd5e 100644 --- a/src/Appwrite/Migration/Version/V25.php +++ b/src/Appwrite/Migration/Version/V25.php @@ -242,15 +242,15 @@ class V25 extends Migration case 'users': try { - $this->createAttributeFromCollection($this->dbForProject, $id, 'pwned'); + $this->createAttributeFromCollection($this->dbForProject, $id, 'passwordPwned'); } catch (Throwable $th) { - Console::warning("Failed to create attribute \"pwned\" in collection {$id}: {$th->getMessage()}"); + Console::warning("Failed to create attribute \"passwordPwned\" in collection {$id}: {$th->getMessage()}"); } try { - $this->createIndexFromCollection($this->dbForProject, $id, '_key_pwned'); + $this->createIndexFromCollection($this->dbForProject, $id, '_key_passwordPwned'); } catch (Throwable $th) { - Console::warning("Failed to create index \"_key_pwned\" from {$id}: {$th->getMessage()}"); + Console::warning("Failed to create index \"_key_passwordPwned\" from {$id}: {$th->getMessage()}"); } $this->dbForProject->purgeCachedCollection($id); diff --git a/src/Appwrite/Platform/Modules/Users/Base.php b/src/Appwrite/Platform/Modules/Users/Base.php index 92c8ffe6ea..bd48b7b015 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -21,7 +21,7 @@ use Utopia\Emails\Email; class Base extends Action { - protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan, ?bool $pwned = null): Document + protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan, ?bool $passwordPwned = null): Document { $name = $name ?? ''; $plaintextPassword = $password; @@ -144,7 +144,7 @@ class Base extends Action 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], - 'pwned' => $pwned, + 'passwordPwned' => $passwordPwned, ]); if (!$isHashed && !empty($password)) { diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php index 838495a521..5fa213f83c 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php @@ -74,14 +74,14 @@ class Create extends Base public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords): void { - $pwned = empty($password) ? null : $pwnedPasswords->check($password); - if ($pwned) { + $passwordPwned = empty($password) ? null : $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } $plaintext = new Plaintext(); - $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan, $pwned); + $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan, $passwordPwned); $response ->setStatusCode(Response::STATUS_CODE_CREATED) diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index 822fc51606..aba1363d92 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -86,8 +86,8 @@ class Update extends Action } } - $pwned = \strlen($password) === 0 ? null : $pwnedPasswords->check($password); - if ($pwned) { + $passwordPwned = \strlen($password) === 0 ? null : $pwnedPasswords->check($password); + if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -98,7 +98,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), - 'pwned' => null, + 'passwordPwned' => null, 'passwordUpdate' => $user->getAttribute('passwordUpdate'), ])); $queueForEvents->setParam('userId', $user->getId()); @@ -129,7 +129,7 @@ class Update extends Action $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) - ->setAttribute('pwned', $pwned) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $hasher->getName()) ->setAttribute('hashOptions', $hasher->getOptions()); @@ -137,7 +137,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), 'passwordHistory' => $user->getAttribute('passwordHistory'), - 'pwned' => $user->getAttribute('pwned'), + 'passwordPwned' => $user->getAttribute('passwordPwned'), 'passwordUpdate' => $user->getAttribute('passwordUpdate'), 'hash' => $user->getAttribute('hash'), 'hashOptions' => $user->getAttribute('hashOptions'), diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php index 9762a51b8b..e2e721c8c2 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php @@ -13,7 +13,7 @@ class Users extends Base 'registration', 'emailVerification', 'phoneVerification', - 'pwned', + 'passwordPwned', 'labels', 'impersonator', 'accessedAt', diff --git a/src/Appwrite/Utopia/Response/Model/Account.php b/src/Appwrite/Utopia/Response/Model/Account.php index b6375f98f5..c716c24649 100644 --- a/src/Appwrite/Utopia/Response/Model/Account.php +++ b/src/Appwrite/Utopia/Response/Model/Account.php @@ -113,7 +113,7 @@ class Account extends Model 'default' => null, 'example' => true, ]) - ->addRule('pwned', [ + ->addRule('passwordPwned', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', 'required' => false, diff --git a/src/Appwrite/Utopia/Response/Model/User.php b/src/Appwrite/Utopia/Response/Model/User.php index d76eefb446..91d4ca7e54 100644 --- a/src/Appwrite/Utopia/Response/Model/User.php +++ b/src/Appwrite/Utopia/Response/Model/User.php @@ -143,7 +143,7 @@ class User extends Model 'default' => null, 'example' => true, ]) - ->addRule('pwned', [ + ->addRule('passwordPwned', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', 'required' => false, diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 19c018b66b..2a78a4ae3c 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -739,8 +739,8 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userA['headers']['status-code']); - $this->assertArrayHasKey('pwned', $userA['body']); - $this->assertNull($userA['body']['pwned']); + $this->assertArrayHasKey('passwordPwned', $userA['body']); + $this->assertNull($userA['body']['passwordPwned']); // Policy on: a clean password is recorded as clean $this->updatePolicy(['enabled' => true]); @@ -753,12 +753,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userB['headers']['status-code']); - $this->assertFalse($userB['body']['pwned']); + $this->assertFalse($userB['body']['passwordPwned']); $response = $this->client->call(Client::METHOD_GET, '/users/' . $userB['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['pwned']); + $this->assertFalse($response['body']['passwordPwned']); // A hashed import never sees the plaintext, so nothing is known $userC = $this->client->call(Client::METHOD_POST, '/users/sha', $this->serverHeaders(), [ @@ -770,7 +770,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userC['headers']['status-code']); - $this->assertNull($userC['body']['pwned']); + $this->assertNull($userC['body']['passwordPwned']); // Signing in records a breached password, on the users and the account API $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ @@ -783,7 +783,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $userA['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['pwned']); + $this->assertTrue($response['body']['passwordPwned']); $projectId = $this->getProject()['$id']; $response = $this->client->call(Client::METHOD_GET, '/account', \array_merge($this->clientHeaders(), [ @@ -791,14 +791,14 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ])); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['pwned']); + $this->assertTrue($response['body']['passwordPwned']); // Listing users can filter on the flag $ids = fn (array $response) => \array_column($response['body']['users'], '$id'); $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ 'queries' => [ - Query::equal('pwned', [true])->toString(), + Query::equal('passwordPwned', [true])->toString(), Query::orderDesc('$createdAt')->toString(), Query::limit(100)->toString(), ], @@ -811,7 +811,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ 'queries' => [ - Query::equal('pwned', [false])->toString(), + Query::equal('passwordPwned', [false])->toString(), Query::orderDesc('$createdAt')->toString(), Query::limit(100)->toString(), ], @@ -824,7 +824,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ 'queries' => [ - Query::isNull('pwned')->toString(), + Query::isNull('passwordPwned')->toString(), Query::orderDesc('$createdAt')->toString(), Query::limit(100)->toString(), ], @@ -841,7 +841,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['pwned']); + $this->assertFalse($response['body']['passwordPwned']); // Without the policy a new password is unknown again $this->updatePolicy(['enabled' => false]); @@ -851,7 +851,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertNull($response['body']['pwned']); + $this->assertNull($response['body']['passwordPwned']); // Clearing the password clears the flag $this->updatePolicy(['enabled' => true]); @@ -861,7 +861,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertNull($response['body']['pwned']); + $this->assertNull($response['body']['passwordPwned']); $this->updatePolicy(['enabled' => false]); } @@ -884,7 +884,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $account['headers']['status-code']); - $this->assertFalse($account['body']['pwned']); + $this->assertFalse($account['body']['passwordPwned']); $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -901,7 +901,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/account', $headers); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['pwned']); + $this->assertFalse($response['body']['passwordPwned']); $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ 'password' => $this->cleanPassword(), @@ -909,7 +909,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['pwned']); + $this->assertFalse($response['body']['passwordPwned']); // Recovery records the new password too $recovery = $this->client->call(Client::METHOD_POST, '/account/recovery', $this->clientHeaders(), [ @@ -935,7 +935,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $account['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['pwned']); + $this->assertFalse($response['body']['passwordPwned']); // Anonymous conversions record the first password $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $this->anonymousHeaders(), [ @@ -944,7 +944,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(200, $response['headers']['status-code']); - $this->assertFalse($response['body']['pwned']); + $this->assertFalse($response['body']['passwordPwned']); /** * Test for FAILURE @@ -962,7 +962,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ]); $this->assertSame(201, $userD['headers']['status-code']); - $this->assertNull($userD['body']['pwned']); + $this->assertNull($userD['body']['passwordPwned']); $this->updatePolicy(['enabled' => true, 'forceReset' => true]); @@ -977,7 +977,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['pwned']); + $this->assertTrue($response['body']['passwordPwned']); // An outage with a fail-open policy leaves the recorded state untouched and lets the sign-in through $this->updatePolicy(['endpoint' => self::DEAD_ENDPOINT, 'failClosed' => false]); @@ -992,7 +992,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['pwned']); + $this->assertTrue($response['body']['passwordPwned']); // Filtering on an attribute outside the whitelist is rejected $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ From f559b4a55fadcbb8ed0d8b4d8aefe857eb55b03e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 14:23:14 +0200 Subject: [PATCH 15/38] feat(policies): optional sign-in checks and pwned policy on by default Adds a `sessions` option to the password pwned policy, off by default, controlling whether passwords are checked when a session is created. `forceReset` now only applies when sessions are checked, giving three sign-in modes: no check, check and record, check and block. Flips the policy defaults so `enabled` is true. New and existing projects reject breached passwords out of the box, while sign-in checks stay opt-in. The mock range endpoint reports distinctive fixtures now, so enabling the policy by default cannot collide with passwords other suites use. Co-Authored-By: Claude Opus 5 (1M context) --- app/controllers/api/account.php | 22 +- app/controllers/mock.php | 6 +- src/Appwrite/Auth/Validator/PasswordPwned.php | 14 +- .../Organization/Http/Projects/Create.php | 3 +- .../Project/Http/Project/Policies/Get.php | 3 +- .../Project/Policies/PasswordPwned/Update.php | 14 +- .../Project/Http/Project/Policies/XList.php | 3 +- .../Modules/Projects/Http/Projects/Create.php | 3 +- .../Response/Model/PolicyPasswordPwned.php | 10 +- tests/e2e/Services/Project/PoliciesBase.php | 37 ++- .../PoliciesPasswordPwnedIntegrationTest.php | 238 ++++++++++++++---- .../unit/Auth/Validator/PasswordPwnedTest.php | 15 +- 12 files changed, 292 insertions(+), 76 deletions(-) diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 3286b78f85..38b260b718 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -1048,18 +1048,20 @@ Http::post('/v1/account/sessions/email') $authorization->addRole(Role::user($user->getId())->toString()); - // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in - $passwordPwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); + if ($pwnedPasswords->checksSessions()) { + // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in + $passwordPwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); - if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { - $user->setAttribute('passwordPwned', $passwordPwned); - $dbForProject->updateDocument('users', $user->getId(), new Document([ - 'passwordPwned' => $passwordPwned, - ])); - } + if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { + $user->setAttribute('passwordPwned', $passwordPwned); + $dbForProject->updateDocument('users', $user->getId(), new Document([ + 'passwordPwned' => $passwordPwned, + ])); + } - if ($passwordPwned && $pwnedPasswords->isForceReset()) { - throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); + if ($passwordPwned && $pwnedPasswords->isForceReset()) { + throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); + } } // Re-hash if not using recommended algo diff --git a/app/controllers/mock.php b/app/controllers/mock.php index 6470b4eafa..3b745fa501 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -514,9 +514,9 @@ Http::get('/v1/mock/tests/general/pwned-passwords/:prefix') // Mirrors the Have I Been Pwned range API: every leaked hash sharing the // requested prefix comes back as `SUFFIX:COUNT`, one per line. $leaked = [ - 'Password123!' => 12345, - 'Summer2024!' => 678, - 'letmein1234' => 9, + 'pwned-fixture-common' => 12345, + 'pwned-fixture-uncommon' => 678, + 'pwned-fixture-rare' => 9, ]; $prefix = \strtoupper($prefix); diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index e0ca9ce919..ea03f3cc86 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -27,6 +27,7 @@ class PasswordPwned extends Password protected bool $enabled; protected string $endpoint; protected int $threshold; + protected bool $sessions; protected bool $forceReset; protected bool $failClosed; protected ?Cache $cache; @@ -40,9 +41,10 @@ class PasswordPwned extends Password { parent::__construct($allowEmpty); - $this->enabled = (bool) ($policy['enabled'] ?? false); + $this->enabled = (bool) ($policy['enabled'] ?? true); $this->endpoint = \rtrim(($policy['endpoint'] ?? '') ?: ($endpoint ?: self::ENDPOINT), '/'); $this->threshold = \max(1, (int) ($policy['threshold'] ?? 1)); + $this->sessions = (bool) ($policy['sessions'] ?? false); $this->forceReset = (bool) ($policy['forceReset'] ?? false); $this->failClosed = (bool) ($policy['failClosed'] ?? true); $this->cache = $cache; @@ -61,8 +63,18 @@ class PasswordPwned extends Password return $this->enabled; } + /** + * Whether passwords are checked when a session is created. + */ + public function checksSessions(): bool + { + return $this->enabled && $this->sessions; + } + /** * Whether a breached password blocks sign-in until it is reset. + * + * Only takes effect when sessions are checked. */ public function isForceReset(): bool { diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index 2361d6a31d..6bde4e883d 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -92,9 +92,10 @@ class Create extends Action 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, 'passwordPwned' => [ - 'enabled' => false, + 'enabled' => true, 'endpoint' => '', 'threshold' => 1, + 'sessions' => false, 'forceReset' => false, 'failClosed' => true, ], diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php index 98e2654925..cb064d294b 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php @@ -137,9 +137,10 @@ class Get extends Action ], 'password-pwned' => [ new Document(\array_merge([ - 'enabled' => false, + 'enabled' => true, 'endpoint' => '', 'threshold' => 1, + 'sessions' => false, 'forceReset' => false, 'failClosed' => true, ], $auths['passwordPwned'] ?? [], [ diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php index 9aef08278d..799440ef41 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -45,7 +45,7 @@ class Update extends Action group: 'policies', name: 'updatePasswordPwnedPolicy', description: <<param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true to block passwords exposed in known data breaches, or false to allow them. When changing this policy, existing passwords remain valid.', optional: true) + ->param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true to block passwords exposed in known data breaches, or false to allow them. Default is true. When changing this policy, existing passwords remain valid.', optional: true) ->param('endpoint', null, new AnyOf([new WhiteList([''], true), new Multiple([new URL(['http', 'https']), new PublicDomain()], Multiple::TYPE_STRING)], AnyOf::TYPE_STRING), 'Custom endpoint of a Have I Been Pwned compatible range API, for example a self-hosted mirror. Pass an empty string to use the server default.', optional: true) ->param('threshold', null, new Range(1, PHP_INT_MAX), 'Minimum number of known breaches a password must appear in before it is rejected. Default is 1.', optional: true) - ->param('forceReset', null, new Boolean(), 'Whether signing in with a breached password is blocked until the password is reset. Default is false, which allows the sign-in.', optional: true) + ->param('sessions', null, new Boolean(), 'Whether passwords are checked when a session is created. When enabled, signing in records whether the password appears in a known data breach. Default is false.', optional: true) + ->param('forceReset', null, new Boolean(), 'Whether signing in with a breached password is blocked until the password is reset. Only applies when sessions are checked. Default is false, which allows the sign-in.', optional: true) ->param('failClosed', null, new Boolean(), 'Whether passwords are rejected when the breach service cannot be reached. Default is true. Set to false to skip the check instead.', optional: true) ->inject('response') ->inject('dbForPlatform') @@ -72,6 +73,7 @@ class Update extends Action ?bool $enabled, ?string $endpoint, ?int $threshold, + ?bool $sessions, ?bool $forceReset, ?bool $failClosed, Response $response, @@ -82,9 +84,10 @@ class Update extends Action ): void { $auths = $project->getAttribute('auths', []); $auths['passwordPwned'] = \array_merge([ - 'enabled' => false, + 'enabled' => true, 'endpoint' => '', 'threshold' => 1, + 'sessions' => false, 'forceReset' => false, 'failClosed' => true, ], $auths['passwordPwned'] ?? []); @@ -98,6 +101,9 @@ class Update extends Action if ($threshold !== null) { $auths['passwordPwned']['threshold'] = $threshold; } + if ($sessions !== null) { + $auths['passwordPwned']['sessions'] = $sessions; + } if ($forceReset !== null) { $auths['passwordPwned']['forceReset'] = $forceReset; } diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php index 8d5d85ec50..6b8d8c1073 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php @@ -117,9 +117,10 @@ class XList extends Action 'enabled' => $auths['personalDataCheck'] ?? false, ]), new Document(\array_merge([ - 'enabled' => false, + 'enabled' => true, 'endpoint' => '', 'threshold' => 1, + 'sessions' => false, 'forceReset' => false, 'failClosed' => true, ], $auths['passwordPwned'] ?? [], [ diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php index 9182796e9a..0176d68605 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -89,9 +89,10 @@ class Create extends Action 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, 'passwordPwned' => [ - 'enabled' => false, + 'enabled' => true, 'endpoint' => '', 'threshold' => 1, + 'sessions' => false, 'forceReset' => false, 'failClosed' => true, ], diff --git a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php index fb258a8ebb..2ae371e4da 100644 --- a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -18,7 +18,7 @@ class PolicyPasswordPwned extends PolicyBase ->addRule('enabled', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Whether password pwned policy is enabled.', - 'default' => false, + 'default' => true, 'example' => true, ]) ->addRule('endpoint', [ @@ -33,9 +33,15 @@ class PolicyPasswordPwned extends PolicyBase 'default' => 1, 'example' => 1, ]) + ->addRule('sessions', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether passwords are checked when a session is created.', + 'default' => false, + 'example' => false, + ]) ->addRule('forceReset', [ 'type' => self::TYPE_BOOLEAN, - 'description' => 'Whether signing in with a breached password is blocked until the password is reset.', + 'description' => 'Whether signing in with a breached password is blocked until the password is reset. Only applies when sessions are checked.', 'default' => false, 'example' => false, ]) diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index b06dd0b791..ca7cb73fc6 100644 --- a/tests/e2e/Services/Project/PoliciesBase.php +++ b/tests/e2e/Services/Project/PoliciesBase.php @@ -17,7 +17,7 @@ trait PoliciesBase 'password-history' => ['total'], 'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'], 'password-personal-data' => ['enabled'], - 'password-pwned' => ['enabled', 'endpoint', 'threshold', 'forceReset', 'failClosed'], + 'password-pwned' => ['enabled', 'endpoint', 'threshold', 'sessions', 'forceReset', 'failClosed'], 'session-alert' => ['enabled'], 'session-duration' => ['duration'], 'session-invalidation' => ['enabled'], @@ -652,6 +652,7 @@ trait PoliciesBase $this->assertSame(true, $policy['body']['enabled']); $this->assertSame('', $policy['body']['endpoint']); $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['sessions']); $this->assertSame(false, $policy['body']['forceReset']); $this->assertSame(true, $policy['body']['failClosed']); @@ -672,24 +673,45 @@ trait PoliciesBase $this->assertSame(false, $policy['body']['enabled']); } - public function testUpdatePasswordPwnedPolicyDisabledByDefault(): void + public function testUpdatePasswordPwnedPolicyDefaults(): void { + $this->resetPasswordPwnedPolicy(); + $policy = $this->getPolicy('password-pwned'); $this->assertSame(200, $policy['headers']['status-code']); $this->assertSame('password-pwned', $policy['body']['$id']); - $this->assertSame(false, $policy['body']['enabled']); + $this->assertSame(true, $policy['body']['enabled']); $this->assertSame('', $policy['body']['endpoint']); $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['sessions']); $this->assertSame(false, $policy['body']['forceReset']); $this->assertSame(true, $policy['body']['failClosed']); } + public function testUpdatePasswordPwnedPolicySessions(): void + { + $response = $this->updatePasswordPwnedPolicy(['sessions' => true]); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(true, $policy['body']['sessions']); + + $response = $this->updatePasswordPwnedPolicy(['sessions' => false]); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(false, $policy['body']['sessions']); + } + public function testUpdatePasswordPwnedPolicyOptionPreservesOtherOptions(): void { $response = $this->updatePasswordPwnedPolicy([ 'endpoint' => 'https://example.com/range', 'threshold' => 5, + 'sessions' => true, 'forceReset' => true, 'failClosed' => false, ]); @@ -704,6 +726,7 @@ trait PoliciesBase $this->assertSame(true, $policy['body']['enabled']); $this->assertSame('https://example.com/range', $policy['body']['endpoint']); $this->assertSame(5, $policy['body']['threshold']); + $this->assertSame(true, $policy['body']['sessions']); $this->assertSame(true, $policy['body']['forceReset']); $this->assertSame(false, $policy['body']['failClosed']); @@ -720,16 +743,17 @@ trait PoliciesBase $this->assertSame(200, $response['headers']['status-code']); $policy = $this->getPolicy('password-pwned'); - $this->assertSame(false, $policy['body']['enabled']); + $this->assertSame(true, $policy['body']['enabled']); $this->assertSame('', $policy['body']['endpoint']); $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['sessions']); $this->assertSame(false, $policy['body']['forceReset']); $this->assertSame(true, $policy['body']['failClosed']); } public function testUpdatePasswordPwnedPolicyInvalidType(): void { - foreach (['enabled', 'forceReset', 'failClosed'] as $option) { + foreach (['enabled', 'sessions', 'forceReset', 'failClosed'] as $option) { $response = $this->updatePasswordPwnedPolicy([$option => 'not-a-boolean']); $this->assertSame(400, $response['headers']['status-code'], $option); @@ -1468,9 +1492,10 @@ trait PoliciesBase protected function resetPasswordPwnedPolicy(): void { $this->updatePasswordPwnedPolicy([ - 'enabled' => false, + 'enabled' => true, 'endpoint' => '', 'threshold' => 1, + 'sessions' => false, 'forceReset' => false, 'failClosed' => true, ]); diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 2a78a4ae3c..a773824c5c 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -21,8 +21,8 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope use SideServer; // Reported as breached by the mock range endpoint, 12345 and 9 times respectively - private const PWNED_PASSWORD = 'Password123!'; - private const RARELY_PWNED_PASSWORD = 'letmein1234'; + private const PWNED_PASSWORD = 'pwned-fixture-common'; + private const RARELY_PWNED_PASSWORD = 'pwned-fixture-rare'; // The mock range endpoint the stack already uses through _APP_PWNED_PASSWORDS_ENDPOINT private const MOCK_ENDPOINT = 'http://localhost/v1/mock/tests/general/pwned-passwords'; @@ -30,6 +30,44 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope // Nothing listens here, so lookups fail private const DEAD_ENDPOINT = 'http://localhost:1/range'; + public function testDefaultsOnNewProject(): void + { + // A project created through the real endpoint, so these are the shipped defaults + $project = $this->getProject(fresh: true); + + $headers = [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $project['$id'], + 'x-appwrite-key' => $project['apiKey'], + ]; + + $response = $this->client->call(Client::METHOD_GET, '/project/policies/password-pwned', $headers); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertSame('password-pwned', $response['body']['$id']); + + // Breached passwords are rejected out of the box + $this->assertTrue($response['body']['enabled']); + $this->assertTrue($response['body']['failClosed']); + $this->assertSame(1, $response['body']['threshold']); + $this->assertSame('', $response['body']['endpoint']); + + // Sign-in checks stay opt-in + $this->assertFalse($response['body']['sessions']); + $this->assertFalse($response['body']['forceReset']); + + // A breached password is blocked without touching the policy + $response = $this->client->call(Client::METHOD_POST, '/users', $headers, [ + 'userId' => ID::unique(), + 'email' => 'pwned_default_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Default Policy User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + } + public function testCreateUserWithPolicyDisabled(): void { $this->updatePolicy(['enabled' => false]); @@ -399,7 +437,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $user['headers']['status-code']); - $this->updatePolicy(['enabled' => true, 'forceReset' => true]); + $this->updatePolicy(['enabled' => true, 'sessions' => true, 'forceReset' => true]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -430,7 +468,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); - $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'forceReset' => false, 'failClosed' => true]); + $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => true]); } public function testForceResetOnSignIn(): void @@ -451,7 +489,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope /** * Test for SUCCESS */ - $this->updatePolicy(['enabled' => true, 'forceReset' => false]); + $this->updatePolicy(['enabled' => true, 'sessions' => true, 'forceReset' => false]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -500,7 +538,73 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); - $this->updatePolicy(['enabled' => false, 'forceReset' => false]); + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'forceReset' => false]); + } + + public function testSessionChecksAreOptional(): void + { + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_sessions_' . \uniqid() . '@localhost.test'; + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Sessions User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + $this->assertNull($user['body']['passwordPwned']); + + /** + * Test for SUCCESS + */ + // Sign-in checks are off by default, so a forced reset has nothing to act on + $this->updatePolicy(['enabled' => true, 'sessions' => false, 'forceReset' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + // Nothing was looked up, so nothing was recorded + $response = $this->client->call(Client::METHOD_GET, '/users/' . $user['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNull($response['body']['passwordPwned']); + + // Checking sessions without forcing a reset records the breach and still allows the sign-in + $this->updatePolicy(['sessions' => true, 'forceReset' => false]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $user['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['passwordPwned']); + + /** + * Test for FAILURE + */ + $this->updatePolicy(['forceReset' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(412, $response['headers']['status-code']); + $this->assertSame('user_password_reset_required', $response['body']['type']); + + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'forceReset' => false]); } public function testUpdateAnonymousAccountEmail(): void @@ -742,8 +846,8 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertArrayHasKey('passwordPwned', $userA['body']); $this->assertNull($userA['body']['passwordPwned']); - // Policy on: a clean password is recorded as clean - $this->updatePolicy(['enabled' => true]); + // Policy on, with sign-in checks: a clean password is recorded as clean + $this->updatePolicy(['enabled' => true, 'sessions' => true]); $userB = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ 'userId' => ID::unique(), @@ -783,6 +887,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/' . $userA['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); + $this->assertArrayHasKey('passwordPwned', $response['body']); $this->assertTrue($response['body']['passwordPwned']); $projectId = $this->getProject()['$id']; @@ -791,49 +896,96 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope ])); $this->assertSame(200, $response['headers']['status-code']); + $this->assertArrayHasKey('passwordPwned', $response['body']); $this->assertTrue($response['body']['passwordPwned']); - // Listing users can filter on the flag - $ids = fn (array $response) => \array_column($response['body']['users'], '$id'); - - $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ - 'queries' => [ - Query::equal('passwordPwned', [true])->toString(), - Query::orderDesc('$createdAt')->toString(), - Query::limit(100)->toString(), - ], - ]); + // A user that was never checked reports the flag as null on the users API + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userC['body']['$id'], $this->serverHeaders()); $this->assertSame(200, $response['headers']['status-code']); - $this->assertContains($userA['body']['$id'], $ids($response)); - $this->assertNotContains($userB['body']['$id'], $ids($response)); - $this->assertNotContains($userC['body']['$id'], $ids($response)); + $this->assertArrayHasKey('passwordPwned', $response['body']); + $this->assertNull($response['body']['passwordPwned']); - $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ - 'queries' => [ - Query::equal('passwordPwned', [false])->toString(), + // Listing users returns the flag and can filter on it + $userAId = $userA['body']['$id']; + $userBId = $userB['body']['$id']; + $userCId = $userC['body']['$id']; + + $list = function (?string $filter) { + $queries = [ Query::orderDesc('$createdAt')->toString(), Query::limit(100)->toString(), - ], - ]); + ]; - $this->assertSame(200, $response['headers']['status-code']); - $this->assertContains($userB['body']['$id'], $ids($response)); - $this->assertNotContains($userA['body']['$id'], $ids($response)); - $this->assertNotContains($userC['body']['$id'], $ids($response)); + if ($filter !== null) { + \array_unshift($queries, $filter); + } - $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ - 'queries' => [ - Query::isNull('passwordPwned')->toString(), - Query::orderDesc('$createdAt')->toString(), - Query::limit(100)->toString(), - ], - ]); + $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ + 'queries' => $queries, + ]); - $this->assertSame(200, $response['headers']['status-code']); - $this->assertContains($userC['body']['$id'], $ids($response)); - $this->assertNotContains($userA['body']['$id'], $ids($response)); - $this->assertNotContains($userB['body']['$id'], $ids($response)); + $this->assertSame(200, $response['headers']['status-code']); + + $users = []; + foreach ($response['body']['users'] as $user) { + $users[$user['$id']] = $user; + } + + return $users; + }; + + // Every listed user carries the flag, whether or not it was ever checked + $listed = $list(null); + + $this->assertArrayHasKey('passwordPwned', $listed[$userAId]); + $this->assertTrue($listed[$userAId]['passwordPwned']); + $this->assertFalse($listed[$userBId]['passwordPwned']); + $this->assertNull($listed[$userCId]['passwordPwned']); + + // Breached passwords only + $listed = $list(Query::equal('passwordPwned', [true])->toString()); + + $this->assertArrayHasKey($userAId, $listed); + $this->assertArrayNotHasKey($userBId, $listed); + $this->assertArrayNotHasKey($userCId, $listed); + + foreach ($listed as $user) { + $this->assertTrue($user['passwordPwned']); + } + + // Clean passwords only + $listed = $list(Query::equal('passwordPwned', [false])->toString()); + + $this->assertArrayHasKey($userBId, $listed); + $this->assertArrayNotHasKey($userAId, $listed); + $this->assertArrayNotHasKey($userCId, $listed); + + foreach ($listed as $user) { + $this->assertFalse($user['passwordPwned']); + } + + // Never checked + $listed = $list(Query::isNull('passwordPwned')->toString()); + + $this->assertArrayHasKey($userCId, $listed); + $this->assertArrayNotHasKey($userAId, $listed); + $this->assertArrayNotHasKey($userBId, $listed); + + foreach ($listed as $user) { + $this->assertNull($user['passwordPwned']); + } + + // Checked at least once + $listed = $list(Query::isNotNull('passwordPwned')->toString()); + + $this->assertArrayHasKey($userAId, $listed); + $this->assertArrayHasKey($userBId, $listed); + $this->assertArrayNotHasKey($userCId, $listed); + + foreach ($listed as $user) { + $this->assertNotNull($user['passwordPwned']); + } // A clean password clears the flag $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userA['body']['$id'] . '/password', $this->serverHeaders(), [ @@ -964,7 +1116,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $userD['headers']['status-code']); $this->assertNull($userD['body']['passwordPwned']); - $this->updatePolicy(['enabled' => true, 'forceReset' => true]); + $this->updatePolicy(['enabled' => true, 'sessions' => true, 'forceReset' => true]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $emailD, @@ -1001,7 +1153,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(400, $response['headers']['status-code']); - $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'forceReset' => false, 'failClosed' => true]); + $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => true]); } /** diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index 92ebe47b5f..08d6ba4fea 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -19,22 +19,31 @@ final class PasswordPwnedTest extends TestCase private const LEAKED = 'Password123!'; private const ENDPOINT = 'https://breaches.test/range'; - public function testDisabledByDefault(): void + public function testEnabledByDefaultWithoutSessionChecks(): void { $validator = new PasswordPwned(); - $this->assertFalse($validator->isEnabled()); + $this->assertTrue($validator->isEnabled()); + $this->assertFalse($validator->checksSessions()); $this->assertFalse($validator->isForceReset()); } public function testPolicyFlags(): void { - $validator = new PasswordPwned(['enabled' => true, 'forceReset' => true]); + $validator = new PasswordPwned(['enabled' => true, 'sessions' => true, 'forceReset' => true]); $this->assertTrue($validator->isEnabled()); + $this->assertTrue($validator->checksSessions()); $this->assertTrue($validator->isForceReset()); } + public function testSessionChecksNeedAnEnabledPolicy(): void + { + $validator = new PasswordPwned(['enabled' => false, 'sessions' => true, 'forceReset' => true]); + + $this->assertFalse($validator->checksSessions()); + } + public function testDisabledPolicyNeverChecks(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); From 03bc7c694f7d68272f8b583497eef87c0d26316c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 14:35:29 +0200 Subject: [PATCH 16/38] test(pwned): assert the k-anonymity guarantee instead of the transport Review feedback: the validator tests mirrored the URL format, HTTP method, an internal header, and the class's own endpoint constant, so they could never fail meaningfully and made harmless transport changes require synchronised rewrites. They now assert what the guarantee actually is: neither the password, its full hash, nor the identifying suffix reaches the service, and only the five character prefix does. Endpoint precedence is asserted with values the test owns rather than the source constant, and the fetch double records the URLs that left the server rather than how they were transported. Co-Authored-By: Claude Opus 5 (1M context) --- .../unit/Auth/Validator/PasswordPwnedTest.php | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index 08d6ba4fea..bd7d45b554 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -111,18 +111,25 @@ final class PasswordPwnedTest extends TestCase $this->assertFalse($this->validator(['threshold' => 9], $adapter)->isValid(self::LEAKED)); } - public function testOnlyHashPrefixLeavesTheServer(): void + public function testOnlyTheHashPrefixLeavesTheServer(): void { $adapter = new RangeAdapter(body: ''); $validator = $this->validator([], $adapter); $validator->isValid(self::LEAKED); - $hash = \strtoupper(\sha1(self::LEAKED)); $this->assertCount(1, $adapter->requests); - $this->assertSame(self::ENDPOINT . '/' . \substr($hash, 0, 5), $adapter->requests[0]['url']); - $this->assertSame('GET', $adapter->requests[0]['method']); - $this->assertSame('true', $adapter->requests[0]['headers']['add-padding'] ?? null); + + $hash = \strtoupper(\sha1(self::LEAKED)); + $url = $adapter->requests[0]; + + // Neither the password nor anything that identifies it may reach the service + $this->assertStringNotContainsStringIgnoringCase(self::LEAKED, $url); + $this->assertStringNotContainsStringIgnoringCase($hash, $url); + $this->assertStringNotContainsStringIgnoringCase(\substr($hash, 5), $url); + + // Only the first five characters of the hash go out, so the service cannot tell which password was checked + $this->assertStringEndsWith(\substr($hash, 0, 5), $url); } public function testRangeIsCachedPerPrefix(): void @@ -212,18 +219,15 @@ final class PasswordPwnedTest extends TestCase $this->assertCount(0, $adapter->requests); } - public function testEndpointPrecedence(): void + public function testPolicyEndpointOverridesTheServerEndpoint(): void { $adapter = new RangeAdapter(body: ''); - $prefix = \substr(\strtoupper(\sha1(self::LEAKED)), 0, 5); (new PasswordPwned(['enabled' => true, 'endpoint' => 'https://policy.test/range/'], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); (new PasswordPwned(['enabled' => true, 'endpoint' => ''], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); - (new PasswordPwned(['enabled' => true], null, '', new Client($adapter)))->isValid(self::LEAKED); - $this->assertSame('https://policy.test/range/' . $prefix, $adapter->requests[0]['url']); - $this->assertSame('https://server.test/range/' . $prefix, $adapter->requests[1]['url']); - $this->assertSame(PasswordPwned::ENDPOINT . '/' . $prefix, $adapter->requests[2]['url']); + $this->assertStringStartsWith('https://policy.test/range/', $adapter->requests[0]); + $this->assertStringStartsWith('https://server.test/range/', $adapter->requests[1]); } /** @@ -254,7 +258,7 @@ final class PasswordPwnedTest extends TestCase final class RangeAdapter implements Adapter { - /** @var array}> */ + /** @var array URLs the validator asked the breach service for */ public array $requests = []; public function __construct( @@ -272,7 +276,7 @@ final class RangeAdapter implements Adapter RequestOptions $options, ?callable $chunkCallback = null ): Response { - $this->requests[] = ['url' => $url, 'method' => $method, 'headers' => $headers]; + $this->requests[] = $url; if ($this->failure !== null) { throw $this->failure; From ef1e6ab1c8e7df7a5894331f56b712d16245219f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 14:43:37 +0200 Subject: [PATCH 17/38] fix(policies): skip the pwned check on outage instead of rejecting Review feedback: with the policy now enabled by default, defaulting `failClosed` to true meant any project that had never configured the policy would reject password creation, updates and recovery with a 503 whenever the breach service was unreachable. `failClosed` now defaults to false, so an outage skips the check and leaves the recorded state untouched. Rejecting on outage stays available by setting it to true. Co-Authored-By: Claude Opus 5 (1M context) --- src/Appwrite/Auth/Validator/PasswordPwned.php | 2 +- .../Organization/Http/Projects/Create.php | 2 +- .../Project/Http/Project/Policies/Get.php | 2 +- .../Project/Policies/PasswordPwned/Update.php | 4 +-- .../Project/Http/Project/Policies/XList.php | 2 +- .../Modules/Projects/Http/Projects/Create.php | 2 +- .../Response/Model/PolicyPasswordPwned.php | 4 +-- tests/e2e/Services/Project/PoliciesBase.php | 12 +++---- .../PoliciesPasswordPwnedIntegrationTest.php | 6 ++-- .../unit/Auth/Validator/PasswordPwnedTest.php | 33 ++++++++++++------- 10 files changed, 39 insertions(+), 30 deletions(-) diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index ea03f3cc86..d50101fe74 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -46,7 +46,7 @@ class PasswordPwned extends Password $this->threshold = \max(1, (int) ($policy['threshold'] ?? 1)); $this->sessions = (bool) ($policy['sessions'] ?? false); $this->forceReset = (bool) ($policy['forceReset'] ?? false); - $this->failClosed = (bool) ($policy['failClosed'] ?? true); + $this->failClosed = (bool) ($policy['failClosed'] ?? false); $this->cache = $cache; $this->client = $client ?? (new Client()) ->setConnectTimeout(self::CONNECT_TIMEOUT) diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index 6bde4e883d..c000d212ae 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -97,7 +97,7 @@ class Create extends Action 'threshold' => 1, 'sessions' => false, 'forceReset' => false, - 'failClosed' => true, + 'failClosed' => false, ], 'disposableEmails' => false, 'canonicalEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php index cb064d294b..3a02a71b9f 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php @@ -142,7 +142,7 @@ class Get extends Action 'threshold' => 1, 'sessions' => false, 'forceReset' => false, - 'failClosed' => true, + 'failClosed' => false, ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', ])), diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php index 799440ef41..965cbf3e5e 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -60,7 +60,7 @@ class Update extends Action ->param('threshold', null, new Range(1, PHP_INT_MAX), 'Minimum number of known breaches a password must appear in before it is rejected. Default is 1.', optional: true) ->param('sessions', null, new Boolean(), 'Whether passwords are checked when a session is created. When enabled, signing in records whether the password appears in a known data breach. Default is false.', optional: true) ->param('forceReset', null, new Boolean(), 'Whether signing in with a breached password is blocked until the password is reset. Only applies when sessions are checked. Default is false, which allows the sign-in.', optional: true) - ->param('failClosed', null, new Boolean(), 'Whether passwords are rejected when the breach service cannot be reached. Default is true. Set to false to skip the check instead.', optional: true) + ->param('failClosed', null, new Boolean(), 'Whether passwords are rejected when the breach service cannot be reached. Default is false, which skips the check so an outage never blocks your users. Set to true to reject the password instead.', optional: true) ->inject('response') ->inject('dbForPlatform') ->inject('project') @@ -89,7 +89,7 @@ class Update extends Action 'threshold' => 1, 'sessions' => false, 'forceReset' => false, - 'failClosed' => true, + 'failClosed' => false, ], $auths['passwordPwned'] ?? []); if ($enabled !== null) { diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php index 6b8d8c1073..b13541a8eb 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php @@ -122,7 +122,7 @@ class XList extends Action 'threshold' => 1, 'sessions' => false, 'forceReset' => false, - 'failClosed' => true, + 'failClosed' => false, ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', ])), diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php index 0176d68605..6a9e4f28f1 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -94,7 +94,7 @@ class Create extends Action 'threshold' => 1, 'sessions' => false, 'forceReset' => false, - 'failClosed' => true, + 'failClosed' => false, ], 'disposableEmails' => false, 'canonicalEmails' => false, diff --git a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php index 2ae371e4da..6fe844740e 100644 --- a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -48,8 +48,8 @@ class PolicyPasswordPwned extends PolicyBase ->addRule('failClosed', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Whether passwords are rejected when the breach service cannot be reached. When false, the check is skipped instead.', - 'default' => true, - 'example' => true, + 'default' => false, + 'example' => false, ]); } diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index ca7cb73fc6..3a195e6232 100644 --- a/tests/e2e/Services/Project/PoliciesBase.php +++ b/tests/e2e/Services/Project/PoliciesBase.php @@ -654,7 +654,7 @@ trait PoliciesBase $this->assertSame(1, $policy['body']['threshold']); $this->assertSame(false, $policy['body']['sessions']); $this->assertSame(false, $policy['body']['forceReset']); - $this->assertSame(true, $policy['body']['failClosed']); + $this->assertSame(false, $policy['body']['failClosed']); // Cleanup $this->updatePasswordPwnedPolicy(['enabled' => false]); @@ -686,7 +686,7 @@ trait PoliciesBase $this->assertSame(1, $policy['body']['threshold']); $this->assertSame(false, $policy['body']['sessions']); $this->assertSame(false, $policy['body']['forceReset']); - $this->assertSame(true, $policy['body']['failClosed']); + $this->assertSame(false, $policy['body']['failClosed']); } public function testUpdatePasswordPwnedPolicySessions(): void @@ -713,7 +713,7 @@ trait PoliciesBase 'threshold' => 5, 'sessions' => true, 'forceReset' => true, - 'failClosed' => false, + 'failClosed' => true, ]); $this->assertSame(200, $response['headers']['status-code']); @@ -728,7 +728,7 @@ trait PoliciesBase $this->assertSame(5, $policy['body']['threshold']); $this->assertSame(true, $policy['body']['sessions']); $this->assertSame(true, $policy['body']['forceReset']); - $this->assertSame(false, $policy['body']['failClosed']); + $this->assertSame(true, $policy['body']['failClosed']); // Cleanup $this->resetPasswordPwnedPolicy(); @@ -748,7 +748,7 @@ trait PoliciesBase $this->assertSame(1, $policy['body']['threshold']); $this->assertSame(false, $policy['body']['sessions']); $this->assertSame(false, $policy['body']['forceReset']); - $this->assertSame(true, $policy['body']['failClosed']); + $this->assertSame(false, $policy['body']['failClosed']); } public function testUpdatePasswordPwnedPolicyInvalidType(): void @@ -1497,7 +1497,7 @@ trait PoliciesBase 'threshold' => 1, 'sessions' => false, 'forceReset' => false, - 'failClosed' => true, + 'failClosed' => false, ]); } diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index a773824c5c..e7d8fc57d3 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -48,7 +48,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope // Breached passwords are rejected out of the box $this->assertTrue($response['body']['enabled']); - $this->assertTrue($response['body']['failClosed']); + $this->assertFalse($response['body']['failClosed']); $this->assertSame(1, $response['body']['threshold']); $this->assertSame('', $response['body']['endpoint']); @@ -468,7 +468,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); - $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => true]); + $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => false]); } public function testForceResetOnSignIn(): void @@ -1153,7 +1153,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(400, $response['headers']['status-code']); - $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => true]); + $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => false]); } /** diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index bd7d45b554..167069e56e 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -156,11 +156,28 @@ final class PasswordPwnedTest extends TestCase $this->assertCount(2, $adapter->requests); } - public function testUnreachableServiceFailsClosedByDefault(): void + public function testUnreachableServiceSkipsTheCheckByDefault(): void { $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); $validator = $this->validator([], $adapter); + // An outage of the breach service must not stop people setting a password + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testUnexpectedStatusSkipsTheCheckByDefault(): void + { + $adapter = new RangeAdapter(statusCode: 503, body: ''); + $validator = $this->validator([], $adapter); + + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testUnreachableServiceIsRejectedWhenFailingClosed(): void + { + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $validator = $this->validator(['failClosed' => true], $adapter); + try { $validator->isValid(self::LEAKED); $this->fail('Expected the check to fail closed'); @@ -169,29 +186,21 @@ final class PasswordPwnedTest extends TestCase } } - public function testUnexpectedStatusFailsClosedByDefault(): void + public function testUnexpectedStatusIsRejectedWhenFailingClosed(): void { $adapter = new RangeAdapter(statusCode: 503, body: ''); - $validator = $this->validator([], $adapter); + $validator = $this->validator(['failClosed' => true], $adapter); $this->expectException(Exception::class); $validator->isValid(self::LEAKED); } - public function testUnreachableServiceSkipsTheCheckWhenFailingOpen(): void - { - $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); - $validator = $this->validator(['failClosed' => false], $adapter); - - $this->assertTrue($validator->isValid(self::LEAKED)); - } - public function testFailedLookupIsNotCached(): void { $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); $cache = new Cache(new Memory()); - $validator = new PasswordPwned(['enabled' => true, 'failClosed' => false], $cache, self::ENDPOINT, new Client($adapter)); + $validator = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); $validator->isValid(self::LEAKED); $validator->isValid(self::LEAKED); From 4f2e203327d1b8ba74b240a1a8c2a847e99ee8f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 15:26:38 +0200 Subject: [PATCH 18/38] refactor(policies): reduce the pwned policy to three options The policy is now `enabled`, `sessions` and `users`. - `endpoint` is gone; lookups always use `_APP_PWNED_PASSWORDS_ENDPOINT`, so a project can no longer point the check at its own service. - `threshold` is gone; a password found in any known breach is rejected. - `failClosed` is gone; an unreachable breach service always surfaces `general_pwned_passwords_unavailable` rather than silently passing. - `forceReset` is renamed to `users`, matching `sessions`. Its meaning is unchanged: a breached password blocks the sign-in until it is reset, and it still only applies when sessions are checked. The outage path is now covered by unit tests only, since a project can no longer be pointed at an unreachable endpoint from an e2e test. Co-Authored-By: Claude Opus 5 (1M context) --- app/controllers/api/account.php | 4 +- app/init/registers.php | 1 - src/Appwrite/Auth/Validator/PasswordPwned.php | 36 ++-- .../Organization/Http/Projects/Create.php | 5 +- .../Project/Http/Project/Policies/Get.php | 5 +- .../Project/Policies/PasswordPwned/Update.php | 36 +--- .../Project/Http/Project/Policies/XList.php | 5 +- .../Modules/Projects/Http/Projects/Create.php | 5 +- .../Response/Model/PolicyPasswordPwned.php | 22 +- tests/e2e/Services/Project/PoliciesBase.php | 54 +---- .../PoliciesPasswordPwnedIntegrationTest.php | 202 ++---------------- .../unit/Auth/Validator/PasswordPwnedTest.php | 67 ++---- 12 files changed, 71 insertions(+), 371 deletions(-) diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 38b260b718..9256ab59c7 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -1050,7 +1050,7 @@ Http::post('/v1/account/sessions/email') if ($pwnedPasswords->checksSessions()) { // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in - $passwordPwned = $pwnedPasswords->check($password, required: $pwnedPasswords->isForceReset()); + $passwordPwned = $pwnedPasswords->check($password); if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { $user->setAttribute('passwordPwned', $passwordPwned); @@ -1059,7 +1059,7 @@ Http::post('/v1/account/sessions/email') ])); } - if ($passwordPwned && $pwnedPasswords->isForceReset()) { + if ($passwordPwned && $pwnedPasswords->blocksUsers()) { throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); } } diff --git a/app/init/registers.php b/app/init/registers.php index 3c7c39c697..22d49647cb 100644 --- a/app/init/registers.php +++ b/app/init/registers.php @@ -35,7 +35,6 @@ if (!Http::isProduction()) { // Useful for existing tests involving webhooks PublicDomain::allow(['request-catcher-sms']); PublicDomain::allow(['request-catcher-webhook']); - PublicDomain::allow(['localhost']); // Lets the pwned passwords policy point at the mock range endpoint } $register->set('pools', function () { diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index d50101fe74..ef2bc680dc 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -26,27 +26,23 @@ class PasswordPwned extends Password protected bool $enabled; protected string $endpoint; - protected int $threshold; protected bool $sessions; - protected bool $forceReset; - protected bool $failClosed; + protected bool $users; protected ?Cache $cache; protected Client $client; /** * @param array $policy the project's `passwordPwned` auth settings - * @param ?string $endpoint server-wide endpoint, used when the policy sets none + * @param ?string $endpoint the breach API this server is configured to use */ public function __construct(array $policy = [], ?Cache $cache = null, ?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false) { parent::__construct($allowEmpty); $this->enabled = (bool) ($policy['enabled'] ?? true); - $this->endpoint = \rtrim(($policy['endpoint'] ?? '') ?: ($endpoint ?: self::ENDPOINT), '/'); - $this->threshold = \max(1, (int) ($policy['threshold'] ?? 1)); $this->sessions = (bool) ($policy['sessions'] ?? false); - $this->forceReset = (bool) ($policy['forceReset'] ?? false); - $this->failClosed = (bool) ($policy['failClosed'] ?? false); + $this->users = (bool) ($policy['users'] ?? false); + $this->endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/'); $this->cache = $cache; $this->client = $client ?? (new Client()) ->setConnectTimeout(self::CONNECT_TIMEOUT) @@ -72,13 +68,13 @@ class PasswordPwned extends Password } /** - * Whether a breached password blocks sign-in until it is reset. + * Whether users signing in with a breached password are blocked until they reset it. * * Only takes effect when sessions are checked. */ - public function isForceReset(): bool + public function blocksUsers(): bool { - return $this->forceReset; + return $this->users; } /** @@ -94,14 +90,13 @@ class PasswordPwned extends Password } /** - * Whether the password appears in at least `threshold` known breaches. + * Whether the password appears in a known breach. * - * Returns null when the policy is disabled, or when the service could not - * be reached and the answer is not required by a fail-closed policy. + * Returns null only when the policy is disabled. * - * @throws Exception when the answer is required, the policy fails closed, and the service is unreachable + * @throws Exception when the breach service cannot be reached */ - public function check(string $password, bool $required = true): ?bool + public function check(string $password): ?bool { if (!$this->enabled) { return null; @@ -114,14 +109,11 @@ class PasswordPwned extends Password $breaches = $this->range($prefix); if ($breaches === null) { - if ($required && $this->failClosed) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } - - return null; + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } - return ($breaches[$suffix] ?? 0) >= $this->threshold; + // Entries with no breaches are dropped, so any hit means the password is breached + return isset($breaches[$suffix]); } /** diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index c000d212ae..10d846791f 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -93,11 +93,8 @@ class Create extends Action 'personalDataCheck' => false, 'passwordPwned' => [ 'enabled' => true, - 'endpoint' => '', - 'threshold' => 1, 'sessions' => false, - 'forceReset' => false, - 'failClosed' => false, + 'users' => false, ], 'disposableEmails' => false, 'canonicalEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php index 3a02a71b9f..9984257c66 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php @@ -138,11 +138,8 @@ class Get extends Action 'password-pwned' => [ new Document(\array_merge([ 'enabled' => true, - 'endpoint' => '', - 'threshold' => 1, 'sessions' => false, - 'forceReset' => false, - 'failClosed' => false, + 'users' => false, ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', ])), diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php index 965cbf3e5e..08b7e5fef8 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -11,14 +11,8 @@ use Appwrite\Utopia\Response; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Validator\Authorization; -use Utopia\Domains\Validator\PublicDomain; use Utopia\Platform\Scope\HTTP; -use Utopia\Validator\AnyOf; use Utopia\Validator\Boolean; -use Utopia\Validator\Multiple; -use Utopia\Validator\Range; -use Utopia\Validator\URL; -use Utopia\Validator\WhiteList; class Update extends Action { @@ -45,7 +39,7 @@ class Update extends Action group: 'policies', name: 'updatePasswordPwnedPolicy', description: <<param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true to block passwords exposed in known data breaches, or false to allow them. Default is true. When changing this policy, existing passwords remain valid.', optional: true) - ->param('endpoint', null, new AnyOf([new WhiteList([''], true), new Multiple([new URL(['http', 'https']), new PublicDomain()], Multiple::TYPE_STRING)], AnyOf::TYPE_STRING), 'Custom endpoint of a Have I Been Pwned compatible range API, for example a self-hosted mirror. Pass an empty string to use the server default.', optional: true) - ->param('threshold', null, new Range(1, PHP_INT_MAX), 'Minimum number of known breaches a password must appear in before it is rejected. Default is 1.', optional: true) ->param('sessions', null, new Boolean(), 'Whether passwords are checked when a session is created. When enabled, signing in records whether the password appears in a known data breach. Default is false.', optional: true) - ->param('forceReset', null, new Boolean(), 'Whether signing in with a breached password is blocked until the password is reset. Only applies when sessions are checked. Default is false, which allows the sign-in.', optional: true) - ->param('failClosed', null, new Boolean(), 'Whether passwords are rejected when the breach service cannot be reached. Default is false, which skips the check so an outage never blocks your users. Set to true to reject the password instead.', optional: true) + ->param('users', null, new Boolean(), 'Whether users signing in with a breached password are blocked until they reset it. Only applies when sessions are checked. Default is false, which allows the sign-in.', optional: true) ->inject('response') ->inject('dbForPlatform') ->inject('project') @@ -71,11 +62,8 @@ class Update extends Action public function action( ?bool $enabled, - ?string $endpoint, - ?int $threshold, ?bool $sessions, - ?bool $forceReset, - ?bool $failClosed, + ?bool $users, Response $response, Database $dbForPlatform, Document $project, @@ -85,30 +73,18 @@ class Update extends Action $auths = $project->getAttribute('auths', []); $auths['passwordPwned'] = \array_merge([ 'enabled' => true, - 'endpoint' => '', - 'threshold' => 1, 'sessions' => false, - 'forceReset' => false, - 'failClosed' => false, + 'users' => false, ], $auths['passwordPwned'] ?? []); if ($enabled !== null) { $auths['passwordPwned']['enabled'] = $enabled; } - if ($endpoint !== null) { - $auths['passwordPwned']['endpoint'] = $endpoint; - } - if ($threshold !== null) { - $auths['passwordPwned']['threshold'] = $threshold; - } if ($sessions !== null) { $auths['passwordPwned']['sessions'] = $sessions; } - if ($forceReset !== null) { - $auths['passwordPwned']['forceReset'] = $forceReset; - } - if ($failClosed !== null) { - $auths['passwordPwned']['failClosed'] = $failClosed; + if ($users !== null) { + $auths['passwordPwned']['users'] = $users; } $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document([ diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php index b13541a8eb..32bbaa2e7d 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php @@ -118,11 +118,8 @@ class XList extends Action ]), new Document(\array_merge([ 'enabled' => true, - 'endpoint' => '', - 'threshold' => 1, 'sessions' => false, - 'forceReset' => false, - 'failClosed' => false, + 'users' => false, ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', ])), diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php index 6a9e4f28f1..f5a689adeb 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -90,11 +90,8 @@ class Create extends Action 'personalDataCheck' => false, 'passwordPwned' => [ 'enabled' => true, - 'endpoint' => '', - 'threshold' => 1, 'sessions' => false, - 'forceReset' => false, - 'failClosed' => false, + 'users' => false, ], 'disposableEmails' => false, 'canonicalEmails' => false, diff --git a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php index 6fe844740e..d1352e078e 100644 --- a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -21,33 +21,15 @@ class PolicyPasswordPwned extends PolicyBase 'default' => true, 'example' => true, ]) - ->addRule('endpoint', [ - 'type' => self::TYPE_STRING, - 'description' => 'Custom endpoint of a Have I Been Pwned compatible range API. Empty when the server default is used.', - 'default' => '', - 'example' => 'https://api.pwnedpasswords.com/range', - ]) - ->addRule('threshold', [ - 'type' => self::TYPE_INTEGER, - 'description' => 'Minimum number of known breaches a password must appear in before it is rejected.', - 'default' => 1, - 'example' => 1, - ]) ->addRule('sessions', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Whether passwords are checked when a session is created.', 'default' => false, 'example' => false, ]) - ->addRule('forceReset', [ + ->addRule('users', [ 'type' => self::TYPE_BOOLEAN, - 'description' => 'Whether signing in with a breached password is blocked until the password is reset. Only applies when sessions are checked.', - 'default' => false, - 'example' => false, - ]) - ->addRule('failClosed', [ - 'type' => self::TYPE_BOOLEAN, - 'description' => 'Whether passwords are rejected when the breach service cannot be reached. When false, the check is skipped instead.', + 'description' => 'Whether users signing in with a breached password are blocked until they reset it. Only applies when sessions are checked.', 'default' => false, 'example' => false, ]); diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index 3a195e6232..a50d8c707b 100644 --- a/tests/e2e/Services/Project/PoliciesBase.php +++ b/tests/e2e/Services/Project/PoliciesBase.php @@ -17,7 +17,7 @@ trait PoliciesBase 'password-history' => ['total'], 'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'], 'password-personal-data' => ['enabled'], - 'password-pwned' => ['enabled', 'endpoint', 'threshold', 'sessions', 'forceReset', 'failClosed'], + 'password-pwned' => ['enabled', 'sessions', 'users'], 'session-alert' => ['enabled'], 'session-duration' => ['duration'], 'session-invalidation' => ['enabled'], @@ -650,11 +650,8 @@ trait PoliciesBase $policy = $this->getPolicy('password-pwned'); $this->assertSame(200, $policy['headers']['status-code']); $this->assertSame(true, $policy['body']['enabled']); - $this->assertSame('', $policy['body']['endpoint']); - $this->assertSame(1, $policy['body']['threshold']); $this->assertSame(false, $policy['body']['sessions']); - $this->assertSame(false, $policy['body']['forceReset']); - $this->assertSame(false, $policy['body']['failClosed']); + $this->assertSame(false, $policy['body']['users']); // Cleanup $this->updatePasswordPwnedPolicy(['enabled' => false]); @@ -682,11 +679,8 @@ trait PoliciesBase $this->assertSame(200, $policy['headers']['status-code']); $this->assertSame('password-pwned', $policy['body']['$id']); $this->assertSame(true, $policy['body']['enabled']); - $this->assertSame('', $policy['body']['endpoint']); - $this->assertSame(1, $policy['body']['threshold']); $this->assertSame(false, $policy['body']['sessions']); - $this->assertSame(false, $policy['body']['forceReset']); - $this->assertSame(false, $policy['body']['failClosed']); + $this->assertSame(false, $policy['body']['users']); } public function testUpdatePasswordPwnedPolicySessions(): void @@ -709,11 +703,8 @@ trait PoliciesBase public function testUpdatePasswordPwnedPolicyOptionPreservesOtherOptions(): void { $response = $this->updatePasswordPwnedPolicy([ - 'endpoint' => 'https://example.com/range', - 'threshold' => 5, 'sessions' => true, - 'forceReset' => true, - 'failClosed' => true, + 'users' => true, ]); $this->assertSame(200, $response['headers']['status-code']); @@ -724,11 +715,8 @@ trait PoliciesBase $policy = $this->getPolicy('password-pwned'); $this->assertSame(true, $policy['body']['enabled']); - $this->assertSame('https://example.com/range', $policy['body']['endpoint']); - $this->assertSame(5, $policy['body']['threshold']); $this->assertSame(true, $policy['body']['sessions']); - $this->assertSame(true, $policy['body']['forceReset']); - $this->assertSame(true, $policy['body']['failClosed']); + $this->assertSame(true, $policy['body']['users']); // Cleanup $this->resetPasswordPwnedPolicy(); @@ -744,40 +732,17 @@ trait PoliciesBase $policy = $this->getPolicy('password-pwned'); $this->assertSame(true, $policy['body']['enabled']); - $this->assertSame('', $policy['body']['endpoint']); - $this->assertSame(1, $policy['body']['threshold']); $this->assertSame(false, $policy['body']['sessions']); - $this->assertSame(false, $policy['body']['forceReset']); - $this->assertSame(false, $policy['body']['failClosed']); + $this->assertSame(false, $policy['body']['users']); } public function testUpdatePasswordPwnedPolicyInvalidType(): void { - foreach (['enabled', 'sessions', 'forceReset', 'failClosed'] as $option) { + foreach (['enabled', 'sessions', 'users'] as $option) { $response = $this->updatePasswordPwnedPolicy([$option => 'not-a-boolean']); $this->assertSame(400, $response['headers']['status-code'], $option); } - - $response = $this->updatePasswordPwnedPolicy(['threshold' => 'not-a-number']); - - $this->assertSame(400, $response['headers']['status-code']); - } - - public function testUpdatePasswordPwnedPolicyInvalidThreshold(): void - { - $response = $this->updatePasswordPwnedPolicy(['threshold' => 0]); - - $this->assertSame(400, $response['headers']['status-code']); - } - - public function testUpdatePasswordPwnedPolicyInvalidEndpoint(): void - { - foreach (['not-a-url', 'ftp://example.com/range', 'http://192.168.1.1/range'] as $endpoint) { - $response = $this->updatePasswordPwnedPolicy(['endpoint' => $endpoint]); - - $this->assertSame(400, $response['headers']['status-code'], $endpoint); - } } public function testUpdatePasswordPwnedPolicyWithoutAuth(): void @@ -1493,11 +1458,8 @@ trait PoliciesBase { $this->updatePasswordPwnedPolicy([ 'enabled' => true, - 'endpoint' => '', - 'threshold' => 1, 'sessions' => false, - 'forceReset' => false, - 'failClosed' => false, + 'users' => false, ]); } diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index e7d8fc57d3..c52e3602a3 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -20,15 +20,8 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope use ProjectCustom; use SideServer; - // Reported as breached by the mock range endpoint, 12345 and 9 times respectively + // Reported as breached by the mock range endpoint private const PWNED_PASSWORD = 'pwned-fixture-common'; - private const RARELY_PWNED_PASSWORD = 'pwned-fixture-rare'; - - // The mock range endpoint the stack already uses through _APP_PWNED_PASSWORDS_ENDPOINT - private const MOCK_ENDPOINT = 'http://localhost/v1/mock/tests/general/pwned-passwords'; - - // Nothing listens here, so lookups fail - private const DEAD_ENDPOINT = 'http://localhost:1/range'; public function testDefaultsOnNewProject(): void { @@ -48,13 +41,10 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope // Breached passwords are rejected out of the box $this->assertTrue($response['body']['enabled']); - $this->assertFalse($response['body']['failClosed']); - $this->assertSame(1, $response['body']['threshold']); - $this->assertSame('', $response['body']['endpoint']); // Sign-in checks stay opt-in $this->assertFalse($response['body']['sessions']); - $this->assertFalse($response['body']['forceReset']); + $this->assertFalse($response['body']['users']); // A breached password is blocked without touching the policy $response = $this->client->call(Client::METHOD_POST, '/users', $headers, [ @@ -318,160 +308,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->updatePolicy(['enabled' => false]); } - public function testThreshold(): void - { - $this->updatePolicy(['enabled' => true, 'threshold' => 10]); - - /** - * Test for SUCCESS - */ - $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_rare_' . \uniqid() . '@localhost.test', - 'password' => self::RARELY_PWNED_PASSWORD, - 'name' => 'Rarely Pwned User', - ]); - - $this->assertSame(201, $response['headers']['status-code']); - - /** - * Test for FAILURE - */ - $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_often_' . \uniqid() . '@localhost.test', - 'password' => self::PWNED_PASSWORD, - 'name' => 'Often Pwned User', - ]); - - $this->assertSame(400, $response['headers']['status-code']); - $this->assertSame('password_pwned', $response['body']['type']); - - $this->updatePolicy(['enabled' => false, 'threshold' => 1]); - } - - public function testCustomEndpoint(): void - { - $this->updatePolicy(['enabled' => true, 'endpoint' => self::MOCK_ENDPOINT]); - - /** - * Test for FAILURE - */ - $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_endpoint_' . \uniqid() . '@localhost.test', - 'password' => self::PWNED_PASSWORD, - 'name' => 'Endpoint User', - ]); - - $this->assertSame(400, $response['headers']['status-code']); - $this->assertSame('password_pwned', $response['body']['type']); - - /** - * Test for SUCCESS - */ - $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_endpoint_clean_' . \uniqid() . '@localhost.test', - 'password' => $this->cleanPassword(), - 'name' => 'Endpoint Clean User', - ]); - - $this->assertSame(201, $response['headers']['status-code']); - - // An empty endpoint falls back to the server configuration - $this->updatePolicy(['endpoint' => '']); - - $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_fallback_' . \uniqid() . '@localhost.test', - 'password' => self::PWNED_PASSWORD, - 'name' => 'Fallback User', - ]); - - $this->assertSame(400, $response['headers']['status-code']); - $this->assertSame('password_pwned', $response['body']['type']); - - $this->updatePolicy(['enabled' => false]); - } - - public function testFailClosed(): void - { - $this->updatePolicy(['enabled' => true, 'endpoint' => self::DEAD_ENDPOINT, 'failClosed' => true]); - - /** - * Test for FAILURE - */ - $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_outage_' . \uniqid() . '@localhost.test', - 'password' => $this->cleanPassword(), - 'name' => 'Outage User', - ]); - - $this->assertSame(503, $response['headers']['status-code']); - $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); - - $response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_outage_account_' . \uniqid() . '@localhost.test', - 'password' => $this->cleanPassword(), - 'name' => 'Outage Account', - ]); - - $this->assertSame(503, $response['headers']['status-code']); - $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); - - // Forced reset needs the lookup, so sign-in fails closed as well - $this->updatePolicy(['enabled' => false]); - - $email = 'pwned_outage_signin_' . \uniqid() . '@localhost.test'; - $password = $this->cleanPassword(); - - $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => $email, - 'password' => $password, - 'name' => 'Outage Sign In User', - ]); - - $this->assertSame(201, $user['headers']['status-code']); - - $this->updatePolicy(['enabled' => true, 'sessions' => true, 'forceReset' => true]); - - $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ - 'email' => $email, - 'password' => $password, - ]); - - $this->assertSame(503, $response['headers']['status-code']); - $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); - - /** - * Test for SUCCESS - */ - $this->updatePolicy(['failClosed' => false]); - - $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ - 'email' => $email, - 'password' => $password, - ]); - - $this->assertSame(201, $response['headers']['status-code']); - - $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ - 'userId' => ID::unique(), - 'email' => 'pwned_outage_open_' . \uniqid() . '@localhost.test', - 'password' => self::PWNED_PASSWORD, - 'name' => 'Outage Open User', - ]); - - $this->assertSame(201, $response['headers']['status-code']); - - $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => false]); - } - - public function testForceResetOnSignIn(): void + public function testSignInBlockedUntilReset(): void { $this->updatePolicy(['enabled' => false]); @@ -489,7 +326,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope /** * Test for SUCCESS */ - $this->updatePolicy(['enabled' => true, 'sessions' => true, 'forceReset' => false]); + $this->updatePolicy(['enabled' => true, 'sessions' => true, 'users' => false]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -501,7 +338,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope /** * Test for FAILURE */ - $this->updatePolicy(['forceReset' => true]); + $this->updatePolicy(['users' => true]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -538,7 +375,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); - $this->updatePolicy(['enabled' => false, 'sessions' => false, 'forceReset' => false]); + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'users' => false]); } public function testSessionChecksAreOptional(): void @@ -561,7 +398,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope * Test for SUCCESS */ // Sign-in checks are off by default, so a forced reset has nothing to act on - $this->updatePolicy(['enabled' => true, 'sessions' => false, 'forceReset' => true]); + $this->updatePolicy(['enabled' => true, 'sessions' => false, 'users' => true]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -577,7 +414,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertNull($response['body']['passwordPwned']); // Checking sessions without forcing a reset records the breach and still allows the sign-in - $this->updatePolicy(['sessions' => true, 'forceReset' => false]); + $this->updatePolicy(['sessions' => true, 'users' => false]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -594,7 +431,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope /** * Test for FAILURE */ - $this->updatePolicy(['forceReset' => true]); + $this->updatePolicy(['users' => true]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $email, @@ -604,7 +441,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(412, $response['headers']['status-code']); $this->assertSame('user_password_reset_required', $response['body']['type']); - $this->updatePolicy(['enabled' => false, 'sessions' => false, 'forceReset' => false]); + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'users' => false]); } public function testUpdateAnonymousAccountEmail(): void @@ -1116,7 +953,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $userD['headers']['status-code']); $this->assertNull($userD['body']['passwordPwned']); - $this->updatePolicy(['enabled' => true, 'sessions' => true, 'forceReset' => true]); + $this->updatePolicy(['enabled' => true, 'sessions' => true, 'users' => true]); $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ 'email' => $emailD, @@ -1131,21 +968,6 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(200, $response['headers']['status-code']); $this->assertTrue($response['body']['passwordPwned']); - // An outage with a fail-open policy leaves the recorded state untouched and lets the sign-in through - $this->updatePolicy(['endpoint' => self::DEAD_ENDPOINT, 'failClosed' => false]); - - $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ - 'email' => $emailD, - 'password' => self::PWNED_PASSWORD, - ]); - - $this->assertSame(201, $response['headers']['status-code']); - - $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['passwordPwned']); - // Filtering on an attribute outside the whitelist is rejected $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ 'queries' => [Query::equal('passwordHistory', ['x'])->toString()], @@ -1153,7 +975,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(400, $response['headers']['status-code']); - $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'sessions' => false, 'forceReset' => false, 'failClosed' => false]); + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'users' => false]); } /** diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index 167069e56e..6be2387956 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -25,21 +25,21 @@ final class PasswordPwnedTest extends TestCase $this->assertTrue($validator->isEnabled()); $this->assertFalse($validator->checksSessions()); - $this->assertFalse($validator->isForceReset()); + $this->assertFalse($validator->blocksUsers()); } public function testPolicyFlags(): void { - $validator = new PasswordPwned(['enabled' => true, 'sessions' => true, 'forceReset' => true]); + $validator = new PasswordPwned(['enabled' => true, 'sessions' => true, 'users' => true]); $this->assertTrue($validator->isEnabled()); $this->assertTrue($validator->checksSessions()); - $this->assertTrue($validator->isForceReset()); + $this->assertTrue($validator->blocksUsers()); } public function testSessionChecksNeedAnEnabledPolicy(): void { - $validator = new PasswordPwned(['enabled' => false, 'sessions' => true, 'forceReset' => true]); + $validator = new PasswordPwned(['enabled' => false, 'sessions' => true, 'users' => true]); $this->assertFalse($validator->checksSessions()); } @@ -63,14 +63,6 @@ final class PasswordPwnedTest extends TestCase $this->assertFalse($validator->check('never-leaked-' . \uniqid())); } - public function testCheckNotRequiredReturnsUnknownOnOutage(): void - { - $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); - $validator = $this->validator(['failClosed' => true], $adapter); - - $this->assertNull($validator->check(self::LEAKED, required: false)); - } - public function testLeakedPasswordIsRejected(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); @@ -103,12 +95,11 @@ final class PasswordPwnedTest extends TestCase $this->assertFalse($validator->isValid(self::LEAKED)); } - public function testThresholdToleratesRareBreaches(): void + public function testAnySingleBreachIsEnough(): void { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 9])); + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 1])); - $this->assertTrue($this->validator(['threshold' => 10], $adapter)->isValid(self::LEAKED)); - $this->assertFalse($this->validator(['threshold' => 9], $adapter)->isValid(self::LEAKED)); + $this->assertFalse($this->validator([], $adapter)->isValid(self::LEAKED)); } public function testOnlyTheHashPrefixLeavesTheServer(): void @@ -156,40 +147,23 @@ final class PasswordPwnedTest extends TestCase $this->assertCount(2, $adapter->requests); } - public function testUnreachableServiceSkipsTheCheckByDefault(): void + public function testUnreachableServiceIsReported(): void { $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); $validator = $this->validator([], $adapter); - // An outage of the breach service must not stop people setting a password - $this->assertTrue($validator->isValid(self::LEAKED)); - } - - public function testUnexpectedStatusSkipsTheCheckByDefault(): void - { - $adapter = new RangeAdapter(statusCode: 503, body: ''); - $validator = $this->validator([], $adapter); - - $this->assertTrue($validator->isValid(self::LEAKED)); - } - - public function testUnreachableServiceIsRejectedWhenFailingClosed(): void - { - $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); - $validator = $this->validator(['failClosed' => true], $adapter); - try { $validator->isValid(self::LEAKED); - $this->fail('Expected the check to fail closed'); + $this->fail('Expected the unreachable service to surface'); } catch (Exception $e) { $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); } } - public function testUnexpectedStatusIsRejectedWhenFailingClosed(): void + public function testUnexpectedStatusIsReported(): void { $adapter = new RangeAdapter(statusCode: 503, body: ''); - $validator = $this->validator(['failClosed' => true], $adapter); + $validator = $this->validator([], $adapter); $this->expectException(Exception::class); @@ -202,8 +176,13 @@ final class PasswordPwnedTest extends TestCase $cache = new Cache(new Memory()); $validator = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); - $validator->isValid(self::LEAKED); - $validator->isValid(self::LEAKED); + foreach ([1, 2] as $attempt) { + try { + $validator->isValid(self::LEAKED); + } catch (Exception) { + // The lookup failed, which is the point; it must be retried rather than remembered + } + } $this->assertCount(2, $adapter->requests); } @@ -228,15 +207,15 @@ final class PasswordPwnedTest extends TestCase $this->assertCount(0, $adapter->requests); } - public function testPolicyEndpointOverridesTheServerEndpoint(): void + public function testLookupsGoToTheConfiguredEndpoint(): void { $adapter = new RangeAdapter(body: ''); - (new PasswordPwned(['enabled' => true, 'endpoint' => 'https://policy.test/range/'], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); - (new PasswordPwned(['enabled' => true, 'endpoint' => ''], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['enabled' => true], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['enabled' => true], null, 'https://other.test/range/', new Client($adapter)))->isValid(self::LEAKED); - $this->assertStringStartsWith('https://policy.test/range/', $adapter->requests[0]); - $this->assertStringStartsWith('https://server.test/range/', $adapter->requests[1]); + $this->assertStringStartsWith('https://server.test/range/', $adapter->requests[0]); + $this->assertStringStartsWith('https://other.test/range/', $adapter->requests[1]); } /** From 84f3c39d73215c46ca6a9796978761f9072e2576 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 15:33:18 +0200 Subject: [PATCH 19/38] feat(auth): make the pwned lookup adapter driven The breach lookup moves out of the validator and behind an adapter, so a server can choose who answers the question. - `hibp` keeps the current behaviour: the public Have I Been Pwned range API with k-anonymity, sending only the first five characters of the SHA-1 hash and caching ranges per prefix. - `appwrite` talks to an Appwrite Pwned service (https://github.com/appwrite-labs/pwned), which answers for a whole password. The password travels inside a short-lived JWT signed with `_APP_OPENSSL_KEY_V1`, so it is only appropriate for a service on your own network, and in exchange the service caches and can front a detector of its own choosing. `_APP_PWNED_PASSWORDS_ADAPTER` picks the adapter and defaults to `hibp`. `_APP_PWNED_PASSWORDS_ENDPOINT` now defaults to empty and falls back to whichever address the chosen adapter ships with. An unknown adapter name fails loudly at request time rather than quietly falling back. `PasswordPwned` keeps the policy decisions and delegates the lookup, so its unit test no longer needs an HTTP double. Each adapter has its own test next to it. Co-Authored-By: Claude Opus 5 (1M context) --- .env | 1 + app/config/variables.php | 15 +- app/init/resources/request.php | 13 +- docker-compose.yml | 1 + src/Appwrite/Auth/Pwned.php | 55 ++++ src/Appwrite/Auth/Pwned/Appwrite.php | 66 +++++ src/Appwrite/Auth/Pwned/HIBP.php | 95 +++++++ src/Appwrite/Auth/Validator/PasswordPwned.php | 97 +------ tests/unit/Auth/Pwned/AppwriteTest.php | 150 +++++++++++ tests/unit/Auth/Pwned/HIBPTest.php | 198 +++++++++++++++ .../unit/Auth/Validator/PasswordPwnedTest.php | 239 +++--------------- 11 files changed, 640 insertions(+), 290 deletions(-) create mode 100644 src/Appwrite/Auth/Pwned.php create mode 100644 src/Appwrite/Auth/Pwned/Appwrite.php create mode 100644 src/Appwrite/Auth/Pwned/HIBP.php create mode 100644 tests/unit/Auth/Pwned/AppwriteTest.php create mode 100644 tests/unit/Auth/Pwned/HIBPTest.php diff --git a/.env b/.env index 12b71fab58..a29af52345 100644 --- a/.env +++ b/.env @@ -175,6 +175,7 @@ _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET= _APP_PROJECT_REGIONS=default _APP_GEO_SECRET=your-secret-key _APP_GEO_ENDPOINT=http://appwrite-geo/v1 +_APP_PWNED_PASSWORDS_ADAPTER=hibp _APP_PWNED_PASSWORDS_ENDPOINT=http://localhost/v1/mock/tests/general/pwned-passwords _APP_VCS_GITHUB_APP_ID= _APP_VCS_GITHUB_APP_NAME= diff --git a/app/config/variables.php b/app/config/variables.php index 1245758fca..9bcde780f8 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -485,10 +485,19 @@ return [ 'filter' => 'token' ], [ - 'name' => '_APP_PWNED_PASSWORDS_ENDPOINT', - 'description' => 'Endpoint of the Have I Been Pwned range API used by the password pwned project policy. Only the first five characters of a password SHA-1 hash are sent to this endpoint. Defaults to the public Have I Been Pwned service.', + 'name' => '_APP_PWNED_PASSWORDS_ADAPTER', + 'description' => 'Service the password pwned project policy asks whether a password has been breached. `hibp` calls the Have I Been Pwned range API and only ever sends the first five characters of the password SHA-1 hash. `appwrite` calls an [Appwrite Pwned](https://github.com/appwrite-labs/pwned) service you run yourself, which caches answers and can front a detector of your choice, but receives the whole password inside a JWT signed with `_APP_OPENSSL_KEY_V1`, so only point it at a service on your own network.', 'introduction' => 'TBD', - 'default' => 'https://api.pwnedpasswords.com/range', + 'default' => 'hibp', + 'required' => false, + 'question' => '', + 'filter' => '' + ], + [ + 'name' => '_APP_PWNED_PASSWORDS_ENDPOINT', + 'description' => 'Address the adapter chosen in `_APP_PWNED_PASSWORDS_ADAPTER` calls. Leave empty to use that adapter\'s default, which is `https://api.pwnedpasswords.com/range` for `hibp` and `http://appwrite-pwned/v1/detection` for `appwrite`.', + 'introduction' => 'TBD', + 'default' => '', 'required' => false, 'question' => '', 'filter' => '' diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 430f73cbff..f669ee1d90 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -3,6 +3,8 @@ use Ahc\Jwt\JWT; use Ahc\Jwt\JWTException; use Appwrite\Auth\Key; +use Appwrite\Auth\Pwned\Appwrite as PwnedAppwrite; +use Appwrite\Auth\Pwned\HIBP as PwnedHIBP; use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; @@ -675,7 +677,16 @@ return function (Container $context): void { }, ['user', 'store', 'proofForToken']); $context->set('pwnedPasswords', function (Document $project, Cache $cache) { - return new PasswordPwned($project->getAttribute('auths', [])['passwordPwned'] ?? [], $cache, System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + $endpoint = System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT', ''); + $name = \strtolower(System::getEnv('_APP_PWNED_PASSWORDS_ADAPTER', 'hibp')); + + $adapter = match ($name) { + 'hibp' => new PwnedHIBP($endpoint, $cache), + 'appwrite' => new PwnedAppwrite($endpoint, System::getEnv('_APP_OPENSSL_KEY_V1', '')), + default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_ADAPTER: ' . $name), + }; + + return new PasswordPwned($adapter, $project->getAttribute('auths', [])['passwordPwned'] ?? []); }, ['project', 'cache']); $context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) { diff --git a/docker-compose.yml b/docker-compose.yml index 8c9f5446f8..2aff35ba09 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -254,6 +254,7 @@ services: - _APP_MIGRATION_HOST - _APP_GEO_SECRET - _APP_GEO_ENDPOINT + - _APP_PWNED_PASSWORDS_ADAPTER - _APP_PWNED_PASSWORDS_ENDPOINT - _APP_LIMIT_DATABASE_BATCH - _APP_DOCUMENTSDB diff --git a/src/Appwrite/Auth/Pwned.php b/src/Appwrite/Auth/Pwned.php new file mode 100644 index 0000000000..7bd145794c --- /dev/null +++ b/src/Appwrite/Auth/Pwned.php @@ -0,0 +1,55 @@ +endpoint = \rtrim($endpoint, '/'); + $this->client = $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + } + + /** + * Adapter name, as accepted by `_APP_PWNED_PASSWORDS_ADAPTER`. + */ + abstract public function getName(): string; + + /** + * Whether the password appears in a known data breach. + * + * @throws Exception when the breach service cannot be reached or answers with nonsense + */ + abstract public function isPwned(string $password): bool; + + /** + * A password is never silently accepted when the lookup did not happen. + * + * @throws Exception + */ + protected function unavailable(): never + { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } +} diff --git a/src/Appwrite/Auth/Pwned/Appwrite.php b/src/Appwrite/Auth/Pwned/Appwrite.php new file mode 100644 index 0000000000..2392ec22c0 --- /dev/null +++ b/src/Appwrite/Auth/Pwned/Appwrite.php @@ -0,0 +1,66 @@ +secret = $secret; + } + + public function getName(): string + { + return 'appwrite'; + } + + public function isPwned(string $password): bool + { + $jwt = new JWT($this->secret, 'HS256', self::TOKEN_EXPIRY, self::TOKEN_LEEWAY); + + try { + $response = $this->client + ->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON) + ->fetch($this->endpoint, Client::METHOD_POST, [ + 'password' => $jwt->encode(['password' => $password]), + ]); + } catch (\Throwable) { + $this->unavailable(); + } + + if ($response->getStatusCode() !== 200) { + $this->unavailable(); + } + + $body = \json_decode($response->text(), true); + + if (!\is_array($body) || !\is_bool($body['leaked'] ?? null)) { + $this->unavailable(); + } + + return $body['leaked']; + } +} diff --git a/src/Appwrite/Auth/Pwned/HIBP.php b/src/Appwrite/Auth/Pwned/HIBP.php new file mode 100644 index 0000000000..e115715bbd --- /dev/null +++ b/src/Appwrite/Auth/Pwned/HIBP.php @@ -0,0 +1,95 @@ +cache = $cache; + } + + public function getName(): string + { + return 'hibp'; + } + + public function isPwned(string $password): bool + { + $hash = \strtoupper(\sha1($password)); + $prefix = \substr($hash, 0, self::PREFIX_LENGTH); + $suffix = \substr($hash, self::PREFIX_LENGTH); + + // Entries with no breaches are dropped, so any hit means the password is breached + return isset($this->range($prefix)[$suffix]); + } + + /** + * Breach counts for every known hash sharing the prefix, from cache or the service. + * + * @return array hash suffix => breach count + */ + private function range(string $prefix): array + { + $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix; + + if ($this->cache !== null) { + $cached = $this->cache->load($key, self::CACHE_TTL); + if (\is_array($cached)) { + return $cached; + } + } + + try { + $response = $this->client + ->addHeader('Add-Padding', 'true') + ->fetch($this->endpoint . '/' . $prefix); + } catch (\Throwable) { + $this->unavailable(); + } + + if ($response->getStatusCode() !== 200) { + $this->unavailable(); + } + + // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches + $breaches = []; + foreach (\explode("\n", $response->text()) as $line) { + $line = \trim($line); + $separator = \strpos($line, ':'); + if ($line === '' || $separator === false) { + continue; + } + + $count = (int) \substr($line, $separator + 1); + if ($count > 0) { + $breaches[\strtoupper(\substr($line, 0, $separator))] = $count; + } + } + + $this->cache?->save($key, $breaches); + + return $breaches; + } +} diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index ef2bc680dc..40b6fdae87 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -2,53 +2,33 @@ namespace Appwrite\Auth\Validator; +use Appwrite\Auth\Pwned; use Appwrite\Extend\Exception; -use Utopia\Cache\Cache; -use Utopia\Fetch\Client; /** - * Validates that a password has not been exposed in a known data breach. + * Validates a password against the project's `password-pwned` policy. * - * Configured from the project's `password-pwned` policy. Uses the Have I Been - * Pwned range API with k-anonymity: only the first five characters of the - * SHA-1 hash leave the server, and the returned suffixes are compared locally. - * Range responses are cached per prefix so repeated checks do not hit the - * service again. + * The lookup itself belongs to the configured adapter, see `Appwrite\Auth\Pwned`. + * This class only decides whether the policy asks for one. */ class PasswordPwned extends Password { - public const ENDPOINT = 'https://api.pwnedpasswords.com/range'; - public const CACHE_TTL = 3600; // seconds - - private const PREFIX_LENGTH = 5; - private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds - private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds - protected bool $enabled; - protected string $endpoint; protected bool $sessions; protected bool $users; - protected ?Cache $cache; - protected Client $client; + protected Pwned $adapter; /** * @param array $policy the project's `passwordPwned` auth settings - * @param ?string $endpoint the breach API this server is configured to use */ - public function __construct(array $policy = [], ?Cache $cache = null, ?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false) + public function __construct(Pwned $adapter, array $policy = [], bool $allowEmpty = false) { parent::__construct($allowEmpty); + $this->adapter = $adapter; $this->enabled = (bool) ($policy['enabled'] ?? true); $this->sessions = (bool) ($policy['sessions'] ?? false); $this->users = (bool) ($policy['users'] ?? false); - $this->endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/'); - $this->cache = $cache; - $this->client = $client ?? (new Client()) - ->setConnectTimeout(self::CONNECT_TIMEOUT) - ->setTimeout(self::REQUEST_TIMEOUT) - ->setAllowRedirects(false) - ->setUserAgent('Appwrite'); } /** @@ -102,18 +82,7 @@ class PasswordPwned extends Password return null; } - $hash = \strtoupper(\sha1($password)); - $prefix = \substr($hash, 0, self::PREFIX_LENGTH); - $suffix = \substr($hash, self::PREFIX_LENGTH); - - $breaches = $this->range($prefix); - - if ($breaches === null) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } - - // Entries with no breaches are dropped, so any hit means the password is breached - return isset($breaches[$suffix]); + return $this->adapter->isPwned($password); } /** @@ -122,7 +91,7 @@ class PasswordPwned extends Password * @param mixed $value * * @return bool - * @throws Exception when the breach service is unreachable and the policy fails closed + * @throws Exception when the breach service cannot be reached */ public function isValid($value): bool { @@ -137,54 +106,6 @@ class PasswordPwned extends Password return $this->check($value) !== true; } - /** - * Breach counts for every known hash sharing the prefix, from cache or the service. - * - * @return ?array hash suffix => breach count, null when the service could not be reached - */ - private function range(string $prefix): ?array - { - $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix; - - if ($this->cache !== null) { - $cached = $this->cache->load($key, self::CACHE_TTL); - if (\is_array($cached)) { - return $cached; - } - } - - try { - $response = $this->client - ->addHeader('Add-Padding', 'true') - ->fetch($this->endpoint . '/' . $prefix); - } catch (\Throwable) { - return null; - } - - if ($response->getStatusCode() !== 200) { - return null; - } - - // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches - $breaches = []; - foreach (\explode("\n", $response->text()) as $line) { - $line = \trim($line); - $separator = \strpos($line, ':'); - if ($line === '' || $separator === false) { - continue; - } - - $count = (int) \substr($line, $separator + 1); - if ($count > 0) { - $breaches[\strtoupper(\substr($line, 0, $separator))] = $count; - } - } - - $this->cache?->save($key, $breaches); - - return $breaches; - } - /** * Is array * diff --git a/tests/unit/Auth/Pwned/AppwriteTest.php b/tests/unit/Auth/Pwned/AppwriteTest.php new file mode 100644 index 0000000000..e5a97895c4 --- /dev/null +++ b/tests/unit/Auth/Pwned/AppwriteTest.php @@ -0,0 +1,150 @@ +assertTrue($this->adapter($fetch)->isPwned(self::PASSWORD)); + } + + public function testCleanPasswordIsNotReported(): void + { + $fetch = new DetectionFetch(body: '{"leaked":false}'); + + $this->assertFalse($this->adapter($fetch)->isPwned(self::PASSWORD)); + } + + public function testThePasswordTravelsInAJwtTheServiceCanOpen(): void + { + $fetch = new DetectionFetch(body: '{"leaked":false}'); + + $this->adapter($fetch)->isPwned(self::PASSWORD); + + $this->assertCount(1, $fetch->requests); + $this->assertSame('POST', $fetch->requests[0]['method']); + $this->assertSame(self::ENDPOINT, $fetch->requests[0]['url']); + + $sent = \json_decode($fetch->requests[0]['body'], true); + $this->assertIsArray($sent); + $this->assertArrayHasKey('password', $sent); + + // The service decodes with the shared secret, so it must round-trip + $decoded = (new JWT(self::SECRET, 'HS256', 900, 10))->decode($sent['password']); + $this->assertSame(self::PASSWORD, $decoded['password']); + } + + public function testATokenSignedWithAnotherSecretIsNotAccepted(): void + { + $fetch = new DetectionFetch(body: '{"leaked":false}'); + + $this->adapter($fetch)->isPwned(self::PASSWORD); + + $sent = \json_decode($fetch->requests[0]['body'], true); + + $this->expectException(\Throwable::class); + + (new JWT('a-different-secret', 'HS256', 900, 10))->decode($sent['password']); + } + + public function testUnreachableServiceIsReported(): void + { + $fetch = new DetectionFetch(failure: new \RuntimeException('connection refused')); + + try { + $this->adapter($fetch)->isPwned(self::PASSWORD); + $this->fail('Expected the unreachable service to surface'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + + public function testRejectedTokenIsReported(): void + { + // The service answers 400 when it cannot decode the token + $fetch = new DetectionFetch(statusCode: 400, body: '{"message":"Failed to verify JWT."}'); + + $this->expectException(Exception::class); + + $this->adapter($fetch)->isPwned(self::PASSWORD); + } + + public function testDetectorFailureIsReported(): void + { + $fetch = new DetectionFetch(statusCode: 500, body: ''); + + $this->expectException(Exception::class); + + $this->adapter($fetch)->isPwned(self::PASSWORD); + } + + /** + * A body the adapter cannot read must never be taken as a clean password. + */ + public function testUnreadableAnswerIsReported(): void + { + foreach (['', 'not json', '{}', '{"leaked":"yes"}', '{"pwned":true}'] as $body) { + $fetch = new DetectionFetch(body: $body); + + try { + $this->adapter($fetch)->isPwned(self::PASSWORD); + $this->fail('Expected an unreadable answer to surface: ' . $body); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + } + + private function adapter(DetectionFetch $fetch): Appwrite + { + return new Appwrite(self::ENDPOINT, self::SECRET, new Client($fetch)); + } +} + +final class DetectionFetch implements Adapter +{ + /** @var array */ + public array $requests = []; + + public function __construct( + private int $statusCode = 200, + private string $body = '', + private ?\Throwable $failure = null, + ) { + } + + public function send( + string $url, + string $method, + mixed $body, + array $headers, + RequestOptions $options, + ?callable $chunkCallback = null + ): Response { + $this->requests[] = ['url' => $url, 'method' => $method, 'body' => $body]; + + if ($this->failure !== null) { + throw $this->failure; + } + + return new Response($this->statusCode, $this->body, []); + } +} diff --git a/tests/unit/Auth/Pwned/HIBPTest.php b/tests/unit/Auth/Pwned/HIBPTest.php new file mode 100644 index 0000000000..da4ca10a15 --- /dev/null +++ b/tests/unit/Auth/Pwned/HIBPTest.php @@ -0,0 +1,198 @@ +range([self::LEAKED => 42])); + + $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + } + + public function testCleanPasswordIsNotReported(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); + + $this->assertFalse($this->adapter($fetch)->isPwned('never-leaked-' . \uniqid())); + } + + public function testAnySingleBreachCounts(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 1])); + + $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + } + + public function testPaddedEntryWithZeroCountIsNotABreach(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 0])); + + $this->assertFalse($this->adapter($fetch)->isPwned(self::LEAKED)); + } + + public function testSuffixComparisonIgnoresCase(): void + { + $fetch = new RangeFetch(body: \strtolower($this->range([self::LEAKED => 3]))); + + $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + } + + public function testOnlyTheHashPrefixLeavesTheServer(): void + { + $fetch = new RangeFetch(body: ''); + + $this->adapter($fetch)->isPwned(self::LEAKED); + + $this->assertCount(1, $fetch->urls); + + $hash = \strtoupper(\sha1(self::LEAKED)); + $url = $fetch->urls[0]; + + // Neither the password nor anything that identifies it may reach the service + $this->assertStringNotContainsStringIgnoringCase(self::LEAKED, $url); + $this->assertStringNotContainsStringIgnoringCase($hash, $url); + $this->assertStringNotContainsStringIgnoringCase(\substr($hash, 5), $url); + + // Only the first five characters go out, so the service cannot tell which password was checked + $this->assertStringEndsWith(\substr($hash, 0, 5), $url); + } + + public function testRangeIsCachedPerPrefix(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); + $cache = new Cache(new Memory()); + + $this->assertTrue((new HIBP(self::ENDPOINT, $cache, new Client($fetch)))->isPwned(self::LEAKED)); + $this->assertTrue((new HIBP(self::ENDPOINT, $cache, new Client($fetch)))->isPwned(self::LEAKED)); + + $this->assertCount(1, $fetch->urls); + } + + public function testCacheIsScopedToEndpoint(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); + $cache = new Cache(new Memory()); + + (new HIBP('https://one.test/range', $cache, new Client($fetch)))->isPwned(self::LEAKED); + (new HIBP('https://two.test/range', $cache, new Client($fetch)))->isPwned(self::LEAKED); + + $this->assertCount(2, $fetch->urls); + } + + public function testLookupsGoToTheConfiguredEndpoint(): void + { + $fetch = new RangeFetch(body: ''); + + (new HIBP('https://server.test/range', null, new Client($fetch)))->isPwned(self::LEAKED); + (new HIBP('https://other.test/range/', null, new Client($fetch)))->isPwned(self::LEAKED); + + $this->assertStringStartsWith('https://server.test/range/', $fetch->urls[0]); + $this->assertStringStartsWith('https://other.test/range/', $fetch->urls[1]); + } + + public function testUnreachableServiceIsReported(): void + { + $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); + + try { + $this->adapter($fetch)->isPwned(self::LEAKED); + $this->fail('Expected the unreachable service to surface'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + + public function testUnexpectedStatusIsReported(): void + { + $fetch = new RangeFetch(statusCode: 503, body: ''); + + $this->expectException(Exception::class); + + $this->adapter($fetch)->isPwned(self::LEAKED); + } + + public function testFailedLookupIsNotCached(): void + { + $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); + $adapter = new HIBP(self::ENDPOINT, new Cache(new Memory()), new Client($fetch)); + + foreach ([1, 2] as $attempt) { + try { + $adapter->isPwned(self::LEAKED); + } catch (Exception) { + // The lookup failed, which is the point; it must be retried rather than remembered + } + } + + $this->assertCount(2, $fetch->urls); + } + + private function adapter(RangeFetch $fetch): HIBP + { + return new HIBP(self::ENDPOINT, null, new Client($fetch)); + } + + /** + * Builds a range response body the way the Have I Been Pwned API does: + * one `SUFFIX:COUNT` line per leaked hash, CRLF separated, plus padding. + * + * @param array $leaked password => breach count + */ + private function range(array $leaked): string + { + $lines = []; + foreach ($leaked as $password => $count) { + $lines[] = \substr(\strtoupper(\sha1((string) $password)), 5) . ':' . $count; + } + $lines[] = \str_repeat('0', 35) . ':0'; + + return \implode("\r\n", $lines); + } +} + +final class RangeFetch implements Adapter +{ + /** @var array URLs the adapter asked the breach service for */ + public array $urls = []; + + public function __construct( + private int $statusCode = 200, + private string $body = '', + private ?\Throwable $failure = null, + ) { + } + + public function send( + string $url, + string $method, + mixed $body, + array $headers, + RequestOptions $options, + ?callable $chunkCallback = null + ): Response { + $this->urls[] = $url; + + if ($this->failure !== null) { + throw $this->failure; + } + + return new Response($this->statusCode, $this->body, []); + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index 6be2387956..79360c602a 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -4,24 +4,18 @@ declare(strict_types=1); namespace Tests\Unit\Auth\Validator; +use Appwrite\Auth\Pwned; use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; -use Utopia\Cache\Adapter\Memory; -use Utopia\Cache\Cache; -use Utopia\Fetch\Adapter; -use Utopia\Fetch\Client; -use Utopia\Fetch\Options\Request as RequestOptions; -use Utopia\Fetch\Response; final class PasswordPwnedTest extends TestCase { - private const LEAKED = 'Password123!'; - private const ENDPOINT = 'https://breaches.test/range'; + private const PASSWORD = 'Password123!'; public function testEnabledByDefaultWithoutSessionChecks(): void { - $validator = new PasswordPwned(); + $validator = new PasswordPwned(new FakePwned()); $this->assertTrue($validator->isEnabled()); $this->assertFalse($validator->checksSessions()); @@ -30,7 +24,7 @@ final class PasswordPwnedTest extends TestCase public function testPolicyFlags(): void { - $validator = new PasswordPwned(['enabled' => true, 'sessions' => true, 'users' => true]); + $validator = new PasswordPwned(new FakePwned(), ['enabled' => true, 'sessions' => true, 'users' => true]); $this->assertTrue($validator->isEnabled()); $this->assertTrue($validator->checksSessions()); @@ -39,237 +33,86 @@ final class PasswordPwnedTest extends TestCase public function testSessionChecksNeedAnEnabledPolicy(): void { - $validator = new PasswordPwned(['enabled' => false, 'sessions' => true, 'users' => true]); + $validator = new PasswordPwned(new FakePwned(), ['enabled' => false, 'sessions' => true, 'users' => true]); $this->assertFalse($validator->checksSessions()); } - public function testDisabledPolicyNeverChecks(): void + public function testDisabledPolicyNeverAsksTheAdapter(): void { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = new PasswordPwned(['enabled' => false], null, self::ENDPOINT, new Client($adapter)); + $adapter = new FakePwned(pwned: true); + $validator = new PasswordPwned($adapter, ['enabled' => false]); - $this->assertNull($validator->check(self::LEAKED)); - $this->assertTrue($validator->isValid(self::LEAKED)); - $this->assertCount(0, $adapter->requests); + $this->assertNull($validator->check(self::PASSWORD)); + $this->assertTrue($validator->isValid(self::PASSWORD)); + $this->assertSame(0, $adapter->calls); } - public function testCheckReportsBreachState(): void + public function testCheckReportsWhatTheAdapterFound(): void { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = $this->validator([], $adapter); - - $this->assertTrue($validator->check(self::LEAKED)); - $this->assertFalse($validator->check('never-leaked-' . \uniqid())); + $this->assertTrue((new PasswordPwned(new FakePwned(pwned: true)))->check(self::PASSWORD)); + $this->assertFalse((new PasswordPwned(new FakePwned(pwned: false)))->check(self::PASSWORD)); } - public function testLeakedPasswordIsRejected(): void + public function testBreachedPasswordIsInvalid(): void { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = $this->validator([], $adapter); - - $this->assertFalse($validator->isValid(self::LEAKED)); + $this->assertFalse((new PasswordPwned(new FakePwned(pwned: true)))->isValid(self::PASSWORD)); + $this->assertTrue((new PasswordPwned(new FakePwned(pwned: false)))->isValid(self::PASSWORD)); } - public function testCleanPasswordIsAccepted(): void + public function testAdapterFailureSurfaces(): void { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = $this->validator([], $adapter); - - $this->assertTrue($validator->isValid('never-leaked-' . \uniqid())); - } - - public function testPaddedEntryWithZeroCountIsNotABreach(): void - { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 0])); - $validator = $this->validator([], $adapter); - - $this->assertTrue($validator->isValid(self::LEAKED)); - } - - public function testSuffixComparisonIgnoresCase(): void - { - $adapter = new RangeAdapter(body: \strtolower($this->range([self::LEAKED => 3]))); - $validator = $this->validator([], $adapter); - - $this->assertFalse($validator->isValid(self::LEAKED)); - } - - public function testAnySingleBreachIsEnough(): void - { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 1])); - - $this->assertFalse($this->validator([], $adapter)->isValid(self::LEAKED)); - } - - public function testOnlyTheHashPrefixLeavesTheServer(): void - { - $adapter = new RangeAdapter(body: ''); - $validator = $this->validator([], $adapter); - - $validator->isValid(self::LEAKED); - - $this->assertCount(1, $adapter->requests); - - $hash = \strtoupper(\sha1(self::LEAKED)); - $url = $adapter->requests[0]; - - // Neither the password nor anything that identifies it may reach the service - $this->assertStringNotContainsStringIgnoringCase(self::LEAKED, $url); - $this->assertStringNotContainsStringIgnoringCase($hash, $url); - $this->assertStringNotContainsStringIgnoringCase(\substr($hash, 5), $url); - - // Only the first five characters of the hash go out, so the service cannot tell which password was checked - $this->assertStringEndsWith(\substr($hash, 0, 5), $url); - } - - public function testRangeIsCachedPerPrefix(): void - { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $cache = new Cache(new Memory()); - - $first = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); - $second = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); - - $this->assertFalse($first->isValid(self::LEAKED)); - $this->assertFalse($second->isValid(self::LEAKED)); - $this->assertCount(1, $adapter->requests); - } - - public function testCacheIsScopedToEndpoint(): void - { - $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $cache = new Cache(new Memory()); - - (new PasswordPwned(['enabled' => true], $cache, 'https://one.test/range', new Client($adapter)))->isValid(self::LEAKED); - (new PasswordPwned(['enabled' => true], $cache, 'https://two.test/range', new Client($adapter)))->isValid(self::LEAKED); - - $this->assertCount(2, $adapter->requests); - } - - public function testUnreachableServiceIsReported(): void - { - $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); - $validator = $this->validator([], $adapter); - - try { - $validator->isValid(self::LEAKED); - $this->fail('Expected the unreachable service to surface'); - } catch (Exception $e) { - $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); - } - } - - public function testUnexpectedStatusIsReported(): void - { - $adapter = new RangeAdapter(statusCode: 503, body: ''); - $validator = $this->validator([], $adapter); + $adapter = new FakePwned(failure: new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE)); + $validator = new PasswordPwned($adapter); $this->expectException(Exception::class); - $validator->isValid(self::LEAKED); - } - - public function testFailedLookupIsNotCached(): void - { - $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); - $cache = new Cache(new Memory()); - $validator = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); - - foreach ([1, 2] as $attempt) { - try { - $validator->isValid(self::LEAKED); - } catch (Exception) { - // The lookup failed, which is the point; it must be retried rather than remembered - } - } - - $this->assertCount(2, $adapter->requests); + $validator->isValid(self::PASSWORD); } public function testBasePasswordRulesStillApply(): void { - $adapter = new RangeAdapter(body: ''); - $validator = $this->validator([], $adapter); + $adapter = new FakePwned(pwned: false); + $validator = new PasswordPwned($adapter); $this->assertFalse($validator->isValid('short')); $this->assertFalse($validator->isValid(\str_repeat('p', 257))); $this->assertFalse($validator->isValid('')); - $this->assertCount(0, $adapter->requests); + $this->assertSame(0, $adapter->calls); } public function testAllowEmptySkipsTheLookup(): void { - $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned(['enabled' => true], null, self::ENDPOINT, new Client($adapter), allowEmpty: true); + $adapter = new FakePwned(pwned: true); + $validator = new PasswordPwned($adapter, [], allowEmpty: true); $this->assertTrue($validator->isValid('')); - $this->assertCount(0, $adapter->requests); - } - - public function testLookupsGoToTheConfiguredEndpoint(): void - { - $adapter = new RangeAdapter(body: ''); - - (new PasswordPwned(['enabled' => true], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); - (new PasswordPwned(['enabled' => true], null, 'https://other.test/range/', new Client($adapter)))->isValid(self::LEAKED); - - $this->assertStringStartsWith('https://server.test/range/', $adapter->requests[0]); - $this->assertStringStartsWith('https://other.test/range/', $adapter->requests[1]); - } - - /** - * @param array $policy - */ - private function validator(array $policy, RangeAdapter $adapter): PasswordPwned - { - return new PasswordPwned(\array_merge(['enabled' => true], $policy), null, self::ENDPOINT, new Client($adapter)); - } - - /** - * Builds a range response body the way the Have I Been Pwned API does: - * one `SUFFIX:COUNT` line per leaked hash, CRLF separated, plus padding. - * - * @param array $leaked password => breach count - */ - private function range(array $leaked): string - { - $lines = []; - foreach ($leaked as $password => $count) { - $lines[] = \substr(\strtoupper(\sha1((string) $password)), 5) . ':' . $count; - } - $lines[] = \str_repeat('0', 35) . ':0'; - - return \implode("\r\n", $lines); + $this->assertSame(0, $adapter->calls); } } -final class RangeAdapter implements Adapter +final class FakePwned extends Pwned { - /** @var array URLs the validator asked the breach service for */ - public array $requests = []; + public int $calls = 0; - public function __construct( - private int $statusCode = 200, - private string $body = '', - private ?\Throwable $failure = null, - ) { + public function __construct(private bool $pwned = false, private ?\Throwable $failure = null) + { + parent::__construct('https://breaches.test'); } - public function send( - string $url, - string $method, - mixed $body, - array $headers, - RequestOptions $options, - ?callable $chunkCallback = null - ): Response { - $this->requests[] = $url; + public function getName(): string + { + return 'fake'; + } + + public function isPwned(string $password): bool + { + $this->calls++; if ($this->failure !== null) { throw $this->failure; } - return new Response($this->statusCode, $this->body, []); + return $this->pwned; } } From 21d36f8425abaac509daff71952da10320a9f141 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 15:42:54 +0200 Subject: [PATCH 20/38] refactor(auth): configure the breach lookup with one DSN Replaces `_APP_PWNED_PASSWORDS_ADAPTER` and `_APP_PWNED_PASSWORDS_ENDPOINT` with a single `_APP_PWNED_PASSWORDS_DSN`, following how storage, logging and the database connections are configured. The scheme picks the adapter and the rest carries whatever that adapter needs. - `hibp://localhost` reads no details, like `local://localhost` does for storage. - `appwrite://SECRET@HOST[:PORT][/PATH][?tls=true]` carries the host and the JWT secret the service shares, so the secret is no longer borrowed from `_APP_OPENSSL_KEY_V1`. The path defaults to `v1/detection`. - `mock://localhost` is new. It reports a fixed list of passwords as breached without leaving the process, and is refused on a production server because it would report every real password as safe. The test stack now uses the mock adapter, which lets the mock range route in `app/controllers/mock.php` go away. E2E covers the policy, the adapter unit tests cover each protocol. Co-Authored-By: Claude Opus 5 (1M context) --- .env | 3 +- app/config/variables.php | 15 ++----- app/controllers/mock.php | 32 --------------- app/init/resources/request.php | 17 +++++--- docker-compose.yml | 3 +- src/Appwrite/Auth/Pwned.php | 38 +++++++++--------- src/Appwrite/Auth/Pwned/Appwrite.php | 25 ++++++++---- src/Appwrite/Auth/Pwned/HIBP.php | 10 +++-- src/Appwrite/Auth/Pwned/Mock.php | 36 +++++++++++++++++ .../PoliciesPasswordPwnedIntegrationTest.php | 6 +-- tests/unit/Auth/Pwned/AppwriteTest.php | 27 +++++++++++-- tests/unit/Auth/Pwned/HIBPTest.php | 16 ++++---- tests/unit/Auth/Pwned/MockTest.php | 39 +++++++++++++++++++ 13 files changed, 169 insertions(+), 98 deletions(-) create mode 100644 src/Appwrite/Auth/Pwned/Mock.php create mode 100644 tests/unit/Auth/Pwned/MockTest.php diff --git a/.env b/.env index a29af52345..261a9e3848 100644 --- a/.env +++ b/.env @@ -175,8 +175,7 @@ _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET= _APP_PROJECT_REGIONS=default _APP_GEO_SECRET=your-secret-key _APP_GEO_ENDPOINT=http://appwrite-geo/v1 -_APP_PWNED_PASSWORDS_ADAPTER=hibp -_APP_PWNED_PASSWORDS_ENDPOINT=http://localhost/v1/mock/tests/general/pwned-passwords +_APP_PWNED_PASSWORDS_DSN=mock://localhost _APP_VCS_GITHUB_APP_ID= _APP_VCS_GITHUB_APP_NAME= _APP_VCS_GITHUB_CLIENT_ID= diff --git a/app/config/variables.php b/app/config/variables.php index 9bcde780f8..315b498a29 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -485,19 +485,10 @@ return [ 'filter' => 'token' ], [ - 'name' => '_APP_PWNED_PASSWORDS_ADAPTER', - 'description' => 'Service the password pwned project policy asks whether a password has been breached. `hibp` calls the Have I Been Pwned range API and only ever sends the first five characters of the password SHA-1 hash. `appwrite` calls an [Appwrite Pwned](https://github.com/appwrite-labs/pwned) service you run yourself, which caches answers and can front a detector of your choice, but receives the whole password inside a JWT signed with `_APP_OPENSSL_KEY_V1`, so only point it at a service on your own network.', + 'name' => '_APP_PWNED_PASSWORDS_DSN', + 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter.\n\nExamples:\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which caches answers and can front a detector of your choice. It receives the whole password inside a JWT signed with `SECRET`, which must match the service's `APPWRITE_PWNED_JWT_SECRET`, so only point it at a service on your own network. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", 'introduction' => 'TBD', - 'default' => 'hibp', - 'required' => false, - 'question' => '', - 'filter' => '' - ], - [ - 'name' => '_APP_PWNED_PASSWORDS_ENDPOINT', - 'description' => 'Address the adapter chosen in `_APP_PWNED_PASSWORDS_ADAPTER` calls. Leave empty to use that adapter\'s default, which is `https://api.pwnedpasswords.com/range` for `hibp` and `http://appwrite-pwned/v1/detection` for `appwrite`.', - 'introduction' => 'TBD', - 'default' => '', + 'default' => 'hibp://localhost', 'required' => false, 'question' => '', 'filter' => '' diff --git a/app/controllers/mock.php b/app/controllers/mock.php index 3b745fa501..9d91cccde4 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -501,35 +501,3 @@ Http::shutdown() $response->dynamic(new Document(['result' => \implode(',', $methods) . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK); }); - -Http::get('/v1/mock/tests/general/pwned-passwords/:prefix') - ->desc('Pwned Passwords range') - ->groups(['mock']) - ->label('scope', 'public') - ->label('docs', false) - ->label('mock', true) - ->param('prefix', '', new Text(5, 5), 'First five characters of the SHA-1 password hash.') - ->inject('response') - ->action(function (string $prefix, Response $response) { - // Mirrors the Have I Been Pwned range API: every leaked hash sharing the - // requested prefix comes back as `SUFFIX:COUNT`, one per line. - $leaked = [ - 'pwned-fixture-common' => 12345, - 'pwned-fixture-uncommon' => 678, - 'pwned-fixture-rare' => 9, - ]; - - $prefix = \strtoupper($prefix); - $lines = []; - foreach ($leaked as $password => $count) { - $hash = \strtoupper(\sha1($password)); - if (\str_starts_with($hash, $prefix)) { - $lines[] = \substr($hash, 5) . ':' . $count; - } - } - - // Padded entries carry a count of 0 and must never be treated as a breach - $lines[] = \str_repeat('0', 35) . ':0'; - - $response->text(\implode("\r\n", $lines)); - }); diff --git a/app/init/resources/request.php b/app/init/resources/request.php index f669ee1d90..ce0a337fa9 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -5,6 +5,7 @@ use Ahc\Jwt\JWTException; use Appwrite\Auth\Key; use Appwrite\Auth\Pwned\Appwrite as PwnedAppwrite; use Appwrite\Auth\Pwned\HIBP as PwnedHIBP; +use Appwrite\Auth\Pwned\Mock as PwnedMock; use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; @@ -52,6 +53,7 @@ use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\DI\Container; use Utopia\Domains\Domain; +use Utopia\DSN\DSN; use Utopia\Http\Http; use Utopia\Locale\Locale; use Utopia\Lock\Distributed as DistributedLock; @@ -677,13 +679,16 @@ return function (Container $context): void { }, ['user', 'store', 'proofForToken']); $context->set('pwnedPasswords', function (Document $project, Cache $cache) { - $endpoint = System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT', ''); - $name = \strtolower(System::getEnv('_APP_PWNED_PASSWORDS_ADAPTER', 'hibp')); + $dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'hibp://localhost')); - $adapter = match ($name) { - 'hibp' => new PwnedHIBP($endpoint, $cache), - 'appwrite' => new PwnedAppwrite($endpoint, System::getEnv('_APP_OPENSSL_KEY_V1', '')), - default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_ADAPTER: ' . $name), + $adapter = match ($dsn->getScheme()) { + 'hibp' => new PwnedHIBP($cache), + 'appwrite' => new PwnedAppwrite($dsn), + // Reports almost every password as safe, so it must never be reachable on a real server + 'mock' => Http::isProduction() + ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach adapter cannot be used in production.') + : new PwnedMock(), + default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_DSN scheme: ' . $dsn->getScheme()), }; return new PasswordPwned($adapter, $project->getAttribute('auths', [])['passwordPwned'] ?? []); diff --git a/docker-compose.yml b/docker-compose.yml index 2aff35ba09..b263f7961d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -254,8 +254,7 @@ services: - _APP_MIGRATION_HOST - _APP_GEO_SECRET - _APP_GEO_ENDPOINT - - _APP_PWNED_PASSWORDS_ADAPTER - - _APP_PWNED_PASSWORDS_ENDPOINT + - _APP_PWNED_PASSWORDS_DSN - _APP_LIMIT_DATABASE_BATCH - _APP_DOCUMENTSDB - _APP_VECTORSDB diff --git a/src/Appwrite/Auth/Pwned.php b/src/Appwrite/Auth/Pwned.php index 7bd145794c..25ae03bd2b 100644 --- a/src/Appwrite/Auth/Pwned.php +++ b/src/Appwrite/Auth/Pwned.php @@ -8,31 +8,17 @@ use Utopia\Fetch\Client; /** * Looks a password up in a database of known data breaches. * - * Adapters differ in what leaves the server and where it goes, so read the - * concrete class before choosing one. Pick the adapter with - * `_APP_PWNED_PASSWORDS_ADAPTER` and the address with - * `_APP_PWNED_PASSWORDS_ENDPOINT`. + * The adapter and its details both come from `_APP_PWNED_PASSWORDS_DSN`, whose + * scheme picks the adapter. Adapters differ in what leaves the server and where + * it goes, so read the concrete class before choosing one. */ abstract class Pwned { - protected const CONNECT_TIMEOUT = 3 * 1000; // milliseconds - protected const REQUEST_TIMEOUT = 5 * 1000; // milliseconds - - protected string $endpoint; - protected Client $client; - - public function __construct(string $endpoint, ?Client $client = null) - { - $this->endpoint = \rtrim($endpoint, '/'); - $this->client = $client ?? (new Client()) - ->setConnectTimeout(self::CONNECT_TIMEOUT) - ->setTimeout(self::REQUEST_TIMEOUT) - ->setAllowRedirects(false) - ->setUserAgent('Appwrite'); - } + private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds + private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds /** - * Adapter name, as accepted by `_APP_PWNED_PASSWORDS_ADAPTER`. + * Adapter name, matching the DSN scheme that selects it. */ abstract public function getName(): string; @@ -43,6 +29,18 @@ abstract class Pwned */ abstract public function isPwned(string $password): bool; + /** + * A client with the timeouts a password check can afford to wait. + */ + protected function client(?Client $client = null): Client + { + return $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + } + /** * A password is never silently accepted when the lookup did not happen. * diff --git a/src/Appwrite/Auth/Pwned/Appwrite.php b/src/Appwrite/Auth/Pwned/Appwrite.php index 2392ec22c0..099f86711a 100644 --- a/src/Appwrite/Auth/Pwned/Appwrite.php +++ b/src/Appwrite/Auth/Pwned/Appwrite.php @@ -4,6 +4,7 @@ namespace Appwrite\Auth\Pwned; use Ahc\Jwt\JWT; use Appwrite\Auth\Pwned; +use Utopia\DSN\DSN; use Utopia\Fetch\Client; /** @@ -11,25 +12,35 @@ use Utopia\Fetch\Client; * * The service answers for a whole password rather than a hash prefix, so unlike * `HIBP` this sends the password itself. It travels inside a short-lived JWT - * signed with a secret shared with the service, which is only safe on a network - * you control. In exchange the service caches answers and can front Have I Been - * Pwned or another detector without the server knowing which. + * signed with a secret the service shares, which is only safe on a network you + * control. In exchange the service caches answers and can front Have I Been + * Pwned or another detector without this server knowing which. + * + * DSN: `appwrite://SECRET@HOST[:PORT][/PATH][?tls=true]`. The secret must match + * the service's `APPWRITE_PWNED_JWT_SECRET`, the path defaults to + * `v1/detection`, and the connection is plain HTTP unless `tls=true`. */ class Appwrite extends Pwned { - public const ENDPOINT = 'http://appwrite-pwned/v1/detection'; + private const PATH = 'v1/detection'; // The service decodes with the same window private const TOKEN_EXPIRY = 900; // seconds private const TOKEN_LEEWAY = 10; // seconds + protected string $endpoint; protected string $secret; + protected Client $client; - public function __construct(string $endpoint = '', string $secret = '', ?Client $client = null) + public function __construct(DSN $dsn, ?Client $client = null) { - parent::__construct($endpoint ?: self::ENDPOINT, $client); + $scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http'; + $port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : ''; + $path = $dsn->getPath(); - $this->secret = $secret; + $this->endpoint = $scheme . '://' . $dsn->getHost() . $port . '/' . ($path === '' || $path === null ? self::PATH : $path); + $this->secret = $dsn->getUser() ?? ''; + $this->client = $this->client($client); } public function getName(): string diff --git a/src/Appwrite/Auth/Pwned/HIBP.php b/src/Appwrite/Auth/Pwned/HIBP.php index e115715bbd..bbbf7ce8a3 100644 --- a/src/Appwrite/Auth/Pwned/HIBP.php +++ b/src/Appwrite/Auth/Pwned/HIBP.php @@ -13,6 +13,8 @@ use Utopia\Fetch\Client; * leave the server, and the candidate suffixes that come back are compared * locally. Range responses are cached per prefix, so a busy project does not * ask the service the same question twice. + * + * DSN: `hibp://localhost`, no details are read. */ class HIBP extends Pwned { @@ -22,12 +24,14 @@ class HIBP extends Pwned private const PREFIX_LENGTH = 5; protected ?Cache $cache; + protected Client $client; + protected string $endpoint; - public function __construct(string $endpoint = '', ?Cache $cache = null, ?Client $client = null) + public function __construct(?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT) { - parent::__construct($endpoint ?: self::ENDPOINT, $client); - $this->cache = $cache; + $this->client = $this->client($client); + $this->endpoint = \rtrim($endpoint, '/'); } public function getName(): string diff --git a/src/Appwrite/Auth/Pwned/Mock.php b/src/Appwrite/Auth/Pwned/Mock.php new file mode 100644 index 0000000000..d272ae9e0c --- /dev/null +++ b/src/Appwrite/Auth/Pwned/Mock.php @@ -0,0 +1,36 @@ +assertCount(1, $fetch->requests); $this->assertSame('POST', $fetch->requests[0]['method']); - $this->assertSame(self::ENDPOINT, $fetch->requests[0]['url']); + $this->assertSame('http://pwned.test/v1/detection', $fetch->requests[0]['url']); $sent = \json_decode($fetch->requests[0]['body'], true); $this->assertIsArray($sent); @@ -113,9 +114,29 @@ final class AppwriteTest extends TestCase } } + public function testTheDsnDescribesWhereAndHowToConnect(): void + { + $cases = [ + 'appwrite://secret@pwned.test/v1/detection' => 'http://pwned.test/v1/detection', + // The path the service exposes is assumed when the DSN leaves it out + 'appwrite://secret@pwned.test' => 'http://pwned.test/v1/detection', + 'appwrite://secret@pwned.test:8088' => 'http://pwned.test:8088/v1/detection', + 'appwrite://secret@pwned.test/custom/path' => 'http://pwned.test/custom/path', + 'appwrite://secret@pwned.test?tls=true' => 'https://pwned.test/v1/detection', + ]; + + foreach ($cases as $dsn => $expected) { + $fetch = new DetectionFetch(body: '{"leaked":false}'); + + (new Appwrite(new DSN($dsn), new Client($fetch)))->isPwned(self::PASSWORD); + + $this->assertSame($expected, $fetch->requests[0]['url'], $dsn); + } + } + private function adapter(DetectionFetch $fetch): Appwrite { - return new Appwrite(self::ENDPOINT, self::SECRET, new Client($fetch)); + return new Appwrite(new DSN(self::DSN), new Client($fetch)); } } diff --git a/tests/unit/Auth/Pwned/HIBPTest.php b/tests/unit/Auth/Pwned/HIBPTest.php index da4ca10a15..9c3a55ce3b 100644 --- a/tests/unit/Auth/Pwned/HIBPTest.php +++ b/tests/unit/Auth/Pwned/HIBPTest.php @@ -79,8 +79,8 @@ final class HIBPTest extends TestCase $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - $this->assertTrue((new HIBP(self::ENDPOINT, $cache, new Client($fetch)))->isPwned(self::LEAKED)); - $this->assertTrue((new HIBP(self::ENDPOINT, $cache, new Client($fetch)))->isPwned(self::LEAKED)); + $this->assertTrue((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isPwned(self::LEAKED)); + $this->assertTrue((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isPwned(self::LEAKED)); $this->assertCount(1, $fetch->urls); } @@ -90,8 +90,8 @@ final class HIBPTest extends TestCase $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - (new HIBP('https://one.test/range', $cache, new Client($fetch)))->isPwned(self::LEAKED); - (new HIBP('https://two.test/range', $cache, new Client($fetch)))->isPwned(self::LEAKED); + (new HIBP($cache, new Client($fetch), 'https://one.test/range'))->isPwned(self::LEAKED); + (new HIBP($cache, new Client($fetch), 'https://two.test/range'))->isPwned(self::LEAKED); $this->assertCount(2, $fetch->urls); } @@ -100,8 +100,8 @@ final class HIBPTest extends TestCase { $fetch = new RangeFetch(body: ''); - (new HIBP('https://server.test/range', null, new Client($fetch)))->isPwned(self::LEAKED); - (new HIBP('https://other.test/range/', null, new Client($fetch)))->isPwned(self::LEAKED); + (new HIBP(null, new Client($fetch), 'https://server.test/range'))->isPwned(self::LEAKED); + (new HIBP(null, new Client($fetch), 'https://other.test/range/'))->isPwned(self::LEAKED); $this->assertStringStartsWith('https://server.test/range/', $fetch->urls[0]); $this->assertStringStartsWith('https://other.test/range/', $fetch->urls[1]); @@ -131,7 +131,7 @@ final class HIBPTest extends TestCase public function testFailedLookupIsNotCached(): void { $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); - $adapter = new HIBP(self::ENDPOINT, new Cache(new Memory()), new Client($fetch)); + $adapter = new HIBP(new Cache(new Memory()), new Client($fetch), self::ENDPOINT); foreach ([1, 2] as $attempt) { try { @@ -146,7 +146,7 @@ final class HIBPTest extends TestCase private function adapter(RangeFetch $fetch): HIBP { - return new HIBP(self::ENDPOINT, null, new Client($fetch)); + return new HIBP(null, new Client($fetch), self::ENDPOINT); } /** diff --git a/tests/unit/Auth/Pwned/MockTest.php b/tests/unit/Auth/Pwned/MockTest.php new file mode 100644 index 0000000000..932c7422b9 --- /dev/null +++ b/tests/unit/Auth/Pwned/MockTest.php @@ -0,0 +1,39 @@ +assertTrue($adapter->isPwned($password), $password); + } + } + + public function testAnythingElseIsReportedAsSafe(): void + { + $adapter = new Mock(); + + $this->assertFalse($adapter->isPwned('some-other-password')); + $this->assertFalse($adapter->isPwned('')); + } + + public function testMatchingIsExact(): void + { + $adapter = new Mock(); + $fixture = Mock::BREACHED[0]; + + // A fixture that merely contains or resembles a breached one is not breached + $this->assertFalse($adapter->isPwned(\strtoupper($fixture))); + $this->assertFalse($adapter->isPwned($fixture . '!')); + $this->assertFalse($adapter->isPwned(\substr($fixture, 1))); + } +} From eb94af3654753c268eed8c46041527454463e2c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 15:48:47 +0200 Subject: [PATCH 21/38] refactor(auth): drop the adapter layer, let the validator be the validator Review feedback: `Appwrite\Auth\Pwned` was a second hierarchy wrapped by a validator whose `isValid()` nothing called, and every call site reached for `check()` instead. That is not how validators are used here. `PasswordPwned` is now abstract, with one subclass per service, the same shape as `OAuth2` and its providers. The request resource hands back the right subclass and call sites use `isValid()` like they already do for `PersonalData` and `PasswordHistory`. The tri-state for the `passwordPwned` user attribute did not need a method of its own after all. A call site knows whether the policy is enabled, so null comes from not asking rather than from a return value. Co-Authored-By: Claude Opus 5 (1M context) --- app/controllers/api/account.php | 17 ++- app/init/resources/request.php | 21 ++- src/Appwrite/Auth/Pwned.php | 53 -------- src/Appwrite/Auth/Validator/PasswordPwned.php | 70 ++++++---- .../PasswordPwned}/Appwrite.php | 22 +-- .../PasswordPwned}/HIBP.php | 22 +-- .../PasswordPwned}/Mock.php | 15 +-- .../Modules/Users/Http/Users/Create.php | 4 +- .../Users/Http/Users/Password/Update.php | 4 +- .../PoliciesPasswordPwnedIntegrationTest.php | 2 +- tests/unit/Auth/Pwned/MockTest.php | 39 ------ .../PasswordPwned}/AppwriteTest.php | 127 +++++++++--------- .../PasswordPwned}/HIBPTest.php | 56 ++++---- .../Auth/Validator/PasswordPwned/MockTest.php | 38 ++++++ .../unit/Auth/Validator/PasswordPwnedTest.php | 86 +++--------- 15 files changed, 257 insertions(+), 319 deletions(-) delete mode 100644 src/Appwrite/Auth/Pwned.php rename src/Appwrite/Auth/{Pwned => Validator/PasswordPwned}/Appwrite.php (83%) rename src/Appwrite/Auth/{Pwned => Validator/PasswordPwned}/HIBP.php (84%) rename src/Appwrite/Auth/{Pwned => Validator/PasswordPwned}/Mock.php (68%) delete mode 100644 tests/unit/Auth/Pwned/MockTest.php rename tests/unit/Auth/{Pwned => Validator/PasswordPwned}/AppwriteTest.php (77%) rename tests/unit/Auth/{Pwned => Validator/PasswordPwned}/HIBPTest.php (68%) create mode 100644 tests/unit/Auth/Validator/PasswordPwned/MockTest.php diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 9256ab59c7..e665d9cb43 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -363,7 +363,8 @@ Http::post('/v1/account') } } - $passwordPwned = $pwnedPasswords->check($password); + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -1050,9 +1051,9 @@ Http::post('/v1/account/sessions/email') if ($pwnedPasswords->checksSessions()) { // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in - $passwordPwned = $pwnedPasswords->check($password); + $passwordPwned = !$pwnedPasswords->isValid($password); - if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { + if ($passwordPwned !== $user->getAttribute('passwordPwned')) { $user->setAttribute('passwordPwned', $passwordPwned); $dbForProject->updateDocument('users', $user->getId(), new Document([ 'passwordPwned' => $passwordPwned, @@ -3509,7 +3510,8 @@ Http::patch('/v1/account/password') } } - $passwordPwned = $pwnedPasswords->check($password); + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3613,7 +3615,7 @@ Http::patch('/v1/account/email') } } - $passwordPwned = $pwnedPasswords->check($password); + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3787,7 +3789,7 @@ Http::patch('/v1/account/phone') } } - $passwordPwned = $pwnedPasswords->check($password); + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -4234,7 +4236,8 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } - $passwordPwned = $pwnedPasswords->check($password); + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } diff --git a/app/init/resources/request.php b/app/init/resources/request.php index ce0a337fa9..ca3b559721 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -3,10 +3,9 @@ use Ahc\Jwt\JWT; use Ahc\Jwt\JWTException; use Appwrite\Auth\Key; -use Appwrite\Auth\Pwned\Appwrite as PwnedAppwrite; -use Appwrite\Auth\Pwned\HIBP as PwnedHIBP; -use Appwrite\Auth\Pwned\Mock as PwnedMock; -use Appwrite\Auth\Validator\PasswordPwned; +use Appwrite\Auth\Validator\PasswordPwned\Appwrite as PasswordPwnedAppwrite; +use Appwrite\Auth\Validator\PasswordPwned\HIBP as PasswordPwnedHIBP; +use Appwrite\Auth\Validator\PasswordPwned\Mock as PasswordPwnedMock; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; use Appwrite\Deployment\Deployments; @@ -681,17 +680,17 @@ return function (Container $context): void { $context->set('pwnedPasswords', function (Document $project, Cache $cache) { $dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'hibp://localhost')); - $adapter = match ($dsn->getScheme()) { - 'hibp' => new PwnedHIBP($cache), - 'appwrite' => new PwnedAppwrite($dsn), + $policy = $project->getAttribute('auths', [])['passwordPwned'] ?? []; + + return match ($dsn->getScheme()) { + 'hibp' => new PasswordPwnedHIBP($policy, $cache), + 'appwrite' => new PasswordPwnedAppwrite($policy, $dsn), // Reports almost every password as safe, so it must never be reachable on a real server 'mock' => Http::isProduction() - ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach adapter cannot be used in production.') - : new PwnedMock(), + ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach validator cannot be used in production.') + : new PasswordPwnedMock($policy), default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_DSN scheme: ' . $dsn->getScheme()), }; - - return new PasswordPwned($adapter, $project->getAttribute('auths', [])['passwordPwned'] ?? []); }, ['project', 'cache']); $context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) { diff --git a/src/Appwrite/Auth/Pwned.php b/src/Appwrite/Auth/Pwned.php deleted file mode 100644 index 25ae03bd2b..0000000000 --- a/src/Appwrite/Auth/Pwned.php +++ /dev/null @@ -1,53 +0,0 @@ -setConnectTimeout(self::CONNECT_TIMEOUT) - ->setTimeout(self::REQUEST_TIMEOUT) - ->setAllowRedirects(false) - ->setUserAgent('Appwrite'); - } - - /** - * A password is never silently accepted when the lookup did not happen. - * - * @throws Exception - */ - protected function unavailable(): never - { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } -} diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index 40b6fdae87..649d21948d 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -2,30 +2,32 @@ namespace Appwrite\Auth\Validator; -use Appwrite\Auth\Pwned; use Appwrite\Extend\Exception; +use Utopia\Fetch\Client; /** * Validates a password against the project's `password-pwned` policy. * - * The lookup itself belongs to the configured adapter, see `Appwrite\Auth\Pwned`. - * This class only decides whether the policy asks for one. + * Subclasses differ in who answers the question and in what leaves the server, + * so read the one you are configuring. `_APP_PWNED_PASSWORDS_DSN` picks it, and + * the DSN scheme matches the subclass. */ -class PasswordPwned extends Password +abstract class PasswordPwned extends Password { + private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds + private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds + protected bool $enabled; protected bool $sessions; protected bool $users; - protected Pwned $adapter; /** * @param array $policy the project's `passwordPwned` auth settings */ - public function __construct(Pwned $adapter, array $policy = [], bool $allowEmpty = false) + public function __construct(array $policy = [], bool $allowEmpty = false) { parent::__construct($allowEmpty); - $this->adapter = $adapter; $this->enabled = (bool) ($policy['enabled'] ?? true); $this->sessions = (bool) ($policy['sessions'] ?? false); $this->users = (bool) ($policy['users'] ?? false); @@ -69,25 +71,12 @@ class PasswordPwned extends Password return 'Password must not have been exposed in a known data breach.'; } - /** - * Whether the password appears in a known breach. - * - * Returns null only when the policy is disabled. - * - * @throws Exception when the breach service cannot be reached - */ - public function check(string $password): ?bool - { - if (!$this->enabled) { - return null; - } - - return $this->adapter->isPwned($password); - } - /** * Is valid. * + * A password the policy did not look at is valid, so callers that need to + * tell "clean" from "never checked" ask `isEnabled()` first. + * * @param mixed $value * * @return bool @@ -103,7 +92,11 @@ class PasswordPwned extends Password return true; } - return $this->check($value) !== true; + if (!$this->enabled) { + return true; + } + + return !$this->isPwned($value); } /** @@ -129,4 +122,33 @@ class PasswordPwned extends Password { return self::TYPE_STRING; } + + /** + * Whether the password appears in a known data breach. + * + * @throws Exception when the breach service cannot be reached or answers with nonsense + */ + abstract protected function isPwned(string $password): bool; + + /** + * A client with the timeouts a password check can afford to wait. + */ + protected function client(?Client $client = null): Client + { + return $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + } + + /** + * A password is never silently accepted when the lookup did not happen. + * + * @throws Exception + */ + protected function unavailable(): never + { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } } diff --git a/src/Appwrite/Auth/Pwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php similarity index 83% rename from src/Appwrite/Auth/Pwned/Appwrite.php rename to src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php index 099f86711a..a2199a50d5 100644 --- a/src/Appwrite/Auth/Pwned/Appwrite.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -1,14 +1,14 @@ $policy + */ + public function __construct(array $policy, DSN $dsn, ?Client $client = null) { + parent::__construct($policy); + $scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http'; $port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : ''; $path = $dsn->getPath(); @@ -43,12 +48,7 @@ class Appwrite extends Pwned $this->client = $this->client($client); } - public function getName(): string - { - return 'appwrite'; - } - - public function isPwned(string $password): bool + protected function isPwned(string $password): bool { $jwt = new JWT($this->secret, 'HS256', self::TOKEN_EXPIRY, self::TOKEN_LEEWAY); diff --git a/src/Appwrite/Auth/Pwned/HIBP.php b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php similarity index 84% rename from src/Appwrite/Auth/Pwned/HIBP.php rename to src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php index bbbf7ce8a3..086c5a5f6f 100644 --- a/src/Appwrite/Auth/Pwned/HIBP.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php @@ -1,13 +1,13 @@ $policy + */ + public function __construct(array $policy = [], ?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT) { + parent::__construct($policy); + $this->cache = $cache; $this->client = $this->client($client); $this->endpoint = \rtrim($endpoint, '/'); } - public function getName(): string - { - return 'hibp'; - } - - public function isPwned(string $password): bool + protected function isPwned(string $password): bool { $hash = \strtoupper(\sha1($password)); $prefix = \substr($hash, 0, self::PREFIX_LENGTH); diff --git a/src/Appwrite/Auth/Pwned/Mock.php b/src/Appwrite/Auth/Validator/PasswordPwned/Mock.php similarity index 68% rename from src/Appwrite/Auth/Pwned/Mock.php rename to src/Appwrite/Auth/Validator/PasswordPwned/Mock.php index d272ae9e0c..3be74fb19d 100644 --- a/src/Appwrite/Auth/Pwned/Mock.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Mock.php @@ -1,8 +1,8 @@ check($password); + $passwordPwned = empty($password) || !$pwnedPasswords->isEnabled() + ? null + : !$pwnedPasswords->isValid($password); if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index aba1363d92..b39fdc6a82 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -86,7 +86,9 @@ class Update extends Action } } - $passwordPwned = \strlen($password) === 0 ? null : $pwnedPasswords->check($password); + $passwordPwned = \strlen($password) === 0 || !$pwnedPasswords->isEnabled() + ? null + : !$pwnedPasswords->isValid($password); if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 7564df4e96..05d001f109 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -20,7 +20,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope use ProjectCustom; use SideServer; - // Reported as breached by the mock adapter, see Appwrite\Auth\Pwned\Mock + // Reported as breached by the mock adapter, see Appwrite\Auth\Validator\PasswordPwned\Mock private const PWNED_PASSWORD = 'pwned-fixture-common'; public function testDefaultsOnNewProject(): void diff --git a/tests/unit/Auth/Pwned/MockTest.php b/tests/unit/Auth/Pwned/MockTest.php deleted file mode 100644 index 932c7422b9..0000000000 --- a/tests/unit/Auth/Pwned/MockTest.php +++ /dev/null @@ -1,39 +0,0 @@ -assertTrue($adapter->isPwned($password), $password); - } - } - - public function testAnythingElseIsReportedAsSafe(): void - { - $adapter = new Mock(); - - $this->assertFalse($adapter->isPwned('some-other-password')); - $this->assertFalse($adapter->isPwned('')); - } - - public function testMatchingIsExact(): void - { - $adapter = new Mock(); - $fixture = Mock::BREACHED[0]; - - // A fixture that merely contains or resembles a breached one is not breached - $this->assertFalse($adapter->isPwned(\strtoupper($fixture))); - $this->assertFalse($adapter->isPwned($fixture . '!')); - $this->assertFalse($adapter->isPwned(\substr($fixture, 1))); - } -} diff --git a/tests/unit/Auth/Pwned/AppwriteTest.php b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php similarity index 77% rename from tests/unit/Auth/Pwned/AppwriteTest.php rename to tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php index 924c30dfcc..43ad793fd2 100644 --- a/tests/unit/Auth/Pwned/AppwriteTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace Tests\Unit\Auth\Pwned; +namespace Tests\Unit\Auth\Validator\PasswordPwned; use Ahc\Jwt\JWT; -use Appwrite\Auth\Pwned\Appwrite; +use Appwrite\Auth\Validator\PasswordPwned\Appwrite; use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; use Utopia\DSN\DSN; @@ -20,29 +20,36 @@ final class AppwriteTest extends TestCase private const SECRET = 'shared-with-the-service'; private const DSN = 'appwrite://' . self::SECRET . '@pwned.test/v1/detection'; - public function testLeakedPasswordIsReported(): void + public function testLeakedPasswordIsRejected(): void { $fetch = new DetectionFetch(body: '{"leaked":true}'); - $this->assertTrue($this->adapter($fetch)->isPwned(self::PASSWORD)); + $this->assertFalse($this->validator($fetch)->isValid(self::PASSWORD)); } - public function testCleanPasswordIsNotReported(): void + public function testCleanPasswordIsAccepted(): void { $fetch = new DetectionFetch(body: '{"leaked":false}'); - $this->assertFalse($this->adapter($fetch)->isPwned(self::PASSWORD)); + $this->assertTrue($this->validator($fetch)->isValid(self::PASSWORD)); + } + + public function testDisabledPolicyNeverAsksTheService(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + + $this->assertTrue((new Appwrite(['enabled' => false], new DSN(self::DSN), new Client($fetch)))->isValid(self::PASSWORD)); + $this->assertCount(0, $fetch->requests); } public function testThePasswordTravelsInAJwtTheServiceCanOpen(): void { $fetch = new DetectionFetch(body: '{"leaked":false}'); - $this->adapter($fetch)->isPwned(self::PASSWORD); + $this->validator($fetch)->isValid(self::PASSWORD); $this->assertCount(1, $fetch->requests); $this->assertSame('POST', $fetch->requests[0]['method']); - $this->assertSame('http://pwned.test/v1/detection', $fetch->requests[0]['url']); $sent = \json_decode($fetch->requests[0]['body'], true); $this->assertIsArray($sent); @@ -57,7 +64,7 @@ final class AppwriteTest extends TestCase { $fetch = new DetectionFetch(body: '{"leaked":false}'); - $this->adapter($fetch)->isPwned(self::PASSWORD); + $this->validator($fetch)->isValid(self::PASSWORD); $sent = \json_decode($fetch->requests[0]['body'], true); @@ -66,54 +73,6 @@ final class AppwriteTest extends TestCase (new JWT('a-different-secret', 'HS256', 900, 10))->decode($sent['password']); } - public function testUnreachableServiceIsReported(): void - { - $fetch = new DetectionFetch(failure: new \RuntimeException('connection refused')); - - try { - $this->adapter($fetch)->isPwned(self::PASSWORD); - $this->fail('Expected the unreachable service to surface'); - } catch (Exception $e) { - $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); - } - } - - public function testRejectedTokenIsReported(): void - { - // The service answers 400 when it cannot decode the token - $fetch = new DetectionFetch(statusCode: 400, body: '{"message":"Failed to verify JWT."}'); - - $this->expectException(Exception::class); - - $this->adapter($fetch)->isPwned(self::PASSWORD); - } - - public function testDetectorFailureIsReported(): void - { - $fetch = new DetectionFetch(statusCode: 500, body: ''); - - $this->expectException(Exception::class); - - $this->adapter($fetch)->isPwned(self::PASSWORD); - } - - /** - * A body the adapter cannot read must never be taken as a clean password. - */ - public function testUnreadableAnswerIsReported(): void - { - foreach (['', 'not json', '{}', '{"leaked":"yes"}', '{"pwned":true}'] as $body) { - $fetch = new DetectionFetch(body: $body); - - try { - $this->adapter($fetch)->isPwned(self::PASSWORD); - $this->fail('Expected an unreadable answer to surface: ' . $body); - } catch (Exception $e) { - $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); - } - } - } - public function testTheDsnDescribesWhereAndHowToConnect(): void { $cases = [ @@ -128,15 +87,63 @@ final class AppwriteTest extends TestCase foreach ($cases as $dsn => $expected) { $fetch = new DetectionFetch(body: '{"leaked":false}'); - (new Appwrite(new DSN($dsn), new Client($fetch)))->isPwned(self::PASSWORD); + (new Appwrite([], new DSN($dsn), new Client($fetch)))->isValid(self::PASSWORD); $this->assertSame($expected, $fetch->requests[0]['url'], $dsn); } } - private function adapter(DetectionFetch $fetch): Appwrite + public function testUnreachableServiceIsReported(): void { - return new Appwrite(new DSN(self::DSN), new Client($fetch)); + $fetch = new DetectionFetch(failure: new \RuntimeException('connection refused')); + + try { + $this->validator($fetch)->isValid(self::PASSWORD); + $this->fail('Expected the unreachable service to surface'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + + public function testRejectedTokenIsReported(): void + { + // The service answers 400 when it cannot decode the token + $fetch = new DetectionFetch(statusCode: 400, body: '{"message":"Failed to verify JWT."}'); + + $this->expectException(Exception::class); + + $this->validator($fetch)->isValid(self::PASSWORD); + } + + public function testDetectorFailureIsReported(): void + { + $fetch = new DetectionFetch(statusCode: 500, body: ''); + + $this->expectException(Exception::class); + + $this->validator($fetch)->isValid(self::PASSWORD); + } + + /** + * An answer the validator cannot read must never pass as a clean password. + */ + public function testUnreadableAnswerIsReported(): void + { + foreach (['', 'not json', '{}', '{"leaked":"yes"}', '{"pwned":true}'] as $body) { + $fetch = new DetectionFetch(body: $body); + + try { + $this->validator($fetch)->isValid(self::PASSWORD); + $this->fail('Expected an unreadable answer to surface: ' . $body); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + } + + private function validator(DetectionFetch $fetch): Appwrite + { + return new Appwrite([], new DSN(self::DSN), new Client($fetch)); } } diff --git a/tests/unit/Auth/Pwned/HIBPTest.php b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php similarity index 68% rename from tests/unit/Auth/Pwned/HIBPTest.php rename to tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php index 9c3a55ce3b..4b5e70ec52 100644 --- a/tests/unit/Auth/Pwned/HIBPTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace Tests\Unit\Auth\Pwned; +namespace Tests\Unit\Auth\Validator\PasswordPwned; -use Appwrite\Auth\Pwned\HIBP; +use Appwrite\Auth\Validator\PasswordPwned\HIBP; use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; use Utopia\Cache\Adapter\Memory; @@ -19,46 +19,46 @@ final class HIBPTest extends TestCase private const LEAKED = 'Password123!'; private const ENDPOINT = 'https://breaches.test/range'; - public function testLeakedPasswordIsReported(): void + public function testLeakedPasswordIsRejected(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); - $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); } - public function testCleanPasswordIsNotReported(): void + public function testCleanPasswordIsAccepted(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); - $this->assertFalse($this->adapter($fetch)->isPwned('never-leaked-' . \uniqid())); + $this->assertTrue($this->validator($fetch)->isValid('never-leaked-' . \uniqid())); } - public function testAnySingleBreachCounts(): void + public function testAnySingleBreachIsEnough(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 1])); - $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); } public function testPaddedEntryWithZeroCountIsNotABreach(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 0])); - $this->assertFalse($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertTrue($this->validator($fetch)->isValid(self::LEAKED)); } public function testSuffixComparisonIgnoresCase(): void { $fetch = new RangeFetch(body: \strtolower($this->range([self::LEAKED => 3]))); - $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); } public function testOnlyTheHashPrefixLeavesTheServer(): void { $fetch = new RangeFetch(body: ''); - $this->adapter($fetch)->isPwned(self::LEAKED); + $this->validator($fetch)->isValid(self::LEAKED); $this->assertCount(1, $fetch->urls); @@ -74,13 +74,21 @@ final class HIBPTest extends TestCase $this->assertStringEndsWith(\substr($hash, 0, 5), $url); } + public function testDisabledPolicyNeverAsksTheService(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); + + $this->assertTrue((new HIBP(['enabled' => false], null, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); + $this->assertCount(0, $fetch->urls); + } + public function testRangeIsCachedPerPrefix(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - $this->assertTrue((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isPwned(self::LEAKED)); - $this->assertTrue((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isPwned(self::LEAKED)); + $this->assertFalse((new HIBP([], $cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); + $this->assertFalse((new HIBP([], $cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); $this->assertCount(1, $fetch->urls); } @@ -90,8 +98,8 @@ final class HIBPTest extends TestCase $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - (new HIBP($cache, new Client($fetch), 'https://one.test/range'))->isPwned(self::LEAKED); - (new HIBP($cache, new Client($fetch), 'https://two.test/range'))->isPwned(self::LEAKED); + (new HIBP([], $cache, new Client($fetch), 'https://one.test/range'))->isValid(self::LEAKED); + (new HIBP([], $cache, new Client($fetch), 'https://two.test/range'))->isValid(self::LEAKED); $this->assertCount(2, $fetch->urls); } @@ -100,8 +108,8 @@ final class HIBPTest extends TestCase { $fetch = new RangeFetch(body: ''); - (new HIBP(null, new Client($fetch), 'https://server.test/range'))->isPwned(self::LEAKED); - (new HIBP(null, new Client($fetch), 'https://other.test/range/'))->isPwned(self::LEAKED); + (new HIBP([], null, new Client($fetch), 'https://server.test/range'))->isValid(self::LEAKED); + (new HIBP([], null, new Client($fetch), 'https://other.test/range/'))->isValid(self::LEAKED); $this->assertStringStartsWith('https://server.test/range/', $fetch->urls[0]); $this->assertStringStartsWith('https://other.test/range/', $fetch->urls[1]); @@ -112,7 +120,7 @@ final class HIBPTest extends TestCase $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); try { - $this->adapter($fetch)->isPwned(self::LEAKED); + $this->validator($fetch)->isValid(self::LEAKED); $this->fail('Expected the unreachable service to surface'); } catch (Exception $e) { $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); @@ -125,17 +133,17 @@ final class HIBPTest extends TestCase $this->expectException(Exception::class); - $this->adapter($fetch)->isPwned(self::LEAKED); + $this->validator($fetch)->isValid(self::LEAKED); } public function testFailedLookupIsNotCached(): void { $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); - $adapter = new HIBP(new Cache(new Memory()), new Client($fetch), self::ENDPOINT); + $validator = new HIBP([], new Cache(new Memory()), new Client($fetch), self::ENDPOINT); foreach ([1, 2] as $attempt) { try { - $adapter->isPwned(self::LEAKED); + $validator->isValid(self::LEAKED); } catch (Exception) { // The lookup failed, which is the point; it must be retried rather than remembered } @@ -144,9 +152,9 @@ final class HIBPTest extends TestCase $this->assertCount(2, $fetch->urls); } - private function adapter(RangeFetch $fetch): HIBP + private function validator(RangeFetch $fetch): HIBP { - return new HIBP(null, new Client($fetch), self::ENDPOINT); + return new HIBP([], null, new Client($fetch), self::ENDPOINT); } /** @@ -169,7 +177,7 @@ final class HIBPTest extends TestCase final class RangeFetch implements Adapter { - /** @var array URLs the adapter asked the breach service for */ + /** @var array URLs the validator asked the breach service for */ public array $urls = []; public function __construct( diff --git a/tests/unit/Auth/Validator/PasswordPwned/MockTest.php b/tests/unit/Auth/Validator/PasswordPwned/MockTest.php new file mode 100644 index 0000000000..efa712ce5e --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwned/MockTest.php @@ -0,0 +1,38 @@ +assertFalse($validator->isValid($password), $password); + } + } + + public function testAnythingElseIsAccepted(): void + { + $validator = new Mock(); + + $this->assertTrue($validator->isValid('some-other-password')); + } + + public function testMatchingIsExact(): void + { + $validator = new Mock(); + $fixture = Mock::BREACHED[0]; + + // A password that merely resembles a fixture is not breached + $this->assertTrue($validator->isValid(\strtoupper($fixture))); + $this->assertTrue($validator->isValid($fixture . '!')); + $this->assertTrue($validator->isValid(\substr($fixture, 1))); + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index 79360c602a..5dfbdcc133 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -4,18 +4,20 @@ declare(strict_types=1); namespace Tests\Unit\Auth\Validator; -use Appwrite\Auth\Pwned; -use Appwrite\Auth\Validator\PasswordPwned; -use Appwrite\Extend\Exception; +use Appwrite\Auth\Validator\PasswordPwned\Mock; use PHPUnit\Framework\TestCase; +/** + * The policy decisions every breach validator shares, exercised through the one + * subclass that needs no service behind it. + */ final class PasswordPwnedTest extends TestCase { - private const PASSWORD = 'Password123!'; + private const BREACHED = Mock::BREACHED[0]; public function testEnabledByDefaultWithoutSessionChecks(): void { - $validator = new PasswordPwned(new FakePwned()); + $validator = new Mock(); $this->assertTrue($validator->isEnabled()); $this->assertFalse($validator->checksSessions()); @@ -24,7 +26,7 @@ final class PasswordPwnedTest extends TestCase public function testPolicyFlags(): void { - $validator = new PasswordPwned(new FakePwned(), ['enabled' => true, 'sessions' => true, 'users' => true]); + $validator = new Mock(['enabled' => true, 'sessions' => true, 'users' => true]); $this->assertTrue($validator->isEnabled()); $this->assertTrue($validator->checksSessions()); @@ -33,86 +35,38 @@ final class PasswordPwnedTest extends TestCase public function testSessionChecksNeedAnEnabledPolicy(): void { - $validator = new PasswordPwned(new FakePwned(), ['enabled' => false, 'sessions' => true, 'users' => true]); + $validator = new Mock(['enabled' => false, 'sessions' => true, 'users' => true]); $this->assertFalse($validator->checksSessions()); } - public function testDisabledPolicyNeverAsksTheAdapter(): void - { - $adapter = new FakePwned(pwned: true); - $validator = new PasswordPwned($adapter, ['enabled' => false]); - - $this->assertNull($validator->check(self::PASSWORD)); - $this->assertTrue($validator->isValid(self::PASSWORD)); - $this->assertSame(0, $adapter->calls); - } - - public function testCheckReportsWhatTheAdapterFound(): void - { - $this->assertTrue((new PasswordPwned(new FakePwned(pwned: true)))->check(self::PASSWORD)); - $this->assertFalse((new PasswordPwned(new FakePwned(pwned: false)))->check(self::PASSWORD)); - } - public function testBreachedPasswordIsInvalid(): void { - $this->assertFalse((new PasswordPwned(new FakePwned(pwned: true)))->isValid(self::PASSWORD)); - $this->assertTrue((new PasswordPwned(new FakePwned(pwned: false)))->isValid(self::PASSWORD)); + $validator = new Mock(); + + $this->assertFalse($validator->isValid(self::BREACHED)); + $this->assertTrue($validator->isValid('a-password-nobody-leaked')); } - public function testAdapterFailureSurfaces(): void + public function testDisabledPolicyAcceptsEverything(): void { - $adapter = new FakePwned(failure: new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE)); - $validator = new PasswordPwned($adapter); + $validator = new Mock(['enabled' => false]); - $this->expectException(Exception::class); - - $validator->isValid(self::PASSWORD); + $this->assertTrue($validator->isValid(self::BREACHED)); } public function testBasePasswordRulesStillApply(): void { - $adapter = new FakePwned(pwned: false); - $validator = new PasswordPwned($adapter); + $validator = new Mock(); $this->assertFalse($validator->isValid('short')); $this->assertFalse($validator->isValid(\str_repeat('p', 257))); $this->assertFalse($validator->isValid('')); - $this->assertSame(0, $adapter->calls); } - public function testAllowEmptySkipsTheLookup(): void + public function testAllowEmptyAcceptsAnEmptyPassword(): void { - $adapter = new FakePwned(pwned: true); - $validator = new PasswordPwned($adapter, [], allowEmpty: true); - - $this->assertTrue($validator->isValid('')); - $this->assertSame(0, $adapter->calls); - } -} - -final class FakePwned extends Pwned -{ - public int $calls = 0; - - public function __construct(private bool $pwned = false, private ?\Throwable $failure = null) - { - parent::__construct('https://breaches.test'); - } - - public function getName(): string - { - return 'fake'; - } - - public function isPwned(string $password): bool - { - $this->calls++; - - if ($this->failure !== null) { - throw $this->failure; - } - - return $this->pwned; + $this->assertTrue((new Mock([], allowEmpty: true))->isValid('')); + $this->assertFalse((new Mock([], allowEmpty: true))->isValid(self::BREACHED)); } } From dfee18d6e36be1697c3d2141960c59e73307d74c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 16:01:42 +0200 Subject: [PATCH 22/38] refactor(auth): let the call site read the pwned policy Drops `isEnabled()`, `checksSessions()` and `blocksUsers()`. Each call site now reads `auths.passwordPwned` from the project itself, the way the personal data and history checks already read theirs, and repeats the defaults rather than sharing them. The validator no longer carries policy at all, so it takes no policy argument and the request resource no longer depends on the project. What is left is a validator that answers one question: has this password been exposed in a breach. Co-Authored-By: Claude Opus 5 (1M context) --- app/controllers/api/account.php | 26 +++++--- app/init/resources/request.php | 12 ++-- src/Appwrite/Auth/Validator/PasswordPwned.php | 59 ++----------------- .../Auth/Validator/PasswordPwned/Appwrite.php | 7 +-- .../Auth/Validator/PasswordPwned/HIBP.php | 7 +-- .../Modules/Users/Http/Users/Create.php | 2 +- .../Users/Http/Users/Password/Update.php | 2 +- .../Validator/PasswordPwned/AppwriteTest.php | 12 +--- .../Auth/Validator/PasswordPwned/HIBPTest.php | 24 +++----- .../unit/Auth/Validator/PasswordPwnedTest.php | 38 +----------- 10 files changed, 47 insertions(+), 142 deletions(-) diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index e665d9cb43..0eab71cbd8 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -364,7 +364,9 @@ Http::post('/v1/account') } // null when the policy did not look, false when it looked and found nothing - $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -1049,7 +1051,9 @@ Http::post('/v1/account/sessions/email') $authorization->addRole(Role::user($user->getId())->toString()); - if ($pwnedPasswords->checksSessions()) { + $pwnedPolicy = $project->getAttribute('auths', [])['passwordPwned'] ?? []; + + if (($pwnedPolicy['enabled'] ?? true) && ($pwnedPolicy['sessions'] ?? false)) { // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in $passwordPwned = !$pwnedPasswords->isValid($password); @@ -1060,7 +1064,7 @@ Http::post('/v1/account/sessions/email') ])); } - if ($passwordPwned && $pwnedPasswords->blocksUsers()) { + if ($passwordPwned && ($pwnedPolicy['users'] ?? false)) { throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); } } @@ -3511,7 +3515,9 @@ Http::patch('/v1/account/password') } // null when the policy did not look, false when it looked and found nothing - $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3615,7 +3621,9 @@ Http::patch('/v1/account/email') } } - $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3789,7 +3797,9 @@ Http::patch('/v1/account/phone') } } - $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -4237,7 +4247,9 @@ Http::put('/v1/account/recovery') } // null when the policy did not look, false when it looked and found nothing - $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } diff --git a/app/init/resources/request.php b/app/init/resources/request.php index ca3b559721..21a02cd696 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -677,21 +677,19 @@ return function (Container $context): void { return; }, ['user', 'store', 'proofForToken']); - $context->set('pwnedPasswords', function (Document $project, Cache $cache) { + $context->set('pwnedPasswords', function (Cache $cache) { $dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'hibp://localhost')); - $policy = $project->getAttribute('auths', [])['passwordPwned'] ?? []; - return match ($dsn->getScheme()) { - 'hibp' => new PasswordPwnedHIBP($policy, $cache), - 'appwrite' => new PasswordPwnedAppwrite($policy, $dsn), + 'hibp' => new PasswordPwnedHIBP($cache), + 'appwrite' => new PasswordPwnedAppwrite($dsn), // Reports almost every password as safe, so it must never be reachable on a real server 'mock' => Http::isProduction() ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach validator cannot be used in production.') - : new PasswordPwnedMock($policy), + : new PasswordPwnedMock(), default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_DSN scheme: ' . $dsn->getScheme()), }; - }, ['project', 'cache']); + }, ['cache']); $context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) { if ($project->isEmpty() || $project->getId() === 'console') { diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index 649d21948d..225c38102d 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -6,59 +6,19 @@ use Appwrite\Extend\Exception; use Utopia\Fetch\Client; /** - * Validates a password against the project's `password-pwned` policy. + * Validates that a password has not been exposed in a known data breach. * - * Subclasses differ in who answers the question and in what leaves the server, - * so read the one you are configuring. `_APP_PWNED_PASSWORDS_DSN` picks it, and - * the DSN scheme matches the subclass. + * Whether to ask at all is the caller's decision, read from the project's + * `passwordPwned` policy, the same way the personal data and history checks + * work. Subclasses differ in who answers the question and in what leaves the + * server, so read the one you are configuring. `_APP_PWNED_PASSWORDS_DSN` picks + * it, and the DSN scheme matches the subclass. */ abstract class PasswordPwned extends Password { private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds - protected bool $enabled; - protected bool $sessions; - protected bool $users; - - /** - * @param array $policy the project's `passwordPwned` auth settings - */ - public function __construct(array $policy = [], bool $allowEmpty = false) - { - parent::__construct($allowEmpty); - - $this->enabled = (bool) ($policy['enabled'] ?? true); - $this->sessions = (bool) ($policy['sessions'] ?? false); - $this->users = (bool) ($policy['users'] ?? false); - } - - /** - * Whether the project enforces the policy at all. - */ - public function isEnabled(): bool - { - return $this->enabled; - } - - /** - * Whether passwords are checked when a session is created. - */ - public function checksSessions(): bool - { - return $this->enabled && $this->sessions; - } - - /** - * Whether users signing in with a breached password are blocked until they reset it. - * - * Only takes effect when sessions are checked. - */ - public function blocksUsers(): bool - { - return $this->users; - } - /** * Get Description. * @@ -74,9 +34,6 @@ abstract class PasswordPwned extends Password /** * Is valid. * - * A password the policy did not look at is valid, so callers that need to - * tell "clean" from "never checked" ask `isEnabled()` first. - * * @param mixed $value * * @return bool @@ -92,10 +49,6 @@ abstract class PasswordPwned extends Password return true; } - if (!$this->enabled) { - return true; - } - return !$this->isPwned($value); } diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php index a2199a50d5..b6a103e8c4 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -32,13 +32,8 @@ class Appwrite extends PasswordPwned protected string $secret; protected Client $client; - /** - * @param array $policy - */ - public function __construct(array $policy, DSN $dsn, ?Client $client = null) + public function __construct(DSN $dsn, ?Client $client = null) { - parent::__construct($policy); - $scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http'; $port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : ''; $path = $dsn->getPath(); diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php index 086c5a5f6f..e1fa1ffe9a 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php @@ -27,13 +27,8 @@ class HIBP extends PasswordPwned protected Client $client; protected string $endpoint; - /** - * @param array $policy - */ - public function __construct(array $policy = [], ?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT) + public function __construct(?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT) { - parent::__construct($policy); - $this->cache = $cache; $this->client = $this->client($client); $this->endpoint = \rtrim($endpoint, '/'); diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php index 61c46bf062..54dd362269 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php @@ -74,7 +74,7 @@ class Create extends Base public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords): void { - $passwordPwned = empty($password) || !$pwnedPasswords->isEnabled() + $passwordPwned = empty($password) || !($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) ? null : !$pwnedPasswords->isValid($password); if ($passwordPwned) { diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index b39fdc6a82..2efba854a0 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -86,7 +86,7 @@ class Update extends Action } } - $passwordPwned = \strlen($password) === 0 || !$pwnedPasswords->isEnabled() + $passwordPwned = \strlen($password) === 0 || !($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) ? null : !$pwnedPasswords->isValid($password); if ($passwordPwned) { diff --git a/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php index 43ad793fd2..55f8447469 100644 --- a/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php @@ -34,14 +34,6 @@ final class AppwriteTest extends TestCase $this->assertTrue($this->validator($fetch)->isValid(self::PASSWORD)); } - public function testDisabledPolicyNeverAsksTheService(): void - { - $fetch = new DetectionFetch(body: '{"leaked":true}'); - - $this->assertTrue((new Appwrite(['enabled' => false], new DSN(self::DSN), new Client($fetch)))->isValid(self::PASSWORD)); - $this->assertCount(0, $fetch->requests); - } - public function testThePasswordTravelsInAJwtTheServiceCanOpen(): void { $fetch = new DetectionFetch(body: '{"leaked":false}'); @@ -87,7 +79,7 @@ final class AppwriteTest extends TestCase foreach ($cases as $dsn => $expected) { $fetch = new DetectionFetch(body: '{"leaked":false}'); - (new Appwrite([], new DSN($dsn), new Client($fetch)))->isValid(self::PASSWORD); + (new Appwrite(new DSN($dsn), new Client($fetch)))->isValid(self::PASSWORD); $this->assertSame($expected, $fetch->requests[0]['url'], $dsn); } @@ -143,7 +135,7 @@ final class AppwriteTest extends TestCase private function validator(DetectionFetch $fetch): Appwrite { - return new Appwrite([], new DSN(self::DSN), new Client($fetch)); + return new Appwrite(new DSN(self::DSN), new Client($fetch)); } } diff --git a/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php index 4b5e70ec52..d14636122f 100644 --- a/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php @@ -74,21 +74,13 @@ final class HIBPTest extends TestCase $this->assertStringEndsWith(\substr($hash, 0, 5), $url); } - public function testDisabledPolicyNeverAsksTheService(): void - { - $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); - - $this->assertTrue((new HIBP(['enabled' => false], null, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); - $this->assertCount(0, $fetch->urls); - } - public function testRangeIsCachedPerPrefix(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - $this->assertFalse((new HIBP([], $cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); - $this->assertFalse((new HIBP([], $cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); + $this->assertFalse((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); + $this->assertFalse((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); $this->assertCount(1, $fetch->urls); } @@ -98,8 +90,8 @@ final class HIBPTest extends TestCase $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - (new HIBP([], $cache, new Client($fetch), 'https://one.test/range'))->isValid(self::LEAKED); - (new HIBP([], $cache, new Client($fetch), 'https://two.test/range'))->isValid(self::LEAKED); + (new HIBP($cache, new Client($fetch), 'https://one.test/range'))->isValid(self::LEAKED); + (new HIBP($cache, new Client($fetch), 'https://two.test/range'))->isValid(self::LEAKED); $this->assertCount(2, $fetch->urls); } @@ -108,8 +100,8 @@ final class HIBPTest extends TestCase { $fetch = new RangeFetch(body: ''); - (new HIBP([], null, new Client($fetch), 'https://server.test/range'))->isValid(self::LEAKED); - (new HIBP([], null, new Client($fetch), 'https://other.test/range/'))->isValid(self::LEAKED); + (new HIBP(null, new Client($fetch), 'https://server.test/range'))->isValid(self::LEAKED); + (new HIBP(null, new Client($fetch), 'https://other.test/range/'))->isValid(self::LEAKED); $this->assertStringStartsWith('https://server.test/range/', $fetch->urls[0]); $this->assertStringStartsWith('https://other.test/range/', $fetch->urls[1]); @@ -139,7 +131,7 @@ final class HIBPTest extends TestCase public function testFailedLookupIsNotCached(): void { $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); - $validator = new HIBP([], new Cache(new Memory()), new Client($fetch), self::ENDPOINT); + $validator = new HIBP(new Cache(new Memory()), new Client($fetch), self::ENDPOINT); foreach ([1, 2] as $attempt) { try { @@ -154,7 +146,7 @@ final class HIBPTest extends TestCase private function validator(RangeFetch $fetch): HIBP { - return new HIBP([], null, new Client($fetch), self::ENDPOINT); + return new HIBP(null, new Client($fetch), self::ENDPOINT); } /** diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index 5dfbdcc133..b5e95ef59f 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -8,38 +8,13 @@ use Appwrite\Auth\Validator\PasswordPwned\Mock; use PHPUnit\Framework\TestCase; /** - * The policy decisions every breach validator shares, exercised through the one + * The behaviour every breach validator shares, exercised through the one * subclass that needs no service behind it. */ final class PasswordPwnedTest extends TestCase { private const BREACHED = Mock::BREACHED[0]; - public function testEnabledByDefaultWithoutSessionChecks(): void - { - $validator = new Mock(); - - $this->assertTrue($validator->isEnabled()); - $this->assertFalse($validator->checksSessions()); - $this->assertFalse($validator->blocksUsers()); - } - - public function testPolicyFlags(): void - { - $validator = new Mock(['enabled' => true, 'sessions' => true, 'users' => true]); - - $this->assertTrue($validator->isEnabled()); - $this->assertTrue($validator->checksSessions()); - $this->assertTrue($validator->blocksUsers()); - } - - public function testSessionChecksNeedAnEnabledPolicy(): void - { - $validator = new Mock(['enabled' => false, 'sessions' => true, 'users' => true]); - - $this->assertFalse($validator->checksSessions()); - } - public function testBreachedPasswordIsInvalid(): void { $validator = new Mock(); @@ -48,13 +23,6 @@ final class PasswordPwnedTest extends TestCase $this->assertTrue($validator->isValid('a-password-nobody-leaked')); } - public function testDisabledPolicyAcceptsEverything(): void - { - $validator = new Mock(['enabled' => false]); - - $this->assertTrue($validator->isValid(self::BREACHED)); - } - public function testBasePasswordRulesStillApply(): void { $validator = new Mock(); @@ -66,7 +34,7 @@ final class PasswordPwnedTest extends TestCase public function testAllowEmptyAcceptsAnEmptyPassword(): void { - $this->assertTrue((new Mock([], allowEmpty: true))->isValid('')); - $this->assertFalse((new Mock([], allowEmpty: true))->isValid(self::BREACHED)); + $this->assertTrue((new Mock(allowEmpty: true))->isValid('')); + $this->assertFalse((new Mock(allowEmpty: true))->isValid(self::BREACHED)); } } From 920938917853718e9926ff4ec4ea6dd33b5435c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 16:06:33 +0200 Subject: [PATCH 23/38] refactor(auth): inline the client and unavailable helpers Drops `client()` and `unavailable()` from the abstract validator. Each HTTP subclass builds its own client and raises `GENERAL_PWNED_PASSWORDS_UNAVAILABLE` where the lookup fails, repeating the timeouts rather than sharing them. What is left on the abstract is the validator contract itself: a description, `isValid()`, and the `isPwned()` question subclasses answer. The mock subclass no longer inherits HTTP concerns it never used. Co-Authored-By: Claude Opus 5 (1M context) --- src/Appwrite/Auth/Validator/PasswordPwned.php | 29 ++----------------- .../Auth/Validator/PasswordPwned/Appwrite.php | 15 +++++++--- .../Auth/Validator/PasswordPwned/HIBP.php | 14 +++++++-- 3 files changed, 25 insertions(+), 33 deletions(-) diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index 225c38102d..bdeb53efa8 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -3,7 +3,6 @@ namespace Appwrite\Auth\Validator; use Appwrite\Extend\Exception; -use Utopia\Fetch\Client; /** * Validates that a password has not been exposed in a known data breach. @@ -16,9 +15,6 @@ use Utopia\Fetch\Client; */ abstract class PasswordPwned extends Password { - private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds - private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds - /** * Get Description. * @@ -79,29 +75,10 @@ abstract class PasswordPwned extends Password /** * Whether the password appears in a known data breach. * + * A password is never silently accepted when the lookup did not happen, so + * an unreachable service raises `GENERAL_PWNED_PASSWORDS_UNAVAILABLE`. + * * @throws Exception when the breach service cannot be reached or answers with nonsense */ abstract protected function isPwned(string $password): bool; - - /** - * A client with the timeouts a password check can afford to wait. - */ - protected function client(?Client $client = null): Client - { - return $client ?? (new Client()) - ->setConnectTimeout(self::CONNECT_TIMEOUT) - ->setTimeout(self::REQUEST_TIMEOUT) - ->setAllowRedirects(false) - ->setUserAgent('Appwrite'); - } - - /** - * A password is never silently accepted when the lookup did not happen. - * - * @throws Exception - */ - protected function unavailable(): never - { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } } diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php index b6a103e8c4..2035d8fff3 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -4,6 +4,7 @@ namespace Appwrite\Auth\Validator\PasswordPwned; use Ahc\Jwt\JWT; use Appwrite\Auth\Validator\PasswordPwned; +use Appwrite\Extend\Exception; use Utopia\DSN\DSN; use Utopia\Fetch\Client; @@ -23,6 +24,8 @@ use Utopia\Fetch\Client; class Appwrite extends PasswordPwned { private const PATH = 'v1/detection'; + private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds + private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds // The service decodes with the same window private const TOKEN_EXPIRY = 900; // seconds @@ -40,7 +43,11 @@ class Appwrite extends PasswordPwned $this->endpoint = $scheme . '://' . $dsn->getHost() . $port . '/' . ($path === '' || $path === null ? self::PATH : $path); $this->secret = $dsn->getUser() ?? ''; - $this->client = $this->client($client); + $this->client = $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); } protected function isPwned(string $password): bool @@ -54,17 +61,17 @@ class Appwrite extends PasswordPwned 'password' => $jwt->encode(['password' => $password]), ]); } catch (\Throwable) { - $this->unavailable(); + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } if ($response->getStatusCode() !== 200) { - $this->unavailable(); + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } $body = \json_decode($response->text(), true); if (!\is_array($body) || !\is_bool($body['leaked'] ?? null)) { - $this->unavailable(); + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } return $body['leaked']; diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php index e1fa1ffe9a..b2cc224b24 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php @@ -3,6 +3,7 @@ namespace Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PasswordPwned; +use Appwrite\Extend\Exception; use Utopia\Cache\Cache; use Utopia\Fetch\Client; @@ -22,6 +23,8 @@ class HIBP extends PasswordPwned public const CACHE_TTL = 3600; // seconds private const PREFIX_LENGTH = 5; + private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds + private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds protected ?Cache $cache; protected Client $client; @@ -30,7 +33,11 @@ class HIBP extends PasswordPwned public function __construct(?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT) { $this->cache = $cache; - $this->client = $this->client($client); + $this->client = $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); $this->endpoint = \rtrim($endpoint, '/'); } @@ -48,6 +55,7 @@ class HIBP extends PasswordPwned * Breach counts for every known hash sharing the prefix, from cache or the service. * * @return array hash suffix => breach count + * @throws Exception when the service cannot be reached */ private function range(string $prefix): array { @@ -65,11 +73,11 @@ class HIBP extends PasswordPwned ->addHeader('Add-Padding', 'true') ->fetch($this->endpoint . '/' . $prefix); } catch (\Throwable) { - $this->unavailable(); + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } if ($response->getStatusCode() !== 200) { - $this->unavailable(); + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches From 4b1246c012dc9cf5176d6f6a0c652d5e380e10c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 16:07:58 +0200 Subject: [PATCH 24/38] feat(auth): cache breach answers for every validator Moves the caching into the abstract validator as a `remember()` helper, so it is written once rather than per subclass, and gives the Appwrite validator the cache it was missing. Each subclass still chooses its own key, because what is worth remembering differs: Have I Been Pwned caches a whole range of hashes per prefix, the Appwrite service caches a single answer per password. Nothing is stored when the lookup throws, so an outage is retried rather than remembered. The Appwrite key is an HMAC of the password under the secret the service already shares, not a bare hash, so a cache dump cannot be cracked back into user passwords. Co-Authored-By: Claude Opus 5 (1M context) --- app/init/resources/request.php | 2 +- src/Appwrite/Auth/Validator/PasswordPwned.php | 35 +++++++++++ .../Auth/Validator/PasswordPwned/Appwrite.php | 47 ++++++++------ .../Auth/Validator/PasswordPwned/HIBP.php | 61 ++++++++----------- .../Validator/PasswordPwned/AppwriteTest.php | 56 ++++++++++++++++- 5 files changed, 143 insertions(+), 58 deletions(-) diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 21a02cd696..0d78198a0c 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -682,7 +682,7 @@ return function (Container $context): void { return match ($dsn->getScheme()) { 'hibp' => new PasswordPwnedHIBP($cache), - 'appwrite' => new PasswordPwnedAppwrite($dsn), + 'appwrite' => new PasswordPwnedAppwrite($dsn, $cache), // Reports almost every password as safe, so it must never be reachable on a real server 'mock' => Http::isProduction() ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach validator cannot be used in production.') diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index bdeb53efa8..fe6158a29b 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -3,6 +3,7 @@ namespace Appwrite\Auth\Validator; use Appwrite\Extend\Exception; +use Utopia\Cache\Cache; /** * Validates that a password has not been exposed in a known data breach. @@ -15,6 +16,13 @@ use Appwrite\Extend\Exception; */ abstract class PasswordPwned extends Password { + /** + * How long an answer from a breach service stays good for. + */ + protected const CACHE_TTL = 3600; // seconds + + protected ?Cache $cache = null; + /** * Get Description. * @@ -81,4 +89,31 @@ abstract class PasswordPwned extends Password * @throws Exception when the breach service cannot be reached or answers with nonsense */ abstract protected function isPwned(string $password): bool; + + /** + * Remembers what a breach service said, so the same question is not asked twice. + * + * Subclasses choose the key, because what is worth remembering differs: a + * whole range of hashes for one, a single answer for another. Nothing is + * stored when the lookup throws, so an outage is retried rather than + * remembered. + * + * @param callable(): array $resolve + * @return array + */ + protected function remember(string $key, callable $resolve): array + { + // A miss reads back as false, so an answer is always wrapped in an array + $cached = $this->cache?->load($key, static::CACHE_TTL); + + if (\is_array($cached)) { + return $cached; + } + + $answer = $resolve(); + + $this->cache?->save($key, $answer); + + return $answer; + } } diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php index 2035d8fff3..2006302a98 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -5,6 +5,7 @@ namespace Appwrite\Auth\Validator\PasswordPwned; use Ahc\Jwt\JWT; use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Extend\Exception; +use Utopia\Cache\Cache; use Utopia\DSN\DSN; use Utopia\Fetch\Client; @@ -35,8 +36,9 @@ class Appwrite extends PasswordPwned protected string $secret; protected Client $client; - public function __construct(DSN $dsn, ?Client $client = null) + public function __construct(DSN $dsn, ?Cache $cache = null, ?Client $client = null) { + $this->cache = $cache; $scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http'; $port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : ''; $path = $dsn->getPath(); @@ -52,28 +54,35 @@ class Appwrite extends PasswordPwned protected function isPwned(string $password): bool { - $jwt = new JWT($this->secret, 'HS256', self::TOKEN_EXPIRY, self::TOKEN_LEEWAY); + // Keyed with the secret the service shares, so the cache never holds a crackable password hash + $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . \hash_hmac('sha256', $password, $this->secret); - try { - $response = $this->client - ->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON) - ->fetch($this->endpoint, Client::METHOD_POST, [ - 'password' => $jwt->encode(['password' => $password]), - ]); - } catch (\Throwable) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } + $answer = $this->remember($key, function () use ($password) { + $jwt = new JWT($this->secret, 'HS256', self::TOKEN_EXPIRY, self::TOKEN_LEEWAY); - if ($response->getStatusCode() !== 200) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } + try { + $response = $this->client + ->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON) + ->fetch($this->endpoint, Client::METHOD_POST, [ + 'password' => $jwt->encode(['password' => $password]), + ]); + } catch (\Throwable) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } - $body = \json_decode($response->text(), true); + if ($response->getStatusCode() !== 200) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } - if (!\is_array($body) || !\is_bool($body['leaked'] ?? null)) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } + $body = \json_decode($response->text(), true); - return $body['leaked']; + if (!\is_array($body) || !\is_bool($body['leaked'] ?? null)) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + return ['leaked' => $body['leaked']]; + }); + + return (bool) ($answer['leaked'] ?? false); } } diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php index b2cc224b24..3527b3088f 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php @@ -20,13 +20,11 @@ use Utopia\Fetch\Client; class HIBP extends PasswordPwned { public const ENDPOINT = 'https://api.pwnedpasswords.com/range'; - public const CACHE_TTL = 3600; // seconds private const PREFIX_LENGTH = 5; private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds - protected ?Cache $cache; protected Client $client; protected string $endpoint; @@ -59,44 +57,35 @@ class HIBP extends PasswordPwned */ private function range(string $prefix): array { - $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix; - - if ($this->cache !== null) { - $cached = $this->cache->load($key, self::CACHE_TTL); - if (\is_array($cached)) { - return $cached; - } - } - - try { - $response = $this->client - ->addHeader('Add-Padding', 'true') - ->fetch($this->endpoint . '/' . $prefix); - } catch (\Throwable) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } - - if ($response->getStatusCode() !== 200) { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } - - // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches - $breaches = []; - foreach (\explode("\n", $response->text()) as $line) { - $line = \trim($line); - $separator = \strpos($line, ':'); - if ($line === '' || $separator === false) { - continue; + return $this->remember('pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix, function () use ($prefix) { + try { + $response = $this->client + ->addHeader('Add-Padding', 'true') + ->fetch($this->endpoint . '/' . $prefix); + } catch (\Throwable) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } - $count = (int) \substr($line, $separator + 1); - if ($count > 0) { - $breaches[\strtoupper(\substr($line, 0, $separator))] = $count; + if ($response->getStatusCode() !== 200) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } - } - $this->cache?->save($key, $breaches); + // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches + $breaches = []; + foreach (\explode("\n", $response->text()) as $line) { + $line = \trim($line); + $separator = \strpos($line, ':'); + if ($line === '' || $separator === false) { + continue; + } - return $breaches; + $count = (int) \substr($line, $separator + 1); + if ($count > 0) { + $breaches[\strtoupper(\substr($line, 0, $separator))] = $count; + } + } + + return $breaches; + }); } } diff --git a/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php index 55f8447469..96992c79db 100644 --- a/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php @@ -8,6 +8,8 @@ use Ahc\Jwt\JWT; use Appwrite\Auth\Validator\PasswordPwned\Appwrite; use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; +use Utopia\Cache\Adapter\Memory; +use Utopia\Cache\Cache; use Utopia\DSN\DSN; use Utopia\Fetch\Adapter; use Utopia\Fetch\Client; @@ -79,7 +81,7 @@ final class AppwriteTest extends TestCase foreach ($cases as $dsn => $expected) { $fetch = new DetectionFetch(body: '{"leaked":false}'); - (new Appwrite(new DSN($dsn), new Client($fetch)))->isValid(self::PASSWORD); + (new Appwrite(new DSN($dsn), null, new Client($fetch)))->isValid(self::PASSWORD); $this->assertSame($expected, $fetch->requests[0]['url'], $dsn); } @@ -133,9 +135,59 @@ final class AppwriteTest extends TestCase } } + public function testAnswersAreCached(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + $cache = new Cache(new Memory()); + + $this->assertFalse((new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)))->isValid(self::PASSWORD)); + $this->assertFalse((new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)))->isValid(self::PASSWORD)); + + $this->assertCount(1, $fetch->requests); + } + + public function testEachPasswordGetsItsOwnAnswer(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + $cache = new Cache(new Memory()); + $validator = new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)); + + $validator->isValid(self::PASSWORD); + $validator->isValid('a-completely-different-password'); + + $this->assertCount(2, $fetch->requests); + } + + public function testCacheIsScopedToEndpoint(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + $cache = new Cache(new Memory()); + + (new Appwrite(new DSN('appwrite://secret@one.test'), $cache, new Client($fetch)))->isValid(self::PASSWORD); + (new Appwrite(new DSN('appwrite://secret@two.test'), $cache, new Client($fetch)))->isValid(self::PASSWORD); + + $this->assertCount(2, $fetch->requests); + } + + public function testFailedLookupIsNotCached(): void + { + $fetch = new DetectionFetch(failure: new \RuntimeException('connection refused')); + $validator = new Appwrite(new DSN(self::DSN), new Cache(new Memory()), new Client($fetch)); + + foreach ([1, 2] as $attempt) { + try { + $validator->isValid(self::PASSWORD); + } catch (Exception) { + // The lookup failed, which is the point; it must be retried rather than remembered + } + } + + $this->assertCount(2, $fetch->requests); + } + private function validator(DetectionFetch $fetch): Appwrite { - return new Appwrite(new DSN(self::DSN), new Client($fetch)); + return new Appwrite(new DSN(self::DSN), null, new Client($fetch)); } } From b4669d6630ffe2aa203831ddef1a155ee3008d9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 16:29:31 +0200 Subject: [PATCH 25/38] fix(auth): initialise the password validator base in both subclasses `HIBP` and `Appwrite` declare constructors and never called the parent, so `Password::$allowEmpty` was never initialised and every `isValid()` call raised "Typed property must not be accessed before initialization". `Mock` declares no constructor, so it inherited the parent's and hid the problem from the tests that use it. Both now forward `$allowEmpty` to the parent, the way PasswordDictionary and PersonalData do. Co-Authored-By: Claude Opus 5 (1M context) --- src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php | 4 +++- src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php index 2006302a98..e7b95d04d4 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -36,8 +36,10 @@ class Appwrite extends PasswordPwned protected string $secret; protected Client $client; - public function __construct(DSN $dsn, ?Cache $cache = null, ?Client $client = null) + public function __construct(DSN $dsn, ?Cache $cache = null, ?Client $client = null, bool $allowEmpty = false) { + parent::__construct($allowEmpty); + $this->cache = $cache; $scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http'; $port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : ''; diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php index 3527b3088f..603b18866b 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php @@ -28,8 +28,10 @@ class HIBP extends PasswordPwned protected Client $client; protected string $endpoint; - public function __construct(?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT) + public function __construct(?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT, bool $allowEmpty = false) { + parent::__construct($allowEmpty); + $this->cache = $cache; $this->client = $client ?? (new Client()) ->setConnectTimeout(self::CONNECT_TIMEOUT) From 947dae804c9d0665d30945a6c01992ef175e305c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 16 Sep 2026 22:33:30 +0200 Subject: [PATCH 26/38] feat(auth): send the pwned service the password with a Bearer token appwrite-labs/pwned#6 rewrote the Appwrite Pwned service: it answers from its own copy of the Have I Been Pwned corpus and checks a shared secret sent as `Authorization: Bearer `, in place of the JWT it used to expect inside the body. The adapter now sends the password as it is in the JSON body, with the DSN's user part as the Bearer token. The answer is unchanged, `{"leaked": bool}`; every other status, a rejected secret (401), a password the service will not take (400) or a missing dataset (503), still surfaces as GENERAL_PWNED_PASSWORDS_UNAVAILABLE, so a lookup that did not happen never passes as a clean password. The unit test checks the body and headers that leave the adapter and the service's error objects; the variable description names the new secret. Co-Authored-By: Claude Fable 5.1 --- app/config/variables.php | 2 +- .../Auth/Validator/PasswordPwned/Appwrite.php | 26 ++++---- .../Validator/PasswordPwned/AppwriteTest.php | 64 ++++++++----------- 3 files changed, 39 insertions(+), 53 deletions(-) diff --git a/app/config/variables.php b/app/config/variables.php index 315b498a29..80c562aa2f 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -486,7 +486,7 @@ return [ ], [ 'name' => '_APP_PWNED_PASSWORDS_DSN', - 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter.\n\nExamples:\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which caches answers and can front a detector of your choice. It receives the whole password inside a JWT signed with `SECRET`, which must match the service's `APPWRITE_PWNED_JWT_SECRET`, so only point it at a service on your own network. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", + 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter.\n\nExamples:\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which answers from its own copy of the Have I Been Pwned corpus, so nothing about the password leaves your network. It receives the whole password, authenticated with `SECRET` as a Bearer token, which must match the service's `APPWRITE_PWNED_SECRET`, so only point it at a service on your own network or behind TLS. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", 'introduction' => 'TBD', 'default' => 'hibp://localhost', 'required' => false, diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php index e7b95d04d4..d9a758a0d1 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -2,7 +2,6 @@ namespace Appwrite\Auth\Validator\PasswordPwned; -use Ahc\Jwt\JWT; use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Extend\Exception; use Utopia\Cache\Cache; @@ -12,15 +11,15 @@ use Utopia\Fetch\Client; /** * Asks an Appwrite Pwned service, https://github.com/appwrite-labs/pwned. * - * The service answers for a whole password rather than a hash prefix, so unlike - * `HIBP` this sends the password itself. It travels inside a short-lived JWT - * signed with a secret the service shares, which is only safe on a network you - * control. In exchange the service caches answers and can front Have I Been - * Pwned or another detector without this server knowing which. + * The service answers from its own copy of the Have I Been Pwned corpus, for a + * whole password rather than a hash prefix, so unlike `HIBP` this sends the + * password itself. The request carries a secret the service shares as a + * Bearer token, which is only safe on a network you control or behind TLS. + * In exchange nothing about the password ever leaves that network. * * DSN: `appwrite://SECRET@HOST[:PORT][/PATH][?tls=true]`. The secret must match - * the service's `APPWRITE_PWNED_JWT_SECRET`, the path defaults to - * `v1/detection`, and the connection is plain HTTP unless `tls=true`. + * the service's `APPWRITE_PWNED_SECRET`, the path defaults to `v1/detection`, + * and the connection is plain HTTP unless `tls=true`. */ class Appwrite extends PasswordPwned { @@ -28,10 +27,6 @@ class Appwrite extends PasswordPwned private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds - // The service decodes with the same window - private const TOKEN_EXPIRY = 900; // seconds - private const TOKEN_LEEWAY = 10; // seconds - protected string $endpoint; protected string $secret; protected Client $client; @@ -60,18 +55,19 @@ class Appwrite extends PasswordPwned $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . \hash_hmac('sha256', $password, $this->secret); $answer = $this->remember($key, function () use ($password) { - $jwt = new JWT($this->secret, 'HS256', self::TOKEN_EXPIRY, self::TOKEN_LEEWAY); - try { $response = $this->client ->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON) + ->addHeader('authorization', 'Bearer ' . $this->secret) ->fetch($this->endpoint, Client::METHOD_POST, [ - 'password' => $jwt->encode(['password' => $password]), + 'password' => $password, ]); } catch (\Throwable) { throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } + // Anything else is the service's own error object: a rejected secret + // (401), a password it will not take (400) or a missing dataset (503) if ($response->getStatusCode() !== 200) { throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); } diff --git a/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php index 96992c79db..0d9c1cd194 100644 --- a/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php @@ -4,7 +4,6 @@ declare(strict_types=1); namespace Tests\Unit\Auth\Validator\PasswordPwned; -use Ahc\Jwt\JWT; use Appwrite\Auth\Validator\PasswordPwned\Appwrite; use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; @@ -36,7 +35,7 @@ final class AppwriteTest extends TestCase $this->assertTrue($this->validator($fetch)->isValid(self::PASSWORD)); } - public function testThePasswordTravelsInAJwtTheServiceCanOpen(): void + public function testThePasswordIsSentAsIsWithTheSharedSecretAsBearerToken(): void { $fetch = new DetectionFetch(body: '{"leaked":false}'); @@ -45,26 +44,12 @@ final class AppwriteTest extends TestCase $this->assertCount(1, $fetch->requests); $this->assertSame('POST', $fetch->requests[0]['method']); - $sent = \json_decode($fetch->requests[0]['body'], true); - $this->assertIsArray($sent); - $this->assertArrayHasKey('password', $sent); + // The service hashes the password itself, so it travels in the clear + $this->assertSame(['password' => self::PASSWORD], \json_decode($fetch->requests[0]['body'], true)); - // The service decodes with the shared secret, so it must round-trip - $decoded = (new JWT(self::SECRET, 'HS256', 900, 10))->decode($sent['password']); - $this->assertSame(self::PASSWORD, $decoded['password']); - } - - public function testATokenSignedWithAnotherSecretIsNotAccepted(): void - { - $fetch = new DetectionFetch(body: '{"leaked":false}'); - - $this->validator($fetch)->isValid(self::PASSWORD); - - $sent = \json_decode($fetch->requests[0]['body'], true); - - $this->expectException(\Throwable::class); - - (new JWT('a-different-secret', 'HS256', 900, 10))->decode($sent['password']); + $headers = \array_change_key_case($fetch->requests[0]['headers'], CASE_LOWER); + $this->assertSame('Bearer ' . self::SECRET, $headers['authorization'] ?? null); + $this->assertSame('application/json', $headers['content-type'] ?? null); } public function testTheDsnDescribesWhereAndHowToConnect(): void @@ -99,23 +84,28 @@ final class AppwriteTest extends TestCase } } - public function testRejectedTokenIsReported(): void + /** + * The service answers every failure with its own error object; none of them may pass as a clean password. + */ + public function testServiceErrorsAreReported(): void { - // The service answers 400 when it cannot decode the token - $fetch = new DetectionFetch(statusCode: 400, body: '{"message":"Failed to verify JWT."}'); + $errors = [ + 401 => '{"type":"general_unauthorized","message":"Missing or invalid Bearer token in the Authorization header.","code":401,"version":"0.2.0"}', + 400 => '{"type":"general_argument_invalid","message":"Invalid `password` param: Value must be a valid string and at least 1 chars and no longer than 256 chars","code":400,"version":"0.2.0"}', + 503 => '{"type":"dataset_unavailable","message":"The password dataset could not be read.","code":503,"version":"0.2.0"}', + 500 => '', + ]; - $this->expectException(Exception::class); + foreach ($errors as $statusCode => $body) { + $fetch = new DetectionFetch(statusCode: $statusCode, body: $body); - $this->validator($fetch)->isValid(self::PASSWORD); - } - - public function testDetectorFailureIsReported(): void - { - $fetch = new DetectionFetch(statusCode: 500, body: ''); - - $this->expectException(Exception::class); - - $this->validator($fetch)->isValid(self::PASSWORD); + try { + $this->validator($fetch)->isValid(self::PASSWORD); + $this->fail('Expected a ' . $statusCode . ' to surface'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType(), (string) $statusCode); + } + } } /** @@ -193,7 +183,7 @@ final class AppwriteTest extends TestCase final class DetectionFetch implements Adapter { - /** @var array */ + /** @var array}> */ public array $requests = []; public function __construct( @@ -211,7 +201,7 @@ final class DetectionFetch implements Adapter RequestOptions $options, ?callable $chunkCallback = null ): Response { - $this->requests[] = ['url' => $url, 'method' => $method, 'body' => $body]; + $this->requests[] = ['url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers]; if ($this->failure !== null) { throw $this->failure; From 40ead5aa9473f3de1e345d1abaddd7ce63837f3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 16 Sep 2026 22:40:12 +0200 Subject: [PATCH 27/38] feat(auth): add a `none` breach validator that reports every password safe `_APP_PWNED_PASSWORDS_DSN=none://localhost` picks a validator that never asks anyone and accepts every password, for a server that must not or cannot reach a breach service, such as an air-gapped installation. Unlike `mock`, it is allowed in production: it is an operator's explicit choice, not a test fixture. Projects can still switch the policy on, but it protects nothing until the server is pointed at a real service. Co-Authored-By: Claude Fable 5.1 --- app/config/variables.php | 2 +- app/init/resources/request.php | 3 ++ .../Auth/Validator/PasswordPwned/None.php | 23 ++++++++++++ .../Auth/Validator/PasswordPwned/NoneTest.php | 36 +++++++++++++++++++ 4 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 src/Appwrite/Auth/Validator/PasswordPwned/None.php create mode 100644 tests/unit/Auth/Validator/PasswordPwned/NoneTest.php diff --git a/app/config/variables.php b/app/config/variables.php index 80c562aa2f..93940e508a 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -486,7 +486,7 @@ return [ ], [ 'name' => '_APP_PWNED_PASSWORDS_DSN', - 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter.\n\nExamples:\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which answers from its own copy of the Have I Been Pwned corpus, so nothing about the password leaves your network. It receives the whole password, authenticated with `SECRET` as a Bearer token, which must match the service's `APPWRITE_PWNED_SECRET`, so only point it at a service on your own network or behind TLS. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", + 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter.\n\nExamples:\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which answers from its own copy of the Have I Been Pwned corpus, so nothing about the password leaves your network. It receives the whole password, authenticated with `SECRET` as a Bearer token, which must match the service's `APPWRITE_PWNED_SECRET`, so only point it at a service on your own network or behind TLS. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- None: `none://localhost` — reports every password as safe without asking anyone, for a server that must not or cannot reach a breach service. Projects can still enable the policy, but it protects nothing until you point the server at a real service\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", 'introduction' => 'TBD', 'default' => 'hibp://localhost', 'required' => false, diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 0d78198a0c..2410ffc6f3 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -6,6 +6,7 @@ use Appwrite\Auth\Key; use Appwrite\Auth\Validator\PasswordPwned\Appwrite as PasswordPwnedAppwrite; use Appwrite\Auth\Validator\PasswordPwned\HIBP as PasswordPwnedHIBP; use Appwrite\Auth\Validator\PasswordPwned\Mock as PasswordPwnedMock; +use Appwrite\Auth\Validator\PasswordPwned\None as PasswordPwnedNone; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; use Appwrite\Deployment\Deployments; @@ -683,6 +684,8 @@ return function (Container $context): void { return match ($dsn->getScheme()) { 'hibp' => new PasswordPwnedHIBP($cache), 'appwrite' => new PasswordPwnedAppwrite($dsn, $cache), + // Reports every password as safe by choice, for servers that cannot reach a breach service + 'none' => new PasswordPwnedNone(), // Reports almost every password as safe, so it must never be reachable on a real server 'mock' => Http::isProduction() ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach validator cannot be used in production.') diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/None.php b/src/Appwrite/Auth/Validator/PasswordPwned/None.php new file mode 100644 index 0000000000..2e5581b789 --- /dev/null +++ b/src/Appwrite/Auth/Validator/PasswordPwned/None.php @@ -0,0 +1,23 @@ +assertTrue($validator->isValid($password), $password); + } + } + + public function testBasePasswordRulesStillApply(): void + { + $validator = new None(); + + $this->assertFalse($validator->isValid('short')); + $this->assertFalse($validator->isValid(\str_repeat('p', 257))); + $this->assertFalse($validator->isValid('')); + } + + public function testAllowEmptyAcceptsAnEmptyPassword(): void + { + $this->assertTrue((new None(allowEmpty: true))->isValid('')); + } +} From ccf4aea37f6a655bc681c10358252130439f0eec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 16 Sep 2026 22:47:49 +0200 Subject: [PATCH 28/38] fix(auth): default the breach service DSN to none A server that has not been told which breach service to ask should ask nobody, rather than call the public Have I Been Pwned API on its own: `_APP_PWNED_PASSWORDS_DSN` now defaults to `none://localhost`. The policy stays enabled by default per project, but it protects nothing until an operator points the DSN at a service, which the variable description now says first. Co-Authored-By: Claude Fable 5.1 --- app/config/variables.php | 4 ++-- app/init/resources/request.php | 3 ++- src/Appwrite/Auth/Validator/PasswordPwned/None.php | 9 +++++---- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/app/config/variables.php b/app/config/variables.php index 93940e508a..e813b22f12 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -486,9 +486,9 @@ return [ ], [ 'name' => '_APP_PWNED_PASSWORDS_DSN', - 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter.\n\nExamples:\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which answers from its own copy of the Have I Been Pwned corpus, so nothing about the password leaves your network. It receives the whole password, authenticated with `SECRET` as a Bearer token, which must match the service's `APPWRITE_PWNED_SECRET`, so only point it at a service on your own network or behind TLS. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- None: `none://localhost` — reports every password as safe without asking anyone, for a server that must not or cannot reach a breach service. Projects can still enable the policy, but it protects nothing until you point the server at a real service\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", + 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter. Nothing is asked until you set it: the default, `none://localhost`, reports every password as safe, so the policy protects nothing until this points at a service.\n\nOptions:\n- None: `none://localhost` — the default. Reports every password as safe without asking anyone, for a server that must not or cannot reach a breach service\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which answers from its own copy of the Have I Been Pwned corpus, so nothing about the password leaves your network. It receives the whole password, authenticated with `SECRET` as a Bearer token, which must match the service's `APPWRITE_PWNED_SECRET`, so only point it at a service on your own network or behind TLS. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", 'introduction' => 'TBD', - 'default' => 'hibp://localhost', + 'default' => 'none://localhost', 'required' => false, 'question' => '', 'filter' => '' diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 2410ffc6f3..dfec05587c 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -679,7 +679,8 @@ return function (Container $context): void { }, ['user', 'store', 'proofForToken']); $context->set('pwnedPasswords', function (Cache $cache) { - $dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'hibp://localhost')); + // Nothing is asked until an operator points this at a service + $dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'none://localhost')); return match ($dsn->getScheme()) { 'hibp' => new PasswordPwnedHIBP($cache), diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/None.php b/src/Appwrite/Auth/Validator/PasswordPwned/None.php index 2e5581b789..95f57d4c39 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned/None.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/None.php @@ -7,10 +7,11 @@ use Appwrite\Auth\Validator\PasswordPwned; /** * Reports every password as safe, without asking anyone. * - * For a server that must not, or cannot, reach a breach service, such as an - * air-gapped installation. Projects can still switch the policy on, but it - * protects nothing until the server is pointed at a real service, and every - * checked user reads as clean. + * The default until an operator points `_APP_PWNED_PASSWORDS_DSN` at a + * service, and the right choice for a server that must not, or cannot, reach + * one, such as an air-gapped installation. Projects can still switch the + * policy on, but it protects nothing until the server is pointed at a real + * service, and every checked user reads as clean. * * DSN: `none://localhost`, no details are read. */ From 2f243adb42a713073409b26fe1c67b1d643c4739 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 11:18:11 +0530 Subject: [PATCH 29/38] chore: bump self-hosted console to 1.1.114 --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index e4717e6d8c..83077ddc03 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -265,7 +265,7 @@ services: max-file: "5" max-size: 10m container_name: appwrite-console - image: appwrite/new:1.1.107-self-hosted + image: appwrite/new:1.1.114-self-hosted restart: unless-stopped networks: - appwrite From d7448b4dd4dbeabb0e5c3ab4cc874a34491f7c38 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 14:09:14 +0530 Subject: [PATCH 30/38] chore(deps): require utopia-php/database ^7.3.11 --- composer.json | 2 +- composer.lock | 79 ++++++++++++++++++++++++++------------------------- 2 files changed, 41 insertions(+), 40 deletions(-) diff --git a/composer.json b/composer.json index db2629c0c1..a803e212cc 100644 --- a/composer.json +++ b/composer.json @@ -86,7 +86,7 @@ "utopia-php/compression": "0.1.*", "utopia-php/config": "1.*", "utopia-php/console": "^0.2", - "utopia-php/database": "^7.3.9", + "utopia-php/database": "^7.3.11", "utopia-php/detector": "0.2.*", "utopia-php/domains": "^4.2.1", "utopia-php/emails": "0.8.*", diff --git a/composer.lock b/composer.lock index fe6cd94318..03b99efe28 100644 --- a/composer.lock +++ b/composer.lock @@ -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": "1c490bf3e48c238620409ca6ec2dc175", + "content-hash": "c0c1b58b94677d51187d04d79843b0f3", "packages": [ { "name": "adhocore/jwt", @@ -218,23 +218,24 @@ }, { "name": "brick/math", - "version": "0.18.0", + "version": "1.0.0", "source": { "type": "git", "url": "https://github.com/brick/math.git", - "reference": "82944324d1c1bdb2c2618e89978d4e2ad78d69ad" + "reference": "2effe05d2177c451b86c6a073196a4034c02f211" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/brick/math/zipball/82944324d1c1bdb2c2618e89978d4e2ad78d69ad", - "reference": "82944324d1c1bdb2c2618e89978d4e2ad78d69ad", + "url": "https://api.github.com/repos/brick/math/zipball/2effe05d2177c451b86c6a073196a4034c02f211", + "reference": "2effe05d2177c451b86c6a073196a4034c02f211", "shasum": "" }, "require": { "php": "^8.2" }, "require-dev": { - "phpstan/phpstan": "2.1.22", + "phpstan/phpstan": "2.2.13", + "phpstan/phpstan-phpunit": "2.0.18", "phpunit/phpunit": "^11.5" }, "type": "library", @@ -265,7 +266,7 @@ ], "support": { "issues": "https://github.com/brick/math/issues", - "source": "https://github.com/brick/math/tree/0.18.0" + "source": "https://github.com/brick/math/tree/1.0.0" }, "funding": [ { @@ -273,7 +274,7 @@ "type": "github" } ], - "time": "2026-06-14T18:21:03+00:00" + "time": "2026-09-12T10:28:18+00:00" }, { "name": "chillerlan/php-qrcode", @@ -1993,20 +1994,20 @@ }, { "name": "ramsey/uuid", - "version": "4.9.3", + "version": "4.9.4", "source": { "type": "git", "url": "https://github.com/ramsey/uuid.git", - "reference": "1df15849d00943a67d677dc9cfd80795f038c9f8" + "reference": "75d73f48d02797c2c285a7e9f348fadc0102ffe2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ramsey/uuid/zipball/1df15849d00943a67d677dc9cfd80795f038c9f8", - "reference": "1df15849d00943a67d677dc9cfd80795f038c9f8", + "url": "https://api.github.com/repos/ramsey/uuid/zipball/75d73f48d02797c2c285a7e9f348fadc0102ffe2", + "reference": "75d73f48d02797c2c285a7e9f348fadc0102ffe2", "shasum": "" }, "require": { - "brick/math": ">=0.8.16 <=0.18", + "brick/math": "^0.8.16 || ^0.9 || ^0.10 || ^0.11 || ^0.12 || ^0.13 || ^0.14 || ^0.15 || ^0.16 || ^0.17 || ^0.18 || ^0.19 || ^0.20 || ^1.0", "php": "^8.0", "ramsey/collection": "^1.2 || ^2.0" }, @@ -2065,9 +2066,9 @@ ], "support": { "issues": "https://github.com/ramsey/uuid/issues", - "source": "https://github.com/ramsey/uuid/tree/4.9.3" + "source": "https://github.com/ramsey/uuid/tree/4.9.4" }, - "time": "2026-06-18T03:57:49+00:00" + "time": "2026-09-16T11:39:30+00:00" }, { "name": "spomky-labs/otphp", @@ -2984,16 +2985,16 @@ }, { "name": "utopia-php/cache", - "version": "5.1.0", + "version": "5.1.1", "source": { "type": "git", "url": "https://github.com/utopia-php/cache.git", - "reference": "62d8ac01d725bfe07474cc4960775904b1a5101e" + "reference": "35fee421ef64d6079abcf97b149b2413d71276c3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/cache/zipball/62d8ac01d725bfe07474cc4960775904b1a5101e", - "reference": "62d8ac01d725bfe07474cc4960775904b1a5101e", + "url": "https://api.github.com/repos/utopia-php/cache/zipball/35fee421ef64d6079abcf97b149b2413d71276c3", + "reference": "35fee421ef64d6079abcf97b149b2413d71276c3", "shasum": "" }, "require": { @@ -3038,9 +3039,9 @@ ], "support": { "issues": "https://github.com/utopia-php/cache/issues", - "source": "https://github.com/utopia-php/cache/tree/5.1.0" + "source": "https://github.com/utopia-php/cache/tree/5.1.1" }, - "time": "2026-09-16T14:41:42+00:00" + "time": "2026-09-16T20:55:55+00:00" }, { "name": "utopia-php/cdn", @@ -3106,16 +3107,16 @@ }, { "name": "utopia-php/circuit-breaker", - "version": "0.4.0", + "version": "0.4.1", "source": { "type": "git", "url": "https://github.com/utopia-php/circuit-breaker.git", - "reference": "c6d93c7ba9d895cf906360e000f74ff762d83e17" + "reference": "51c9b9b0de6754af4da6364da0f3a5d7e940ef2c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/circuit-breaker/zipball/c6d93c7ba9d895cf906360e000f74ff762d83e17", - "reference": "c6d93c7ba9d895cf906360e000f74ff762d83e17", + "url": "https://api.github.com/repos/utopia-php/circuit-breaker/zipball/51c9b9b0de6754af4da6364da0f3a5d7e940ef2c", + "reference": "51c9b9b0de6754af4da6364da0f3a5d7e940ef2c", "shasum": "" }, "require": { @@ -3159,9 +3160,9 @@ ], "support": { "issues": "https://github.com/utopia-php/circuit-breaker/issues", - "source": "https://github.com/utopia-php/circuit-breaker/tree/0.4.0" + "source": "https://github.com/utopia-php/circuit-breaker/tree/0.4.1" }, - "time": "2026-08-21T10:20:24+00:00" + "time": "2026-09-16T10:12:28+00:00" }, { "name": "utopia-php/cli", @@ -3407,16 +3408,16 @@ }, { "name": "utopia-php/database", - "version": "7.3.9", + "version": "7.3.11", "source": { "type": "git", "url": "https://github.com/utopia-php/database.git", - "reference": "54364c687d6ddb3d976d7130b9001c0b29276933" + "reference": "e45195ffb7019e70b88cf7d33814ecafd3fa2866" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/database/zipball/54364c687d6ddb3d976d7130b9001c0b29276933", - "reference": "54364c687d6ddb3d976d7130b9001c0b29276933", + "url": "https://api.github.com/repos/utopia-php/database/zipball/e45195ffb7019e70b88cf7d33814ecafd3fa2866", + "reference": "e45195ffb7019e70b88cf7d33814ecafd3fa2866", "shasum": "" }, "require": { @@ -3461,9 +3462,9 @@ ], "support": { "issues": "https://github.com/utopia-php/database/issues", - "source": "https://github.com/utopia-php/database/tree/7.3.9" + "source": "https://github.com/utopia-php/database/tree/7.3.11" }, - "time": "2026-09-14T13:25:01+00:00" + "time": "2026-09-17T08:18:45+00:00" }, { "name": "utopia-php/detector", @@ -4747,16 +4748,16 @@ }, { "name": "utopia-php/telemetry", - "version": "0.4.10", + "version": "0.4.11", "source": { "type": "git", "url": "https://github.com/utopia-php/telemetry.git", - "reference": "29432a590bf96597ba8f0e767c966be16481651a" + "reference": "852e76c89d0c20fc6560ac9687b15457a97b3704" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/telemetry/zipball/29432a590bf96597ba8f0e767c966be16481651a", - "reference": "29432a590bf96597ba8f0e767c966be16481651a", + "url": "https://api.github.com/repos/utopia-php/telemetry/zipball/852e76c89d0c20fc6560ac9687b15457a97b3704", + "reference": "852e76c89d0c20fc6560ac9687b15457a97b3704", "shasum": "" }, "require": { @@ -4792,9 +4793,9 @@ ], "support": { "issues": "https://github.com/utopia-php/telemetry/issues", - "source": "https://github.com/utopia-php/telemetry/tree/0.4.10" + "source": "https://github.com/utopia-php/telemetry/tree/0.4.11" }, - "time": "2026-09-11T06:27:08+00:00" + "time": "2026-09-16T10:12:28+00:00" }, { "name": "utopia-php/usage", From e06f75bd8eef77c528dd37a954a7db75b9a168cc Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 14:13:42 +0530 Subject: [PATCH 31/38] chore(deps): bump utopia-php/vcs to 5.5.0 --- composer.json | 2 +- composer.lock | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index 8d5d830090..04ab21bc17 100644 --- a/composer.json +++ b/composer.json @@ -104,7 +104,7 @@ "utopia-php/telemetry": "^0.4", "utopia-php/user-agent": "0.1.*", "mustangostang/spyc": "0.6.*", - "utopia-php/vcs": "5.4.*", + "utopia-php/vcs": "5.5.*", "utopia-php/websocket": "2.0.2", "dragonmantank/cron-expression": "3.4.*", "chillerlan/php-qrcode": "4.3.*", diff --git a/composer.lock b/composer.lock index 4c270aa001..5ef852281f 100644 --- a/composer.lock +++ b/composer.lock @@ -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": "a6c7073c169d41bd738310bdb883d0e3", + "content-hash": "f7ded3605b7574ac15000ccecaa56361", "packages": [ { "name": "adhocore/jwt", @@ -5079,16 +5079,16 @@ }, { "name": "utopia-php/vcs", - "version": "5.4.0", + "version": "5.5.0", "source": { "type": "git", "url": "https://github.com/utopia-php/vcs.git", - "reference": "1224f6eade2ad7be43c9bcb4459321d9ffec97dc" + "reference": "de3d3dafe019f8cffd97480a9f2bf15d7514678c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/vcs/zipball/1224f6eade2ad7be43c9bcb4459321d9ffec97dc", - "reference": "1224f6eade2ad7be43c9bcb4459321d9ffec97dc", + "url": "https://api.github.com/repos/utopia-php/vcs/zipball/de3d3dafe019f8cffd97480a9f2bf15d7514678c", + "reference": "de3d3dafe019f8cffd97480a9f2bf15d7514678c", "shasum": "" }, "require": { @@ -5131,10 +5131,10 @@ "vcs" ], "support": { - "source": "https://github.com/utopia-php/vcs/tree/5.4.0", + "source": "https://github.com/utopia-php/vcs/tree/5.5.0", "issues": "https://github.com/utopia-php/vcs/issues" }, - "time": "2026-09-15T08:06:27+00:00" + "time": "2026-09-17T08:01:03+00:00" }, { "name": "utopia-php/websocket", From 91f52cb061c2220c32d8476d18ef56d68f2e0760 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 14:20:03 +0530 Subject: [PATCH 32/38] chore(deps): require utopia-php/vcs 5.5 --- composer.json | 2 +- composer.lock | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/composer.json b/composer.json index a803e212cc..587dd90749 100644 --- a/composer.json +++ b/composer.json @@ -110,7 +110,7 @@ "utopia-php/telemetry": "^0.4", "utopia-php/user-agent": "0.1.*", "mustangostang/spyc": "0.6.*", - "utopia-php/vcs": "5.4.*", + "utopia-php/vcs": "5.5.*", "utopia-php/websocket": "2.0.2", "dragonmantank/cron-expression": "3.4.*", "chillerlan/php-qrcode": "4.3.*", diff --git a/composer.lock b/composer.lock index 03b99efe28..cde9eadc74 100644 --- a/composer.lock +++ b/composer.lock @@ -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": "c0c1b58b94677d51187d04d79843b0f3", + "content-hash": "59039ff57c3917eab949bc0daf0a9668", "packages": [ { "name": "adhocore/jwt", @@ -4934,16 +4934,16 @@ }, { "name": "utopia-php/vcs", - "version": "5.4.0", + "version": "5.5.0", "source": { "type": "git", "url": "https://github.com/utopia-php/vcs.git", - "reference": "1224f6eade2ad7be43c9bcb4459321d9ffec97dc" + "reference": "de3d3dafe019f8cffd97480a9f2bf15d7514678c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/vcs/zipball/1224f6eade2ad7be43c9bcb4459321d9ffec97dc", - "reference": "1224f6eade2ad7be43c9bcb4459321d9ffec97dc", + "url": "https://api.github.com/repos/utopia-php/vcs/zipball/de3d3dafe019f8cffd97480a9f2bf15d7514678c", + "reference": "de3d3dafe019f8cffd97480a9f2bf15d7514678c", "shasum": "" }, "require": { @@ -4986,10 +4986,10 @@ "vcs" ], "support": { - "source": "https://github.com/utopia-php/vcs/tree/5.4.0", + "source": "https://github.com/utopia-php/vcs/tree/5.5.0", "issues": "https://github.com/utopia-php/vcs/issues" }, - "time": "2026-09-15T08:06:27+00:00" + "time": "2026-09-17T08:01:03+00:00" }, { "name": "utopia-php/websocket", From 549fd4446ba94da28917f36b48f51b0d66ed7bd9 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 14:43:55 +0530 Subject: [PATCH 33/38] chore(deps): bump utopia-php/user-agent to 0.1.2 --- composer.lock | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/composer.lock b/composer.lock index cde9eadc74..005febd297 100644 --- a/composer.lock +++ b/composer.lock @@ -4852,16 +4852,16 @@ }, { "name": "utopia-php/user-agent", - "version": "0.1.1", + "version": "0.1.2", "source": { "type": "git", "url": "https://github.com/utopia-php/user-agent.git", - "reference": "4f7bb7288cfe3ce8e257944c0827914901c873bc" + "reference": "0396bd6187fbc00b5a61f8876ff822f3428fe8c5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/utopia-php/user-agent/zipball/4f7bb7288cfe3ce8e257944c0827914901c873bc", - "reference": "4f7bb7288cfe3ce8e257944c0827914901c873bc", + "url": "https://api.github.com/repos/utopia-php/user-agent/zipball/0396bd6187fbc00b5a61f8876ff822f3428fe8c5", + "reference": "0396bd6187fbc00b5a61f8876ff822f3428fe8c5", "shasum": "" }, "require": { @@ -4888,9 +4888,9 @@ ], "support": { "issues": "https://github.com/utopia-php/user-agent/issues", - "source": "https://github.com/utopia-php/user-agent/tree/0.1.1" + "source": "https://github.com/utopia-php/user-agent/tree/0.1.2" }, - "time": "2026-07-20T09:05:28+00:00" + "time": "2026-09-17T08:48:33+00:00" }, { "name": "utopia-php/validators", From e749da240ab1ab4347f1e2a7d5965b213204a3a9 Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 15:40:50 +0530 Subject: [PATCH 34/38] fix(deployments): redeploy from the resource's current root directory --- .../Http/Deployments/Duplicate/Create.php | 3 +- .../Http/Deployments/Duplicate/Create.php | 3 +- .../VCSGitea/VCSGiteaConsoleClientTest.php | 152 +----------------- tests/unit/Deployment/DeploymentsTest.php | 117 -------------- 4 files changed, 3 insertions(+), 272 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php index 7ba0a2fbf8..f5842b298d 100644 --- a/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Functions/Http/Deployments/Duplicate/Create.php @@ -167,8 +167,7 @@ class Create extends Action $owner, $repository, $ref, - // Older connected deployments did not snapshot their source root. - $deployment->getAttribute('providerRootDirectory') ?? $function->getAttribute('providerRootDirectory', ''), + $function->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php index 1a399d34c8..c7348f315c 100644 --- a/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php +++ b/src/Appwrite/Platform/Modules/Sites/Http/Deployments/Duplicate/Create.php @@ -192,8 +192,7 @@ class Create extends Action $owner, $repository, $ref, - // Older connected deployments did not snapshot their source root. - $deployment->getAttribute('providerRootDirectory') ?? $site->getAttribute('providerRootDirectory', ''), + $site->getAttribute('providerRootDirectory', ''), ); } else { // Public template repo: providerBranch holds the resolved ref, diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index a7ed0dbff1..8db0756915 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -4,20 +4,13 @@ declare(strict_types=1); namespace Tests\E2E\Services\VCSGitea; -use Appwrite\Database\Factory; use Appwrite\Tests\Async\Exceptions\Critical; use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; -use Utopia\Cache\Adapter\Pool as CachePool; -use Utopia\Cache\Adapter\Sharding; -use Utopia\Cache\Cache; -use Utopia\Config\Config; -use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; -use Utopia\Database\Validator\Authorization; use Utopia\System\System; final class VCSGiteaConsoleClientTest extends Scope @@ -117,146 +110,6 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-v2'), 30000, 1000); } - public function testCreateDeploymentFromNestedRootDirectory(): void - { - /** - * Test for SUCCESS - */ - $projectId = $this->getProject()['$id']; - $headers = \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()); - $installationId = $this->createInstallationHelper()['$id']; - - $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ - 'name' => 'function-' . \uniqid(), - 'auto_init' => true, - 'default_branch' => 'main', - 'private' => false, - ]); - $this->assertEquals(201, $repository['headers']['status-code'], \json_encode($repository['body'])); - $repositoryName = $repository['body']['name']; - - $workdir = \sys_get_temp_dir() . '/vcs-gitea-' . \uniqid(); - $endpoint = System::getEnv('_APP_VCS_GITEA_ENDPOINT', 'http://gitea:3000'); - $remote = \str_replace('://', '://' . self::GITEA_USERNAME . ':' . self::GITEA_PASSWORD . '@', $endpoint) - . '/' . self::GITEA_USERNAME . '/' . $repositoryName . '.git'; - - $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); - \mkdir($workdir . '/docs/nested', 0o777, true); - \file_put_contents($workdir . '/index.js', "module.exports = async (context) => context.res.send('gitea-root:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); - \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v1:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); - $this->gitHelper('git add index.js docs && git commit -m "Add nested function"', $workdir); - $this->gitHelper('git push origin main', $workdir); - - $function = $this->client->call(Client::METHOD_POST, '/functions', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'functionId' => ID::unique(), - 'name' => 'Gitea nested VCS', - 'execute' => [Role::any()->toString()], - 'runtime' => 'node-22', - 'entrypoint' => 'index.js', - 'timeout' => 15, - 'installationId' => $installationId, - 'providerRepositoryId' => (string) $repository['body']['id'], - 'providerBranch' => 'main', - 'providerRootDirectory' => './docs/nested/', - ]); - $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); - $functionId = $function['body']['$id']; - - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/vcs', \array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'type' => 'branch', - 'reference' => 'main', - 'activate' => true, - ]); - $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); - - $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v1:./docs/nested/'), 30000, 1000); - - $knownIds = $this->listDeploymentIdsHelper($functionId); - - \file_put_contents($workdir . '/docs/nested/index.js', "module.exports = async (context) => context.res.send('gitea-nested-v2:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); - $this->gitHelper('git add docs && git commit -m "Update nested function"', $workdir); - $this->gitHelper('git push origin main', $workdir); - - $webhookDeploymentId = $this->waitForNewDeploymentReadyHelper($functionId, $knownIds); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $webhookDeploymentId), 30000, 1000); - - // Upgrade fixture: deployments created before source roots were saved - // have NULL here. This metadata has no public update endpoint. - $seed = function (?string $root) use ($projectId, $webhookDeploymentId) { - global $register; - $pools = $register->get('pools'); - $cache = new Cache(new Sharding(\array_map( - fn (string $name) => new CachePool($pools->get($name)), - Config::getParam('pools-cache', []), - ))); - $authorization = new Authorization(); - $factory = new Factory($pools, $cache, $authorization); - - $authorization->skip(function () use ($factory, $projectId, $webhookDeploymentId, $root) { - $project = $factory->platform()->getDocument('projects', $projectId); - $database = $factory->project($project); - $database->updateDocument('deployments', $webhookDeploymentId, new Document([ - 'providerRootDirectory' => $root, - ])); - $database->purgeCachedDocument('deployments', $webhookDeploymentId); - $this->assertSame($root, $database->getDocument('deployments', $webhookDeploymentId)->getAttribute('providerRootDirectory')); - }); - }; - if (\Swoole\Coroutine::getCid() >= 0) { - $seed(null); - } else { - \Swoole\Coroutine\run(fn () => $seed(null)); - } - - $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ - 'deploymentId' => $webhookDeploymentId, - ]); - $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); - - $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $duplicate['body']['$id']), 30000, 1000); - - // The healed deployment must retain its source root after settings change. - $updated = $this->client->call(Client::METHOD_PUT, '/functions/' . $functionId, $headers, [ - 'name' => 'Gitea nested VCS', - 'execute' => [Role::any()->toString()], - 'providerRootDirectory' => 'missing', - ]); - $this->assertEquals(200, $updated['headers']['status-code'], \json_encode($updated['body'])); - $this->assertSame('missing', $updated['body']['providerRootDirectory']); - - $preserved = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ - 'deploymentId' => $duplicate['body']['$id'], - ]); - $this->assertEquals(202, $preserved['headers']['status-code'], \json_encode($preserved['body'])); - $this->waitForDeploymentReadyHelper($functionId, $preserved['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-nested-v2:./docs/nested/', $preserved['body']['$id']), 30000, 1000); - - // An explicit empty snapshot names the repository root, even when the - // function now points elsewhere. It must not take the legacy fallback. - if (\Swoole\Coroutine::getCid() >= 0) { - $seed(''); - } else { - \Swoole\Coroutine\run(fn () => $seed('')); - } - $root = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ - 'deploymentId' => $webhookDeploymentId, - ]); - $this->assertEquals(202, $root['headers']['status-code'], \json_encode($root['body'])); - $this->waitForDeploymentReadyHelper($functionId, $root['body']['$id']); - $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-root:', $root['body']['$id']), 30000, 1000); - } - public function testClosePullRequestRemovesAuthorization(): void { /** @@ -585,7 +438,7 @@ final class VCSGiteaConsoleClientTest extends Scope return $response['body']['deployments'] ?? []; } - private function assertExecutionOutputHelper(string $functionId, string $output, ?string $deploymentId = null): void + private function assertExecutionOutputHelper(string $functionId, string $output): void { $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', \array_merge([ 'content-type' => 'application/json', @@ -597,9 +450,6 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEquals(201, $execution['headers']['status-code'], \json_encode($execution['body'])); $this->assertEquals('completed', $execution['body']['status'] ?? '', \json_encode($execution['body'])); $this->assertEquals($output, $execution['body']['responseBody'] ?? ''); - if ($deploymentId !== null) { - $this->assertSame($deploymentId, $execution['body']['deploymentId']); - } } private function buildGiteaState(string $projectId, string $success, string $failure): string diff --git a/tests/unit/Deployment/DeploymentsTest.php b/tests/unit/Deployment/DeploymentsTest.php index 55da3c35ea..0ef0ea0633 100644 --- a/tests/unit/Deployment/DeploymentsTest.php +++ b/tests/unit/Deployment/DeploymentsTest.php @@ -6,66 +6,12 @@ namespace Tests\Unit\Deployment; use Appwrite\Deployment\Deployments; use Appwrite\Extend\Exception; -use OpenRuntimes\Orchestrator\Jobs; -use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Http\Client\ClientInterface; -use Psr\Http\Message\RequestInterface; -use Psr\Http\Message\ResponseInterface; use Utopia\Config\Config; -use Utopia\Database\Database; use Utopia\Database\Document; -use Utopia\Psr7\Response; -use Utopia\Psr7\Stream; -use Utopia\VCS\Adapter\Git\GitHub; final class DeploymentsTest extends TestCase { - public static function sources(): \Iterator - { - yield 'archive subdirectory' => [true, 'functions/api']; - yield 'archive root' => [true, '']; - yield 'clone subdirectory' => [false, 'functions/api']; - yield 'clone root' => [false, '']; - } - - #[DataProvider('sources')] - public function testCreateVcsDeploymentPersistsSourceRoot(bool $archives, string $root): void - { - $previousKey = \getenv('_APP_OPENSSL_KEY_V1'); - \putenv('_APP_OPENSSL_KEY_V1=unit-test-key'); - - try { - $database = new VcsDeploymentDatabase(); - $client = new VcsBuildClient(); - $deployments = new Deployments(new Jobs($client), $database, new Document(['$id' => 'project', 'region' => 'default']), ['apiHostname' => 'localhost']); - - $deployment = $deployments->createFromVcs( - new Document([ - '$id' => 'function', - '$collection' => 'functions', - 'runtime' => \array_key_first(Config::getParam('runtimes-v2')), - 'providerRootDirectory' => 'changed/function/setting', - ]), - new Document(['$id' => 'deployment', 'buildCommands' => 'npm ci']), - 900, - new VcsRepository($archives), - 'owner', - 'repository', - 'commit', - $root, - ); - - $this->assertSame('waiting', $deployment->getAttribute('status')); - $this->assertSame($root, $database->getDocument('deployments', 'deployment')->getAttribute('providerRootDirectory')); - $this->assertSame($root, $client->payload['environment']['APPWRITE_VCS_ROOT_DIRECTORY']); - $artifacts = \array_column($client->payload['artifacts'], null, 'id'); - $this->assertSame($root, $artifacts[$archives ? 'extract' : 'source']['subdir'] ?? ''); - } finally { - \putenv($previousKey === false ? '_APP_OPENSSL_KEY_V1' : '_APP_OPENSSL_KEY_V1=' . $previousKey); - } - } - public function testSiteCommandIncludesFrameworkAndDeploymentCommands(): void { Config::setParam('frameworks', [ @@ -237,66 +183,3 @@ final readonly class ExposedDeployments extends Deployments return static::payload($project, $resource, $deployment, $platform, 137); } } - -final class VcsDeploymentDatabase extends Database -{ - private Document $deployment; - - public function __construct() - { - } - - public function createDocument(string $collection, Document $document): Document - { - $this->deployment = clone $document; - $this->deployment->setAttribute('$sequence', '1'); - - return clone $this->deployment; - } - - public function updateDocuments(string $collection, Document $updates, array $queries = [], int $batchSize = self::INSERT_BATCH_SIZE, ?callable $onNext = null, ?callable $onError = null): int - { - $this->deployment->setAttributes($updates->getArrayCopy()); - - return 1; - } - - public function getDocument(string $collection, string $id, array $queries = [], bool $forUpdate = false): Document - { - return clone $this->deployment; - } -} - -final class VcsBuildClient implements ClientInterface -{ - public array $payload = []; - - public function sendRequest(RequestInterface $request): ResponseInterface - { - $this->payload = \json_decode((string) $request->getBody(), true, flags: JSON_THROW_ON_ERROR); - - return new Response(202, body: new Stream('{"id":"build","status":"accepted"}')); - } -} - -final class VcsRepository extends GitHub -{ - public function __construct(private bool $archives) - { - } - - public function supportsRepositoryArchives(): bool - { - return $this->archives; - } - - public function getRepositoryPresignedUrl(string $owner, string $repositoryName, string $ref = '', string $format = 'tarball'): string - { - return 'https://vcs.example/source.tar.gz'; - } - - public function getRepositoryCloneUrl(string $owner, string $repositoryName): string - { - return 'https://vcs.example/source.git'; - } -} From c00eb376db6513db5718305c02d5e42f457438ae Mon Sep 17 00:00:00 2001 From: harsh mahajan Date: Thu, 17 Sep 2026 15:40:50 +0530 Subject: [PATCH 35/38] test(vcs): cover a redeploy after the root directory changes --- .../VCSGitea/VCSGiteaConsoleClientTest.php | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php index 8db0756915..cea9401442 100644 --- a/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php +++ b/tests/e2e/Services/VCSGitea/VCSGiteaConsoleClientTest.php @@ -110,6 +110,75 @@ final class VCSGiteaConsoleClientTest extends Scope $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'gitea-v2'), 30000, 1000); } + public function testCreateDuplicateDeploymentWithRootDirectory(): void + { + $projectId = $this->getProject()['$id']; + $headers = \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()); + $installationId = $this->createInstallationHelper()['$id']; + + $repository = $this->giteaApiHelper(Client::METHOD_POST, '/api/v1/user/repos', [ + 'name' => 'function-' . \uniqid(), + 'auto_init' => true, + 'default_branch' => 'main', + 'private' => false, + ]); + $this->assertEquals(201, $repository['headers']['status-code'], \json_encode($repository['body'])); + + $workdir = \sys_get_temp_dir() . '/vcs-gitea-' . \uniqid(); + $endpoint = System::getEnv('_APP_VCS_GITEA_ENDPOINT', 'http://gitea:3000'); + $remote = \str_replace('://', '://' . self::GITEA_USERNAME . ':' . self::GITEA_PASSWORD . '@', $endpoint) + . '/' . self::GITEA_USERNAME . '/' . $repository['body']['name'] . '.git'; + + $this->gitHelper("git clone {$remote} {$workdir}", \sys_get_temp_dir()); + foreach (['api', 'web'] as $directory) { + \mkdir($workdir . '/functions/' . $directory, 0o777, true); + \file_put_contents($workdir . '/functions/' . $directory . '/index.js', "module.exports = async (context) => context.res.send('{$directory}:' + process.env.APPWRITE_VCS_ROOT_DIRECTORY);\n"); + } + $this->gitHelper('git add functions && git commit -m "Add functions"', $workdir); + $this->gitHelper('git push origin main', $workdir); + + $function = $this->client->call(Client::METHOD_POST, '/functions', $headers, [ + 'functionId' => ID::unique(), + 'name' => 'Gitea root directory', + 'execute' => [Role::any()->toString()], + 'runtime' => 'node-22', + 'entrypoint' => 'index.js', + 'timeout' => 15, + 'installationId' => $installationId, + 'providerRepositoryId' => (string) $repository['body']['id'], + 'providerBranch' => 'main', + 'providerRootDirectory' => 'functions/api', + ]); + $this->assertEquals(201, $function['headers']['status-code'], \json_encode($function['body'])); + $functionId = $function['body']['$id']; + + $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/vcs', $headers, [ + 'type' => 'branch', + 'reference' => 'main', + 'activate' => true, + ]); + $this->assertEquals(202, $deployment['headers']['status-code'], \json_encode($deployment['body'])); + $this->waitForDeploymentReadyHelper($functionId, $deployment['body']['$id']); + + $function = $this->client->call(Client::METHOD_PUT, '/functions/' . $functionId, $headers, [ + 'name' => 'Gitea root directory', + 'execute' => [Role::any()->toString()], + 'providerRootDirectory' => 'functions/web', + ]); + $this->assertEquals(200, $function['headers']['status-code'], \json_encode($function['body'])); + + $duplicate = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments/duplicate', $headers, [ + 'deploymentId' => $deployment['body']['$id'], + ]); + $this->assertEquals(202, $duplicate['headers']['status-code'], \json_encode($duplicate['body'])); + $this->waitForDeploymentReadyHelper($functionId, $duplicate['body']['$id']); + + $this->assertEventually(fn () => $this->assertExecutionOutputHelper($functionId, 'web:functions/web'), 30000, 1000); + } + public function testClosePullRequestRemovesAuthorization(): void { /** From 897a877eb8a1dc0eb0002b0c26869f5f03899856 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Thu, 17 Sep 2026 14:32:35 +0100 Subject: [PATCH 36/38] refactor(specs): drop the x-appwrite.idGenerator extension MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The key is emitted on every CustomId parameter with the single constant value "ID.unique", so it carries no information beyond "this validator was CustomId", and an audit found no consumer reading it: not the SDK generator, not vibes, not the console, MCP, or the Terraform provider. Vibes classifies creatable resource IDs from the schema description instead, matching /choose a custom … id|generate a random id|ID.unique\(\)/ in isCreatableIdSchema(), and treats every path and query parameter as an existing-resource reference regardless. Of the 88 canonical sites, 80 are already matched by that regex and 7 of the remaining 8 are path parameters vibes excludes by rule, so removing the extension changes no consumer behaviour. This continues the OpenAPI3 standards cleanup: x-appwrite should hold only what OpenAPI cannot express, and a constant-valued flag with no reader does not qualify. --- src/Appwrite/SDK/Specification/Format/OpenAPI3.php | 3 --- tests/unit/SDK/Specification/FormatTest.php | 4 ++-- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/Appwrite/SDK/Specification/Format/OpenAPI3.php b/src/Appwrite/SDK/Specification/Format/OpenAPI3.php index cf5bb66056..87640bcde2 100644 --- a/src/Appwrite/SDK/Specification/Format/OpenAPI3.php +++ b/src/Appwrite/SDK/Specification/Format/OpenAPI3.php @@ -668,9 +668,6 @@ class OpenAPI3 extends Format break; case \Appwrite\Utopia\Database\Validator\CustomId::class: $node['schema']['type'] = $validator->getType(); - $node['schema']['x-appwrite'] = [ - 'idGenerator' => 'ID.unique', - ]; $node['schema']['example'] = ($param['example'] ?? '') !== '' ? $param['example'] : '<' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . '>'; break; case \Appwrite\Task\Validator\Cron::class: diff --git a/tests/unit/SDK/Specification/FormatTest.php b/tests/unit/SDK/Specification/FormatTest.php index 47e6ed01f3..823687593e 100644 --- a/tests/unit/SDK/Specification/FormatTest.php +++ b/tests/unit/SDK/Specification/FormatTest.php @@ -379,7 +379,7 @@ final class FormatTest extends TestCase $this->assertArrayNotHasKey('x-enum-name', $status); } - public function testOpenApiCustomIdBodyFieldIncludesIdGeneratorMetadata(): void + public function testOpenApiCustomIdBodyFieldOmitsVendorMetadata(): void { Method::$processed = []; Method::$errors = []; @@ -400,7 +400,7 @@ final class FormatTest extends TestCase $userId = $spec['paths']['/tests']['post']['requestBody']['content']['application/json']['schema']['properties']['userId']; - $this->assertSame(['idGenerator' => 'ID.unique'], $userId['x-appwrite']); + $this->assertArrayNotHasKey('x-appwrite', $userId); $this->assertSame('', $userId['example']); $this->assertArrayNotHasKey('x-example', $userId); } From 0477fbcfc0694756b0ca25cd3f43e11b87ead7f4 Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Thu, 17 Sep 2026 15:24:49 +0100 Subject: [PATCH 37/38] test: keep the CustomId case asserting only its generated example --- tests/unit/SDK/Specification/FormatTest.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/unit/SDK/Specification/FormatTest.php b/tests/unit/SDK/Specification/FormatTest.php index 823687593e..f03f773411 100644 --- a/tests/unit/SDK/Specification/FormatTest.php +++ b/tests/unit/SDK/Specification/FormatTest.php @@ -379,7 +379,7 @@ final class FormatTest extends TestCase $this->assertArrayNotHasKey('x-enum-name', $status); } - public function testOpenApiCustomIdBodyFieldOmitsVendorMetadata(): void + public function testOpenApiCustomIdBodyFieldUsesGeneratedExample(): void { Method::$processed = []; Method::$errors = []; @@ -400,7 +400,6 @@ final class FormatTest extends TestCase $userId = $spec['paths']['/tests']['post']['requestBody']['content']['application/json']['schema']['properties']['userId']; - $this->assertArrayNotHasKey('x-appwrite', $userId); $this->assertSame('', $userId['example']); $this->assertArrayNotHasKey('x-example', $userId); } From 0ffc90bd077c92f03e417d737f2c77c99ef682df Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Thu, 17 Sep 2026 15:50:44 +0100 Subject: [PATCH 38/38] refactor(specs): name the alias summary "summary" An operation carries its short title in the standard `summary` field and its prose in `description`. A method alias in `x-appwrite.methods[]` mirrors an operation, but carried the same short title under `desc` while keeping `description` as a separate sibling, so `desc` read like an abbreviation of the field sitting next to it. Emit `summary` instead, and rename the PHP side to match: Method::$desc becomes $summary with getSummary(), and the 16 call sites pass `summary:`. Route::getDesc() is Utopia's and is untouched. No consumer changes. The generator never read the key, deriving an alias summary from its name. Vibes already reads `additionalMethod.summary || additionalMethod.desc`, so it takes the new field on the first branch and its fallback can be dropped once historical specs stop mattering. While here, validateDesc() validates a description, so it is renamed to validateDescription() to keep it distinct from the new summary. --- .../Collections/Documents/Create.php | 4 ++-- .../Collections/Documents/Create.php | 4 ++-- .../Databases/Http/Embeddings/Text/Create.php | 2 +- .../Http/TablesDB/Tables/Rows/Create.php | 4 ++-- .../Collections/Documents/Create.php | 4 ++-- .../Modules/Presences/HTTP/Delete.php | 2 +- .../Platform/Modules/Presences/HTTP/Get.php | 2 +- .../Modules/Presences/HTTP/Update.php | 4 ++-- .../Modules/Presences/HTTP/Upsert.php | 4 ++-- .../Platform/Modules/Presences/HTTP/XList.php | 2 +- src/Appwrite/SDK/Method.php | 23 +++++++++---------- .../SDK/Specification/Format/OpenAPI3.php | 2 +- tests/unit/SDK/Specification/FormatTest.php | 3 +++ 13 files changed, 31 insertions(+), 29 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php index e451447835..0b79dc90bd 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Databases/Collections/Documents/Create.php @@ -77,7 +77,7 @@ class Create extends Action namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), name: self::getName(), - desc: 'Create document', + summary: 'Create document', description: '/docs/references/databases/create-document.md', auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], responses: [ @@ -104,7 +104,7 @@ class Create extends Action namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), name: $this->getBulkActionName(self::getName()), - desc: 'Create documents', + summary: 'Create documents', description: '/docs/references/databases/create-documents.md', auth: [AuthType::ADMIN, AuthType::KEY], responses: [ diff --git a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php index ea7c96c1b4..1f48c594a0 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/DocumentsDB/Collections/Documents/Create.php @@ -60,7 +60,7 @@ class Create extends DocumentCreate namespace: 'documentsDB', group: $this->getSdkGroup(), name: 'createDocument', - desc: 'Create document', + summary: 'Create document', description: '/docs/references/documentsdb/create-document.md', auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], responses: [ @@ -83,7 +83,7 @@ class Create extends DocumentCreate namespace: 'documentsDB', group: $this->getSdkGroup(), name: 'createDocuments', - desc: 'Create documents', + summary: 'Create documents', description: '/docs/references/documentsdb/create-documents.md', auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Databases/Http/Embeddings/Text/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/Embeddings/Text/Create.php index cdd6f79bda..763f47d9a2 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/Embeddings/Text/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/Embeddings/Text/Create.php @@ -57,7 +57,7 @@ class Create extends CreateDocumentAction namespace: 'embeddings', group: 'embeddings', name: 'createTextEmbeddings', - desc: 'Create Text Embedding', + summary: 'Create Text Embedding', description: '/docs/references/embeddings/create-text-embeddings.md', auth: [AuthType::ADMIN, AuthType::KEY, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php index d408783b5c..1f1179c34e 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/TablesDB/Tables/Rows/Create.php @@ -55,7 +55,7 @@ class Create extends DocumentCreate namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), name: self::getName(), - desc: 'Create row', + summary: 'Create row', description: '/docs/references/tablesdb/create-row.md', auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], responses: [ @@ -78,7 +78,7 @@ class Create extends DocumentCreate namespace: $this->getSDKNamespace(), group: $this->getSDKGroup(), name: $this->getBulkActionName(self::getName()), - desc: 'Create rows', + summary: 'Create rows', description: '/docs/references/tablesdb/create-rows.md', auth: [AuthType::ADMIN, AuthType::KEY], responses: [ diff --git a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php index 680308544f..63600f9b8e 100644 --- a/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php +++ b/src/Appwrite/Platform/Modules/Databases/Http/VectorsDB/Collections/Documents/Create.php @@ -54,7 +54,7 @@ class Create extends DocumentCreate namespace: 'vectorsDB', group: $this->getSdkGroup(), name: 'createDocument', - desc: 'Create document', + summary: 'Create document', description: '/docs/references/vectorsdb/create-document.md', auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], responses: [ @@ -77,7 +77,7 @@ class Create extends DocumentCreate namespace: 'vectorsDB', group: $this->getSdkGroup(), name: 'createDocuments', - desc: 'Create documents', + summary: 'Create documents', description: '/docs/references/vectorsdb/create-documents.md', auth: [AuthType::ADMIN, AuthType::KEY], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php index 66ab00c3a7..3938ae05d1 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Delete.php @@ -40,7 +40,7 @@ class Delete extends PlatformAction namespace: 'presences', group: 'presences', name: 'delete', - desc: 'Delete presence', + summary: 'Delete presence', description: '/docs/references/presences/delete.md', auth: [AuthType::ADMIN, AuthType::KEY, AuthType::SESSION, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php index ba6b769f70..06d3a49592 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Get.php @@ -35,7 +35,7 @@ class Get extends PlatformAction namespace: 'presences', group: 'presences', name: 'get', - desc: 'Get presence', + summary: 'Get presence', description: '/docs/references/presences/get.md', auth: [AuthType::ADMIN, AuthType::KEY, AuthType::SESSION, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php index fc2f9c6036..d5d0466111 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Update.php @@ -51,7 +51,7 @@ class Update extends PlatformAction namespace: 'presences', group: 'presences', name: 'update', - desc: 'Update presence', + summary: 'Update presence', description: '/docs/references/presences/update.md', auth: [AuthType::SESSION, AuthType::ADMIN], responses: [ @@ -74,7 +74,7 @@ class Update extends PlatformAction namespace: 'presences', group: 'presences', name: 'update', - desc: 'Update presence', + summary: 'Update presence', description: '/docs/references/presences/update.md', auth: [AuthType::KEY, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php b/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php index 245910d57c..49c304af02 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/Upsert.php @@ -52,7 +52,7 @@ class Upsert extends PlatformAction namespace: 'presences', group: 'presences', name: 'upsert', - desc: 'Upsert presence', + summary: 'Upsert presence', description: '/docs/references/presences/upsert.md', auth: [AuthType::SESSION, AuthType::ADMIN], responses: [ @@ -74,7 +74,7 @@ class Upsert extends PlatformAction namespace: 'presences', group: 'presences', name: 'upsert', - desc: 'Upsert presence', + summary: 'Upsert presence', description: '/docs/references/presences/upsert.md', auth: [AuthType::KEY, AuthType::JWT], responses: [ diff --git a/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php b/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php index 94dca8c4ee..656321199d 100644 --- a/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php +++ b/src/Appwrite/Platform/Modules/Presences/HTTP/XList.php @@ -45,7 +45,7 @@ class XList extends PlatformAction namespace: 'presences', group: 'presences', name: 'list', - desc: 'List presences', + summary: 'List presences', description: '/docs/references/presences/list.md', auth: [AuthType::ADMIN, AuthType::KEY, AuthType::SESSION, AuthType::JWT], responses: [ diff --git a/src/Appwrite/SDK/Method.php b/src/Appwrite/SDK/Method.php index 3b62661a33..a36b9d5552 100644 --- a/src/Appwrite/SDK/Method.php +++ b/src/Appwrite/SDK/Method.php @@ -21,7 +21,6 @@ class Method * @param string $namespace * @param ?string $group * @param string $name - * @param string $desc * @param string $description * @param array $auth * @param array $responses @@ -33,7 +32,7 @@ class Method * @param ContentType $requestType * @param array $parameters * @param array $additionalParameters - * @param string $desc + * @param string $summary * @param bool $public Whether this method should be rendered on the website/documentation * @param array $locationAuth Security scheme keys for location-type methods: first is the required project binding; additional keys supplement the base auth as an optional alternative */ @@ -52,13 +51,13 @@ class Method protected ContentType $requestType = ContentType::JSON, protected array $parameters = [], protected array $additionalParameters = [], - protected string $desc = '', + protected string $summary = '', protected bool $public = true, protected array $locationAuth = [] ) { $this->validateMethod($name, $namespace); $this->validateAuthTypes($auth); - $this->validateDesc($description); + $this->validateDescription($description); foreach ($responses as $response) { $this->validateResponseModel($response->getModel()); @@ -89,18 +88,18 @@ class Method } } - protected function validateDesc(string $desc): void + protected function validateDescription(string $description): void { - if (empty($desc)) { + if (empty($description)) { self::$errors[] = "Error with {$this->getRouteName()} method: Description label is empty"; return; } - if (\str_ends_with($desc, '.md')) { - $descPath = $this->getDescriptionFilePath() ?: $this->getDescription(); + if (\str_ends_with($description, '.md')) { + $path = $this->getDescriptionFilePath() ?: $this->getDescription(); - if (empty($descPath)) { - self::$errors[] = "Error with {$this->getRouteName()} method: Description file not found at {$desc}"; + if (empty($path)) { + self::$errors[] = "Error with {$this->getRouteName()} method: Description file not found at {$description}"; return; } } @@ -147,9 +146,9 @@ class Method return $this->name; } - public function getDesc(): string + public function getSummary(): string { - return $this->desc; + return $this->summary; } public function getDescription(): string diff --git a/src/Appwrite/SDK/Specification/Format/OpenAPI3.php b/src/Appwrite/SDK/Specification/Format/OpenAPI3.php index cf5bb66056..2dac6fc3d4 100644 --- a/src/Appwrite/SDK/Specification/Format/OpenAPI3.php +++ b/src/Appwrite/SDK/Specification/Format/OpenAPI3.php @@ -356,7 +356,7 @@ class OpenAPI3 extends Format 'name' => $methodObj->getMethodName(), 'namespace' => $methodObj->getNamespace(), 'platforms' => $methodSdkPlatforms, - 'desc' => $methodObj->getDesc(), + 'summary' => $methodObj->getSummary(), 'auth' => $this->getExampleAuth($methodSecurities, [], $methodSdkPlatforms), 'parameters' => [], 'required' => [], diff --git a/tests/unit/SDK/Specification/FormatTest.php b/tests/unit/SDK/Specification/FormatTest.php index 47e6ed01f3..02c372b1e5 100644 --- a/tests/unit/SDK/Specification/FormatTest.php +++ b/tests/unit/SDK/Specification/FormatTest.php @@ -1525,6 +1525,7 @@ final class FormatTest extends TestCase auth: [AuthType::KEY], responses: [], parameters: [new Parameter('presenceId', optional: false), new Parameter('userId', optional: false)], + summary: 'Update presence for a user', ), ]) ->param('presenceId', '', new Text(256), 'Presence ID.') @@ -1544,6 +1545,8 @@ final class FormatTest extends TestCase $this->assertSame(['server'], $canonical['x-appwrite']['methods'][1]['platforms']); $this->assertSame(['server' => ['Project' => [], 'Key' => []]], $canonical['x-appwrite']['methods'][1]['auth']); $this->assertSame(['presenceId', 'userId'], $canonical['x-appwrite']['methods'][1]['required']); + $this->assertSame('', $canonical['x-appwrite']['methods'][0]['summary']); + $this->assertSame('Update presence for a user', $canonical['x-appwrite']['methods'][1]['summary']); $this->assertCount(1, $client['x-appwrite']['methods']); $this->assertSame(['Project' => []], $client['x-appwrite']['methods'][0]['auth']);