按 DDD 重构认证流程并复用用户 bind 实现 LDAP 仓储

This commit is contained in:
2026-09-27 16:54:54 +00:00
parent 14f69a8a7c
commit a4b99d54f3
43 changed files with 1143 additions and 1167 deletions
+3
View File
@@ -4,6 +4,9 @@
- 默认中文维护项目文档、commit、issue 和 PR;代码与上游 API 名称保留英文。
- 项目使用 Java 与 Spring;Native 是交付约束,不是可选优化,不引入 Kotlin。
- 日常变更先通过适用的 JVM 测试,不要求每轮执行耗时的 Native 编译与测试;Native 仍为交付目标,在阶段性验收或兼容性风险变化时集中验证。未执行的验证明确报告。
- 按 DDD 组织 authentication 上下文:领域拥有 User/UserRepository 与认证事务规则,应用层编排,基础设施实现 AD 仓储,Web 仅处理传输与会话;领域和应用层不依赖 Spring/Servlet/LDAP。
- 用户仓储复用本次用户 bind 的连接,不新增只读服务账号;连接限于当前用例,不保留密码或连接在 HTTP session 中。
- 选型演示在真实接入后删除,不将演示入口、状态机、验证码或开关保留为应用功能。
- 只实现当前任务范围。Hydra 负责签发,首轮 AD 负责身份和组,本服务独立于 Ayatori。
- 不把 LDAP 密码成功当成完整 MFA 成功;所有因素绑定同一主体与认证事务。
- 不提交凭据、MFA secret、生产配置秘密或包含上述内容的测试输出。
+25 -6
View File
@@ -54,7 +54,7 @@ npm --prefix frontend run build
```
测试需要可用的 Docker,生成器配置了 Grafana LGTM Testcontainer。
包含隔离浏览器原型和 AD 第一因素测试;默认 Spring Security 登录页不是 IAM 登录流程。
测试覆盖 AD 第一因素、浏览器流程和监控集成。人类登录统一从 `/signin` 进入。
使用 GraalVM 25 验证原生测试与编译:
```sh
@@ -67,13 +67,32 @@ Docker 开发使用 `scripts/gradle-in-docker`,默认持久挂载 Gradle 缓
JVM、AOT、Native 测试及原生应用 HTTP 检查已通过,实测范围与资源数据见
[本地验证结果](docs/bootstrap.md#2026-09-25-本地验证结果)。
新增 AD 路径本轮按维护者要求只进行 JVM 验证,不沿用基线的 Native 验收结论。
真实目录密码与属性/直接所属组读取已通过维护者浏览器验收;MFA 与 Hydra 链路仍待实现。
重构前的真实目录密码与属性/直接所属组读取已通过维护者浏览器验收;Spring Data LDAP
版本已通过 JVM 和浏览器回归,真实人类复验待反馈。MFA 与 Hydra 链路仍待实现。
## 浏览器流程预览
## 领域与代码组织
人类登录界面采用 React + Vite,参考 Keycloakify 的内联上下文与原生表单提交方式。
原型默认关闭,仅测试页面切换与局部交互,不执行真实认证。启动、浏览器测试和边界见
[浏览器流程原型](docs/browser-preview.md)。
当前限界上下文为 `authentication`,使用 DDD 分层,依赖向领域内部收敛:
```text
interfaces/web → application → domain
infrastructure/ad → application/port + domain
configuration → 装配上述实现
```
- `authentication/domain`:`User`、`UserRepository`、`LoginTransaction`;稳定主体、组成员关系、
登录步骤与期限属于领域模型,不依赖 Spring、Servlet、LDAP 或持久化注解。
- `authentication/application`:登录用例,编排密码认证、用户仓储查询与事务推进;
`port` 描述密码认证及其用户仓储会话,不暴露 `DirContext`。
- `authentication/infrastructure/ad`:AD bind、Spring Data LDAP 用户仓储、LDAP 实体与领域映射。
使用同一次用户 bind 的连接,查询结束关闭,不新增服务账号,不保存用户密码。
- `authentication/interfaces/web`:HTTP、CSRF、会话存取和页面数据转换;不定义认证状态规则。
- `configuration`:Spring 组件装配、安全链、静态资源和 Native hints。
- `frontend/src`:入口、页面、表单组件和页面数据契约分别维护,只包含真实登录流程。
测试分别覆盖领域规则、应用用例、AD 仓储和 Web 行为,LDAP 夹具集中在测试 `support` 包。
界面采用 React + Vite,Spring 在 HTML 中内联当前步骤上下文,浏览器原生表单 POST,
由服务端决定下一页。不增加前端路由器、模板引擎或 Node 运行服务。
## AD 第一因素接入
-1
View File
@@ -27,7 +27,6 @@ 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'
+18 -11
View File
@@ -1,13 +1,17 @@
# AD 第一因素接入
`/signin` 接收 AD 用户名(sAMAccountName)或本域 UPN,使用 Spring Security
`ActiveDirectoryLdapAuthenticationProvider` 以用户身份执行 LDAPS bind 与目录查询。
`/signin` 接收 AD 用户名(sAMAccountName)或本域 UPN,通过 Spring LDAP `ContextSource.getContext` 以用户身份执行 LDAPS bind,
随后由 Spring Data LDAP 仓储复用这条已认证连接查询用户与组。
不使用额外目录服务账号,不写入 AD,不复制 Authelia 的绑定密码。
领域仓储接口为 `UserRepository`,`User` 与 `LoginTransaction` 为领域模型。应用层以
try-with-resources 管理已认证用户仓储会话;基础设施的 `AdUserRepository` 通过
`SimpleLdapRepository<AdUserEntry>`、`LdapTemplate`、ODM 实现读取与转换,关闭后不可继续查询。
`AdUserEntry` 的 LDAP 注解不会进入领域对象。
成功后重定向到 `/signin/mfa`,显示目录账号、objectGUID、邮箱、直接所属组及组 DN。
**这是密码因素验收页面,MFA 尚未接入,不是完整登录成功。** 不创建 Spring Security
认证上下文,不调用 Hydra,不替换现役 Go/Authelia/Gitea 登录链路。演示入口 `/preview`
仍完全隔离,默认关闭,演示码不能推进真实认证。
认证上下文,不调用 Hydra,不替换现役 Go/Authelia/Gitea 登录链路。
## 目录和组语义
@@ -17,7 +21,8 @@
不把 Spring 的 `FACTOR_PASSWORD` 当作组。结果排序,不做应用专用组改写。
- 此轮不展开嵌套组、不推导 primaryGroupID,也不宣称与 Authelia 的有效组集合完全一致。
遇到 ranged memberOf 或不同 DN 同名 CN 拒绝映射,不静默丢组或合并不同主体。
- AD bind 执行密码及账号状态检查;Spring 解析禁用、锁定、密码过期等 AD 子码。
- AD bind 执行密码及账号状态检查;基础设施层将禁用、锁定、密码过期等 AD 子码转换为
应用层认证失败原因,不向领域层泄露 LDAP/Spring 异常。
搜索排除 computer 对象,只接受唯一用户条目和合法 objectGUID/sAMAccountName。
- 邮箱作为目录属性展示,不声称 `email_verified=true`。
@@ -69,7 +74,7 @@ java -Djavax.net.ssl.trustStore=/run/iam/truststore \
这里 truststore 仅含公开信任锚,口令不是目录密码。保留所需公共根证书;不得禁用
LDAP endpoint identification 或用信任所有证书的 socket factory。连接/读取超时为 3/5 秒。
AD 根范围查询可能返回 DomainDnsZones/ForestDnsZones 等分区 referral;配置为 ignore,
由 Spring AD provider 忽略 partial result,不使用 throw 打断用户查询,也不 follow 转发用户凭据。
由仓储的 LdapTemplate 忽略 partial result,不使用 throw 打断用户查询,也不 follow 转发用户凭据。
浏览器入口只接受 HTTPS;明文请求返回 426。默认不信任转发头。若以后由代理终结 TLS,
必须配合仅受信代理可达的后端网络和转发头配置,不能公开一个信任任意 forwarded header
@@ -86,7 +91,7 @@ AD 根范围查询可能返回 DomainDnsZones/ForestDnsZones 等分区 referral
入口限流、审计、MFA、Hydra 事务和恢复策略。
基础存活检查使用 `/actuator/health/liveness`。Boot 自动配置的 LDAP 健康项并未连接这里
独立配置的 AD provider,不能把该项当作此认证路径的可用性验证。
按用户 bind 创建的仓储连接,不能把该项当作此认证路径的可用性验证。
## 本轮验证边界
@@ -95,12 +100,14 @@ AD 根范围查询可能返回 DomainDnsZones/ForestDnsZones 等分区 referral
仍未完整认证。UnboundID 的 UPN bind 与 AD 子码由测试拦截器模拟,不能替代 Samba AD。
测试证书、私钥与账号全为虚构夹具,不用于实际部署。
2026-09-25:JVM 测试共 12 项通过(原有 6 项、新增 AD 6 项),`bootJar` 构建通过。
实际 JVM 使用受信 CA 完成 Samba AD RootDSE 查询,HTTPS 页面返回 200。
2026-09-25:DDD/Spring Data LDAP 版本通过 20 项 JVM 测试和 `bootJar` 构建,
包含同一次 bind 连接完成仓储查询、用例结束关闭连接、领域规则及监控集成。
开发 HTTPS 实例已更新为该版本。此前 JVM 使用受信 CA 完成 Samba AD RootDSE 查询。
浏览器已检查登录表单渲染、真实 CSRF 原生 POST 和失败后清空密码;只使用在访问 AD 前
即拒绝的合成外域用户名,不尝试猜测人类密码。浏览器回归共 1 项通过,包含移动端布局。
复现:`IAM_AD_URL=https://验收域名:端口 npm --prefix frontend run test:browser -- ad-login.spec.ts`。
维护者已在 HTTPS 页面完成真实密码验证,成功到达待 MFA 页面,并反馈目录标识、邮箱与
重构前,维护者已在 HTTPS 页面完成真实密码验证,成功到达待 MFA 页面,并反馈目录标识、邮箱与
六个直接所属组的查询结果。该验收覆盖 Samba AD 第一因素与属性读取,不表示 MFA、
嵌套组/主组等价性或 Hydra 登录已完成。不在聊天、命令行或日志中传递人类密码。
嵌套组/主组等价性或 Hydra 登录已完成。Spring Data LDAP 重构后的真实人类复验仍待反馈。
不在聊天、命令行或日志中传递人类密码。
新增 AD 路径尚未进行 Native 测试,不能复用旧 UI 原型的 Native 结论。
-106
View File
@@ -1,106 +0,0 @@
# 浏览器登录流程原型
参考 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.

Before

Width:  |  Height:  |  Size: 37 KiB

+1 -1
View File
@@ -2,7 +2,7 @@ import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: {
baseURL: process.env.IAM_PREVIEW_URL ?? "http://127.0.0.1:18081",
baseURL: process.env.IAM_AD_URL,
headless: true,
},
});
+23
View File
@@ -0,0 +1,23 @@
import { useState, type ReactNode } from "react";
import type { CsrfToken } from "../page-context";
type Props = {
action: string;
csrf: CsrfToken;
label: string;
children?: ReactNode;
};
/** Submit a browser document request; the server owns authentication transitions. */
export function SubmitForm({ action, csrf, label, children }: Props) {
const [pending, setPending] = useState(false);
return (
<form method="post" action={action} onSubmit={() => setPending(true)} aria-busy={pending}>
<input type="hidden" name={csrf.name} value={csrf.value} />
{children}
<button className="primary" type="submit" disabled={pending}>
{pending ? "正在继续…" : label}
</button>
</form>
);
}
+3 -187
View File
@@ -1,192 +1,8 @@
import { createRoot } from "react-dom/client";
import { useState, useLayoutEffect, type ReactNode } from "react";
import { readPageContext } from "./page-context";
import { SignInPage } from "./pages/SignInPage";
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 />,
<SignInPage context={readPageContext()} />,
);
+32
View File
@@ -0,0 +1,32 @@
export type CsrfToken = { name: string; value: string };
type PageBase = {
name: string;
error: string;
action: string;
csrf: CsrfToken;
};
export type SignInContext = PageBase & (
| { step: "password" }
| {
step: "mfa-pending";
identity: {
username: string;
subjectId: string;
email: string;
groups: string[];
groupDns: string[];
};
}
);
export function readPageContext(): SignInContext {
const data = document.getElementById("login-context")?.textContent;
if (!data) throw new Error("Missing login page context");
const context: SignInContext = JSON.parse(data);
if (context.step !== "password" && context.step !== "mfa-pending") {
throw new Error("Unknown login step");
}
return context;
}
+54
View File
@@ -0,0 +1,54 @@
import { SubmitForm } from "../components/SubmitForm";
import type { SignInContext } from "../page-context";
export function SignInPage({ context }: { context: SignInContext }) {
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>}
{context.step === "mfa-pending" && (
<div className="directory-result">
<dl>
<dt>账号</dt><dd>{context.identity.username}</dd>
<dt>目录标识</dt><dd>{context.identity.subjectId}</dd>
<dt>邮箱</dt><dd>{context.identity.email || "未设置"}</dd>
</dl>
<h2>直接所属组</h2>
{context.identity.groups.length
? <ul>{context.identity.groups.map(group => <li key={group}>{group}</li>)}</ul>
: <p>没有直接所属组。</p>}
<details>
<summary>组 DN</summary>
<ul>{context.identity.groupDns.map(dn => <li key={dn}>{dn}</li>)}</ul>
</details>
<p>当前仅读取 memberOf,不展开嵌套组,也不包含主组。</p>
</div>
)}
<SubmitForm action={context.action} csrf={context.csrf}
label={context.step === "password" ? "继续" : "退出并重新验证"}>
{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>
</>}
</SubmitForm>
</section>
<footer>独立 IAM · AD 接入验证</footer>
</main>
);
}
+2 -91
View File
@@ -29,15 +29,6 @@ header {
.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;
@@ -50,39 +41,6 @@ header {
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;
@@ -144,42 +102,12 @@ button {
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;
@@ -195,12 +123,6 @@ button:focus-visible {
.card {
padding: 26px 22px;
}
.steps {
gap: 5px;
}
.steps li {
font-size: 11px;
}
}
@media (prefers-color-scheme: dark) {
:root {
@@ -211,28 +133,17 @@ button:focus-visible {
background: #1e3027;
border-color: #344b3d;
}
.brand,
.steps [aria-current],
.success {
.brand {
color: #b9ddc8;
}
.intro,
.eyebrow,
.help p,
.link,
.back {
.eyebrow {
color: #acbfb2;
}
.steps li {
color: #98aa9e;
}
input:not([type="hidden"]) {
background: #18271f;
border-color: #526657;
}
.help {
border-color: #3a4d40;
}
.error {
background: #492b29;
color: #ffc3b9;
-95
View File
@@ -1,95 +0,0 @@
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" });
});
+2 -2
View File
@@ -59,7 +59,7 @@ def main():
def request(path, authenticated=False):
headers = {'Accept': 'text/plain' if authenticated and path == '/actuator/prometheus' else 'application/json'}
if path == '/preview':
if path == '/signin':
headers['Accept'] = 'text/html'
if authenticated:
headers['Authorization'] = f'Basic {basic}'
@@ -80,7 +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'
assert request('/signin')[0] == 404, 'Sign-in must be disabled without directory configuration'
status, before = request('/actuator/prometheus', authenticated=True)
assert status == 200, 'Authenticated Prometheus scrape failed'
for _ in range(3):
@@ -1,153 +0,0 @@
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();
}
}
@@ -1,12 +0,0 @@
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,50 @@
package top.ddupan.iam.login.authentication.application;
import java.time.Clock;
import java.util.UUID;
import top.ddupan.iam.login.authentication.application.port.PasswordAuthenticator;
import top.ddupan.iam.login.authentication.domain.UserRepository;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
import top.ddupan.iam.login.authentication.domain.LoginTransaction;
/** Coordinates the first-factor use case. HTTP/session/LDAP details stay in adapters. */
public final class SignInService {
public enum PasswordResult { ACCEPTED, REJECTED, EXPIRED, WRONG_STEP, RETRY_LATER }
private final PasswordAuthenticator authenticator;
private final Clock clock;
private final boolean enabled;
public SignInService(PasswordAuthenticator authenticator, Clock clock, boolean enabled) {
this.authenticator = authenticator;
this.clock = clock;
this.enabled = enabled;
}
public boolean enabled() { return enabled; }
public LoginTransaction start() { return LoginTransaction.start(UUID.randomUUID(), clock.instant()); }
public boolean expired(LoginTransaction transaction) { return transaction.expiredAt(clock.instant()); }
public PasswordResult submitPassword(LoginTransaction transaction, String username, String password) {
if (!enabled) throw new IllegalStateException("Human sign-in is disabled");
var attempt = transaction.beginPasswordAttempt(clock.instant());
if (attempt != LoginTransaction.Attempt.ALLOWED) {
return switch (attempt) {
case EXPIRED -> PasswordResult.EXPIRED;
case WRONG_STEP -> PasswordResult.WRONG_STEP;
case RETRY_LATER -> PasswordResult.RETRY_LATER;
case ALLOWED -> throw new IllegalStateException("Unexpected attempt result");
};
}
try (var session = authenticator.authenticate(username, password)) {
var identity = session.users().findByLoginName(session.loginName());
if (identity.isEmpty()) return PasswordResult.REJECTED;
// A slow directory response must not revive an expired transaction.
var verifiedAt = clock.instant();
if (transaction.expiredAt(verifiedAt)) return PasswordResult.EXPIRED;
transaction.passwordVerified(identity.orElseThrow(), verifiedAt);
return PasswordResult.ACCEPTED;
} catch (PasswordVerificationException | UserRepository.AccessFailure ex) {
return PasswordResult.REJECTED;
}
}
}
@@ -0,0 +1,10 @@
package top.ddupan.iam.login.authentication.application.port;
import top.ddupan.iam.login.authentication.domain.UserRepository;
/** Uses the authenticated user's connection, without exposing connection or credential objects. */
public interface AuthenticatedUserSession extends AutoCloseable {
String loginName();
UserRepository users();
@Override void close();
}
@@ -0,0 +1,6 @@
package top.ddupan.iam.login.authentication.application.port;
/** Password authentication opens a short-lived user repository scope. */
public interface PasswordAuthenticator {
AuthenticatedUserSession authenticate(String username, String password);
}
@@ -0,0 +1,14 @@
package top.ddupan.iam.login.authentication.application.port;
/** Adapter failures translated into application vocabulary, without vendor exception details. */
public final class PasswordVerificationException extends RuntimeException {
public enum Reason { REJECTED, DISABLED, LOCKED, PASSWORD_EXPIRED, ACCOUNT_EXPIRED, UNAVAILABLE }
private final Reason reason;
public PasswordVerificationException(Reason reason) {
super(reason.name());
this.reason = reason;
}
public Reason reason() { return reason; }
}
@@ -0,0 +1,56 @@
package top.ddupan.iam.login.authentication.domain;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.UUID;
/** Owns first-factor ordering, lifetime and the identity to which further factors must bind. */
public final class LoginTransaction {
private static final Duration LIFETIME = Duration.ofMinutes(10);
private static final Duration ATTEMPT_INTERVAL = Duration.ofSeconds(2);
public enum Step { PASSWORD_REQUIRED, MFA_REQUIRED }
public enum Attempt { ALLOWED, EXPIRED, WRONG_STEP, RETRY_LATER }
private final UUID id;
private Step step = Step.PASSWORD_REQUIRED;
private Instant expiresAt;
private Instant retryAfter = Instant.MIN;
private User identity;
private LoginTransaction(UUID id, Instant now) {
this.id = Objects.requireNonNull(id);
this.expiresAt = now.plus(LIFETIME);
}
public static LoginTransaction start(UUID id, Instant now) {
return new LoginTransaction(id, now);
}
public Attempt beginPasswordAttempt(Instant now) {
if (expiredAt(now)) return Attempt.EXPIRED;
if (step != Step.PASSWORD_REQUIRED) return Attempt.WRONG_STEP;
if (now.isBefore(retryAfter)) return Attempt.RETRY_LATER;
retryAfter = now.plus(ATTEMPT_INTERVAL);
return Attempt.ALLOWED;
}
public void passwordVerified(User identity, Instant now) {
if (expiredAt(now) || step != Step.PASSWORD_REQUIRED) {
throw new IllegalStateException("Password verification is not allowed in this transaction state");
}
this.identity = Objects.requireNonNull(identity);
this.step = Step.MFA_REQUIRED;
this.expiresAt = now.plus(LIFETIME);
}
public UUID id() { return id; }
public Step step() { return step; }
public boolean expiredAt(Instant now) { return !now.isBefore(expiresAt); }
public User identity() {
if (identity == null) throw new IllegalStateException("No verified identity yet");
return identity;
}
}
@@ -0,0 +1,48 @@
package top.ddupan.iam.login.authentication.domain;
import java.util.List;
import java.util.Objects;
/** Directory-owned user aggregate. Identity is stable while profile and membership may change. */
public final class User {
private final UserId id;
private final String username;
private final String displayName;
private final String email;
private final List<GroupMembership> memberships;
public User(UserId id, String username, String displayName, String email, List<GroupMembership> memberships) {
this.id = Objects.requireNonNull(id);
if (username == null || username.isBlank()) throw new IllegalArgumentException("Missing username");
this.username = username;
this.displayName = Objects.requireNonNull(displayName);
this.email = Objects.requireNonNull(email);
this.memberships = List.copyOf(memberships);
}
public UserId id() { return id; }
public String username() { return username; }
public String displayName() { return displayName; }
public String email() { return email; }
public List<GroupMembership> memberships() { return memberships; }
@Override public boolean equals(Object other) { return other instanceof User user && id.equals(user.id); }
@Override public int hashCode() { return id.hashCode(); }
public record UserId(String authority, String value) {
public UserId {
if (authority == null || authority.isBlank() || value == null || value.isBlank()) {
throw new IllegalArgumentException("Missing user identifier");
}
}
}
/** External group identifiers are opaque to the domain. */
public record GroupMembership(String name, String externalId) {
public GroupMembership {
if (name == null || name.isBlank() || externalId == null || externalId.isBlank()) {
throw new IllegalArgumentException("Missing group identifier");
}
}
}
}
@@ -0,0 +1,12 @@
package top.ddupan.iam.login.authentication.domain;
import java.util.Optional;
/** Read-only user collection; directory entries and LDAP types never cross this boundary. */
public interface UserRepository {
Optional<User> findByLoginName(String loginName);
final class AccessFailure extends RuntimeException {
public AccessFailure() { super("User repository is unavailable or returned an invalid user"); }
}
}
@@ -0,0 +1,27 @@
package top.ddupan.iam.login.authentication.infrastructure.ad;
import java.util.Locale;
import javax.naming.NamingException;
import org.springframework.LdapDataEntry;
import org.springframework.ldap.odm.core.impl.DefaultObjectDirectoryMapper;
import top.ddupan.iam.login.authentication.domain.UserRepository;
/** Keep Spring's ODM mapping while refusing silently truncated AD group attributes. */
final class AdEntryMapper extends DefaultObjectDirectoryMapper {
@Override
public <T> T mapFromLdapDataEntry(LdapDataEntry entry, Class<T> type) {
var ids = entry.getAttributes().getIDs();
try {
while (ids.hasMore()) {
if (ids.next().toLowerCase(Locale.ROOT).startsWith("memberof;")) {
throw new UserRepository.AccessFailure();
}
}
} catch (NamingException ex) {
throw new UserRepository.AccessFailure();
} finally {
try { ids.close(); } catch (NamingException ignored) { }
}
return super.mapFromLdapDataEntry(entry, type);
}
}
@@ -0,0 +1,91 @@
package top.ddupan.iam.login.authentication.infrastructure.ad;
import java.net.URI;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.ldap.repository.support.SimpleLdapRepository;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.core.support.SingleContextSource;
import org.springframework.stereotype.Component;
import top.ddupan.iam.login.authentication.application.port.AuthenticatedUserSession;
import top.ddupan.iam.login.authentication.application.port.PasswordAuthenticator;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException.Reason;
/** Bind authenticates; the scoped Spring Data repository owns all user and membership reads. */
@Component
@EnableConfigurationProperties(AdProperties.class)
public final class AdPasswordAuthenticator implements PasswordAuthenticator {
private static final Pattern AD_SUBCODE = Pattern.compile("\\bdata\\s+([0-9a-f]+)", Pattern.CASE_INSENSITIVE);
private final AdProperties properties;
private final LdapContextSource contexts;
public AdPasswordAuthenticator(AdProperties properties) {
this.properties = properties;
if (!properties.enabled()) { contexts = null; return; }
var 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");
}
contexts = new LdapContextSource();
contexts.setUrl(properties.url());
contexts.setBase(properties.baseDn());
contexts.setPooled(false);
contexts.setReferral("ignore");
contexts.setBaseEnvironmentProperties(Map.of(
"com.sun.jndi.ldap.connect.timeout", "3000",
"com.sun.jndi.ldap.read.timeout", "5000",
"java.naming.ldap.attributes.binary", "objectGUID"));
contexts.afterPropertiesSet();
}
@Override
public AuthenticatedUserSession authenticate(String username, String password) {
if (contexts == null) throw new PasswordVerificationException(Reason.UNAVAILABLE);
if (username == null || username.isBlank() || username.length() > 256
|| username.contains("\\") || !username.equals(username.strip())
|| (username.contains("@") && !username.toLowerCase(Locale.ROOT)
.endsWith("@" + properties.domain().toLowerCase(Locale.ROOT)))
|| password == null || password.isEmpty() || password.length() > 1024) {
throw new PasswordVerificationException(Reason.REJECTED);
}
String principal = username.contains("@") ? username : username + "@" + properties.domain();
try {
var connection = new SingleContextSource(contexts.getContext(principal, password));
try {
var mapper = new AdEntryMapper();
var operations = new LdapTemplate(connection);
operations.setIgnorePartialResultException(true);
operations.setObjectDirectoryMapper(mapper);
var entries = new SimpleLdapRepository<>(operations, mapper, AdUserEntry.class);
return new AdUserRepository(entries, connection, properties.domain(), principal);
} catch (RuntimeException ex) {
connection.destroy();
throw ex;
}
} catch (org.springframework.ldap.AuthenticationException ex) {
throw new PasswordVerificationException(reason(ex));
} catch (org.springframework.ldap.NamingException | org.springframework.dao.DataAccessException ex) {
throw new PasswordVerificationException(Reason.UNAVAILABLE);
}
}
private static Reason reason(org.springframework.ldap.AuthenticationException exception) {
// Translate AD's diagnostic codes; never expose the diagnostic or credentials to the use case.
var matcher = AD_SUBCODE.matcher(exception.getMessage() == null ? "" : exception.getMessage());
if (!matcher.find()) return Reason.REJECTED;
return switch (matcher.group(1).toLowerCase(Locale.ROOT)) {
case "533" -> Reason.DISABLED;
case "775" -> Reason.LOCKED;
case "532", "773" -> Reason.PASSWORD_EXPIRED;
case "701" -> Reason.ACCOUNT_EXPIRED;
default -> Reason.REJECTED;
};
}
}
@@ -1,4 +1,4 @@
package top.ddupan.iam.login.ad;
package top.ddupan.iam.login.authentication.infrastructure.ad;
import org.springframework.boot.context.properties.ConfigurationProperties;
@@ -0,0 +1,20 @@
package top.ddupan.iam.login.authentication.infrastructure.ad;
import java.util.List;
import javax.naming.Name;
import lombok.Getter;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;
/** Persistence representation, deliberately separate from the domain user. */
@Getter
@Entry(objectClasses = "user")
public final class AdUserEntry {
@Id private Name dn;
@Attribute(name = "objectGUID", type = Attribute.Type.BINARY) private byte[] objectGuid;
@Attribute(name = "sAMAccountName") private String accountName;
@Attribute(name = "displayName") private String displayName;
@Attribute(name = "mail") private String email;
@Attribute(name = "memberOf") private List<String> memberOf;
}
@@ -0,0 +1,82 @@
package top.ddupan.iam.login.authentication.infrastructure.ad;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.List;
import java.util.Optional;
import java.util.TreeMap;
import java.util.UUID;
import javax.naming.NamingException;
import javax.naming.ldap.LdapName;
import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.ldap.core.support.SingleContextSource;
import top.ddupan.iam.login.authentication.application.port.AuthenticatedUserSession;
import top.ddupan.iam.login.authentication.domain.User;
import top.ddupan.iam.login.authentication.domain.User.GroupMembership;
import top.ddupan.iam.login.authentication.domain.User.UserId;
import top.ddupan.iam.login.authentication.domain.UserRepository;
import static org.springframework.ldap.query.LdapQueryBuilder.query;
/** One authenticated connection and one Spring Data repository per use-case scope. */
final class AdUserRepository implements UserRepository, AuthenticatedUserSession {
private final LdapRepository<AdUserEntry> entries;
private final SingleContextSource connection;
private final String authority;
private final String loginName;
private boolean closed;
AdUserRepository(LdapRepository<AdUserEntry> entries, SingleContextSource connection,
String authority, String loginName) {
this.entries = entries;
this.connection = connection;
this.authority = authority;
this.loginName = loginName;
}
@Override
public Optional<User> findByLoginName(String name) {
requireOpen();
try {
return entries.findOne(query().where("objectClass").is("user")
.and("objectClass").not().is("computer")
.and(query().where("sAMAccountName").is(name).or("userPrincipalName").is(name)))
.map(this::toUser);
} catch (org.springframework.ldap.NamingException | org.springframework.dao.DataAccessException | IllegalArgumentException ex) {
throw new UserRepository.AccessFailure();
}
}
private User toUser(AdUserEntry entry) {
var groups = new TreeMap<String, GroupMembership>();
for (String dn : entry.getMemberOf() == null ? List.<String>of() : entry.getMemberOf()) {
try {
var name = new LdapName(dn);
var rdn = name.getRdn(name.size() - 1);
if (!rdn.getType().equalsIgnoreCase("CN")) throw new UserRepository.AccessFailure();
String cn = rdn.getValue().toString();
if (groups.putIfAbsent(cn, new GroupMembership(cn, dn)) != null) {
throw new UserRepository.AccessFailure();
}
} catch (NamingException ex) { throw new UserRepository.AccessFailure(); }
}
return new User(new UserId(authority, guid(entry.getObjectGuid())), entry.getAccountName(),
entry.getDisplayName() == null ? entry.getAccountName() : entry.getDisplayName(),
entry.getEmail() == null ? "" : entry.getEmail(), List.copyOf(groups.values()));
}
static String guid(byte[] bytes) {
if (bytes == null || bytes.length != 16) throw new UserRepository.AccessFailure();
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());
return new UUID(most, ByteBuffer.wrap(bytes, 8, 8).getLong()).toString();
}
@Override public String loginName() { requireOpen(); return loginName; }
@Override public UserRepository users() { requireOpen(); return this; }
private void requireOpen() { if (closed) throw new IllegalStateException("User repository scope is closed"); }
@Override public void close() {
if (!closed) { closed = true; connection.destroy(); }
}
}
@@ -0,0 +1,12 @@
package top.ddupan.iam.login.authentication.interfaces.web;
import top.ddupan.iam.login.authentication.domain.LoginTransaction;
/** HTTP-session storage plus presentation feedback. Authentication rules live in the aggregate. */
final class BrowserSignInState {
final LoginTransaction transaction;
String username = "";
String error = "";
BrowserSignInState(LoginTransaction transaction) { this.transaction = transaction; }
}
@@ -1,4 +1,4 @@
package top.ddupan.iam.login.preview;
package top.ddupan.iam.login.authentication.interfaces.web;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -1,30 +1,30 @@
package top.ddupan.iam.login.ad;
package top.ddupan.iam.login.authentication.interfaces.web;
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;
import top.ddupan.iam.login.authentication.application.SignInService;
import top.ddupan.iam.login.authentication.domain.LoginTransaction.Step;
import top.ddupan.iam.login.authentication.domain.User.GroupMembership;
/** Human first-factor PoC. No SecurityContext, MFA acceptance, or Hydra calls. */
/** Translates browser requests and use-case outcomes; no directory or authentication policy here. */
@RestController
public class AdLoginController {
static final String STATE = AdLoginController.class.getName() + ".state";
private final AdPasswordVerifier verifier;
public class SignInController {
static final String STATE = SignInController.class.getName() + ".state";
private final SignInService signIn;
private final PageRenderer renderer;
public AdLoginController(AdPasswordVerifier verifier, PageRenderer renderer) {
this.verifier = verifier;
public SignInController(SignInService signIn, PageRenderer renderer) {
this.signIn = signIn;
this.renderer = renderer;
}
@@ -34,7 +34,7 @@ public class AdLoginController {
var session = request.getSession();
synchronized (session) {
var state = state(session);
if (state.identity != null) return redirect("/signin/mfa");
if (state.transaction.step() == Step.MFA_REQUIRED) return redirect("/signin/mfa");
return renderer.render(Map.of("step", "password", "name", state.username,
"error", state.error, "action", "/signin/password", "csrf", csrf(csrf)));
}
@@ -48,26 +48,22 @@ public class AdLoginController {
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);
var state = (BrowserSignInState) session.getAttribute(STATE);
if (state == null) return redirect("/signin");
state.username = username.length() <= 256 ? username : "";
try {
var identity = verifier.verify(username, password);
return switch (signIn.submitPassword(state.transaction, username, password)) {
case ACCEPTED -> {
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");
yield redirect("/signin/mfa");
}
case REJECTED -> {
state.error = "无法验证账号,请检查凭据与账号状态,或稍后重试。";
yield redirect("/signin");
}
case EXPIRED, WRONG_STEP -> redirect("/signin");
case RETRY_LATER -> throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS);
};
}
}
@@ -78,12 +74,14 @@ public class AdLoginController {
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(),
if (state.transaction.step() != Step.MFA_REQUIRED) return redirect("/signin");
var user = state.transaction.identity();
return renderer.render(Map.of("step", "mfa-pending", "name", user.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())));
"identity", Map.of("username", user.username(), "subjectId", user.id().value(),
"email", user.email(),
"groups", user.memberships().stream().map(GroupMembership::name).toList(),
"groupDns", user.memberships().stream().map(GroupMembership::externalId).toList())));
}
}
@@ -96,33 +94,25 @@ public class AdLoginController {
}
private void requireAvailable(HttpServletRequest request) {
if (!verifier.enabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
if (!signIn.enabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
if (!request.isSecure()) throw new ResponseStatusException(HttpStatus.UPGRADE_REQUIRED, "HTTPS required");
}
private BrowserSignInState state(HttpSession session) {
var state = (BrowserSignInState) session.getAttribute(STATE);
if (state == null || signIn.expired(state.transaction)) {
state = new BrowserSignInState(signIn.start());
session.setAttribute(STATE, state);
}
return state;
}
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,34 @@
package top.ddupan.iam.login.configuration;
import java.time.Clock;
import javax.naming.directory.DirContext;
import javax.naming.ldap.LdapContext;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.ldap.core.DirContextProxy;
import top.ddupan.iam.login.authentication.infrastructure.ad.AdUserEntry;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.ddupan.iam.login.authentication.application.SignInService;
import top.ddupan.iam.login.authentication.application.port.PasswordAuthenticator;
import top.ddupan.iam.login.authentication.infrastructure.ad.AdProperties;
/** Composition root: dependencies point inward, framework wiring stays outside the model. */
@Configuration(proxyBeanMethods = false)
@RegisterReflectionForBinding(AdUserEntry.class)
@ImportRuntimeHints(AuthenticationConfiguration.DirectoryHints.class)
class AuthenticationConfiguration {
@Bean
SignInService signInService(PasswordAuthenticator authenticator, AdProperties properties) {
return new SignInService(authenticator, Clock.systemUTC(), properties.enabled());
}
static class DirectoryHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.proxies().registerJdkProxy(LdapContext.class, DirContextProxy.class);
hints.proxies().registerJdkProxy(DirContext.class, DirContextProxy.class);
}
}
}
@@ -0,0 +1,22 @@
package top.ddupan.iam.login.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration(proxyBeanMethods = false)
class SecurityConfiguration {
@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/signin", "/signin/**", "/assets/**", "/actuator/health/**").permitAll()
.anyRequest().authenticated())
.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();
}
}
@@ -0,0 +1,28 @@
package top.ddupan.iam.login.configuration;
import java.time.Duration;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration(proxyBeanMethods = false)
@ImportRuntimeHints(WebConfiguration.Resources.class)
class WebConfiguration implements WebMvcConfigurer {
@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/**");
}
}
}
@@ -1,44 +0,0 @@
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/**");
}
}
}
@@ -1,129 +0,0 @@
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,7 +1,6 @@
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;
@@ -12,8 +11,6 @@ import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.Transpo
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;
@@ -21,14 +18,10 @@ 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(properties = "iam.ui-preview.enabled=true")
@SpringBootTest
@AutoConfigureMockMvc
@AutoConfigureMetrics
@AutoConfigureTracing
@@ -52,61 +45,8 @@ class IamLoginApplicationTests {
MockMvc mvc;
@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();
void signInIsDisabledUntilDirectoryIsConfigured() throws Exception {
mvc.perform(get("/signin").secure(true)).andExpect(status().isNotFound());
}
@Test
@@ -1,211 +0,0 @@
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();
}
}
@@ -0,0 +1,107 @@
package top.ddupan.iam.login.authentication.application;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import top.ddupan.iam.login.authentication.application.port.AuthenticatedUserSession;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
import top.ddupan.iam.login.authentication.domain.LoginTransaction;
import top.ddupan.iam.login.authentication.domain.User;
import top.ddupan.iam.login.authentication.domain.UserRepository;
import static org.assertj.core.api.Assertions.*;
class SignInServiceTests {
static final User ALICE = new User(new User.UserId("directory", "alice-id"), "alice", "Alice", "", List.of());
@Test
void verifiesPasswordThenReadsTheBoundUserAndClosesTheRepositoryScope() {
var scope = new Scope(name -> {
assertThat(name).isEqualTo("alice@directory");
return Optional.of(ALICE);
});
var service = new SignInService((username, password) -> scope, new TestClock(), true);
var transaction = service.start();
assertThat(service.submitPassword(transaction, "alice", "secret")).isEqualTo(SignInService.PasswordResult.ACCEPTED);
assertThat(scope.closed).isTrue();
assertThat(transaction.step()).isEqualTo(LoginTransaction.Step.MFA_REQUIRED);
assertThat(transaction.identity()).isEqualTo(ALICE);
}
@Test
void failedAuthenticationDoesNotAdvanceTheTransaction() {
var service = new SignInService((username, password) -> {
throw new PasswordVerificationException(PasswordVerificationException.Reason.REJECTED);
}, new TestClock(), true);
var transaction = service.start();
assertThat(service.submitPassword(transaction, "alice", "wrong")).isEqualTo(SignInService.PasswordResult.REJECTED);
assertThat(transaction.step()).isEqualTo(LoginTransaction.Step.PASSWORD_REQUIRED);
}
@Test
void missingUserDoesNotAuthenticateAndStillClosesTheScope() {
var scope = new Scope(name -> Optional.empty());
var service = new SignInService((username, password) -> scope, new TestClock(), true);
var transaction = service.start();
assertThat(service.submitPassword(transaction, "alice", "secret")).isEqualTo(SignInService.PasswordResult.REJECTED);
assertThat(scope.closed).isTrue();
assertThat(transaction.step()).isEqualTo(LoginTransaction.Step.PASSWORD_REQUIRED);
}
@Test
void expiredAndRepeatedAttemptsDoNotCallTheDirectory() {
var calls = new AtomicInteger();
var clock = new TestClock();
var service = new SignInService((username, password) -> {
calls.incrementAndGet();
throw new PasswordVerificationException(PasswordVerificationException.Reason.REJECTED);
}, clock, true);
var transaction = service.start();
service.submitPassword(transaction, "alice", "wrong");
assertThat(service.submitPassword(transaction, "alice", "wrong")).isEqualTo(SignInService.PasswordResult.RETRY_LATER);
clock.now = clock.now.plusSeconds(600);
assertThat(service.submitPassword(transaction, "alice", "wrong")).isEqualTo(SignInService.PasswordResult.EXPIRED);
assertThat(calls.get()).isEqualTo(1);
}
@Test
void aSlowRepositoryCannotReviveAnExpiredTransaction() {
var clock = new TestClock();
var scope = new Scope(name -> { clock.now = clock.now.plusSeconds(600); return Optional.of(ALICE); });
var service = new SignInService((username, password) -> scope, clock, true);
var transaction = service.start();
assertThat(service.submitPassword(transaction, "alice", "secret")).isEqualTo(SignInService.PasswordResult.EXPIRED);
assertThat(transaction.step()).isEqualTo(LoginTransaction.Step.PASSWORD_REQUIRED);
assertThat(scope.closed).isTrue();
}
@Test
void repositoryFailureClosesTheScopeWithoutPromotingIdentity() {
var scope = new Scope(name -> { throw new UserRepository.AccessFailure(); });
var service = new SignInService((username, password) -> scope, new TestClock(), true);
var transaction = service.start();
assertThat(service.submitPassword(transaction, "alice", "secret")).isEqualTo(SignInService.PasswordResult.REJECTED);
assertThat(transaction.step()).isEqualTo(LoginTransaction.Step.PASSWORD_REQUIRED);
assertThat(scope.closed).isTrue();
}
private static final class Scope implements AuthenticatedUserSession {
private final UserRepository users;
boolean closed;
Scope(UserRepository users) { this.users = users; }
@Override public String loginName() { return "alice@directory"; }
@Override public UserRepository users() { return users; }
@Override public void close() { closed = true; }
}
private static final class TestClock extends Clock {
Instant now = Instant.parse("2026-01-01T00:00:00Z");
@Override public Instant instant() { return now; }
@Override public ZoneId getZone() { return ZoneOffset.UTC; }
@Override public Clock withZone(ZoneId zone) { return Clock.fixed(now, zone); }
}
}
@@ -0,0 +1,44 @@
package top.ddupan.iam.login.authentication.domain;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
class LoginTransactionTests {
static final Instant NOW = Instant.parse("2026-01-01T00:00:00Z");
static final User ALICE = new User(new User.UserId("directory", "alice-id"), "alice", "Alice", "", List.of());
@Test
void passwordVerificationBindsIdentityAndOnlyAdvancesToMfa() {
var transaction = LoginTransaction.start(UUID.randomUUID(), NOW);
assertThat(transaction.beginPasswordAttempt(NOW)).isEqualTo(LoginTransaction.Attempt.ALLOWED);
transaction.passwordVerified(ALICE, NOW);
assertThat(transaction.step()).isEqualTo(LoginTransaction.Step.MFA_REQUIRED);
assertThat(transaction.identity()).isEqualTo(ALICE);
assertThat(transaction.beginPasswordAttempt(NOW.plusSeconds(3))).isEqualTo(LoginTransaction.Attempt.WRONG_STEP);
var bob = new User(new User.UserId("directory", "bob-id"), "bob", "Bob", "", List.of());
assertThatThrownBy(() -> transaction.passwordVerified(bob, NOW.plusSeconds(3)))
.isInstanceOf(IllegalStateException.class);
assertThat(transaction.identity()).isEqualTo(ALICE);
}
@Test
void expiredTransactionsCannotAcceptAPasswordResult() {
var transaction = LoginTransaction.start(UUID.randomUUID(), NOW);
assertThat(transaction.beginPasswordAttempt(NOW.plusSeconds(600))).isEqualTo(LoginTransaction.Attempt.EXPIRED);
assertThatThrownBy(() -> transaction.passwordVerified(ALICE, NOW.plusSeconds(600)))
.isInstanceOf(IllegalStateException.class);
}
@Test
void attemptsAreSeparatedWithoutAdvancingAuthentication() {
var transaction = LoginTransaction.start(UUID.randomUUID(), NOW);
assertThat(transaction.beginPasswordAttempt(NOW)).isEqualTo(LoginTransaction.Attempt.ALLOWED);
assertThat(transaction.beginPasswordAttempt(NOW.plusSeconds(1))).isEqualTo(LoginTransaction.Attempt.RETRY_LATER);
assertThat(transaction.beginPasswordAttempt(NOW.plusSeconds(2))).isEqualTo(LoginTransaction.Attempt.ALLOWED);
assertThat(transaction.step()).isEqualTo(LoginTransaction.Step.PASSWORD_REQUIRED);
assertThatThrownBy(transaction::identity).isInstanceOf(IllegalStateException.class);
}
}
@@ -0,0 +1,79 @@
package top.ddupan.iam.login.authentication.infrastructure.ad;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException.Reason;
import top.ddupan.iam.login.authentication.domain.User.GroupMembership;
import top.ddupan.iam.login.support.AdDirectoryFixture;
import static org.assertj.core.api.Assertions.*;
class AdUserRepositoryIntegrationTests {
private static AdDirectoryFixture directory;
private static AdPasswordAuthenticator authenticator;
@BeforeAll static void start() {
directory = new AdDirectoryFixture();
authenticator = new AdPasswordAuthenticator(new AdProperties(true,
directory.url(), "example.test", "dc=example,dc=test"));
}
@AfterAll static void close() { directory.close(); }
@Test
void repositoryUsesTheBoundConnectionAndMapsGuidAndGroupsDespiteReferrals() {
int before = directory.binds.get();
try (var session = authenticator.authenticate("alice", "fixture-password")) {
var user = session.users().findByLoginName(session.loginName()).orElseThrow();
assertThat(user.id().value()).isEqualTo("00112233-4455-6677-8899-aabbccddeeff");
assertThat(user.memberships()).extracting(GroupMembership::name).containsExactly("MixedCase", "gitea-admins");
assertThat(session.users().findByLoginName("alice")).contains(user);
assertThat(directory.binds.get() - before).isEqualTo(1);
assertThat(directory.searchConnection).isEqualTo(directory.bindConnection);
}
}
@Test
void closingTheScopePreventsFurtherRepositoryUse() {
var session = authenticator.authenticate("[email protected]", "fixture-password");
var users = session.users();
session.close();
assertThatThrownBy(() -> users.findByLoginName("alice")).isInstanceOf(IllegalStateException.class);
assertThatThrownBy(session::users).isInstanceOf(IllegalStateException.class);
}
@Test
void wrongPasswordsUnknownAccountsAndAdAccountStatesAreTranslated() {
rejected("alice", "wrong", Reason.REJECTED);
rejected("unknown", "fixture-password", Reason.REJECTED);
rejected("disabled", "fixture-password", Reason.DISABLED);
rejected("locked", "fixture-password", Reason.LOCKED);
rejected("expired", "fixture-password", Reason.PASSWORD_EXPIRED);
}
@Test
void emptyPasswordsAndForeignDomainsNeverAttemptBind() {
int before = directory.binds.get();
rejected("alice", "", Reason.REJECTED);
rejected("[email protected]", "fixture-password", Reason.REJECTED);
assertThat(directory.binds.get()).isEqualTo(before);
}
@Test
void rejectsWrongTlsHostnameAndPlainLdapConfiguration() {
var wrongName = new AdPasswordAuthenticator(new AdProperties(true,
directory.mismatchedHostnameUrl(), "example.test", "dc=example,dc=test"));
assertThatThrownBy(() -> wrongName.authenticate("alice", "fixture-password"))
.isInstanceOfSatisfying(PasswordVerificationException.class,
ex -> assertThat(ex.reason()).isEqualTo(Reason.UNAVAILABLE));
assertThatThrownBy(() -> new AdPasswordAuthenticator(new AdProperties(true,
"ldap://localhost:389", "example.test", "dc=example,dc=test")))
.isInstanceOf(IllegalArgumentException.class);
}
private static void rejected(String username, String password, Reason reason) {
assertThatThrownBy(() -> authenticator.authenticate(username, password))
.isInstanceOfSatisfying(PasswordVerificationException.class,
ex -> assertThat(ex.reason()).isEqualTo(reason));
}
}
@@ -0,0 +1,90 @@
package top.ddupan.iam.login.authentication.interfaces.web;
import top.ddupan.iam.login.support.AdDirectoryFixture;
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.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 Data LDAP; 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(SignInIntegrationTests.FixtureHints.class)
class SignInIntegrationTests {
static class FixtureHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader loader) {
hints.resources().registerPattern("ldap/fixture.p12");
}
}
static class Directory {
static final AdDirectoryFixture INSTANCE = new AdDirectoryFixture();
}
@DynamicPropertySource
static void directory(DynamicPropertyRegistry registry) {
registry.add("iam.ad.url", () -> Directory.INSTANCE.url());
}
@AfterAll
static void close() { Directory.INSTANCE.close(); }
@Autowired MockMvc mvc;
@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());
}
@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 = (BrowserSignInState) session.getAttribute(SignInController.STATE);
assertThat(state.transaction.step()).isEqualTo(top.ddupan.iam.login.authentication.domain.LoginTransaction.Step.PASSWORD_REQUIRED);
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();
}
}
@@ -0,0 +1,100 @@
package top.ddupan.iam.login.support;
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 javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
/** Lazily initialized LDAPS fixture: loading test metadata must not start a server. */
public final class AdDirectoryFixture implements AutoCloseable {
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");
private final SSLContext original;
private final InMemoryDirectoryServer ldap;
public final java.util.concurrent.atomic.AtomicInteger binds = new java.util.concurrent.atomic.AtomicInteger();
public volatile long bindConnection;
public volatile long searchConnection;
public AdDirectoryFixture() {
try {
original = SSLContext.getDefault();
var store = KeyStore.getInstance("PKCS12");
try (var stream = AdDirectoryFixture.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) {
searchConnection = result.getConnectionID();
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 {
binds.incrementAndGet();
bindConnection = request.getConnectionID();
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); }
}
public String url() { return "ldaps://localhost:" + ldap.getListenPort(); }
public String mismatchedHostnameUrl() { return "ldaps://127.0.0.1:" + ldap.getListenPort(); }
@Override public void close() { ldap.shutDown(true); SSLContext.setDefault(original); }
}