Skip to content

多租户协程隔离(Core/Tenant/) ​

008_tenant_isolation 提供租户目录、配额、域名绑定与成员表,配合 TenantScopedResourceFactory、TenantContext 与 TenantResolver 实现**默认封闭(Fail-Closed)**的多租户数据隔离。

1. 防漏接核心:业务库只暴露 TenantScopedResourceFactory ​

php
<?php

use Plinth\DeckCore\Core\Tenant\TenantContext;
use Plinth\DeckCore\Core\Tenant\TenantScopedResourceFactory;

$resources = new TenantScopedResourceFactory($db, new TenantContext());

// 先由宿主校验活跃租户与当前登录账号的成员身份,再进入有界租户上下文
$rows = $resources->runInTenant($authorizedTenantId, function () use ($resources) {
    $node = $resources->scopedNodeKey('orders');
    // 使用 $node 做 RBAC 节点能力校验,再执行租户内查询
    return $resources->select('orders', [], [
        'columns' => ['id', 'title', 'amount'],
        'orderBy' => ['id' => 'DESC'],
        'limit' => 50,
        'offset' => 0,
    ]);
});

强隔离保证 ​

  • 不暴露裸 Query Builder:所有查询强制拼入 tenant_id 条件,插入强制盖章,禁止更新 tenant_id 列;
  • 跨租户访问直接 403:按主键读写、更新、删除前先校验记录归属,缺失或异租户记录一律返回 403;
  • 协程安全:
    • PHP 8.1+ Fiber:使用 WeakMap 绑定当前 Fiber 实例,支持交错挂起/恢复零串味;
    • Swoole / OpenSwoole:使用协程 getContext() 隔离;
    • 传统 FPM(PHP 7.2+):同步请求上下文并在 finally 中自动还原。

2. 使用 DeckCoreStarterKit 与租户解析中间件 ​

php
<?php

use Plinth\DeckCore\Core\Host\DeckCoreStarterKit;
use Plinth\DeckCore\Core\Http\HttpDispatcher;
use Plinth\DeckCore\Core\Http\ResponseSpec;
use Plinth\DeckCore\Core\Tenant\TenantContext;
use Plinth\DeckCore\Core\Tenant\TenantScopedQuery;

$kit = new DeckCoreStarterKit($db, [
    'nodeKey' => 'platform',
    'tenantResolverOptions' => [
        'baseDomain' => 'plinth-lab.com',       // acme.plinth-lab.com -> tenant = acme
        'hostMap' => ['portal.acme.com' => 'acme'],
        'allowHeader' => true,                  // X-DeckCore-Tenant: acme
        'allowQuery' => false,                  // 默认关闭 URL 参数切换,防止越权诱导
    ],
]);

$business = new HttpDispatcher();
$business->before($kit->tenantResolver()->middleware());
$business->get('/api/items', function () use ($db) {
    return ResponseSpec::success([
        'items' => TenantScopedQuery::apply($db->table('items'))->select(),
    ]);
});

try {
    $response = $business->dispatch($request);
} finally {
    // 长驻内存 worker(Swoole / RoadRunner / FrankenPHP)务必在 finally 清理上下文
    TenantContext::clear();
}

3. 内置租户管理端点 ​

方法与路径权限与行为
GET /current已认证账号;返回当前解析租户与自身活跃成员租户
GET /平台 tenant:manage;租户分页列表
GET /detail平台或本租户活跃成员;查看租户详情与配额
POST /save平台 tenant:manage;创建/更新租户,支持 expected_revision 乐观锁(冲突 409)
POST /status平台 tenant:manage;启用(1)或停用(0),停用后业务访问一律 403
GET /members平台或本租户 admin;成员列表
POST /members/save平台或本租户 admin;绑定或调整租户成员角色
POST /members/delete平台或本租户 admin;移除租户成员

磐石工坊(Plinth Lab)· 企业级多框架中后台统一底座