diff --git a/AGENTS.md b/AGENTS.md index 532628c..b27fdf1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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、生产配置秘密或包含上述内容的测试输出。 diff --git a/README.md b/README.md index a41f2f3..cb074d6 100644 --- a/README.md +++ b/README.md @@ -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 第一因素接入 diff --git a/build.gradle b/build.gradle index ad43c2b..2eace16 100644 --- a/build.gradle +++ b/build.gradle @@ -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' diff --git a/docs/ad-login.md b/docs/ad-login.md index a6e35cc..37771f9 100644 --- a/docs/ad-login.md +++ b/docs/ad-login.md @@ -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`、`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 结论。 diff --git a/docs/browser-preview.md b/docs/browser-preview.md deleted file mode 100644 index 1382899..0000000 --- a/docs/browser-preview.md +++ /dev/null @@ -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' -``` - -访问 。填写称呼,尝试错误演示码,再用 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 行分隔符,避免 `` 逃逸; - 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 和人类验收不在这些结果范围内。 diff --git a/docs/images/browser-preview.png b/docs/images/browser-preview.png deleted file mode 100644 index 29f6957..0000000 Binary files a/docs/images/browser-preview.png and /dev/null differ diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 58ec8c4..586bad4 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -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, }, }); diff --git a/frontend/src/components/SubmitForm.tsx b/frontend/src/components/SubmitForm.tsx new file mode 100644 index 0000000..b5eee3a --- /dev/null +++ b/frontend/src/components/SubmitForm.tsx @@ -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 ( +
setPending(true)} aria-busy={pending}> + + {children} + +
+ ); +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index af38606..0125aff 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -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 ( -
setPending(true)} - aria-busy={pending} - > - - {children} - -
- ); -} - -function App() { - useLayoutEffect(() => { performance.mark("iam-page-ready"); }, []); - const [showHelp, setShowHelp] = useState(false); - return ( -
-
- - iam - 预览 - -
-
-
登录交互原型
-
    - {(["identity", "verification", "complete"] as const).map( - (step, i) => ( -
  1. - {i + 1} - {["填写称呼", "模拟验证", "完成"][i]} -
  2. - ), - )} -
- {context.step === "identity" && ( - <> -

从这里开始

-

- 体验一次完整的页面切换。先告诉我们怎么称呼你。 -

- - )} - {context.step === "verification" && ( - <> -

你好,{context.name}

-

- 这是第二步页面。输入演示码 123456{" "} - 继续,也可以试试输入错误的演示码。 -

- - )} - {context.step === "complete" && ( - <> - -

体验完成

-

- {context.name} - ,你已走完页面预览。这没有建立登录身份,也没有向任何应用授权。 -

- - )} - {context.error && ( -

- {context.error} -

- )} -
- {context.step === "identity" && ( - - )} - {context.step === "verification" && ( - - )} -
- {context.step === "verification" && ( - - 返回上一步 - - )} -
- - {showHelp && ( -

不是。这里仅演示页面交互,请勿输入真实密码或 MFA 验证码。

- )} -
-
-
独立 IAM · 页面体验预览
-
- ); -} - -function SignIn() { - useLayoutEffect(() => { performance.mark("iam-page-ready"); }, []); - const identity = context.identity; - return
-
iam
-
-
AD 登录验证
-

{context.step === "password" ? "登录你的账号" : "密码已验证,等待 MFA"}

-

{context.step === "password" - ? "使用 AD 用户名或完整 UPN 登录。" - : `${context.name},目录验证成功。第二因素尚未接入,本次没有完成登录或向应用授权。`}

- {context.error &&

{context.error}

} - {identity &&
-
账号
{identity.username}
-
目录标识
{identity.objectGuid}
-
邮箱
{identity.email || "未设置"}
-

直接所属组

- {identity.groups.length ?
    {identity.groups.map(group =>
  • {group}
  • )}
:

没有直接所属组。

} -
组 DN
    {identity.groupDns.map(dn =>
  • {dn}
  • )}
-

当前仅读取 memberOf,不展开嵌套组,也不包含主组。

-
} -
{context.step === "password" && <> - - - }
-
-
独立 IAM · AD 接入验证
-
; -} - createRoot(document.getElementById("root")!).render( - context.step === "password" || context.step === "mfa-pending" ? : , + , ); diff --git a/frontend/src/page-context.ts b/frontend/src/page-context.ts new file mode 100644 index 0000000..70a0614 --- /dev/null +++ b/frontend/src/page-context.ts @@ -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; +} diff --git a/frontend/src/pages/SignInPage.tsx b/frontend/src/pages/SignInPage.tsx new file mode 100644 index 0000000..f565cdd --- /dev/null +++ b/frontend/src/pages/SignInPage.tsx @@ -0,0 +1,54 @@ +import { SubmitForm } from "../components/SubmitForm"; +import type { SignInContext } from "../page-context"; + +export function SignInPage({ context }: { context: SignInContext }) { + return ( +
+
iam
+
+
AD 登录验证
+

+ {context.step === "password" ? "登录你的账号" : "密码已验证,等待 MFA"} +

+

+ {context.step === "password" + ? "使用 AD 用户名或完整 UPN 登录。" + : `${context.name},目录验证成功。第二因素尚未接入,本次没有完成登录或向应用授权。`} +

+ {context.error &&

{context.error}

} + {context.step === "mfa-pending" && ( +
+
+
账号
{context.identity.username}
+
目录标识
{context.identity.subjectId}
+
邮箱
{context.identity.email || "未设置"}
+
+

直接所属组

+ {context.identity.groups.length + ?
    {context.identity.groups.map(group =>
  • {group}
  • )}
+ :

没有直接所属组。

} +
+ 组 DN +
    {context.identity.groupDns.map(dn =>
  • {dn}
  • )}
+
+

当前仅读取 memberOf,不展开嵌套组,也不包含主组。

+
+ )} + + {context.step === "password" && <> + + + } + +
+
独立 IAM · AD 接入验证
+
+ ); +} diff --git a/frontend/src/style.css b/frontend/src/style.css index 3318073..8cb080e 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -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; diff --git a/frontend/tests/preview.spec.ts b/frontend/tests/preview.spec.ts deleted file mode 100644 index 7295140..0000000 --- a/frontend/tests/preview.spec.ts +++ /dev/null @@ -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 = ""; - 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" }); -}); diff --git a/scripts/native-smoke.py b/scripts/native-smoke.py index 0d7ad00..c51c2ad 100755 --- a/scripts/native-smoke.py +++ b/scripts/native-smoke.py @@ -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): diff --git a/src/main/java/top/ddupan/iam/login/ad/AdPasswordVerifier.java b/src/main/java/top/ddupan/iam/login/ad/AdPasswordVerifier.java deleted file mode 100644 index 235ab76..0000000 --- a/src/main/java/top/ddupan/iam/login/ad/AdPasswordVerifier.java +++ /dev/null @@ -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 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 dns = membership == null ? List.of() : Arrays.stream(membership).sorted().toList(); - var groups = new java.util.TreeSet(); - 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(); - } -} diff --git a/src/main/java/top/ddupan/iam/login/ad/DirectoryIdentity.java b/src/main/java/top/ddupan/iam/login/ad/DirectoryIdentity.java deleted file mode 100644 index 28cf372..0000000 --- a/src/main/java/top/ddupan/iam/login/ad/DirectoryIdentity.java +++ /dev/null @@ -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 groups, List groupDns) { - public DirectoryIdentity { - groups = List.copyOf(groups); - groupDns = List.copyOf(groupDns); - } -} diff --git a/src/main/java/top/ddupan/iam/login/authentication/application/SignInService.java b/src/main/java/top/ddupan/iam/login/authentication/application/SignInService.java new file mode 100644 index 0000000..c3985e6 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/application/SignInService.java @@ -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; + } + } +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/application/port/AuthenticatedUserSession.java b/src/main/java/top/ddupan/iam/login/authentication/application/port/AuthenticatedUserSession.java new file mode 100644 index 0000000..bc6aee3 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/application/port/AuthenticatedUserSession.java @@ -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(); +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/application/port/PasswordAuthenticator.java b/src/main/java/top/ddupan/iam/login/authentication/application/port/PasswordAuthenticator.java new file mode 100644 index 0000000..63ee91e --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/application/port/PasswordAuthenticator.java @@ -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); +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/application/port/PasswordVerificationException.java b/src/main/java/top/ddupan/iam/login/authentication/application/port/PasswordVerificationException.java new file mode 100644 index 0000000..873e36d --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/application/port/PasswordVerificationException.java @@ -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; } +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/domain/LoginTransaction.java b/src/main/java/top/ddupan/iam/login/authentication/domain/LoginTransaction.java new file mode 100644 index 0000000..5048b81 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/domain/LoginTransaction.java @@ -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; + } +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/domain/User.java b/src/main/java/top/ddupan/iam/login/authentication/domain/User.java new file mode 100644 index 0000000..73cd327 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/domain/User.java @@ -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 memberships; + + public User(UserId id, String username, String displayName, String email, List 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 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"); + } + } + } +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/domain/UserRepository.java b/src/main/java/top/ddupan/iam/login/authentication/domain/UserRepository.java new file mode 100644 index 0000000..caea6cb --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/domain/UserRepository.java @@ -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 findByLoginName(String loginName); + + final class AccessFailure extends RuntimeException { + public AccessFailure() { super("User repository is unavailable or returned an invalid user"); } + } +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdEntryMapper.java b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdEntryMapper.java new file mode 100644 index 0000000..029a79f --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdEntryMapper.java @@ -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 mapFromLdapDataEntry(LdapDataEntry entry, Class 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); + } +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdPasswordAuthenticator.java b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdPasswordAuthenticator.java new file mode 100644 index 0000000..fa8c7d7 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdPasswordAuthenticator.java @@ -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; + }; + } +} diff --git a/src/main/java/top/ddupan/iam/login/ad/AdProperties.java b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdProperties.java similarity index 76% rename from src/main/java/top/ddupan/iam/login/ad/AdProperties.java rename to src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdProperties.java index 6ebcaca..b1441d5 100644 --- a/src/main/java/top/ddupan/iam/login/ad/AdProperties.java +++ b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdProperties.java @@ -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; diff --git a/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdUserEntry.java b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdUserEntry.java new file mode 100644 index 0000000..c562425 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdUserEntry.java @@ -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 memberOf; +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdUserRepository.java b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdUserRepository.java new file mode 100644 index 0000000..a7e6765 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/infrastructure/ad/AdUserRepository.java @@ -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 entries; + private final SingleContextSource connection; + private final String authority; + private final String loginName; + private boolean closed; + + AdUserRepository(LdapRepository entries, SingleContextSource connection, + String authority, String loginName) { + this.entries = entries; + this.connection = connection; + this.authority = authority; + this.loginName = loginName; + } + + @Override + public Optional 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(); + for (String dn : entry.getMemberOf() == null ? List.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(); } + } +} diff --git a/src/main/java/top/ddupan/iam/login/authentication/interfaces/web/BrowserSignInState.java b/src/main/java/top/ddupan/iam/login/authentication/interfaces/web/BrowserSignInState.java new file mode 100644 index 0000000..49ea262 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/authentication/interfaces/web/BrowserSignInState.java @@ -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; } +} diff --git a/src/main/java/top/ddupan/iam/login/preview/PageRenderer.java b/src/main/java/top/ddupan/iam/login/authentication/interfaces/web/PageRenderer.java similarity index 95% rename from src/main/java/top/ddupan/iam/login/preview/PageRenderer.java rename to src/main/java/top/ddupan/iam/login/authentication/interfaces/web/PageRenderer.java index 0b69f23..e738fd6 100644 --- a/src/main/java/top/ddupan/iam/login/preview/PageRenderer.java +++ b/src/main/java/top/ddupan/iam/login/authentication/interfaces/web/PageRenderer.java @@ -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; diff --git a/src/main/java/top/ddupan/iam/login/ad/AdLoginController.java b/src/main/java/top/ddupan/iam/login/authentication/interfaces/web/SignInController.java similarity index 54% rename from src/main/java/top/ddupan/iam/login/ad/AdLoginController.java rename to src/main/java/top/ddupan/iam/login/authentication/interfaces/web/SignInController.java index 4d18a50..576f7ee 100644 --- a/src/main/java/top/ddupan/iam/login/ad/AdLoginController.java +++ b/src/main/java/top/ddupan/iam/login/authentication/interfaces/web/SignInController.java @@ -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); - 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"); - } + return switch (signIn.submitPassword(state.transaction, username, password)) { + case ACCEPTED -> { + request.changeSessionId(); + state.error = ""; + 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 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 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; - } } diff --git a/src/main/java/top/ddupan/iam/login/configuration/AuthenticationConfiguration.java b/src/main/java/top/ddupan/iam/login/configuration/AuthenticationConfiguration.java new file mode 100644 index 0000000..a4369ad --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/configuration/AuthenticationConfiguration.java @@ -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); + } + } +} diff --git a/src/main/java/top/ddupan/iam/login/configuration/SecurityConfiguration.java b/src/main/java/top/ddupan/iam/login/configuration/SecurityConfiguration.java new file mode 100644 index 0000000..7375039 --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/configuration/SecurityConfiguration.java @@ -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(); + } +} diff --git a/src/main/java/top/ddupan/iam/login/configuration/WebConfiguration.java b/src/main/java/top/ddupan/iam/login/configuration/WebConfiguration.java new file mode 100644 index 0000000..3ec3acc --- /dev/null +++ b/src/main/java/top/ddupan/iam/login/configuration/WebConfiguration.java @@ -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/**"); + } + } +} diff --git a/src/main/java/top/ddupan/iam/login/preview/PreviewConfiguration.java b/src/main/java/top/ddupan/iam/login/preview/PreviewConfiguration.java deleted file mode 100644 index 99ef53d..0000000 --- a/src/main/java/top/ddupan/iam/login/preview/PreviewConfiguration.java +++ /dev/null @@ -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/**"); - } - } -} diff --git a/src/main/java/top/ddupan/iam/login/preview/PreviewController.java b/src/main/java/top/ddupan/iam/login/preview/PreviewController.java deleted file mode 100644 index 0ecee40..0000000 --- a/src/main/java/top/ddupan/iam/login/preview/PreviewController.java +++ /dev/null @@ -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 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 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 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 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 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 = ""; - } -} diff --git a/src/test/java/top/ddupan/iam/login/IamLoginApplicationTests.java b/src/test/java/top/ddupan/iam/login/IamLoginApplicationTests.java index abfb7d5..d97fc0e 100644 --- a/src/test/java/top/ddupan/iam/login/IamLoginApplicationTests.java +++ b/src/test/java/top/ddupan/iam/login/IamLoginApplicationTests.java @@ -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", "")) - .andExpect(status().isSeeOther()); - var html = mvc.perform(get("/preview/verify").session(session)) - .andExpect(status().isOk()).andReturn() - .getResponse().getContentAsString(); - assertThat(html).doesNotContain("") - .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 diff --git a/src/test/java/top/ddupan/iam/login/ad/AdIntegrationTests.java b/src/test/java/top/ddupan/iam/login/ad/AdIntegrationTests.java deleted file mode 100644 index 419b63f..0000000 --- a/src/test/java/top/ddupan/iam/login/ad/AdIntegrationTests.java +++ /dev/null @@ -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 "disabled@example.test" -> "533"; - case "locked@example.test" -> "775"; - case "expired@example.test" -> "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("alice@example.test")) { - 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", "alice@example.test"), - new com.unboundid.ldap.sdk.Attribute("userPassword", "fixture-password"), - new com.unboundid.ldap.sdk.Attribute("displayName", "Alice "), - new com.unboundid.ldap.sdk.Attribute("mail", "alice@example.test"), - 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("alice@example.test", "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("alice@other.test", "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", ""), + new com.unboundid.ldap.sdk.Attribute("mail", "alice@example.test"), + 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); } +}