1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2026-08-06 16:54:05 +00:00

Merge branch 'master' into broadcasting-fixes

This commit is contained in:
lukinovec 2026-06-29 13:19:26 +02:00 committed by GitHub
commit f20f8016d8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 1586 additions and 210 deletions

View file

@ -16,6 +16,15 @@ use Stancl\Tenancy\Contracts\Tenant;
/**
* Makes cache tenant-aware by applying a prefix.
*
* Using this bootstrapper together with DatabaseTenancyBootstrapper
* with a database cache store will result in "double scoping". The store will be scoped
* by the DB connection (entries will go into the tenant's database) *and* by the prefix.
* This is harmless in most cases, but is important to be aware of.
*
* If you only use database cache stores, consider using DatabaseCacheBootstrapper instead.
*
* @see Stancl\Tenancy\Bootstrappers\DatabaseCacheBootstrapper
*/
class CacheTenancyBootstrapper implements TenancyBootstrapper
{

View file

@ -21,11 +21,15 @@ use Stancl\Tenancy\TenancyServiceProvider;
*
* By default, this bootstrapper scopes ALL cache stores that use the database driver. If you only
* want to scope SOME stores, set the static $stores property to an array of names of the stores
* you want to scope. These stores must use 'database' as their driver.
* you want to scope. Those stores must use 'database' as their driver.
*
* Notably, this bootstrapper sets TenancyServiceProvider::$adjustCacheManagerUsing to a callback
* that ensures all affected stores still use the central connection when accessed via global cache
* (typicaly the GlobalCache facade or global_cache() helper).
* (typically the GlobalCache facade or global_cache() helper). The code in TenancyServiceProvider
* that uses `extend()` callbacks to make database stores on the global cache manager use the central
* connection only corrects stores scoped by the Database*Tenancy*Bootstrapper. This bootstrapper
* also changes the stores' connection in the *config* to 'tenant' which doesn't let that callback
* change the connection back to central on the global cache manager.
*/
class DatabaseCacheBootstrapper implements TenancyBootstrapper
{

View file

@ -5,14 +5,42 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Bootstrappers;
use Exception;
use Illuminate\Support\Facades\Schema;
use RuntimeException;
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\DatabaseManager;
use Stancl\Tenancy\Database\Exceptions\TenantDatabaseDoesNotExistException;
use Throwable;
class DatabaseTenancyBootstrapper implements TenancyBootstrapper
{
/**
* When true, throw an exception if a tenant gets connected to
* another tenant's database or to the central database.
*
* This case should never come up in well-configured apps where
* users cannot set or edit tenant IDs or database names, so this
* option is disabled by default.
*
* However, applications dealing with extremely sensitive data may
* choose to enable this runtime check to prevent a bug or misconfiguration
* from creating an exploit that would let an attacker access another
* tenant's data or data from the central database.
*
* One way such a scenario might come up is if an application allows
* broad tenant attribute updates on a page for updating some fields
* on the tenant, without restricting that action to only a limited
* set of fields that are safe to edit. An attacker might be able to add
* something like ['tenancy_db_name' => '...'] to the request which could
* lead to this internal attribute being updated on an existing tenant.
*
* It's possible that enabling this setting will negate the performance
* benefits of cached tenant lookup.
*/
public static bool $harden = false;
/** @var DatabaseManager */
protected $database;
@ -41,10 +69,39 @@ class DatabaseTenancyBootstrapper implements TenancyBootstrapper
}
$this->database->connectToTenant($tenant);
if (static::$harden) {
try {
$this->verifyTenantCanUseDatabase($tenant);
} catch (Throwable $e) {
// Revert connection back to central
$this->revert();
throw $e;
}
}
}
public function revert(): void
{
$this->database->reconnectToCentral();
}
protected function verifyTenantCanUseDatabase(Tenant $tenant): void
{
/** @var \Stancl\Tenancy\Database\Models\Tenant&TenantWithDatabase $tenant */
$tenantDbName = $tenant->database()->getName();
// Check that no other tenant uses this tenant's database
if ($tenant::where($tenant->getTenantKeyName(), '!=', $tenant->getTenantKey())
->where($tenant::getDataColumn() . '->' . $tenant->internalPrefix() . 'db_name', $tenantDbName)
->exists()) {
throw new RuntimeException('Tenant cannot use a database of another tenant.');
}
if (Schema::hasTable($tenant->getTable())) {
// Throw if the current database/schema has the tenants table (i.e. it's not central)
throw new RuntimeException('Tenant cannot use the central database.');
}
}
}

View file

@ -16,7 +16,7 @@ use Stancl\Tenancy\Resolvers\PathTenantResolver;
/**
* Makes the app use TenancyUrlGenerator (instead of Illuminate\Routing\UrlGenerator) which:
* - prefixes route names with the tenant route name prefix (PathTenantResolver::tenantRouteNamePrefix() by default)
* - passes the tenant parameter to the link generated by route() and temporarySignedRoute() (PathTenantResolver::tenantParameterName() by default).
* - passes the tenant parameter (PathTenantResolver::tenantParameterName() by default) to the link generated by the affected methods like route() and temporarySignedRoute().
*
* Used with path and query string identification.
*

View file

@ -14,6 +14,7 @@ use Stancl\Tenancy\Concerns\ParallelCommand;
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Exceptions\TenantDatabaseDoesNotExistException;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface as OI;
class MigrateFresh extends BaseCommand
@ -72,11 +73,13 @@ class MigrateFresh extends BaseCommand
protected function migrateTenant(TenantWithDatabase $tenant): bool
{
return $this->callSilently('tenants:migrate', [
$output = $this->getOutput()->isVerbose() ? $this->output : new NullOutput;
return $this->runCommand('tenants:migrate', [
'--tenants' => [$tenant->getTenantKey()],
'--step' => $this->option('step'),
'--force' => true,
]) === 0;
], $output) === 0;
}
protected function childHandle(mixed ...$args): bool

View file

@ -17,7 +17,8 @@ class Run extends Command
protected $description = 'Run a command for tenant(s)';
protected $signature = 'tenants:run {commandname : The artisan command.}
{--tenants=* : The tenant(s) to run the command for. Default: all}';
{--tenants=* : The tenant(s) to run the command for. Default: all}
{--skip-tenants=* : The tenant(s) to skip}';
public function handle(): int
{

View file

@ -10,15 +10,16 @@ use Stancl\Tenancy\Database\Concerns\PendingScope;
use Symfony\Component\Console\Input\InputOption;
/**
* Adds 'tenants' and 'with-pending' options.
* Adds 'tenants', 'skip-tenants', and 'with-pending' options.
*/
trait HasTenantOptions
{
protected function getOptions()
{
return array_merge([
new InputOption('tenants', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_OPTIONAL, 'The tenants to run this command for. Leave empty for all tenants', null),
new InputOption('with-pending', null, InputOption::VALUE_NONE, 'Include pending tenants in query'), // todo@pending should we also offer without-pending? if we add this, mention in docs
new InputOption('tenants', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_OPTIONAL, 'The tenants to run this command for. Leave empty for all tenants', null),
new InputOption('skip-tenants', null, InputOption::VALUE_IS_ARRAY|InputOption::VALUE_OPTIONAL, 'The tenants to skip when running this command', null),
new InputOption('with-pending', null, InputOption::VALUE_OPTIONAL, 'Include pending tenants in query if true/1, exclude if false/0. Defaults to the tenancy.pending.include_in_queries config value.'),
], parent::getOptions());
}
@ -42,8 +43,15 @@ trait HasTenantOptions
->when($this->option('tenants'), function ($query) {
$query->whereIn(tenancy()->model()->getTenantKeyName(), $this->option('tenants'));
})
->when($this->option('skip-tenants'), function ($query) {
$query->whereNotIn(tenancy()->model()->getTenantKeyName(), $this->option('skip-tenants'));
})
->when(tenancy()->model()::hasGlobalScope(PendingScope::class), function ($query) {
$query->withPending(config('tenancy.pending.include_in_queries') ?: $this->option('with-pending'));
$includePending = $this->input->hasParameterOption('--with-pending')
? filter_var($this->option('with-pending') ?? true, FILTER_VALIDATE_BOOLEAN)
: config('tenancy.pending.include_in_queries');
$query->withPending($includePending);
});
}

View file

@ -28,6 +28,18 @@ trait HasPending
public static function bootHasPending(): void
{
static::addGlobalScope(new PendingScope());
static::creating(function (self $tenant): void {
if ($tenant->pending()) {
event(new CreatingPendingTenant($tenant));
}
});
static::created(function (self $tenant): void {
if ($tenant->pending()) {
event(new PendingTenantCreated($tenant));
}
});
}
/** Initialize the trait. */
@ -49,22 +61,11 @@ trait HasPending
*/
public static function createPending(array $attributes = []): Model&Tenant
{
$tenant = null;
try {
$tenant = static::create(array_merge(static::getPendingAttributes($attributes), $attributes));
event(new CreatingPendingTenant($tenant));
} finally {
// Update the pending_since value only after the tenant is created so it's
// not marked as pending until after migrations, seeders, etc are run.
$tenant?->update([
'pending_since' => now()->timestamp,
]);
}
event(new PendingTenantCreated($tenant));
return $tenant;
return static::create(array_merge(
static::getPendingAttributes($attributes),
$attributes,
['pending_since' => now()->timestamp],
));
}
/**
@ -99,27 +100,51 @@ trait HasPending
*/
public static function pullPendingFromPool(bool $firstOrCreate = false, array $attributes = []): ?Tenant
{
$tenant = DB::transaction(function () use ($attributes): ?Tenant {
/** @var (Model&Tenant)|null $tenant */
$tenant = static::onlyPending()->first();
// Attempt pulling a pending tenant.
// The loop handles the case where a single tenant is being pulled by multiple processes at the same time.
// If a tenant was pulled by a concurrent process, try pulling the next one in the pool.
while (true) {
/** @var (Model&Tenant)|null $pullCandidate */
$pullCandidate = static::onlyPending()->first();
if ($tenant !== null) {
event(new PullingPendingTenant($tenant));
$tenant->update(array_merge($attributes, [
'pending_since' => null,
]));
if ($pullCandidate === null) {
return $firstOrCreate ? static::create($attributes) : null;
}
// Fired before the claim, so it can fire once per attempt, including for a candidate
// that ends up being claimed by a different process (in which case the loop retries).
// PendingTenantPulled (below) fires exactly once, for the actually pulled tenant.
event(new PullingPendingTenant($pullCandidate));
$tenant = DB::transaction(function () use ($pullCandidate, $attributes): ?Tenant {
$tenantWasPulled = static::onlyPending()
->whereKey($pullCandidate->getKey())
->update([$pullCandidate->getColumnForQuery('pending_since') => null]) > 0;
if (! $tenantWasPulled) {
return null;
}
// The tenant's pending_since was just cleared, and a PullingPendingTenant listener
// may have made changes to the tenant, so re-fetch it to make sure it's up to date.
/** @var Model&Tenant $pulledTenant */
$pulledTenant = static::findOrFail($pullCandidate->getKey());
if (! empty($attributes)) {
$pulledTenant->update($attributes);
}
return $pulledTenant;
});
if ($tenant === null) {
// If another pull claimed this tenant first, try claiming the next one
continue;
}
event(new PendingTenantPulled($tenant));
return $tenant;
});
if ($tenant === null) {
return $firstOrCreate ? static::create($attributes) : null;
}
// Only triggered if a tenant that was pulled from the pool is returned
event(new PendingTenantPulled($tenant));
return $tenant;
}
}

View file

@ -28,6 +28,9 @@ trait ManagesPostgresUsers
$username = $databaseConfig->getUsername();
$password = $databaseConfig->getPassword();
$this->validateParameter($username);
$this->validatePassword($password);
$createUser = ! $this->userExists($username);
if ($createUser) {
@ -44,6 +47,8 @@ trait ManagesPostgresUsers
// Tenant DB username
$username = $databaseConfig->getUsername();
$this->validateParameter($username);
// Tenant host connection config
$connectionName = $this->connection()->getConfig('name');
$centralDatabase = $this->connection()->getConfig('database');
@ -77,6 +82,6 @@ trait ManagesPostgresUsers
public function userExists(string $username): bool
{
return (bool) $this->connection()->selectOne("SELECT usename FROM pg_user WHERE usename = '{$username}'");
return (bool) $this->connection()->select('SELECT usename FROM pg_user WHERE usename = ?', [$username]);
}
}

View file

@ -14,7 +14,7 @@ class PendingScope implements Scope
/**
* Apply the scope to a given Eloquent query builder.
*
* @param Builder<Model> $builder
* @param Builder<covariant Model> $builder
*
* @return void
*/
@ -58,8 +58,10 @@ class PendingScope implements Scope
{
$builder->macro('withoutPending', function (Builder $builder) {
$builder->withoutGlobalScope(static::class)
->whereNull($builder->getModel()->getColumnForQuery('pending_since'))
->orWhereNull($builder->getModel()->getDataColumn());
->where(function (Builder $query) {
$query->whereNull($query->getModel()->getColumnForQuery('pending_since'))
->orWhereNull($query->getModel()->getDataColumn());
});
return $builder;
});

View file

@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Database\Concerns;
use InvalidArgumentException;
/**
* Provides methods to validate database parameters (e.g. database names, usernames, passwords)
* before using them in SQL statements (or in file paths in the case of SQLiteDatabaseManager).
*
* Used where parameters can be provided by users, and where parameter binding cannot be used.
*
* @see \Stancl\Tenancy\Database\TenantDatabaseManagers\TenantDatabaseManager
* @see \Stancl\Tenancy\Database\TenantDatabaseManagers\SQLiteDatabaseManager
*/
trait ValidatesDatabaseParameters
{
/**
* Characters allowed in parameters.
*
* Used as the default allowlist in validateParameter(), which validates non-password
* parameters such as database names or usernames.
*
* Since non-password parameters don't need to use as many special characters, we use
* a stricter allowlist here.
*/
public static string $allowedParameterCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
/**
* Characters allowed in database user passwords.
*
* The allowlist for passwords is less strict than for other parameters
* because it's more common to use more special characters in passwords.
*/
public static string $allowedPasswordCharacters = ' !#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~';
/**
* Ensure that parameter (database name, username, etc.)
* only contains allowed characters before being used in SQL statements
* (or paths in the case of SQLiteDatabaseManager).
*
* By default, only the characters in $allowedParameterCharacters are allowed.
*
* @throws InvalidArgumentException
*/
protected function validateParameter(mixed $parameter, string|null $allowedCharacters = null): void
{
if (is_null($parameter)) {
throw new InvalidArgumentException('Parameter cannot be null.');
}
if (is_numeric($parameter)) {
$parameter = (string) $parameter;
}
if (! is_string($parameter)) {
throw new InvalidArgumentException('Parameter has to be a string.');
}
if ($parameter === '') {
throw new InvalidArgumentException('Parameter cannot be an empty string.');
}
$allowedCharacters ??= static::$allowedParameterCharacters;
foreach (str_split($parameter) as $character) {
if (! str_contains($allowedCharacters, $character)) {
throw new InvalidArgumentException("Forbidden character '{$character}' in parameter.");
}
}
}
/**
* Ensure password only contains allowed characters ($allowedPasswordCharacters)
* before being used in SQL statements.
*
* Used in permission controlled managers as a shorthand for calling validateParameter()
* with the less strict allowlist to validate database user passwords.
*
* @throws InvalidArgumentException
*/
protected function validatePassword(string|null $password): void
{
if (is_null($password)) {
throw new InvalidArgumentException('Password cannot be null.');
}
if ($password === '') {
throw new InvalidArgumentException('Password cannot be an empty string.');
}
$this->validateParameter($password, allowedCharacters: static::$allowedPasswordCharacters);
}
}

View file

@ -12,7 +12,7 @@ use Illuminate\Database\Eloquent\Scope;
class ParentModelScope implements Scope
{
/**
* @param Builder<Model> $builder
* @param Builder<covariant Model> $builder
*/
public function apply(Builder $builder, Model $model): void
{

View file

@ -12,16 +12,22 @@ class MicrosoftSQLDatabaseManager extends TenantDatabaseManager
{
$database = $tenant->database()->getName();
$this->validateParameter($database);
return $this->connection()->statement("CREATE DATABASE [{$database}]");
}
public function deleteDatabase(TenantWithDatabase $tenant): bool
{
return $this->connection()->statement("DROP DATABASE [{$tenant->database()->getName()}]");
$database = $tenant->database()->getName();
$this->validateParameter($database);
return $this->connection()->statement("DROP DATABASE [{$database}]");
}
public function databaseExists(string $name): bool
{
return (bool) $this->connection()->select("SELECT name FROM master.sys.databases WHERE name = '$name'");
return (bool) $this->connection()->select('SELECT name FROM master.sys.databases WHERE name = ?', [$name]);
}
}

View file

@ -14,16 +14,38 @@ class MySQLDatabaseManager extends TenantDatabaseManager
$charset = $this->connection()->getConfig('charset');
$collation = $this->connection()->getConfig('collation');
return $this->connection()->statement("CREATE DATABASE `{$database}` CHARACTER SET `$charset` COLLATE `$collation`");
$this->validateParameter($database);
// MySQL defaults to the server's charset and collation
// if charset and collation are not specified.
// If charset is specified but collation is null, MySQL
// will choose a default collation for the specified charset (and vice versa).
$statement = "CREATE DATABASE `{$database}`";
if ($charset !== null) {
$this->validateParameter($charset);
$statement .= " CHARACTER SET `{$charset}`";
}
if ($collation !== null) {
$this->validateParameter($collation);
$statement .= " COLLATE `{$collation}`";
}
return $this->connection()->statement($statement);
}
public function deleteDatabase(TenantWithDatabase $tenant): bool
{
return $this->connection()->statement("DROP DATABASE `{$tenant->database()->getName()}`");
$database = $tenant->database()->getName();
$this->validateParameter($database);
return $this->connection()->statement("DROP DATABASE `{$database}`");
}
public function databaseExists(string $name): bool
{
return (bool) $this->connection()->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$name'");
return (bool) $this->connection()->select('SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?', [$name]);
}
}

View file

@ -24,6 +24,10 @@ class PermissionControlledMicrosoftSQLServerDatabaseManager extends MicrosoftSQL
$username = $databaseConfig->getUsername();
$password = $databaseConfig->getPassword();
$this->validateParameter($database);
$this->validateParameter($username);
$this->validatePassword($password);
// Create login
$this->connection()->statement("CREATE LOGIN [$username] WITH PASSWORD = '$password'");
@ -37,12 +41,16 @@ class PermissionControlledMicrosoftSQLServerDatabaseManager extends MicrosoftSQL
public function deleteUser(DatabaseConfig $databaseConfig): bool
{
return $this->connection()->statement("DROP LOGIN [{$databaseConfig->getUsername()}]");
$username = $databaseConfig->getUsername();
$this->validateParameter($username);
return $this->connection()->statement("DROP LOGIN [{$username}]");
}
public function userExists(string $username): bool
{
return (bool) $this->connection()->select("SELECT sp.name as username FROM sys.server_principals sp WHERE sp.name = '{$username}'");
return (bool) $this->connection()->select('SELECT sp.name as username FROM sys.server_principals sp WHERE sp.name = ?', [$username]);
}
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
@ -54,11 +62,15 @@ class PermissionControlledMicrosoftSQLServerDatabaseManager extends MicrosoftSQL
public function deleteDatabase(TenantWithDatabase $tenant): bool
{
$name = $tenant->database()->getName();
$this->validateParameter($name);
// Close all connections to the database before deleting it
// Set the database to SINGLE_USER mode to ensure that
// No other connections are using the database while we're trying to delete it
// Rollback all active transactions
$this->connection()->statement("ALTER DATABASE [{$tenant->database()->getName()}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;");
$this->connection()->statement("ALTER DATABASE [{$name}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;");
return parent::deleteDatabase($tenant);
}

View file

@ -25,6 +25,10 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
$username = $databaseConfig->getUsername();
$password = $databaseConfig->getPassword();
$this->validateParameter($database);
$this->validateParameter($username);
$this->validatePassword($password);
$this->connection()->statement("CREATE USER `{$username}`@`%` IDENTIFIED BY '{$password}'");
$grants = implode(', ', static::$grants);
@ -48,11 +52,15 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl
public function deleteUser(DatabaseConfig $databaseConfig): bool
{
return $this->connection()->statement("DROP USER IF EXISTS '{$databaseConfig->getUsername()}'");
$username = $databaseConfig->getUsername();
$this->validateParameter($username);
return $this->connection()->statement("DROP USER IF EXISTS '{$username}'");
}
public function userExists(string $username): bool
{
return (bool) $this->connection()->select("SELECT count(*) FROM mysql.user WHERE user = '$username'")[0]->{'count(*)'};
return (bool) $this->connection()->select('SELECT count(*) FROM mysql.user WHERE user = ?', [$username])[0]->{'count(*)'};
}
}

View file

@ -20,6 +20,10 @@ class PermissionControlledPostgreSQLDatabaseManager extends PostgreSQLDatabaseMa
$username = $databaseConfig->getUsername();
$schema = $databaseConfig->connection()['search_path'];
$this->validateParameter($database);
$this->validateParameter($username);
$this->validateParameter($schema);
// Host config
$connectionName = $this->connection()->getConfig('name');
$centralDatabase = $this->connection()->getConfig('database');
@ -32,10 +36,10 @@ class PermissionControlledPostgreSQLDatabaseManager extends PostgreSQLDatabaseMa
$this->connection()->reconnect();
// Grant permissions to create and use tables in the configured schema ("public" by default) to the user
$this->connection()->statement("GRANT USAGE, CREATE ON SCHEMA {$schema} TO \"{$username}\"");
$this->connection()->statement("GRANT USAGE, CREATE ON SCHEMA \"{$schema}\" TO \"{$username}\"");
// Grant permissions to use sequences in the current schema to the user
$this->connection()->statement("GRANT USAGE ON ALL SEQUENCES IN SCHEMA {$schema} TO \"{$username}\"");
$this->connection()->statement("GRANT USAGE ON ALL SEQUENCES IN SCHEMA \"{$schema}\" TO \"{$username}\"");
// Reconnect to central database
config(["database.connections.{$connectionName}.database" => $centralDatabase]);

View file

@ -23,23 +23,27 @@ class PermissionControlledPostgreSQLSchemaManager extends PostgreSQLSchemaManage
// Central database name
$database = DB::connection(config('tenancy.database.central_connection'))->getDatabaseName();
$this->connection()->statement("GRANT CONNECT ON DATABASE {$database} TO \"{$username}\"");
$this->validateParameter($username);
$this->validateParameter($schema);
$this->validateParameter($database);
$this->connection()->statement("GRANT CONNECT ON DATABASE \"{$database}\" TO \"{$username}\"");
$this->connection()->statement("GRANT USAGE, CREATE ON SCHEMA \"{$schema}\" TO \"{$username}\"");
$this->connection()->statement("GRANT USAGE ON ALL SEQUENCES IN SCHEMA \"{$schema}\" TO \"{$username}\"");
$tables = $this->connection()->select("SELECT table_name FROM information_schema.tables WHERE table_schema = '{$schema}' AND table_type = 'BASE TABLE'");
$tables = $this->connection()->select("SELECT table_name FROM information_schema.tables WHERE table_schema = ? AND table_type = 'BASE TABLE'", [$schema]);
// Grant permissions to any existing tables. This is used with RLS
foreach ($tables as $table) {
$tableName = $table->table_name;
/** @var string $primaryKey */
$primaryKey = $this->connection()->selectOne(<<<SQL
$primaryKey = $this->connection()->selectOne(<<<'SQL'
SELECT column_name
FROM information_schema.key_column_usage
WHERE table_name = '{$tableName}'
WHERE table_name = ?
AND constraint_name LIKE '%_pkey'
SQL)->column_name;
SQL, [$tableName])->column_name;
// Grant all permissions for all existing tables
$this->connection()->statement("GRANT ALL ON \"{$schema}\".\"{$tableName}\" TO \"{$username}\"");

View file

@ -10,16 +10,24 @@ class PostgreSQLDatabaseManager extends TenantDatabaseManager
{
public function createDatabase(TenantWithDatabase $tenant): bool
{
return $this->connection()->statement("CREATE DATABASE \"{$tenant->database()->getName()}\" WITH TEMPLATE=template0");
$name = $tenant->database()->getName();
$this->validateParameter($name);
return $this->connection()->statement("CREATE DATABASE \"{$name}\" WITH TEMPLATE=template0");
}
public function deleteDatabase(TenantWithDatabase $tenant): bool
{
return $this->connection()->statement("DROP DATABASE \"{$tenant->database()->getName()}\"");
$name = $tenant->database()->getName();
$this->validateParameter($name);
return $this->connection()->statement("DROP DATABASE \"{$name}\"");
}
public function databaseExists(string $name): bool
{
return (bool) $this->connection()->selectOne("SELECT datname FROM pg_database WHERE datname = '$name'");
return (bool) $this->connection()->select('SELECT datname FROM pg_database WHERE datname = ?', [$name]);
}
}

View file

@ -10,17 +10,25 @@ class PostgreSQLSchemaManager extends TenantDatabaseManager
{
public function createDatabase(TenantWithDatabase $tenant): bool
{
return $this->connection()->statement("CREATE SCHEMA \"{$tenant->database()->getName()}\"");
$name = $tenant->database()->getName();
$this->validateParameter($name);
return $this->connection()->statement("CREATE SCHEMA \"{$name}\"");
}
public function deleteDatabase(TenantWithDatabase $tenant): bool
{
return $this->connection()->statement("DROP SCHEMA \"{$tenant->database()->getName()}\" CASCADE");
$name = $tenant->database()->getName();
$this->validateParameter($name);
return $this->connection()->statement("DROP SCHEMA \"{$name}\" CASCADE");
}
public function databaseExists(string $name): bool
{
return (bool) $this->connection()->select("SELECT schema_name FROM information_schema.schemata WHERE schema_name = '$name'");
return (bool) $this->connection()->select('SELECT schema_name FROM information_schema.schemata WHERE schema_name = ?', [$name]);
}
public function makeConnectionConfig(array $baseConfig, string $databaseName): array

View file

@ -6,13 +6,17 @@ namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
use Closure;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
use PDO;
use Stancl\Tenancy\Database\Concerns\ValidatesDatabaseParameters;
use Stancl\Tenancy\Database\Contracts\TenantDatabaseManager;
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
use Throwable;
class SQLiteDatabaseManager implements TenantDatabaseManager
{
use ValidatesDatabaseParameters;
/**
* SQLite database directory path.
*
@ -57,6 +61,13 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
*/
public static Closure|null $closeInMemoryConnectionUsing = null;
/**
* Characters allowed in database names.
*
* Includes dots to support file extensions (e.g. '.sqlite').
*/
public static string $allowedDatabaseNameCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.';
public function createDatabase(TenantWithDatabase $tenant): bool
{
/** @var TenantWithDatabase&Model $tenant */
@ -122,6 +133,9 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
public function makeConnectionConfig(array $baseConfig, string $databaseName): array
{
if ($this->isInMemory($databaseName)) {
// Named in-memory DBs are formatted like 'file:_tenancy_inmemory_tenant123?mode=memory&cache=shared'
$this->validateDatabaseName($databaseName, extraAllowedCharacters: ':?=&');
$baseConfig['database'] = $databaseName;
if (static::$persistInMemoryConnectionUsing !== null) {
@ -129,7 +143,7 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
(static::$persistInMemoryConnectionUsing)(new PDO($dsn), $dsn);
}
} else {
$baseConfig['database'] = database_path($databaseName);
$baseConfig['database'] = $this->getPath($databaseName);
}
return $baseConfig;
@ -137,6 +151,8 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
public function getPath(string $name): string
{
$this->validateDatabaseName($name);
if (static::$path) {
return rtrim(static::$path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $name;
}
@ -146,6 +162,28 @@ class SQLiteDatabaseManager implements TenantDatabaseManager
public static function isInMemory(string $name): bool
{
return $name === ':memory:' || str_contains($name, '_tenancy_inmemory_');
$isNamed = str_starts_with($name, 'file:_tenancy_inmemory_') &&
str_ends_with($name, '?mode=memory&cache=shared');
return $name === ':memory:' || $isNamed;
}
/**
* Ensure database name only contains allowed characters
* (allowedDatabaseNameCharacters() + $extraAllowedCharacters) and is not a directory name.
*
* @throws InvalidArgumentException
*/
protected function validateDatabaseName(string $name, string $extraAllowedCharacters = ''): void
{
$this->validateParameter($name, static::$allowedDatabaseNameCharacters . $extraAllowedCharacters);
if ($name === '') {
throw new InvalidArgumentException('Database name cannot be empty.');
}
if (is_dir($name)) {
throw new InvalidArgumentException('Database name cannot be a directory.');
}
}
}

View file

@ -6,11 +6,14 @@ namespace Stancl\Tenancy\Database\TenantDatabaseManagers;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Stancl\Tenancy\Database\Concerns\ValidatesDatabaseParameters;
use Stancl\Tenancy\Database\Contracts\StatefulTenantDatabaseManager;
use Stancl\Tenancy\Database\Exceptions\NoConnectionSetException;
abstract class TenantDatabaseManager implements StatefulTenantDatabaseManager
{
use ValidatesDatabaseParameters;
/** The database connection to the server. */
protected string $connection;

View file

@ -13,7 +13,7 @@ use Stancl\Tenancy\Tenancy;
class TenantScope implements Scope
{
/**
* @param Builder<Model> $builder
* @param Builder<covariant Model> $builder
*/
public function apply(Builder $builder, Model $model)
{

View file

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Features;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
@ -61,9 +62,9 @@ class UserImpersonation implements Feature
Auth::guard($token->auth_guard)->loginUsingId($token->user_id, $token->remember);
$token->delete();
session()->put('tenancy_impersonation_guard', $token->auth_guard);
session()->put('tenancy_impersonating', true);
$token->delete();
return redirect($token->redirect_url);
}
@ -76,16 +77,30 @@ class UserImpersonation implements Feature
public static function isImpersonating(): bool
{
return session()->has('tenancy_impersonating');
return session()->has('tenancy_impersonation_guard');
}
/**
* Logout from the current domain and forget impersonation session.
* Stop user impersonation by forgetting the impersonation session.
*
* When $logout is true, the user will also be logged out
* from the impersonation guard stored in the session.
*
* Throws an exception if impersonation is not active
* (= the impersonation guard is not in the session).
*/
public static function stopImpersonating(): void
public static function stopImpersonating(bool $logout = true): void
{
auth()->logout();
if (! static::isImpersonating()) {
throw new Exception('Not currently impersonating any user.');
}
session()->forget('tenancy_impersonating');
if ($logout) {
$guard = session()->get('tenancy_impersonation_guard');
auth($guard)->logout();
}
session()->forget('tenancy_impersonation_guard');
}
}

View file

@ -22,12 +22,34 @@ class DeleteDatabase implements ShouldQueue
protected TenantWithDatabase&Model $tenant,
) {}
/** Skip database deletion if the create_database internal attribute is false. */
public static bool $skipWhenCreateDatabaseIsFalse = true;
/** Ignore exceptions thrown during database deletion and continue execution. */
public static bool $ignoreFailures = false;
public function handle(): void
{
if (static::$skipWhenCreateDatabaseIsFalse && $this->tenant->getInternal('create_database') === false) {
// If database creation was skipped, we presume deletion should also be skipped.
// To avoid this skip, either unset the `create_database` attribute (or make it true), or
// set the $skipWhenCreateDatabaseIsFalse static property to false.
return;
}
event(new DeletingDatabase($this->tenant));
$this->tenant->database()->manager()->deleteDatabase($this->tenant);
$deleted = false;
event(new DatabaseDeleted($this->tenant));
try {
$this->tenant->database()->manager()->deleteDatabase($this->tenant);
$deleted = true;
} catch (\Throwable $e) {
if (! static::$ignoreFailures) {
throw $e;
}
}
if ($deleted) event(new DatabaseDeleted($this->tenant));
}
}

View file

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Stancl\Tenancy\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use Stancl\Tenancy\Contracts\Tenant;
class DeleteTenantStorage implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public Tenant $tenant,
) {}
public function handle(): void
{
if (config('tenancy.filesystem.suffix_storage_path') === false) {
// Skip storage deletion if path suffixing is disabled
return;
}
$centralStoragePath = tenancy()->central(fn () => storage_path());
$tenantStoragePath = tenancy()->run($this->tenant, fn () => storage_path());
if ($tenantStoragePath === $centralStoragePath) {
// Check again to ensure the tenant storage path is distinct from the central storage path
// to avoid any accidental central storage path deletion
return;
}
if (is_dir($tenantStoragePath)) {
File::deleteDirectory($tenantStoragePath);
}
}
}

View file

@ -17,6 +17,16 @@ class MigrateDatabase implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Should pending tenants be included while migrating,
* regardless of the tenancy.pending.include_in_queries config value.
*
* If false, pending tenants will be specifically excluded.
*
* If null, default to tenancy.pending.include_in_queries config.
*/
public static ?bool $includePending = true;
public function __construct(
protected TenantWithDatabase&Model $tenant,
) {}
@ -25,6 +35,7 @@ class MigrateDatabase implements ShouldQueue
{
Artisan::call('tenants:migrate', [
'--tenants' => [$this->tenant->getTenantKey()],
'--with-pending' => static::$includePending ?? config('tenancy.pending.include_in_queries'),
]);
}
}

View file

@ -17,6 +17,16 @@ class SeedDatabase implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Should pending tenants be included while seeding,
* regardless of the tenancy.pending.include_in_queries config value.
*
* If false, pending tenants will be specifically excluded.
*
* If null, default to tenancy.pending.include_in_queries config.
*/
public static ?bool $includePending = true;
public function __construct(
protected TenantWithDatabase&Model $tenant,
) {}
@ -25,6 +35,7 @@ class SeedDatabase implements ShouldQueue
{
Artisan::call('tenants:seed', [
'--tenants' => [$this->tenant->getTenantKey()],
'--with-pending' => static::$includePending ?? config('tenancy.pending.include_in_queries'),
]);
}
}

View file

@ -7,11 +7,7 @@ namespace Stancl\Tenancy\Listeners;
use Stancl\Tenancy\Events\Contracts\TenantEvent;
/**
* Can be used to manually create framework directories in the tenant storage when storage_path() is scoped.
*
* Useful when using real-time facades which use the framework/cache directory.
*
* Generally not needed anymore as the directory is also created by the FilesystemTenancyBootstrapper.
* @deprecated FilesystemTenancyBootstrapper creates the path automatically when suffix_storage_path is enabled.
*/
class CreateTenantStorage
{

View file

@ -7,14 +7,29 @@ namespace Stancl\Tenancy\Listeners;
use Illuminate\Support\Facades\File;
use Stancl\Tenancy\Events\Contracts\TenantEvent;
/**
* @deprecated Use Stancl\Tenancy\Jobs\DeleteTenantStorage in a job pipeline instead.
*/
class DeleteTenantStorage
{
public function handle(TenantEvent $event): void
{
$path = tenancy()->run($event->tenant, fn () => storage_path());
if (config('tenancy.filesystem.suffix_storage_path') === false) {
// Skip storage deletion if path suffixing is disabled
return;
}
if (is_dir($path)) {
File::deleteDirectory($path);
$centralStoragePath = tenancy()->central(fn () => storage_path());
$tenantStoragePath = tenancy()->run($event->tenant, fn () => storage_path());
if ($tenantStoragePath === $centralStoragePath) {
// Check again to ensure the tenant storage path is distinct from the central storage path
// to avoid any accidental central storage path deletion
return;
}
if (is_dir($tenantStoragePath)) {
File::deleteDirectory($tenantStoragePath);
}
}
}

View file

@ -31,10 +31,12 @@ class PreventAccessFromUnwantedDomains
{
$route = tenancy()->getRoute($request);
if ($this->shouldBeSkipped($route) || tenancy()->routeIsUniversal($route)) {
if ($this->shouldBeSkipped($route)) {
return $next($request);
}
// If the route is universal, neither of these checks will pass and the logic will
// fall through to the $next($request) call at the end.
if ($this->accessingTenantRouteFromCentralDomain($request, $route) || $this->accessingCentralRouteFromTenantDomain($request, $route)) {
$abortRequest = static::$abortRequest ?? function () {
abort(404);

View file

@ -22,16 +22,18 @@ use Stancl\Tenancy\Resolvers\RequestDataTenantResolver;
* - Automatically passing ['tenant' => ...] to each route() call -- if TenancyUrlGenerator::$passTenantParameterToRoutes is enabled
* This is a more universal solution since it supports both path identification and query parameter identification.
*
* - Prepends route names passed to route() and URL::temporarySignedRoute()
* with `tenant.` (or the configured prefix) if $prefixRouteNames is enabled.
* - Prepends route names with the tenant route name prefix ('tenant.' by default,
* configurable at tenant_route_name_prefix under PathTenantResolver) if $prefixRouteNames is enabled.
* This is primarily useful when using route cloning with path identification.
*
* To bypass this behavior on any single route() call, pass the $bypassParameter as true (['central' => true] by default).
* Affected methods: route(), toRoute(), temporarySignedRoute(), signedRoute() (the last two via the route() override).
*
* To bypass this behavior on any single affected method call, pass the $bypassParameter as true (['central' => true] by default).
*/
class TenancyUrlGenerator extends UrlGenerator
{
/**
* Parameter which works as a flag for bypassing the behavior modification of route() and temporarySignedRoute().
* Parameter which works as a flag for bypassing the behavior modification of the affected methods.
*
* For example, in tenant context:
* Route::get('/', ...)->name('home');
@ -44,12 +46,12 @@ class TenancyUrlGenerator extends UrlGenerator
* Note: UrlGeneratorBootstrapper::$addTenantParameterToDefaults is not affected by this, though
* it doesn't matter since it doesn't pass any extra parameters when not needed.
*
* @see UrlGeneratorBootstrapper
* @see Stancl\Tenancy\Bootstrappers\UrlGeneratorBootstrapper
*/
public static string $bypassParameter = 'central';
/**
* Should route names passed to route() or temporarySignedRoute()
* Should route names passed to the affected methods
* get prefixed with the tenant route name prefix.
*
* This is useful when using e.g. path identification with third-party packages
@ -59,12 +61,12 @@ class TenancyUrlGenerator extends UrlGenerator
public static bool $prefixRouteNames = false;
/**
* Should the tenant parameter be passed to route() or temporarySignedRoute() calls.
* Should the tenant parameter be passed to the affected methods.
*
* This is useful with path or query parameter identification. The former can be handled
* more elegantly using UrlGeneratorBootstrapper::$addTenantParameterToDefaults.
*
* @see UrlGeneratorBootstrapper
* @see Stancl\Tenancy\Bootstrappers\UrlGeneratorBootstrapper
*/
public static bool $passTenantParameterToRoutes = false;
@ -105,8 +107,18 @@ class TenancyUrlGenerator extends UrlGenerator
public static bool $passQueryParameter = true;
/**
* Override the route() method so that the route name gets prefixed
* and the tenant parameter gets added when in tenant context.
* Override the route() method to prefix the route name before $this->routes->getByName($name) is called
* in the parent route() call.
*
* This is necessary because $this->routes->getByName($name) is called to retrieve the route
* before passing it to toRoute(). If only the prefixed route (e.g. 'tenant.foo') is registered
* and the original ('foo') isn't, route() would throw a RouteNotFoundException.
* So route() has to be overridden to prefix the passed route name, even though toRoute() is overridden already.
*
* Only the name is taken from prepareRouteInputs() here parameter handling
* (adding tenant parameter, removing bypass parameter) is delegated to toRoute().
*
* Affects temporarySignedRoute() and signedRoute() as well since they call route() under the hood.
*/
public function route($name, $parameters = [], $absolute = true)
{
@ -114,32 +126,28 @@ class TenancyUrlGenerator extends UrlGenerator
throw new InvalidArgumentException('Attribute [name] expects a string backed enum.');
}
[$name, $parameters] = $this->prepareRouteInputs($name, Arr::wrap($parameters)); // @phpstan-ignore argument.type
[$name] = $this->prepareRouteInputs(Arr::wrap($parameters), $name); // @phpstan-ignore argument.type
return parent::route($name, $parameters, $absolute);
}
/**
* Override the temporarySignedRoute() method so that the route name gets prefixed
* and the tenant parameter gets added when in tenant context.
* Override the toRoute() to prefix the route name
* and add the tenant parameter when in tenant context.
*
* Also affects route(). Even though route() is overridden separately, it delegates parameter handling to toRoute().
*/
public function temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true)
public function toRoute($route, $parameters, $absolute)
{
if ($name instanceof BackedEnum && ! is_string($name = $name->value)) {
throw new InvalidArgumentException('Attribute [name] expects a string backed enum.');
$name = $route->getName();
[$prefixedName, $parameters] = $this->prepareRouteInputs(Arr::wrap($parameters), $name);
if ($name && $prefixedName !== $name && $tenantRoute = $this->routes->getByName($prefixedName)) {
$route = $tenantRoute;
}
$wrappedParameters = Arr::wrap($parameters);
[$name, $parameters] = $this->prepareRouteInputs($name, $wrappedParameters); // @phpstan-ignore argument.type
if (isset($wrappedParameters[static::$bypassParameter])) {
// If the bypass parameter was passed, we need to add it back to the parameters after prepareRouteInputs() removes it,
// so that the underlying route() call in parent::temporarySignedRoute() can bypass the behavior modification as well.
$parameters[static::$bypassParameter] = $wrappedParameters[static::$bypassParameter];
}
return parent::temporarySignedRoute($name, $expiration, $parameters, $absolute);
return parent::toRoute($route, $parameters, $absolute);
}
/**
@ -155,16 +163,19 @@ class TenancyUrlGenerator extends UrlGenerator
}
/**
* Takes a route name and an array of parameters to return the prefixed route name
* Takes an array of parameters and a route name to return the prefixed route name
* and the route parameters with the tenant parameter added.
*
* To skip these modifications, pass the bypass parameter in route parameters.
* Before returning the modified route inputs, the bypass parameter is removed from the parameters.
*/
protected function prepareRouteInputs(string $name, array $parameters): array
protected function prepareRouteInputs(array $parameters, string|null $name): array
{
if (! $this->routeBehaviorModificationBypassed($parameters)) {
$name = $this->routeNameOverride($name) ?? $this->prefixRouteName($name);
if (! is_null($name)) {
$name = $this->routeNameOverride($name) ?? $this->prefixRouteName($name);
}
$parameters = $this->addTenantParameter($parameters);
}

View file

@ -7,6 +7,7 @@ namespace Stancl\Tenancy\Resolvers;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Stancl\Tenancy\Contracts\Domain;
use Stancl\Tenancy\Contracts\SingleDomainTenant;
@ -58,7 +59,19 @@ class DomainTenantResolver extends Contracts\CachedTenantResolver
public static function isSubdomain(string $domain): bool
{
return Str::endsWith($domain, config('tenancy.identification.central_domains'));
$centralDomains = Arr::wrap(config('tenancy.identification.central_domains'));
if (in_array($domain, $centralDomains, true)) {
return false;
}
foreach ($centralDomains as $centralDomain) {
if (Str::endsWith($domain, '.' . $centralDomain)) {
return true;
}
}
return false;
}
public function resolved(Tenant $tenant, mixed ...$args): void

View file

@ -86,14 +86,30 @@ class TenancyServiceProvider extends ServiceProvider
// This works great for cache stores that are *directly* scoped, like Redis or
// any other tagged or prefixed stores, but it doesn't work for the database driver.
//
// When we use the DatabaseTenancyBootstrapper, it changes the default connection,
// and therefore the connection of the database store that will be created when
// this new CacheManager is instantiated again.
// When DatabaseTenancyBootstrapper is used, it changes the default DB connection
// to 'tenant'. A freshly created CacheManager would therefore instantiate database
// stores with the tenant connection.
//
// For that reason, we also adjust the relevant stores on this new CacheManager
// using the callback below. It is set by DatabaseCacheBootstrapper.
// For that reason, we override the 'database' driver creator on this manager so that
// database stores are built with the central connection, and we run the
// $adjustCacheManagerUsing callback below (set by DatabaseCacheBootstrapper).
$manager = new CacheManager($app);
// When DatabaseTenancyBootstrapper is used, database stores whose 'connection'
// config is null fall back to the default DB connection ('tenant'). Reset each
// such store to its explicitly configured connection, or fall back to central.
$centralConnection = $app['config']['tenancy.database.central_connection'];
$manager->extend('database', function ($_app, array $config) use ($centralConnection) {
$config['connection'] ??= $centralConnection;
/** @var CacheManager $this */
return $this->createDatabaseDriver($config); // @phpstan-ignore method.protected
});
// DatabaseCacheBootstrapper explicitly writes 'tenant' into each store's 'connection'
// config. The extend() closure above would then read 'tenant' as the configured value
// (not null) and use it directly, so the central connection fallback wouldn't be used.
// This callback is used to correct those connections back to central for globalCache.
if (static::$adjustCacheManagerUsing !== null) {
(static::$adjustCacheManagerUsing)($manager);
}