feat(auth): 统一身份 - 增加可选IAM快捷登录并保留原业务权限

This commit is contained in:
2026-09-10 10:33:03 +08:00
parent 27fbef9321
commit aa0d22bbe2
518 changed files with 5919 additions and 13 deletions
+115
View File
@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace think\facade {
// In-memory config only: no application bootstrap, database, cache or network.
final class Config
{
public static array $values = [];
public static function get(string $key, $default = null) { return self::$values[$key] ?? $default; }
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\service\iam\IamLoginService;
use app\adminapi\service\iam\IamLoginTransactionStore;
use think\facade\Config;
function txExpect(bool $ok, string $message): void {
if (!$ok) { throw new \RuntimeException('FAIL: ' . $message); }
}
function txReject(callable $call, string $message): void {
try { $call(); } catch (\Throwable $error) { return; }
throw new \RuntimeException('FAIL: accepted ' . $message);
}
$directory = sys_get_temp_dir() . '/zyt-iam-test-' . bin2hex(random_bytes(12));
try {
$store = new IamLoginTransactionStore($directory);
$value = bin2hex(random_bytes(32));
$browser = bin2hex(random_bytes(32));
$store->put('state', $value, $browser, ['nonce' => 'nonce'], 600);
txReject(fn() => $store->consume('state', $value, 'another-browser'), 'wrong browser');
txReject(fn() => $store->consume('ticket', $value, $browser), 'state as ticket');
txExpect($store->consume('state', $value, $browser) === ['nonce' => 'nonce'], 'correct browser can consume after rejected foreign browser');
txReject(fn() => $store->consume('state', $value, $browser), 'state replay');
$store->put('ticket', $value, $browser, ['subject' => 'employee'], 60);
txReject(fn() => $store->consume('state', $value, $browser), 'ticket as state');
txExpect($store->consume('ticket', $value, $browser) === ['subject' => 'employee'], 'same value separate ticket namespace');
txReject(fn() => $store->consume('ticket', $value, $browser), 'ticket replay');
foreach (['state', 'ticket'] as $kind) {
$expired = bin2hex(random_bytes(32));
$store->put($kind, $expired, $browser, ['expired' => true], -1);
txReject(fn() => $store->consume($kind, $expired, $browser), 'expired ' . $kind);
}
foreach (['../escape', '', str_repeat('z', 64), str_repeat('a', 63)] as $invalid) {
txReject(fn() => $store->put('state', $invalid, $browser, [], 60), 'invalid transaction identifier');
}
txReject(fn() => $store->consume('invalid-kind', $value, $browser), 'invalid namespace');
foreach (glob($directory . '/*.json') ?: [] as $file) {
txExpect((fileperms($file) & 0777) === 0600, 'private file permissions');
txExpect(!str_contains((string) file_get_contents($file), $browser), 'browser cookie is hashed at rest');
}
for ($i = 1; $i <= 20; ++$i) {
txExpect($store->allowStart('192.0.2.1'), 'allowed request ' . $i);
}
txExpect(!$store->allowStart('192.0.2.1'), 'request 21 rejected');
txExpect(!$store->allowStart('192.0.2.1'), 'later request rejected');
txExpect($store->allowStart('192.0.2.2'), 'rate limit IP isolation');
$limit = $directory . '/limit-' . hash('sha256', '192.0.2.1') . '.json';
file_put_contents($limit, json_encode(['count' => 20, 'expires' => time() - 1]));
txExpect($store->allowStart('192.0.2.1'), 'expired rate limit resets');
$context = ['applicationId' => 'zyt', 'localIdentityKey' => 'employee',
'employee' => ['oidcSubject' => 'employee', 'status' => 'active'],
'externalAccountId' => '42', 'shouldCreateLocalAccount' => false];
txExpect(IamLoginService::boundAdminId($context, 'employee', 'zyt') === 42, 'explicit existing binding');
foreach (['applicationId' => 'other', 'localIdentityKey' => 'other', 'externalAccountId' => '',
'shouldCreateLocalAccount' => true] as $field => $bad) {
$changed = $context;
$changed[$field] = $bad;
txReject(fn() => IamLoginService::boundAdminId($changed, 'employee', 'zyt'), $field);
}
foreach (['oidcSubject' => 'other', 'status' => 'disabled'] as $field => $bad) {
$changed = $context;
$changed['employee'][$field] = $bad;
txReject(fn() => IamLoginService::boundAdminId($changed, 'employee', 'zyt'), 'employee ' . $field);
}
foreach (['0', '-1', '01', '42.1', '42e1', 'admin', '42 ', '99999999999', null, true, false, 42.0] as $bad) {
$changed = $context;
$changed['externalAccountId'] = $bad;
txReject(fn() => IamLoginService::boundAdminId($changed, 'employee', 'zyt'), 'invalid externalAccountId');
}
foreach (array_keys($context) as $field) {
$changed = $context;
unset($changed[$field]);
txReject(fn() => IamLoginService::boundAdminId($changed, 'employee', 'zyt'), 'missing ' . $field);
}
$changed = $context;
$changed['shouldCreateLocalAccount'] = 'false';
txReject(fn() => IamLoginService::boundAdminId($changed, 'employee', 'zyt'), 'non-boolean creation flag');
foreach ([[], ['enabled' => false], ['enabled' => 'false'], ['enabled' => true]] as $config) {
Config::$values = ['iam' => $config];
txExpect(IamLoginService::settings() === ['enabled' => false, 'loginUrl' => ''], 'disabled/incomplete config stays closed');
txReject(fn() => new IamLoginService(), 'disabled constructor without bootstrap');
}
$config = ['enabled' => true, 'issuer' => 'https://iam.example.test', 'client_id' => 'zyt',
'client_secret' => 'secret', 'redirect_uri' => 'https://zyt.example.test/adminapi/iam/callback',
'api_url' => 'https://iam.example.test', 'application_id' => 'zyt', 'application_token' => 'secret',
'public_url' => 'https://zyt.example.test'];
Config::$values = ['iam' => $config];
txExpect(IamLoginService::settings() === ['enabled' => true, 'loginUrl' => 'https://zyt.example.test/adminapi/iam/start'], 'complete config enables without HTTP');
$config['redirect_uri'] = 'https://zyt.example.test/wrong';
Config::$values = ['iam' => $config];
txExpect(IamLoginService::settings()['enabled'] === false, 'callback URI mismatch');
echo "IamLoginTransactionTest passed (browser binding, replay, namespaces, expiry, 20-request limit, explicit binding, disabled config; no DB/network)\n";
} finally {
foreach (glob($directory . '/*') ?: [] as $file) { unlink($file); }
if (is_dir($directory)) { rmdir($directory); }
}
}
+88
View File
@@ -0,0 +1,88 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import vm from 'node:vm'
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const ts = require('typescript')
const root = new URL('../../', import.meta.url)
const vue = fs.readFileSync(new URL('admin/src/views/account/login.vue', root), 'utf8')
const api = fs.readFileSync(new URL('admin/src/api/user.ts', root), 'utf8')
const store = fs.readFileSync(new URL('admin/src/stores/modules/user.ts', root), 'utf8')
const script = vue.match(/<script lang="ts" setup>([\s\S]*?)<\/script>/)[1]
const js = ts.transpileModule(script, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020 } }).outputText
// Imports are injected with controlled test doubles; all actual component handlers execute.
const runnable = js.replace(/^.*require\(.+\);?$/gm, '').replace(/^Object.defineProperty\(exports.*$/gm, '')
async function scenario(query, result, fail = false, enabled = true, wecomEnabled = false) {
const calls = [], paths = [], errors = []
let mounted, cleaned = ''
const ref = value => ({ value })
const userStore = {
iamLogin: async ticket => { calls.push(['iam', ticket, cleaned]); if (fail) throw new Error('expired'); return result },
workWechatLogin: async code => { calls.push(['wechat', code]); return result }
}
const c = {
exports: {}, console, URL, URLSearchParams,
vue_1: { ref, shallowRef: ref, computed: fn => ref(fn()), watch() {}, nextTick: async fn => fn?.(), onMounted: fn => { mounted = fn } },
user_2: { getIamConfig: async () => ({ enabled, loginUrl: 'https://iam.example/login' }), getWorkWechatConfig: async () => ({ enabled: wecomEnabled, corp_id: 'corp', agent_id: 'agent' }) },
user_1: { default: () => userStore },
app_1: { default: () => ({ config: {} }) },
cache_1: { default: { get() {}, set() {} } },
cacheEnums_1: { ACCOUNT_KEY: 'account' },
pageEnum_1: { PageEnum: { INDEX: '/' } },
useLockFn_1: { useLockFn: fn => ({ isLock: ref(false), lockFn: fn }) },
element_plus_1: { ElMessage: { error: text => errors.push(text) } },
reactive: value => value,
useRoute: () => ({ query: { redirect: '/dashboard' } }),
useRouter: () => ({ push: async path => paths.push(path) }),
navigator: { userAgent: 'wxwork' },
window: { location: { href: `https://zyt.example/admin/login${query}`, origin: 'https://zyt.example', pathname: '/admin/login', search: query, assign: url => calls.push(['assign', url]) }, history: { state: { back: '/' }, replaceState: (_, __, url) => { cleaned = url } } }
}
vm.createContext(c)
vm.runInContext(runnable, c)
await mounted()
await Promise.resolve()
return { calls, paths, errors, cleaned, context: c }
}
for (const [result, destination] of [[{ is_paw: 0, need_bind_work_wechat: true }, '/change-password'], [{ is_paw: 1, need_bind_work_wechat: true }, '/bind-work-wechat'], [{ is_paw: 1 }, '/dashboard']]) {
const s = await scenario('?iam_ticket=one-use&code=wecom&state=admin_login&redirect=%2Fdashboard', result)
assert.equal(s.calls.length, 1)
assert.equal(s.calls[0][0], 'iam')
assert.equal(s.calls[0][1], 'one-use')
assert.equal(s.calls[0][2], '/admin/login?redirect=%2Fdashboard')
assert.deepEqual(s.paths, [destination])
await vm.runInContext("handleIamCallback('one-use', null)", s.context)
assert.equal(s.calls.length, 1)
}
for (const query of ['?iam_error=Denied&code=wecom&state=admin_login', '?iam_ticket=']) {
const s = await scenario(query, {})
assert.equal(s.calls.length, 0)
assert.equal(s.errors.length, 1)
assert.equal(s.cleaned, '/admin/login')
}
const failed = await scenario('?iam_ticket=expired', {}, true)
assert.equal(failed.errors[0], 'expired')
assert.equal(vm.runInContext('iamLoading.value', failed.context), false)
const iamErrorWithWecom = await scenario('?iam_error=Denied', {}, false, true, true)
assert.equal(vm.runInContext('wxWorkEnabled.value', iamErrorWithWecom.context), true)
assert.equal(vm.runInContext('wxWorkAutoLogin.value', iamErrorWithWecom.context), false)
assert.equal(iamErrorWithWecom.calls.length, 0)
const wecom = await scenario('?code=original&state=admin_login', { is_paw: 1 })
assert.equal(wecom.calls[0][0], 'wechat')
assert.equal(wecom.calls[0][1], 'original')
const disabled = await scenario('', {}, false, false)
vm.runInContext('handleIamLogin()', disabled.context)
assert.equal(disabled.calls.length, 0)
const enabled = await scenario('', {})
assert.equal(enabled.calls.length, 0, 'IAM never auto redirects')
vm.runInContext('handleIamLogin()', enabled.context)
assert.equal(enabled.calls[0][0], 'assign')
assert.match(api, /url: '\/iam\/exchange'[\s\S]*withCredentials: true/)
assert.match(api, /withToken: false, isOpenRetry: false/)
assert.match(store, /async iamLogin\(ticket: string\)[\s\S]*cache\.set\(TOKEN_KEY, data\.token\)/)
assert.match(vue, /v-if="iamEnabled"/)
assert.match(vue, /userStore\.login\(formData\)/)
assert.match(vue, /userStore\.workWechatLogin\(code\)/)
console.log('PASS IAM UI: optional entry, callback priority, URL cleanup, one exchange, error recovery, password/bind/local redirects, existing login contracts')
+96
View File
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
require dirname(__DIR__) . '/vendor/autoload.php';
use app\adminapi\service\iam\IamOidcClient;
use Firebase\JWT\JWT;
function iamExpect(bool $ok, string $label): void
{
if (!$ok) { throw new RuntimeException('FAIL: ' . $label); }
}
function iamReject(callable $call, string $label): void
{
try { $call(); } catch (Throwable $error) { return; }
throw new RuntimeException('FAIL: accepted ' . $label);
}
function iamB64(string $value): string { return rtrim(strtr(base64_encode($value), '+/', '-_'), '='); }
$key = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
$other = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
$details = openssl_pkey_get_details($key);
$jwks = ['keys' => [['kty' => 'RSA', 'kid' => 'test', 'alg' => 'RS256', 'use' => 'sig',
'n' => iamB64($details['rsa']['n']), 'e' => iamB64($details['rsa']['e'])]]];
$config = ['issuer' => 'https://iam.example.test', 'client_id' => 'zyt', 'client_secret' => 'secret',
'redirect_uri' => 'https://zyt.example.test/admin/iam/callback', 'api_url' => 'https://iam.example.test',
'application_id' => 'zyt app', 'application_token' => 'application-secret'];
$nonce = str_repeat('n', 32);
$verifier = str_repeat('v', 64);
$metadata = ['issuer' => $config['issuer'], 'authorization_endpoint' => $config['issuer'] . '/oauth/authorize',
'token_endpoint' => $config['issuer'] . '/oauth/token', 'jwks_uri' => $config['issuer'] . '/oauth/jwks'];
$claims = ['iss' => $config['issuer'], 'aud' => 'zyt', 'sub' => 'employee-7', 'nonce' => $nonce,
'iat' => time() - 1, 'exp' => time() + 300, 'nbf' => time() - 1];
$token = JWT::encode($claims, $key, 'RS256', 'test');
$calls = [];
$transport = function (string $method, string $url, array $headers, string $body) use (&$metadata, &$token, &$jwks, &$calls, $config, $verifier): array {
$calls[] = [$method, $url, $headers, $body];
if (str_ends_with($url, '/.well-known/openid-configuration')) { $data = $metadata; }
elseif (str_ends_with($url, '/oauth/token')) {
parse_str($body, $params);
iamExpect($method === 'POST' && $params['code_verifier'] === $verifier && $params['redirect_uri'] === $config['redirect_uri'], 'token form');
iamExpect(in_array('Authorization: Basic ' . base64_encode('zyt:secret'), $headers, true), 'client authentication');
$data = ['id_token' => $token];
} elseif (str_ends_with($url, '/oauth/jwks')) { $data = $jwks; }
elseif (str_ends_with($url, '/provisioning-context')) {
iamExpect(in_array('Authorization: Bearer application-secret', $headers, true), 'application bearer');
iamExpect(str_contains($url, '/zyt%20app/employees/employee-7/'), 'encoded provisioning path');
$data = ['externalAccountId' => '9'];
} else { throw new RuntimeException('Unexpected request'); }
return ['status' => 200, 'body' => json_encode($data, JSON_THROW_ON_ERROR)];
};
$client = new IamOidcClient($config, $transport);
parse_str(parse_url($client->authorizationUrl(str_repeat('s', 32), $nonce, $verifier), PHP_URL_QUERY), $query);
iamExpect($query['code_challenge_method'] === 'S256' && $query['code_challenge'] === iamB64(hash('sha256', $verifier, true)), 'PKCE S256');
iamExpect($client->exchange('code', $verifier, $nonce)['sub'] === 'employee-7', 'valid token');
iamExpect($client->provisioning('employee-7')['externalAccountId'] === '9', 'provisioning');
foreach (['iss' => 'https://other.example.test', 'aud' => 'other', 'nonce' => 'wrong', 'exp' => time() - 1,
'nbf' => time() + 100, 'iat' => time() + 100, 'azp' => 'other', 'sub' => ''] as $field => $value) {
$changed = $claims;
$changed[$field] = $value;
$token = JWT::encode($changed, $key, 'RS256', 'test');
iamReject(fn() => $client->exchange('code', $verifier, $nonce), $field);
}
$changed = $claims;
$changed['aud'] = ['zyt', 'other'];
$token = JWT::encode($changed, $key, 'RS256', 'test');
iamReject(fn() => $client->exchange('code', $verifier, $nonce), 'multiple audiences without azp');
$changed['azp'] = 'zyt';
$token = JWT::encode($changed, $key, 'RS256', 'test');
iamExpect($client->exchange('code', $verifier, $nonce)['azp'] === 'zyt', 'multiple audience azp');
$token = JWT::encode($claims, $other, 'RS256', 'test');
iamReject(fn() => $client->exchange('code', $verifier, $nonce), 'wrong signature');
$token = JWT::encode($claims, str_repeat('s', 64), 'HS256', 'test');
iamReject(fn() => $client->exchange('code', $verifier, $nonce), 'algorithm confusion');
$token = JWT::encode($claims, $key, 'RS256', 'unknown');
iamReject(fn() => $client->exchange('code', $verifier, $nonce), 'unknown kid');
iamReject(fn() => $client->authorizationUrl(str_repeat('s', 32), $nonce, 'short'), 'short verifier');
$metadata['issuer'] = 'https://other.example.test';
iamReject(fn() => (new IamOidcClient($config, $transport))->authorizationUrl(str_repeat('s', 32), $nonce, $verifier), 'discovery issuer');
$metadata['issuer'] = $config['issuer'];
$metadata['jwks_uri'] = 'https://other.example.test/jwks';
iamReject(fn() => (new IamOidcClient($config, $transport))->authorizationUrl(str_repeat('s', 32), $nonce, $verifier), 'cross-origin JWKS');
foreach (['http://iam.example.test', 'https://user@iam.example.test', 'https://iam.example.test/#fragment'] as $invalid) {
$bad = $config;
$bad['issuer'] = $invalid;
iamReject(fn() => new IamOidcClient($bad, $transport), 'invalid HTTPS configuration');
}
$bad = $config;
$bad['api_url'] = 'https://other.example.test';
iamReject(fn() => new IamOidcClient($bad, $transport), 'cross-origin provisioning');
iamReject(fn() => (new IamOidcClient($config, fn() => ['status' => 302, 'body' => '{}']))->authorizationUrl(str_repeat('s', 32), $nonce, $verifier), 'HTTP redirect');
iamReject(fn() => (new IamOidcClient($config, fn() => ['status' => 200, 'body' => 'invalid']))->authorizationUrl(str_repeat('s', 32), $nonce, $verifier), 'invalid JSON');
echo "IamOidcClientTest passed (offline RSA, claims, discovery, PKCE, provisioning, HTTPS)\n";