fix(iam): align cross-app proofs and add native IAM target launch
This commit is contained in:
@@ -7,17 +7,17 @@ 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};
|
||||
use app\adminapi\service\iam\v2\{IamV2Client, IamV2Source, IamV2Manager, IamV2Flow, IamV2Target};
|
||||
|
||||
/** 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'];
|
||||
public array $notNeedLogin = ['status', 'introspect', 'checkSession', 'revocation', 'launchContinue', 'selfCallback', 'passwordContinue', 'targetConfig', 'targetPrepare', 'targetCallback', 'targetExchange', 'targetReset'];
|
||||
private function invokeV2(callable $fn)
|
||||
{
|
||||
try {
|
||||
if (!IamV2Client::enabled()) { throw new RuntimeException('FEATURE_DISABLED'); }
|
||||
$reads = ['status','accounts','identities','operationresult','audit','job'];
|
||||
$reads = ['status','accounts','identities','operationresult','audit','job','targetconfig'];
|
||||
$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']);
|
||||
@@ -57,7 +57,9 @@ final class IamV2Controller extends BaseAdminController
|
||||
$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;
|
||||
'management_capabilities' => IamV2Source::capabilities((int) $legacy['admin_id']),
|
||||
'protected_review_operator' => IamV2Source::reviewOperator((int) $legacy['admin_id']),
|
||||
'protected_account' => IamV2Source::protectedAccount((int) $legacy['admin_id'])] + $b;
|
||||
});
|
||||
}
|
||||
public function reauth()
|
||||
@@ -100,8 +102,9 @@ final class IamV2Controller extends BaseAdminController
|
||||
}
|
||||
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']]; });
|
||||
return $this->serviceResult(function () { $this->serviceAuth(); $b = $this->input();
|
||||
return IamV2Source::liveStatus((string) ($b['sessionId'] ?? ''), (int) ($b['sessionVersion'] ?? 0),
|
||||
(string) ($b['purpose'] ?? ''), (array) ($b['targetLocalIds'] ?? [])); });
|
||||
}
|
||||
public function launchStart()
|
||||
{
|
||||
@@ -123,7 +126,9 @@ final class IamV2Controller extends BaseAdminController
|
||||
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';
|
||||
$erpOrigin = IamV2Client::origin((string) Config::get('iam.erp_url'));
|
||||
$delivery = IamV2Client::https((string) Config::get('iam.erp_callback_url') ?: $erpOrigin . '/api/erp/iam/v2/launch/callback');
|
||||
if (!in_array($delivery, [$erpOrigin . '/api/erp/iam/v2/launch/callback', $erpOrigin . '/basic-api/api/erp/iam/v2/launch/callback'], true)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
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']); }
|
||||
@@ -176,6 +181,55 @@ final class IamV2Controller extends BaseAdminController
|
||||
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'); }
|
||||
}
|
||||
private function targetOrigin(): void
|
||||
{
|
||||
if (!$this->request->isPost() || (string) $this->request->header('origin') !== IamV2Client::origin((string) Config::get('iam.public_url'))) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
}
|
||||
public function targetConfig()
|
||||
{
|
||||
if (!IamV2Client::enabled()) { return $this->data(['enabled' => false]); }
|
||||
return $this->invokeV2(function () {
|
||||
$source = (string) $this->request->get('source', 'iam-portal');
|
||||
return ['enabled' => true, 'restart_url' => IamV2Client::origin((string) Config::get('iam.portal_url')) . ($source === 'iam-admin' ? '/admin' : '/portal')];
|
||||
});
|
||||
}
|
||||
public function targetPrepare()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
$out = (new IamV2Target())->prepare((string) $this->request->post('source', ''), (string) $this->request->post('intent', ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Target::COOKIE, $out['browser'], ['expires' => time() + 300, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['url' => $out['url']];
|
||||
});
|
||||
}
|
||||
public function targetCallback()
|
||||
{
|
||||
try {
|
||||
if (!$this->request->isPost()) { throw new RuntimeException('METHOD_NOT_ALLOWED'); }
|
||||
$out = (new IamV2Target())->callback((string) $this->request->post('transaction_id', ''), (string) $this->request->post('grant', ''),
|
||||
(string) ($_COOKIE[IamV2Target::COOKIE] ?? ''), (string) $this->request->header('origin', ''));
|
||||
return redirect('/admin/iam/launch?' . http_build_query($out))->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 redirect('/admin/iam/launch?iam_error=' . rawurlencode($code))->header(['Cache-Control' => 'no-store', 'Referrer-Policy' => 'no-referrer']);
|
||||
}
|
||||
}
|
||||
public function targetExchange()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
return (new IamV2Target())->exchange((string) $this->request->post('ticket', ''), (string) ($_COOKIE[IamV2Target::COOKIE] ?? ''),
|
||||
(string) $this->request->header('token', ''), (string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
});
|
||||
}
|
||||
public function targetReset()
|
||||
{
|
||||
return $this->invokeV2(function () { $this->targetOrigin();
|
||||
IamV2Source::revokeSession((string) ($_COOKIE[IamV2Source::COOKIE] ?? ''));
|
||||
setcookie(IamV2Source::COOKIE, '', ['expires' => 1, 'path' => '/adminapi', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
|
||||
setcookie(IamV2Target::COOKIE, '', ['expires' => 1, 'path' => '/adminapi/iam/v2/launch', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
|
||||
return ['reset' => true];
|
||||
});
|
||||
}
|
||||
public function revocation()
|
||||
{
|
||||
return $this->serviceResult(fn() => \app\adminapi\service\iam\v2\IamV2Events::accept(
|
||||
|
||||
@@ -72,6 +72,8 @@ 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()) {
|
||||
try { \app\adminapi\service\iam\v2\IamV2Target::compensate((string) $token); }
|
||||
catch (\Throwable $e) { return JsonService::fail('统一身份授权已失效或暂时不可用,请重新验证', [], 0); }
|
||||
$binding = \think\facade\Db::name('iam_v2_binding')->where('admin_id', $adminInfo['admin_id'])->find();
|
||||
if ($binding && $binding['state'] !== 'unlinked') {
|
||||
try {
|
||||
|
||||
@@ -21,3 +21,10 @@ 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');
|
||||
|
||||
// ZYT as a target for the same person's IAM admin/portal session only.
|
||||
Route::get('iam/v2/launch/config', 'IamV2/targetConfig');
|
||||
Route::post('iam/v2/launch/prepare', 'IamV2/targetPrepare');
|
||||
Route::post('iam/v2/launch/callback', 'IamV2/targetCallback');
|
||||
Route::post('iam/v2/launch/exchange', 'IamV2/targetExchange');
|
||||
Route::post('iam/v2/launch/reset', 'IamV2/targetReset');
|
||||
|
||||
@@ -36,15 +36,16 @@ 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) {
|
||||
return IamLoginService::boundAdminId($context, $subject, $config['application_id']);
|
||||
}
|
||||
// A local tombstone blocks auto-creation, not an explicitly reviewed newer central binding.
|
||||
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'); }
|
||||
}
|
||||
if (($context['externalAccountId'] ?? null) !== '') {
|
||||
throw new RuntimeException('统一账号绑定状态不一致');
|
||||
}
|
||||
|
||||
@@ -79,9 +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']);
|
||||
$result = (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
|
||||
// Reconcile/revoke the previous binding generation before minting the new token.
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
(new \app\adminapi\service\iam\v2\IamV2Manager())->assertLinked((int) $admin->id);
|
||||
}
|
||||
$result = (array) (new LoginLogic())->login(['account' => $admin->account, 'terminal' => AdminTerminalEnum::PC]);
|
||||
if (\app\adminapi\service\iam\v2\IamV2Client::enabled()) {
|
||||
\app\adminapi\service\iam\v2\IamV2Source::enroll($result['token'], 'oidc', true, (int) ($transaction['auth_time'] ?? 0));
|
||||
}
|
||||
return $result;
|
||||
|
||||
@@ -39,7 +39,11 @@ final class IamV2Client
|
||||
{
|
||||
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']];
|
||||
$management = preg_match('#^/(identities|operations|audit|batch|jobs)(/|[?]|$)#D', $path) === 1;
|
||||
$credential = (string) ($this->settings[$management ? 'v2_management_token' : 'v2_token'] ?? '');
|
||||
if (strlen($credential) < 32 || preg_match('/[\r\n]/', $credential)
|
||||
|| ($management && hash_equals((string) $this->settings['v2_token'], $credential))) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$headers = ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer ' . $credential];
|
||||
if ($method !== 'GET') {
|
||||
$headers[] = 'X-Request-ID: ' . bin2hex(random_bytes(16));
|
||||
$headers[] = 'Idempotency-Key: ' . ($key ?? bin2hex(random_bytes(24)));
|
||||
@@ -59,7 +63,10 @@ final class IamV2Client
|
||||
}
|
||||
$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'])) {
|
||||
$operationEnvelope = isset($result['id']) && is_string($result['id'])
|
||||
&& in_array($result['status'] ?? '', ['pending', 'succeeded', 'failed', 'conflict'], true)
|
||||
&& preg_match('#^/(operations|jobs|batch)(/|$)#D', $path);
|
||||
if (($r['status'] ?? 0) < 200 || $r['status'] >= 300 || (isset($result['error']) && !$operationEnvelope)) {
|
||||
$code = $result['error']['code'] ?? 'SERVICE_UNAVAILABLE';
|
||||
throw new RuntimeException(preg_match('/^[A-Z_]{3,64}$/D', $code) ? $code : 'SERVICE_UNAVAILABLE');
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use think\facade\Db;
|
||||
|
||||
final class IamV2Events
|
||||
{
|
||||
public static function accept(string $raw, string $signature, string $eventId, string $secret, ?callable $revoke = null): array
|
||||
public static function accept(string $raw, string $signature, string $eventId, string $secret, ?callable $revoke = null, ?callable $refresh = null, ?callable $locate = null, ?callable $generation = 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);
|
||||
@@ -15,9 +15,28 @@ final class IamV2Events
|
||||
$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'); }
|
||||
if (!$stamp || $stamp > time() + 60) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$customRevoke = $revoke !== null;
|
||||
$revoke ??= fn(int $id) => IamV2Manager::revoke($id);
|
||||
return Db::transaction(function () use ($event, $eventId, $raw, $revoke) {
|
||||
$refresh ??= fn(int $id) => (new IamV2Manager())->binding($id, true);
|
||||
$generation ??= $customRevoke ? fn(int $id, int $upper) => $revoke($id) : fn(int $id, int $upper) => IamV2Source::revokeGeneration($id, $upper, (string) $event['employeeId']);
|
||||
$locate ??= static function (array $event): array {
|
||||
if (($event['eventType'] ?? '') === 'binding_revoked' && isset($event['externalAccountId'])) {
|
||||
if (!is_string($event['externalAccountId']) || !preg_match('/^[1-9][0-9]{0,9}$/D', $event['externalAccountId'])) { throw new RuntimeException('INVALID_EVENT'); }
|
||||
return [(int) $event['externalAccountId']];
|
||||
}
|
||||
$reply = (new IamV2Client())->call('GET', '/bindings?' . http_build_query(['employeeId' => $event['employeeId'], 'page' => 1, 'pageSize' => 100], '', '&', PHP_QUERY_RFC3986));
|
||||
if (($reply['total'] ?? 0) > 100) { throw new RuntimeException('SERVICE_UNAVAILABLE'); }
|
||||
$ids = [];
|
||||
foreach ($reply['items'] ?? [] as $item) {
|
||||
if (($item['binding']['employeeId'] ?? '') !== $event['employeeId'] || ($item['binding']['applicationId'] ?? '') !== 'zyt') { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$external = (string) ($item['binding']['externalAccountId'] ?? '');
|
||||
if (!preg_match('/^[1-9][0-9]{0,9}$/D', $external)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$ids[] = (int) $external;
|
||||
}
|
||||
return $ids;
|
||||
};
|
||||
return Db::transaction(function () use ($event, $eventId, $raw, $revoke, $refresh, $locate, $generation) {
|
||||
$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'); }
|
||||
@@ -25,11 +44,36 @@ final class IamV2Events
|
||||
}
|
||||
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();
|
||||
if (!$rows && ($event['eventType'] ?? '') !== 'source_binding_revoked') {
|
||||
foreach ($locate($event) as $id) {
|
||||
$row = Db::name('iam_v2_binding')->where('admin_id', $id)->find();
|
||||
if (!$row) { $refresh($id); $row = Db::name('iam_v2_binding')->where('admin_id', $id)->find(); }
|
||||
if ($row) { $rows[] = $row; }
|
||||
}
|
||||
}
|
||||
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']);
|
||||
$bindingEvent = ($event['eventType'] ?? '') === 'binding_revoked'
|
||||
|| in_array($event['reason'] ?? '', ['iam.v2.unbind', 'iam.v2.rebind'], true);
|
||||
// ZYT is source-only in this rollout; target-derived revocation belongs to ERP.
|
||||
if (($event['eventType'] ?? '') === 'source_binding_revoked') { continue; }
|
||||
$upper = isset($event['bindingVersion']) ? (int) $event['bindingVersion'] : null;
|
||||
if ($bindingEvent && $upper !== null && ($upper < (int) $row['version'] || $row['employee_id'] !== $event['employeeId'])) { $generation((int) $row['admin_id'], $upper); continue; }
|
||||
if (!$bindingEvent || $upper === null) {
|
||||
// Durable outbox delivery may be old. Current central state wins over a stale generic event.
|
||||
// A failed lookup rolls back event receipt, so the durable outbox can retry.
|
||||
$current = $refresh((int) $row['admin_id']);
|
||||
if (($current['binding']['state'] ?? '') === 'verified' && ($current['employee']['status'] ?? '') === 'active'
|
||||
&& ($current['access']['allowed'] ?? false)) { continue; }
|
||||
}
|
||||
$updates = ['checked_at' => 0];
|
||||
// Personnel disable/entitlement events invalidate sessions, not the binding itself.
|
||||
// A versioned binding event carries the OLD generation as its revocation upper bound.
|
||||
if ($bindingEvent && $upper !== null && $upper > 0) {
|
||||
$updates['state'] = 'revoked'; $updates['version'] = max((int) $row['version'], $upper);
|
||||
}
|
||||
Db::name('iam_v2_binding')->where('admin_id', $row['admin_id'])->update($updates);
|
||||
if ($bindingEvent && $upper !== null) { $generation((int) $row['admin_id'], $upper); }
|
||||
else { $revoke((int) $row['admin_id']); }
|
||||
}
|
||||
return ['accepted' => true];
|
||||
});
|
||||
|
||||
@@ -12,6 +12,14 @@ final class IamV2Flow
|
||||
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 peek(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
$row = Db::name('iam_v2_flow')->where('flow_key', hash('sha256', $kind . ':' . $secret))->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'); }
|
||||
return $p;
|
||||
}
|
||||
public static function take(string $kind, string $secret, string $sid): array
|
||||
{
|
||||
return Db::transaction(function () use ($kind, $secret, $sid) {
|
||||
|
||||
@@ -17,6 +17,13 @@ final class IamV2Manager
|
||||
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'); }
|
||||
if ($result['binding'] ?? null) {
|
||||
$b = $result['binding']; $employee = $result['employee'] ?? [];
|
||||
if (($b['applicationId'] ?? '') !== (string) Config::get('iam.application_id', 'zyt')
|
||||
|| !is_int($b['version'] ?? null) || $b['version'] < 1
|
||||
|| !in_array($b['state'] ?? '', ['verified','revoked','pending','conflict'], true)
|
||||
|| empty($employee['id']) || ($b['employeeId'] ?? '') !== $employee['id'] || empty($employee['oidcSubject'])) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
}
|
||||
$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'); }
|
||||
@@ -25,9 +32,11 @@ final class IamV2Manager
|
||||
'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)))) {
|
||||
$changed = $row && $row['state'] === 'verified' && (($row['employee_id'] ?? '') !== ($values['employee_id'] ?? '') || (int) $row['version'] !== $version);
|
||||
if ($state === 'revoked' || (($result['employee'] ?? null) && (($result['employee']['status'] ?? '') !== 'active' || !($result['access']['allowed'] ?? false)))) {
|
||||
self::revoke($id);
|
||||
} elseif ($changed) {
|
||||
IamV2Source::revokeGeneration($id, (int) $row['version'], (string) $row['employee_id']);
|
||||
}
|
||||
return $result + ['checked_at' => time()];
|
||||
}
|
||||
@@ -68,8 +77,8 @@ final class IamV2Manager
|
||||
$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 ($id < 1 || strlen(trim((string) ($input['reason'] ?? ''))) < 3) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$out = ['kind' => $kind, 'externalAccountId' => (string) $id, 'reason' => mb_strcut(trim($input['reason']), 0, 500, 'UTF-8')];
|
||||
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'); }
|
||||
@@ -84,18 +93,36 @@ final class IamV2Manager
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
public static function cap(string $kind): string { return ['create_and_bind' => 'create', 'reconcile' => 'read'][$kind] ?? $kind; }
|
||||
public static function cap(string $kind): string { return ['create_and_bind' => 'create', 'reconcile' => 'bind'][$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]);
|
||||
IamV2Source::authorize($session, $cap, [$target], true, true);
|
||||
$current = $this->binding($target, true); $caps = ['iam:' . $cap];
|
||||
if ($body['kind'] === 'create_and_bind' && ($current['binding']['state'] ?? '') === 'revoked') {
|
||||
if (!isset($body['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$target], true, true); $caps[] = 'iam:rebind';
|
||||
}
|
||||
$body['proof'] = IamV2Source::proof($session, 'management', [$target], $caps, null, ['protectedReviewEligible' => IamV2Source::reviewOperator((int) $session['admin_id'])]);
|
||||
$op = $this->client->call('POST', '/operations', $body, $requestId);
|
||||
$this->remember('operation', (string) $op['id'], $session, [$target], ['iam:' . $cap]);
|
||||
$op = $this->reviewLink($op);
|
||||
$this->remember('operation', (string) $op['id'], $session, [$target], $caps);
|
||||
if (($op['status'] ?? '') === 'succeeded') { $this->binding($target, true); }
|
||||
return $op;
|
||||
}
|
||||
private function reviewLink(array $operation): array
|
||||
{
|
||||
if (!isset($operation['reviewUrl'])) { return $operation; }
|
||||
$origin = IamV2Client::origin((string) Config::get('iam.portal_url'));
|
||||
$parts = parse_url((string) $operation['reviewUrl']);
|
||||
$fixed = parse_url($origin);
|
||||
if (!$parts || ($parts['scheme'] ?? '') !== 'https' || ($parts['host'] ?? '') !== $fixed['host']
|
||||
|| ($parts['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($parts['path'] ?? '') !== '/admin/iam/review'
|
||||
|| isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($parts['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['request'] ?? null) !== ($operation['id'] ?? null)) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
return $operation;
|
||||
}
|
||||
public function remember(string $kind, string $id, array $session, array $targets, array $caps = []): void
|
||||
{
|
||||
$key = hash('sha256', $kind . ':' . $id);
|
||||
@@ -115,12 +142,17 @@ final class IamV2Manager
|
||||
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 = [];
|
||||
IamV2Source::authorize($session, 'batch'); $mapped = []; $targets = []; $caps = ['iam:batch']; $indexMap = []; $review = []; $itemCaps = [];
|
||||
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;
|
||||
$held = ['iam:' . $cap];
|
||||
if ($item['kind'] === 'create_and_bind' && (($this->binding($id, true)['binding']['state'] ?? '') === 'revoked')) {
|
||||
if (!isset($item['expectedVersion'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Source::authorize($session, 'rebind', [$id]); $held[] = 'iam:rebind';
|
||||
}
|
||||
$indexMap[] = (int) $index; $mapped[] = $item; $targets[] = $id; $itemCaps[] = $held; $caps = array_merge($caps, $held);
|
||||
} catch (RuntimeException $e) {
|
||||
$review[] = ['index' => (int) $index, 'externalAccountId' => (string) ($input['user_id'] ?? ''),
|
||||
'status' => $e->getMessage() === 'PROTECTED_ACCOUNT_REVIEW_REQUIRED' ? 'review' : 'invalid', 'message' => $e->getMessage()];
|
||||
@@ -140,29 +172,60 @@ final class IamV2Manager
|
||||
}
|
||||
unset($item);
|
||||
Db::name('iam_v2_resource')->where('resource_key', $resource)->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'indexMap' => $indexMap, 'ready' => $ready])]);
|
||||
'targets' => $targets, 'capabilities' => $caps, 'indexMap' => $indexMap, 'ready' => $ready, 'itemCaps' => $itemCaps])]);
|
||||
$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']); }
|
||||
$scope = $this->owned('preview', $preview, $session);
|
||||
$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);
|
||||
$targets = array_map(fn($i) => $scope['targets'][$i], $indexes); $caps = ['iam:batch']; $itemCaps = [];
|
||||
foreach ($indexes as $i) { $itemCaps[$i] = $scope['itemCaps'][$i] ?? $scope['capabilities']; $caps = array_merge($caps, $itemCaps[$i]); }
|
||||
$caps = array_values(array_unique($caps));
|
||||
foreach ($caps as $cap) { IamV2Source::authorize($session, substr($cap, 4), $targets); }
|
||||
$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;
|
||||
'proof' => IamV2Source::proof($session, 'management', $targets, $caps)], $key);
|
||||
$this->remember('job', (string) $r['id'], $session, $targets, $caps);
|
||||
Db::name('iam_v2_resource')->where('resource_key', hash('sha256', 'job:' . $r['id']))->update(['payload' => json_encode([
|
||||
'targets' => $targets, 'capabilities' => $caps, 'itemCaps' => $itemCaps, 'centralIndexes' => $indexes])]);
|
||||
return $r;
|
||||
}
|
||||
/** Public retry indexes are job.items positions, not original central preview indexes. */
|
||||
public static function retrySelection(array $job, array $positions = []): array
|
||||
{
|
||||
$items = $job['items'] ?? []; $central = $job['indexes'] ?? [];
|
||||
if ($positions === []) { $positions = array_keys($items); }
|
||||
$indexes = []; $targets = []; $caps = ['iam:batch'];
|
||||
foreach (array_unique($positions) as $position) {
|
||||
if (!is_int($position) || !isset($items[$position], $central[$position])) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
$item = $items[$position];
|
||||
if (!in_array($item['status'] ?? '', ['failed', 'pending'], true)) { continue; }
|
||||
$indexes[] = $central[$position]; $targets[] = (int) $item['externalAccountId']; $caps[] = 'iam:' . self::cap($item['kind']);
|
||||
}
|
||||
return ['indexes' => $indexes, 'targets' => $targets, 'capabilities' => array_values(array_unique($caps))];
|
||||
}
|
||||
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'])]);
|
||||
$job = $this->client->call('GET', $path);
|
||||
// The saved mapping prevents the central endpoint changing this operation's target set.
|
||||
if (!isset($job['indexes'])) { $job['indexes'] = $scope['centralIndexes'] ?? []; }
|
||||
$selected = self::retrySelection($job, $indexes);
|
||||
if (!$selected['indexes']) { return $job; }
|
||||
if (array_diff($selected['targets'], array_map('intval', $scope['targets']))) { throw new RuntimeException('FORBIDDEN'); }
|
||||
foreach ($selected['indexes'] as $i) { $selected['capabilities'] = array_merge($selected['capabilities'], $scope['itemCaps'][$i] ?? []); }
|
||||
$selected['capabilities'] = array_values(array_unique($selected['capabilities']));
|
||||
foreach ($selected['capabilities'] as $cap) { IamV2Source::authorize($session, substr($cap, 4), $selected['targets']); }
|
||||
$r = $this->client->call('POST', $path . '/retry', ['indexes' => $selected['indexes'],
|
||||
'proof' => IamV2Source::proof($session, 'management', $selected['targets'], $selected['capabilities'])]);
|
||||
$scope['targets'] = $selected['targets'];
|
||||
} else { $r = $this->client->call('GET', $path); }
|
||||
foreach ($scope['targets'] as $target) { $this->binding((int) $target, true); } return $r;
|
||||
foreach ($scope['targets'] as $target) { $this->binding((int) $target, true); }
|
||||
return $kind === 'operation' ? $this->reviewLink($r) : $r;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,16 +15,18 @@ 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'); }
|
||||
if (!in_array($method, ['password', 'wecom', 'oidc', 'iam_launch'], true)) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (in_array($method, ['oidc', 'iam_launch'], true) && $authTime !== null && ($authTime < 0 || $authTime > time() + 60)) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
$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); }
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $legacy['admin_id'])->where('state', 'verified')->find();
|
||||
$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)];
|
||||
'token_hash' => hash('sha256', $token), 'account_stamp' => self::accountStamp($admin), 'auth_method' => $method, 'auth_time' => in_array($method, ['oidc', 'iam_launch'], true) ? max(0, $authTime ?? 0) : time(),
|
||||
'version' => 1, 'revoked' => 0, 'binding_version' => (int) ($binding['version'] ?? 0), 'employee_id' => $binding['employee_id'] ?? '', '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']);
|
||||
@@ -57,8 +59,36 @@ final class IamV2Source
|
||||
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'); }
|
||||
if ((int) ($s['binding_version'] ?? 0) > 0) {
|
||||
$binding = Db::name('iam_v2_binding')->where('admin_id', $s['admin_id'])->find();
|
||||
if ($binding && ($binding['state'] === 'revoked' || (int) $binding['version'] > (int) $s['binding_version'] || $binding['employee_id'] !== $s['employee_id'])) {
|
||||
self::revokeSession($id); throw new RuntimeException('REAUTH_REQUIRED');
|
||||
}
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
/** Service callback: local-only live authorization, safe while central holds its state lock. */
|
||||
public static function liveStatus(string $id, int $version, string $purpose = '', array $targets = []): array
|
||||
{
|
||||
$s = self::check($id, $version);
|
||||
$out = ['active' => true, 'actorLocalId' => (string) $s['admin_id'], 'sessionId' => $s['session_id'], 'sessionVersion' => (int) $s['version'],
|
||||
'authMethod' => $s['auth_method'], 'authTime' => (int) $s['auth_time'], 'expiresAt' => (int) $s['expires_at']];
|
||||
if ($purpose !== 'management') { return $out; }
|
||||
if ($s['auth_time'] < time() - 300) { throw new RuntimeException('REAUTH_REQUIRED'); }
|
||||
if (!$targets || count($targets) > 100) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
foreach ($targets as $target) {
|
||||
if (!is_string($target) || !preg_match('/^[1-9][0-9]{0,9}$/D', $target)) { throw new RuntimeException('INVALID_INPUT'); }
|
||||
}
|
||||
$caps = self::capabilities((int) $s['admin_id']);
|
||||
if (!$caps) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::scope((int) $s['admin_id'], $targets);
|
||||
$protected = false;
|
||||
foreach ($targets as $target) { self::admin((int) $target); $protected = self::protectedAccount((int) $target) || $protected; }
|
||||
$eligible = count($targets) === 1 && self::reviewOperator((int) $s['admin_id']);
|
||||
if ($protected && !$eligible) { throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED'); }
|
||||
return $out + ['purpose' => 'management', 'capabilities' => array_map(fn($c) => 'iam:' . $c, $caps),
|
||||
'targetLocalIds' => $targets, 'protectedAccount' => $protected, 'protectedReviewEligible' => $eligible];
|
||||
}
|
||||
public static function reauth(string $token, string $password): array
|
||||
{
|
||||
$legacy = Db::name('admin_session')->where('token', $token)->where('expire_time', '>', time())->find();
|
||||
@@ -80,13 +110,16 @@ final class IamV2Source
|
||||
$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
|
||||
public static function reviewOperator(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;
|
||||
return $roles && Db::name('system_role')->whereIn('id', $roles)->whereIn('name', ['管理员', '系统管理员', '超级管理员'])->whereNull('delete_time')->count() > 0;
|
||||
}
|
||||
public static function protectedAccount(int $id): bool
|
||||
{
|
||||
return self::reviewOperator($id) || count(array_intersect(self::capabilities($id), ['bind','create','unbind','rebind','batch'])) > 0;
|
||||
}
|
||||
public static function visibleIds(int $id): ?array
|
||||
{
|
||||
@@ -99,15 +132,15 @@ final class IamV2Source
|
||||
$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
|
||||
public static function authorize(array $session, string $capability, array $targets = [], bool $recent = true, bool $protectedReview = false): 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)) {
|
||||
// Single-target high-privilege requests may reach central review, never bypass it.
|
||||
if (self::protectedAccount((int) $id) && !($protectedReview && count($targets) === 1 && self::reviewOperator((int) $session['admin_id']))) {
|
||||
throw new RuntimeException('PROTECTED_ACCOUNT_REVIEW_REQUIRED');
|
||||
}
|
||||
}
|
||||
@@ -120,13 +153,15 @@ final class IamV2Source
|
||||
'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']));
|
||||
$payload += array_intersect_key($extra, array_flip(['oidcNonce', 'state', 'protectedReviewEligible']));
|
||||
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
|
||||
{
|
||||
// The central Go attestor serializes an absent transaction as an empty string.
|
||||
$transaction = $transaction === '' ? null : $transaction;
|
||||
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();
|
||||
@@ -134,10 +169,14 @@ final class IamV2Source
|
||||
$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']);
|
||||
$p['protectedReviewEligible'] = ($p['protectedReviewEligible'] ?? false) === true
|
||||
&& count($p['targetLocalIds']) === 1 && self::reviewOperator((int) $session['admin_id']);
|
||||
foreach ($p['capabilities'] as $cap) {
|
||||
if (!str_starts_with($cap, 'iam:')) { throw new RuntimeException('FORBIDDEN'); }
|
||||
self::authorize($session, substr($cap, 4), $p['targetLocalIds']);
|
||||
self::authorize($session, substr($cap, 4), $p['targetLocalIds'], true, ($p['protectedReviewEligible'] ?? false) === true && count($p['targetLocalIds']) === 1);
|
||||
}
|
||||
// Target protection can change during the proof's short lifetime. Recompute it.
|
||||
$p['protectedAccount'] = count(array_filter($p['targetLocalIds'], fn($id) => self::protectedAccount((int) $id))) > 0;
|
||||
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;
|
||||
});
|
||||
@@ -146,6 +185,19 @@ final class IamV2Source
|
||||
{
|
||||
Db::name('iam_v2_source_session')->where('session_id', $id)->inc('version')->update(['revoked' => 1]);
|
||||
}
|
||||
public static function revokeGeneration(int $id, int $upper, ?string $employeeId = null): void
|
||||
{
|
||||
$query = Db::name('iam_v2_source_session')->where('admin_id', $id)->where('binding_version', '<=', $upper);
|
||||
if ($employeeId !== null) { $query->where(function ($q) use ($employeeId) { $q->where('employee_id', $employeeId)->whereOr('binding_version', 0); }); }
|
||||
$sessions = $query->select()->toArray();
|
||||
foreach ($sessions as $s) { self::revokeSession($s['session_id']); }
|
||||
foreach ($sessions as $s) {
|
||||
$newer = Db::name('iam_v2_source_session')->where('token_hash', $s['token_hash'])->where('revoked', 0)->where('expires_at', '>', time())->find();
|
||||
if ($newer) { continue; }
|
||||
$legacy = Db::name('admin_session')->where('id', $s['business_session_id'])->find();
|
||||
if ($legacy && hash_equals($s['token_hash'], hash('sha256', $legacy['token']))) { \app\adminapi\logic\auth\AdminLogic::expireToken($legacy['token']); }
|
||||
}
|
||||
}
|
||||
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]);
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
namespace app\adminapi\service\iam\v2;
|
||||
|
||||
use RuntimeException;
|
||||
use think\facade\Config;
|
||||
use think\facade\Db;
|
||||
use app\adminapi\logic\LoginLogic;
|
||||
use app\adminapi\logic\auth\AdminLogic;
|
||||
use app\adminapi\service\iam\{IamAccountProvisioner, IamOidcClient};
|
||||
use app\common\enum\AdminTerminalEnum;
|
||||
|
||||
/** ZYT target accepts only the person's own IAM admin/portal source, never ERP. */
|
||||
final class IamV2Target
|
||||
{
|
||||
public const COOKIE = 'ZYT_IAM_V2_TARGET';
|
||||
private array $settings;
|
||||
public function __construct(private ?IamV2Client $client = null, private $resolve = null, private $login = null)
|
||||
{
|
||||
$this->settings = (array) Config::get('iam');
|
||||
$this->client ??= new IamV2Client();
|
||||
$this->resolve ??= fn(array $result) => $this->resolveAdmin($result);
|
||||
$this->login ??= function (int $id, array $authentication): array {
|
||||
$admin = IamV2Source::admin($id);
|
||||
$result = (array) (new LoginLogic())->login(['account' => $admin['account'], 'terminal' => AdminTerminalEnum::PC]);
|
||||
IamV2Source::enroll($result['token'], 'iam_launch', true, self::authTime($authentication['authTime'] ?? null));
|
||||
return $result;
|
||||
};
|
||||
}
|
||||
public static function authTime($value): int
|
||||
{
|
||||
$time = is_int($value) ? $value : (is_string($value) ? strtotime($value) : false);
|
||||
if (!$time || $time < 0 || $time > time() + 60) { throw new RuntimeException('INVALID_AUTHENTICATION'); }
|
||||
return $time;
|
||||
}
|
||||
private function registered(string $source): string
|
||||
{
|
||||
$sources = $this->settings['v2_sources'] ?? [];
|
||||
if (!in_array($source, ['iam-admin', 'iam-portal'], true) || !is_array($sources) || !isset($sources[$source])) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
return IamV2Client::https((string) $sources[$source]);
|
||||
}
|
||||
public static function existing(string $token, string $sourceSession = ''): ?int
|
||||
{
|
||||
$id = null;
|
||||
if ($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']); $id = (int) $legacy['admin_id'];
|
||||
}
|
||||
if ($sourceSession !== '') {
|
||||
try { $session = IamV2Source::check($sourceSession); } catch (RuntimeException $e) { $session = null; }
|
||||
if ($session) {
|
||||
if ($id !== null && $id !== (int) $session['admin_id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) $session['admin_id'];
|
||||
}
|
||||
}
|
||||
return $id;
|
||||
}
|
||||
public function prepare(string $source, string $intent, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$registered = $this->registered($source);
|
||||
if (!preg_match('/^[A-Za-z0-9_-]{32,256}$/D', $intent)) { throw new RuntimeException('INVALID_REQUEST'); }
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
$browser = bin2hex(random_bytes(32)); $state = bin2hex(random_bytes(32)); $verifier = bin2hex(random_bytes(32));
|
||||
$tx = $this->client->call('POST', '/launch-transactions', ['sourceApplicationId' => $source, 'stateHash' => hash('sha256', $state),
|
||||
'codeChallenge' => rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=')]);
|
||||
$id = $tx['transactionId'] ?? '';
|
||||
if (!is_string($id) || !preg_match('/^[A-Za-z0-9_-]{1,128}$/D', $id)) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
$actual = parse_url((string) ($tx['sourceContinueUrl'] ?? '')); $fixed = parse_url($registered);
|
||||
if (!$actual || ($actual['scheme'] ?? '') !== $fixed['scheme'] || ($actual['host'] ?? '') !== $fixed['host']
|
||||
|| ($actual['port'] ?? 443) !== ($fixed['port'] ?? 443) || ($actual['path'] ?? '') !== ($fixed['path'] ?? '')
|
||||
|| isset($actual['user']) || isset($actual['pass']) || isset($actual['fragment'])) { throw new RuntimeException('INVALID_FIXED_URL'); }
|
||||
parse_str($actual['query'] ?? '', $query);
|
||||
if (count($query) !== 1 || ($query['transaction_id'] ?? null) !== $id) { throw new RuntimeException('INVALID_RESPONSE'); }
|
||||
IamV2Flow::put('target_launch', $id, ['sessionId' => hash('sha256', $browser), 'source' => $source, 'verifier' => $verifier,
|
||||
'stateHash' => hash('sha256', $state), 'expectedAdminId' => $existing]);
|
||||
return ['url' => $registered . '?' . http_build_query(['transaction_id' => $id, 'intent' => $intent], '', '&', PHP_QUERY_RFC3986), 'browser' => $browser];
|
||||
}
|
||||
public function callback(string $transaction, string $grant, string $browser, string $origin): array
|
||||
{
|
||||
if (!preg_match('/^[a-f0-9]{64}$/D', $browser) || !preg_match('/^[A-Za-z0-9_-]{43}$/D', $grant)) { throw new RuntimeException('TRANSACTION_EXPIRED'); }
|
||||
$flow = IamV2Flow::peek('target_launch', $transaction, hash('sha256', $browser));
|
||||
$source = parse_url($this->registered($flow['source']));
|
||||
$expectedOrigin = $source['scheme'] . '://' . $source['host'] . (isset($source['port']) ? ':' . $source['port'] : '');
|
||||
if ($origin !== $expectedOrigin) { throw new RuntimeException('INVALID_ORIGIN'); }
|
||||
IamV2Flow::take('target_launch', $transaction, hash('sha256', $browser));
|
||||
$result = $this->client->call('POST', '/launch-grants/exchange', ['transactionId' => $transaction, 'grant' => $grant, 'codeVerifier' => $flow['verifier']]);
|
||||
$employee = $result['employee'] ?? []; $auth = $result['authentication'] ?? [];
|
||||
if (($employee['status'] ?? '') !== 'active' || !is_string($employee['oidcSubject'] ?? null) || $employee['oidcSubject'] === ''
|
||||
|| empty($employee['id']) || !($result['access']['allowed'] ?? false) || ($auth['sourceApplicationId'] ?? '') !== $flow['source']
|
||||
|| empty($auth['sessionId']) || !is_string($auth['authMethod'] ?? null) || $auth['authMethod'] === '' || !is_int($auth['sessionVersion'] ?? null) || $auth['sessionVersion'] < 1) { throw new RuntimeException('NOT_AUTHORIZED'); }
|
||||
self::authTime($auth['authTime'] ?? null);
|
||||
if ($flow['expectedAdminId'] !== null && (string) ($result['binding']['externalAccountId'] ?? '') !== (string) $flow['expectedAdminId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$id = (int) ($this->resolve)($result);
|
||||
if ($id < 1 || ($flow['expectedAdminId'] !== null && $id !== (int) $flow['expectedAdminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
IamV2Source::admin($id);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $employee['oidcSubject']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$ticket = bin2hex(random_bytes(32));
|
||||
IamV2Flow::put('target_ticket', $ticket, ['sessionId' => hash('sha256', $browser), 'adminId' => $id, 'expectedAdminId' => $flow['expectedAdminId'],
|
||||
'employeeId' => $employee['id'], 'bindingVersion' => (int) $current['binding']['version'], 'source' => $flow['source'], 'authentication' => $auth], 60);
|
||||
return ['ticket' => $ticket, 'source' => $flow['source']];
|
||||
}
|
||||
private function resolveAdmin(array $result): int
|
||||
{
|
||||
$employee = $result['employee']; $subject = $employee['oidcSubject'];
|
||||
$client = new IamOidcClient($this->settings); $context = $client->provisioning($subject);
|
||||
if (($context['employee']['id'] ?? '') !== $employee['id']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$binding = $result['binding'] ?? null;
|
||||
if ($binding && (($binding['applicationId'] ?? '') !== 'zyt' || ($binding['state'] ?? '') !== 'verified'
|
||||
|| (string) ($context['externalAccountId'] ?? '') !== (string) $binding['externalAccountId']
|
||||
|| (int) ($context['bindingVersion'] ?? 0) !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
if (!$binding && ($context['externalAccountId'] ?? '') !== '') { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
$id = (new IamAccountProvisioner())->resolve($client, $this->settings, $subject);
|
||||
$current = (new IamV2Manager($this->client))->assertLinked($id);
|
||||
if (($current['employee']['id'] ?? '') !== $employee['id'] || ($current['employee']['oidcSubject'] ?? '') !== $subject
|
||||
|| ($binding && (int) $current['binding']['version'] !== (int) $binding['version'])) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
return $id;
|
||||
}
|
||||
public function exchange(string $ticket, string $browser, string $token, string $sourceSession = ''): array
|
||||
{
|
||||
$flow = IamV2Flow::peek('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$existing = self::existing($token, $sourceSession);
|
||||
if (($flow['expectedAdminId'] !== null && $existing !== (int) $flow['expectedAdminId']) || ($existing !== null && $existing !== (int) $flow['adminId'])) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
$current = (new IamV2Manager($this->client))->assertLinked((int) $flow['adminId']);
|
||||
if (($current['employee']['id'] ?? '') !== $flow['employeeId']) { throw new RuntimeException('ACCOUNT_MISMATCH'); }
|
||||
if ((int) $current['binding']['version'] !== (int) $flow['bindingVersion']) { throw new RuntimeException('BINDING_CONFLICT'); }
|
||||
IamV2Flow::take('target_ticket', $ticket, hash('sha256', $browser));
|
||||
$result = ($this->login)((int) $flow['adminId'], $flow['authentication']);
|
||||
$hash = hash('sha256', $result['token']);
|
||||
$values = ['token_hash' => $hash, 'admin_id' => (int) $flow['adminId'], 'employee_id' => $flow['employeeId'],
|
||||
'source_application_id' => $flow['source'], 'source_binding_version' => (int) ($flow['authentication']['sourceBindingVersion'] ?? 0), 'checked_at' => time()];
|
||||
$old = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if ($old) { Db::name('iam_v2_target_session')->where('token_hash', $hash)->update($values); }
|
||||
else { Db::name('iam_v2_target_session')->insert($values); }
|
||||
return $result;
|
||||
}
|
||||
public static function compensate(string $token): void
|
||||
{
|
||||
$hash = hash('sha256', $token); $row = Db::name('iam_v2_target_session')->where('token_hash', $hash)->find();
|
||||
if (!$row || $row['checked_at'] > time() - 30) { return; }
|
||||
$query = http_build_query(['employeeId' => $row['employee_id'], 'sourceApplicationId' => $row['source_application_id'],
|
||||
'sourceBindingVersion' => (int) $row['source_binding_version']], '', '&', PHP_QUERY_RFC3986);
|
||||
$check = (new IamV2Client())->call('GET', '/launch-authorizations/check?' . $query);
|
||||
if (!($check['allowed'] ?? false)) {
|
||||
Db::name('iam_v2_source_session')->where('token_hash', $hash)->where('revoked', 0)->inc('version')->update(['revoked' => 1]);
|
||||
AdminLogic::expireToken($token); throw new RuntimeException('NOT_AUTHORIZED');
|
||||
}
|
||||
Db::name('iam_v2_target_session')->where('token_hash', $hash)->update(['checked_at' => time()]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user