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; } }