Add support for stripe-style identifiers on existing models with UUIDs (#5548)

This is a partial implementation to begin moving towards stripe-style
identifiers for resources in the system. Any models with an existing
`uuid` column can easily be updated to return an identifier in the
format of `prfx_xyz` where `prfx` is a four character prefix, and `xyz`
is the UUID, encoded using base-32.

These are quite easy to use within the API layer because we just need to
do one quick transformation to extract the UUID for those models. This
PR implements that logic for servers in the `SubstituteClientBindings`
logic.

A future PR will need to come through and handle identifiers for models
that _don't_ currently use UUIDs for reference that we want to expose to
clients. In those cases it is easier to just generate base-32 encoded
UUID7s that get stored in the database and indexed. They follow the same
base approach, but you don't need to do any transformations in the code
(other than stripping the prefix, unless we decide to store the prefix).

There is also now a `PTERODACTYL_USE_SERVER_IDENTIFIERS` environment
variable, that when set to true, updates the front-end and API response
to use this new identifier in place of the `uuidShort` value.
This commit is contained in:
Dane Everitt
2026-02-14 11:21:57 -08:00
committed by GitHub
parent 14185a9430
commit a81c3b4d52
19 changed files with 183 additions and 27 deletions
+1
View File
@@ -47,6 +47,7 @@ return (new Config())
'var',
],
],
'phpdoc_no_alias_tag' => false,
// 'random_api_migration' => true,
'ternary_to_null_coalescing' => true,
'yoda_style' => [
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace Pterodactyl\Contracts\Models;
use Illuminate\Database\Eloquent\Builder;
interface Identifiable
{
public function scopeWhereIdentifier(Builder $builder, string $identifier): void;
}
@@ -15,7 +15,13 @@ class SubstituteClientBindings extends SubstituteBindings
// Override default behavior of the model binding to use a specific table
// column rather than the default 'id'.
$this->router->bind('server', function ($value) {
return Server::query()->where(strlen($value) === 8 ? 'uuidShort' : 'uuid', $value)->firstOrFail();
return Server::query()
->when(
str_starts_with($value, 'serv_'),
fn ($builder) => $builder->whereIdentifier($value),
fn ($builder) => $builder->where(strlen($value) === 8 ? 'uuidShort' : 'uuid', $value)
)
->firstOrFail();
});
$this->router->bind('user', function ($value, $route) {
+5 -1
View File
@@ -7,9 +7,11 @@ use Illuminate\Support\Facades\Event;
use Pterodactyl\Events\ActivityLogged;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\MassPrunable;
use Pterodactyl\Contracts\Models\Identifiable;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Illuminate\Database\Eloquent\Model as IlluminateModel;
/**
@@ -48,9 +50,11 @@ use Illuminate\Database\Eloquent\Model as IlluminateModel;
*
* @mixin \Eloquent
*/
class ActivityLog extends Model
#[Attributes\Identifiable('actl')]
class ActivityLog extends Model implements Identifiable
{
use MassPrunable;
use HasRealtimeIdentifier;
public const RESOURCE_NAME = 'activity_log';
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace Pterodactyl\Models\Attributes;
#[\Attribute(\Attribute::TARGET_CLASS)]
readonly class Identifiable
{
public function __construct(public string $prefix, public string $column = 'uuid')
{
}
}
+5 -1
View File
@@ -3,6 +3,8 @@
namespace Pterodactyl\Models;
use Illuminate\Database\Eloquent\SoftDeletes;
use Pterodactyl\Contracts\Models\Identifiable;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -25,11 +27,13 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
* @property Server $server
* @property \Pterodactyl\Models\AuditLog[] $audits
*/
class Backup extends Model
#[Attributes\Identifiable('bkup')]
class Backup extends Model implements Identifiable
{
/** @use HasFactory<\Database\Factories\BackupFactory> */
use HasFactory;
use SoftDeletes;
use HasRealtimeIdentifier;
public const RESOURCE_NAME = 'backup';
+5 -1
View File
@@ -2,7 +2,9 @@
namespace Pterodactyl\Models;
use Pterodactyl\Contracts\Models\Identifiable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -47,10 +49,12 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
* @property Egg|null $scriptFrom
* @property Egg|null $configFrom
*/
class Egg extends Model
#[Attributes\Identifiable('eegg')]
class Egg extends Model implements Identifiable
{
/** @use HasFactory<\Database\Factories\EggFactory> */
use HasFactory;
use HasRealtimeIdentifier;
/**
* The resource name for this model when it is transformed into an
+6 -1
View File
@@ -3,6 +3,8 @@
namespace Pterodactyl\Models;
use Illuminate\Validation\Rules\NotIn;
use Pterodactyl\Contracts\Models\Identifiable;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
/**
@@ -18,8 +20,11 @@ use Illuminate\Database\Eloquent\Relations\BelongsToMany;
* @property \Pterodactyl\Models\Node[]|\Illuminate\Database\Eloquent\Collection $nodes
* @property \Pterodactyl\Models\Server[]|\Illuminate\Database\Eloquent\Collection $servers
*/
class Mount extends Model
#[Attributes\Identifiable('moun')]
class Mount extends Model implements Identifiable
{
use HasRealtimeIdentifier;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
+5 -1
View File
@@ -7,7 +7,9 @@ use Symfony\Component\Yaml\Yaml;
use Illuminate\Container\Container;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Encryption\Encrypter;
use Pterodactyl\Contracts\Models\Identifiable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
@@ -40,11 +42,13 @@ use Illuminate\Database\Eloquent\Relations\HasManyThrough;
* @property \Pterodactyl\Models\Server[]|\Illuminate\Database\Eloquent\Collection $servers
* @property \Pterodactyl\Models\Allocation[]|\Illuminate\Database\Eloquent\Collection $allocations
*/
class Node extends Model
#[Attributes\Identifiable('node')]
class Node extends Model implements Identifiable
{
/** @use HasFactory<\Database\Factories\NodeFactory> */
use HasFactory;
use Notifiable;
use HasRealtimeIdentifier;
/**
* The resource name for this model when it is transformed into an
+5 -2
View File
@@ -5,8 +5,10 @@ namespace Pterodactyl\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Query\JoinClause;
use Znck\Eloquent\Traits\BelongsToThrough;
use Pterodactyl\Contracts\Models\Identifiable;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
@@ -103,19 +105,20 @@ use Pterodactyl\Exceptions\Http\Server\ServerStateConflictException;
*
* @mixin \Eloquent
*/
class Server extends Model
#[Attributes\Identifiable('serv')]
class Server extends Model implements Identifiable
{
/** @use HasFactory<\Database\Factories\ServerFactory> */
use HasFactory;
use BelongsToThrough;
use Notifiable;
use HasRealtimeIdentifier;
/**
* The resource name for this model when it is transformed into an
* API representation using fractal.
*/
public const RESOURCE_NAME = 'server';
public const STATUS_INSTALLING = 'installing';
public const STATUS_INSTALL_FAILED = 'install_failed';
public const STATUS_REINSTALL_FAILED = 'reinstall_failed';
@@ -0,0 +1,73 @@
<?php
namespace Pterodactyl\Models\Traits;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Str;
use Webmozart\Assert\Assert;
use ParagonIE\ConstantTime\Base32;
use Illuminate\Database\Eloquent\Builder;
use Pterodactyl\Models\Attributes\Identifiable;
use Illuminate\Database\Eloquent\Casts\Attribute;
/**
* Support realtime identifiers on models that do not track an "identifier" column in
* the database. This allows us to make use of the existing data reliant on UUID columns
* while still allowing for output and querying against a more human readable identifier
* value.
*
* @property-read string $identifier
*
* @method static Builder whereIdentifier(string $identifier)
*
* @mixin \Illuminate\Database\Eloquent\Model
*/
trait HasRealtimeIdentifier
{
private static string $identifierPrefix;
private static string $identifierDataColumn;
protected function identifier(): Attribute
{
return Attribute::get(function () {
$bytes = Uuid::fromString($this->getRawOriginal(static::$identifierDataColumn))->getBytes();
return sprintf('%s_%s', static::$identifierPrefix, Base32::encodeUnpadded($bytes));
});
}
public function scopeWhereIdentifier(Builder $builder, string $identifier): void
{
if (!str_starts_with($identifier, $prefix = self::$identifierPrefix . '_')) {
$builder->whereRaw('0 = 1');
return;
}
$bytes = rescue(fn () => Base32::decode(Str::replaceFirst($prefix, '', $identifier)), report: false);
if (empty($bytes)) {
$builder->whereRaw('0 = 1');
return;
}
$builder->where(self::$identifierDataColumn, Uuid::fromBytes($bytes)->toString());
}
protected static function bootHasRealtimeIdentifier(): void
{
$attrs = (new \ReflectionClass(static::class))->getAttributes(Identifiable::class);
Assert::count(
$attrs,
1,
'The #[' . Identifiable::class . '] attribute must be set on ' . static::class . ' to use realtime identifiers.'
);
$instance = $attrs[0]->newInstance();
self::$identifierPrefix = $instance->prefix;
self::$identifierDataColumn = $instance->column;
}
}
+9 -2
View File
@@ -9,11 +9,13 @@ use Illuminate\Validation\Rules\In;
use Illuminate\Auth\Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Builder;
use Pterodactyl\Contracts\Models\Identifiable;
use Pterodactyl\Models\Traits\HasAccessTokens;
use Illuminate\Auth\Passwords\CanResetPassword;
use Pterodactyl\Traits\Helpers\AvailableLanguages;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Pterodactyl\Models\Traits\HasRealtimeIdentifier;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
@@ -79,10 +81,12 @@ use Pterodactyl\Notifications\SendPasswordReset as ResetPasswordNotification;
*
* @mixin \Eloquent
*/
#[Attributes\Identifiable('user')]
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
CanResetPasswordContract,
Identifiable
{
use Authenticatable;
use Authorizable;
@@ -93,6 +97,7 @@ class User extends Model implements
use Notifiable;
/** @use \Illuminate\Database\Eloquent\Factories\HasFactory<\Database\Factories\UserFactory> */
use HasFactory;
use HasRealtimeIdentifier;
public const USER_LEVEL_USER = 0;
public const USER_LEVEL_ADMIN = 1;
@@ -193,7 +198,9 @@ class User extends Model implements
*/
public function toVueObject(): array
{
return Collection::make($this->toArray())->except(['id', 'external_id'])->toArray();
return Collection::make($this->toArray())->except(['id', 'external_id'])
->merge(['identifier' => $this->identifier])
->toArray();
}
/**
@@ -38,7 +38,14 @@ class ServerTransformer extends BaseClientTransformer
return [
'server_owner' => $user->id === $server->owner_id,
'identifier' => $server->uuidShort,
'identifier' => config('pterodactyl.features.new_server_identifiers')
? $server->identifier
: $server->uuidShort,
'__deprecated_uuid_short' => $server->uuidShort,
// In Pterodactyl 2.0 we'll be replacing `identifier` above with the actual
// "identifier" used internally. This is a completely different value compared
// to the current however, and would be quite a breaking change to URLs.
'server_identifier' => $server->identifier,
'internal_id' => $server->id,
'uuid' => $server->uuid,
'name' => $server->name,
@@ -23,6 +23,7 @@ class UserTransformer extends BaseClientTransformer
{
return [
'uuid' => $model->uuid,
'identifier' => $model->identifier,
'username' => $model->username,
'email' => $model->email,
'image' => 'https://gravatar.com/avatar/' . md5(Str::lower($model->email)),
+4
View File
@@ -189,4 +189,8 @@ return [
'telemetry' => [
'enabled' => env('PTERODACTYL_TELEMETRY_ENABLED', true),
],
'features' => [
'new_server_identifiers' => (bool) env('PTERODACTYL_USE_SERVER_IDENTIFIERS', false),
],
];
-7
View File
@@ -10,13 +10,6 @@
</testsuites>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_DATABASE" value="testing"/>
<env name="MAIL_MAILER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
</php>
<source>
<include>
+1
View File
@@ -2,6 +2,7 @@ import { MarkRequired } from 'ts-essentials';
import { FractalResponseData, FractalResponseList } from '../http';
export type UUID = string;
export type Identifier<P extends string = string> = `${P}_${string}`;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Model {}
+20 -1
View File
@@ -1,6 +1,7 @@
import http, { FractalResponseData, FractalResponseList } from '@/api/http';
import { rawDataToServerAllocation, rawDataToServerEggVariable } from '@/api/transformers';
import { ServerEggVariable, ServerStatus } from '@/api/server/types';
import { Identifier } from '@/api/definitions';
export interface Allocation {
id: number;
@@ -12,8 +13,24 @@ export interface Allocation {
}
export interface Server {
id: string;
/**
* This value is determined by the presence of the `PTERODACTYL_USE_SERVER_IDENTIFIERS` environment
* variable which changes what the API can respond with. It will eventually be removed and referenced
* as the "identifier" key, but this allows users to slowly opt-in to these new URLs and trial it
* as they wish.
*
* @deprecated this is the "uuid_short" which will be removed in 2.0, prefer use of "identifier"
*/
id: string | Identifier<'serv'>;
identifier: Identifier<'serv'>; // Set from "server_identifier" and should be used moving forward to reference a server.
internalId: number | string;
/**
* Exists only to maintain support in cases where the short-uuid is necessary for server reference
* and cannot be easily replaced with "identifier".
*
* @deprecated
*/
__deprecatedUuidShort: string;
uuid: string;
name: string;
node: string;
@@ -47,7 +64,9 @@ export interface Server {
export const rawDataToServerObject = ({ attributes: data }: FractalResponseData): Server => ({
id: data.identifier,
identifier: data.server_identifier,
internalId: data.internal_id,
__deprecatedUuidShort: data.__deprecated_uuid_short,
uuid: data.uuid,
name: data.name,
node: data.node,
@@ -2,6 +2,7 @@
namespace Pterodactyl\Tests\Integration\Api\Client;
use Ramsey\Uuid\Uuid;
use Pterodactyl\Models\User;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\Subuser;
@@ -53,8 +54,8 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
$servers = [
$this->createServerModel(['user_id' => $users[0]->id, 'name' => 'Julia']),
$this->createServerModel(['user_id' => $users[1]->id, 'uuidShort' => '12121212', 'name' => 'Janice']),
$this->createServerModel(['user_id' => $users[1]->id, 'uuid' => '88788878-12356789', 'external_id' => 'ext123', 'name' => 'Julia']),
$this->createServerModel(['user_id' => $users[1]->id, 'uuid' => '88788878-abcdefgh', 'name' => 'Jennifer']),
$this->createServerModel(['user_id' => $users[1]->id, 'uuid' => Uuid::uuid4()->toString(), 'external_id' => 'ext123', 'name' => 'Julia']),
$this->createServerModel(['user_id' => $users[1]->id, 'uuid' => Uuid::uuid4()->toString(), 'name' => 'Jennifer']),
];
$this->actingAs($users[1])->getJson('/api/client?filter[*]=Julia')
@@ -77,16 +78,14 @@ class ClientControllerTest extends ClientApiIntegrationTestCase
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.attributes.identifier', $servers[1]->uuidShort);
$this->actingAs($users[1])->getJson('/api/client?filter[*]=88788878')
$this->actingAs($users[1])->getJson("/api/client?filter[*]={$servers[2]->uuidShort}")
->assertOk()
->assertJsonCount(2, 'data')
->assertJsonPath('data.0.attributes.identifier', $servers[2]->uuidShort)
->assertJsonPath('data.1.attributes.identifier', $servers[3]->uuidShort);
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.attributes.identifier', $servers[2]->uuidShort);
$this->actingAs($users[1])->getJson('/api/client?filter[*]=88788878-abcd')
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.attributes.identifier', $servers[3]->uuidShort);
->assertJsonCount(0, 'data');
$this->actingAs($users[0])->getJson('/api/client?filter[*]=Julia&type=admin-all')
->assertOk()