35 changed files with 3001 additions and 26 deletions
+6
View File
@@ -42,3 +42,9 @@ out/
*.log
__pycache__/
frontend/node_modules/
frontend/dist/
frontend/test-results/
frontend/playwright-report/
.playwright-cli/
+1 -1
View File
@@ -3,7 +3,7 @@
- 后续修改必须新建分支并提交 PR;未经维护者明确指示,不直接推 main、不自行合并。
- 默认中文维护项目文档、commit、issue 和 PR;代码与上游 API 名称保留英文。
- 项目使用 Java 与 Spring;Native 是交付约束,不是可选优化,不引入 Kotlin。
- 变更需通过适用的 JVM 测试和 Native 集成测试;未执行的验证明确报告。
- 日常变更先通过适用的 JVM 测试,不要求每轮执行耗时的 Native 编译与测试;Native 仍为交付目标,在阶段性验收或兼容性风险变化时集中验证。未执行的验证明确报告。
- 只实现当前任务范围。Hydra 负责签发,首轮 AD 负责身份和组,本服务独立于 Ayatori。
- 不把 LDAP 密码成功当成完整 MFA 成功;所有因素绑定同一主体与认证事务。
- 不提交凭据、MFA secret、生产配置秘密或包含上述内容的测试输出。
+20 -4
View File
@@ -1,7 +1,7 @@
# iam-login
独立 IAM 的登录与认证服务,以 Java、Spring Security 和 GraalVM Native 实现,作为
Hydra 的 Login/Consent 应用。当前已生成 Spring Initializr 骨架,尚未实现 AD、MFA 与 Hydra 登录链路。
Hydra 的 Login/Consent 应用。已实现 AD 密码与直接所属组查询,以及等待 MFA 的浏览器页面;MFA 与 Hydra 登录链路仍待实现。
## 职责与边界
@@ -34,7 +34,8 @@ Hydra 的 Login/Consent 应用。当前已生成 Spring Initializr 骨架,尚
4.1.1 和 Gradle;Spring Security 等库由 Boot BOM 管理,插件版本在 build.gradle 中固定。
Native 使用 GraalVM 25。
Native 构建与原生二进制上的认证测试是交付要求;JVM 测试通过或 native 编译成功都不
日常改动先跑 JVM 测试,不要求每轮编译 Native。Native 构建与原生二进制上的认证测试
留在阶段性验收;JVM 测试通过或 native 编译成功都不
单独构成验收。Keycloak 可作为流程与安全边界参考,不以它采用 Quarkus 作为 native
兼容性证据,不直接引入其服务端 SPI 和模型。
@@ -46,12 +47,14 @@ Native 构建与原生二进制上的认证测试是交付要求;JVM 测试通
[项目初始化](docs/bootstrap.md)。使用 JDK 25 执行:
```sh
npm --prefix frontend ci
npm --prefix frontend run build
./gradlew test testAot
./gradlew bootRun
```
测试需要可用的 Docker,生成器配置了 Grafana LGTM Testcontainer。
当前只有默认应用和上下文测试,默认 Spring Security 登录页不是可用的 IAM 登录流程。
包含隔离浏览器原型和 AD 第一因素测试;默认 Spring Security 登录页不是 IAM 登录流程。
使用 GraalVM 25 验证原生测试与编译:
```sh
@@ -63,4 +66,17 @@ Docker 开发使用 `scripts/gradle-in-docker`,默认持久挂载 Gradle 缓
原生应用可用 `python3 scripts/native-smoke.py` 检查启动、默认访问控制和 HTTP 指标。
JVM、AOT、Native 测试及原生应用 HTTP 检查已通过,实测范围与资源数据见
[本地验证结果](docs/bootstrap.md#2026-09-25-本地验证结果)。
AD、MFA 与 Hydra 认证链路仍待实现与验收。
新增 AD 路径本轮按维护者要求只进行 JVM 验证,不沿用基线的 Native 验收结论。
真实目录密码与属性/直接所属组读取已通过维护者浏览器验收;MFA 与 Hydra 链路仍待实现。
## 浏览器流程预览
人类登录界面采用 React + Vite,参考 Keycloakify 的内联上下文与原生表单提交方式。
原型默认关闭,仅测试页面切换与局部交互,不执行真实认证。启动、浏览器测试和边界见
[浏览器流程原型](docs/browser-preview.md)。
## AD 第一因素接入
真实入口为 `/signin`,默认关闭且要求 HTTPS。密码验证通过后显示 AD 身份与直接所属组,
停在等待 MFA 状态,不建立完整登录身份或接受 Hydra challenge。
配置、组语义、HTTPS 与验收边界见 [AD 接入](docs/ad-login.md)。
+13
View File
@@ -27,6 +27,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.security:spring-security-webauthn'
implementation 'org.springframework.security:spring-security-ldap'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
@@ -71,3 +72,15 @@ graalvmNative {
}
}
}
// Vite owns the HTML and hashed assets; only the controller can serve the page shell.
// Build it with `npm ci && npm run build` in frontend/ before invoking Gradle.
tasks.named('processResources') {
inputs.files(fileTree('frontend/dist'))
doFirst {
if (!file('frontend/dist/index.html').exists()) {
throw new GradleException('Missing UI build: run npm ci && npm run build in frontend/')
}
}
from('frontend/dist') { into 'ui' }
}
+106
View File
@@ -0,0 +1,106 @@
# AD 第一因素接入
`/signin` 接收 AD 用户名(sAMAccountName)或本域 UPN,使用 Spring Security
`ActiveDirectoryLdapAuthenticationProvider` 以用户身份执行 LDAPS bind 与目录查询。
不使用额外目录服务账号,不写入 AD,不复制 Authelia 的绑定密码。
成功后重定向到 `/signin/mfa`,显示目录账号、objectGUID、邮箱、直接所属组及组 DN。
**这是密码因素验收页面,MFA 尚未接入,不是完整登录成功。** 不创建 Spring Security
认证上下文,不调用 Hydra,不替换现役 Go/Authelia/Gitea 登录链路。演示入口 `/preview`
仍完全隔离,默认关闭,演示码不能推进真实认证。
## 目录和组语义
- AD 是身份和组权威。objectGUID 按 AD 混合字节序解析为标准 UUID,作为目录稳定键;
不是已确定的 Hydra `sub`。切换前仍须处理现役 issuer/sub 哈希的主体连续性。
- 从 `memberOf` 读取直接成员关系,保留原始 DN;CN 保留大小写,不添加 `ROLE_`,
不把 Spring 的 `FACTOR_PASSWORD` 当作组。结果排序,不做应用专用组改写。
- 此轮不展开嵌套组、不推导 primaryGroupID,也不宣称与 Authelia 的有效组集合完全一致。
遇到 ranged memberOf 或不同 DN 同名 CN 拒绝映射,不静默丢组或合并不同主体。
- AD bind 执行密码及账号状态检查;Spring 解析禁用、锁定、密码过期等 AD 子码。
搜索排除 computer 对象,只接受唯一用户条目和合法 objectGUID/sAMAccountName。
- 邮箱作为目录属性展示,不声称 `email_verified=true`。
## 启用
正常 JVM 构建:
```sh
IAM_DOCKER_USE_SUDO=1 scripts/gradle-in-docker test bootJar
```
Gradle 与 npm 缓存默认持久挂载,可用 `IAM_GRADLE_CACHE`、`IAM_NPM_CACHE` 指定目录。
日常迭代不必每轮跑 Native;新增 AD/JNDI/TLS 路径的原生验收留到阶段性验证。
运行时配置(非秘密):
```yaml
iam:
ad:
enabled: true
url: ldaps://dc1.ad.ddupan.top:636
domain: ad.ddupan.top
base-dn: DC=ad,DC=ddupan,DC=top
server:
port: 18082
ssl:
enabled: true
certificate: file:/run/iam/browser.crt
certificate-private-key: file:/run/iam/browser.key
servlet:
session:
cookie:
secure: true
same-site: lax
```
证书与私钥使用外部受管文件,不加入仓库。开发验收可使用本机的 Tailscale HTTPS 域名
及相应证书;用匹配证书的主机名打开,不能用 LAN IP 替代域名后跳过警告。
部署与证书自动续期归 homelab-infra,此轮本地运行不是生产部署。
LDAPS 使用默认 JSSE 信任库并执行服务端域名校验。Samba 当前证书由 OpenBao 内部 CA
签发,需把**公开 CA** 加入运行用 truststore,并通过 JVM 参数指定:
```sh
java -Djavax.net.ssl.trustStore=/run/iam/truststore \
-Djavax.net.ssl.trustStorePassword=changeit -jar iam-login.jar
```
这里 truststore 仅含公开信任锚,口令不是目录密码。保留所需公共根证书;不得禁用
LDAP endpoint identification 或用信任所有证书的 socket factory。连接/读取超时为 3/5 秒。
AD 根范围查询可能返回 DomainDnsZones/ForestDnsZones 等分区 referral;配置为 ignore,
由 Spring AD provider 忽略 partial result,不使用 throw 打断用户查询,也不 follow 转发用户凭据。
浏览器入口只接受 HTTPS;明文请求返回 426。默认不信任转发头。若以后由代理终结 TLS,
必须配合仅受信代理可达的后端网络和转发头配置,不能公开一个信任任意 forwarded header
的 HTTP 端口。当前开发验收由应用直接终结 TLS。
## 状态与操作
原生表单 POST 带 Spring CSRF token;服务端决定下一页。密码成功后轮换 session ID,
只保存目录身份快照和十分钟期限,不保存密码;重启或“退出并重新验证”清除事务。
页面禁止缓存,内联 JSON 转义 HTML 结束标记。失败页面不披露目录内部异常。
当前每个 session 只保留一份事务,多标签页会共享状态。两秒提交间隔仅用于同事务的
重复提交,不是账号/IP 限流;此 PoC 仅供受控 LAN/Tailscale 验收,生产发布前仍需完善
入口限流、审计、MFA、Hydra 事务和恢复策略。
基础存活检查使用 `/actuator/health/liveness`。Boot 自动配置的 LDAP 健康项并未连接这里
独立配置的 AD provider,不能把该项当作此认证路径的可用性验证。
## 本轮验证边界
隔离测试使用真实 TLS、LDAP bind 和搜索,校验正确/错误密码、未知账号、AD 账号状态
子码、GUID 字节序、组名、错误 TLS 主机名、CSRF、HTTPS、会话轮换、超时和密码成功后
仍未完整认证。UnboundID 的 UPN bind 与 AD 子码由测试拦截器模拟,不能替代 Samba AD。
测试证书、私钥与账号全为虚构夹具,不用于实际部署。
2026-09-25:JVM 测试共 12 项通过(原有 6 项、新增 AD 6 项),`bootJar` 构建通过。
实际 JVM 使用受信 CA 完成 Samba AD RootDSE 查询,HTTPS 页面返回 200。
浏览器已检查登录表单渲染、真实 CSRF 原生 POST 和失败后清空密码;只使用在访问 AD 前
即拒绝的合成外域用户名,不尝试猜测人类密码。浏览器回归共 1 项通过,包含移动端布局。
复现:`IAM_AD_URL=https://验收域名:端口 npm --prefix frontend run test:browser -- ad-login.spec.ts`。
维护者已在 HTTPS 页面完成真实密码验证,成功到达待 MFA 页面,并反馈目录标识、邮箱与
六个直接所属组的查询结果。该验收覆盖 Samba AD 第一因素与属性读取,不表示 MFA、
嵌套组/主组等价性或 Hydra 登录已完成。不在聊天、命令行或日志中传递人类密码。
新增 AD 路径尚未进行 Native 测试,不能复用旧 UI 原型的 Native 结论。
+3
View File
@@ -126,3 +126,6 @@ Prometheus 注册器中的 CPU 时间计数器并断言数值有效,避免后
这是一次本地 smoke 测量,启动耗时含检查器轮询,RSS 不是峰值或负载预算,ELF 大小不等于
运行镜像大小。未验证 AD、MFA、Hydra、目录就绪或 OTLP 后端数据查询,也尚未接入 CI。
运行报告生成在 `build/reports/native-smoke/result.json`,不提交运行日志或构建产物。
手写 Native 补丁位于 `META-INF/native-image/top.ddupan.iam/iam-login-manual/`,
与 Spring AOT 生成的 `iam-login/` 目录分开,避免 `bootJar` 中同名元数据冲突。
+106
View File
@@ -0,0 +1,106 @@
# 浏览器登录流程原型
参考 Keycloakify:Spring 返回 HTML 时内联当前页面上下文,React 用 `createRoot` 渲染,
表单原生 POST 到 Spring,后端按 session 中的步骤校验并返回 303 重定向。
每次导航重新挂载 React,带 hash 的 JS/CSS 可长期缓存。局部帮助展开不发请求。
这是浏览器交互实验,不是身份验证实现:没有 AD 查询、真实密码、TOTP、WebAuthn 或
Hydra accept;不会创建 Spring Security 登录身份。演示码 **123456** 仅用于切换页面,
不得作为 MFA 实现复用。默认关闭,显式设置 `iam.ui-preview.enabled=true` 才开放 `/preview`。
所有其他受保护入口仍需认证,Prometheus 权限保持不变。
![浏览器交互原型首页](images/browser-preview.png)
## 本地体验
有 Node 24 和 JDK 25 时:
```sh
cd frontend
npm ci
npm run build
cd ..
./gradlew bootRun --args='--server.address=127.0.0.1 --server.port=18081 --iam.ui-preview.enabled=true'
```
访问 <http://127.0.0.1:18081/preview>。填写称呼,尝试错误演示码,再用 123456 完成。
后退链接、刷新、重新体验都走服务端流程。启用 DevTools 的 Network 面板观察 document
POST、303、GET;不要勾选 Disable cache,否则无法观察正常的静态资源缓存。
Docker 开发:
```sh
IAM_DOCKER_USE_SUDO=1 scripts/gradle-in-docker bootRun \
--args='--server.address=127.0.0.1 --server.port=18081 --iam.ui-preview.enabled=true'
```
`gradle-in-docker` 先用固定 Node 镜像构建前端,再运行 GraalVM 容器。
Gradle 缓存默认 `$HOME/.cache/iam-login/gradle`,npm 缓存默认 `$HOME/.cache/iam-login/npm`;
可用 `IAM_GRADLE_CACHE` / `IAM_NPM_CACHE` 指定持久目录。Node 仅参与构建,部署无 Node 服务。
直接调用 Gradle 时先构建前端;缺少 `frontend/dist/index.html` 会明确失败。
前端 watch 可用 `npm run watch`,修改后仍需让后端重新复制资源并重启;本轮不实现 HMR 桥接。
## 验证
```sh
IAM_DOCKER_USE_SUDO=1 scripts/gradle-in-docker test testAot nativeTest nativeCompile
python3 scripts/native-smoke.py
build/native/nativeCompile/iam-login --server.address=127.0.0.1 --server.port=18081 \
--iam.ui-preview.enabled=true
# 另一个终端,应用保持运行
cd frontend
npm ci
npx playwright install chromium
npm run test:browser
```
浏览器测试覆盖原生页面导航、错误重试、局部交互零请求、无 fetch/XHR、静态 JS 缓存、
移动端布局、脚本结束标记转义,以及完成预览仍不能访问受保护应用。
额外计时使用 Chromium 模拟 60ms 网络延迟、1.5Mbps 下载和四倍 CPU slowdown,
用于比较首屏和缓存后的页面切换,不代表真实 LAN、Tailscale 或手机性能。
## 实现边界
- 页面壳在 `frontend/index.html`,Vite 构建后作为私有 classpath 资源 `ui/index.html` 打包,
不提供静态 index 入口;控制器仅替换一个固定 JSON 数据位置。
- Java 使用 JSON 序列化后转义 `<`、`>`、`&` 和 Unicode 行分隔符,避免 `</script>` 逃逸;
React 按文本输出动态内容,不通过 HTML 字符串插入用户名。
- session 持有演示步骤。表单带 Spring Security CSRF token,缺失被拒绝;
非当前步骤的提交拒绝,未知/过期 session 的后续页面回到初始步骤。
- 页面与重定向 `no-store`,静态 hash 资源 public/immutable。CSP 不允许内联可执行脚本。
- 单 session 仅有一个演示流程,多标签页会共享步骤。正式认证需要独立事务、过期策略、
主体与因素绑定;本原型不提供这些保证。
- 当前采取整页切换,不提前实现 fetch 优化。后续根据测量选择需要局部更新的步骤。
- 首屏依赖 JavaScript,没有 React SSR、Flight、客户端路由、FreeMarker 或模板引擎。
关闭 JavaScript 时显示明确提示,不宣称无 JS 可用。
来源:[Keycloakify 入口](https://github.com/keycloakify/keycloakify-starter/blob/main/src/main.tsx)、
[登录表单](https://github.com/keycloakify/keycloakify/blob/main/src/login/pages/Login.tsx)、
[Vite 构建](https://vite.dev/guide/build)。
## 2026-09-25 本地验证结果
本轮应用代码为 `dcf634d`,随后修正 smoke 对 HTML 入口的 Accept 请求头。
使用固定 GraalVM Java 25.0.2 镜像,构建限制 4 CPU / 8 GiB;原生应用采用默认 O2。
| 检查 | 结果 |
|---|---|
| 前端 TypeScript / Vite、bootJar | 通过 |
| JVM test / testAot / nativeTest | 各 6 项,0 失败、0 跳过 |
| Native 应用 smoke | liveness UP;匿名应用及指标 401;认证指标 200;健康请求计数增加 3 |
| 默认关闭 / 显式开启预览 | HTML 请求分别 404 / 200,在同一 Native 构建上实测 |
| Native 上的 Chromium 测试 | 3 项通过,包含整页原生 POST、无 fetch/XHR、缓存、转义与移动端 |
| ELF 文件大小 | 126,291,016 bytes,约 120.44 MiB,不是容器镜像大小 |
| 启动到 liveness 可响应 | 单次 0.351 秒 |
| smoke 请求后 RSS | 148,996 KiB,约 145.50 MiB |
| 模拟限速下的首屏 | 从导航开始到 React 提交 DOM:1,702 ms |
| 模拟限速下的缓存后切换 | Playwright 点击开始到下一页标题可见:560 ms |
浏览器计时条件为 60ms 网络延迟、1.5Mbps 下载、0.75Mbps 上传及四倍 CPU slowdown。
这是单次、本机、模拟网络测量,不是生产 SLA,两个计时区间也不同;不据此声称 Native
比 JVM 快多少。原型没有启用 HTTP 压缩,首屏实际下载约 223KB JS;构建日志中的约 70KB
是 gzip 估算,不是本轮实际传输大小。后续页面的 JS `transferSize=0`,确认命中浏览器缓存。
本轮没有新增反射补丁。Native 测试日志以及 smoke 的启动、请求、关闭阶段未发现 Native
反射或资源注册错误。生成目录中的配套 `.so` 文件应随 Native 产物保留;这里不承诺单文件
静态链接交付。AD、真实 MFA、Hydra 和人类验收不在这些结果范围内。
Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

+3
View File
@@ -20,6 +20,9 @@ WebAuthn 集成;TOTP、恢复方式与已有 Authelia MFA 的迁移方式需
- Hydra admin 保持内部访问,业务日志不得包含密码、MFA secret、token 或 challenge。
- 原生二进制与隔离 Hydra 完成授权码链路,再验证现有 Gitea 账号及权限。
日常迭代以 JVM 测试为准,不要求每轮执行 Native 编译。Native 验证安排在阶段性验收
或新增反射、JNDI、TLS 等兼容性风险时集中进行;记录尚未覆盖的新路径。
## Native 与监控
- CI 构建 Native 产物并对该产物执行集成测试;测试报告区分 JVM 与 Native。
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<title>登录 · IAM</title>
</head>
<body>
<div id="root"></div>
<noscript>本页使用 React 渲染页面,请启用 JavaScript。</noscript>
<script id="login-context" type="application/json">
__IAM_PAGE_CONTEXT__
</script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1280
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
{
"name": "iam-login-ui",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"build": "tsc --noEmit && vite build",
"watch": "vite build --watch",
"test:browser": "playwright test"
},
"dependencies": {
"react": "19.3.0",
"react-dom": "19.3.0"
},
"devDependencies": {
"vite": "8.3.1",
"typescript": "7.0.2",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@playwright/test": "1.63.0"
}
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: {
baseURL: process.env.IAM_PREVIEW_URL ?? "http://127.0.0.1:18081",
headless: true,
},
});
+192
View File
@@ -0,0 +1,192 @@
import { createRoot } from "react-dom/client";
import { useState, useLayoutEffect, type ReactNode } from "react";
import "./style.css";
type PageContext = {
step: "identity" | "verification" | "complete" | "password" | "mfa-pending";
identity?: { username: string; objectGuid: string; email: string; groups: string[]; groupDns: string[] };
name: string;
error: string;
action: string;
csrf: { name: string; value: string };
};
const context: PageContext = JSON.parse(
document.getElementById("login-context")!.textContent!,
);
function Form({ children }: { children: ReactNode }) {
const [pending, setPending] = useState(false);
return (
<form
method="post"
action={context.action}
onSubmit={() => setPending(true)}
aria-busy={pending}
>
<input
type="hidden"
name={context.csrf.name}
value={context.csrf.value}
/>
{children}
<button className="primary" type="submit" disabled={pending}>
{pending
? "正在继续…"
: (context.step === "complete" || context.step === "mfa-pending")
? (context.step === "mfa-pending" ? "退出并重新验证" : "重新体验")
: "继续"}
</button>
</form>
);
}
function App() {
useLayoutEffect(() => { performance.mark("iam-page-ready"); }, []);
const [showHelp, setShowHelp] = useState(false);
return (
<main>
<header>
<a href="/preview" className="brand" aria-label="IAM 登录体验预览">
i<span>am</span>
<span className="badge">预览</span>
</a>
</header>
<section className="card" aria-labelledby="title">
<div className="eyebrow">登录交互原型</div>
<ol className="steps" aria-label="当前步骤">
{(["identity", "verification", "complete"] as const).map(
(step, i) => (
<li
key={step}
aria-current={context.step === step ? "step" : undefined}
>
<span>{i + 1}</span>
{["填写称呼", "模拟验证", "完成"][i]}
</li>
),
)}
</ol>
{context.step === "identity" && (
<>
<h1 id="title">从这里开始</h1>
<p className="intro">
体验一次完整的页面切换。先告诉我们怎么称呼你。
</p>
</>
)}
{context.step === "verification" && (
<>
<h1 id="title">你好,{context.name}</h1>
<p className="intro">
这是第二步页面。输入演示码 <strong>123456</strong>{" "}
继续,也可以试试输入错误的演示码。
</p>
</>
)}
{context.step === "complete" && (
<>
<div className="success" aria-hidden="true">
✓
</div>
<h1 id="title">体验完成</h1>
<p className="intro">
{context.name}
,你已走完页面预览。这没有建立登录身份,也没有向任何应用授权。
</p>
</>
)}
{context.error && (
<p className="error" role="alert">
{context.error}
</p>
)}
<Form>
{context.step === "identity" && (
<label>
称呼
<input
name="name"
autoComplete="off"
autoFocus
required
maxLength={64}
placeholder="例如:小潘"
defaultValue={context.name}
/>
</label>
)}
{context.step === "verification" && (
<label>
演示码
<input
name="code"
inputMode="numeric"
autoComplete="off"
autoFocus
required
maxLength={6}
pattern="[0-9]{6}"
placeholder="123456"
aria-invalid={Boolean(context.error)}
/>
</label>
)}
</Form>
{context.step === "verification" && (
<a className="back" href="/preview">
返回上一步
</a>
)}
<div className="help">
<button
type="button"
className="link"
aria-expanded={showHelp}
onClick={() => setShowHelp(!showHelp)}
>
这是真实登录吗?
</button>
{showHelp && (
<p>不是。这里仅演示页面交互,请勿输入真实密码或 MFA 验证码。</p>
)}
</div>
</section>
<footer>独立 IAM · 页面体验预览</footer>
</main>
);
}
function SignIn() {
useLayoutEffect(() => { performance.mark("iam-page-ready"); }, []);
const identity = context.identity;
return <main>
<header><a href="/signin" className="brand">i<span>am</span></a></header>
<section className="card" aria-labelledby="title">
<div className="eyebrow">AD 登录验证</div>
<h1 id="title">{context.step === "password" ? "登录你的账号" : "密码已验证,等待 MFA"}</h1>
<p className="intro">{context.step === "password"
? "使用 AD 用户名或完整 UPN 登录。"
: `${context.name},目录验证成功。第二因素尚未接入,本次没有完成登录或向应用授权。`}</p>
{context.error && <p className="error" role="alert">{context.error}</p>}
{identity && <div className="directory-result">
<dl><dt>账号</dt><dd>{identity.username}</dd>
<dt>目录标识</dt><dd>{identity.objectGuid}</dd>
<dt>邮箱</dt><dd>{identity.email || "未设置"}</dd></dl>
<h2>直接所属组</h2>
{identity.groups.length ? <ul>{identity.groups.map(group => <li key={group}>{group}</li>)}</ul> : <p>没有直接所属组。</p>}
<details><summary>组 DN</summary><ul>{identity.groupDns.map(dn => <li key={dn}>{dn}</li>)}</ul></details>
<p>当前仅读取 memberOf,不展开嵌套组,也不包含主组。</p>
</div>}
<Form>{context.step === "password" && <>
<label>用户名<input name="username" autoComplete="username" autoFocus required maxLength={256} defaultValue={context.name} /></label>
<label>密码<input name="password" type="password" autoComplete="current-password" required maxLength={1024} /></label>
</>}</Form>
</section>
<footer>独立 IAM · AD 接入验证</footer>
</main>;
}
createRoot(document.getElementById("root")!).render(
context.step === "password" || context.step === "mfa-pending" ? <SignIn /> : <App />,
);
+244
View File
@@ -0,0 +1,244 @@
:root {
font-family: Inter, "Noto Sans SC", system-ui, sans-serif;
color: #182826;
background: #f3f5f1;
font-synthesis: none;
font-size: 16px;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
}
main {
max-width: 520px;
margin: 0 auto;
padding: 40px 20px 28px;
}
header {
margin-bottom: 40px;
}
.brand {
font-size: 32px;
font-weight: 750;
letter-spacing: -2px;
color: #285448;
text-decoration: none;
}
.brand > span:first-child {
font-weight: 400;
}
.badge {
font-size: 11px;
letter-spacing: 1px;
vertical-align: middle;
margin-left: 14px;
padding: 5px 8px;
border: 1px solid #b7c9be;
border-radius: 5px;
}
.card {
background: #fff;
border: 1px solid #dce4dd;
border-radius: 18px;
padding: 36px;
box-shadow: 0 12px 40px #173f2510;
}
.eyebrow {
font-size: 12px;
color: #60746a;
letter-spacing: 2px;
}
.steps {
display: flex;
justify-content: space-between;
padding: 0;
list-style: none;
margin: 25px 0 32px;
gap: 8px;
}
.steps li {
font-size: 12px;
color: #718078;
display: flex;
align-items: center;
gap: 7px;
}
.steps li span {
display: inline-grid;
place-items: center;
width: 23px;
height: 23px;
border: 1px solid #ccd7ce;
border-radius: 50%;
font-size: 11px;
}
.steps [aria-current] {
color: #215542;
font-weight: 650;
}
.steps [aria-current] span {
background: #215542;
color: white;
border-color: #215542;
}
h1 {
font-size: 27px;
letter-spacing: -0.5px;
line-height: 1.35;
margin: 0 0 12px;
overflow-wrap: anywhere;
}
.intro {
font-size: 14px;
color: #60716a;
line-height: 1.8;
margin: 0 0 25px;
}
label {
display: block;
font-size: 14px;
font-weight: 600;
}
input:not([type="hidden"]) {
display: block;
width: 100%;
border: 1px solid #bdccc1;
border-radius: 8px;
padding: 13px 14px;
margin: 9px 0 22px;
font: inherit;
color: inherit;
background: #fff;
}
input:focus {
outline: 3px solid #a9cbbc;
outline-offset: 2px;
}
button {
font: inherit;
cursor: pointer;
}
.primary {
width: 100%;
border: 0;
background: #245b47;
color: #fff;
font-weight: 600;
border-radius: 8px;
padding: 13px;
}
.primary:hover {
background: #194734;
}
.primary:disabled {
opacity: 0.65;
cursor: wait;
}
.error {
color: #9e302b;
background: #fff0ed;
padding: 12px;
border-radius: 8px;
font-size: 14px;
line-height: 1.6;
}
.back {
display: block;
text-align: center;
font-size: 13px;
margin-top: 18px;
color: #476a58;
}
.help {
border-top: 1px solid #e5ebe6;
margin-top: 28px;
padding-top: 20px;
}
.link {
background: none;
border: 0;
color: #5b7064;
padding: 0;
font-size: 13px;
}
.help p {
font-size: 13px;
line-height: 1.8;
color: #6a756e;
margin-bottom: 0;
}
footer {
text-align: center;
color: #7c887e;
font-size: 12px;
margin-top: 28px;
}
.success {
color: #245b47;
font-size: 30px;
margin-bottom: 12px;
}
a:focus-visible,
button:focus-visible {
outline: 3px solid #a9cbbc;
outline-offset: 3px;
}
@media (max-width: 480px) {
main {
padding-top: 24px;
}
header {
margin-bottom: 24px;
}
.card {
padding: 26px 22px;
}
.steps {
gap: 5px;
}
.steps li {
font-size: 11px;
}
}
@media (prefers-color-scheme: dark) {
:root {
background: #14221c;
color: #edf4ee;
}
.card {
background: #1e3027;
border-color: #344b3d;
}
.brand,
.steps [aria-current],
.success {
color: #b9ddc8;
}
.intro,
.eyebrow,
.help p,
.link,
.back {
color: #acbfb2;
}
.steps li {
color: #98aa9e;
}
input:not([type="hidden"]) {
background: #18271f;
border-color: #526657;
}
.help {
border-color: #3a4d40;
}
.error {
background: #492b29;
color: #ffc3b9;
}
}
.directory-result { overflow-wrap: anywhere; }
.directory-result dd { margin: 0 0 1rem; }
.directory-result h2 { font-size: 1rem; }
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+31
View File
@@ -0,0 +1,31 @@
import { test, expect } from "@playwright/test";
// Explicit opt-in: never submit synthetic credentials to an arbitrary configured directory.
// The external-domain username below must be rejected before any LDAP bind.
test("AD HTTPS page uses native POST and keeps failed credentials out of the response", async ({ page, context }) => {
test.skip(!process.env.IAM_AD_URL, "Set IAM_AD_URL to the HTTPS first-factor PoC");
const url = new URL("/signin", process.env.IAM_AD_URL!);
expect(url.protocol).toBe("https:");
const requests: { method: string; type: string; path: string }[] = [];
page.on("request", request => requests.push({
method: request.method(), type: request.resourceType(), path: new URL(request.url()).pathname,
}));
await page.goto(url.toString());
await expect(page.getByRole("heading", { name: "登录你的账号" })).toBeVisible();
await expect(page.locator("form")).toHaveAttribute("method", "post");
await expect(page.locator("input[name=_csrf]")).toHaveCount(1);
const session = (await context.cookies()).find(cookie => cookie.name === "JSESSIONID");
expect(session).toMatchObject({ secure: true, httpOnly: true, sameSite: "Lax" });
await page.getByLabel("用户名", { exact: true }).fill("[email protected]");
await page.getByLabel("密码", { exact: true }).fill("synthetic-ui-check");
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("alert")).toContainText("无法验证账号");
await expect(page.getByLabel("密码", { exact: true })).toHaveValue("");
expect(await page.content()).not.toContain("synthetic-ui-check");
expect(requests.filter(request => request.method === "POST")).toEqual([
{ method: "POST", type: "document", path: "/signin/password" },
]);
expect(requests.filter(request => ["fetch", "xhr"].includes(request.type))).toHaveLength(0);
await page.setViewportSize({ width: 390, height: 844 });
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
});
+95
View File
@@ -0,0 +1,95 @@
import { test, expect } from "@playwright/test";
test("原生 POST 逐页导航,内联上下文,浏览器缓存静态资源", async ({ page }) => {
const xhr: string[] = [];
const posts: string[] = [];
const errors: string[] = [];
page.on("pageerror", (e) => errors.push(e.message));
page.on("request", (req) => {
if (["fetch", "xhr"].includes(req.resourceType())) xhr.push(req.url());
if (req.method() === "POST" && req.isNavigationRequest())
posts.push(req.url());
});
await page.goto("/preview");
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
const scriptUrl = await page.locator("script[src]").getAttribute("src");
await page.getByRole("button", { name: "这是真实登录吗?" }).click();
await expect(page.getByText("不是。这里仅演示页面交互")).toBeVisible();
await page.getByLabel("称呼").fill("预览用户");
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page).toHaveURL(/\/preview\/verify$/);
await expect(
page.getByRole("heading", { name: "你好,预览用户" }),
).toBeVisible();
await page.getByLabel("演示码").fill("000000");
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("alert")).toContainText("演示码不正确");
await page.getByLabel("演示码").fill("123456");
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("heading", { name: "体验完成" })).toBeVisible();
expect(posts).toHaveLength(3);
expect(xhr).toEqual([]);
expect(errors).toEqual([]);
const timing = await page.evaluate(() => ({
navigation: performance
.getEntriesByType("navigation")
.map((e) => e.toJSON()),
resources: performance.getEntriesByType("resource").map((e) => e.toJSON()),
}));
const script = timing.resources.find((r) => r.name.endsWith(scriptUrl!));
expect(script?.transferSize).toBe(0);
await test
.info()
.attach("navigation-and-cache.json", {
body: JSON.stringify(timing, null, 2),
contentType: "application/json",
});
expect(
(
await page.request.get("/", { headers: { Accept: "application/json" } })
).status(),
).toBe(401);
await page.getByRole("button", { name: "重新体验" }).click();
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
});
test("移动端与脚本结束标记作为纯文本显示", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/preview");
const name = "</script><script>window.__injected=1</script>";
await page.getByLabel("称呼").fill(name);
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("heading")).toHaveText(`你好,${name}`);
expect(
await page.evaluate(() => Reflect.get(window, "__injected")),
).toBeUndefined();
expect(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
).toBe(true);
await page.screenshot({ path: "test-results/mobile.png", fullPage: true });
});
test("受限网络下首屏和缓存后页面切换计时", async ({ page, context }) => {
const cdp = await context.newCDPSession(page);
await cdp.send("Network.enable");
await cdp.send("Network.emulateNetworkConditions", {
offline: false, latency: 60, downloadThroughput: 1_500_000 / 8,
uploadThroughput: 750_000 / 8,
});
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
await page.goto("/preview");
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
const cold = await page.evaluate(() => performance.getEntriesByName("iam-page-ready")[0].startTime);
await page.getByLabel("称呼").fill("计时体验");
const start = performance.now();
await page.getByRole("button", { name: "继续", exact: true }).click();
await expect(page.getByRole("heading", { name: "你好,计时体验" })).toBeVisible();
const warm = performance.now() - start;
const result = { network_latency_ms: 60, download_mbps: 1.5, cpu_slowdown: 4,
cold_navigation_to_react_commit_ms: Math.round(cold), warm_click_to_visible_ms: Math.round(warm) };
console.log(JSON.stringify(result));
await test.info().attach("timing.json", { body: JSON.stringify(result, null, 2), contentType: "application/json" });
});
+13
View File
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"skipLibCheck": true
},
"include": ["src"]
}
+6
View File
@@ -0,0 +1,6 @@
import { defineConfig } from "vite";
export default defineConfig({
base: "/",
build: { outDir: "dist", emptyOutDir: true },
});
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
cache_dir=${IAM_NPM_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/iam-login/npm}
mkdir -p -- "$cache_dir"
cache_dir=$(cd -- "$cache_dir" && pwd)
docker_cmd=(docker)
if [[ ${IAM_DOCKER_USE_SUDO:-0} == 1 ]]; then
docker_cmd=(sudo -n docker)
fi
exec "${docker_cmd[@]}" run --rm --network host \
--cpus 2 --memory 1g --user "$(id -u):$(id -g)" \
-e HOME=/npm -e npm_config_cache=/npm \
-v "$cache_dir:/npm" -v "$repo_root:/workspace" \
-w /workspace/frontend node@sha256:d8e448a56fc63242f70026718378bd4b00f8c82e78d20eefb199224a4d8e33d8 \
sh -c 'npm ci --no-audit --no-fund && npm run build'
+2
View File
@@ -13,6 +13,8 @@ if (($# == 0)); then
set -- test
fi
"$repo_root/scripts/frontend-in-docker"
# Linux host networking is needed for Testcontainers' published ports.
exec "${docker_cmd[@]}" run --rm --network host \
--cpus "${IAM_BUILD_CPUS:-4}" --memory "${IAM_BUILD_MEMORY:-8g}" \
+3
View File
@@ -59,6 +59,8 @@ def main():
def request(path, authenticated=False):
headers = {'Accept': 'text/plain' if authenticated and path == '/actuator/prometheus' else 'application/json'}
if path == '/preview':
headers['Accept'] = 'text/html'
if authenticated:
headers['Authorization'] = f'Basic {basic}'
req = urllib.request.Request(base_url + path, headers=headers)
@@ -78,6 +80,7 @@ def main():
ready_seconds = time.monotonic() - started
assert request('/actuator/prometheus')[0] == 401, 'Anonymous metrics must be rejected'
assert request('/')[0] == 401, 'Anonymous application access must be rejected'
assert request('/preview')[0] == 404, 'UI preview must be disabled by default'
status, before = request('/actuator/prometheus', authenticated=True)
assert status == 200, 'Authenticated Prometheus scrape failed'
for _ in range(3):
@@ -0,0 +1,128 @@
package top.ddupan.iam.login.ad;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.time.Instant;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import top.ddupan.iam.login.preview.PageRenderer;
/** Human first-factor PoC. No SecurityContext, MFA acceptance, or Hydra calls. */
@RestController
public class AdLoginController {
static final String STATE = AdLoginController.class.getName() + ".state";
private final AdPasswordVerifier verifier;
private final PageRenderer renderer;
public AdLoginController(AdPasswordVerifier verifier, PageRenderer renderer) {
this.verifier = verifier;
this.renderer = renderer;
}
@GetMapping(value = "/signin", produces = MediaType.TEXT_HTML_VALUE)
ResponseEntity<String> page(HttpServletRequest request, CsrfToken csrf) {
requireAvailable(request);
var session = request.getSession();
synchronized (session) {
var state = state(session);
if (state.identity != null) return redirect("/signin/mfa");
return renderer.render(Map.of("step", "password", "name", state.username,
"error", state.error, "action", "/signin/password", "csrf", csrf(csrf)));
}
}
@PostMapping("/signin/password")
ResponseEntity<String> password(HttpServletRequest request,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String password) {
requireAvailable(request);
var session = request.getSession(false);
if (session == null) throw new ResponseStatusException(HttpStatus.CONFLICT);
synchronized (session) {
var state = (State) session.getAttribute(STATE);
if (state == null || state.identity != null || state.expires.isBefore(Instant.now())) {
return redirect("/signin");
}
// Prevent double submissions in this transaction; perimeter rate limits belong at ingress.
if (state.retryAfter.isAfter(Instant.now())) throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS);
state.retryAfter = Instant.now().plusSeconds(2);
state.username = username.length() <= 256 ? username : "";
try {
var identity = verifier.verify(username, password);
request.changeSessionId();
state.identity = identity;
state.error = "";
state.expires = Instant.now().plusSeconds(600);
return redirect("/signin/mfa");
} catch (AuthenticationException | org.springframework.dao.DataAccessException ex) {
// Neither directory exception details nor passwords enter HTML/session/logs.
state.error = "无法验证账号,请检查凭据与账号状态,或稍后重试。";
return redirect("/signin");
}
}
}
@GetMapping(value = "/signin/mfa", produces = MediaType.TEXT_HTML_VALUE)
ResponseEntity<String> pending(HttpServletRequest request, CsrfToken csrf) {
requireAvailable(request);
var session = request.getSession(false);
if (session == null) return redirect("/signin");
synchronized (session) {
var state = state(session);
if (state.identity == null) return redirect("/signin");
var identity = state.identity;
return renderer.render(Map.of("step", "mfa-pending", "name", identity.displayName(),
"error", "", "action", "/signin/restart", "csrf", csrf(csrf),
"identity", Map.of("username", identity.username(), "objectGuid", identity.objectGuid(),
"email", identity.email(), "groups", identity.groups(), "groupDns", identity.groupDns())));
}
}
@PostMapping("/signin/restart")
ResponseEntity<String> restart(HttpServletRequest request) {
requireAvailable(request);
var session = request.getSession(false);
if (session != null) session.invalidate();
return redirect("/signin");
}
private void requireAvailable(HttpServletRequest request) {
if (!verifier.enabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
if (!request.isSecure()) throw new ResponseStatusException(HttpStatus.UPGRADE_REQUIRED, "HTTPS required");
}
private static Map<String, String> csrf(CsrfToken token) {
return Map.of("name", token.getParameterName(), "value", token.getToken());
}
private static State state(HttpSession session) {
var state = (State) session.getAttribute(STATE);
if (state == null || state.expires.isBefore(Instant.now())) {
state = new State();
session.setAttribute(STATE, state);
}
return state;
}
private static ResponseEntity<String> redirect(String location) {
return ResponseEntity.status(HttpStatus.SEE_OTHER).header("Location", location)
.header("Cache-Control", "no-store").build();
}
static final class State {
String username = "";
String error = "";
DirectoryIdentity identity;
Instant expires = Instant.now().plusSeconds(600);
Instant retryAfter = Instant.EPOCH;
}
}
@@ -0,0 +1,153 @@
package top.ddupan.iam.login.ad;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.naming.NamingException;
import javax.naming.ldap.LdapName;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.stereotype.Service;
/** Invoke explicitly as a first factor; never register this as a web AuthenticationProvider. */
@Service
@EnableConfigurationProperties(AdProperties.class)
public class AdPasswordVerifier {
private final ActiveDirectoryLdapAuthenticationProvider provider;
private final AdProperties properties;
public AdPasswordVerifier(AdProperties properties) {
this.properties = properties;
if (!properties.enabled()) {
provider = null;
return;
}
URI uri = URI.create(properties.url());
if (!"ldaps".equals(uri.getScheme()) || uri.getHost() == null || uri.getUserInfo() != null
|| uri.getQuery() != null || uri.getFragment() != null
|| properties.domain() == null || properties.domain().isBlank()
|| properties.baseDn() == null || properties.baseDn().isBlank()) {
throw new IllegalArgumentException("AD requires an LDAPS URL, domain and base DN");
}
provider = new ActiveDirectoryLdapAuthenticationProvider(
properties.domain(), properties.url(), properties.baseDn());
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(false);
provider.setSearchFilter("(&(objectClass=user)(!(objectClass=computer))(userPrincipalName={0}))");
// AD domain searches include other naming-context references. Ignore them (never follow
// with user credentials); Spring's AD provider already ignores partial-result exceptions.
provider.setContextEnvironmentProperties(Map.of(
"com.sun.jndi.ldap.connect.timeout", "3000",
"com.sun.jndi.ldap.read.timeout", "5000",
"java.naming.ldap.attributes.binary", "objectGUID",
"java.naming.referral", "ignore"));
// Directory groups are mapped independently; do not confuse FACTOR_PASSWORD with a group.
provider.setAuthoritiesPopulator((entry, username) -> List.of());
provider.setUserDetailsContextMapper(new IdentityMapper());
}
public boolean enabled() { return properties.enabled(); }
public DirectoryIdentity verify(String username, String password) {
if (provider == null) throw new IllegalStateException("AD login is disabled");
if (username == null || username.isBlank() || username.length() > 256
|| username.contains("\\") || !username.equals(username.strip())
|| (username.contains("@") && !username.toLowerCase(java.util.Locale.ROOT)
.endsWith("@" + properties.domain().toLowerCase(java.util.Locale.ROOT)))
|| password == null || password.isEmpty() || password.length() > 1024) {
throw new BadCredentialsException("Invalid credentials");
}
var token = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
try {
var result = provider.authenticate(token);
try {
return ((IdentityUser) result.getPrincipal()).identity;
} finally {
if (result instanceof org.springframework.security.core.CredentialsContainer credentials) {
credentials.eraseCredentials();
}
}
} finally {
token.eraseCredentials();
}
}
static final class IdentityUser extends User {
final DirectoryIdentity identity;
IdentityUser(DirectoryIdentity identity) {
super(identity.username(), "", List.of());
this.identity = identity;
}
}
static final class IdentityMapper implements UserDetailsContextMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations entry, String username,
Collection<? extends GrantedAuthority> authorities) {
try {
// Refuse an incomplete ranged result instead of silently dropping groups.
var ids = entry.getAttributes().getIDs();
try {
while (ids.hasMore()) {
if (ids.next().toLowerCase(java.util.Locale.ROOT).startsWith("memberof;")) {
throw new IllegalArgumentException("Ranged membership is not supported yet");
}
}
} finally { ids.close(); }
String account = required(entry, "sAMAccountName");
String display = entry.getStringAttribute("displayName");
String email = entry.getStringAttribute("mail");
String[] membership = entry.getStringAttributes("memberOf");
List<String> dns = membership == null ? List.of() : Arrays.stream(membership).sorted().toList();
var groups = new java.util.TreeSet<String>();
for (String dn : dns) {
var name = new LdapName(dn);
var rdn = name.getRdn(name.size() - 1);
if (!rdn.getType().equalsIgnoreCase("CN")) throw new IllegalArgumentException("Group has no CN");
if (!groups.add(rdn.getValue().toString())) throw new IllegalArgumentException("Ambiguous group CN");
}
return new IdentityUser(new DirectoryIdentity(
guid((byte[]) entry.getObjectAttribute("objectGUID")), account,
display == null ? account : display, email == null ? "" : email,
List.copyOf(groups), dns));
} catch (NamingException | IllegalArgumentException | ClassCastException ex) {
throw new InternalAuthenticationServiceException("Directory identity cannot be mapped", ex);
}
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter context) {
throw new UnsupportedOperationException("Read-only directory integration");
}
private static String required(DirContextOperations entry, String attribute) {
String value = entry.getStringAttribute(attribute);
if (value == null || value.isBlank()) throw new IllegalArgumentException("Missing directory attribute");
return value;
}
}
static String guid(byte[] bytes) {
if (bytes == null || bytes.length != 16) throw new IllegalArgumentException("Invalid objectGUID");
var little = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
long most = Integer.toUnsignedLong(little.getInt()) << 32
| (long) Short.toUnsignedInt(little.getShort()) << 16
| Short.toUnsignedInt(little.getShort());
long least = ByteBuffer.wrap(bytes, 8, 8).getLong();
return new UUID(most, least).toString();
}
}
@@ -0,0 +1,6 @@
package top.ddupan.iam.login.ad;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("iam.ad")
public record AdProperties(boolean enabled, String url, String domain, String baseDn) {}
@@ -0,0 +1,12 @@
package top.ddupan.iam.login.ad;
import java.util.List;
/** Directory key only: deliberately not a Hydra subject or a completed authentication. */
public record DirectoryIdentity(String objectGuid, String username, String displayName,
String email, List<String> groups, List<String> groupDns) {
public DirectoryIdentity {
groups = List.copyOf(groups);
groupDns = List.copyOf(groupDns);
}
}
@@ -0,0 +1,32 @@
package top.ddupan.iam.login.preview;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
/** Shared HTML shell; the page context is data, never executable JavaScript. */
@Component
public class PageRenderer {
private static final String SLOT = "__IAM_PAGE_CONTEXT__";
private final String shell;
private final JsonMapper json = JsonMapper.builder().build();
public PageRenderer() throws IOException {
shell = new ClassPathResource("ui/index.html").getContentAsString(StandardCharsets.UTF_8);
if (shell.indexOf(SLOT) < 0 || shell.indexOf(SLOT) != shell.lastIndexOf(SLOT)) {
throw new IllegalStateException("Expected exactly one UI context slot");
}
}
public ResponseEntity<String> render(Object context) {
String safe = json.writeValueAsString(context).replace("<", "\\u003c")
.replace(">", "\\u003e").replace("&", "\\u0026")
.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029");
return ResponseEntity.ok().header("Cache-Control", "no-store")
.contentType(MediaType.TEXT_HTML).body(shell.replace(SLOT, safe));
}
}
@@ -0,0 +1,44 @@
package top.ddupan.iam.login.preview;
import java.time.Duration;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.http.CacheControl;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration(proxyBeanMethods = false)
@ImportRuntimeHints(PreviewConfiguration.Resources.class)
class PreviewConfiguration implements WebMvcConfigurer {
@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/signin", "/signin/**", "/preview", "/preview/**", "/assets/**", "/actuator/health/**").permitAll()
.anyRequest().authenticated())
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.headers(headers -> headers.contentSecurityPolicy(csp -> csp.policyDirectives(
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
+ "object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")))
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/ui/assets/")
.setCacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic().immutable());
}
static class Resources implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.resources().registerPattern("ui/**");
}
}
}
@@ -0,0 +1,129 @@
package top.ddupan.iam.login.preview;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.Map;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
/** An isolated UI experiment. It never creates an authenticated SecurityContext. */
@RestController
class PreviewController {
private static final String STATE = PreviewController.class.getName() + ".state";
private final boolean enabled;
private final PageRenderer renderer;
PreviewController(@Value("${iam.ui-preview.enabled:false}") boolean enabled, PageRenderer renderer) {
this.enabled = enabled;
this.renderer = renderer;
}
@GetMapping(value = {"/preview", "/preview/verify", "/preview/complete"}, produces = MediaType.TEXT_HTML_VALUE)
ResponseEntity<String> page(HttpServletRequest request, CsrfToken csrf) {
requireEnabled();
var session = request.getSession();
synchronized (session) {
var state = state(session);
var path = request.getRequestURI().substring(request.getContextPath().length());
if (path.equals("/preview")) {
if (!state.step.equals("identity")) state.error = "";
state.step = "identity";
} else if (!path.equals(pathFor(state.step))) {
return redirect(pathFor(state.step));
}
var context = Map.of("step", state.step, "name", state.name, "error", state.error,
"action", switch (state.step) {
case "identity" -> "/preview/identify";
case "verification" -> "/preview/verify";
default -> "/preview/restart";
}, "csrf", Map.of("name", csrf.getParameterName(), "value", csrf.getToken()));
return renderer.render(context);
}
}
@PostMapping("/preview/identify")
ResponseEntity<String> identify(@RequestParam(defaultValue = "") String name, HttpSession session) {
requireEnabled();
synchronized (session) {
var state = state(session);
requireStep(state, "identity");
if (name.isBlank() || name.length() > 64) {
state.error = "称呼须为 1 到 64 个字符。";
return redirect("/preview");
}
state.name = name.strip();
state.error = "";
state.step = "verification";
return redirect("/preview/verify");
}
}
@PostMapping("/preview/verify")
ResponseEntity<String> verify(@RequestParam(defaultValue = "") String code, HttpSession session) {
requireEnabled();
synchronized (session) {
var state = state(session);
requireStep(state, "verification");
if (!code.equals("123456")) {
state.error = "演示码不正确,请输入 123456。";
return redirect("/preview/verify");
}
state.error = "";
state.step = "complete";
return redirect("/preview/complete");
}
}
@PostMapping("/preview/restart")
ResponseEntity<String> restart(HttpSession session) {
requireEnabled();
synchronized (session) {
session.removeAttribute(STATE);
return redirect("/preview");
}
}
private void requireEnabled() {
if (!enabled) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
private static void requireStep(State state, String step) {
if (!state.step.equals(step)) throw new ResponseStatusException(HttpStatus.CONFLICT, "页面已过期,请重新打开预览");
}
private static State state(HttpSession session) {
var state = (State) session.getAttribute(STATE);
if (state == null) {
state = new State();
session.setAttribute(STATE, state);
}
return state;
}
private static String pathFor(String step) {
return switch (step) {
case "verification" -> "/preview/verify";
case "complete" -> "/preview/complete";
default -> "/preview";
};
}
private static ResponseEntity<String> redirect(String path) {
return ResponseEntity.status(HttpStatus.SEE_OTHER).header("Location", path)
.header("Cache-Control", "no-store").build();
}
private static class State {
String step = "identity";
String name = "";
String error = "";
}
}
@@ -1,6 +1,7 @@
package top.ddupan.iam.login;
import io.micrometer.core.instrument.MeterRegistry;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -10,42 +11,114 @@ import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.OtlpLog
import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.Transport;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.grafana.LgtmStackContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.utility.DockerImageName;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@SpringBootTest(properties = "iam.ui-preview.enabled=true")
@AutoConfigureMockMvc
@AutoConfigureMetrics
@AutoConfigureTracing
@Testcontainers
class IamLoginApplicationTests {
// Field-based service connections are recreated by the test context in AOT mode.
@Container
@ServiceConnection
static final LgtmStackContainer grafanaLgtm = new LgtmStackContainer(
DockerImageName.parse(TestcontainersConfiguration.LGTM_IMAGE));
// Field-based service connections are recreated by the test context in AOT mode.
@Container
@ServiceConnection
static final LgtmStackContainer grafanaLgtm = new LgtmStackContainer(
DockerImageName.parse(TestcontainersConfiguration.LGTM_IMAGE));
@Autowired
OtlpLoggingConnectionDetails loggingConnectionDetails;
@Autowired
OtlpLoggingConnectionDetails loggingConnectionDetails;
@Autowired
@Qualifier("prometheusMeterRegistry")
MeterRegistry prometheus;
@Autowired
@Qualifier("prometheusMeterRegistry")
MeterRegistry prometheus;
@Test
void processCpuTimeCanBeRead() {
assertThat(prometheus.get("process.cpu.time").functionCounter().count()).isFinite().isNotNegative();
}
@Autowired
MockMvc mvc;
@Test
void loggingConnectionUsesRunningContainer() {
assertThat(grafanaLgtm.isRunning()).isTrue();
assertThat(loggingConnectionDetails.getUrl(Transport.HTTP))
.isEqualTo(grafanaLgtm.getOtlpHttpUrl() + "/v1/logs");
}
@Test
void previewHasInlineContextAndNoCache() throws Exception {
var result = mvc.perform(get("/preview"))
.andExpect(status().isOk())
.andExpect(header().string("Cache-Control", "no-store"))
.andReturn();
assertThat(result.getResponse().getContentAsString()).contains("login-context", "identity", "_csrf")
.doesNotContain("__IAM_PAGE_CONTEXT__");
}
@Test
void previewRejectsMissingCsrf() throws Exception {
mvc.perform(post("/preview/identify").param("name", "测试"))
.andExpect(status().isForbidden());
}
@Test
void previewChecksStepsAndEscapesScriptEndTags() throws Exception {
var session = new MockHttpSession();
mvc.perform(post("/preview/verify")
.session(session).with(csrf())
.param("code", "123456"))
.andExpect(status().isConflict());
mvc.perform(post("/preview/identify")
.session(session).with(csrf())
.param("name", "</script><script>alert(1)</script>"))
.andExpect(status().isSeeOther());
var html = mvc.perform(get("/preview/verify").session(session))
.andExpect(status().isOk()).andReturn()
.getResponse().getContentAsString();
assertThat(html).doesNotContain("</script><script>alert(1)</script>")
.contains("\\u003c/script\\u003e");
}
@Test
void previewRetriesAndCompletesWithoutAuthenticating() throws Exception {
var session = new MockHttpSession();
mvc.perform(post("/preview/identify")
.session(session).with(csrf())
.param("name", "测试"))
.andExpect(redirectedUrl("/preview/verify"));
mvc.perform(post("/preview/verify")
.session(session).with(csrf())
.param("code", "000000"))
.andExpect(redirectedUrl("/preview/verify"));
var retry = mvc.perform(get("/preview/verify").session(session))
.andReturn().getResponse();
assertThat(retry.getContentAsString(StandardCharsets.UTF_8)).contains("演示码不正确");
mvc.perform(post("/preview/verify")
.session(session).with(csrf())
.param("code", "123456"))
.andExpect(redirectedUrl("/preview/complete"));
mvc.perform(get("/").session(session)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
assertThat(session.getAttribute("SPRING_SECURITY_CONTEXT")).isNull();
}
@Test
void processCpuTimeCanBeRead() {
assertThat(prometheus.get("process.cpu.time").functionCounter().count()).isFinite().isNotNegative();
}
@Test
void loggingConnectionUsesRunningContainer() {
assertThat(grafanaLgtm.isRunning()).isTrue();
assertThat(loggingConnectionDetails.getUrl(Transport.HTTP))
.isEqualTo(grafanaLgtm.getOtlpHttpUrl() + "/v1/logs");
}
}
@@ -0,0 +1,211 @@
package top.ddupan.iam.login.ad;
import com.unboundid.ldap.listener.InMemoryDirectoryServer;
import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig;
import com.unboundid.ldap.listener.InMemoryListenerConfig;
import com.unboundid.ldap.listener.interceptor.InMemoryInterceptedSimpleBindRequest;
import com.unboundid.ldap.listener.interceptor.InMemoryInterceptedSearchResult;
import com.unboundid.ldap.sdk.SearchResultReference;
import com.unboundid.ldap.listener.interceptor.InMemoryOperationInterceptor;
import com.unboundid.ldap.sdk.Entry;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SimpleBindRequest;
import java.net.InetAddress;
import java.security.KeyStore;
import java.time.Instant;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/** Real LDAPS sockets and Spring's AD provider; AD bind/subcode semantics are simulated. */
@SpringBootTest(properties = {"iam.ad.enabled=true", "iam.ad.domain=example.test", "iam.ad.base-dn=dc=example,dc=test"})
@AutoConfigureMockMvc
@ImportRuntimeHints(AdIntegrationTests.FixtureHints.class)
class AdIntegrationTests {
static class FixtureHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader loader) {
hints.resources().registerPattern("ldap/fixture.p12");
}
}
static final String BASE = "dc=example,dc=test";
static final String USER_DN = "cn=Alice," + BASE;
static final byte[] GUID = java.util.HexFormat.of().parseHex("33221100554477668899aabbccddeeff");
static class Fixture {
static final SSLContext ORIGINAL;
static final InMemoryDirectoryServer LDAP;
static {
try {
ORIGINAL = SSLContext.getDefault();
var store = KeyStore.getInstance("PKCS12");
try (var stream = AdIntegrationTests.class.getResourceAsStream("/ldap/fixture.p12")) {
store.load(stream, "fixture-only".toCharArray());
}
var keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keys.init(store, "fixture-only".toCharArray());
var trust = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trust.init(store);
var ssl = SSLContext.getInstance("TLS");
ssl.init(keys.getKeyManagers(), trust.getTrustManagers(), null);
SSLContext.setDefault(ssl);
var config = new InMemoryDirectoryServerConfig(BASE);
config.setSchema(null);
config.setListenerConfigs(InMemoryListenerConfig.createLDAPSConfig("ldaps",
InetAddress.getByName("127.0.0.1"), 0, ssl.getServerSocketFactory(), ssl.getSocketFactory()));
config.addInMemoryOperationInterceptor(new InMemoryOperationInterceptor() {
@Override
public void processSearchResult(InMemoryInterceptedSearchResult result) {
try {
// Like Samba AD's DomainDnsZones/ForestDnsZones continuation references.
// A client following this reference would fail instead of returning the user.
result.sendSearchReference(new SearchResultReference(
new String[]{"ldap://127.0.0.1:1/DC=other,DC=test"}, null));
} catch (LDAPException ex) { throw new IllegalStateException(ex); }
}
@Override
public void processSimpleBindRequest(InMemoryInterceptedSimpleBindRequest request) throws LDAPException {
String name = request.getRequest().getBindDN();
String subcode = switch (name) {
case "[email protected]" -> "533";
case "[email protected]" -> "775";
case "[email protected]" -> "532";
default -> null;
};
if (subcode != null) throw new LDAPException(ResultCode.INVALID_CREDENTIALS,
"80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data " + subcode + ", v1db1");
if (name.equalsIgnoreCase("[email protected]")) {
request.setRequest(new SimpleBindRequest(USER_DN, request.getRequest().getPassword().getValue()));
} else if (!name.equals(USER_DN)) {
throw new LDAPException(ResultCode.INVALID_CREDENTIALS, "Invalid credentials");
}
}
});
LDAP = new InMemoryDirectoryServer(config);
LDAP.startListening();
LDAP.add(new Entry(BASE, new com.unboundid.ldap.sdk.Attribute("objectClass", "domain"),
new com.unboundid.ldap.sdk.Attribute("dc", "example")));
LDAP.add(new Entry(USER_DN,
new com.unboundid.ldap.sdk.Attribute("objectClass", "user"),
new com.unboundid.ldap.sdk.Attribute("cn", "Alice"),
new com.unboundid.ldap.sdk.Attribute("sAMAccountName", "alice"),
new com.unboundid.ldap.sdk.Attribute("userPrincipalName", "[email protected]"),
new com.unboundid.ldap.sdk.Attribute("userPassword", "fixture-password"),
new com.unboundid.ldap.sdk.Attribute("displayName", "Alice </script><script>attack()</script>"),
new com.unboundid.ldap.sdk.Attribute("mail", "[email protected]"),
new com.unboundid.ldap.sdk.Attribute("objectGUID", GUID),
new com.unboundid.ldap.sdk.Attribute("memberOf", "CN=gitea-admins," + BASE, "CN=MixedCase," + BASE)));
} catch (Exception ex) { throw new ExceptionInInitializerError(ex); }
}
}
@DynamicPropertySource
static void directory(DynamicPropertyRegistry registry) {
registry.add("iam.ad.url", () -> "ldaps://localhost:" + Fixture.LDAP.getListenPort());
}
@AfterAll
static void close() { Fixture.LDAP.shutDown(true); SSLContext.setDefault(Fixture.ORIGINAL); }
@Autowired AdPasswordVerifier verifier;
@Autowired MockMvc mvc;
@Test
void passwordReadsGuidAndExactGroupsOverTlsDespitePartitionReferrals() {
var identity = verifier.verify("alice", "fixture-password");
assertThat(identity.objectGuid()).isEqualTo("00112233-4455-6677-8899-aabbccddeeff");
assertThat(identity.groups()).containsExactly("MixedCase", "gitea-admins");
assertThat(identity.groupDns()).containsExactly("CN=MixedCase," + BASE, "CN=gitea-admins," + BASE);
assertThat(verifier.verify("[email protected]", "fixture-password")).isEqualTo(identity);
}
@Test
void rejectsPasswordsUnknownUsersAndAdAccountStates() {
assertThatThrownBy(() -> verifier.verify("alice", "wrong")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("alice", "")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("unknown", "fixture-password")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("[email protected]", "fixture-password")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("disabled", "fixture-password")).isInstanceOf(DisabledException.class);
assertThatThrownBy(() -> verifier.verify("locked", "fixture-password")).isInstanceOf(LockedException.class);
assertThatThrownBy(() -> verifier.verify("expired", "fixture-password")).isInstanceOf(CredentialsExpiredException.class);
}
@Test
void rejectsWrongTlsHostnameAndPlainLdapConfiguration() {
var wrongName = new AdPasswordVerifier(new AdProperties(true,
"ldaps://127.0.0.1:" + Fixture.LDAP.getListenPort(), "example.test", BASE));
assertThatThrownBy(() -> wrongName.verify("alice", "fixture-password"))
.hasStackTraceContaining("No subject alternative names matching IP address");
assertThatThrownBy(() -> new AdPasswordVerifier(new AdProperties(true,
"ldap://localhost:389", "example.test", BASE))).isInstanceOf(IllegalArgumentException.class);
}
@Test
void browserRequiresHttpsCsrfAndOrderedSteps() throws Exception {
mvc.perform(get("/signin")).andExpect(status().isUpgradeRequired());
mvc.perform(get("/signin/mfa").secure(true)).andExpect(redirectedUrl("/signin"));
mvc.perform(post("/signin/password").secure(true).param("username", "alice")
.param("password", "fixture-password")).andExpect(status().isForbidden());
}
@Test
void successfulPasswordRotatesSessionAndStopsBeforeMfa() throws Exception {
var session = new MockHttpSession();
mvc.perform(get("/signin").secure(true).session(session)).andExpect(status().isOk());
String oldId = session.getId();
mvc.perform(post("/signin/password").secure(true).session(session).with(csrf())
.param("username", "alice").param("password", "fixture-password"))
.andExpect(redirectedUrl("/signin/mfa"));
assertThat(session.getId()).isNotEqualTo(oldId);
var html = mvc.perform(get("/signin/mfa").secure(true).session(session))
.andExpect(status().isOk()).andExpect(header().string("Cache-Control", "no-store"))
.andReturn().getResponse().getContentAsString();
assertThat(html).contains("mfa-pending", "gitea-admins", "\\u003c/script\\u003e")
.doesNotContain("fixture-password", "</script><script>attack()");
assertThat(session.getAttribute("SPRING_SECURITY_CONTEXT")).isNull();
mvc.perform(get("/").secure(true).session(session).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
var state = (AdLoginController.State) session.getAttribute(AdLoginController.STATE);
state.expires = Instant.EPOCH;
mvc.perform(get("/signin/mfa").secure(true).session(session)).andExpect(redirectedUrl("/signin"));
}
@Test
void failedPasswordDoesNotRetainIdentityAndRestartInvalidatesSession() throws Exception {
var session = new MockHttpSession();
mvc.perform(get("/signin").secure(true).session(session));
mvc.perform(post("/signin/password").secure(true).session(session).with(csrf())
.param("username", "alice").param("password", "wrong"))
.andExpect(redirectedUrl("/signin"));
var state = (AdLoginController.State) session.getAttribute(AdLoginController.STATE);
assertThat(state.identity).isNull();
assertThat(state.error).isNotBlank().doesNotContain("LDAP", "wrong");
mvc.perform(post("/signin/restart").secure(true).session(session).with(csrf()))
.andExpect(redirectedUrl("/signin"));
assertThat(session.isInvalid()).isTrue();
}
}
+4
View File
@@ -0,0 +1,4 @@
fixture.p12 是仅用于隔离 LDAPS 测试的自签名证书和测试私钥,口令为 fixture-only。
仅信任 localhost,不能用于生产。测试账户和密码都是虚构数据。
测试服务仅绑定 127.0.0.1;JVM/Native 均执行真实 TLS、bind 和搜索,但 AD 的 UPN bind
与禁用/锁定/密码过期子码由拦截器模拟,不代替 Samba AD 人类验收。
Binary file not shown.