Merge pull request '接入 AD 第一因素与 React 登录页面,由 Spring Security 管理认证' (#4) from feat/ad-login into main
Reviewed-on: #4
This commit was merged in pull request #4.
This commit is contained in:
@@ -42,3 +42,9 @@ out/
|
||||
*.log
|
||||
|
||||
__pycache__/
|
||||
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/test-results/
|
||||
frontend/playwright-report/
|
||||
.playwright-cli/
|
||||
|
||||
@@ -3,9 +3,13 @@
|
||||
- 后续修改必须新建分支并提交 PR;未经维护者明确指示,不直接推 main、不自行合并。
|
||||
- 默认中文维护项目文档、commit、issue 和 PR;代码与上游 API 名称保留英文。
|
||||
- 项目使用 Java 与 Spring;Native 是交付约束,不是可选优化,不引入 Kotlin。
|
||||
- 变更需通过适用的 JVM 测试和 Native 集成测试;未执行的验证明确报告。
|
||||
- 日常变更先通过适用的 JVM 测试,不要求每轮执行耗时的 Native 编译与测试;Native 仍为交付目标,在阶段性验收或兼容性风险变化时集中验证。未执行的验证明确报告。
|
||||
- 按 DDD 组织 authentication 上下文:领域拥有 User/UserRepository,应用层编排目录认证与读取,基础设施实现 AD 仓储与 Security Provider,Web 仅渲染页面;领域和应用层不依赖 Spring/Servlet/LDAP。
|
||||
- 用户仓储复用本次用户 bind 的连接,不新增只读服务账号;连接限于当前用例,不保留密码或连接在 HTTP session 中。
|
||||
- 选型演示在真实接入后删除,不将演示入口、状态机、验证码或开关保留为应用功能。
|
||||
- 只实现当前任务范围。Hydra 负责签发,首轮 AD 负责身份和组,本服务独立于 Ayatori。
|
||||
- 不把 LDAP 密码成功当成完整 MFA 成功;所有因素绑定同一主体与认证事务。
|
||||
- React 只替换 Spring Security 默认登录 UI;表单认证、SecurityContext、因素状态、会话轮换与退出交给框架,不自建登录状态机。
|
||||
- LDAP 密码成功可以建立仅含密码因素的 SecurityContext,但不等于完整 MFA 或 Hydra 授权;受保护操作必须检查所需因素。
|
||||
- 不提交凭据、MFA secret、生产配置秘密或包含上述内容的测试输出。
|
||||
- 生产部署配置属于 homelab-infra;本仓库初始化不授权切换现役登录入口。
|
||||
- 文档区分计划、实现、Native 实测和人类验收,禁止将代码存在当成部署证据。
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# iam-login
|
||||
|
||||
独立 IAM 的登录与认证服务,以 Java、Spring Security 和 GraalVM Native 实现,作为
|
||||
Hydra 的 Login/Consent 应用。当前已生成 Spring Initializr 骨架,尚未实现 AD、MFA 与 Hydra 登录链路。
|
||||
Hydra 的 Login/Consent 应用。已实现 AD 密码与直接所属组查询,以及等待 MFA 的浏览器页面;MFA 与 Hydra 登录链路仍待实现。
|
||||
|
||||
## 职责与边界
|
||||
|
||||
@@ -34,7 +34,8 @@ Hydra 的 Login/Consent 应用。当前已生成 Spring Initializr 骨架,尚
|
||||
4.1.1 和 Gradle;Spring Security 等库由 Boot BOM 管理,插件版本在 build.gradle 中固定。
|
||||
Native 使用 GraalVM 25。
|
||||
|
||||
Native 构建与原生二进制上的认证测试是交付要求;JVM 测试通过或 native 编译成功都不
|
||||
日常改动先跑 JVM 测试,不要求每轮编译 Native。Native 构建与原生二进制上的认证测试
|
||||
留在阶段性验收;JVM 测试通过或 native 编译成功都不
|
||||
单独构成验收。Keycloak 可作为流程与安全边界参考,不以它采用 Quarkus 作为 native
|
||||
兼容性证据,不直接引入其服务端 SPI 和模型。
|
||||
|
||||
@@ -46,12 +47,14 @@ Native 构建与原生二进制上的认证测试是交付要求;JVM 测试通
|
||||
[项目初始化](docs/bootstrap.md)。使用 JDK 25 执行:
|
||||
|
||||
```sh
|
||||
npm --prefix frontend ci
|
||||
npm --prefix frontend run build
|
||||
./gradlew test testAot
|
||||
./gradlew bootRun
|
||||
```
|
||||
|
||||
测试需要可用的 Docker,生成器配置了 Grafana LGTM Testcontainer。
|
||||
当前只有默认应用和上下文测试,默认 Spring Security 登录页不是可用的 IAM 登录流程。
|
||||
测试覆盖 AD 第一因素、浏览器流程和监控集成。人类登录统一从 `/signin` 进入。
|
||||
使用 GraalVM 25 验证原生测试与编译:
|
||||
|
||||
```sh
|
||||
@@ -63,4 +66,39 @@ Docker 开发使用 `scripts/gradle-in-docker`,默认持久挂载 Gradle 缓
|
||||
原生应用可用 `python3 scripts/native-smoke.py` 检查启动、默认访问控制和 HTTP 指标。
|
||||
JVM、AOT、Native 测试及原生应用 HTTP 检查已通过,实测范围与资源数据见
|
||||
[本地验证结果](docs/bootstrap.md#2026-09-25-本地验证结果)。
|
||||
AD、MFA 与 Hydra 认证链路仍待实现与验收。
|
||||
新增 AD 路径本轮按维护者要求只进行 JVM 验证,不沿用基线的 Native 验收结论。
|
||||
重构前的真实目录密码与属性/直接所属组读取已通过维护者浏览器验收;Spring Data LDAP
|
||||
版本已通过 JVM 和浏览器回归,真实人类复验待反馈。MFA 与 Hydra 链路仍待实现。
|
||||
|
||||
## 领域与代码组织
|
||||
|
||||
当前限界上下文为 `authentication`,使用 DDD 分层,依赖向领域内部收敛:
|
||||
|
||||
```text
|
||||
interfaces/web → infrastructure/security(principal)+ domain
|
||||
infrastructure/security → application → domain
|
||||
infrastructure/ad → application/port + domain
|
||||
configuration → 装配上述实现
|
||||
```
|
||||
|
||||
- `authentication/domain`:`User`、`UserRepository`;稳定主体与组成员关系属于领域模型,不依赖 Spring、Servlet、LDAP 或持久化注解。
|
||||
- `authentication/application`:`VerifyPassword` 用例,编排密码认证与同连接用户仓储查询;
|
||||
`port` 描述密码认证及其用户仓储会话,不暴露 `DirContext`。
|
||||
- `authentication/infrastructure/ad`:AD bind、Spring Data LDAP 用户仓储、LDAP 实体与领域映射。
|
||||
使用同一次用户 bind 的连接,查询结束关闭,不新增服务账号,不保存用户密码。
|
||||
- `authentication/infrastructure/security`:Provider 将目录用户转换为仅含密码因素的认证结果。
|
||||
- `authentication/interfaces/web`:登录页面与上下文转换;不处理密码 POST、认证会话或退出。
|
||||
- `configuration`:Spring 组件装配、安全链、静态资源和 Native hints。
|
||||
- `frontend/src`:入口、页面、表单组件和页面数据契约分别维护,只包含真实登录流程。
|
||||
|
||||
测试覆盖应用用例、AD 仓储和完整 Spring Security 过滤器链,LDAP 夹具集中在测试 `support` 包。
|
||||
界面采用 React + Vite,Spring 在 HTML 中内联当前步骤上下文,浏览器原生表单 POST,
|
||||
表单由 Spring Security `formLogin` 处理,框架维护因素、SecurityContext、会话轮换和退出。
|
||||
React 只替换默认登录 UI,不增加前端路由器、模板引擎或 Node 运行服务。
|
||||
|
||||
## AD 第一因素接入
|
||||
|
||||
真实入口为 `/signin`,默认关闭且要求 HTTPS。密码验证通过后显示 AD 身份与直接所属组,
|
||||
保存仅含 `FACTOR_PASSWORD` 的认证结果,停在等待 MFA 状态。待 MFA 页要求十分钟内的密码因素;
|
||||
其他应用入口暂时全部拒绝,不能凭密码因素接受 Hydra challenge。监控 Basic 认证使用独立无状态安全链。
|
||||
配置、组语义、HTTPS 与验收边界见 [AD 接入](docs/ad-login.md)。
|
||||
|
||||
@@ -71,3 +71,15 @@ graalvmNative {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Vite owns the HTML and hashed assets; only the controller can serve the page shell.
|
||||
// Build it with `npm ci && npm run build` in frontend/ before invoking Gradle.
|
||||
tasks.named('processResources') {
|
||||
inputs.files(fileTree('frontend/dist'))
|
||||
doFirst {
|
||||
if (!file('frontend/dist/index.html').exists()) {
|
||||
throw new GradleException('Missing UI build: run npm ci && npm run build in frontend/')
|
||||
}
|
||||
}
|
||||
from('frontend/dist') { into 'ui' }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# AD 第一因素接入
|
||||
|
||||
`/signin` 接收 AD 用户名(sAMAccountName)或本域 UPN,通过 Spring LDAP `ContextSource.getContext` 以用户身份执行 LDAPS bind,
|
||||
随后由 Spring Data LDAP 仓储复用这条已认证连接查询用户与组。
|
||||
不使用额外目录服务账号,不写入 AD,不复制 Authelia 的绑定密码。
|
||||
|
||||
领域仓储接口为 `UserRepository`,`User` 为领域模型。`VerifyPassword` 应用用例以
|
||||
try-with-resources 管理已认证用户仓储会话;基础设施的 `AdUserRepository` 通过
|
||||
`SimpleLdapRepository<AdUserEntry>`、`LdapTemplate`、ODM 实现读取与转换,关闭后不可继续查询。
|
||||
`AdUserEntry` 的 LDAP 注解不会进入领域对象。
|
||||
|
||||
成功后重定向到 `/signin/mfa`,显示目录账号、objectGUID、邮箱、直接所属组及组 DN。
|
||||
**这是密码因素验收页面,MFA 尚未接入,不是完整登录成功。** Spring Security 保存
|
||||
仅含 `FACTOR_PASSWORD` 的认证结果;其余应用请求使用 `denyAll`,不调用 Hydra,
|
||||
不替换现役 Go/Authelia/Gitea 登录链路。
|
||||
|
||||
## 目录和组语义
|
||||
|
||||
- AD 是身份和组权威。objectGUID 按 AD 混合字节序解析为标准 UUID,作为目录稳定键;
|
||||
不是已确定的 Hydra `sub`。切换前仍须处理现役 issuer/sub 哈希的主体连续性。
|
||||
- 从 `memberOf` 读取直接成员关系,保留原始 DN;CN 保留大小写,不添加 `ROLE_`,
|
||||
不把 Spring 的 `FACTOR_PASSWORD` 当作组。结果排序,不做应用专用组改写。
|
||||
- 此轮不展开嵌套组、不推导 primaryGroupID,也不宣称与 Authelia 的有效组集合完全一致。
|
||||
遇到 ranged memberOf 或不同 DN 同名 CN 拒绝映射,不静默丢组或合并不同主体。
|
||||
- AD bind 执行密码及账号状态检查;基础设施层将禁用、锁定、密码过期等 AD 子码转换为
|
||||
应用层认证失败原因,不向领域层泄露 LDAP/Spring 异常。
|
||||
搜索排除 computer 对象,只接受唯一用户条目和合法 objectGUID/sAMAccountName。
|
||||
- 邮箱作为目录属性展示,不声称 `email_verified=true`。
|
||||
|
||||
## 启用
|
||||
|
||||
`iam.ad.enabled=true` 时才装配登录 Controller 与浏览器安全链(含 formLogin)。
|
||||
未启用时入口由兜底安全链拒绝,匿名 GET 返回 401;不注册密码处理端点。
|
||||
|
||||
正常 JVM 构建:
|
||||
|
||||
```sh
|
||||
IAM_DOCKER_USE_SUDO=1 scripts/gradle-in-docker test bootJar
|
||||
```
|
||||
|
||||
Gradle 与 npm 缓存默认持久挂载,可用 `IAM_GRADLE_CACHE`、`IAM_NPM_CACHE` 指定目录。
|
||||
日常迭代不必每轮跑 Native;新增 AD/JNDI/TLS 路径的原生验收留到阶段性验证。
|
||||
|
||||
运行时配置(非秘密):
|
||||
|
||||
```yaml
|
||||
iam:
|
||||
ad:
|
||||
enabled: true
|
||||
url: ldaps://dc1.ad.ddupan.top:636
|
||||
domain: ad.ddupan.top
|
||||
base-dn: DC=ad,DC=ddupan,DC=top
|
||||
server:
|
||||
port: 18082
|
||||
ssl:
|
||||
enabled: true
|
||||
certificate: file:/run/iam/browser.crt
|
||||
certificate-private-key: file:/run/iam/browser.key
|
||||
servlet:
|
||||
session:
|
||||
cookie:
|
||||
secure: true
|
||||
same-site: lax
|
||||
```
|
||||
|
||||
证书与私钥使用外部受管文件,不加入仓库。开发验收可使用本机的 Tailscale HTTPS 域名
|
||||
及相应证书;用匹配证书的主机名打开,不能用 LAN IP 替代域名后跳过警告。
|
||||
部署与证书自动续期归 homelab-infra,此轮本地运行不是生产部署。
|
||||
|
||||
LDAPS 使用默认 JSSE 信任库并执行服务端域名校验。Samba 当前证书由 OpenBao 内部 CA
|
||||
签发,需把**公开 CA** 加入运行用 truststore,并通过 JVM 参数指定:
|
||||
|
||||
```sh
|
||||
java -Djavax.net.ssl.trustStore=/run/iam/truststore \
|
||||
-Djavax.net.ssl.trustStorePassword=changeit -jar iam-login.jar
|
||||
```
|
||||
|
||||
这里 truststore 仅含公开信任锚,口令不是目录密码。保留所需公共根证书;不得禁用
|
||||
LDAP endpoint identification 或用信任所有证书的 socket factory。连接/读取超时为 3/5 秒。
|
||||
AD 根范围查询可能返回 DomainDnsZones/ForestDnsZones 等分区 referral;配置为 ignore,
|
||||
由仓储的 LdapTemplate 忽略 partial result,不使用 throw 打断用户查询,也不 follow 转发用户凭据。
|
||||
|
||||
浏览器安全链通过 Spring Security `redirectToHttps` 将明文请求重定向至 HTTPS,
|
||||
重定向前不执行密码验证或退出。默认不信任转发头。若以后由代理终结 TLS,
|
||||
必须配合仅受信代理可达的后端网络和转发头配置,不能公开一个信任任意 forwarded header
|
||||
的 HTTP 端口。当前开发验收由应用直接终结 TLS。
|
||||
|
||||
## 状态与操作
|
||||
|
||||
React 只渲染登录页面与待 MFA 页面,原生表单 POST 由 Spring Security `formLogin`
|
||||
接收。`DirectoryAuthenticationProvider` 调用目录用例并返回不含密码的 principal 和
|
||||
带签发时间的 `FACTOR_PASSWORD`;目录组只保留在身份快照中,不映射为本服务权限。
|
||||
框架负责 CSRF、成功/失败跳转、SecurityContext 持久化、session ID 轮换以及 POST logout。
|
||||
`/signin/restart` 是框架 logout 地址;不再维护 LoginTransaction 或另一份浏览器认证状态。
|
||||
|
||||
待 MFA 页通过框架的 `validDuration` 要求密码因素在十分钟内完成,过期后需要重新认证。
|
||||
这不是完整登录会话的过期策略。MFA 与 Hydra 尚未实现,其余应用入口当前拒绝所有访问。
|
||||
`/actuator/**` 使用独立无状态 Basic 安全链,人类密码因素不能用于读取监控端点,
|
||||
监控账号也不能借 Basic 进入人类登录流程。
|
||||
|
||||
移除原来事务内的两秒提交间隔;它不是有效的账号/IP 限流。此 PoC 仍仅供受控
|
||||
LAN/Tailscale 验收,生产发布前需完善入口限流、审计、MFA、Hydra challenge 和恢复策略。
|
||||
页面禁止缓存,内联 JSON 转义 HTML 结束标记。错误页面只显示统一消息。
|
||||
|
||||
基础存活检查使用 `/actuator/health/liveness`。Boot 自动配置的 LDAP 健康项并未连接这里
|
||||
按用户 bind 创建的仓储连接,不能把该项当作此认证路径的可用性验证。
|
||||
|
||||
## 本轮验证边界
|
||||
|
||||
隔离测试使用真实 TLS、LDAP bind 和搜索,校验正确/错误密码、未知账号、AD 账号状态
|
||||
子码、GUID 字节序、组名、错误 TLS 主机名、CSRF、HTTPS、会话轮换、因素过期和密码成功后
|
||||
仍不能访问受保护应用入口。UnboundID 的 UPN bind 与 AD 子码由测试拦截器模拟,不能替代 Samba AD。
|
||||
测试证书、私钥与账号全为虚构夹具,不用于实际部署。
|
||||
|
||||
2026-09-27:Spring Security 重构通过 18 项 JVM 测试和 `bootJar` 构建,覆盖
|
||||
密码因素的保存与有效期、会话轮换、退出、未完成 MFA 的访问限制,以及监控安全链隔离。
|
||||
此前 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 页面,并反馈目录标识、邮箱与
|
||||
六个直接所属组的查询结果。该验收覆盖 Samba AD 第一因素与属性读取,不表示 MFA、
|
||||
嵌套组/主组等价性或 Hydra 登录已完成。Spring Security 重构后的真实人类复验仍待反馈。
|
||||
不在聊天、命令行或日志中传递人类密码。
|
||||
新增 AD 路径尚未进行 Native 测试,不能复用旧 UI 原型的 Native 结论。
|
||||
@@ -126,3 +126,6 @@ Prometheus 注册器中的 CPU 时间计数器并断言数值有效,避免后
|
||||
这是一次本地 smoke 测量,启动耗时含检查器轮询,RSS 不是峰值或负载预算,ELF 大小不等于
|
||||
运行镜像大小。未验证 AD、MFA、Hydra、目录就绪或 OTLP 后端数据查询,也尚未接入 CI。
|
||||
运行报告生成在 `build/reports/native-smoke/result.json`,不提交运行日志或构建产物。
|
||||
|
||||
手写 Native 补丁位于 `META-INF/native-image/top.ddupan.iam/iam-login-manual/`,
|
||||
与 Spring AOT 生成的 `iam-login/` 目录分开,避免 `bootJar` 中同名元数据冲突。
|
||||
|
||||
@@ -20,9 +20,15 @@ WebAuthn 集成;TOTP、恢复方式与已有 Authelia MFA 的迁移方式需
|
||||
- Hydra admin 保持内部访问,业务日志不得包含密码、MFA secret、token 或 challenge。
|
||||
- 原生二进制与隔离 Hydra 完成授权码链路,再验证现有 Gitea 账号及权限。
|
||||
|
||||
日常迭代以 JVM 测试为准,不要求每轮执行 Native 编译。Native 验证安排在阶段性验收
|
||||
或新增反射、JNDI、TLS 等兼容性风险时集中进行;记录尚未覆盖的新路径。
|
||||
|
||||
## Native 与监控
|
||||
|
||||
- CI 构建 Native 产物并对该产物执行集成测试;测试报告区分 JVM 与 Native。
|
||||
- 登录 Controller 与安全链使用 `@ConditionalOnProperty(iam.ad.enabled)`;AOT 在构建时
|
||||
决定 bean 是否存在。AD Native 产物必须在 AOT 阶段启用此属性,验证实际入口与兜底链,
|
||||
不能假设运行时修改属性会重新装配 bean。本轮只验证 JVM,尚未验收该 Native 路径。
|
||||
- 最终运行镜像无需 JRE,不允许以回退 JVM 的方式令 Native 验收通过。
|
||||
- LDAP、MFA、数据库、TLS、JSON 和 Hydra HTTP 客户端全部在 Native 中执行。
|
||||
- 纳入 Actuator、Micrometer Prometheus 与 OpenTelemetry/分布式追踪;实际发起请求后
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>登录 · IAM</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<noscript>本页使用 React 渲染页面,请启用 JavaScript。</noscript>
|
||||
<script id="login-context" type="application/json">
|
||||
__IAM_PAGE_CONTEXT__
|
||||
</script>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+1280
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "iam-login-ui",
|
||||
"private": true,
|
||||
"version": "0.0.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"watch": "vite build --watch",
|
||||
"test:browser": "playwright test"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "8.3.1",
|
||||
"typescript": "7.0.2",
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@playwright/test": "1.63.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "@playwright/test";
|
||||
export default defineConfig({
|
||||
testDir: "./tests",
|
||||
use: {
|
||||
baseURL: process.env.IAM_AD_URL,
|
||||
headless: true,
|
||||
},
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { readPageContext } from "./page-context";
|
||||
import { SignInPage } from "./pages/SignInPage";
|
||||
import "./style.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<SignInPage context={readPageContext()} />,
|
||||
);
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
:root {
|
||||
font-family: Inter, "Noto Sans SC", system-ui, sans-serif;
|
||||
color: #182826;
|
||||
background: #f3f5f1;
|
||||
font-synthesis: none;
|
||||
font-size: 16px;
|
||||
}
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
main {
|
||||
max-width: 520px;
|
||||
margin: 0 auto;
|
||||
padding: 40px 20px 28px;
|
||||
}
|
||||
header {
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
.brand {
|
||||
font-size: 32px;
|
||||
font-weight: 750;
|
||||
letter-spacing: -2px;
|
||||
color: #285448;
|
||||
text-decoration: none;
|
||||
}
|
||||
.brand > span:first-child {
|
||||
font-weight: 400;
|
||||
}
|
||||
.card {
|
||||
background: #fff;
|
||||
border: 1px solid #dce4dd;
|
||||
border-radius: 18px;
|
||||
padding: 36px;
|
||||
box-shadow: 0 12px 40px #173f2510;
|
||||
}
|
||||
.eyebrow {
|
||||
font-size: 12px;
|
||||
color: #60746a;
|
||||
letter-spacing: 2px;
|
||||
}
|
||||
h1 {
|
||||
font-size: 27px;
|
||||
letter-spacing: -0.5px;
|
||||
line-height: 1.35;
|
||||
margin: 0 0 12px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.intro {
|
||||
font-size: 14px;
|
||||
color: #60716a;
|
||||
line-height: 1.8;
|
||||
margin: 0 0 25px;
|
||||
}
|
||||
label {
|
||||
display: block;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
input:not([type="hidden"]) {
|
||||
display: block;
|
||||
width: 100%;
|
||||
border: 1px solid #bdccc1;
|
||||
border-radius: 8px;
|
||||
padding: 13px 14px;
|
||||
margin: 9px 0 22px;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
background: #fff;
|
||||
}
|
||||
input:focus {
|
||||
outline: 3px solid #a9cbbc;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
button {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.primary {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
background: #245b47;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
border-radius: 8px;
|
||||
padding: 13px;
|
||||
}
|
||||
.primary:hover {
|
||||
background: #194734;
|
||||
}
|
||||
.primary:disabled {
|
||||
opacity: 0.65;
|
||||
cursor: wait;
|
||||
}
|
||||
.error {
|
||||
color: #9e302b;
|
||||
background: #fff0ed;
|
||||
padding: 12px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
footer {
|
||||
text-align: center;
|
||||
color: #7c887e;
|
||||
font-size: 12px;
|
||||
margin-top: 28px;
|
||||
}
|
||||
a:focus-visible,
|
||||
button:focus-visible {
|
||||
outline: 3px solid #a9cbbc;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
main {
|
||||
padding-top: 24px;
|
||||
}
|
||||
header {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
.card {
|
||||
padding: 26px 22px;
|
||||
}
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
background: #14221c;
|
||||
color: #edf4ee;
|
||||
}
|
||||
.card {
|
||||
background: #1e3027;
|
||||
border-color: #344b3d;
|
||||
}
|
||||
.brand {
|
||||
color: #b9ddc8;
|
||||
}
|
||||
.intro,
|
||||
.eyebrow {
|
||||
color: #acbfb2;
|
||||
}
|
||||
input:not([type="hidden"]) {
|
||||
background: #18271f;
|
||||
border-color: #526657;
|
||||
}
|
||||
.error {
|
||||
background: #492b29;
|
||||
color: #ffc3b9;
|
||||
}
|
||||
}
|
||||
|
||||
.directory-result { overflow-wrap: anywhere; }
|
||||
.directory-result dd { margin: 0 0 1rem; }
|
||||
.directory-result h2 { font-size: 1rem; }
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,31 @@
|
||||
import { test, expect } from "@playwright/test";
|
||||
|
||||
// Explicit opt-in: never submit synthetic credentials to an arbitrary configured directory.
|
||||
// The external-domain username below must be rejected before any LDAP bind.
|
||||
test("AD HTTPS page uses native POST and keeps failed credentials out of the response", async ({ page, context }) => {
|
||||
test.skip(!process.env.IAM_AD_URL, "Set IAM_AD_URL to the HTTPS first-factor PoC");
|
||||
const url = new URL("/signin", process.env.IAM_AD_URL!);
|
||||
expect(url.protocol).toBe("https:");
|
||||
const requests: { method: string; type: string; path: string }[] = [];
|
||||
page.on("request", request => requests.push({
|
||||
method: request.method(), type: request.resourceType(), path: new URL(request.url()).pathname,
|
||||
}));
|
||||
await page.goto(url.toString());
|
||||
await expect(page.getByRole("heading", { name: "登录你的账号" })).toBeVisible();
|
||||
await expect(page.locator("form")).toHaveAttribute("method", "post");
|
||||
await expect(page.locator("input[name=_csrf]")).toHaveCount(1);
|
||||
const session = (await context.cookies()).find(cookie => cookie.name === "JSESSIONID");
|
||||
expect(session).toMatchObject({ secure: true, httpOnly: true, sameSite: "Lax" });
|
||||
await page.getByLabel("用户名", { exact: true }).fill("[email protected]");
|
||||
await page.getByLabel("密码", { exact: true }).fill("synthetic-ui-check");
|
||||
await page.getByRole("button", { name: "继续", exact: true }).click();
|
||||
await expect(page.getByRole("alert")).toContainText("无法验证账号");
|
||||
await expect(page.getByLabel("密码", { exact: true })).toHaveValue("");
|
||||
expect(await page.content()).not.toContain("synthetic-ui-check");
|
||||
expect(requests.filter(request => request.method === "POST")).toEqual([
|
||||
{ method: "POST", type: "document", path: "/signin/password" },
|
||||
]);
|
||||
expect(requests.filter(request => ["fetch", "xhr"].includes(request.type))).toHaveLength(0);
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth)).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
export default defineConfig({
|
||||
base: "/",
|
||||
build: { outDir: "dist", emptyOutDir: true },
|
||||
});
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
repo_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
|
||||
cache_dir=${IAM_NPM_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/iam-login/npm}
|
||||
mkdir -p -- "$cache_dir"
|
||||
cache_dir=$(cd -- "$cache_dir" && pwd)
|
||||
docker_cmd=(docker)
|
||||
if [[ ${IAM_DOCKER_USE_SUDO:-0} == 1 ]]; then
|
||||
docker_cmd=(sudo -n docker)
|
||||
fi
|
||||
exec "${docker_cmd[@]}" run --rm --network host \
|
||||
--cpus 2 --memory 1g --user "$(id -u):$(id -g)" \
|
||||
-e HOME=/npm -e npm_config_cache=/npm \
|
||||
-v "$cache_dir:/npm" -v "$repo_root:/workspace" \
|
||||
-w /workspace/frontend node@sha256:d8e448a56fc63242f70026718378bd4b00f8c82e78d20eefb199224a4d8e33d8 \
|
||||
sh -c 'npm ci --no-audit --no-fund && npm run build'
|
||||
@@ -13,6 +13,8 @@ if (($# == 0)); then
|
||||
set -- test
|
||||
fi
|
||||
|
||||
"$repo_root/scripts/frontend-in-docker"
|
||||
|
||||
# Linux host networking is needed for Testcontainers' published ports.
|
||||
exec "${docker_cmd[@]}" run --rm --network host \
|
||||
--cpus "${IAM_BUILD_CPUS:-4}" --memory "${IAM_BUILD_MEMORY:-8g}" \
|
||||
|
||||
@@ -59,6 +59,8 @@ def main():
|
||||
|
||||
def request(path, authenticated=False):
|
||||
headers = {'Accept': 'text/plain' if authenticated and path == '/actuator/prometheus' else 'application/json'}
|
||||
if path == '/signin':
|
||||
headers['Accept'] = 'text/html'
|
||||
if authenticated:
|
||||
headers['Authorization'] = f'Basic {basic}'
|
||||
req = urllib.request.Request(base_url + path, headers=headers)
|
||||
@@ -78,6 +80,7 @@ def main():
|
||||
ready_seconds = time.monotonic() - started
|
||||
assert request('/actuator/prometheus')[0] == 401, 'Anonymous metrics must be rejected'
|
||||
assert request('/')[0] == 401, 'Anonymous application access must be rejected'
|
||||
assert request('/signin')[0] == 401, '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):
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package top.ddupan.iam.login.authentication.application;
|
||||
|
||||
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;
|
||||
import top.ddupan.iam.login.authentication.domain.User;
|
||||
|
||||
/** Resolves the user through the same authenticated directory connection. */
|
||||
public final class VerifyPassword {
|
||||
private final PasswordAuthenticator authenticator;
|
||||
|
||||
public VerifyPassword(PasswordAuthenticator authenticator) {
|
||||
this.authenticator = authenticator;
|
||||
}
|
||||
|
||||
public User verify(String username, String password) {
|
||||
try (var session = authenticator.authenticate(username, password)) {
|
||||
return session.users().findByLoginName(session.loginName())
|
||||
.orElseThrow(() -> new PasswordVerificationException(Reason.REJECTED));
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
@@ -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();
|
||||
}
|
||||
+6
@@ -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);
|
||||
}
|
||||
+14
@@ -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,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"); }
|
||||
}
|
||||
}
|
||||
+27
@@ -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);
|
||||
}
|
||||
}
|
||||
+91
@@ -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;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package top.ddupan.iam.login.authentication.infrastructure.ad;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties("iam.ad")
|
||||
public record AdProperties(boolean enabled, String url, String domain, String baseDn) {}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
+82
@@ -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(); }
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package top.ddupan.iam.login.authentication.infrastructure.security;
|
||||
|
||||
import java.util.List;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.authentication.InternalAuthenticationServiceException;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.authority.FactorGrantedAuthority;
|
||||
import top.ddupan.iam.login.authentication.application.VerifyPassword;
|
||||
import top.ddupan.iam.login.authentication.application.port.PasswordVerificationException;
|
||||
import top.ddupan.iam.login.authentication.domain.UserRepository;
|
||||
|
||||
/** Bridges directory authentication into Spring Security's form-login lifecycle. */
|
||||
public final class DirectoryAuthenticationProvider implements AuthenticationProvider {
|
||||
private final VerifyPassword passwords;
|
||||
|
||||
public DirectoryAuthenticationProvider(VerifyPassword passwords) {
|
||||
this.passwords = passwords;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(Authentication request) {
|
||||
try {
|
||||
var user = passwords.verify(request.getName(),
|
||||
request.getCredentials() instanceof String password ? password : null);
|
||||
// Directory groups remain profile data, not local application authorities.
|
||||
return UsernamePasswordAuthenticationToken.authenticated(new DirectoryPrincipal(user), null,
|
||||
List.of(FactorGrantedAuthority.fromAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY)));
|
||||
} catch (PasswordVerificationException ex) {
|
||||
if (ex.reason() == PasswordVerificationException.Reason.UNAVAILABLE) {
|
||||
throw new InternalAuthenticationServiceException("Directory unavailable");
|
||||
}
|
||||
throw new BadCredentialsException("Unable to verify credentials");
|
||||
} catch (UserRepository.AccessFailure ex) {
|
||||
throw new InternalAuthenticationServiceException("Directory unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> authentication) {
|
||||
return UsernamePasswordAuthenticationToken.class.equals(authentication);
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.ddupan.iam.login.authentication.infrastructure.security;
|
||||
|
||||
import org.springframework.security.core.AuthenticatedPrincipal;
|
||||
import top.ddupan.iam.login.authentication.domain.User;
|
||||
|
||||
/** An immutable directory snapshot; never contains credentials or connections. */
|
||||
public record DirectoryPrincipal(User user) implements AuthenticatedPrincipal {
|
||||
@Override
|
||||
public String getName() {
|
||||
return user.id().authority() + ":" + user.id().value();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package top.ddupan.iam.login.authentication.interfaces.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Shared HTML shell; the page context is data, never executable JavaScript. */
|
||||
@Component
|
||||
public class PageRenderer {
|
||||
private static final String SLOT = "__IAM_PAGE_CONTEXT__";
|
||||
private final String shell;
|
||||
private final JsonMapper json = JsonMapper.builder().build();
|
||||
|
||||
public PageRenderer() throws IOException {
|
||||
shell = new ClassPathResource("ui/index.html").getContentAsString(StandardCharsets.UTF_8);
|
||||
if (shell.indexOf(SLOT) < 0 || shell.indexOf(SLOT) != shell.lastIndexOf(SLOT)) {
|
||||
throw new IllegalStateException("Expected exactly one UI context slot");
|
||||
}
|
||||
}
|
||||
|
||||
public ResponseEntity<String> render(Object context) {
|
||||
String safe = json.writeValueAsString(context).replace("<", "\\u003c")
|
||||
.replace(">", "\\u003e").replace("&", "\\u0026")
|
||||
.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029");
|
||||
return ResponseEntity.ok().header("Cache-Control", "no-store")
|
||||
.contentType(new MediaType(MediaType.TEXT_HTML, StandardCharsets.UTF_8)).body(shell.replace(SLOT, safe));
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package top.ddupan.iam.login.authentication.interfaces.web;
|
||||
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.security.web.csrf.CsrfToken;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.ddupan.iam.login.authentication.domain.User.GroupMembership;
|
||||
import top.ddupan.iam.login.authentication.infrastructure.security.DirectoryPrincipal;
|
||||
|
||||
/** Renders Spring Security's login pages; form processing belongs to the security filters. */
|
||||
@RestController
|
||||
@ConditionalOnProperty(prefix = "iam.ad", name = "enabled", havingValue = "true")
|
||||
public class SignInController {
|
||||
private final PageRenderer renderer;
|
||||
|
||||
public SignInController(PageRenderer renderer) {
|
||||
this.renderer = renderer;
|
||||
}
|
||||
|
||||
@GetMapping(value = "/signin", produces = MediaType.TEXT_HTML_VALUE)
|
||||
ResponseEntity<String> page(@RequestParam(required = false) String error, CsrfToken csrf) {
|
||||
return renderer.render(Map.of("step", "password", "name", "",
|
||||
"error", error == null ? "" : "无法验证账号,请检查凭据与账号状态,或稍后重试。",
|
||||
"action", "/signin/password", "csrf", csrf(csrf)));
|
||||
}
|
||||
|
||||
@GetMapping(value = "/signin/mfa", produces = MediaType.TEXT_HTML_VALUE)
|
||||
ResponseEntity<String> pending(@AuthenticationPrincipal DirectoryPrincipal principal, CsrfToken csrf) {
|
||||
var user = principal.user();
|
||||
return renderer.render(Map.of("step", "mfa-pending", "name", user.displayName(),
|
||||
"error", "", "action", "/signin/restart", "csrf", csrf(csrf),
|
||||
"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())));
|
||||
}
|
||||
|
||||
private static Map<String, String> csrf(CsrfToken token) {
|
||||
return Map.of("name", token.getParameterName(), "value", token.getToken());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package top.ddupan.iam.login.configuration;
|
||||
|
||||
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.VerifyPassword;
|
||||
import top.ddupan.iam.login.authentication.application.port.PasswordAuthenticator;
|
||||
|
||||
/** Composition root: dependencies point inward, framework wiring stays outside the model. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@RegisterReflectionForBinding(AdUserEntry.class)
|
||||
@ImportRuntimeHints(AuthenticationConfiguration.DirectoryHints.class)
|
||||
class AuthenticationConfiguration {
|
||||
@Bean
|
||||
VerifyPassword verifyPassword(PasswordAuthenticator authenticator) {
|
||||
return new VerifyPassword(authenticator);
|
||||
}
|
||||
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,84 @@
|
||||
package top.ddupan.iam.login.configuration;
|
||||
|
||||
import java.time.Duration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.ProviderManager;
|
||||
import org.springframework.security.authorization.AuthorizationManagerFactories;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.authorization.EnableMultiFactorAuthentication;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
|
||||
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
|
||||
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
|
||||
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
|
||||
import top.ddupan.iam.login.authentication.application.VerifyPassword;
|
||||
import top.ddupan.iam.login.authentication.infrastructure.security.DirectoryAuthenticationProvider;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableMultiFactorAuthentication(authorities = {})
|
||||
class SecurityConfiguration {
|
||||
// Operational Basic authentication is isolated from human first-factor authentication.
|
||||
@Bean
|
||||
@Order(1)
|
||||
SecurityFilterChain management(HttpSecurity http) throws Exception {
|
||||
return http.securityMatcher("/actuator/**")
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/actuator/health/**").permitAll()
|
||||
.anyRequest().authenticated())
|
||||
.securityContext(context -> context.securityContextRepository(
|
||||
new org.springframework.security.web.context.NullSecurityContextRepository()))
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(
|
||||
org.springframework.security.config.http.SessionCreationPolicy.STATELESS))
|
||||
.httpBasic(Customizer.withDefaults())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(2)
|
||||
@ConditionalOnProperty(prefix = "iam.ad", name = "enabled", havingValue = "true")
|
||||
SecurityFilterChain browser(HttpSecurity http, VerifyPassword passwords) throws Exception {
|
||||
var passwordFactor = AuthorizationManagerFactories.<RequestAuthorizationContext>multiFactor()
|
||||
.requireFactor(factor -> factor.passwordAuthority().validDuration(Duration.ofMinutes(10)))
|
||||
.build();
|
||||
return http.securityMatcher("/signin", "/signin/**", "/assets/**")
|
||||
.redirectToHttps(Customizer.withDefaults())
|
||||
.authenticationManager(new ProviderManager(new DirectoryAuthenticationProvider(passwords)))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/error", "/signin", "/signin/password", "/assets/**").permitAll()
|
||||
.requestMatchers("/signin/mfa").access(passwordFactor.authenticated())
|
||||
// No complete MFA or Hydra acceptance exists yet. Fail closed until those are implemented.
|
||||
.anyRequest().denyAll())
|
||||
.formLogin(form -> form.loginPage("/signin").loginProcessingUrl("/signin/password")
|
||||
.defaultSuccessUrl("/signin/mfa", true).failureUrl("/signin?error"))
|
||||
.logout(logout -> logout.logoutUrl("/signin/restart").logoutSuccessUrl("/signin"))
|
||||
.exceptionHandling(exceptions -> exceptions
|
||||
.defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/signin"),
|
||||
PathPatternRequestMatcher.withDefaults().matcher("/signin/**"))
|
||||
.defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
|
||||
org.springframework.security.web.util.matcher.AnyRequestMatcher.INSTANCE))
|
||||
.requestCache(cache -> cache.disable())
|
||||
.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();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(3)
|
||||
SecurityFilterChain fallback(HttpSecurity http) throws Exception {
|
||||
return http.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/error").permitAll()
|
||||
.anyRequest().denyAll())
|
||||
.exceptionHandling(exceptions -> exceptions
|
||||
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
|
||||
.requestCache(cache -> cache.disable())
|
||||
.logout(logout -> logout.disable())
|
||||
.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/**");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,42 +10,58 @@ import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.OtlpLog
|
||||
import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.Transport;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.testcontainers.grafana.LgtmStackContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.utility.DockerImageName;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
@AutoConfigureMetrics
|
||||
@AutoConfigureTracing
|
||||
@Testcontainers
|
||||
class IamLoginApplicationTests {
|
||||
|
||||
// Field-based service connections are recreated by the test context in AOT mode.
|
||||
@Container
|
||||
@ServiceConnection
|
||||
static final LgtmStackContainer grafanaLgtm = new LgtmStackContainer(
|
||||
DockerImageName.parse(TestcontainersConfiguration.LGTM_IMAGE));
|
||||
// Field-based service connections are recreated by the test context in AOT mode.
|
||||
@Container
|
||||
@ServiceConnection
|
||||
static final LgtmStackContainer grafanaLgtm = new LgtmStackContainer(
|
||||
DockerImageName.parse(TestcontainersConfiguration.LGTM_IMAGE));
|
||||
|
||||
@Autowired
|
||||
OtlpLoggingConnectionDetails loggingConnectionDetails;
|
||||
@Autowired
|
||||
OtlpLoggingConnectionDetails loggingConnectionDetails;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("prometheusMeterRegistry")
|
||||
MeterRegistry prometheus;
|
||||
@Autowired
|
||||
@Qualifier("prometheusMeterRegistry")
|
||||
MeterRegistry prometheus;
|
||||
|
||||
@Test
|
||||
void processCpuTimeCanBeRead() {
|
||||
assertThat(prometheus.get("process.cpu.time").functionCounter().count()).isFinite().isNotNegative();
|
||||
}
|
||||
@Autowired
|
||||
MockMvc mvc;
|
||||
|
||||
@Test
|
||||
void loggingConnectionUsesRunningContainer() {
|
||||
assertThat(grafanaLgtm.isRunning()).isTrue();
|
||||
assertThat(loggingConnectionDetails.getUrl(Transport.HTTP))
|
||||
.isEqualTo(grafanaLgtm.getOtlpHttpUrl() + "/v1/logs");
|
||||
}
|
||||
@Test
|
||||
void signInIsDisabledUntilDirectoryIsConfigured() throws Exception {
|
||||
mvc.perform(get("/signin").secure(true)).andExpect(status().isUnauthorized());
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/signin/password")
|
||||
.secure(true).with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf()))
|
||||
.andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void processCpuTimeCanBeRead() {
|
||||
assertThat(prometheus.get("process.cpu.time").functionCounter().count()).isFinite().isNotNegative();
|
||||
}
|
||||
|
||||
@Test
|
||||
void loggingConnectionUsesRunningContainer() {
|
||||
assertThat(grafanaLgtm.isRunning()).isTrue();
|
||||
assertThat(loggingConnectionDetails.getUrl(Transport.HTTP))
|
||||
.isEqualTo(grafanaLgtm.getOtlpHttpUrl() + "/v1/logs");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package top.ddupan.iam.login.authentication.application;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
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.User;
|
||||
import top.ddupan.iam.login.authentication.domain.UserRepository;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class VerifyPasswordTests {
|
||||
static final User ALICE = new User(new User.UserId("directory", "alice-id"), "alice", "Alice", "", List.of());
|
||||
|
||||
@Test
|
||||
void readsTheBoundUserAndClosesTheConnection() {
|
||||
var scope = new Scope(name -> {
|
||||
assertThat(name).isEqualTo("alice@directory");
|
||||
return Optional.of(ALICE);
|
||||
});
|
||||
assertThat(new VerifyPassword((username, password) -> scope).verify("alice", "secret")).isEqualTo(ALICE);
|
||||
assertThat(scope.closed).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingUserClosesTheConnectionAndRejectsAuthentication() {
|
||||
var scope = new Scope(name -> Optional.empty());
|
||||
assertThatThrownBy(() -> new VerifyPassword((u, p) -> scope).verify("alice", "secret"))
|
||||
.isInstanceOf(PasswordVerificationException.class);
|
||||
assertThat(scope.closed).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void repositoryFailureStillClosesTheConnection() {
|
||||
var scope = new Scope(name -> { throw new UserRepository.AccessFailure(); });
|
||||
assertThatThrownBy(() -> new VerifyPassword((u, p) -> scope).verify("alice", "secret"))
|
||||
.isInstanceOf(UserRepository.AccessFailure.class);
|
||||
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; }
|
||||
}
|
||||
}
|
||||
+79
@@ -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));
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
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 java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.FactorGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
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",
|
||||
"management.otlp.metrics.export.enabled=false", "spring.security.user.name=fixture-monitor", "spring.security.user.password=fixture-monitor-password"})
|
||||
@AutoConfigureMockMvc
|
||||
@org.springframework.boot.micrometer.metrics.test.autoconfigure.AutoConfigureMetrics
|
||||
@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(redirectedUrl("https://localhost/signin"));
|
||||
mvc.perform(get("/signin/mfa").with(https())).andExpect(redirectedUrl("/signin"));
|
||||
mvc.perform(post("/signin/password").with(https()).param("username", "alice")
|
||||
.param("password", "fixture-password")).andExpect(status().isForbidden());
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulPasswordRotatesSessionAndStopsBeforeMfa() throws Exception {
|
||||
var session = new MockHttpSession();
|
||||
mvc.perform(get("/signin").with(https()).session(session)).andExpect(status().isOk());
|
||||
String oldId = session.getId();
|
||||
mvc.perform(post("/signin/password").with(https()).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").with(https()).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()");
|
||||
var authentication = ((SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT")).getAuthentication();
|
||||
assertThat(authentication.isAuthenticated()).isTrue();
|
||||
assertThat(authentication.getCredentials()).isNull();
|
||||
assertThat(authentication.getAuthorities()).extracting("authority").containsExactly("FACTOR_PASSWORD");
|
||||
mvc.perform(get("/").with(https()).session(session).accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isForbidden());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedPasswordDoesNotRetainIdentityAndRestartInvalidatesSession() throws Exception {
|
||||
var session = new MockHttpSession();
|
||||
mvc.perform(get("/signin").with(https()).session(session));
|
||||
mvc.perform(post("/signin/password").with(https()).session(session).with(csrf())
|
||||
.param("username", "alice").param("password", "wrong"))
|
||||
.andExpect(redirectedUrl("/signin?error"));
|
||||
assertThat(session.getAttribute("SPRING_SECURITY_CONTEXT")).isNull();
|
||||
mvc.perform(get("/signin").with(https()).param("error", "").session(session))
|
||||
.andExpect(content().string(org.hamcrest.Matchers.containsString("无法验证账号")));
|
||||
mvc.perform(post("/signin/restart").with(https()).session(session).with(csrf()))
|
||||
.andExpect(redirectedUrl("/signin"));
|
||||
assertThat(session.isInvalid()).isTrue();
|
||||
}
|
||||
@Test
|
||||
void plaintextPasswordPostCannotReachDirectory() throws Exception {
|
||||
int before = Directory.INSTANCE.binds.get();
|
||||
mvc.perform(post("/signin/password").with(csrf()).param("username", "alice")
|
||||
.param("password", "fixture-password")).andExpect(redirectedUrl("https://localhost/signin/password"));
|
||||
assertThat(Directory.INSTANCE.binds.get()).isEqualTo(before);
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredPasswordFactorCannotOpenPendingPage() throws Exception {
|
||||
var session = login();
|
||||
var context = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
|
||||
var previous = context.getAuthentication();
|
||||
context.setAuthentication(UsernamePasswordAuthenticationToken.authenticated(previous.getPrincipal(), null,
|
||||
List.of(FactorGrantedAuthority.withAuthority(FactorGrantedAuthority.PASSWORD_AUTHORITY)
|
||||
.issuedAt(Instant.now().minusSeconds(601)).build())));
|
||||
mvc.perform(get("/signin/mfa").with(https()).session(session))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
}
|
||||
|
||||
@Test
|
||||
void directorySessionCannotScrapeManagementAndLogoutClearsAuthentication() throws Exception {
|
||||
var session = login();
|
||||
mvc.perform(get("/actuator/prometheus").with(https()).session(session))
|
||||
.andExpect(status().isUnauthorized());
|
||||
mvc.perform(post("/signin/restart").session(session).with(csrf()))
|
||||
.andExpect(redirectedUrl("https://localhost/signin/restart"));
|
||||
assertThat(session.isInvalid()).isFalse();
|
||||
mvc.perform(post("/signin/restart").with(https()).session(session))
|
||||
.andExpect(status().isForbidden());
|
||||
mvc.perform(post("/signin/restart").with(https()).session(session).with(csrf()))
|
||||
.andExpect(redirectedUrl("/signin"));
|
||||
assertThat(session.isInvalid()).isTrue();
|
||||
mvc.perform(get("/signin/mfa").with(https())).andExpect(status().is3xxRedirection());
|
||||
}
|
||||
|
||||
@Test
|
||||
void managementBasicCredentialsCannotAuthenticateBrowserLogin() throws Exception {
|
||||
mvc.perform(get("/actuator/prometheus").with(https()).with(
|
||||
org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors
|
||||
.httpBasic("fixture-monitor", "fixture-monitor-password")))
|
||||
.andExpect(status().isOk());
|
||||
mvc.perform(get("/signin/mfa").with(https()).with(
|
||||
org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors
|
||||
.httpBasic("fixture-monitor", "fixture-monitor-password")))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
}
|
||||
|
||||
private static org.springframework.test.web.servlet.request.RequestPostProcessor https() {
|
||||
return request -> {
|
||||
request.setScheme("https");
|
||||
request.setSecure(true);
|
||||
request.setServerPort(443);
|
||||
return request;
|
||||
};
|
||||
}
|
||||
|
||||
private MockHttpSession login() throws Exception {
|
||||
var session = new MockHttpSession();
|
||||
mvc.perform(post("/signin/password").with(https()).session(session).with(csrf())
|
||||
.param("username", "alice").param("password", "fixture-password"))
|
||||
.andExpect(redirectedUrl("/signin/mfa"));
|
||||
return session;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
fixture.p12 是仅用于隔离 LDAPS 测试的自签名证书和测试私钥,口令为 fixture-only。
|
||||
仅信任 localhost,不能用于生产。测试账户和密码都是虚构数据。
|
||||
测试服务仅绑定 127.0.0.1;JVM/Native 均执行真实 TLS、bind 和搜索,但 AD 的 UPN bind
|
||||
与禁用/锁定/密码过期子码由拦截器模拟,不代替 Samba AD 人类验收。
|
||||
Binary file not shown.
Reference in New Issue
Block a user