fix(databases): type-guard the deprecated databases path like every other one

The legacy /v1/databases path was exempt from the by-id type guard while its own
list stayed type-filtered, so the two disagreed about which databases exist:
GET /v1/databases/{id} answered for a DocumentsDB or VectorsDB database that
GET /v1/databases had never listed, and /collections on one then queried
database_{sequence} — a table shaped for another product — and 500'd.

The guard and the list filter already share getAllowedDatabaseTypes() precisely
so they cannot diverge; the legacy path just opted out of it. Removing the
exemption and giving legacy the mirror of TablesDB's set makes them agree.
TablesDB and legacy are the same product either side of a rename, so each serves
both types and refuses the other two — a caller migrating between the two paths
never loses a database, and DocumentsDB and VectorsDB now get a typed
not-found instead of an opaque 500.

Fixes DAT-2219

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jake BarnbyandClaude Fable 5 committed 2026-08-09 00:24:13 +12:00
1 parent 6231bbef55
commit 875c25596f
3 files changed
+238 -18

No files matched your search

@@ -26,10 +26,10 @@ class Action extends AppwriteAction
* the list filter ({@see getDatabaseTypeQueryFilters()}) and the by-id guard
* ({@see isDatabaseTypeMismatch()}) so they cannot diverge.
*
* TablesDB is the compatibility successor to the legacy databases API, so it
* also serves legacy-typed databases; the other product APIs are scoped to
* their own type. Every database carries a non-null `type` (set on create
* and backfilled to 'legacy' by migration V23), so null is not represented.
* TablesDB and the legacy databases API are the same product either side of a
* rename, so each serves both types; DocumentsDB and VectorsDB are scoped to
* their own. Every database carries a non-null `type` (set on create and
* backfilled to 'legacy' by migration V23), so null is not represented.
*
* @return string[]
*/
@@ -37,22 +37,23 @@ class Action extends AppwriteAction
{
return match ($this->getDatabaseType()) {
DATABASE_TYPE_TABLESDB => [DATABASE_TYPE_TABLESDB, DATABASE_TYPE_LEGACY],
DATABASE_TYPE_LEGACY => [DATABASE_TYPE_LEGACY, DATABASE_TYPE_TABLESDB],
default => [$this->getDatabaseType()],
};
}
/**
* A database resolved by id on a product-DB path must be one of the path's
* allowed types; otherwise it is treated as not-found rather than proceeding
* to a type-mismatched backend operation that surfaces as an opaque 500. The
* legacy /v1/databases API is intentionally not type-guarded.
* A database resolved by id must be one of the path's allowed types; otherwise
* it is treated as not-found rather than proceeding to a type-mismatched backend
* operation that surfaces as an opaque 500.
*
* The legacy path was previously exempt, which left it resolving by id what its
* own list refused to return: `GET /v1/databases/{id}` answered for a DocumentsDB
* or VectorsDB database that `GET /v1/databases` had never listed, and
* `/collections` on one then 500'd against a table shaped for another product.
*/
protected function isDatabaseTypeMismatch(Document $database): bool
{
if ($this->getDatabaseType() === DATABASE_TYPE_LEGACY) {
return false;
}
return !in_array($database->getAttribute('type', ''), $this->getAllowedDatabaseTypes(), true);
}
@@ -5,8 +5,10 @@ declare(strict_types=1);
namespace Tests\Unit\Platform\Modules\Databases;
use Appwrite\Platform\Modules\Databases\Http\Databases\Action;
use Appwrite\Platform\Modules\Databases\Http\Databases\XList;
use PHPUnit\Framework\TestCase;
use Utopia\Database\Document;
use Utopia\Database\Query;
final class DatabaseTypeMismatchTest extends TestCase
{
@@ -80,9 +82,73 @@ final class DatabaseTypeMismatchTest extends TestCase
$this->assertTrue($vectors->exposeMismatch(new Document(['type' => DATABASE_TYPE_LEGACY])));
}
public function testLegacyDatabasesPathIsNeverTypeGuarded(): void
/**
* The legacy path is the mirror of the TablesDB one: same product either side of
* a rename, so it serves both types and refuses the other two.
*
* It was previously exempt from the guard entirely, which let it resolve by id
* what its own list refused to return — `GET /v1/databases/{id}` answered for a
* DocumentsDB or VectorsDB database that `GET /v1/databases` never listed, and
* `/collections` on one then 500'd against a table shaped for another product.
*/
public function testLegacyPathServesTablesdbAndRefusesTheOtherProducts(): void
{
$legacy = new class () extends Action {
$legacy = $this->legacyAction();
$this->assertSame([DATABASE_TYPE_LEGACY, DATABASE_TYPE_TABLESDB], $legacy->exposeAllowedTypes());
$this->assertFalse($legacy->exposeMismatch(new Document(['type' => DATABASE_TYPE_LEGACY])));
$this->assertFalse($legacy->exposeMismatch(new Document(['type' => DATABASE_TYPE_TABLESDB])));
$this->assertTrue($legacy->exposeMismatch(new Document(['type' => DATABASE_TYPE_DOCUMENTSDB])));
$this->assertTrue($legacy->exposeMismatch(new Document(['type' => DATABASE_TYPE_VECTORSDB])));
$this->assertTrue($legacy->exposeMismatch(new Document([])));
}
/**
* The by-id guard and the list filter must select the same set, or the two
* disagree about which databases exist.
*/
public function testLegacyListFilterAndByIdGuardSelectTheSameSet(): void
{
$legacy = $this->legacyAction();
$filters = $legacy->exposeQueryFilters();
$this->assertCount(1, $filters);
$this->assertSame('type', $filters[0]->getAttribute());
$listed = $filters[0]->getValues();
$this->assertSame($legacy->exposeAllowedTypes(), $listed);
foreach ([DATABASE_TYPE_LEGACY, DATABASE_TYPE_TABLESDB, DATABASE_TYPE_DOCUMENTSDB, DATABASE_TYPE_VECTORSDB] as $type) {
$this->assertSame(
in_array($type, $listed, true),
!$legacy->exposeMismatch(new Document(['type' => $type])),
"list and get disagree about whether a '{$type}' database exists on /v1/databases",
);
}
}
/**
* The two paths over the same product must accept the same databases, so a caller
* migrating from /v1/databases to /v1/tablesdb never loses one.
*/
public function testLegacyAndTablesdbPathsAcceptTheSameDatabases(): void
{
$legacy = $this->legacyAction();
$tablesdb = $this->tablesdbAction();
foreach ([DATABASE_TYPE_LEGACY, DATABASE_TYPE_TABLESDB, DATABASE_TYPE_DOCUMENTSDB, DATABASE_TYPE_VECTORSDB] as $type) {
$this->assertSame(
$tablesdb->exposeMismatch(new Document(['type' => $type])),
$legacy->exposeMismatch(new Document(['type' => $type])),
"the deprecated and successor paths disagree about a '{$type}' database",
);
}
}
private function legacyAction(): object
{
$legacy = new class () extends XList {
public static function getName(): string
{
return 'testLegacyTypeGuard';
@@ -92,11 +158,39 @@ final class DatabaseTypeMismatchTest extends TestCase
{
return $this->isDatabaseTypeMismatch($database);
}
/** @return string[] */
public function exposeAllowedTypes(): array
{
return $this->getAllowedDatabaseTypes();
}
/** @return Query[] */
public function exposeQueryFilters(): array
{
return $this->getDatabaseTypeQueryFilters();
}
};
$legacy->setHttpPath('/v1/databases/:databaseId/collections');
$this->assertFalse($legacy->exposeMismatch(new Document(['type' => DATABASE_TYPE_LEGACY])));
$this->assertFalse($legacy->exposeMismatch(new Document([])));
$this->assertFalse($legacy->exposeMismatch(new Document(['type' => DATABASE_TYPE_TABLESDB])));
$this->assertFalse($legacy->exposeMismatch(new Document(['type' => DATABASE_TYPE_DOCUMENTSDB])));
return $legacy;
}
private function tablesdbAction(): object
{
$tablesdb = new class () extends Action {
public static function getName(): string
{
return 'testTablesdbMirrorGuard';
}
public function exposeMismatch(Document $database): bool
{
return $this->isDatabaseTypeMismatch($database);
}
};
$tablesdb->setHttpPath('/v1/tablesdb/:databaseId/tables');
return $tablesdb;
}
}
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Platform\Modules\Databases;
use Appwrite\Extend\Exception;
use Appwrite\Platform\Modules\Databases\Http\Databases\Collections\XList;
use Appwrite\Utopia\Response as UtopiaResponse;
use PHPUnit\Framework\TestCase;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
/**
* `GET /v1/databases/{id}/collections` on a VectorsDB or DocumentsDB database used to
* reach the backend and query `database_{sequence}`, a table shaped for a different
* product, which surfaced as an opaque 500.
*
* The refusal has to happen before the backend is touched, so these tests assert the
* backend is never reached rather than pinning the wording of whatever the engine
* would have thrown.
*/
final class LegacyCollectionsRefusalTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
require_once __DIR__ . '/../../../../../src/Appwrite/Platform/Modules/Databases/Constants.php';
}
/**
* @param array<string, mixed> $attributes
* @return array{reached: bool}
*/
private function listCollections(array $attributes): array
{
$reached = false;
$dbForProject = $this->createMock(Database::class);
$dbForProject
->method('getDocument')
->willReturn(new Document(['$id' => 'db', '$sequence' => '7', ...$attributes]));
$dbForProject
->method('find')
->willReturnCallback(function () use (&$reached): array {
$reached = true;
return [];
});
$dbForProject
->method('count')
->willReturnCallback(function () use (&$reached): int {
$reached = true;
return 0;
});
(new XList())->action(
'db',
[],
'',
false,
$this->createMock(UtopiaResponse::class),
$dbForProject,
new Authorization(),
);
return ['reached' => $reached];
}
public function testAVectorsDatabaseIsRefusedBeforeTheBackendIsQueried(): void
{
try {
$this->listCollections(['type' => DATABASE_TYPE_VECTORSDB]);
$this->fail('Listing collections of a VectorsDB database on /v1/databases must be refused, not served.');
} catch (Exception $exception) {
$this->assertSame(Exception::DATABASE_NOT_FOUND, $exception->getType());
}
}
public function testADocumentsDatabaseIsRefusedBeforeTheBackendIsQueried(): void
{
try {
$this->listCollections(['type' => DATABASE_TYPE_DOCUMENTSDB]);
$this->fail('Listing collections of a DocumentsDB database on /v1/databases must be refused, not served.');
} catch (Exception $exception) {
$this->assertSame(Exception::DATABASE_NOT_FOUND, $exception->getType());
}
}
/**
* The mismatched call must not reach `database_{sequence}` at all — that query is
* where the 500 came from.
*/
public function testTheRefusedCallNeverReachesTheBackend(): void
{
foreach ([DATABASE_TYPE_VECTORSDB, DATABASE_TYPE_DOCUMENTSDB] as $type) {
$reached = true;
try {
$reached = $this->listCollections(['type' => $type])['reached'];
} catch (Exception) {
$reached = false;
}
$this->assertFalse($reached, "a '{$type}' database must be refused before database_{sequence} is queried");
}
}
/**
* The guard must not over-refuse: the products this path really serves still reach
* the backend.
*/
public function testTheServedTypesStillReachTheBackend(): void
{
foreach ([DATABASE_TYPE_LEGACY, DATABASE_TYPE_TABLESDB] as $type) {
$this->assertTrue(
$this->listCollections(['type' => $type])['reached'],
"a '{$type}' database must still be served by /v1/databases/{id}/collections",
);
}
}
}