接入 AD 密码验证与直接所属组,保留待 MFA 边界

This commit is contained in:
2026-09-25 21:06:39 +00:00
parent 2840f58397
commit d14151928d
18 changed files with 699 additions and 33 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
- 后续修改必须新建分支并提交 PR;未经维护者明确指示,不直接推 main、不自行合并。 - 后续修改必须新建分支并提交 PR;未经维护者明确指示,不直接推 main、不自行合并。
- 默认中文维护项目文档、commit、issue 和 PR;代码与上游 API 名称保留英文。 - 默认中文维护项目文档、commit、issue 和 PR;代码与上游 API 名称保留英文。
- 项目使用 Java 与 Spring;Native 是交付约束,不是可选优化,不引入 Kotlin。 - 项目使用 Java 与 Spring;Native 是交付约束,不是可选优化,不引入 Kotlin。
- 变更需通过适用的 JVM 测试和 Native 集成测试;未执行的验证明确报告。 - 日常变更先通过适用的 JVM 测试,不要求每轮执行耗时的 Native 编译与测试;Native 仍为交付目标,在阶段性验收或兼容性风险变化时集中验证。未执行的验证明确报告。
- 只实现当前任务范围。Hydra 负责签发,首轮 AD 负责身份和组,本服务独立于 Ayatori。 - 只实现当前任务范围。Hydra 负责签发,首轮 AD 负责身份和组,本服务独立于 Ayatori。
- 不把 LDAP 密码成功当成完整 MFA 成功;所有因素绑定同一主体与认证事务。 - 不把 LDAP 密码成功当成完整 MFA 成功;所有因素绑定同一主体与认证事务。
- 不提交凭据、MFA secret、生产配置秘密或包含上述内容的测试输出。 - 不提交凭据、MFA secret、生产配置秘密或包含上述内容的测试输出。
+12 -4
View File
@@ -1,7 +1,7 @@
# iam-login # iam-login
独立 IAM 的登录与认证服务,以 Java、Spring Security 和 GraalVM Native 实现,作为 独立 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 中固定。 4.1.1 和 Gradle;Spring Security 等库由 Boot BOM 管理,插件版本在 build.gradle 中固定。
Native 使用 GraalVM 25。 Native 使用 GraalVM 25。
Native 构建与原生二进制上的认证测试是交付要求;JVM 测试通过或 native 编译成功都不 日常改动先跑 JVM 测试,不要求每轮编译 Native。Native 构建与原生二进制上的认证测试
留在阶段性验收;JVM 测试通过或 native 编译成功都不
单独构成验收。Keycloak 可作为流程与安全边界参考,不以它采用 Quarkus 作为 native 单独构成验收。Keycloak 可作为流程与安全边界参考,不以它采用 Quarkus 作为 native
兼容性证据,不直接引入其服务端 SPI 和模型。 兼容性证据,不直接引入其服务端 SPI 和模型。
@@ -53,7 +54,7 @@ npm --prefix frontend run build
``` ```
测试需要可用的 Docker,生成器配置了 Grafana LGTM Testcontainer。 测试需要可用的 Docker,生成器配置了 Grafana LGTM Testcontainer。
当前有隔离的浏览器交互原型与上下文测试,默认 Spring Security 登录页不是可用的 IAM 登录流程。 包含隔离浏览器原型和 AD 第一因素测试;默认 Spring Security 登录页不是 IAM 登录流程。
使用 GraalVM 25 验证原生测试与编译: 使用 GraalVM 25 验证原生测试与编译:
```sh ```sh
@@ -65,10 +66,17 @@ Docker 开发使用 `scripts/gradle-in-docker`,默认持久挂载 Gradle 缓
原生应用可用 `python3 scripts/native-smoke.py` 检查启动、默认访问控制和 HTTP 指标。 原生应用可用 `python3 scripts/native-smoke.py` 检查启动、默认访问控制和 HTTP 指标。
JVM、AOT、Native 测试及原生应用 HTTP 检查已通过,实测范围与资源数据见 JVM、AOT、Native 测试及原生应用 HTTP 检查已通过,实测范围与资源数据见
[本地验证结果](docs/bootstrap.md#2026-09-25-本地验证结果)。 [本地验证结果](docs/bootstrap.md#2026-09-25-本地验证结果)。
AD、MFA 与 Hydra 认证链路仍待实现与验收。 新增 AD 路径本轮按维护者要求只进行 JVM 验证,不沿用基线的 Native 验收结论。
真实目录密码和组结果需人类验收;MFA 与 Hydra 链路仍待实现。
## 浏览器流程预览 ## 浏览器流程预览
人类登录界面采用 React + Vite,参考 Keycloakify 的内联上下文与原生表单提交方式。 人类登录界面采用 React + Vite,参考 Keycloakify 的内联上下文与原生表单提交方式。
原型默认关闭,仅测试页面切换与局部交互,不执行真实认证。启动、浏览器测试和边界见 原型默认关闭,仅测试页面切换与局部交互,不执行真实认证。启动、浏览器测试和边界见
[浏览器流程原型](docs/browser-preview.md)。 [浏览器流程原型](docs/browser-preview.md)。
## AD 第一因素接入
真实入口为 `/signin`,默认关闭且要求 HTTPS。密码验证通过后显示 AD 身份与直接所属组,
停在等待 MFA 状态,不建立完整登录身份或接受 Hydra challenge。
配置、组语义、HTTPS 与验收边界见 [AD 接入](docs/ad-login.md)。
+1
View File
@@ -27,6 +27,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-webmvc' implementation 'org.springframework.boot:spring-boot-starter-webmvc'
implementation 'org.springframework.security:spring-security-webauthn' implementation 'org.springframework.security:spring-security-webauthn'
implementation 'org.springframework.security:spring-security-ldap'
compileOnly 'org.projectlombok:lombok' compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools' developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'io.micrometer:micrometer-registry-prometheus' runtimeOnly 'io.micrometer:micrometer-registry-prometheus'
+102
View File
@@ -0,0 +1,102 @@
# AD 第一因素接入
`/signin` 接收 AD 用户名(sAMAccountName)或本域 UPN,使用 Spring Security
`ActiveDirectoryLdapAuthenticationProvider` 以用户身份执行 LDAPS bind 与目录查询。
不使用额外目录服务账号,不写入 AD,不复制 Authelia 的绑定密码。
成功后重定向到 `/signin/mfa`,显示目录账号、objectGUID、邮箱、直接所属组及组 DN。
**这是密码因素验收页面,MFA 尚未接入,不是完整登录成功。** 不创建 Spring Security
认证上下文,不调用 Hydra,不替换现役 Go/Authelia/Gitea 登录链路。演示入口 `/preview`
仍完全隔离,默认关闭,演示码不能推进真实认证。
## 目录和组语义
- AD 是身份和组权威。objectGUID 按 AD 混合字节序解析为标准 UUID,作为目录稳定键;
不是已确定的 Hydra `sub`。切换前仍须处理现役 issuer/sub 哈希的主体连续性。
- 从 `memberOf` 读取直接成员关系,保留原始 DN;CN 保留大小写,不添加 `ROLE_`,
不把 Spring 的 `FACTOR_PASSWORD` 当作组。结果排序,不做应用专用组改写。
- 此轮不展开嵌套组、不推导 primaryGroupID,也不宣称与 Authelia 的有效组集合完全一致。
遇到 ranged memberOf 或不同 DN 同名 CN 拒绝映射,不静默丢组或合并不同主体。
- AD bind 执行密码及账号状态检查;Spring 解析禁用、锁定、密码过期等 AD 子码。
搜索排除 computer 对象,只接受唯一用户条目和合法 objectGUID/sAMAccountName。
- 邮箱作为目录属性展示,不声称 `email_verified=true`。
## 启用
正常 JVM 构建:
```sh
IAM_DOCKER_USE_SUDO=1 scripts/gradle-in-docker test bootJar
```
Gradle 与 npm 缓存默认持久挂载,可用 `IAM_GRADLE_CACHE`、`IAM_NPM_CACHE` 指定目录。
日常迭代不必每轮跑 Native;新增 AD/JNDI/TLS 路径的原生验收留到阶段性验证。
运行时配置(非秘密):
```yaml
iam:
ad:
enabled: true
url: ldaps://dc1.ad.ddupan.top:636
domain: ad.ddupan.top
base-dn: DC=ad,DC=ddupan,DC=top
server:
port: 18082
ssl:
enabled: true
certificate: file:/run/iam/browser.crt
certificate-private-key: file:/run/iam/browser.key
servlet:
session:
cookie:
secure: true
same-site: lax
```
证书与私钥使用外部受管文件,不加入仓库。开发验收可使用本机的 Tailscale HTTPS 域名
及相应证书;用匹配证书的主机名打开,不能用 LAN IP 替代域名后跳过警告。
部署与证书自动续期归 homelab-infra,此轮本地运行不是生产部署。
LDAPS 使用默认 JSSE 信任库并执行服务端域名校验。Samba 当前证书由 OpenBao 内部 CA
签发,需把**公开 CA** 加入运行用 truststore,并通过 JVM 参数指定:
```sh
java -Djavax.net.ssl.trustStore=/run/iam/truststore \
-Djavax.net.ssl.trustStorePassword=changeit -jar iam-login.jar
```
这里 truststore 仅含公开信任锚,口令不是目录密码。保留所需公共根证书;不得禁用
LDAP endpoint identification 或用信任所有证书的 socket factory。连接/读取超时为 3/5 秒。
浏览器入口只接受 HTTPS;明文请求返回 426。默认不信任转发头。若以后由代理终结 TLS,
必须配合仅受信代理可达的后端网络和转发头配置,不能公开一个信任任意 forwarded header
的 HTTP 端口。当前开发验收由应用直接终结 TLS。
## 状态与操作
原生表单 POST 带 Spring CSRF token;服务端决定下一页。密码成功后轮换 session ID,
只保存目录身份快照和十分钟期限,不保存密码;重启或“退出并重新验证”清除事务。
页面禁止缓存,内联 JSON 转义 HTML 结束标记。失败页面不披露目录内部异常。
当前每个 session 只保留一份事务,多标签页会共享状态。两秒提交间隔仅用于同事务的
重复提交,不是账号/IP 限流;此 PoC 仅供受控 LAN/Tailscale 验收,生产发布前仍需完善
入口限流、审计、MFA、Hydra 事务和恢复策略。
基础存活检查使用 `/actuator/health/liveness`。Boot 自动配置的 LDAP 健康项并未连接这里
独立配置的 AD provider,不能把该项当作此认证路径的可用性验证。
## 本轮验证边界
隔离测试使用真实 TLS、LDAP bind 和搜索,校验正确/错误密码、未知账号、AD 账号状态
子码、GUID 字节序、组名、错误 TLS 主机名、CSRF、HTTPS、会话轮换、超时和密码成功后
仍未完整认证。UnboundID 的 UPN bind 与 AD 子码由测试拦截器模拟,不能替代 Samba AD。
测试证书、私钥与账号全为虚构夹具,不用于实际部署。
2026-09-25:JVM 测试共 12 项通过(原有 6 项、新增 AD 6 项),`bootJar` 构建通过。
实际 JVM 使用受信 CA 完成 Samba AD RootDSE 查询,HTTPS 页面返回 200。
浏览器已检查登录表单渲染、真实 CSRF 原生 POST 和失败后清空密码;只使用在访问 AD 前
即拒绝的合成外域用户名,不尝试猜测人类密码。
实际人类密码与组结果仍需维护者
在 HTTPS 页面输入凭据验收,不在聊天、命令行或日志中传递人类密码。
新增 AD 路径尚未进行 Native 测试,不能复用旧 UI 原型的 Native 结论。
+3
View File
@@ -20,6 +20,9 @@ WebAuthn 集成;TOTP、恢复方式与已有 Authelia MFA 的迁移方式需
- Hydra admin 保持内部访问,业务日志不得包含密码、MFA secret、token 或 challenge。 - Hydra admin 保持内部访问,业务日志不得包含密码、MFA secret、token 或 challenge。
- 原生二进制与隔离 Hydra 完成授权码链路,再验证现有 Gitea 账号及权限。 - 原生二进制与隔离 Hydra 完成授权码链路,再验证现有 Gitea 账号及权限。
日常迭代以 JVM 测试为准,不要求每轮执行 Native 编译。Native 验证安排在阶段性验收
或新增反射、JNDI、TLS 等兼容性风险时集中进行;记录尚未覆盖的新路径。
## Native 与监控 ## Native 与监控
- CI 构建 Native 产物并对该产物执行集成测试;测试报告区分 JVM 与 Native。 - CI 构建 Native 产物并对该产物执行集成测试;测试报告区分 JVM 与 Native。
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" /> <meta name="color-scheme" content="light dark" />
<title>登录体验预览 · IAM</title> <title>登录 · IAM</title>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<noscript>此预览使用 React 渲染页面,请启用 JavaScript。</noscript> <noscript>本页使用 React 渲染页面,请启用 JavaScript。</noscript>
<script id="login-context" type="application/json"> <script id="login-context" type="application/json">
__IAM_PAGE_CONTEXT__ __IAM_PAGE_CONTEXT__
</script> </script>
+37 -4
View File
@@ -3,7 +3,8 @@ import { useState, useLayoutEffect, type ReactNode } from "react";
import "./style.css"; import "./style.css";
type PageContext = { type PageContext = {
step: "identity" | "verification" | "complete"; step: "identity" | "verification" | "complete" | "password" | "mfa-pending";
identity?: { username: string; objectGuid: string; email: string; groups: string[]; groupDns: string[] };
name: string; name: string;
error: string; error: string;
action: string; action: string;
@@ -32,8 +33,8 @@ function Form({ children }: { children: ReactNode }) {
<button className="primary" type="submit" disabled={pending}> <button className="primary" type="submit" disabled={pending}>
{pending {pending
? "正在继续…" ? "正在继续…"
: context.step === "complete" : (context.step === "complete" || context.step === "mfa-pending")
? "重新体验" ? (context.step === "mfa-pending" ? "退出并重新验证" : "重新体验")
: "继续"} : "继续"}
</button> </button>
</form> </form>
@@ -156,4 +157,36 @@ function App() {
); );
} }
createRoot(document.getElementById("root")!).render(<App />); function SignIn() {
useLayoutEffect(() => { performance.mark("iam-page-ready"); }, []);
const identity = context.identity;
return <main>
<header><a href="/signin" className="brand">i<span>am</span></a></header>
<section className="card" aria-labelledby="title">
<div className="eyebrow">AD 登录验证</div>
<h1 id="title">{context.step === "password" ? "登录你的账号" : "密码已验证,等待 MFA"}</h1>
<p className="intro">{context.step === "password"
? "使用 AD 用户名或完整 UPN 登录。"
: `${context.name},目录验证成功。第二因素尚未接入,本次没有完成登录或向应用授权。`}</p>
{context.error && <p className="error" role="alert">{context.error}</p>}
{identity && <div className="directory-result">
<dl><dt>账号</dt><dd>{identity.username}</dd>
<dt>目录标识</dt><dd>{identity.objectGuid}</dd>
<dt>邮箱</dt><dd>{identity.email || "未设置"}</dd></dl>
<h2>直接所属组</h2>
{identity.groups.length ? <ul>{identity.groups.map(group => <li key={group}>{group}</li>)}</ul> : <p>没有直接所属组。</p>}
<details><summary>组 DN</summary><ul>{identity.groupDns.map(dn => <li key={dn}>{dn}</li>)}</ul></details>
<p>当前仅读取 memberOf,不展开嵌套组,也不包含主组。</p>
</div>}
<Form>{context.step === "password" && <>
<label>用户名<input name="username" autoComplete="username" autoFocus required maxLength={256} defaultValue={context.name} /></label>
<label>密码<input name="password" type="password" autoComplete="current-password" required maxLength={1024} /></label>
</>}</Form>
</section>
<footer>独立 IAM · AD 接入验证</footer>
</main>;
}
createRoot(document.getElementById("root")!).render(
context.step === "password" || context.step === "mfa-pending" ? <SignIn /> : <App />,
);
+4
View File
@@ -238,3 +238,7 @@ button:focus-visible {
color: #ffc3b9; color: #ffc3b9;
} }
} }
.directory-result { overflow-wrap: anywhere; }
.directory-result dd { margin: 0 0 1rem; }
.directory-result h2 { font-size: 1rem; }
@@ -0,0 +1,128 @@
package top.ddupan.iam.login.ad;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.time.Instant;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import top.ddupan.iam.login.preview.PageRenderer;
/** Human first-factor PoC. No SecurityContext, MFA acceptance, or Hydra calls. */
@RestController
public class AdLoginController {
static final String STATE = AdLoginController.class.getName() + ".state";
private final AdPasswordVerifier verifier;
private final PageRenderer renderer;
public AdLoginController(AdPasswordVerifier verifier, PageRenderer renderer) {
this.verifier = verifier;
this.renderer = renderer;
}
@GetMapping(value = "/signin", produces = MediaType.TEXT_HTML_VALUE)
ResponseEntity<String> page(HttpServletRequest request, CsrfToken csrf) {
requireAvailable(request);
var session = request.getSession();
synchronized (session) {
var state = state(session);
if (state.identity != null) return redirect("/signin/mfa");
return renderer.render(Map.of("step", "password", "name", state.username,
"error", state.error, "action", "/signin/password", "csrf", csrf(csrf)));
}
}
@PostMapping("/signin/password")
ResponseEntity<String> password(HttpServletRequest request,
@RequestParam(defaultValue = "") String username,
@RequestParam(defaultValue = "") String password) {
requireAvailable(request);
var session = request.getSession(false);
if (session == null) throw new ResponseStatusException(HttpStatus.CONFLICT);
synchronized (session) {
var state = (State) session.getAttribute(STATE);
if (state == null || state.identity != null || state.expires.isBefore(Instant.now())) {
return redirect("/signin");
}
// Prevent double submissions in this transaction; perimeter rate limits belong at ingress.
if (state.retryAfter.isAfter(Instant.now())) throw new ResponseStatusException(HttpStatus.TOO_MANY_REQUESTS);
state.retryAfter = Instant.now().plusSeconds(2);
state.username = username.length() <= 256 ? username : "";
try {
var identity = verifier.verify(username, password);
request.changeSessionId();
state.identity = identity;
state.error = "";
state.expires = Instant.now().plusSeconds(600);
return redirect("/signin/mfa");
} catch (AuthenticationException | org.springframework.dao.DataAccessException ex) {
// Neither directory exception details nor passwords enter HTML/session/logs.
state.error = "无法验证账号,请检查凭据与账号状态,或稍后重试。";
return redirect("/signin");
}
}
}
@GetMapping(value = "/signin/mfa", produces = MediaType.TEXT_HTML_VALUE)
ResponseEntity<String> pending(HttpServletRequest request, CsrfToken csrf) {
requireAvailable(request);
var session = request.getSession(false);
if (session == null) return redirect("/signin");
synchronized (session) {
var state = state(session);
if (state.identity == null) return redirect("/signin");
var identity = state.identity;
return renderer.render(Map.of("step", "mfa-pending", "name", identity.displayName(),
"error", "", "action", "/signin/restart", "csrf", csrf(csrf),
"identity", Map.of("username", identity.username(), "objectGuid", identity.objectGuid(),
"email", identity.email(), "groups", identity.groups(), "groupDns", identity.groupDns())));
}
}
@PostMapping("/signin/restart")
ResponseEntity<String> restart(HttpServletRequest request) {
requireAvailable(request);
var session = request.getSession(false);
if (session != null) session.invalidate();
return redirect("/signin");
}
private void requireAvailable(HttpServletRequest request) {
if (!verifier.enabled()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
if (!request.isSecure()) throw new ResponseStatusException(HttpStatus.UPGRADE_REQUIRED, "HTTPS required");
}
private static Map<String, String> csrf(CsrfToken token) {
return Map.of("name", token.getParameterName(), "value", token.getToken());
}
private static State state(HttpSession session) {
var state = (State) session.getAttribute(STATE);
if (state == null || state.expires.isBefore(Instant.now())) {
state = new State();
session.setAttribute(STATE, state);
}
return state;
}
private static ResponseEntity<String> redirect(String location) {
return ResponseEntity.status(HttpStatus.SEE_OTHER).header("Location", location)
.header("Cache-Control", "no-store").build();
}
static final class State {
String username = "";
String error = "";
DirectoryIdentity identity;
Instant expires = Instant.now().plusSeconds(600);
Instant retryAfter = Instant.EPOCH;
}
}
@@ -0,0 +1,151 @@
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}))");
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", "throw"));
// Directory groups are mapped independently; do not confuse FACTOR_PASSWORD with a group.
provider.setAuthoritiesPopulator((entry, username) -> List.of());
provider.setUserDetailsContextMapper(new IdentityMapper());
}
public boolean enabled() { return properties.enabled(); }
public DirectoryIdentity verify(String username, String password) {
if (provider == null) throw new IllegalStateException("AD login is disabled");
if (username == null || username.isBlank() || username.length() > 256
|| username.contains("\\") || !username.equals(username.strip())
|| (username.contains("@") && !username.toLowerCase(java.util.Locale.ROOT)
.endsWith("@" + properties.domain().toLowerCase(java.util.Locale.ROOT)))
|| password == null || password.isEmpty() || password.length() > 1024) {
throw new BadCredentialsException("Invalid credentials");
}
var token = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
try {
var result = provider.authenticate(token);
try {
return ((IdentityUser) result.getPrincipal()).identity;
} finally {
if (result instanceof org.springframework.security.core.CredentialsContainer credentials) {
credentials.eraseCredentials();
}
}
} finally {
token.eraseCredentials();
}
}
static final class IdentityUser extends User {
final DirectoryIdentity identity;
IdentityUser(DirectoryIdentity identity) {
super(identity.username(), "", List.of());
this.identity = identity;
}
}
static final class IdentityMapper implements UserDetailsContextMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations entry, String username,
Collection<? extends GrantedAuthority> authorities) {
try {
// Refuse an incomplete ranged result instead of silently dropping groups.
var ids = entry.getAttributes().getIDs();
try {
while (ids.hasMore()) {
if (ids.next().toLowerCase(java.util.Locale.ROOT).startsWith("memberof;")) {
throw new IllegalArgumentException("Ranged membership is not supported yet");
}
}
} finally { ids.close(); }
String account = required(entry, "sAMAccountName");
String display = entry.getStringAttribute("displayName");
String email = entry.getStringAttribute("mail");
String[] membership = entry.getStringAttributes("memberOf");
List<String> dns = membership == null ? List.of() : Arrays.stream(membership).sorted().toList();
var groups = new java.util.TreeSet<String>();
for (String dn : dns) {
var name = new LdapName(dn);
var rdn = name.getRdn(name.size() - 1);
if (!rdn.getType().equalsIgnoreCase("CN")) throw new IllegalArgumentException("Group has no CN");
if (!groups.add(rdn.getValue().toString())) throw new IllegalArgumentException("Ambiguous group CN");
}
return new IdentityUser(new DirectoryIdentity(
guid((byte[]) entry.getObjectAttribute("objectGUID")), account,
display == null ? account : display, email == null ? "" : email,
List.copyOf(groups), dns));
} catch (NamingException | IllegalArgumentException | ClassCastException ex) {
throw new InternalAuthenticationServiceException("Directory identity cannot be mapped", ex);
}
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter context) {
throw new UnsupportedOperationException("Read-only directory integration");
}
private static String required(DirContextOperations entry, String attribute) {
String value = entry.getStringAttribute(attribute);
if (value == null || value.isBlank()) throw new IllegalArgumentException("Missing directory attribute");
return value;
}
}
static String guid(byte[] bytes) {
if (bytes == null || bytes.length != 16) throw new IllegalArgumentException("Invalid objectGUID");
var little = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
long most = Integer.toUnsignedLong(little.getInt()) << 32
| (long) Short.toUnsignedInt(little.getShort()) << 16
| Short.toUnsignedInt(little.getShort());
long least = ByteBuffer.wrap(bytes, 8, 8).getLong();
return new UUID(most, least).toString();
}
}
@@ -0,0 +1,6 @@
package top.ddupan.iam.login.ad;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("iam.ad")
public record AdProperties(boolean enabled, String url, String domain, String baseDn) {}
@@ -0,0 +1,12 @@
package top.ddupan.iam.login.ad;
import java.util.List;
/** Directory key only: deliberately not a Hydra subject or a completed authentication. */
public record DirectoryIdentity(String objectGuid, String username, String displayName,
String email, List<String> groups, List<String> groupDns) {
public DirectoryIdentity {
groups = List.copyOf(groups);
groupDns = List.copyOf(groupDns);
}
}
@@ -0,0 +1,32 @@
package top.ddupan.iam.login.preview;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
/** Shared HTML shell; the page context is data, never executable JavaScript. */
@Component
public class PageRenderer {
private static final String SLOT = "__IAM_PAGE_CONTEXT__";
private final String shell;
private final JsonMapper json = JsonMapper.builder().build();
public PageRenderer() throws IOException {
shell = new ClassPathResource("ui/index.html").getContentAsString(StandardCharsets.UTF_8);
if (shell.indexOf(SLOT) < 0 || shell.indexOf(SLOT) != shell.lastIndexOf(SLOT)) {
throw new IllegalStateException("Expected exactly one UI context slot");
}
}
public ResponseEntity<String> render(Object context) {
String safe = json.writeValueAsString(context).replace("<", "\\u003c")
.replace(">", "\\u003e").replace("&", "\\u0026")
.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029");
return ResponseEntity.ok().header("Cache-Control", "no-store")
.contentType(MediaType.TEXT_HTML).body(shell.replace(SLOT, safe));
}
}
@@ -19,7 +19,7 @@ class PreviewConfiguration implements WebMvcConfigurer {
@Bean @Bean
SecurityFilterChain security(HttpSecurity http) throws Exception { SecurityFilterChain security(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(auth -> auth return http.authorizeHttpRequests(auth -> auth
.requestMatchers("/error", "/preview", "/preview/**", "/assets/**", "/actuator/health/**").permitAll() .requestMatchers("/error", "/signin", "/signin/**", "/preview", "/preview/**", "/assets/**", "/actuator/health/**").permitAll()
.anyRequest().authenticated()) .anyRequest().authenticated())
.formLogin(Customizer.withDefaults()) .formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults()) .httpBasic(Customizer.withDefaults())
@@ -2,11 +2,8 @@ package top.ddupan.iam.login.preview;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
@@ -16,23 +13,17 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException; import org.springframework.web.server.ResponseStatusException;
import tools.jackson.databind.json.JsonMapper;
/** An isolated UI experiment. It never creates an authenticated SecurityContext. */ /** An isolated UI experiment. It never creates an authenticated SecurityContext. */
@RestController @RestController
class PreviewController { class PreviewController {
private static final String STATE = PreviewController.class.getName() + ".state"; private static final String STATE = PreviewController.class.getName() + ".state";
private static final String SLOT = "__IAM_PAGE_CONTEXT__";
private final boolean enabled; private final boolean enabled;
private final String shell; private final PageRenderer renderer;
private final JsonMapper json = JsonMapper.builder().build();
PreviewController(@Value("${iam.ui-preview.enabled:false}") boolean enabled) throws IOException { PreviewController(@Value("${iam.ui-preview.enabled:false}") boolean enabled, PageRenderer renderer) {
this.enabled = enabled; this.enabled = enabled;
this.shell = new ClassPathResource("ui/index.html").getContentAsString(StandardCharsets.UTF_8); this.renderer = renderer;
if (shell.indexOf(SLOT) < 0 || shell.indexOf(SLOT) != shell.lastIndexOf(SLOT)) {
throw new IllegalStateException("Expected exactly one UI context slot");
}
} }
@GetMapping(value = {"/preview", "/preview/verify", "/preview/complete"}, produces = MediaType.TEXT_HTML_VALUE) @GetMapping(value = {"/preview", "/preview/verify", "/preview/complete"}, produces = MediaType.TEXT_HTML_VALUE)
@@ -54,8 +45,7 @@ class PreviewController {
case "verification" -> "/preview/verify"; case "verification" -> "/preview/verify";
default -> "/preview/restart"; default -> "/preview/restart";
}, "csrf", Map.of("name", csrf.getParameterName(), "value", csrf.getToken())); }, "csrf", Map.of("name", csrf.getParameterName(), "value", csrf.getToken()));
return ResponseEntity.ok().header("Cache-Control", "no-store") return renderer.render(context);
.contentType(MediaType.TEXT_HTML).body(shell.replace(SLOT, htmlSafeJson(context)));
} }
} }
@@ -131,13 +121,6 @@ class PreviewController {
.header("Cache-Control", "no-store").build(); .header("Cache-Control", "no-store").build();
} }
String htmlSafeJson(Object value) {
// JSON in a script data block still participates in HTML parsing.
return json.writeValueAsString(value).replace("<", "\\u003c")
.replace(">", "\\u003e").replace("&", "\\u0026")
.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029");
}
private static class State { private static class State {
String step = "identity"; String step = "identity";
String name = ""; String name = "";
@@ -0,0 +1,199 @@
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.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 processSimpleBindRequest(InMemoryInterceptedSimpleBindRequest request) throws LDAPException {
String name = request.getRequest().getBindDN();
String subcode = switch (name) {
case "[email protected]" -> "533";
case "[email protected]" -> "775";
case "[email protected]" -> "532";
default -> null;
};
if (subcode != null) throw new LDAPException(ResultCode.INVALID_CREDENTIALS,
"80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data " + subcode + ", v1db1");
if (name.equalsIgnoreCase("[email protected]")) {
request.setRequest(new SimpleBindRequest(USER_DN, request.getRequest().getPassword().getValue()));
} else if (!name.equals(USER_DN)) {
throw new LDAPException(ResultCode.INVALID_CREDENTIALS, "Invalid credentials");
}
}
});
LDAP = new InMemoryDirectoryServer(config);
LDAP.startListening();
LDAP.add(new Entry(BASE, new com.unboundid.ldap.sdk.Attribute("objectClass", "domain"),
new com.unboundid.ldap.sdk.Attribute("dc", "example")));
LDAP.add(new Entry(USER_DN,
new com.unboundid.ldap.sdk.Attribute("objectClass", "user"),
new com.unboundid.ldap.sdk.Attribute("cn", "Alice"),
new com.unboundid.ldap.sdk.Attribute("sAMAccountName", "alice"),
new com.unboundid.ldap.sdk.Attribute("userPrincipalName", "[email protected]"),
new com.unboundid.ldap.sdk.Attribute("userPassword", "fixture-password"),
new com.unboundid.ldap.sdk.Attribute("displayName", "Alice </script><script>attack()</script>"),
new com.unboundid.ldap.sdk.Attribute("mail", "[email protected]"),
new com.unboundid.ldap.sdk.Attribute("objectGUID", GUID),
new com.unboundid.ldap.sdk.Attribute("memberOf", "CN=gitea-admins," + BASE, "CN=MixedCase," + BASE)));
} catch (Exception ex) { throw new ExceptionInInitializerError(ex); }
}
}
@DynamicPropertySource
static void directory(DynamicPropertyRegistry registry) {
registry.add("iam.ad.url", () -> "ldaps://localhost:" + Fixture.LDAP.getListenPort());
}
@AfterAll
static void close() { Fixture.LDAP.shutDown(true); SSLContext.setDefault(Fixture.ORIGINAL); }
@Autowired AdPasswordVerifier verifier;
@Autowired MockMvc mvc;
@Test
void passwordReadsGuidAndExactGroupsOverTls() {
var identity = verifier.verify("alice", "fixture-password");
assertThat(identity.objectGuid()).isEqualTo("00112233-4455-6677-8899-aabbccddeeff");
assertThat(identity.groups()).containsExactly("MixedCase", "gitea-admins");
assertThat(identity.groupDns()).containsExactly("CN=MixedCase," + BASE, "CN=gitea-admins," + BASE);
assertThat(verifier.verify("[email protected]", "fixture-password")).isEqualTo(identity);
}
@Test
void rejectsPasswordsUnknownUsersAndAdAccountStates() {
assertThatThrownBy(() -> verifier.verify("alice", "wrong")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("alice", "")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("unknown", "fixture-password")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("[email protected]", "fixture-password")).isInstanceOf(BadCredentialsException.class);
assertThatThrownBy(() -> verifier.verify("disabled", "fixture-password")).isInstanceOf(DisabledException.class);
assertThatThrownBy(() -> verifier.verify("locked", "fixture-password")).isInstanceOf(LockedException.class);
assertThatThrownBy(() -> verifier.verify("expired", "fixture-password")).isInstanceOf(CredentialsExpiredException.class);
}
@Test
void rejectsWrongTlsHostnameAndPlainLdapConfiguration() {
var wrongName = new AdPasswordVerifier(new AdProperties(true,
"ldaps://127.0.0.1:" + Fixture.LDAP.getListenPort(), "example.test", BASE));
assertThatThrownBy(() -> wrongName.verify("alice", "fixture-password"))
.hasStackTraceContaining("No subject alternative names matching IP address");
assertThatThrownBy(() -> new AdPasswordVerifier(new AdProperties(true,
"ldap://localhost:389", "example.test", BASE))).isInstanceOf(IllegalArgumentException.class);
}
@Test
void browserRequiresHttpsCsrfAndOrderedSteps() throws Exception {
mvc.perform(get("/signin")).andExpect(status().isUpgradeRequired());
mvc.perform(get("/signin/mfa").secure(true)).andExpect(redirectedUrl("/signin"));
mvc.perform(post("/signin/password").secure(true).param("username", "alice")
.param("password", "fixture-password")).andExpect(status().isForbidden());
}
@Test
void successfulPasswordRotatesSessionAndStopsBeforeMfa() throws Exception {
var session = new MockHttpSession();
mvc.perform(get("/signin").secure(true).session(session)).andExpect(status().isOk());
String oldId = session.getId();
mvc.perform(post("/signin/password").secure(true).session(session).with(csrf())
.param("username", "alice").param("password", "fixture-password"))
.andExpect(redirectedUrl("/signin/mfa"));
assertThat(session.getId()).isNotEqualTo(oldId);
var html = mvc.perform(get("/signin/mfa").secure(true).session(session))
.andExpect(status().isOk()).andExpect(header().string("Cache-Control", "no-store"))
.andReturn().getResponse().getContentAsString();
assertThat(html).contains("mfa-pending", "gitea-admins", "\\u003c/script\\u003e")
.doesNotContain("fixture-password", "</script><script>attack()");
assertThat(session.getAttribute("SPRING_SECURITY_CONTEXT")).isNull();
mvc.perform(get("/").secure(true).session(session).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
var state = (AdLoginController.State) session.getAttribute(AdLoginController.STATE);
state.expires = Instant.EPOCH;
mvc.perform(get("/signin/mfa").secure(true).session(session)).andExpect(redirectedUrl("/signin"));
}
@Test
void failedPasswordDoesNotRetainIdentityAndRestartInvalidatesSession() throws Exception {
var session = new MockHttpSession();
mvc.perform(get("/signin").secure(true).session(session));
mvc.perform(post("/signin/password").secure(true).session(session).with(csrf())
.param("username", "alice").param("password", "wrong"))
.andExpect(redirectedUrl("/signin"));
var state = (AdLoginController.State) session.getAttribute(AdLoginController.STATE);
assertThat(state.identity).isNull();
assertThat(state.error).isNotBlank().doesNotContain("LDAP", "wrong");
mvc.perform(post("/signin/restart").secure(true).session(session).with(csrf()))
.andExpect(redirectedUrl("/signin"));
assertThat(session.isInvalid()).isTrue();
}
}
+4
View File
@@ -0,0 +1,4 @@
fixture.p12 是仅用于隔离 LDAPS 测试的自签名证书和测试私钥,口令为 fixture-only。
仅信任 localhost,不能用于生产。测试账户和密码都是虚构数据。
测试服务仅绑定 127.0.0.1;JVM/Native 均执行真实 TLS、bind 和搜索,但 AD 的 UPN bind
与禁用/锁定/密码过期子码由拦截器模拟,不代替 Samba AD 人类验收。
Binary file not shown.