试验 React 内联上下文与原生表单登录流程
This commit is contained in:
@@ -42,3 +42,9 @@ out/
|
|||||||
*.log
|
*.log
|
||||||
|
|
||||||
__pycache__/
|
__pycache__/
|
||||||
|
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
frontend/test-results/
|
||||||
|
frontend/playwright-report/
|
||||||
|
.playwright-cli/
|
||||||
|
|||||||
@@ -46,12 +46,14 @@ Native 构建与原生二进制上的认证测试是交付要求;JVM 测试通
|
|||||||
[项目初始化](docs/bootstrap.md)。使用 JDK 25 执行:
|
[项目初始化](docs/bootstrap.md)。使用 JDK 25 执行:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
npm --prefix frontend ci
|
||||||
|
npm --prefix frontend run build
|
||||||
./gradlew test testAot
|
./gradlew test testAot
|
||||||
./gradlew bootRun
|
./gradlew bootRun
|
||||||
```
|
```
|
||||||
|
|
||||||
测试需要可用的 Docker,生成器配置了 Grafana LGTM Testcontainer。
|
测试需要可用的 Docker,生成器配置了 Grafana LGTM Testcontainer。
|
||||||
当前只有默认应用和上下文测试,默认 Spring Security 登录页不是可用的 IAM 登录流程。
|
当前有隔离的浏览器交互原型与上下文测试,默认 Spring Security 登录页不是可用的 IAM 登录流程。
|
||||||
使用 GraalVM 25 验证原生测试与编译:
|
使用 GraalVM 25 验证原生测试与编译:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -64,3 +66,9 @@ Docker 开发使用 `scripts/gradle-in-docker`,默认持久挂载 Gradle 缓
|
|||||||
JVM、AOT、Native 测试及原生应用 HTTP 检查已通过,实测范围与资源数据见
|
JVM、AOT、Native 测试及原生应用 HTTP 检查已通过,实测范围与资源数据见
|
||||||
[本地验证结果](docs/bootstrap.md#2026-09-25-本地验证结果)。
|
[本地验证结果](docs/bootstrap.md#2026-09-25-本地验证结果)。
|
||||||
AD、MFA 与 Hydra 认证链路仍待实现与验收。
|
AD、MFA 与 Hydra 认证链路仍待实现与验收。
|
||||||
|
|
||||||
|
## 浏览器流程预览
|
||||||
|
|
||||||
|
人类登录界面采用 React + Vite,参考 Keycloakify 的内联上下文与原生表单提交方式。
|
||||||
|
原型默认关闭,仅测试页面切换与局部交互,不执行真实认证。启动、浏览器测试和边界见
|
||||||
|
[浏览器流程原型](docs/browser-preview.md)。
|
||||||
|
|||||||
@@ -71,3 +71,15 @@ graalvmNative {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Vite owns the HTML and hashed assets; only the controller can serve the page shell.
|
||||||
|
// Build it with `npm ci && npm run build` in frontend/ before invoking Gradle.
|
||||||
|
tasks.named('processResources') {
|
||||||
|
inputs.files(fileTree('frontend/dist'))
|
||||||
|
doFirst {
|
||||||
|
if (!file('frontend/dist/index.html').exists()) {
|
||||||
|
throw new GradleException('Missing UI build: run npm ci && npm run build in frontend/')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
from('frontend/dist') { into 'ui' }
|
||||||
|
}
|
||||||
|
|||||||
@@ -126,3 +126,6 @@ Prometheus 注册器中的 CPU 时间计数器并断言数值有效,避免后
|
|||||||
这是一次本地 smoke 测量,启动耗时含检查器轮询,RSS 不是峰值或负载预算,ELF 大小不等于
|
这是一次本地 smoke 测量,启动耗时含检查器轮询,RSS 不是峰值或负载预算,ELF 大小不等于
|
||||||
运行镜像大小。未验证 AD、MFA、Hydra、目录就绪或 OTLP 后端数据查询,也尚未接入 CI。
|
运行镜像大小。未验证 AD、MFA、Hydra、目录就绪或 OTLP 后端数据查询,也尚未接入 CI。
|
||||||
运行报告生成在 `build/reports/native-smoke/result.json`,不提交运行日志或构建产物。
|
运行报告生成在 `build/reports/native-smoke/result.json`,不提交运行日志或构建产物。
|
||||||
|
|
||||||
|
手写 Native 补丁位于 `META-INF/native-image/top.ddupan.iam/iam-login-manual/`,
|
||||||
|
与 Spring AOT 生成的 `iam-login/` 目录分开,避免 `bootJar` 中同名元数据冲突。
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# 浏览器登录流程原型
|
||||||
|
|
||||||
|
参考 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 权限保持不变。
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## 本地体验
|
||||||
|
|
||||||
|
有 Node 24 和 JDK 25 时:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd frontend
|
||||||
|
npm ci
|
||||||
|
npm run build
|
||||||
|
cd ..
|
||||||
|
./gradlew bootRun --args='--server.address=127.0.0.1 --server.port=18081 --iam.ui-preview.enabled=true'
|
||||||
|
```
|
||||||
|
|
||||||
|
访问 <http://127.0.0.1:18081/preview>。填写称呼,尝试错误演示码,再用 123456 完成。
|
||||||
|
后退链接、刷新、重新体验都走服务端流程。启用 DevTools 的 Network 面板观察 document
|
||||||
|
POST、303、GET;不要勾选 Disable cache,否则无法观察正常的静态资源缓存。
|
||||||
|
|
||||||
|
Docker 开发:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
IAM_DOCKER_USE_SUDO=1 scripts/gradle-in-docker bootRun \
|
||||||
|
--args='--server.address=127.0.0.1 --server.port=18081 --iam.ui-preview.enabled=true'
|
||||||
|
```
|
||||||
|
|
||||||
|
`gradle-in-docker` 先用固定 Node 镜像构建前端,再运行 GraalVM 容器。
|
||||||
|
Gradle 缓存默认 `$HOME/.cache/iam-login/gradle`,npm 缓存默认 `$HOME/.cache/iam-login/npm`;
|
||||||
|
可用 `IAM_GRADLE_CACHE` / `IAM_NPM_CACHE` 指定持久目录。Node 仅参与构建,部署无 Node 服务。
|
||||||
|
直接调用 Gradle 时先构建前端;缺少 `frontend/dist/index.html` 会明确失败。
|
||||||
|
前端 watch 可用 `npm run watch`,修改后仍需让后端重新复制资源并重启;本轮不实现 HMR 桥接。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
```sh
|
||||||
|
IAM_DOCKER_USE_SUDO=1 scripts/gradle-in-docker test testAot nativeTest nativeCompile
|
||||||
|
python3 scripts/native-smoke.py
|
||||||
|
build/native/nativeCompile/iam-login --server.address=127.0.0.1 --server.port=18081 \
|
||||||
|
--iam.ui-preview.enabled=true
|
||||||
|
# 另一个终端,应用保持运行
|
||||||
|
cd frontend
|
||||||
|
npm ci
|
||||||
|
npx playwright install chromium
|
||||||
|
npm run test:browser
|
||||||
|
```
|
||||||
|
|
||||||
|
浏览器测试覆盖原生页面导航、错误重试、局部交互零请求、无 fetch/XHR、静态 JS 缓存、
|
||||||
|
移动端布局、脚本结束标记转义,以及完成预览仍不能访问受保护应用。
|
||||||
|
额外计时使用 Chromium 模拟 60ms 网络延迟、1.5Mbps 下载和四倍 CPU slowdown,
|
||||||
|
用于比较首屏和缓存后的页面切换,不代表真实 LAN、Tailscale 或手机性能。
|
||||||
|
|
||||||
|
## 实现边界
|
||||||
|
|
||||||
|
- 页面壳在 `frontend/index.html`,Vite 构建后作为私有 classpath 资源 `ui/index.html` 打包,
|
||||||
|
不提供静态 index 入口;控制器仅替换一个固定 JSON 数据位置。
|
||||||
|
- Java 使用 JSON 序列化后转义 `<`、`>`、`&` 和 Unicode 行分隔符,避免 `</script>` 逃逸;
|
||||||
|
React 按文本输出动态内容,不通过 HTML 字符串插入用户名。
|
||||||
|
- session 持有演示步骤。表单带 Spring Security CSRF token,缺失被拒绝;
|
||||||
|
非当前步骤的提交拒绝,未知/过期 session 的后续页面回到初始步骤。
|
||||||
|
- 页面与重定向 `no-store`,静态 hash 资源 public/immutable。CSP 不允许内联可执行脚本。
|
||||||
|
- 单 session 仅有一个演示流程,多标签页会共享步骤。正式认证需要独立事务、过期策略、
|
||||||
|
主体与因素绑定;本原型不提供这些保证。
|
||||||
|
- 当前采取整页切换,不提前实现 fetch 优化。后续根据测量选择需要局部更新的步骤。
|
||||||
|
- 首屏依赖 JavaScript,没有 React SSR、Flight、客户端路由、FreeMarker 或模板引擎。
|
||||||
|
关闭 JavaScript 时显示明确提示,不宣称无 JS 可用。
|
||||||
|
|
||||||
|
来源:[Keycloakify 入口](https://github.com/keycloakify/keycloakify-starter/blob/main/src/main.tsx)、
|
||||||
|
[登录表单](https://github.com/keycloakify/keycloakify/blob/main/src/login/pages/Login.tsx)、
|
||||||
|
[Vite 构建](https://vite.dev/guide/build)。
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
@@ -0,0 +1,17 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<meta name="color-scheme" content="light dark" />
|
||||||
|
<title>登录体验预览 · IAM</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<noscript>此预览使用 React 渲染页面,请启用 JavaScript。</noscript>
|
||||||
|
<script id="login-context" type="application/json">
|
||||||
|
__IAM_PAGE_CONTEXT__
|
||||||
|
</script>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1280
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "iam-login-ui",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.0.1",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc --noEmit && vite build",
|
||||||
|
"watch": "vite build --watch",
|
||||||
|
"test:browser": "playwright test"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "19.3.0",
|
||||||
|
"react-dom": "19.3.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"vite": "8.3.1",
|
||||||
|
"typescript": "7.0.2",
|
||||||
|
"@types/react": "^19.2.0",
|
||||||
|
"@types/react-dom": "^19.2.0",
|
||||||
|
"@playwright/test": "1.63.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { defineConfig } from "@playwright/test";
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./tests",
|
||||||
|
use: {
|
||||||
|
baseURL: process.env.IAM_PREVIEW_URL ?? "http://127.0.0.1:18081",
|
||||||
|
headless: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import { useState, useLayoutEffect, type ReactNode } from "react";
|
||||||
|
import "./style.css";
|
||||||
|
|
||||||
|
type PageContext = {
|
||||||
|
step: "identity" | "verification" | "complete";
|
||||||
|
name: string;
|
||||||
|
error: string;
|
||||||
|
action: string;
|
||||||
|
csrf: { name: string; value: string };
|
||||||
|
};
|
||||||
|
|
||||||
|
const context: PageContext = JSON.parse(
|
||||||
|
document.getElementById("login-context")!.textContent!,
|
||||||
|
);
|
||||||
|
|
||||||
|
function Form({ children }: { children: ReactNode }) {
|
||||||
|
const [pending, setPending] = useState(false);
|
||||||
|
return (
|
||||||
|
<form
|
||||||
|
method="post"
|
||||||
|
action={context.action}
|
||||||
|
onSubmit={() => setPending(true)}
|
||||||
|
aria-busy={pending}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="hidden"
|
||||||
|
name={context.csrf.name}
|
||||||
|
value={context.csrf.value}
|
||||||
|
/>
|
||||||
|
{children}
|
||||||
|
<button className="primary" type="submit" disabled={pending}>
|
||||||
|
{pending
|
||||||
|
? "正在继续…"
|
||||||
|
: context.step === "complete"
|
||||||
|
? "重新体验"
|
||||||
|
: "继续"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
useLayoutEffect(() => { performance.mark("iam-page-ready"); }, []);
|
||||||
|
const [showHelp, setShowHelp] = useState(false);
|
||||||
|
return (
|
||||||
|
<main>
|
||||||
|
<header>
|
||||||
|
<a href="/preview" className="brand" aria-label="IAM 登录体验预览">
|
||||||
|
i<span>am</span>
|
||||||
|
<span className="badge">预览</span>
|
||||||
|
</a>
|
||||||
|
</header>
|
||||||
|
<section className="card" aria-labelledby="title">
|
||||||
|
<div className="eyebrow">登录交互原型</div>
|
||||||
|
<ol className="steps" aria-label="当前步骤">
|
||||||
|
{(["identity", "verification", "complete"] as const).map(
|
||||||
|
(step, i) => (
|
||||||
|
<li
|
||||||
|
key={step}
|
||||||
|
aria-current={context.step === step ? "step" : undefined}
|
||||||
|
>
|
||||||
|
<span>{i + 1}</span>
|
||||||
|
{["填写称呼", "模拟验证", "完成"][i]}
|
||||||
|
</li>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</ol>
|
||||||
|
{context.step === "identity" && (
|
||||||
|
<>
|
||||||
|
<h1 id="title">从这里开始</h1>
|
||||||
|
<p className="intro">
|
||||||
|
体验一次完整的页面切换。先告诉我们怎么称呼你。
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{context.step === "verification" && (
|
||||||
|
<>
|
||||||
|
<h1 id="title">你好,{context.name}</h1>
|
||||||
|
<p className="intro">
|
||||||
|
这是第二步页面。输入演示码 <strong>123456</strong>{" "}
|
||||||
|
继续,也可以试试输入错误的演示码。
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{context.step === "complete" && (
|
||||||
|
<>
|
||||||
|
<div className="success" aria-hidden="true">
|
||||||
|
✓
|
||||||
|
</div>
|
||||||
|
<h1 id="title">体验完成</h1>
|
||||||
|
<p className="intro">
|
||||||
|
{context.name}
|
||||||
|
,你已走完页面预览。这没有建立登录身份,也没有向任何应用授权。
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{context.error && (
|
||||||
|
<p className="error" role="alert">
|
||||||
|
{context.error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Form>
|
||||||
|
{context.step === "identity" && (
|
||||||
|
<label>
|
||||||
|
称呼
|
||||||
|
<input
|
||||||
|
name="name"
|
||||||
|
autoComplete="off"
|
||||||
|
autoFocus
|
||||||
|
required
|
||||||
|
maxLength={64}
|
||||||
|
placeholder="例如:小潘"
|
||||||
|
defaultValue={context.name}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{context.step === "verification" && (
|
||||||
|
<label>
|
||||||
|
演示码
|
||||||
|
<input
|
||||||
|
name="code"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="off"
|
||||||
|
autoFocus
|
||||||
|
required
|
||||||
|
maxLength={6}
|
||||||
|
pattern="[0-9]{6}"
|
||||||
|
placeholder="123456"
|
||||||
|
aria-invalid={Boolean(context.error)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</Form>
|
||||||
|
{context.step === "verification" && (
|
||||||
|
<a className="back" href="/preview">
|
||||||
|
返回上一步
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
<div className="help">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="link"
|
||||||
|
aria-expanded={showHelp}
|
||||||
|
onClick={() => setShowHelp(!showHelp)}
|
||||||
|
>
|
||||||
|
这是真实登录吗?
|
||||||
|
</button>
|
||||||
|
{showHelp && (
|
||||||
|
<p>不是。这里仅演示页面交互,请勿输入真实密码或 MFA 验证码。</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<footer>独立 IAM · 页面体验预览</footer>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(<App />);
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
:root {
|
||||||
|
font-family: Inter, "Noto Sans SC", system-ui, sans-serif;
|
||||||
|
color: #182826;
|
||||||
|
background: #f3f5f1;
|
||||||
|
font-synthesis: none;
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
max-width: 520px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 40px 20px 28px;
|
||||||
|
}
|
||||||
|
header {
|
||||||
|
margin-bottom: 40px;
|
||||||
|
}
|
||||||
|
.brand {
|
||||||
|
font-size: 32px;
|
||||||
|
font-weight: 750;
|
||||||
|
letter-spacing: -2px;
|
||||||
|
color: #285448;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.brand > span:first-child {
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
.badge {
|
||||||
|
font-size: 11px;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
vertical-align: middle;
|
||||||
|
margin-left: 14px;
|
||||||
|
padding: 5px 8px;
|
||||||
|
border: 1px solid #b7c9be;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #dce4dd;
|
||||||
|
border-radius: 18px;
|
||||||
|
padding: 36px;
|
||||||
|
box-shadow: 0 12px 40px #173f2510;
|
||||||
|
}
|
||||||
|
.eyebrow {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #60746a;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
}
|
||||||
|
.steps {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0;
|
||||||
|
list-style: none;
|
||||||
|
margin: 25px 0 32px;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.steps li {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #718078;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
}
|
||||||
|
.steps li span {
|
||||||
|
display: inline-grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 23px;
|
||||||
|
height: 23px;
|
||||||
|
border: 1px solid #ccd7ce;
|
||||||
|
border-radius: 50%;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.steps [aria-current] {
|
||||||
|
color: #215542;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.steps [aria-current] span {
|
||||||
|
background: #215542;
|
||||||
|
color: white;
|
||||||
|
border-color: #215542;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: 27px;
|
||||||
|
letter-spacing: -0.5px;
|
||||||
|
line-height: 1.35;
|
||||||
|
margin: 0 0 12px;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.intro {
|
||||||
|
font-size: 14px;
|
||||||
|
color: #60716a;
|
||||||
|
line-height: 1.8;
|
||||||
|
margin: 0 0 25px;
|
||||||
|
}
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
input:not([type="hidden"]) {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
border: 1px solid #bdccc1;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 13px 14px;
|
||||||
|
margin: 9px 0 22px;
|
||||||
|
font: inherit;
|
||||||
|
color: inherit;
|
||||||
|
background: #fff;
|
||||||
|
}
|
||||||
|
input:focus {
|
||||||
|
outline: 3px solid #a9cbbc;
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.primary {
|
||||||
|
width: 100%;
|
||||||
|
border: 0;
|
||||||
|
background: #245b47;
|
||||||
|
color: #fff;
|
||||||
|
font-weight: 600;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 13px;
|
||||||
|
}
|
||||||
|
.primary:hover {
|
||||||
|
background: #194734;
|
||||||
|
}
|
||||||
|
.primary:disabled {
|
||||||
|
opacity: 0.65;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
.error {
|
||||||
|
color: #9e302b;
|
||||||
|
background: #fff0ed;
|
||||||
|
padding: 12px;
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
.back {
|
||||||
|
display: block;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 13px;
|
||||||
|
margin-top: 18px;
|
||||||
|
color: #476a58;
|
||||||
|
}
|
||||||
|
.help {
|
||||||
|
border-top: 1px solid #e5ebe6;
|
||||||
|
margin-top: 28px;
|
||||||
|
padding-top: 20px;
|
||||||
|
}
|
||||||
|
.link {
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
color: #5b7064;
|
||||||
|
padding: 0;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.help p {
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.8;
|
||||||
|
color: #6a756e;
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
footer {
|
||||||
|
text-align: center;
|
||||||
|
color: #7c887e;
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 28px;
|
||||||
|
}
|
||||||
|
.success {
|
||||||
|
color: #245b47;
|
||||||
|
font-size: 30px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
a:focus-visible,
|
||||||
|
button:focus-visible {
|
||||||
|
outline: 3px solid #a9cbbc;
|
||||||
|
outline-offset: 3px;
|
||||||
|
}
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
main {
|
||||||
|
padding-top: 24px;
|
||||||
|
}
|
||||||
|
header {
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
padding: 26px 22px;
|
||||||
|
}
|
||||||
|
.steps {
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
.steps li {
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
background: #14221c;
|
||||||
|
color: #edf4ee;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
background: #1e3027;
|
||||||
|
border-color: #344b3d;
|
||||||
|
}
|
||||||
|
.brand,
|
||||||
|
.steps [aria-current],
|
||||||
|
.success {
|
||||||
|
color: #b9ddc8;
|
||||||
|
}
|
||||||
|
.intro,
|
||||||
|
.eyebrow,
|
||||||
|
.help p,
|
||||||
|
.link,
|
||||||
|
.back {
|
||||||
|
color: #acbfb2;
|
||||||
|
}
|
||||||
|
.steps li {
|
||||||
|
color: #98aa9e;
|
||||||
|
}
|
||||||
|
input:not([type="hidden"]) {
|
||||||
|
background: #18271f;
|
||||||
|
border-color: #526657;
|
||||||
|
}
|
||||||
|
.help {
|
||||||
|
border-color: #3a4d40;
|
||||||
|
}
|
||||||
|
.error {
|
||||||
|
background: #492b29;
|
||||||
|
color: #ffc3b9;
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { test, expect } from "@playwright/test";
|
||||||
|
|
||||||
|
test("原生 POST 逐页导航,内联上下文,浏览器缓存静态资源", async ({ page }) => {
|
||||||
|
const xhr: string[] = [];
|
||||||
|
const posts: string[] = [];
|
||||||
|
const errors: string[] = [];
|
||||||
|
page.on("pageerror", (e) => errors.push(e.message));
|
||||||
|
page.on("request", (req) => {
|
||||||
|
if (["fetch", "xhr"].includes(req.resourceType())) xhr.push(req.url());
|
||||||
|
if (req.method() === "POST" && req.isNavigationRequest())
|
||||||
|
posts.push(req.url());
|
||||||
|
});
|
||||||
|
await page.goto("/preview");
|
||||||
|
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
|
||||||
|
const scriptUrl = await page.locator("script[src]").getAttribute("src");
|
||||||
|
await page.getByRole("button", { name: "这是真实登录吗?" }).click();
|
||||||
|
await expect(page.getByText("不是。这里仅演示页面交互")).toBeVisible();
|
||||||
|
await page.getByLabel("称呼").fill("预览用户");
|
||||||
|
await page.getByRole("button", { name: "继续", exact: true }).click();
|
||||||
|
await expect(page).toHaveURL(/\/preview\/verify$/);
|
||||||
|
await expect(
|
||||||
|
page.getByRole("heading", { name: "你好,预览用户" }),
|
||||||
|
).toBeVisible();
|
||||||
|
await page.getByLabel("演示码").fill("000000");
|
||||||
|
await page.getByRole("button", { name: "继续", exact: true }).click();
|
||||||
|
await expect(page.getByRole("alert")).toContainText("演示码不正确");
|
||||||
|
await page.getByLabel("演示码").fill("123456");
|
||||||
|
await page.getByRole("button", { name: "继续", exact: true }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "体验完成" })).toBeVisible();
|
||||||
|
expect(posts).toHaveLength(3);
|
||||||
|
expect(xhr).toEqual([]);
|
||||||
|
expect(errors).toEqual([]);
|
||||||
|
const timing = await page.evaluate(() => ({
|
||||||
|
navigation: performance
|
||||||
|
.getEntriesByType("navigation")
|
||||||
|
.map((e) => e.toJSON()),
|
||||||
|
resources: performance.getEntriesByType("resource").map((e) => e.toJSON()),
|
||||||
|
}));
|
||||||
|
const script = timing.resources.find((r) => r.name.endsWith(scriptUrl!));
|
||||||
|
expect(script?.transferSize).toBe(0);
|
||||||
|
await test
|
||||||
|
.info()
|
||||||
|
.attach("navigation-and-cache.json", {
|
||||||
|
body: JSON.stringify(timing, null, 2),
|
||||||
|
contentType: "application/json",
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
(
|
||||||
|
await page.request.get("/", { headers: { Accept: "application/json" } })
|
||||||
|
).status(),
|
||||||
|
).toBe(401);
|
||||||
|
await page.getByRole("button", { name: "重新体验" }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("移动端与脚本结束标记作为纯文本显示", async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 390, height: 844 });
|
||||||
|
await page.goto("/preview");
|
||||||
|
const name = "</script><script>window.__injected=1</script>";
|
||||||
|
await page.getByLabel("称呼").fill(name);
|
||||||
|
await page.getByRole("button", { name: "继续", exact: true }).click();
|
||||||
|
await expect(page.getByRole("heading")).toHaveText(`你好,${name}`);
|
||||||
|
expect(
|
||||||
|
await page.evaluate(() => Reflect.get(window, "__injected")),
|
||||||
|
).toBeUndefined();
|
||||||
|
expect(
|
||||||
|
await page.evaluate(
|
||||||
|
() => document.documentElement.scrollWidth <= innerWidth,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
await page.screenshot({ path: "test-results/mobile.png", fullPage: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
test("受限网络下首屏和缓存后页面切换计时", async ({ page, context }) => {
|
||||||
|
const cdp = await context.newCDPSession(page);
|
||||||
|
await cdp.send("Network.enable");
|
||||||
|
await cdp.send("Network.emulateNetworkConditions", {
|
||||||
|
offline: false, latency: 60, downloadThroughput: 1_500_000 / 8,
|
||||||
|
uploadThroughput: 750_000 / 8,
|
||||||
|
});
|
||||||
|
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
|
||||||
|
await page.goto("/preview");
|
||||||
|
await expect(page.getByRole("heading", { name: "从这里开始" })).toBeVisible();
|
||||||
|
const cold = await page.evaluate(() => performance.getEntriesByName("iam-page-ready")[0].startTime);
|
||||||
|
await page.getByLabel("称呼").fill("计时体验");
|
||||||
|
const start = performance.now();
|
||||||
|
await page.getByRole("button", { name: "继续", exact: true }).click();
|
||||||
|
await expect(page.getByRole("heading", { name: "你好,计时体验" })).toBeVisible();
|
||||||
|
const warm = performance.now() - start;
|
||||||
|
const result = { network_latency_ms: 60, download_mbps: 1.5, cpu_slowdown: 4,
|
||||||
|
cold_navigation_to_react_commit_ms: Math.round(cold), warm_click_to_visible_ms: Math.round(warm) };
|
||||||
|
console.log(JSON.stringify(result));
|
||||||
|
await test.info().attach("timing.json", { body: JSON.stringify(result, null, 2), contentType: "application/json" });
|
||||||
|
});
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"skipLibCheck": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
base: "/",
|
||||||
|
build: { outDir: "dist", emptyOutDir: true },
|
||||||
|
});
|
||||||
Executable
+16
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
repo_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
|
||||||
|
cache_dir=${IAM_NPM_CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/iam-login/npm}
|
||||||
|
mkdir -p -- "$cache_dir"
|
||||||
|
cache_dir=$(cd -- "$cache_dir" && pwd)
|
||||||
|
docker_cmd=(docker)
|
||||||
|
if [[ ${IAM_DOCKER_USE_SUDO:-0} == 1 ]]; then
|
||||||
|
docker_cmd=(sudo -n docker)
|
||||||
|
fi
|
||||||
|
exec "${docker_cmd[@]}" run --rm --network host \
|
||||||
|
--cpus 2 --memory 1g --user "$(id -u):$(id -g)" \
|
||||||
|
-e HOME=/npm -e npm_config_cache=/npm \
|
||||||
|
-v "$cache_dir:/npm" -v "$repo_root:/workspace" \
|
||||||
|
-w /workspace/frontend node@sha256:d8e448a56fc63242f70026718378bd4b00f8c82e78d20eefb199224a4d8e33d8 \
|
||||||
|
sh -c 'npm ci --no-audit --no-fund && npm run build'
|
||||||
@@ -13,6 +13,8 @@ if (($# == 0)); then
|
|||||||
set -- test
|
set -- test
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
"$repo_root/scripts/frontend-in-docker"
|
||||||
|
|
||||||
# Linux host networking is needed for Testcontainers' published ports.
|
# Linux host networking is needed for Testcontainers' published ports.
|
||||||
exec "${docker_cmd[@]}" run --rm --network host \
|
exec "${docker_cmd[@]}" run --rm --network host \
|
||||||
--cpus "${IAM_BUILD_CPUS:-4}" --memory "${IAM_BUILD_MEMORY:-8g}" \
|
--cpus "${IAM_BUILD_CPUS:-4}" --memory "${IAM_BUILD_MEMORY:-8g}" \
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ def main():
|
|||||||
ready_seconds = time.monotonic() - started
|
ready_seconds = time.monotonic() - started
|
||||||
assert request('/actuator/prometheus')[0] == 401, 'Anonymous metrics must be rejected'
|
assert request('/actuator/prometheus')[0] == 401, 'Anonymous metrics must be rejected'
|
||||||
assert request('/')[0] == 401, 'Anonymous application access must be rejected'
|
assert request('/')[0] == 401, 'Anonymous application access must be rejected'
|
||||||
|
assert request('/preview')[0] == 404, 'UI preview must be disabled by default'
|
||||||
status, before = request('/actuator/prometheus', authenticated=True)
|
status, before = request('/actuator/prometheus', authenticated=True)
|
||||||
assert status == 200, 'Authenticated Prometheus scrape failed'
|
assert status == 200, 'Authenticated Prometheus scrape failed'
|
||||||
for _ in range(3):
|
for _ in range(3):
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package top.ddupan.iam.login.preview;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import org.springframework.aot.hint.RuntimeHints;
|
||||||
|
import org.springframework.aot.hint.RuntimeHintsRegistrar;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.annotation.ImportRuntimeHints;
|
||||||
|
import org.springframework.http.CacheControl;
|
||||||
|
import org.springframework.security.config.Customizer;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.web.SecurityFilterChain;
|
||||||
|
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||||
|
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||||
|
|
||||||
|
@Configuration(proxyBeanMethods = false)
|
||||||
|
@ImportRuntimeHints(PreviewConfiguration.Resources.class)
|
||||||
|
class PreviewConfiguration implements WebMvcConfigurer {
|
||||||
|
@Bean
|
||||||
|
SecurityFilterChain security(HttpSecurity http) throws Exception {
|
||||||
|
return http.authorizeHttpRequests(auth -> auth
|
||||||
|
.requestMatchers("/error", "/preview", "/preview/**", "/assets/**", "/actuator/health/**").permitAll()
|
||||||
|
.anyRequest().authenticated())
|
||||||
|
.formLogin(Customizer.withDefaults())
|
||||||
|
.httpBasic(Customizer.withDefaults())
|
||||||
|
.headers(headers -> headers.contentSecurityPolicy(csp -> csp.policyDirectives(
|
||||||
|
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
|
||||||
|
+ "object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||||
|
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/ui/assets/")
|
||||||
|
.setCacheControl(CacheControl.maxAge(Duration.ofDays(365)).cachePublic().immutable());
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Resources implements RuntimeHintsRegistrar {
|
||||||
|
@Override
|
||||||
|
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
|
||||||
|
hints.resources().registerPattern("ui/**");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
package top.ddupan.iam.login.preview;
|
||||||
|
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpSession;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Map;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.core.io.ClassPathResource;
|
||||||
|
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;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
/** An isolated UI experiment. It never creates an authenticated SecurityContext. */
|
||||||
|
@RestController
|
||||||
|
class PreviewController {
|
||||||
|
private static final String STATE = PreviewController.class.getName() + ".state";
|
||||||
|
private static final String SLOT = "__IAM_PAGE_CONTEXT__";
|
||||||
|
private final boolean enabled;
|
||||||
|
private final String shell;
|
||||||
|
private final JsonMapper json = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
PreviewController(@Value("${iam.ui-preview.enabled:false}") boolean enabled) throws IOException {
|
||||||
|
this.enabled = enabled;
|
||||||
|
this.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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GetMapping(value = {"/preview", "/preview/verify", "/preview/complete"}, produces = MediaType.TEXT_HTML_VALUE)
|
||||||
|
ResponseEntity<String> page(HttpServletRequest request, CsrfToken csrf) {
|
||||||
|
requireEnabled();
|
||||||
|
var session = request.getSession();
|
||||||
|
synchronized (session) {
|
||||||
|
var state = state(session);
|
||||||
|
var path = request.getRequestURI().substring(request.getContextPath().length());
|
||||||
|
if (path.equals("/preview")) {
|
||||||
|
if (!state.step.equals("identity")) state.error = "";
|
||||||
|
state.step = "identity";
|
||||||
|
} else if (!path.equals(pathFor(state.step))) {
|
||||||
|
return redirect(pathFor(state.step));
|
||||||
|
}
|
||||||
|
var context = Map.of("step", state.step, "name", state.name, "error", state.error,
|
||||||
|
"action", switch (state.step) {
|
||||||
|
case "identity" -> "/preview/identify";
|
||||||
|
case "verification" -> "/preview/verify";
|
||||||
|
default -> "/preview/restart";
|
||||||
|
}, "csrf", Map.of("name", csrf.getParameterName(), "value", csrf.getToken()));
|
||||||
|
return ResponseEntity.ok().header("Cache-Control", "no-store")
|
||||||
|
.contentType(MediaType.TEXT_HTML).body(shell.replace(SLOT, htmlSafeJson(context)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/preview/identify")
|
||||||
|
ResponseEntity<String> identify(@RequestParam(defaultValue = "") String name, HttpSession session) {
|
||||||
|
requireEnabled();
|
||||||
|
synchronized (session) {
|
||||||
|
var state = state(session);
|
||||||
|
requireStep(state, "identity");
|
||||||
|
if (name.isBlank() || name.length() > 64) {
|
||||||
|
state.error = "称呼须为 1 到 64 个字符。";
|
||||||
|
return redirect("/preview");
|
||||||
|
}
|
||||||
|
state.name = name.strip();
|
||||||
|
state.error = "";
|
||||||
|
state.step = "verification";
|
||||||
|
return redirect("/preview/verify");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/preview/verify")
|
||||||
|
ResponseEntity<String> verify(@RequestParam(defaultValue = "") String code, HttpSession session) {
|
||||||
|
requireEnabled();
|
||||||
|
synchronized (session) {
|
||||||
|
var state = state(session);
|
||||||
|
requireStep(state, "verification");
|
||||||
|
if (!code.equals("123456")) {
|
||||||
|
state.error = "演示码不正确,请输入 123456。";
|
||||||
|
return redirect("/preview/verify");
|
||||||
|
}
|
||||||
|
state.error = "";
|
||||||
|
state.step = "complete";
|
||||||
|
return redirect("/preview/complete");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/preview/restart")
|
||||||
|
ResponseEntity<String> restart(HttpSession session) {
|
||||||
|
requireEnabled();
|
||||||
|
synchronized (session) {
|
||||||
|
session.removeAttribute(STATE);
|
||||||
|
return redirect("/preview");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requireEnabled() {
|
||||||
|
if (!enabled) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void requireStep(State state, String step) {
|
||||||
|
if (!state.step.equals(step)) throw new ResponseStatusException(HttpStatus.CONFLICT, "页面已过期,请重新打开预览");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static State state(HttpSession session) {
|
||||||
|
var state = (State) session.getAttribute(STATE);
|
||||||
|
if (state == null) {
|
||||||
|
state = new State();
|
||||||
|
session.setAttribute(STATE, state);
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String pathFor(String step) {
|
||||||
|
return switch (step) {
|
||||||
|
case "verification" -> "/preview/verify";
|
||||||
|
case "complete" -> "/preview/complete";
|
||||||
|
default -> "/preview";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ResponseEntity<String> redirect(String path) {
|
||||||
|
return ResponseEntity.status(HttpStatus.SEE_OTHER).header("Location", path)
|
||||||
|
.header("Cache-Control", "no-store").build();
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
String step = "identity";
|
||||||
|
String name = "";
|
||||||
|
String error = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package top.ddupan.iam.login;
|
package top.ddupan.iam.login;
|
||||||
|
|
||||||
import io.micrometer.core.instrument.MeterRegistry;
|
import io.micrometer.core.instrument.MeterRegistry;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
import org.springframework.beans.factory.annotation.Qualifier;
|
||||||
@@ -10,42 +11,114 @@ import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.OtlpLog
|
|||||||
import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.Transport;
|
import org.springframework.boot.opentelemetry.autoconfigure.logging.otlp.Transport;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
|
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.grafana.LgtmStackContainer;
|
||||||
import org.testcontainers.junit.jupiter.Container;
|
import org.testcontainers.junit.jupiter.Container;
|
||||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||||
import org.testcontainers.utility.DockerImageName;
|
import org.testcontainers.utility.DockerImageName;
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||||
|
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||||
|
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||||
|
|
||||||
@SpringBootTest
|
@SpringBootTest(properties = "iam.ui-preview.enabled=true")
|
||||||
|
@AutoConfigureMockMvc
|
||||||
@AutoConfigureMetrics
|
@AutoConfigureMetrics
|
||||||
@AutoConfigureTracing
|
@AutoConfigureTracing
|
||||||
@Testcontainers
|
@Testcontainers
|
||||||
class IamLoginApplicationTests {
|
class IamLoginApplicationTests {
|
||||||
|
|
||||||
// Field-based service connections are recreated by the test context in AOT mode.
|
// Field-based service connections are recreated by the test context in AOT mode.
|
||||||
@Container
|
@Container
|
||||||
@ServiceConnection
|
@ServiceConnection
|
||||||
static final LgtmStackContainer grafanaLgtm = new LgtmStackContainer(
|
static final LgtmStackContainer grafanaLgtm = new LgtmStackContainer(
|
||||||
DockerImageName.parse(TestcontainersConfiguration.LGTM_IMAGE));
|
DockerImageName.parse(TestcontainersConfiguration.LGTM_IMAGE));
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
OtlpLoggingConnectionDetails loggingConnectionDetails;
|
OtlpLoggingConnectionDetails loggingConnectionDetails;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@Qualifier("prometheusMeterRegistry")
|
@Qualifier("prometheusMeterRegistry")
|
||||||
MeterRegistry prometheus;
|
MeterRegistry prometheus;
|
||||||
|
|
||||||
@Test
|
@Autowired
|
||||||
void processCpuTimeCanBeRead() {
|
MockMvc mvc;
|
||||||
assertThat(prometheus.get("process.cpu.time").functionCounter().count()).isFinite().isNotNegative();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void loggingConnectionUsesRunningContainer() {
|
void previewHasInlineContextAndNoCache() throws Exception {
|
||||||
assertThat(grafanaLgtm.isRunning()).isTrue();
|
var result = mvc.perform(get("/preview"))
|
||||||
assertThat(loggingConnectionDetails.getUrl(Transport.HTTP))
|
.andExpect(status().isOk())
|
||||||
.isEqualTo(grafanaLgtm.getOtlpHttpUrl() + "/v1/logs");
|
.andExpect(header().string("Cache-Control", "no-store"))
|
||||||
}
|
.andReturn();
|
||||||
|
assertThat(result.getResponse().getContentAsString()).contains("login-context", "identity", "_csrf")
|
||||||
|
.doesNotContain("__IAM_PAGE_CONTEXT__");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void previewRejectsMissingCsrf() throws Exception {
|
||||||
|
mvc.perform(post("/preview/identify").param("name", "测试"))
|
||||||
|
.andExpect(status().isForbidden());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void previewChecksStepsAndEscapesScriptEndTags() throws Exception {
|
||||||
|
var session = new MockHttpSession();
|
||||||
|
mvc.perform(post("/preview/verify")
|
||||||
|
.session(session).with(csrf())
|
||||||
|
.param("code", "123456"))
|
||||||
|
.andExpect(status().isConflict());
|
||||||
|
mvc.perform(post("/preview/identify")
|
||||||
|
.session(session).with(csrf())
|
||||||
|
.param("name", "</script><script>alert(1)</script>"))
|
||||||
|
.andExpect(status().isSeeOther());
|
||||||
|
var html = mvc.perform(get("/preview/verify").session(session))
|
||||||
|
.andExpect(status().isOk()).andReturn()
|
||||||
|
.getResponse().getContentAsString();
|
||||||
|
assertThat(html).doesNotContain("</script><script>alert(1)</script>")
|
||||||
|
.contains("\\u003c/script\\u003e");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void previewRetriesAndCompletesWithoutAuthenticating() throws Exception {
|
||||||
|
var session = new MockHttpSession();
|
||||||
|
mvc.perform(post("/preview/identify")
|
||||||
|
.session(session).with(csrf())
|
||||||
|
.param("name", "测试"))
|
||||||
|
.andExpect(redirectedUrl("/preview/verify"));
|
||||||
|
mvc.perform(post("/preview/verify")
|
||||||
|
.session(session).with(csrf())
|
||||||
|
.param("code", "000000"))
|
||||||
|
.andExpect(redirectedUrl("/preview/verify"));
|
||||||
|
var retry = mvc.perform(get("/preview/verify").session(session))
|
||||||
|
.andReturn().getResponse();
|
||||||
|
assertThat(retry.getContentAsString(StandardCharsets.UTF_8)).contains("演示码不正确");
|
||||||
|
mvc.perform(post("/preview/verify")
|
||||||
|
.session(session).with(csrf())
|
||||||
|
.param("code", "123456"))
|
||||||
|
.andExpect(redirectedUrl("/preview/complete"));
|
||||||
|
mvc.perform(get("/").session(session)
|
||||||
|
.accept(MediaType.APPLICATION_JSON))
|
||||||
|
.andExpect(status().isUnauthorized());
|
||||||
|
assertThat(session.getAttribute("SPRING_SECURITY_CONTEXT")).isNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void processCpuTimeCanBeRead() {
|
||||||
|
assertThat(prometheus.get("process.cpu.time").functionCounter().count()).isFinite().isNotNegative();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loggingConnectionUsesRunningContainer() {
|
||||||
|
assertThat(grafanaLgtm.isRunning()).isTrue();
|
||||||
|
assertThat(loggingConnectionDetails.getUrl(Transport.HTTP))
|
||||||
|
.isEqualTo(grafanaLgtm.getOtlpHttpUrl() + "/v1/logs");
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user