feat(iam): add guarded identity management and ERP launch source
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\controller;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\service\iam\IamOidcClient;
|
||||
use app\adminapi\service\iam\v2\{IamV2Client, IamV2Source, IamV2Manager, IamV2Flow};
|
||||
|
||||
/** Every endpoint authorizes itself. Never relies on legacy unregistered-route allow rules. */
|
||||
final class IamV2Controller extends BaseAdminController
|
||||
{
|
||||
public array $notNeedLogin = ['status', 'introspect', 'checkSession', 'revocation', 'launchContinue', 'selfCallback', 'passwordContinue'];
|
||||
private function invokeV2(callable $fn)
|
||||
{
|
||||
try {
|
||||
if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$reads = ['status','accounts','identities','operationresult','audit','job'];
|
||||
$read = in_array(strtolower((string) $this->request->action()), $reads, true);
|
||||
if (($read && !$this->request->isGet()) || (!$read && !$this->request->isPost())) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
return $this->data($fn())->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) {
|
||||
$code = preg_match('/^[A-Z_]{3,64}$/D', $e->getMessage()) ? $e->getMessage() : 'SERVICE_UNAVAILABLE';
|
||||
return $this->fail($code, ['error' => ['code' => $code]])->header(['Cache-Control' => 'no-store']);
|
||||
}
|
||||
}
|
||||
private function session(bool $recent = false): array
|
||||
{
|
||||
if (!$this->request->isGet()) {
|
||||
$expected = IamV2Client::origin((string) Config::get('iam.public_url'));
|
||||
if ((string) $this->request->header('origin') !== $expected) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
return IamV2Source::current((string) $this->request->header('token', ''), $recent);
|
||||
}
|
||||
private function input(): array { return (array) $this->request->post(); }
|
||||
private function requestId(): string
|
||||
{
|
||||
$key = (string) $this->request->header('idempotency-key', '');
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $key)) { throw new RuntimeException('INVALID_IDEMPOTENCY_KEY'); }
|
||||
return 'zyt-' . $key;
|
||||
}
|
||||
private function serviceAuth(): void
|
||||
{
|
||||
$expected = (string) Config::get('iam.v2_introspection_token', '');
|
||||
if (!$this->request->isPost() || strlen($expected) < 32 || !hash_equals('Bearer ' . $expected, (string) $this->request->header('authorization', ''))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public function status()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$token = (string) $this->request->header('token', '');
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
IamV2Source::admin((int) $legacy['admin_id']);
|
||||
$fresh = false; try { $s = IamV2Source::current($token); $fresh = $s['auth_time'] >= time() - 300; } catch (\Throwable $e) { $s = null; }
|
||||
$b = (new IamV2Manager())->binding((int) $legacy['admin_id']);
|
||||
return ['enabled' => true, 'session_ready' => $s !== null, 'reauth_required' => !$fresh,
|
||||
'management_capabilities' => IamV2Source::capabilities((int) $legacy['admin_id'])] + $b;
|
||||
});
|
||||
}
|
||||
public function reauth()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
if ((string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
$s = IamV2Source::reauth((string) $this->request->header('token', ''), (string) $this->request->post('password', ''));
|
||||
return ['expires_at' => $s['auth_time'] + 300];
|
||||
});
|
||||
}
|
||||
public function accounts() { return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false); return (new IamV2Manager())->accounts((array) $this->request->get(), (int) $s['admin_id']); }); }
|
||||
public function identities()
|
||||
{
|
||||
return $this->invokeV2(function () {
|
||||
$s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
$q = http_build_query(['q' => mb_substr((string) $this->request->get('q', ''), 0, 64), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20], '', '&', PHP_QUERY_RFC3986);
|
||||
return (new IamV2Client())->call('GET', '/identities?' . $q);
|
||||
});
|
||||
}
|
||||
public function operation() { return $this->invokeV2(fn() => (new IamV2Manager())->operation($this->session(true), $this->input(), $this->requestId())); }
|
||||
public function operationResult() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'operation', (string) $this->request->param('id'))); }
|
||||
public function audit()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); IamV2Source::authorize($s, 'read', [], false);
|
||||
IamV2Source::scope((int) $s['admin_id'], [(int) $this->request->param('id')]);
|
||||
return (new IamV2Client())->call('GET', '/audit?' . http_build_query(['externalAccountId' => (string) (int) $this->request->param('id'), 'page' => max(1, (int) $this->request->get('page', 1)), 'pageSize' => 20])); });
|
||||
}
|
||||
public function preflight() { return $this->invokeV2(fn() => (new IamV2Manager())->preflight($this->session(true), (array) $this->request->post('items', []))); }
|
||||
public function batch() { return $this->invokeV2(fn() => (new IamV2Manager())->batch($this->session(true), (string) $this->request->post('preview_id'), (array) $this->request->post('indexes', []), $this->requestId())); }
|
||||
public function job() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(), 'job', (string) $this->request->param('id'))); }
|
||||
public function retry() { return $this->invokeV2(fn() => (new IamV2Manager())->result($this->session(true), 'job', (string) $this->request->param('id'), true, (array) $this->request->post('indexes', []))); }
|
||||
public function introspect()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input(); return IamV2Source::introspect((string) ($b['proof'] ?? ''), (string) ($b['purpose'] ?? ''), $b['transactionId'] ?? null); });
|
||||
}
|
||||
private function serviceResult(callable $fn)
|
||||
{
|
||||
try { if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); } if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); } return json($fn())->header(['Cache-Control' => 'no-store']); }
|
||||
catch (\Throwable $e) { return json(['active' => false], 403)->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function checkSession()
|
||||
{
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input(); $s = IamV2Source::check((string) ($b['sessionId'] ?? ''), (int) ($b['sessionVersion'] ?? 0));
|
||||
return ['active' => true, 'actorLocalId' => (string) $s['admin_id'], 'authMethod' => $s['auth_method'], 'authTime' => (int) $s['auth_time'], 'expiresAt' => (int) $s['expires_at']]; });
|
||||
}
|
||||
public function launchStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(); (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
IamV2Source::check($s['session_id'], (int) $s['version']);
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('launch', $intent, ['sessionId' => $s['session_id'], 'sessionVersion' => $s['version']]);
|
||||
setcookie('ZYT_IAM_V2_INTENT', $intent, ['expires' => time() + 300, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return ['url' => IamV2Client::origin((string) Config::get('iam.erp_url')) . '/iam/launch?source=zyt&intent=' . $intent]; });
|
||||
}
|
||||
public function launchContinue()
|
||||
{
|
||||
try {
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$intent = (string) $this->request->get('intent', ''); $cookie = (string) ($_COOKIE['ZYT_IAM_V2_INTENT'] ?? '');
|
||||
if ($intent === '' || !hash_equals($cookie, $intent)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$flow = IamV2Flow::take('launch', $intent, $s['session_id']); IamV2Source::check($s['session_id'], (int) $flow['sessionVersion']);
|
||||
$tx = (string) $this->request->get('transaction_id', '');
|
||||
$transaction = $client->call('GET', '/launch-transactions/' . rawurlencode($tx));
|
||||
if (($transaction['sourceApplicationId'] ?? '') !== 'zyt' || ($transaction['targetApplicationId'] ?? '') !== 'zmxy-erp') { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
(new IamV2Manager($client))->assertLinked((int) $s['admin_id']);
|
||||
$grant = $client->call('POST', '/launch-grants', ['transactionId' => $tx, 'proof' => IamV2Source::proof($s, 'launch', [(int) $s['admin_id']], [], $tx)]);
|
||||
$delivery = IamV2Client::origin((string) Config::get('iam.erp_url')) . '/api/erp/iam/v2/launch/callback';
|
||||
if (($grant['deliveryUrl'] ?? '') !== $delivery) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return response(IamV2Flow::form($delivery, ['transaction_id' => $tx, 'grant' => $grant['grant']]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=launch_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
private function selfConfig(): array { $c = (array) Config::get('iam'); $c['redirect_uri'] = IamV2Client::origin($c['public_url']) . '/adminapi/iam/v2/self-link/callback'; return $c; }
|
||||
public function selfStart()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $a = IamV2Source::admin((int) $s['admin_id']);
|
||||
if (IamV2Source::protectedAccount((int) $a['id'])) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
$b = (new IamV2Manager())->binding((int) $s['admin_id'], true);
|
||||
if (($b['binding']['state'] ?? '') === 'verified') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$state = bin2hex(random_bytes(32)); $nonce = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('self_link', $state, ['sessionId' => $s['session_id'], 'nonce' => $nonce, 'verifier' => $verifier, 'version' => $b['binding']['version'] ?? null]);
|
||||
return ['url' => (new IamOidcClient($this->selfConfig()))->authorizationUrl($state, $nonce, $verifier) . '&prompt=login&max_age=300']; });
|
||||
}
|
||||
public function selfCallback()
|
||||
{
|
||||
try {
|
||||
$central = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$flow = IamV2Flow::take('self_link', (string) $this->request->get('state', ''), $s['session_id']);
|
||||
$oidc = new IamOidcClient($this->selfConfig()); $oidc->exchange((string) $this->request->get('code', ''), $flow['verifier'], $flow['nonce']);
|
||||
$proof = IamV2Source::proof($s, 'self_link', [(int) $s['admin_id']], [], null, ['oidcNonce' => $flow['nonce']]);
|
||||
$body = ['idToken' => $oidc->verifiedIdToken(), 'nonce' => $flow['nonce'], 'proof' => $proof, 'externalAccountId' => (string) $s['admin_id']];
|
||||
if ($flow['version'] !== null) { $body['expectedVersion'] = (int) $flow['version']; }
|
||||
$central->call('POST', '/self-link', $body);
|
||||
(new IamV2Manager($central))->binding((int) $s['admin_id'], true);
|
||||
return redirect('/admin/user/setting?iam_result=linked')->header(['Cache-Control' => 'no-store']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=link_failed')->header(['Cache-Control' => 'no-store']); }
|
||||
}
|
||||
public function passwordSetup()
|
||||
{
|
||||
return $this->invokeV2(function () { $s = $this->session(true); $b = (new IamV2Manager())->assertLinked((int) $s['admin_id']);
|
||||
if (!($b['employee']['passwordSetupPending'] ?? false)) { throw new RuntimeException('PASSWORD_ALREADY_SET'); }
|
||||
$result = (new IamV2Client())->call('POST', '/password-setup', ['proof' => IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']])]);
|
||||
$url = parse_url((string) ($result['url'] ?? '')); $portal = parse_url(IamV2Client::origin((string) Config::get('iam.portal_url')));
|
||||
if (!$url || ($url['scheme'] ?? '') !== 'https' || ($url['host'] ?? '') !== $portal['host'] || ($url['port'] ?? 443) !== ($portal['port'] ?? 443) || isset($url['user']) || isset($url['pass']) || ($url['path'] ?? '') !== '/portal/password-setup') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
$intent = bin2hex(random_bytes(32)); IamV2Flow::put('password_setup', $intent, ['sessionId' => $s['session_id'], 'requestId' => $result['requestId']], 900);
|
||||
setcookie('ZYT_IAM_PASSWORD_INTENT', $intent, ['expires' => time() + 900, 'path' => '/adminapi/iam/v2', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
return $result; });
|
||||
}
|
||||
public function passwordContinue()
|
||||
{
|
||||
try {
|
||||
$client = new IamV2Client(); $s = IamV2Source::check((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
$f = IamV2Flow::take('password_setup', (string) ($_COOKIE['ZYT_IAM_PASSWORD_INTENT'] ?? ''), $s['session_id']);
|
||||
$id = (string) $this->request->get('request_id', ''); $state = (string) $this->request->get('state', '');
|
||||
if ($id !== $f['requestId'] || !preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $state)) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$proof = IamV2Source::proof($s, 'password_setup', [(int) $s['admin_id']], [], $id, ['state' => $state]);
|
||||
$url = IamV2Client::origin((string) Config::get('iam.portal_url')) . '/portal/password-setup/authorize';
|
||||
return response(IamV2Flow::form($url, ['request_id' => $id, 'state' => $state, 'proof' => $proof]))->header(['Content-Type' => 'text/html; charset=utf-8', 'Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
} catch (\Throwable $e) { return redirect('/admin/user/setting?iam_result=password_failed'); }
|
||||
}
|
||||
public function revocation()
|
||||
{
|
||||
return $this->serviceResult(fn() => \app\adminapi\service\iam\v2\IamV2Events::accept(
|
||||
(string) $this->request->getContent(), (string) $this->request->header('x-iam-signature', ''),
|
||||
(string) $this->request->header('x-iam-event-id', ''), (string) Config::get('iam.v2_event_secret', '')));
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,15 @@ class LoginController extends BaseAdminController
|
||||
public function account()
|
||||
{
|
||||
$params = (new LoginValidate())->post()->goCheck();
|
||||
return $this->data((new LoginLogic())->login($params));
|
||||
$result = (new LoginLogic())->login($params);
|
||||
// Enroll only a genuinely checked password, never the debug bypass.
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
$a = \think\facade\Db::name('admin')->where('account', $params['account'])->find();
|
||||
if ($a && hash_equals((string) $a['password'], create_password((string) $params['password'], \think\facade\Config::get('project.unique_identification')))) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::enroll($result['token'], 'password');
|
||||
}
|
||||
}
|
||||
return $this->data($result);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -158,6 +166,9 @@ class LoginController extends BaseAdminController
|
||||
public function logout()
|
||||
{
|
||||
//退出登录情况特殊,只有成功的情况,也不需要token验证
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::revokeSession((string) ($_COOKIE[\app\adminapi\service\iam\v2\IamV2Source::COOKIE] ?? ''));
|
||||
}
|
||||
(new LoginLogic())->logout($this->adminInfo);
|
||||
return $this->success();
|
||||
}
|
||||
|
||||
@@ -69,6 +69,20 @@ class LoginMiddleware
|
||||
}
|
||||
}
|
||||
|
||||
// Active requests compensate missed central revocations within a 30-second cache window.
|
||||
// Local-only unlinked accounts and disabled installations keep their original behavior.
|
||||
if ($adminInfo && !$isNotNeedLogin && \app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
$binding = \think\facade\Db::name('iam_v2_binding')->where('admin_id', $adminInfo['admin_id'])->find();
|
||||
if ($binding && $binding['state'] !== 'unlinked') {
|
||||
try {
|
||||
$b = (new \app\adminapi\service\iam\v2\IamV2Manager())->binding((int) $adminInfo['admin_id']);
|
||||
if (($b['binding']['state'] ?? '') !== 'verified' || !($b['access']['allowed'] ?? false) || ($b['employee']['status'] ?? '') !== 'active') {
|
||||
return JsonService::fail('统一账号关联已失效,请重新登录', [], -1);
|
||||
}
|
||||
} catch (\Throwable $e) { return JsonService::fail('统一身份服务暂时不可用,请稍后重试', [], 0); }
|
||||
}
|
||||
}
|
||||
|
||||
//给request赋值,用于控制器
|
||||
$request->adminInfo = $adminInfo;
|
||||
$request->adminId = $adminInfo['admin_id'] ?? 0;
|
||||
|
||||
@@ -222,6 +222,10 @@ class LoginLogic extends BaseLogic
|
||||
// 设置 token
|
||||
$adminInfo = AdminTokenService::setToken($admin->id, $terminal, $admin->multipoint_login);
|
||||
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::enroll($adminInfo['token'], 'wecom');
|
||||
}
|
||||
|
||||
$avatar = $admin->avatar ?: Config::get('project.default_image.admin_avatar');
|
||||
$avatar = FileService::getFileUrl($avatar);
|
||||
|
||||
@@ -279,8 +283,8 @@ class LoginLogic extends BaseLogic
|
||||
$ch = curl_init();
|
||||
curl_setopt($ch, CURLOPT_URL, $url);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
|
||||
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
|
||||
$result = curl_exec($ch);
|
||||
curl_close($ch);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
use think\facade\Route;
|
||||
// Explicit method/path mapping; controller also fails closed for every v2 capability.
|
||||
Route::get('iam/v2/status', 'IamV2/status');
|
||||
Route::post('iam/v2/reauth', 'IamV2/reauth');
|
||||
Route::get('iam/v2/accounts', 'IamV2/accounts');
|
||||
Route::get('iam/v2/identities', 'IamV2/identities');
|
||||
Route::post('iam/v2/operations', 'IamV2/operation');
|
||||
Route::get('iam/v2/operations/:id', 'IamV2/operationResult');
|
||||
Route::get('iam/v2/accounts/:id/audit', 'IamV2/audit');
|
||||
Route::post('iam/v2/batch/preflight', 'IamV2/preflight');
|
||||
Route::post('iam/v2/batch', 'IamV2/batch');
|
||||
Route::get('iam/v2/jobs/:id', 'IamV2/job');
|
||||
Route::post('iam/v2/jobs/:id/retry', 'IamV2/retry');
|
||||
Route::post('iam/v2/proofs/introspect', 'IamV2/introspect');
|
||||
Route::post('iam/v2/sessions/check', 'IamV2/checkSession');
|
||||
Route::post('iam/v2/events/revocation', 'IamV2/revocation');
|
||||
Route::post('iam/v2/launch/start', 'IamV2/launchStart');
|
||||
Route::get('iam/v2/launch/continue', 'IamV2/launchContinue');
|
||||
Route::post('iam/v2/self-link/start', 'IamV2/selfStart');
|
||||
Route::get('iam/v2/self-link/callback', 'IamV2/selfCallback');
|
||||
Route::post('iam/v2/password-setup', 'IamV2/passwordSetup');
|
||||
Route::get('iam/v2/password-continue', 'IamV2/passwordContinue');
|
||||
@@ -36,6 +36,10 @@ final class IamAccountProvisioner
|
||||
|
||||
public function resolve(IamOidcClient $client, array $config, string $subject): int
|
||||
{
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
$tombstone = Db::name('iam_v2_binding')->where('subject', $subject)->where('state', 'revoked')->find();
|
||||
if ($tombstone) { throw new RuntimeException('IAM_BINDING_REVOKED'); }
|
||||
}
|
||||
$context = $client->provisioning($subject);
|
||||
self::validateContext($context, $subject, $config['application_id']);
|
||||
if (($context['shouldCreateLocalAccount'] ?? null) !== true) {
|
||||
|
||||
@@ -67,7 +67,7 @@ final class IamLoginService
|
||||
$claims = $this->client->exchange($code, $transaction['verifier'], $transaction['nonce']);
|
||||
$this->verifiedAdmin($claims['sub']);
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
$this->transactions->put('ticket', $ticket, $browser, ['subject' => $claims['sub']], 60);
|
||||
$this->transactions->put('ticket', $ticket, $browser, ['subject' => $claims['sub'], 'auth_time' => (int) ($claims['auth_time'] ?? 0)], 60);
|
||||
return $ticket;
|
||||
}
|
||||
|
||||
@@ -79,7 +79,12 @@ final class IamLoginService
|
||||
$transaction = $this->transactions->consume('ticket', $ticket, $browser);
|
||||
// Recheck entitlement, binding and local status immediately before issuing the existing business token.
|
||||
$admin = $this->verifiedAdmin($transaction['subject']);
|
||||
return (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
|
||||
$result = (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
(new \app\adminapi\service\iam\v2\IamV2Manager())->assertLinked((int) $admin->id);
|
||||
\app\adminapi\service\iam\v2\IamV2Source::enroll($result['token'], 'oidc', true, (int) ($transaction['auth_time'] ?? 0));
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function boundAdminId(array $context, string $subject, string $applicationId): int
|
||||
|
||||
@@ -14,6 +14,13 @@ final class IamOidcClient
|
||||
private array $config;
|
||||
private $transport;
|
||||
private ?array $discovery = null;
|
||||
private ?string $verifiedToken = null;
|
||||
|
||||
public function verifiedIdToken(): string
|
||||
{
|
||||
if ($this->verifiedToken === null) { throw new RuntimeException("IAM token not verified"); }
|
||||
return $this->verifiedToken;
|
||||
}
|
||||
|
||||
/** Transport signature: (method, url, headers, body): ['status'=>int, 'body'=>string]. */
|
||||
public function __construct(array $config, ?callable $transport = null)
|
||||
@@ -102,6 +109,7 @@ final class IamOidcClient
|
||||
|| (isset($claims['nbf']) && (!is_int($claims['nbf']) || $claims['nbf'] > $now))) {
|
||||
throw new RuntimeException('IAM ID token claims are invalid');
|
||||
}
|
||||
$this->verifiedToken = $response['id_token'];
|
||||
return $claims;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
|
||||
/** Dedicated v2 application credential; never falls back to the v1 provisioning token. */
|
||||
final class IamV2Client
|
||||
{
|
||||
public function __construct(private ?array $settings = null, private $transport = null)
|
||||
{
|
||||
$this->settings ??= (array) Config::get('iam', []);
|
||||
if (!self::enabled($this->settings)) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
self::https((string) ($this->settings['api_url'] ?? ''));
|
||||
foreach (['public_url', 'erp_url'] as $field) { self::origin((string) ($this->settings[$field] ?? '')); }
|
||||
if (strlen((string) ($this->settings['v2_token'] ?? '')) < 32) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
}
|
||||
public static function enabled(?array $settings = null): bool
|
||||
{
|
||||
$settings ??= (array) Config::get('iam', []);
|
||||
return filter_var($settings['v2_enabled'] ?? false, FILTER_VALIDATE_BOOL);
|
||||
}
|
||||
public static function https(string $url): string
|
||||
{
|
||||
$p = parse_url($url);
|
||||
if (!$p || ($p['scheme'] ?? '') !== 'https' || empty($p['host']) || isset($p['user']) || isset($p['pass'])
|
||||
|| isset($p['fragment']) || isset($p['query']) || preg_match('/[\x00-\x20\x7f\\\\]/', $url)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return rtrim($url, '/');
|
||||
}
|
||||
public static function origin(string $url): string
|
||||
{
|
||||
$url = self::https($url);
|
||||
if ((parse_url($url, PHP_URL_PATH) ?? '') !== '') { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $url;
|
||||
}
|
||||
public function call(string $method, string $path, array $body = [], ?string $key = null): array
|
||||
{
|
||||
if (!preg_match('#^/[a-zA-Z0-9/_?=&%.:-]+$#D', $path) || str_contains($path, '..')) { throw new RuntimeException('INVALID_PATH'); }
|
||||
$url = rtrim($this->settings['api_url'], '/') . '/internal/v2/applications/' . rawurlencode($this->settings['application_id'] ?? 'zyt') . $path;
|
||||
$headers = ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer ' . $this->settings['v2_token']];
|
||||
if ($method !== 'GET') {
|
||||
$headers[] = 'X-Request-ID: ' . bin2hex(random_bytes(16));
|
||||
$headers[] = 'Idempotency-Key: ' . ($key ?? bin2hex(random_bytes(24)));
|
||||
}
|
||||
$data = $method === 'GET' ? '' : json_encode($body, JSON_THROW_ON_ERROR);
|
||||
if ($this->transport) { $r = ($this->transport)($method, $url, $headers, $data); }
|
||||
else {
|
||||
$c = curl_init($url); $response = '';
|
||||
curl_setopt_array($c, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_HTTPHEADER => $headers,
|
||||
CURLOPT_POSTFIELDS => $data, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_CONNECTTIMEOUT => 3, CURLOPT_TIMEOUT => 10,
|
||||
CURLOPT_WRITEFUNCTION => static function ($c, $chunk) use (&$response) {
|
||||
if (strlen($response) + strlen($chunk) > 2097152) { return 0; } $response .= $chunk; return strlen($chunk);
|
||||
}]);
|
||||
$ok = curl_exec($c); $r = ['status' => curl_getinfo($c, CURLINFO_RESPONSE_CODE), 'body' => $ok === false ? '' : $response]; curl_close($c);
|
||||
}
|
||||
$result = json_decode($r['body'] ?? '', true);
|
||||
if (!is_array($result)) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
if (($r['status'] ?? 0) < 200 || $r['status'] >= 300 || isset($result['error'])) {
|
||||
$code = $result['error']['code'] ?? 'SERVICE_UNAVAILABLE';
|
||||
throw new RuntimeException(preg_match('/^[A-Z_]{3,64}$/D', $code) ? $code : 'SERVICE_UNAVAILABLE');
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Events
|
||||
{
|
||||
public static function accept(string $raw, string $signature, string $eventId, string $secret, ?callable $revoke = null): array
|
||||
{
|
||||
if (strlen($raw) > 65536 || strlen($secret) < 32 || !hash_equals('sha256=' . hash_hmac('sha256', $raw, $secret), $signature)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$event = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (empty($event['employeeId']) || $eventId === '' || strlen($eventId) > 128 || $eventId !== ($event['id'] ?? '') || !in_array('zyt', (array) ($event['applicationIds'] ?? []), true)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$occurredAt = (string) ($event['occurredAt'] ?? '');
|
||||
if (!preg_match('/^\d{4}-\d{2}-\d{2}T.*(Z|[+-][0-9]{2}:[0-9]{2})$/D', $occurredAt)) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
$stamp = strtotime($occurredAt);
|
||||
if (!$stamp || $stamp > time() + 60 || time() - $stamp > 300) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$revoke ??= fn(int $id) => IamV2Manager::revoke($id);
|
||||
return Db::transaction(function () use ($event, $eventId, $raw, $revoke) {
|
||||
$existing = Db::name('iam_v2_event')->where('event_id', $eventId)->lock(true)->find();
|
||||
if ($existing) {
|
||||
if (!hash_equals($existing['digest'], hash('sha256', $raw))) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return ['accepted' => true, 'duplicate' => true];
|
||||
}
|
||||
Db::name('iam_v2_event')->insert(['event_id' => $eventId, 'digest' => hash('sha256', $raw), 'received_at' => time()]);
|
||||
$rows = Db::name('iam_v2_binding')->where('employee_id', (string) $event['employeeId'])->lock(true)->select()->toArray();
|
||||
foreach ($rows as $row) {
|
||||
if (isset($event['bindingVersion']) && (int) $event['bindingVersion'] < (int) $row['version']) { continue; }
|
||||
Db::name('iam_v2_binding')->where('admin_id', $row['admin_id'])->update(['state' => 'revoked', 'checked_at' => 0,
|
||||
'version' => max((int) $row['version'], (int) ($event['bindingVersion'] ?? 0))]);
|
||||
$revoke((int) $row['admin_id']);
|
||||
}
|
||||
return ['accepted' => true];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
|
||||
final class IamV2Flow
|
||||
{
|
||||
public static function put(string $kind, string $secret, array $payload, int $ttl = 300): void
|
||||
{
|
||||
Db::name('iam_v2_flow')->insert(['flow_key' => hash('sha256', $kind . ':' . $secret), 'kind' => $kind,
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + $ttl, 'consumed' => 0]);
|
||||
}
|
||||
public static function take(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
return Db::transaction(function () use ($kind, $secret, $sid) {
|
||||
$key = hash('sha256', $kind . ':' . $secret);
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', $key)->lock(true)->find();
|
||||
if (!$row || $row['expires_at'] <= time() || (int) $row['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['sessionId'] ?? '') !== $sid) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if (Db::name('iam_v2_flow')->where('flow_key', $key)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return $p;
|
||||
});
|
||||
}
|
||||
public static function form(string $url, array $fields): string
|
||||
{
|
||||
$nonce = bin2hex(random_bytes(18));
|
||||
$escape = fn($s) => htmlspecialchars((string) $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
$inputs = '';
|
||||
foreach ($fields as $name => $value) { $inputs .= '<input type="hidden" name="' . $escape($name) . '" value="' . $escape($value) . '">'; }
|
||||
$origin = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST) . (parse_url($url, PHP_URL_PORT) ? ':' . parse_url($url, PHP_URL_PORT) : '');
|
||||
return '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; base-uri \'none\'; form-action ' . $escape($origin) . '; script-src \'nonce-' . $nonce . '\'"><title>正在验证身份</title><form method="post" action="' . $escape($url) . '">' . $inputs . '<button>继续</button></form><script nonce="' . $nonce . '">document.forms[0].submit()</script>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
|
||||
final class IamV2Manager
|
||||
{
|
||||
public function __construct(private ?IamV2Client $client = null) { $this->client ??= new IamV2Client(); }
|
||||
public function binding(int $id, bool $fresh = false): array
|
||||
{
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$fresh && $row && $row['checked_at'] > time() - 30) { return json_decode($row['payload'], true, 32, JSON_THROW_ON_ERROR); }
|
||||
$result = $this->client->call('GET', '/bindings/by-external/' . $id);
|
||||
if (($result['binding']['externalAccountId'] ?? (string) $id) !== (string) $id) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$state = $result['binding']['state'] ?? 'unlinked';
|
||||
$version = (int) ($result['binding']['version'] ?? 0);
|
||||
if ($row && $row['state'] === 'revoked' && $state === 'verified' && $version <= (int) $row['version']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($row && (int) $row['version'] > $version) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$values = ['admin_id' => $id, 'employee_id' => $result['employee']['id'] ?? '', 'subject' => $result['employee']['oidcSubject'] ?? '',
|
||||
'state' => $state, 'version' => $version, 'payload' => json_encode($result, JSON_THROW_ON_ERROR), 'checked_at' => time()];
|
||||
if ($row) { Db::name('iam_v2_binding')->where('admin_id', $id)->update($values); }
|
||||
else { Db::name('iam_v2_binding')->insert($values); }
|
||||
$changed = $row && (($row['employee_id'] ?? '') !== ($values['employee_id'] ?? '') || (int) $row['version'] !== $version);
|
||||
if ($state === 'revoked' || $changed || (($result['employee'] ?? null) && (($result['employee']['status'] ?? '') !== 'active' || !($result['access']['allowed'] ?? false)))) {
|
||||
self::revoke($id);
|
||||
}
|
||||
return $result + ['checked_at' => time()];
|
||||
}
|
||||
public static function revoke(int $id): void
|
||||
{
|
||||
IamV2Source::revokeAdmin($id);
|
||||
foreach (Db::name('admin_session')->where('admin_id', $id)->column('token') as $token) { AdminLogic::expireToken($token); }
|
||||
}
|
||||
public function assertLinked(int $id): array
|
||||
{
|
||||
$b = $this->binding($id, true);
|
||||
if (($b['binding']['state'] ?? '') !== 'verified') { throw new RuntimeException('NOT_LINKED'); }
|
||||
if (($b['employee']['status'] ?? '') !== 'active' || !($b['access']['allowed'] ?? false)) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return $b;
|
||||
}
|
||||
public function accounts(array $query, int $actor): array
|
||||
{
|
||||
$page = max(1, (int) ($query['page'] ?? 1)); $size = min(20, max(1, (int) ($query['pageSize'] ?? 20)));
|
||||
$db = Db::name('admin')->whereNull('delete_time');
|
||||
$visible = IamV2Source::visibleIds($actor);
|
||||
if ($visible !== null) { $db->whereIn('id', $visible ?: [0]); }
|
||||
if (($query['q'] ?? '') !== '') { $db->whereLike('account|name', '%' . mb_substr((string) $query['q'], 0, 64) . '%'); }
|
||||
if (($query['state'] ?? '') !== '') {
|
||||
$ids = Db::name('iam_v2_binding')->where('state', (string) $query['state'])->column('admin_id');
|
||||
if ($query['state'] === 'unknown') { $db->whereNotIn('id', Db::name('iam_v2_binding')->column('admin_id')); }
|
||||
else { $db->whereIn('id', $ids ?: [0]); }
|
||||
}
|
||||
$total = (clone $db)->count();
|
||||
$items = $db->field('id,account,name,disable,root')->page($page, $size)->select()->toArray();
|
||||
foreach ($items as &$r) {
|
||||
try { $r['iam'] = $this->binding((int) $r['id']); $r['iam']['state'] = $r['iam']['binding']['state'] ?? 'unlinked'; }
|
||||
catch (\Throwable $e) { $r['iam'] = ['state' => 'unknown', 'error' => 'SERVICE_UNAVAILABLE']; }
|
||||
}
|
||||
return ['items' => $items, 'total' => $total];
|
||||
}
|
||||
public static function input(array $input): array
|
||||
{
|
||||
$kind = (string) ($input['kind'] ?? '');
|
||||
if (!in_array($kind, ['bind', 'create_and_bind', 'unbind', 'rebind', 'reconcile'], true)) { throw new RuntimeException('INVALID_OPERATION'); }
|
||||
$id = (int) ($input['user_id'] ?? 0);
|
||||
if ($id < 1 || trim((string) ($input['reason'] ?? '')) === '') { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out = ['kind' => $kind, 'externalAccountId' => (string) $id, 'reason' => mb_substr(trim($input['reason']), 0, 500)];
|
||||
if (isset($input['employee_id'])) { $out['employeeId'] = (string) $input['employee_id']; }
|
||||
if (isset($input['expected_version'])) { $out['expectedVersion'] = (int) $input['expected_version']; }
|
||||
if (in_array($kind, ['unbind','rebind'], true) && !isset($out['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if ($kind === 'create_and_bind') {
|
||||
$n = $input['new_employee'] ?? [];
|
||||
$out['newEmployee'] = ['username' => (string) ($n['username'] ?? ''), 'displayName' => (string) ($n['display_name'] ?? '')];
|
||||
if (!preg_match('/^[A-Za-z0-9_.@-]{3,64}$/D', $out['newEmployee']['username']) || trim($out['newEmployee']['displayName']) === '') { throw new RuntimeException('INVALID_INPUT'); }
|
||||
if (!empty($n['email'])) {
|
||||
if (!filter_var($n['email'], FILTER_VALIDATE_EMAIL)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out['newEmployee']['email'] = $n['email'];
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
public static function cap(string $kind): string { return ['create_and_bind' => 'create', 'reconcile' => 'read'][$kind] ?? $kind; }
|
||||
public function operation(array $session, array $input, string $requestId): array
|
||||
{
|
||||
$body = self::input($input); $target = (int) $body['externalAccountId']; $cap = self::cap($body['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$target]);
|
||||
$this->binding($target, true);
|
||||
$body['proof'] = IamV2Source::proof($session, 'management', [$target], ['iam:' . $cap]);
|
||||
$op = $this->client->call('POST', '/operations', $body, $requestId);
|
||||
$this->remember('operation', (string) $op['id'], $session, [$target], ['iam:' . $cap]);
|
||||
if (($op['status'] ?? '') === 'succeeded') { $this->binding($target, true); }
|
||||
return $op;
|
||||
}
|
||||
public function remember(string $kind, string $id, array $session, array $targets, array $caps = []): void
|
||||
{
|
||||
$key = hash('sha256', $kind . ':' . $id);
|
||||
$existing = Db::name('iam_v2_resource')->where('resource_key', $key)->find();
|
||||
if ($existing) { if ((int) $existing['actor_id'] !== (int) $session['admin_id']) { throw new RuntimeException('FORBIDDEN'); } return; }
|
||||
Db::name('iam_v2_resource')->insert(['resource_key' => $key, 'kind' => $kind, 'external_id' => $id, 'actor_id' => $session['admin_id'],
|
||||
'payload' => json_encode(['targets' => $targets, 'capabilities' => $caps]), 'created_at' => time()]);
|
||||
}
|
||||
public function owned(string $kind, string $id, array $session): array
|
||||
{
|
||||
$r = Db::name('iam_v2_resource')->where('resource_key', hash('sha256', $kind . ':' . $id))->where('actor_id', $session['admin_id'])->find();
|
||||
if (!$r) { throw new RuntimeException('FORBIDDEN'); }
|
||||
$payload = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
IamV2Source::scope((int) $session['admin_id'], $payload['targets']);
|
||||
return $payload;
|
||||
}
|
||||
public function preflight(array $session, array $items): array
|
||||
{
|
||||
if (!$items || count($items) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
IamV2Source::authorize($session, 'batch'); $mapped = []; $targets = []; $caps = ['iam:batch']; $indexMap = []; $review = [];
|
||||
foreach ($items as $index => $input) {
|
||||
try {
|
||||
$item = self::input($input); $id = (int) $item['externalAccountId']; $cap = self::cap($item['kind']);
|
||||
IamV2Source::authorize($session, $cap, [$id]);
|
||||
$indexMap[] = (int) $index; $mapped[] = $item; $targets[] = $id; $caps[] = 'iam:' . $cap;
|
||||
} catch (RuntimeException $e) {
|
||||
$review[] = ['index' => (int) $index, 'externalAccountId' => (string) ($input['user_id'] ?? ''),
|
||||
'status' => $e->getMessage() === 'PROTECTED_ACCOUNT_REVIEW_REQUIRED' ? 'review' : 'invalid', 'message' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
if (!$mapped) { return ['previewId' => null, 'items' => $review, 'expiresAt' => time()]; }
|
||||
$r = $this->client->call('POST', '/batch/preflight', ['items' => $mapped,
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, array_values(array_unique($caps)))]);
|
||||
$this->remember('preview', (string) $r['previewId'], $session, $targets, $caps);
|
||||
$resource = hash('sha256', 'preview:' . $r['previewId']);
|
||||
$ready = [];
|
||||
foreach ($r['items'] as &$item) {
|
||||
$centralIndex = (int) $item['index'];
|
||||
if (!array_key_exists($centralIndex, $indexMap)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$item['index'] = $indexMap[$centralIndex];
|
||||
if ($item['status'] === 'ready') { $ready[] = $item['index']; }
|
||||
}
|
||||
unset($item);
|
||||
Db::name('iam_v2_resource')->where('resource_key', $resource)->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'indexMap' => $indexMap, 'ready' => $ready])]);
|
||||
$r['items'] = array_merge($r['items'], $review);
|
||||
usort($r['items'], fn($a, $b) => $a['index'] <=> $b['index']); return $r;
|
||||
}
|
||||
public function batch(array $session, string $preview, array $indexes, string $key): array
|
||||
{
|
||||
$scope = $this->owned('preview', $preview, $session); IamV2Source::authorize($session, 'batch', $scope['targets']);
|
||||
foreach ($scope['capabilities'] as $cap) { IamV2Source::authorize($session, substr($cap, 4), $scope['targets']); }
|
||||
$indexes = array_values(array_unique(array_map('intval', $indexes)));
|
||||
if (!$indexes || array_diff($indexes, $scope['ready'] ?? [])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$indexes = array_map(fn($i) => array_search($i, $scope['indexMap'], true), $indexes);
|
||||
$r = $this->client->call('POST', '/batch', ['previewId' => $preview, 'indexes' => $indexes,
|
||||
'proof' => IamV2Source::proof($session, 'management', $scope['targets'], $scope['capabilities'])], $key);
|
||||
$this->remember('job', (string) $r['id'], $session, $scope['targets'], $scope['capabilities']); return $r;
|
||||
}
|
||||
public function result(array $session, string $kind, string $id, bool $retry = false, array $indexes = []): array
|
||||
{
|
||||
$scope = $this->owned($kind, $id, $session); IamV2Source::authorize($session, 'read', [], false);
|
||||
$path = ($kind === 'job' ? '/jobs/' : '/operations/') . rawurlencode($id);
|
||||
if ($retry) {
|
||||
foreach ($scope['capabilities'] as $cap) { IamV2Source::authorize($session, substr($cap, 4), $scope['targets']); }
|
||||
$r = $this->client->call('POST', $path . '/retry', ['indexes' => $indexes, 'proof' => IamV2Source::proof($session, 'management', $scope['targets'], $scope['capabilities'])]);
|
||||
} else { $r = $this->client->call('GET', $path); }
|
||||
foreach ($scope['targets'] as $target) { $this->binding((int) $target, true); } return $r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Db;
|
||||
use think\facade\Config;
|
||||
use app\adminapi\logic\auth\AuthLogic;
|
||||
use app\common\cache\AdminAccountSafeCache;
|
||||
|
||||
/** Browser source sessions are separate from legacy account/terminal shared business tokens. */
|
||||
final class IamV2Source
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_SESSION';
|
||||
public static function enroll(string $token, string $method, bool $cookie = true, ?int $authTime = null): array
|
||||
{
|
||||
if (!in_array($method, ['password', 'wecom', 'oidc'], true)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $legacy['admin_id']);
|
||||
$old = (string) ($_COOKIE[self::COOKIE] ?? '');
|
||||
if ($old !== '') { self::revokeSession($old); }
|
||||
$sid = bin2hex(random_bytes(32));
|
||||
$row = ['session_id' => $sid, 'admin_id' => (int) $legacy['admin_id'], 'business_session_id' => $legacy['id'],
|
||||
'token_hash' => hash('sha256', $token), 'account_stamp' => self::accountStamp($admin), 'auth_method' => $method, 'auth_time' => $method === 'oidc' ? max(0, min(time(), $authTime ?? 0)) : time(),
|
||||
'version' => 1, 'revoked' => 0, 'expires_at' => min((int) $legacy['expire_time'], time() + 43200)];
|
||||
Db::name('iam_v2_source_session')->insert($row);
|
||||
if ($cookie) {
|
||||
setcookie(self::COOKIE, $sid, ['expires' => $row['expires_at'], 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
$_COOKIE[self::COOKIE] = $sid;
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
private static function accountStamp(array $admin): string
|
||||
{
|
||||
return hash('sha256', json_encode([$admin['account'], $admin['password'], $admin['work_wechat_userid'] ?? '', (int) $admin['root']], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
public static function admin(int $id): array
|
||||
{
|
||||
$a = Db::name('admin')->where('id', $id)->find();
|
||||
if (!$a || (int) $a['disable'] !== 0 || !empty($a['delete_time'])) { throw new RuntimeException('ACCOUNT_DISABLED'); }
|
||||
return $a;
|
||||
}
|
||||
public static function current(string $token, bool $recent = false): array
|
||||
{
|
||||
$s = self::check((string) ($_COOKIE[self::COOKIE] ?? ''));
|
||||
if (!hash_equals($s['token_hash'], hash('sha256', $token))) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ($recent && $s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
return $s;
|
||||
}
|
||||
public static function check(string $id, ?int $version = null): array
|
||||
{
|
||||
$s = Db::name('iam_v2_source_session')->where('session_id', $id)->find();
|
||||
if (!$s || (int) $s['revoked'] !== 0 || $s['expires_at'] <= time() || ($version !== null && (int) $s['version'] !== $version)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$admin = self::admin((int) $s['admin_id']);
|
||||
if (!hash_equals($s['account_stamp'], self::accountStamp($admin))) { self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if (!$legacy || $legacy['expire_time'] <= time() || (int) $legacy['admin_id'] !== (int) $s['admin_id'] || !hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
return $s;
|
||||
}
|
||||
public static function reauth(string $token, string $password): array
|
||||
{
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
if (!$legacy || $password === '' || strlen($password) > 256) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
$a = self::admin((int) $legacy['admin_id']);
|
||||
$limiter = new AdminAccountSafeCache();
|
||||
if (!$limiter->isSafe()) { throw new RuntimeException('RATE_LIMITED'); }
|
||||
// Deliberately does NOT invoke LoginValidate's local-debug password bypass.
|
||||
if (!hash_equals((string) $a['password'], create_password($password, Config::get('project.unique_identification')))) {
|
||||
$limiter->record(); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
$limiter->relieve(); return self::enroll($token, 'password');
|
||||
}
|
||||
public static function capabilities(int $id): array
|
||||
{
|
||||
$admin = self::admin($id);
|
||||
$all = ['read', 'bind', 'create', 'unbind', 'rebind', 'batch'];
|
||||
if ((int) $admin['root'] === 1) { return $all; }
|
||||
$perms = AuthLogic::getAuthByAdminId($id);
|
||||
return array_values(array_filter($all, fn($p) => in_array('iamV2/' . $p, $perms, true)));
|
||||
}
|
||||
public static function protectedAccount(int $id): bool
|
||||
{
|
||||
$a = self::admin($id);
|
||||
if ((int) $a['root'] === 1) { return true; }
|
||||
$roles = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
if ($roles && Db::name('system_role')->whereIn('id', $roles)->whereIn('name', ['管理员', '系统管理员', '超级管理员'])->whereNull('delete_time')->count() > 0) { return true; }
|
||||
return count(array_intersect(self::capabilities($id), ['bind','create','unbind','rebind','batch'])) > 0;
|
||||
}
|
||||
public static function visibleIds(int $id): ?array
|
||||
{
|
||||
$a = self::admin($id);
|
||||
$a['role_id'] = Db::name('admin_role')->where('admin_id', $id)->column('role_id');
|
||||
return \app\common\service\DataScope\DataScopeService::getVisibleAdminIds($id, $a);
|
||||
}
|
||||
public static function scope(int $actor, array $targets): void
|
||||
{
|
||||
$visible = self::visibleIds($actor);
|
||||
if ($visible !== null && array_diff(array_map('intval', $targets), $visible)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
}
|
||||
public static function authorize(array $session, string $capability, array $targets = [], bool $recent = true): void
|
||||
{
|
||||
if (!in_array($capability, self::capabilities((int) $session['admin_id']), true)) { throw new RuntimeException('FORBIDDEN'); }
|
||||
if ($recent && $session['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
self::scope((int) $session['admin_id'], $targets);
|
||||
foreach ($targets as $id) {
|
||||
$target = self::admin((int) $id);
|
||||
// v1 deliberately fails closed: no dual-side central-admin reauth protocol yet.
|
||||
if (self::protectedAccount((int) $id)) {
|
||||
throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
}
|
||||
}
|
||||
}
|
||||
public static function proof(array $session, string $purpose, array $targets = [], array $capabilities = [], ?string $transaction = null, array $extra = []): string
|
||||
{
|
||||
self::check($session['session_id'], (int) $session['version']);
|
||||
$secret = bin2hex(random_bytes(32));
|
||||
$payload = ['applicationId' => (string) Config::get('iam.application_id', 'zyt'), 'actorLocalId' => (string) $session['admin_id'],
|
||||
'sessionId' => $session['session_id'], 'sessionVersion' => (int) $session['version'], 'authMethod' => $session['auth_method'],
|
||||
'authTime' => (int) $session['auth_time'], 'expiresAt' => time() + 60, 'capabilities' => $capabilities,
|
||||
'targetLocalIds' => array_map('strval', $targets), 'protectedAccount' => count(array_filter($targets, fn($id) => self::protectedAccount((int) $id))) > 0, 'transactionId' => $transaction];
|
||||
$payload += array_intersect_key($extra, array_flip(['oidcNonce', 'state']));
|
||||
Db::name('iam_v2_proof')->insert(['proof_hash' => hash('sha256', $secret), 'purpose' => $purpose, 'session_id' => $session['session_id'],
|
||||
'payload' => json_encode($payload, JSON_THROW_ON_ERROR), 'expires_at' => time() + 60, 'consumed' => 0]);
|
||||
return $secret;
|
||||
}
|
||||
public static function introspect(string $proof, string $purpose, ?string $transaction = null): array
|
||||
{
|
||||
return Db::transaction(function () use ($proof, $purpose, $transaction) {
|
||||
$hash = hash('sha256', $proof);
|
||||
$r = Db::name('iam_v2_proof')->where('proof_hash', $hash)->lock(true)->find();
|
||||
if (!$r || $r['purpose'] !== $purpose || $r['expires_at'] <= time() || (int) $r['consumed'] !== 0) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$p = json_decode($r['payload'], true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($p['transactionId'] ?? null) !== $transaction) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$session = self::check($p['sessionId'], (int) $p['sessionVersion']);
|
||||
foreach ($p['capabilities'] as $cap) {
|
||||
if (!str_starts_with($cap, 'iam:')) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::authorize($session, substr($cap, 4), $p['targetLocalIds']);
|
||||
}
|
||||
if (Db::name('iam_v2_proof')->where('proof_hash', $hash)->where('consumed', 0)->update(['consumed' => 1]) !== 1) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
return ['active' => true] + $p;
|
||||
});
|
||||
}
|
||||
public static function revokeSession(string $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('session_id', $id)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
public static function revokeAdmin(int $id): void
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('admin_id', $id)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user