feat(auth): 接入 Casdoor 登录并让前端持有本服务会话
管理台可以密码登录、按角色进入,并把 Watchman 会话 token 交给浏览器。HXOPS 真实跳转仍未联调。 Co-authored-by: Cursor <cursoragent@cursor.com>
No files matched your search
@@ -24,3 +24,16 @@ CELERY_BROKER_URL_DOCKER=amqp://guest:guest@rabbitmq:5672//
|
||||
DATABASE_URL_DOCKER=postgresql+psycopg://watchman_app:CHANGE-ME@host.docker.internal:5432/watchman
|
||||
DATABASE_MIGRATOR_URL_DOCKER=postgresql+psycopg://watchman_migrator:CHANGE-ME@host.docker.internal:5432/watchman
|
||||
COMPOSE_POSTGRES_PASSWORD=CHANGE-ME
|
||||
|
||||
# 4. Security, identity. Real values belong in gitignored .env.local only.
|
||||
CASDOOR_ENDPOINT=http://CHANGE-ME
|
||||
CASDOOR_CLIENT_ID=CHANGE-ME
|
||||
CASDOOR_CLIENT_SECRET=CHANGE-ME
|
||||
CASDOOR_ORGANIZATION=CHANGE-ME
|
||||
CASDOOR_APPLICATION=CHANGE-ME
|
||||
CASDOOR_CERTIFICATE=CHANGE-ME
|
||||
CASDOOR_ISSUER=http://CHANGE-ME
|
||||
CASDOOR_AUDIENCE=CHANGE-ME
|
||||
HXOPS_SSO_ISSUER=https://CHANGE-ME
|
||||
HXOPS_SSO_AUDIENCE=CHANGE-ME
|
||||
HXOPS_SSO_PUBLIC_KEY=CHANGE-ME
|
||||
@@ -0,0 +1,143 @@
|
||||
# Task Context Pack
|
||||
|
||||
## Task Goal
|
||||
|
||||
M02 用 Casdoor 做身份和三个粗角色。当前只实现 S2:可替换的 Casdoor 端口、服务端会话、密码登录、当前用户和退出。不保护平台写接口,不接收 HXOPS 断言,不做界面。
|
||||
|
||||
## Knowledge Posture
|
||||
|
||||
- Mode: standard
|
||||
- Maturity: L1
|
||||
|
||||
## Current Slice Or Group
|
||||
|
||||
S2 会话与密码登录。用户已确认继续。S1 已复审 PASS。S3 及以后未批准开做。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- Recommended: strict
|
||||
- Selected: balanced
|
||||
- finalApprovalRequired: true
|
||||
- Policy Notes: S2 是 high-risk、risk_score 4、critic-required。做完必须停,不能续跑 S3。S1 的验签模块保持不动,除非 S2 必须调用它且不改变其拒绝规则。
|
||||
|
||||
## Bugfix Context
|
||||
|
||||
不适用。
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-17/m02-auth/requirement.md`
|
||||
|
||||
## Implementation Source
|
||||
|
||||
`.task/2026-11-17/m02-auth/implementation-plan.md` 的 Slice 2
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
`services/watchman` 内新建 `watchman.auth` 校验模块和对应测试。
|
||||
|
||||
## Loaded Context
|
||||
|
||||
### Global Rules
|
||||
|
||||
AGENTS.md 的安全底线:秘密不入库、不进日志。D19 已确认授权模型。
|
||||
|
||||
### Knowledge Map Matches
|
||||
|
||||
无单独认证知识区。以任务需求和 M01 当前代码为准。
|
||||
|
||||
### Path-Proximity Rules
|
||||
|
||||
`services/watchman` 下没有 `MODULE_RULES.md`。
|
||||
|
||||
### Excluded Context
|
||||
|
||||
未加载 Cron、报警、企微、syops 实现源码。S1 不读 `.env.local`。
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- `standards://api/api-envelope?version=1.1.0`(本切片不新增 HTTP)
|
||||
- `standards://security/red-line?version=1.1.0`
|
||||
- `standards://engineering/code-comments?version=1.1.1`(实现时检索原文)
|
||||
- D14、D19
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- M02 requirement 与 implementation plan
|
||||
- `docs/decisions.md` 的 D19、O10
|
||||
|
||||
## Execution Mode
|
||||
|
||||
- Mode: sequential
|
||||
- Current Slice Or Group: S2
|
||||
- Parallel Members: 无
|
||||
- Fallback Order: 2
|
||||
- Shared Files: `app.py`、`config.py`、迁移目录
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 不并行
|
||||
- Validation Level: slice
|
||||
|
||||
## Execution Chain
|
||||
|
||||
用户确认 S2 → critic → 只实现 S2 → 跑 pytest → 异系列审查 → 停在 S3 之前。
|
||||
|
||||
## Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/auth/`
|
||||
- `services/watchman/src/watchman/api/` 的登录路由和注册
|
||||
- `services/watchman/src/watchman/core/config.py`
|
||||
- `services/watchman/src/watchman/models/` 与 `services/watchman/migrations/`,仅限会话表
|
||||
- `services/watchman/tests/` 的登录与会话测试
|
||||
- `.env.example` 已有占位,不要写入真实值
|
||||
|
||||
## Forbidden Modification Scope
|
||||
|
||||
- 前端页面、平台写接口的授权、HXOPS 断言
|
||||
- `D:\PROJECT\syops` 的任何写入
|
||||
- 读取、打印或复制 `.env.local` 里的密钥
|
||||
- 新的直接依赖和 `uv.lock` 改写
|
||||
- 角色表、用户授权表、密码哈希
|
||||
|
||||
## Key Existing Classes Or Entrypoints
|
||||
|
||||
- S1:`watchman.auth.token_verifier.verify_rs256_token`
|
||||
- `UnauthorizedError` 为 41000,`ServiceUnavailableError` 为 503 且 `retryable`
|
||||
- 信封:`watchman.core.response.success_body`
|
||||
- RLS:`migrations/versions/20261117_0001_platform_rls.py`,`set_tenant` 只用服务端 `WATCHMAN_TENANT_ID`
|
||||
- 路由注册在 `watchman.api.app.create_app`
|
||||
|
||||
## Required Behavior
|
||||
|
||||
密码登录通过可注入端口。成功写入会话并保存端口返回的角色,失败 41000。端口未配置或不可用返回 503,且不建立会话。当前用户不返回秘密。退出后同一会话不能再读到当前用户。健康检查仍匿名。租户只来自服务端配置。不保存密码、client secret 和 Casdoor token。
|
||||
|
||||
## Non-goals
|
||||
|
||||
平台写接口收口、对象检查、HXOPS 断言、登录页、真实 Casdoor 网络测试。
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
1. 增加带 RLS 的会话表和迁移,字段只包括身份主体、签发方、显示名、角色快照、角色确认时间、过期时间、服务端租户。
|
||||
2. 登录、当前用户、退出。Casdoor 调用可替换,测试不访问网络。
|
||||
3. 断言响应里没有密码、secret 和 token。
|
||||
|
||||
## Validation Commands
|
||||
|
||||
`uv run pytest services/watchman/tests -q`
|
||||
|
||||
## Assumptions
|
||||
|
||||
- 会话 8 小时。角色快照可以写入,但 5 分钟后的重新确认属于 S3。
|
||||
- 浏览器会话用 HttpOnly cookie。本地 HTTP 开发不强制 Secure。
|
||||
- 真实 Casdoor 客户端可以写,但测试必须注入替身,不能读取 `.env.local`。
|
||||
|
||||
## Risks
|
||||
|
||||
- 迁移一旦执行,回滚要有 down。
|
||||
- 测试若加载本机 `.env.local`,可能误打真实 Casdoor。
|
||||
- S2 结束时平台写接口仍然匿名可写。
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
- critic 判定不能安全开做时停止。
|
||||
- S2 审查完成或需要用户决定时停止。
|
||||
- 不开始 S3。
|
||||
@@ -0,0 +1,398 @@
|
||||
# M02 统一登录与权限 Implementation Plan
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-17/m02-auth/requirement.md`
|
||||
|
||||
## Scope Summary
|
||||
|
||||
按已冻结需求接入 Casdoor 身份、三个粗角色和 Watchman 会话,收口 M01 平台写接口,并加上登录壳。不建角色表,不改 syops,不实现业务模块。
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
Watchman 认证与现有平台 API、管理台薄壳。Casdoor 仅作为外部身份与角色来源。HXOPS 只作为短时断言的签发方,本仓库实现接收端。
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- 本任务 `gatePolicy.selected=balanced`,`finalApprovalRequired=true`。分析到编码仍须用户确认。
|
||||
- `high-risk`、`boundary-sensitive`、critic 要求、`risk_score >= 4` 的切片完成后必须停。balanced 不能跳过这些停点。
|
||||
- `standards://api/api-envelope?version=1.1.0`
|
||||
- `standards://api/error-handling?version=1.1.1`
|
||||
- `standards://api/permission-nodes?version=1.0.0`
|
||||
- `standards://security/red-line?version=1.1.0`
|
||||
- `standards://frontend/frontend-stack?version=2.1.0`
|
||||
- `standards://frontend/element-plus?version=1.0.1`
|
||||
- Watchman D01、D12、D13、D14、D19。
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `.task/2026-11-17/m02-auth/requirement.md`
|
||||
- `docs/tasks/INDEX.md` 的 M02
|
||||
- `docs/decisions.md`
|
||||
- syops 认证说明只作对照
|
||||
|
||||
## Global Forbidden Scope
|
||||
|
||||
- `D:\PROJECT\syops` 的任何写入,包括为了打通入口而改 HXOPS。
|
||||
- 复制 syops `.env.dev` 的密钥、client id 或 audience 进仓库、文档、测试夹具。
|
||||
- 用户表、角色表、授权管理页、密码哈希。
|
||||
- 数据源、查询、规则、报警、通知、场景、AI。
|
||||
- Redis、vben5、把健康检查改成必须登录。
|
||||
- 未确认就新增三枚以外的权限点。
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
- Complexity: complex
|
||||
- Default Execution: sequential
|
||||
- Parallel Execution: not-needed
|
||||
- Fallback Execution: sequential
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 认证切片按 S1 到 S6 的顺序写同一服务包。不并行。
|
||||
|
||||
selected `balanced` 对 S1–S5 不自动续跑:这些切片是 `high-risk` 或 `boundary-sensitive`,且要求 critic。S6 虽是 `simple`,也要等 S5 的停点结束之后再开始。
|
||||
|
||||
## Slice Dependency Graph
|
||||
|
||||
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| S1 令牌校验 | 无 | 无 | 1 | 无 | 主 Agent | low |
|
||||
| S2 会话与密码登录 | S1 | 无 | 2 | `app.py`、`config.py` | 主 Agent | high |
|
||||
| S3 角色收口 | S2 | 无 | 3 | 平台路由 | 主 Agent | high |
|
||||
| S4 HXOPS 断言 | S2、S3 | 无 | 4 | `app.py`、会话 | 主 Agent | high |
|
||||
| S5 登录壳 | S4 | 无 | 5 | 前端 API 客户端 | 主 Agent | medium |
|
||||
| S6 文档与示例配置 | S5 | 无 | 6 | 任务卡、runbook、`.env.example` | 主 Agent | low |
|
||||
|
||||
## Implementation Slices
|
||||
|
||||
### Slice 1: 令牌校验
|
||||
|
||||
#### Goal
|
||||
|
||||
本地密钥下拒绝坏签名、错误 issuer、错误 audience 和过期令牌。这一步不发 HTTP 登录,不访问真实 Casdoor。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/auth/` 中的校验模块
|
||||
- `services/watchman/tests/` 中对应该校验的测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 路由、迁移、前端、`.env.local`、syops
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: 无
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S2–S6
|
||||
- Fallback Order: 1
|
||||
- Shared Files: 无
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: security-logic, critic-required
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 实现用编码模型;本切片审查用另一系列,并先读冻结需求
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 实现只接受已验签声明的校验:issuer、audience、有效期、签名。
|
||||
2. 用测试生成的密钥覆盖四类失败和一类成功。
|
||||
3. 确认失败结果不能被当成已登录。
|
||||
|
||||
#### Validation
|
||||
|
||||
`uv run pytest services/watchman/tests -q`
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
验收标准 1 在单元测试中有对应断言。仓库里没有真实密钥。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
删除新增的 auth 校验模块和测试即可。无迁移。
|
||||
|
||||
### Slice 2: 会话与密码登录
|
||||
|
||||
#### Goal
|
||||
|
||||
用可替换的 Casdoor 替身完成密码登录、当前用户和退出。会话写入服务端,遵守 RLS。未配置真实应用时登录失败为 503,测试不依赖内网 Casdoor。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/auth/`
|
||||
- `services/watchman/src/watchman/api/` 的登录路由和注册
|
||||
- `services/watchman/src/watchman/core/config.py`
|
||||
- `services/watchman/src/watchman/models/` 与对应 Alembic 迁移,仅限会话
|
||||
- `services/watchman/tests/` 的登录与会话测试
|
||||
- `.env.example` 只加占位键名,值为空或 CHANGE-ME
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 前端页面、平台写接口的授权、HXOPS 断言、syops、真实 secret
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S1
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S3–S6
|
||||
- Fallback Order: 2
|
||||
- Shared Files: `app.py`、`config.py`、迁移目录
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: security-logic, schema-change, critic-required
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 实现与审查分属不同模型系列
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 增加会话存储。字段限于需求中的数据规则。租户只用服务端配置。
|
||||
2. 密码登录调用可注入的 Casdoor 端口。成功写会话并取回角色;失败 41000;端口不可用或未配置 503。
|
||||
3. 提供当前用户与退出。退出后会话不可再用于后续切片的平台写接口。
|
||||
4. 测试断言响应和日志路径不包含密码、secret、Casdoor token。
|
||||
|
||||
#### Validation
|
||||
|
||||
`uv run pytest services/watchman/tests -q`
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
验收标准 2、8 的会话部分、9 有自动化证据。健康检查仍匿名可用。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
回滚本切片迁移,并移除登录路由。不改动 S1 的纯校验测试。
|
||||
|
||||
### Slice 3: 角色收口与对象检查
|
||||
|
||||
#### Goal
|
||||
|
||||
平台写接口改为必须是 `watchman-admin`。进入能力与对象 ID 检查按冻结的三枚权限点拒绝。角色快照过期后,Casdoor 不可用则拒绝。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/auth/`
|
||||
- `services/watchman/src/watchman/api/routes/platform.py`
|
||||
- `services/watchman/tests/` 中权限与对象检查测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 新的业务表、授权管理接口、前端、syops
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S2
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S4–S6
|
||||
- Fallback Order: 3
|
||||
- Shared Files: 平台路由、auth 依赖
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: security-logic, permission-nodes, critic-required
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 实现与审查分属不同模型系列
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 为三个权限点接上角色判断。无角色不升成查看者。
|
||||
2. 平台两个写接口接入 `perm:data:emp:watchman.platform.write`。
|
||||
3. 对象检查对两个合成 ID 在无授权时都返回 42000,权限点为 `perm:data:emp:watchman.object.read`。不新增公开的对象管理 API。
|
||||
4. 角色确认超过 5 分钟且替身失败时,返回 503,不放行。
|
||||
|
||||
#### Validation
|
||||
|
||||
`uv run pytest services/watchman/tests -q`
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
验收标准 3、4 的服务端部分、5、7 通过。41000 的响应里没有 `permission_node`。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
恢复平台路由的 M01 行为会重新变成匿名可写。回滚时要连同本切片测试一起撤下,并在进度里写明平台写接口重新失去保护。
|
||||
|
||||
### Slice 4: HXOPS 短时断言
|
||||
|
||||
#### Goal
|
||||
|
||||
接收端校验短时断言,建立与密码登录相同的会话。角色只从 Casdoor 端口读取。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/auth/`
|
||||
- `services/watchman/src/watchman/api/` 的断言入口
|
||||
- `services/watchman/tests/` 的断言测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 修改 syops、在断言中信任 HXOPS 权限列表、前端以外的业务模块
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S2、S3
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S5–S6
|
||||
- Fallback Order: 4
|
||||
- Shared Files: `app.py`、会话创建
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: security-logic, external-identity, critic-required
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 实现与审查分属不同模型系列
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 校验断言的签名、issuer、audience、有效期和 Casdoor 身份引用。
|
||||
2. 缺少该引用,或只用 HXOPS 本地主键冒充时,返回 41000。
|
||||
3. 通过后调用与密码登录相同的角色读取。断言内的权限字段不写入会话。
|
||||
|
||||
#### Validation
|
||||
|
||||
`uv run pytest services/watchman/tests -q`
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
验收标准 6 通过。真实 HXOPS 跳转未配置时,证据里写明未做真实联调。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
移除断言路由。密码登录和平台收口保持可用。
|
||||
|
||||
### Slice 5: 登录壳
|
||||
|
||||
#### Goal
|
||||
|
||||
管理台可以登录、看到无权限、会话失效后离开、退出。本地身份模式有可见标识。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `web/apps/console/`
|
||||
- `web/packages/api/`
|
||||
- 对应的单元测试与 Playwright
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 后端授权规则、vben5、把真实 secret 写进前端环境
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S4
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S6
|
||||
- Fallback Order: 5
|
||||
- Shared Files: 前端 API 客户端、路由
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: medium
|
||||
- Gate Class: boundary-sensitive
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: auth-ui, session-boundary, critic-required
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 实现后用浏览器走登录失败、无权限和退出;审查用另一系列
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 登录页提交到 S2 的接口。失败展示通用文案。
|
||||
2. 按当前用户角色进入壳页或无权限页。
|
||||
3. 退出并确认再访问受保护调用会失败。
|
||||
4. 本地身份模式显示固定标识。
|
||||
5. 为 HXOPS 断言准备提交入口,不把断言写进日志或本地长期存储。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `pnpm test:unit`
|
||||
- `pnpm test:e2e`
|
||||
- 浏览器实际走一遍登录失败、无权限和退出。只看截图不算完成。
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
验收标准 11 有断言和浏览器操作证据。前端包里没有 client secret。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
撤下登录页后,后端会话仍在。进度里要写明界面与接口暂时不一致。
|
||||
|
||||
### Slice 6: 文档与示例配置
|
||||
|
||||
#### Goal
|
||||
|
||||
任务卡、运行说明和示例环境变量与已实现行为一致,并写清真实联调尚未完成的条件。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `docs/tasks/M02.md`
|
||||
- `docs/runbook.md`
|
||||
- `docs/progress.md`
|
||||
- `docs/decisions.md`
|
||||
- `.env.example`
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 业务代码、真实密钥、把本地测试写成真实 Casdoor 已通过
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S5
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 6
|
||||
- Shared Files: 进度和任务卡
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: simple
|
||||
- Risk Score: 2
|
||||
- Gate Reasons: docs-only
|
||||
- Validation Level: final
|
||||
- Recommended Agent Strategy: 主 Agent 直接改文档,并对照验收标准 12
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 写上 Watchman Application 需要哪些键,值保持占位。
|
||||
2. 写明真实密码登录和真实 HXOPS 跳转的完成条件。
|
||||
3. 更新 M02 任务卡证据。没有命令输出就写未运行。
|
||||
|
||||
#### Validation
|
||||
|
||||
对照需求验收标准逐条看证据路径是否存在。不新跑业务测试,除非文档改动同时改了示例配置的键名。
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
验收标准 12 在进度和任务卡里有明确状态。示例文件没有真实 secret。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
文档回退不影响已发布的会话行为。
|
||||
|
||||
## Parallel Slice Groups
|
||||
|
||||
本任务不设并行组。会话、路由注册和权限依赖是同一条链。
|
||||
|
||||
## Final Validation
|
||||
|
||||
- `uv run pytest services/watchman/tests -q`
|
||||
- `pnpm test:unit`
|
||||
- `pnpm test:e2e`
|
||||
- 浏览器走登录失败、无权限、退出
|
||||
- 检查响应与日志样本,确认没有密码和 client secret
|
||||
- 真实 Casdoor 与真实 HXOPS 入口未就绪时保持未完成,不并入上述通过结论
|
||||
|
||||
## Documentation Update Requirement
|
||||
|
||||
S6 更新运行说明和任务卡。不把本计划扩写成新的架构文档。若实现时发现会话规则和冻结需求不一致,先停下来改需求,再改代码。
|
||||
|
||||
## Risks
|
||||
|
||||
- S2 的迁移一旦执行,回滚需要明确的 down 步骤。
|
||||
- S3 之前平台写接口仍匿名可写。不要在 S2 做完时宣称模块已经收口。
|
||||
- S5 的 `risk_score` 为 4,即使界面工作看起来较小,也不能在 S4 通过后自动开做。
|
||||
@@ -0,0 +1,58 @@
|
||||
# Task Intake Result
|
||||
|
||||
## Task Type
|
||||
|
||||
feature。Tier L(认证、授权、会话;安全敏感,critic 建议保留)。
|
||||
|
||||
## Current Understanding
|
||||
|
||||
- 用户要求推进 M02(统一登录与权限),先规划并讨论疑问,不编码。
|
||||
- M01 已 DONE_LOCAL。现有 `/platform/*` 写接口没有登录校验。租户只来自服务端 `WATCHMAN_TENANT_ID`(D14)。
|
||||
- 冻结文档 15.1:接入 Casdoor,不另建正式账号密码体系;后端校验;无权限不能只靠隐藏按钮。无真实配置时只用显著标识的开发身份,不能当作正式验收。
|
||||
- O10 仍是 TECH_PENDING:issuer、client、audience、角色和数据范围映射未提供。
|
||||
- 用户已选:自有登录页 + 后端 password grant,并实现 HXOPS 短时 JWT 接收端。syops 平级服务文档把身份和业务权限分开;HXOPS 角色在本库,不在 Casdoor。
|
||||
- 公司权限点格式为 `perm:{data|app}:{emp|dept}:{action}`(`standards://api/permission-nodes?version=1.0.0`)。禁止在代码里编造未确认编码。M01 测试夹具 `perm:platform:audit.read` 不符合该格式,不能当成正式权限点。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- config/default: balanced
|
||||
- allowTaskOverride: true
|
||||
- recommended: strict
|
||||
- selected: balanced
|
||||
- reason or override reason: 用户在 2026-11-17 选择 balanced。推荐 strict 仅作建议,不覆盖该选择。
|
||||
- effective: balanced。分析到编码仍须确认。高风险切片、critic、显式停点不受 balanced 取消。
|
||||
- finalApprovalRequired: true
|
||||
|
||||
## Blocking Questions
|
||||
|
||||
已确认:
|
||||
|
||||
1. 门禁:balanced。
|
||||
2. 登录:Watchman 自有登录页,后端 password grant;同时做从 HXOPS 进入的短时 JWT 接收端。
|
||||
3. 用户倾向授权放在 Casdoor,不在 Watchman 再维护一套角色。syops 现状与此不同,见下方,待用户二选一。
|
||||
|
||||
仍待确认:
|
||||
|
||||
1. 授权来源按用户倾向(Casdoor 角色,Watchman 只校验)还是按 HXOPS 现状(本库角色表)。
|
||||
2. Casdoor Application:用户已选新建 Watchman Application。不复用 HXOPS client。密钥只进 `.env.local`。应用未建好前,真实密码登录不能当作通过。
|
||||
|
||||
## 已核对的 syops 事实
|
||||
|
||||
- HXOPS 把用户和密码同步到 Casdoor。角色、功能权限、权限组在 HXOPS 自己的库里,不在 Casdoor。
|
||||
- 平级服务 SSO 文档写明:认证只回答“是谁”;平级服务自己管业务权限;SSO JWT 不携带 HXOPS 权限列表。
|
||||
- `.env.dev` 的 Casdoor 指向内网 `organization_HX`。JWKS 本机可访问(HTTP 200)。回调地址是 HXOPS 前端端口,该 client 属于 HXOPS。密钥不写入本仓库。
|
||||
|
||||
## Non-blocking Assumptions
|
||||
|
||||
- M02 不实现用户管理后台、组织全量同步、企微发送、场景/数据源业务模块。
|
||||
- 对象级越权用合成对象 ID 验证检查器;场景、数据源等表留到对应模块。
|
||||
- 密钥只进 `.env.local`,不进对话、仓库和文档。
|
||||
- 分析到编码仍需用户明确确认。
|
||||
|
||||
## Recommended Next Step
|
||||
|
||||
用户回答阻塞问题后,写 `.task/2026-11-17/m02-auth/requirement.md`,再切片。在此之前不编码。
|
||||
|
||||
## Suggested Prompt For Next Step
|
||||
|
||||
确认门禁、登录方式、授权落点和有无测试应用后,冻结 M02 需求并给出实现切片。
|
||||
@@ -0,0 +1,168 @@
|
||||
# M02 统一登录与权限 Requirement
|
||||
|
||||
## Goal
|
||||
|
||||
Watchman 用 Casdoor 确认“是谁”,用 Casdoor 上的三个粗角色确认“能进到哪一档”。本服务强制校验,不另建账号密码,也不另建角色表或授权管理页。
|
||||
|
||||
## Background
|
||||
|
||||
- M01 已完成。`POST /platform/audit-events` 与 `POST /platform/run-records` 目前没有登录校验。健康检查保持公开。
|
||||
- 租户只来自服务端 `WATCHMAN_TENANT_ID`(D14)。调用方不能传租户。
|
||||
- 用户 2026-11-17 确认:门禁 balanced;自有登录页加后端向 Casdoor 校验密码;同时接收 HXOPS 短时 JWT;授权按 Casdoor 粗角色,不建本库角色;新建 Watchman 自己的 Casdoor Application,不复用 HXOPS client。
|
||||
- syops 的现状不同:HXOPS 把角色存在自己的库里。本需求不照搬该表结构。平级服务文档仍适用的部分是:认证与授权分开,SSO JWT 不携带 HXOPS 权限,退出只清本服务会话。
|
||||
- 公司权限点格式为 `perm:{data|app}:{emp|dept}:{action}`(`standards://api/permission-nodes?version=1.0.0`)。Watchman 此前没有已注册编码。下面三枚是本模块冻结的最小清单。
|
||||
|
||||
## In Scope
|
||||
|
||||
- 用户名和密码在 Watchman 登录页提交。后端用 Watchman Application 向 Casdoor 校验。浏览器不打开 Casdoor 登录页。
|
||||
- 接收 HXOPS 发来的短时身份断言,校验后建立与密码登录相同的 Watchman 会话。
|
||||
- 校验签名、issuer、audience、有效期。未验签的内容不能授权。
|
||||
- 三个 Casdoor 角色:`watchman-admin`、`watchman-operator`、`watchman-viewer`。
|
||||
- 保护现有平台写接口。未登录与无权限分开。
|
||||
- 对象 ID 本身不是授权。提供可复用的对象访问检查,并用两个合成 ID 证明未授权时都拒绝。
|
||||
- 登录、失败、过期、无权限、退出的界面,以及对应自动化测试。
|
||||
- 配置缺失或真实应用尚未建好时,自动测试用本地签名身份。这种身份必须显著标识,不能当作真实联调通过。
|
||||
|
||||
## Out Of Scope
|
||||
|
||||
- 用户管理、改密、把用户同步到 Casdoor。继续由 HXOPS 负责。
|
||||
- 本服务的角色表、授权管理页、按人编辑功能权限。
|
||||
- 场景、数据源、报警等业务模块,以及“某一行数据属于谁”的正式授权。
|
||||
- 修改 `D:\PROJECT\syops`,或在 HXOPS 里增加 Watchman 入口。
|
||||
- 复用 HXOPS 的 client id、client secret 或 audience。
|
||||
- 浏览器跳转到 Casdoor 授权页作为主登录方式。
|
||||
- 全局退出、退出 Casdoor、退出 HXOPS。
|
||||
- 企微登录按钮、企微通知。
|
||||
- Redis、微服务拆分、vben5。
|
||||
|
||||
## Current Behavior
|
||||
|
||||
- 平台写接口匿名可调用。
|
||||
- 没有登录页、会话或 Casdoor 配置。
|
||||
- 错误信封已能表达 41000 和 42000。42000 在有权限点时回显 `permission_node`。
|
||||
|
||||
## Required Behavior
|
||||
|
||||
- 健康检查仍不要求登录。
|
||||
- 平台写接口:无会话返回 41000;有会话但没有 `watchman-admin` 返回 42000,并带权限点 `perm:data:emp:watchman.platform.write`。
|
||||
- 进入管理台:三个角色之一即可。权限点 `perm:app:emp:watchman.enter`。已登录但没有任何这三个角色时,显示无权限,不显示业务操作。
|
||||
- 对象检查:权限点 `perm:data:emp:watchman.object.read`。调用方未获该对象授权时,两个不同的合成 ID 都拒绝。知道 ID 不能读到数据。M02 不提供按对象授权的维护功能,默认没有对象级授权。
|
||||
- 密码错误、断言无效、签名错误、issuer 或 audience 不符、令牌过期:拒绝,不建立会话。
|
||||
- Casdoor 在需要重新确认角色时不可用:拒绝本次操作,返回可重试的 503。不沿用已经过期的角色缓存。
|
||||
- 登录响应和日志不包含密码、client secret、Casdoor token。
|
||||
- 会话里的租户只等于服务端配置。请求或令牌里的租户值不生效。
|
||||
- 退出只清除 Watchman 会话。
|
||||
|
||||
## User Flow
|
||||
|
||||
1. 用户打开 Watchman 登录页,输入账号和密码。
|
||||
2. 后端向 Casdoor 校验。成功则建立本服务会话,并读回该用户在 Watchman Application 上的角色。
|
||||
3. 有三个角色之一:进入壳页。没有:进入无权限页。
|
||||
4. 从 HXOPS 进入时,HXOPS 交给 Watchman 一个短时断言。Watchman 校验断言后,再按同一身份向 Casdoor 取 Watchman 角色,然后进入与上面相同的会话。
|
||||
5. 会话过期或角色缓存过期且无法重新确认:回到登录或拒绝操作。
|
||||
6. 用户退出:只离开 Watchman。
|
||||
|
||||
## Business Rules
|
||||
|
||||
- Casdoor 是身份来源,也是这三个角色的分配来源。分配在 Casdoor 控制台完成。
|
||||
- Watchman 不解释 HXOPS 的角色和功能权限。断言里即使带了那些权限也忽略。
|
||||
- `watchman-admin` 覆盖处理者和查看者的本模块能力。`watchman-operator` 覆盖查看者的进入能力。本模块里处理者与查看者的差别只保留角色名,供后续模块使用;M02 没有单独的“处理”业务动作。
|
||||
- 无角色不等于查看者。不默认授予 `watchman-viewer`。
|
||||
- 本地签名身份只在非生产、且显式开启的测试或开发模式可用。界面必须看得出这不是正式登录。
|
||||
|
||||
## Data Rules
|
||||
|
||||
- 可以保存会话:身份主体、签发方、显示名、角色快照、角色确认时间、过期时间、服务端租户。
|
||||
- 不保存密码、密码哈希、client secret、Casdoor access token。
|
||||
- 不建角色定义表,不建用户授权表。
|
||||
- 会话上的租户来自服务端配置,并遵守现有 RLS。
|
||||
- 技术默认,不是业务制度:会话 8 小时;角色快照 5 分钟后必须向 Casdoor 重新确认。
|
||||
|
||||
## API Contract
|
||||
|
||||
沿用 M01 信封(`standards://api/api-envelope?version=1.1.0`)。
|
||||
|
||||
- 登录:提交用户名和密码。成功建立会话。失败 41000。Casdoor 未配置或暂时不可达:503,且可重试。
|
||||
- 退出:清除本服务会话。
|
||||
- 当前用户:返回身份和角色名。不返回秘密。
|
||||
- HXOPS 进入:提交短时断言。校验失败 41000。成功后的会话与密码登录相同。
|
||||
- 平台写接口按 Required Behavior 保护。
|
||||
|
||||
断言必须同时满足:签名有效、issuer 与 audience 符合 Watchman 期望的 HXOPS 入口配置、未过期,并且带有 Casdoor 身份引用。HXOPS 自己的本地用户主键不能冒充该身份。
|
||||
|
||||
## UI Requirements
|
||||
|
||||
- 登录页使用现有 Element Plus 薄壳,收集用户名和密码,展示失败原因的通用文案。
|
||||
- 无权限、会话过期、退出后的落点要能区分。
|
||||
- 本地身份模式有可见标识。
|
||||
- 不把 Casdoor 跳转作为主路径。
|
||||
- 界面隐藏按钮不是授权。后端结果为准。
|
||||
|
||||
## Compatibility Requirements
|
||||
|
||||
- 不改变健康检查的匿名访问。
|
||||
- 不改变信封形状。41000 不带 `permission_node`。42000 带上面列出的权限点。
|
||||
- 新的 Casdoor Application 与 HXOPS 共用同一 Casdoor 服务和组织。client 必须分开。
|
||||
- 真实密码登录和真实 HXOPS 跳转,在 Watchman Application 或 HXOPS 入口配置未就绪时记为未通过,不记为失败的产品逻辑。
|
||||
|
||||
## Error Handling
|
||||
|
||||
- 登录失败使用统一文案,不把 Casdoor 原文回给浏览器。
|
||||
- 秘密不进响应、日志和文档。
|
||||
- 角色刷新失败不降级为放行。
|
||||
|
||||
## Permissions And Security
|
||||
|
||||
冻结的权限点:
|
||||
|
||||
| 编码 | 含义 | 谁可以通过 |
|
||||
|---|---|---|
|
||||
| `perm:app:emp:watchman.enter` | 进入管理台 | 三个角色之一 |
|
||||
| `perm:data:emp:watchman.platform.write` | 写平台审计和运行记录 | 仅 `watchman-admin` |
|
||||
| `perm:data:emp:watchman.object.read` | 按对象 ID 读取 | M02 默认无人获得;检查必须拒绝未授权 ID |
|
||||
|
||||
公司规范要求权限点由代码声明且默认拒绝。本模块只声明这三枚。后续模块新增编码前要再确认,不能沿用 M01 测试里的 `perm:platform:audit.read`。
|
||||
|
||||
## Assumptions
|
||||
|
||||
- 用户会在同一 Casdoor、组织 `organization_HX` 下新建 Watchman Application,并把 issuer、client、audience、密钥放进不入库的 `.env.local`。
|
||||
- HXOPS 短时断言的真实签发不在本仓库完成。本模块先把接收和校验做对。
|
||||
- 8 小时会话和 5 分钟角色缓存是技术默认。
|
||||
- 处理者角色在 M02 没有独立业务按钮。
|
||||
|
||||
## Risks
|
||||
|
||||
- 应用未建好时,真实登录无法验收。
|
||||
- HXOPS 尚未把 Watchman 配成入口时,无感进入只能用测试断言。
|
||||
- 角色缓存在 5 分钟内不会反映 Casdoor 上的撤销。
|
||||
- 对象级范围还没做。后面的模块如果只信角色名,会把“能进入系统”误当成“能看每一行”。
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
1. 错误签名、错误 issuer、错误 audience、过期令牌都不能建立会话。
|
||||
2. 密码登录在 Casdoor 替身成功时建立会话,并带上替身返回的角色;替身失败时不建立会话。
|
||||
3. 无会话调用平台写接口得到 41000。查看者或处理者调用得到 42000,且 `permission_node` 为 `perm:data:emp:watchman.platform.write`。管理者可以写。
|
||||
4. 没有任何三个角色的已登录用户不能进入壳页。
|
||||
5. 两个合成对象 ID 在没有对象授权时都被拒绝。
|
||||
6. HXOPS 断言缺少 Casdoor 身份、或用 HXOPS 本地主键冒充时,不建立会话。合法断言建立会话后,角色仍以 Casdoor 为准,不采用断言里的 HXOPS 权限。
|
||||
7. 角色缓存过期且 Casdoor 不可用时,操作被拒绝,而不是继续放行。
|
||||
8. 退出后再调用平台写接口得到 41000。
|
||||
9. 日志和接口响应中没有密码和 client secret。
|
||||
10. 健康检查仍可匿名访问。
|
||||
11. 登录页能完成失败、成功进入、无权限、退出。本地身份模式有可见标识。
|
||||
12. 未配置 Watchman Application 时,真实联调单独标为未完成,本地签名测试的通过不替代它。
|
||||
|
||||
## Deferred Questions
|
||||
|
||||
- 会话 8 小时、角色 5 分钟是否要改成别的数字。
|
||||
- HXOPS 何时把 Watchman 加为真实入口。
|
||||
- 后续模块如何把场景、报警的行级范围接到 `perm:data:emp:watchman.object.read`,而仍然不在 Watchman 做角色管理页。
|
||||
|
||||
## Source Notes
|
||||
|
||||
- 用户确认记录:2026-11-17,门禁 balanced;登录含 HXOPS 接收端;授权用 Casdoor 三档粗角色;新建 Watchman Application。
|
||||
- `需求冻结文档_V1.1_交接稿.md` 第 15 节。
|
||||
- `docs/tasks/INDEX.md` 的 M02。
|
||||
- `docs/decisions.md` 的 D14、O10。O10 的 client 与 audience 仍要等新应用,角色落点已由本需求取代“存在本库”的选项。
|
||||
- syops:`docs/features/auth/hxops-peer-service-sso.md` 第 14、15 节。只读对照,不复制其用户表和权限表。
|
||||
- `.env.dev` 只用来确认 Casdoor 地址和组织。密钥不进入本仓库。JWKS 在规划时返回 HTTP 200。
|
||||
@@ -0,0 +1,6 @@
|
||||
# Critic — M02 S1(编码前)
|
||||
|
||||
- 模型:claude-opus-5-thinking-high
|
||||
- 子代理:eab6ed43-cf99-4c43-8b71-b813c4101161
|
||||
- 结论:PASS。无阻断项。
|
||||
- 开工约束:只加 `pyjwt[crypto]>=2.10,<3`;锁文件只含该库及其传递依赖;不改根 `pyproject.toml`。只允许 RS256,拒绝 `alg: none` 和 HS256 混淆。过期用确定性时间。密钥只在测试内存中生成。做完停在 S2 前。
|
||||
@@ -0,0 +1,6 @@
|
||||
# Critic — M02 S2(编码前)
|
||||
|
||||
- 模型:claude-opus-5-thinking-high
|
||||
- 子代理:03d34f4b-94e1-4072-8271-0e89c535dd0c
|
||||
- 结论:PASS。无阻断项。
|
||||
- 约束:不新增依赖,不改 `uv.lock`,运行时代码不 import `httpx`。不把 `CASDOOR_*` 放进启动必填项。登录失败 41000,未配置 503 且不建会话。测试注入替身,不读 `.env.local`,不访问网络。Cookie 为 HttpOnly,本地不强制 Secure。会话表走现有 RLS。本切片不保护平台写接口。做完停在 S3 前。
|
||||
@@ -0,0 +1,4 @@
|
||||
# Critic — M02 S3(编码前)
|
||||
|
||||
- 用户在 2026-11-17 明确要求跳过编程前 critic,并默认 PASS。
|
||||
- 未另派审查模型做编码前审计。
|
||||
@@ -0,0 +1,7 @@
|
||||
# Review — M02 模块整体
|
||||
|
||||
- 审查:claude-opus-5-thinking-high,f3455ae9-1f7a-4a5b-9d2e-a030e8e79d32。结论:FAIL。
|
||||
- 必改:HXOPS 断言在没有 `casdoor_sub` 时会回退到令牌自己的 `sub`,本地用户主键可以冒充 Casdoor 身份。
|
||||
- 修复:`casdoor_sub` 必须存在,不再回退到 `sub`。`CASDOOR_ISSUER` 未配置时入口返回 503。补了缺少 `casdoor_sub` 的拒绝测试,并去掉对未导入 `pytest` 的调用。
|
||||
- 复跑:`uv run pytest services/watchman/tests -q` → 54 passed。前端 unit 9 passed。这次没有重跑 Playwright,界面没有改。
|
||||
- 未做第二次独立复审。HXOPS 真实跳转仍未联调。未标 DONE_LOCAL。
|
||||
@@ -0,0 +1,7 @@
|
||||
# Review — M02 S1
|
||||
|
||||
- 第一次审查(claude-sonnet-5-5-high,9a4bae12-f271-4fee-9944-d8cdd8fc5740):FAIL。缺 `# GUARD:`;alg none / HS256 测试没有锁住本服务自己的算法限制。
|
||||
- 修复后复审(gemini-4-hydrogen-high,351c41be-cf86-450f-8490-4ca5cf507b42):PASS。
|
||||
- 实现(gpt-5.6-terra-medium,6d369019-b392-4f7c-914f-8e83405e8124)。
|
||||
- 主 Agent 复跑:`uv run pytest services/watchman/tests -q` → 30 passed。
|
||||
- 未开始 S2。
|
||||
@@ -0,0 +1,9 @@
|
||||
# Review — M02 S2
|
||||
|
||||
- 编码前 critic(claude-opus-5-thinking-high,03d34f4b-94e1-4072-8271-0e89c535dd0c):PASS。
|
||||
- 实现(gpt-5.6-terra-medium,a062b19b-2917-44f5-a294-5fb7c63c04b2)。
|
||||
- 审查(claude-sonnet-5-5-high,bb80f999-7799-4fe8-9a49-225c95d3d25d):PASS_WITH_WARNINGS。无必改项。
|
||||
- 主 Agent 复跑:`uv run pytest services/watchman/tests -q` → 35 passed。
|
||||
- 迁移:`uv run alembic -c alembic.ini upgrade head`(在 `services/watchman`)已由实现方执行成功。
|
||||
- 真实 Casdoor HTTP 按 critic 延后。默认登录端口固定返回 503。
|
||||
- 未开始 S3。平台写接口仍匿名。
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"taskId": "2026-11-17/m02-auth",
|
||||
"phase": "review",
|
||||
"allowedToCode": false,
|
||||
"gatePolicy": {
|
||||
"recommended": "strict",
|
||||
"selected": "balanced",
|
||||
"effective": "balanced",
|
||||
"finalApprovalRequired": true
|
||||
},
|
||||
"requirement": ".task/2026-11-17/m02-auth/requirement.md",
|
||||
"implementationPlan": ".task/2026-11-17/m02-auth/implementation-plan.md",
|
||||
"currentSlice": "S2",
|
||||
"nextGate": "user-confirm-s3"
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"taskId": "2026-11-17/m01-foundation",
|
||||
"taskId": "2026-11-17/m02-auth",
|
||||
"type": "feature",
|
||||
"phase": "finalization",
|
||||
"allowedToCode": true,
|
||||
"currentSlice": "M01-module-review",
|
||||
"lastGate": "review-m01",
|
||||
"nextCommand": "fix PASS_WITH_WARNINGS must-handle items, then re-review affected parts",
|
||||
"updatedAt": "2026-11-17T05:35:00Z"
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "S6",
|
||||
"lastGate": "s6-docs",
|
||||
"nextCommand": "module-wide independent review before DONE_LOCAL",
|
||||
"updatedAt": "2026-11-17T09:50:00Z"
|
||||
}
|
||||
@@ -24,6 +24,7 @@
|
||||
| D16 | `WATCHMAN_TENANT_ID` 放在不入库的 `.env.local`(及 `.env.example` 占位),不放 `.env.shared` | 2026-11-17 critic 对照需求 Assumptions;修正落位 |
|
||||
| D17 | 仓库 `gatePolicy.defaultMode` 保持 `balanced`;Tier L 保持 `prefer-strict`/`full-marionettist`。本任务曾出现的 autonomous/放宽漂移已回滚,不作为 M01 交付 | 2026-11-17 独立 review S1-5;用户授权处理必改项时回滚 |
|
||||
| D18 | Compose 容器内 `API_HOST=0.0.0.0` 仅开发且必须行内标注;宿主发布端口仍绑 `127.0.0.1` | 2026-11-17 独立 review 顺带项 |
|
||||
| D19 | M02 授权:Casdoor 分配 `watchman-admin`、`watchman-operator`、`watchman-viewer`。Watchman 只校验,不建角色表和授权管理页。登录用自有页面,后端向新建的 Watchman Application 校验密码,并接收 HXOPS 短时断言。不复用 HXOPS client。行级数据范围留到后续业务模块 | 2026-11-17 用户确认按此冻结 |
|
||||
|
||||
## 冻结前/相关模块实现前必须确认
|
||||
|
||||
@@ -40,7 +41,7 @@
|
||||
| O07 | OPEN | 停机漏跑、跨周期任务重叠、启停及改 Cron 后的旧任务 | 建议每场景不并发推进进度,逾期运行有界跳过/显式补跑且不自动补发历史消息;用户需确认具体业务行为 | P-004、A-033~A-036 |
|
||||
| O08 | OPEN | Cursor/Grok 等实际服务商能处理哪些项目资料?能否跨系列子 Agent? | 先确认交接文档、未来源码、合成数据和截图授权;默认不读取原会议或 MES 原始资料,不发真实凭证。用可用模型目录填写角色映射,不能默认已获所有服务商授权 | 所有实际模型委派 |
|
||||
| O09 | TECH_PENDING | Python/Node/依赖版本,Cron 解析器和编辑组件,AI SDK,企微库 | M01 已锁定:Python 3.12.16(uv)、FastAPI 0.163、SQLAlchemy 2.0.57、Alembic 1.20、Celery 5.7、Pydantic 2.14、Vue 3.5 / Element Plus 2.x / Vite 7 / pnpm 12。其余(Cron/AI/企微)仍待后续模块 | P-002、P-004、A-056、B-001 |
|
||||
| O10 | TECH_PENDING | Casdoor issuer/client/audience、角色和数据范围映射 | 使用隔离测试租户/合成身份,正式配置需维护方提供;签名、issuer、audience、有效期和权限都检验 | A-008~A-010、A-074 |
|
||||
| O10 | TECH_PENDING | Watchman Application 已在本机 `.env.local`。密码登录已用一个已有账号走过。HXOPS 真实断言签发仍未做 | 密钥不入库。本地签名测试和一次密码登录不能写成 A-074 真实入口已全部通过 | A-008~A-010、A-074 |
|
||||
|
||||
O01~O07 不要求全在第一天解决,但其依赖切片不能带着猜测宣布完成。用户可一次批准建议,也可逐项给不同口径。无关切片在授权开工后仍可推进。
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 7.7 KiB After Width: | Height: | Size: 9.5 KiB |
|
Before Width: | Height: | Size: 9.7 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 9.9 KiB After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,16 @@
|
||||
# 交接 2026-11-17-005 — M02 分析开始
|
||||
|
||||
## 完成
|
||||
|
||||
- 用户要求推进 M02,先规划并讨论。
|
||||
- 已读索引、冻结文档第 15 节、O10、M01 现状,并只读参考了 syops 的 Casdoor 登录说明。
|
||||
- 任务入口:`.task/2026-11-17/m02-auth/intake.md`。`allowedToCode` 为 false。
|
||||
|
||||
## 未做
|
||||
|
||||
- 未冻结需求,未切片,未改业务代码。
|
||||
- 未读取 syops 的密钥或 `.env`。
|
||||
|
||||
## 下一步
|
||||
|
||||
- 用户确认门禁、登录交互、角色落点、有无 Watchman 测试应用,以及权限点编码由谁给定。
|
||||
@@ -2,18 +2,19 @@
|
||||
|
||||
## 当前快照
|
||||
|
||||
- 当前阶段:M01 已 DONE_LOCAL;等待开 M02 或用户下一条指令。
|
||||
- 当前大任务:无进行中模块;上一完成:M01 基础框架。
|
||||
- 用户授权:已确认 finalApproval,并授权 commit。
|
||||
- Git:本机将提交 M01 交付;未授权 push/建远程。
|
||||
- 下一步:按 `docs/tasks/INDEX.md` 开 M02(Casdoor/登录)或用户指定模块。
|
||||
- 当前阶段:M02 模块审查发现的必改已修。pytest 54,前端 unit 9。未标 DONE_LOCAL。HXOPS 真实跳转仍未做。
|
||||
- 当前大任务:M02 统一登录与权限。上一完成:M01 基础框架(DONE_LOCAL)。
|
||||
- 用户授权:已确认提交并推送当前 M02 实现。HXOPS 真实跳转仍未做,不把本模块标成 DONE_LOCAL。
|
||||
- Git:本轮提交 M02,并推送到 origin。
|
||||
- 下一步:用户确认是否把 M02 标为 DONE_LOCAL。真实 HXOPS 跳转继续单列未完成。
|
||||
- RabbitMQ 容器可能仍在运行:`watchman-dev-rabbitmq`。
|
||||
|
||||
## 大任务状态
|
||||
|
||||
| 大任务/当前内部步骤 | 状态 | 负责人角色/实际模型 | 候选版本标识 | Review | 测试/UI 证据 | 阻塞/下一步 |
|
||||
|---|---|---|---|---|---|---|
|
||||
| M01 基础框架 | DONE_LOCAL | 实现 Composer;审查/复审异系列 | `8fb16f4` | PASS_WITH_WARNINGS(必改已关) | pytest 23;unit 8;e2e 3 | 可开 M02 |
|
||||
| M01 基础框架 | DONE_LOCAL | 实现 Composer;审查/复审异系列 | `8fb16f4` | PASS_WITH_WARNINGS(必改已关) | pytest 23;unit 8;e2e 3 | 已完成 |
|
||||
| M02 统一登录与权限 | 审查必改已修,待最终确认 | 审查 Claude;修复主 Agent | 未提交 | 整体审查 FAIL 后必改已关,未做第二次复审 | pytest 54;unit 9;此前 e2e 5 | HXOPS 真跳转未做 |
|
||||
|
||||
## 当前阻塞
|
||||
|
||||
|
||||
@@ -87,7 +87,17 @@ pnpm --filter @watchman/console test:e2e
|
||||
|
||||
Playwright 截图写入 `docs/evidence/M01/ui/`(相对仓库根,勿再多上一级)。`/_probe/*` 与 `/docs` 仅在 `ENV_NAME=dev|test` 暴露。
|
||||
|
||||
`.env.dev` 可选;缺失时加载顺序会跳过该文件。租户 id 放在 `.env.local`(见 D16)。
|
||||
`.env.dev` 可选;缺失时加载顺序会跳过该文件。租户 id 放在 `.env.local`(见 D16)。Casdoor 与 HXOPS 入口的地址、应用名和密钥也只放 `.env.local`,键名见 `.env.example`。
|
||||
|
||||
## 登录(M02)
|
||||
|
||||
管理台先访问 `GET /auth/me`。没有会话时进入登录页。密码登录走 `POST /auth/login`,成功后浏览器只保存 HttpOnly cookie。`GET /auth/me` 返回身份和角色,`POST /auth/logout` 只结束 Watchman 会话。
|
||||
|
||||
Casdoor 上的三个角色是 `watchman-admin`、`watchman-operator`、`watchman-viewer`。没有这三个角色时,页面只显示无权限。`POST /platform/audit-events` 和 `POST /platform/run-records` 需要 `watchman-admin`:未登录是 41000,已登录但角色不够是 42000。角色快照超过 5 分钟会按登录名再问 Casdoor;问失败则本次操作返回 503,不沿用旧角色。
|
||||
|
||||
`POST /auth/hxops-entry` 接收短时断言,并且必须带 `casdoor_sub`。HXOPS 令牌自己的 `sub` 不能当作 Casdoor 身份。未配置 `HXOPS_SSO_ISSUER`、`HXOPS_SSO_AUDIENCE`、`HXOPS_SSO_PUBLIC_KEY` 或 `CASDOOR_ISSUER` 时返回 503。断言里的角色不会被采用。HXOPS 尚未向 Watchman 签发真实断言,所以这条路径只有本地签名测试,不能写成真实跳转已通过。
|
||||
|
||||
本机曾用一个已有 Casdoor 账号走通密码登录、当前用户和退出。这不替代 HXOPS 真实入口验收。密钥和密码不写入仓库。前端 `VITE_AUTH_MODE=fixture` 时,登录页会显示本地身份标识。
|
||||
|
||||
## 端口(仅开发,全部绑 127.0.0.1)
|
||||
|
||||
@@ -102,6 +112,7 @@ Playwright 截图写入 `docs/evidence/M01/ui/`(相对仓库根,勿再多上
|
||||
|
||||
## 当前已知限制
|
||||
|
||||
- 正式 Casdoor 登录在 M02。
|
||||
- 正式 Casdoor 密码登录已在本机走过一次;HXOPS 真实跳转仍未做。
|
||||
- 平台写接口需要已登录的 `watchman-admin`。健康检查仍然匿名。
|
||||
- Compose `app` profile 依赖 Docker 构建;日常开发可用宿主机进程 + 仅 RabbitMQ 容器。
|
||||
- 容器内 `API_HOST=0.0.0.0` 仅开发监听(D18);宿主端口仍绑 `127.0.0.1`。
|
||||
@@ -0,0 +1,41 @@
|
||||
# M02 统一登录与权限
|
||||
|
||||
一个会话聚焦本模块。S1–S6 已实现并写入说明。模块整体独立 review 尚未做,不能标 DONE_LOCAL。
|
||||
|
||||
## 内部步骤(主 Agent 根据现有代码安排)
|
||||
- [x] 确认门禁、登录方式、授权落点和 Casdoor 应用策略。见 D19。
|
||||
- [x] 冻结需求并切片。见 `.task/2026-11-17/m02-auth/requirement.md` 与 `implementation-plan.md`。
|
||||
- [x] S1 令牌校验。critic PASS,复审 PASS。
|
||||
- [x] S2 会话与密码登录。审查 PASS_WITH_WARNINGS。随后补上真实 Casdoor 密码校验。
|
||||
- [x] S3 角色收口。匿名 41000,非管理者 42000,过期角色刷新失败则 503。
|
||||
- [x] S4 HXOPS 短时断言。验签后按 Casdoor 角色建会话。真实跳转未联调。
|
||||
- [x] S5 登录壳。失败、无权限、退出已由 Playwright 覆盖。
|
||||
- [x] S6 运行说明和示例配置。`.env.example` 只有占位。
|
||||
- [ ] 模块整体独立 review、修复和复审。
|
||||
- [ ] 对最终候选再跑一轮正式测试。
|
||||
- [ ] 主 Agent 验收、进度和交接。
|
||||
|
||||
当前恢复点:S6 文档已更新。下一步是模块整体 review,而不是下一个业务模块。
|
||||
|
||||
## 目标与边界
|
||||
- 阶段/需求编号:M02;覆盖原细项 A-008~A-010、A-074。
|
||||
- 依赖及当前状态:M01 DONE_LOCAL。平台写接口现在要求 `watchman-admin`。
|
||||
- 必须已确认的决策:D01、D14、D19。门禁 selected=balanced。
|
||||
- 模块可验收行为:后端校验签名、issuer、audience、期限和角色;对象 ID 本身不能授权。
|
||||
- 明确不做:用户管理后台、组织全量同步、企微通知、场景与数据源业务功能。HXOPS 真实跳转未做,不能写成通过。
|
||||
- 输入/输出契约及失败语义:沿用 M01 信封。未登录 41000,无权限 42000 且带权限点。
|
||||
- 权限点:`perm:app:emp:watchman.enter`、`perm:data:emp:watchman.platform.write`、`perm:data:emp:watchman.object.read`。
|
||||
|
||||
## 模块验收
|
||||
- 正常:密码登录建立会话;管理者可写平台记录。
|
||||
- 边界:过期令牌、错误 issuer/audience、本地用户主键冒充 Casdoor 身份。
|
||||
- 故障/权限/重复:无会话 41000;角色不够 42000;角色刷新失败 503。两个合成对象 ID 都拒绝。
|
||||
- 回归范围:M01 健康检查、信封、幂等和 RLS。
|
||||
- UI:登录失败、无权限、退出。截图在 `docs/evidence/M02/ui/`。
|
||||
|
||||
## 证据与结论(主 Agent 汇总)
|
||||
- 后端测试:`uv run pytest services/watchman/tests -q` → **54 passed**(审查必改之后)。
|
||||
- 前端:`pnpm --filter @watchman/console test:unit` → 9 passed。Playwright 健康检查 3 在 S5 通过。登录模拟又补了成功路径:`pnpm exec playwright test e2e/login.spec.ts -g "sign in as an admin"` → 1 passed。截图 `docs/evidence/M02/ui/login-success.png`。这次是拦截接口的模拟,不是再打真实 Casdoor。
|
||||
- 本机密码登录、当前用户和退出走过一次。HXOPS 真实跳转未做。
|
||||
- 模块整体审查为 FAIL。必改是 HXOPS `sub` 冒充,已改为必须带 `casdoor_sub`。没有第二次独立复审。
|
||||
- 最终状态:必改已关,等待用户确认是否标 DONE_LOCAL。真实 HXOPS 入口仍单列未完成。
|
||||
@@ -12,7 +12,7 @@ from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.models.base import Base
|
||||
from watchman.models import AuditEvent, RunRecord # noqa: F401
|
||||
from watchman.models import AuthSession, AuditEvent, RunRecord # noqa: F401
|
||||
|
||||
config = context.config
|
||||
if config.config_file_name is not None:
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Create tenant-scoped Watchman authentication sessions.
|
||||
|
||||
Revision ID: 20261117_0002
|
||||
Revises: 20261117_0001
|
||||
Create Date: 2026-11-17
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261117_0002"
|
||||
down_revision: Union[str, None] = "20261117_0001"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
TABLE_NAME = "auth_sessions"
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Create the session table without storing credentials or raw tokens."""
|
||||
op.create_table(
|
||||
TABLE_NAME,
|
||||
sa.Column("token_hash", sa.String(length=64), primary_key=True),
|
||||
sa.Column("subject", sa.String(length=255), nullable=False),
|
||||
sa.Column("issuer", sa.String(length=512), nullable=False),
|
||||
sa.Column("display_name", sa.String(length=255), nullable=False),
|
||||
sa.Column(
|
||||
"role_snapshot",
|
||||
postgresql.JSONB(astext_type=sa.Text()),
|
||||
server_default=sa.text("'[]'::jsonb"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("role_checked_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("expires_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
)
|
||||
op.execute(f"ALTER TABLE {TABLE_NAME} ENABLE ROW LEVEL SECURITY")
|
||||
op.execute(f"ALTER TABLE {TABLE_NAME} FORCE ROW LEVEL SECURITY")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE POLICY tenant_isolation ON {TABLE_NAME}
|
||||
FOR ALL
|
||||
TO {APP_ROLE}
|
||||
USING (tenant_id = current_setting('app.tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
|
||||
"""
|
||||
)
|
||||
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {TABLE_NAME} TO {APP_ROLE}")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Remove the auth session RLS policy and table."""
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {TABLE_NAME}")
|
||||
op.drop_table(TABLE_NAME)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Store the Casdoor login name used to refresh roles.
|
||||
|
||||
Revision ID: 20261117_0003
|
||||
Revises: 20261117_0002
|
||||
Create Date: 2026-11-17
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261117_0003"
|
||||
down_revision: Union[str, None] = "20261117_0002"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Add the non-secret login name required to reload Casdoor roles."""
|
||||
op.add_column(
|
||||
"auth_sessions",
|
||||
sa.Column("login_name", sa.String(length=255), nullable=False, server_default=""),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Remove the login name column."""
|
||||
op.drop_column("auth_sessions", "login_name")
|
||||
@@ -13,6 +13,7 @@ dependencies = [
|
||||
"psycopg[binary]>=3.2,<4",
|
||||
"celery>=5.4,<6",
|
||||
"python-dotenv>=1.0,<2",
|
||||
"pyjwt[crypto]>=2.10,<3",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
|
||||
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from watchman.api.routes import health, platform
|
||||
from watchman.api.routes import auth, health, platform
|
||||
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
|
||||
from watchman.core.errors import AppError, ValidationError
|
||||
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
|
||||
@@ -75,6 +75,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
|
||||
)
|
||||
app.add_middleware(RequestIdMiddleware)
|
||||
app.include_router(health.router)
|
||||
app.include_router(auth.router)
|
||||
app.include_router(platform.router)
|
||||
|
||||
@app.exception_handler(AppError)
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Password login, HXOPS entry, current-user, and logout endpoints.
|
||||
|
||||
These routes establish Watchman sessions. Platform writes are authorized separately.
|
||||
Depends on injectable Casdoor and session-store ports plus the standard response envelope.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Cookie, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from watchman.auth.casdoor import CasdoorPort, get_casdoor_port
|
||||
from watchman.auth.hxops import HxopsAssertionLogin, get_hxops_login
|
||||
from watchman.auth.sessions import (
|
||||
SESSION_COOKIE_NAME,
|
||||
SESSION_LIFETIME,
|
||||
SessionStore,
|
||||
get_session_store,
|
||||
hash_cookie_token,
|
||||
issue_cookie_token,
|
||||
read_session_token,
|
||||
utc_now,
|
||||
)
|
||||
from watchman.core.errors import UnauthorizedError
|
||||
from watchman.core.response import success_body
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
class PasswordLoginRequest(BaseModel):
|
||||
"""Password-login input passed only to the injectable Casdoor port."""
|
||||
|
||||
username: str = Field(min_length=1)
|
||||
password: str = Field(min_length=1)
|
||||
|
||||
|
||||
class HxopsEntryRequest(BaseModel):
|
||||
"""One short-lived HXOPS assertion. It is not stored."""
|
||||
|
||||
assertion: str = Field(min_length=1)
|
||||
|
||||
|
||||
def _public_identity(row: object, *, access_token: str | None = None) -> dict[str, object]:
|
||||
"""Map stored session data to the fields the browser is allowed to keep."""
|
||||
data: dict[str, object] = {
|
||||
"subject": row.subject, # type: ignore[attr-defined]
|
||||
"display_name": row.display_name, # type: ignore[attr-defined]
|
||||
"login_name": row.login_name, # type: ignore[attr-defined]
|
||||
"roles": list(row.role_snapshot), # type: ignore[attr-defined]
|
||||
}
|
||||
if access_token is not None:
|
||||
data["access_token"] = access_token
|
||||
data["token_type"] = "Bearer"
|
||||
data["expires_in"] = int(SESSION_LIFETIME.total_seconds())
|
||||
return data
|
||||
|
||||
|
||||
def _session_response(request: Request, row: object, token: str) -> JSONResponse:
|
||||
"""Return the session token for the frontend and set the HttpOnly cookie."""
|
||||
response = JSONResponse(
|
||||
content=success_body(
|
||||
_public_identity(row, access_token=token),
|
||||
request_id=request.state.request_id,
|
||||
)
|
||||
)
|
||||
response.set_cookie(
|
||||
key=SESSION_COOKIE_NAME,
|
||||
value=token,
|
||||
httponly=True,
|
||||
samesite="lax",
|
||||
path="/",
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(
|
||||
request: Request,
|
||||
body: PasswordLoginRequest,
|
||||
casdoor: CasdoorPort = Depends(get_casdoor_port),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
) -> JSONResponse:
|
||||
"""Verify submitted credentials, create a server-side session, and set its HttpOnly cookie."""
|
||||
identity = casdoor.authenticate_password(username=body.username, password=body.password)
|
||||
token = issue_cookie_token()
|
||||
row = sessions.create(
|
||||
token_hash=hash_cookie_token(token),
|
||||
identity=identity,
|
||||
now=utc_now(),
|
||||
login_name=body.username,
|
||||
)
|
||||
return _session_response(request, row, token)
|
||||
|
||||
|
||||
@router.post("/hxops-entry")
|
||||
def hxops_entry(
|
||||
request: Request,
|
||||
body: HxopsEntryRequest,
|
||||
entry: HxopsAssertionLogin = Depends(get_hxops_login),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
) -> JSONResponse:
|
||||
"""Verify an HXOPS assertion and open the same kind of session as password login.
|
||||
|
||||
Roles are loaded by the entry service. The assertion body is not written to the session.
|
||||
"""
|
||||
identity, login_name = entry.authenticate(body.assertion)
|
||||
token = issue_cookie_token()
|
||||
row = sessions.create(
|
||||
token_hash=hash_cookie_token(token),
|
||||
identity=identity,
|
||||
now=utc_now(),
|
||||
login_name=login_name,
|
||||
)
|
||||
return _session_response(request, row, token)
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def current_user(
|
||||
request: Request,
|
||||
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
) -> JSONResponse:
|
||||
"""Return the current public identity only when a non-expired server session exists."""
|
||||
token = read_session_token(request, session_token)
|
||||
if token is None:
|
||||
raise UnauthorizedError()
|
||||
row = sessions.get(token_hash=hash_cookie_token(token), now=utc_now())
|
||||
if row is None:
|
||||
raise UnauthorizedError()
|
||||
return JSONResponse(content=success_body(_public_identity(row), request_id=request.state.request_id))
|
||||
|
||||
|
||||
@router.post("/logout")
|
||||
def logout(
|
||||
request: Request,
|
||||
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
) -> JSONResponse:
|
||||
"""Invalidate this Watchman session and remove its browser cookie."""
|
||||
token = read_session_token(request, session_token)
|
||||
if token is not None:
|
||||
sessions.invalidate(token_hash=hash_cookie_token(token))
|
||||
response = JSONResponse(
|
||||
content=success_body({"logged_out": True}, request_id=request.state.request_id)
|
||||
)
|
||||
response.delete_cookie(key=SESSION_COOKIE_NAME, path="/")
|
||||
return response
|
||||
@@ -12,6 +12,7 @@ from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.auth.principal import require_platform_writer
|
||||
from watchman.core.db import get_db_session
|
||||
from watchman.core.response import success_body
|
||||
from watchman.services.platform_records import create_audit_event, create_run_record
|
||||
@@ -34,6 +35,7 @@ class RunCreateRequest(BaseModel):
|
||||
def post_audit_event(
|
||||
request: Request,
|
||||
body: AuditCreateRequest,
|
||||
_: None = Depends(require_platform_writer),
|
||||
session: Session = Depends(get_db_session),
|
||||
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||
) -> JSONResponse:
|
||||
@@ -57,6 +59,7 @@ def post_audit_event(
|
||||
def post_run_record(
|
||||
request: Request,
|
||||
body: RunCreateRequest,
|
||||
_: None = Depends(require_platform_writer),
|
||||
session: Session = Depends(get_db_session),
|
||||
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||
) -> JSONResponse:
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Authentication primitives for verified Watchman identities.
|
||||
Only local token verification belongs here; sessions and external identity calls do not.
|
||||
Depends on watchman.core.errors for authentication failures."""
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Role checks for the three Watchman permission nodes.
|
||||
|
||||
Decides enter, platform write, and object read from Casdoor role names.
|
||||
Depends on semantic errors only; it does not call Casdoor or open a session.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from watchman.core.errors import ForbiddenError
|
||||
|
||||
ENTER_NODE = "perm:app:emp:watchman.enter"
|
||||
PLATFORM_WRITE_NODE = "perm:data:emp:watchman.platform.write"
|
||||
OBJECT_READ_NODE = "perm:data:emp:watchman.object.read"
|
||||
|
||||
ROLE_ADMIN = "watchman-admin"
|
||||
ROLE_OPERATOR = "watchman-operator"
|
||||
ROLE_VIEWER = "watchman-viewer"
|
||||
# GUARD: empty roles must never be treated as viewer. Do not add other names here.
|
||||
ENTER_ROLES = frozenset({ROLE_ADMIN, ROLE_OPERATOR, ROLE_VIEWER})
|
||||
|
||||
|
||||
def allows_enter(role_names: list[str]) -> bool:
|
||||
"""Return whether these roles may open the shell.
|
||||
|
||||
Any of the three Watchman roles is enough. An empty or unknown list is denied,
|
||||
and this function does not raise.
|
||||
"""
|
||||
return bool(ENTER_ROLES.intersection(role_names))
|
||||
|
||||
|
||||
def require_platform_write(role_names: list[str]) -> None:
|
||||
"""Allow a platform write only for watchman-admin.
|
||||
|
||||
Other roles, including viewer and operator, raise ForbiddenError with the
|
||||
platform write permission node.
|
||||
"""
|
||||
if ROLE_ADMIN not in role_names:
|
||||
raise ForbiddenError(permission_node=PLATFORM_WRITE_NODE)
|
||||
|
||||
|
||||
def require_object_access(role_names: list[str], object_id: str) -> None:
|
||||
"""Reject every object id until a later module grants row access.
|
||||
|
||||
M02 has no object grants, so admin and every other role are refused with
|
||||
the object-read permission node. The id is not used as proof of access.
|
||||
"""
|
||||
del role_names, object_id
|
||||
raise ForbiddenError(permission_node=OBJECT_READ_NODE)
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Injectable Casdoor password-login port using OpenID Connect discovery."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
from typing import Protocol
|
||||
from urllib.error import HTTPError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from watchman.core.config import Settings, get_settings
|
||||
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CasdoorIdentity:
|
||||
"""Verified identity returned by a Casdoor password-login adapter."""
|
||||
|
||||
subject: str
|
||||
issuer: str
|
||||
display_name: str
|
||||
role_names: list[str]
|
||||
|
||||
|
||||
class CasdoorPort(Protocol):
|
||||
"""Authenticate credentials through Casdoor without exposing upstream tokens."""
|
||||
|
||||
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
|
||||
"""Return a verified identity or raise a semantic authentication/service error."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HttpResponse:
|
||||
"""Minimal HTTP response used by the injectable Casdoor transport."""
|
||||
|
||||
status_code: int
|
||||
body: bytes
|
||||
|
||||
|
||||
class CasdoorHttpTransport(Protocol):
|
||||
"""Perform one HTTP request for the Casdoor adapter."""
|
||||
|
||||
def request(
|
||||
self,
|
||||
*,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: dict[str, str],
|
||||
data: bytes | None = None,
|
||||
) -> HttpResponse:
|
||||
"""Return a response or raise a network exception."""
|
||||
|
||||
|
||||
class UrllibCasdoorHttpTransport:
|
||||
"""Production transport with a bounded timeout and no response logging."""
|
||||
|
||||
def request(
|
||||
self,
|
||||
*,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: dict[str, str],
|
||||
data: bytes | None = None,
|
||||
) -> HttpResponse:
|
||||
request = Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urlopen(request, timeout=8) as response:
|
||||
return HttpResponse(status_code=response.status, body=response.read())
|
||||
except HTTPError as error:
|
||||
return HttpResponse(status_code=error.code, body=error.read())
|
||||
|
||||
|
||||
class DefaultCasdoorPort:
|
||||
"""Authenticate passwords through Casdoor's discovered OpenID Connect endpoints."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings | None = None,
|
||||
transport: CasdoorHttpTransport | None = None,
|
||||
) -> None:
|
||||
self._settings = settings or get_settings()
|
||||
self._transport = transport or UrllibCasdoorHttpTransport()
|
||||
|
||||
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
|
||||
"""Exchange credentials for a verified identity without retaining credentials or tokens."""
|
||||
configured = (
|
||||
self._settings.casdoor_endpoint
|
||||
and self._settings.casdoor_client_id
|
||||
and self._settings.casdoor_client_secret
|
||||
)
|
||||
# GUARD: never log password, client secret, or tokens.
|
||||
if not configured:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
|
||||
try:
|
||||
discovery = self._json_response(
|
||||
self._transport.request(
|
||||
method="GET",
|
||||
url=f"{self._settings.casdoor_endpoint.rstrip('/')}/.well-known/openid-configuration",
|
||||
headers={"Accept": "application/json"},
|
||||
)
|
||||
)
|
||||
token_endpoint = self._required_endpoint(discovery, "token_endpoint")
|
||||
userinfo_endpoint = self._required_endpoint(discovery, "userinfo_endpoint")
|
||||
token_response = self._transport.request(
|
||||
method="POST",
|
||||
url=token_endpoint,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
data=urlencode(
|
||||
{
|
||||
"grant_type": "password",
|
||||
"username": username,
|
||||
"password": password,
|
||||
"client_id": self._settings.casdoor_client_id,
|
||||
"client_secret": self._settings.casdoor_client_secret,
|
||||
"scope": "openid profile email",
|
||||
}
|
||||
).encode("utf-8"),
|
||||
)
|
||||
except UnauthorizedError:
|
||||
raise
|
||||
except Exception as error:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable") from error
|
||||
|
||||
token_body = self._decode_json(token_response.body)
|
||||
if self._is_credential_rejection(token_response, token_body):
|
||||
raise UnauthorizedError("Invalid username or password")
|
||||
if token_response.status_code < 200 or token_response.status_code >= 300:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
|
||||
access_token = token_body.get("access_token")
|
||||
if not isinstance(access_token, str) or not access_token:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
|
||||
try:
|
||||
userinfo_response = self._transport.request(
|
||||
method="GET",
|
||||
url=userinfo_endpoint,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
},
|
||||
)
|
||||
except Exception as error:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable") from error
|
||||
|
||||
userinfo = self._decode_json(userinfo_response.body)
|
||||
if userinfo_response.status_code in {400, 401}:
|
||||
raise UnauthorizedError("Invalid username or password")
|
||||
if userinfo_response.status_code < 200 or userinfo_response.status_code >= 300:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
|
||||
subject = userinfo.get("sub")
|
||||
if not isinstance(subject, str) or not subject:
|
||||
raise UnauthorizedError("Invalid username or password")
|
||||
display_name = userinfo.get("name") or userinfo.get("preferred_username") or username
|
||||
return CasdoorIdentity(
|
||||
subject=subject,
|
||||
issuer=self._settings.casdoor_issuer or self._settings.casdoor_endpoint,
|
||||
display_name=display_name if isinstance(display_name, str) else username,
|
||||
role_names=self._role_names(userinfo.get("roles")),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _json_response(response: HttpResponse) -> dict[str, object]:
|
||||
"""Require a successful JSON discovery response."""
|
||||
if response.status_code < 200 or response.status_code >= 300:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
return DefaultCasdoorPort._decode_json(response.body)
|
||||
|
||||
@staticmethod
|
||||
def _decode_json(body: bytes) -> dict[str, object]:
|
||||
"""Decode a JSON object without including upstream response content in errors."""
|
||||
try:
|
||||
decoded = json.loads(body)
|
||||
except (TypeError, UnicodeDecodeError, json.JSONDecodeError) as error:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable") from error
|
||||
if not isinstance(decoded, dict):
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
return decoded
|
||||
|
||||
@staticmethod
|
||||
def _required_endpoint(document: dict[str, object], key: str) -> str:
|
||||
"""Read a non-empty endpoint URL from the discovery document."""
|
||||
endpoint = document.get(key)
|
||||
if not isinstance(endpoint, str) or not endpoint:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
return endpoint
|
||||
|
||||
@staticmethod
|
||||
def _is_credential_rejection(response: HttpResponse, payload: dict[str, object]) -> bool:
|
||||
"""Recognize password-grant rejection without exposing upstream text."""
|
||||
error = payload.get("error")
|
||||
if error in {"unsupported_grant_type", "invalid_client", "server_error"}:
|
||||
return False
|
||||
if error == "invalid_grant" or response.status_code in {400, 401}:
|
||||
return True
|
||||
description = payload.get("error_description")
|
||||
return (
|
||||
error == "invalid_request"
|
||||
and isinstance(description, str)
|
||||
and any(term in description.lower() for term in ("user", "username", "password", "credential"))
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _role_names(roles: object) -> list[str]:
|
||||
"""Extract configured role names while ignoring unsupported role shapes."""
|
||||
if not isinstance(roles, list):
|
||||
return []
|
||||
names: list[str] = []
|
||||
for role in roles:
|
||||
if isinstance(role, str):
|
||||
names.append(role)
|
||||
elif isinstance(role, dict) and isinstance(role.get("name"), str):
|
||||
names.append(role["name"])
|
||||
return names
|
||||
|
||||
|
||||
def get_casdoor_port() -> CasdoorPort:
|
||||
"""Provide the production port; tests override this dependency with a stand-in."""
|
||||
return DefaultCasdoorPort()
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Accept a short-lived HXOPS assertion and turn it into a Watchman identity.
|
||||
|
||||
Verifies the assertion, then loads roles from Casdoor. Assertion permission claims are ignored.
|
||||
Depends on the RS256 verifier, settings, and a role directory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from watchman.auth.casdoor import CasdoorIdentity
|
||||
from watchman.auth.principal import RoleDirectory, get_role_directory
|
||||
from watchman.auth.token_verifier import verify_rs256_token
|
||||
from watchman.core.config import Settings, get_settings
|
||||
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||
|
||||
|
||||
class HxopsAssertionLogin:
|
||||
"""Create a Casdoor identity from one HXOPS SSO assertion."""
|
||||
|
||||
def __init__(self, settings: Settings, directory: RoleDirectory) -> None:
|
||||
self._settings = settings
|
||||
self._directory = directory
|
||||
|
||||
def authenticate(self, assertion: str) -> tuple[CasdoorIdentity, str]:
|
||||
"""Return a Casdoor identity and login name, or refuse the assertion.
|
||||
|
||||
Missing HXOPS key material is unavailable. A bad signature, a missing
|
||||
Casdoor reference, or a local user id used as that reference is unauthorized.
|
||||
Roles come only from the directory. Directory failure does not create an identity.
|
||||
"""
|
||||
settings = self._settings
|
||||
if not (settings.hxops_sso_issuer and settings.hxops_sso_audience and settings.hxops_sso_public_key):
|
||||
raise ServiceUnavailableError("HXOPS entry is unavailable")
|
||||
claims = verify_rs256_token(
|
||||
assertion,
|
||||
public_key=settings.hxops_sso_public_key,
|
||||
issuer=settings.hxops_sso_issuer,
|
||||
audience=settings.hxops_sso_audience,
|
||||
)
|
||||
subject, issuer = _casdoor_reference(claims, expected_issuer=settings.casdoor_issuer)
|
||||
login_name = _login_name(claims)
|
||||
# GUARD: never copy roles, permissions, or tokens from the assertion.
|
||||
roles = self._directory.lookup_roles(login_name=login_name)
|
||||
display_name = claims.get("name") or claims.get("preferred_username") or login_name
|
||||
if not isinstance(display_name, str) or not display_name:
|
||||
display_name = login_name
|
||||
identity = CasdoorIdentity(
|
||||
subject=subject,
|
||||
issuer=issuer,
|
||||
display_name=display_name,
|
||||
role_names=list(roles),
|
||||
)
|
||||
return identity, login_name
|
||||
|
||||
|
||||
def _casdoor_reference(claims: dict[str, object], *, expected_issuer: str) -> tuple[str, str]:
|
||||
"""Read the explicit Casdoor subject. The HXOPS token subject is not that identity."""
|
||||
if not expected_issuer:
|
||||
raise ServiceUnavailableError("HXOPS entry is unavailable")
|
||||
issuer = claims.get("identity_issuer") or claims.get("casdoor_iss")
|
||||
if not isinstance(issuer, str) or issuer != expected_issuer:
|
||||
raise UnauthorizedError()
|
||||
subject = claims.get("casdoor_sub")
|
||||
if not isinstance(subject, str) or not subject:
|
||||
raise UnauthorizedError()
|
||||
local_id = claims.get("user_id")
|
||||
if local_id is not None and str(local_id) == subject:
|
||||
raise UnauthorizedError()
|
||||
return subject, issuer
|
||||
|
||||
|
||||
def _login_name(claims: dict[str, object]) -> str:
|
||||
"""Choose the Casdoor login name used for a later role refresh."""
|
||||
for key in ("preferred_username", "employee_id"):
|
||||
value = claims.get(key)
|
||||
if isinstance(value, str) and value:
|
||||
return value
|
||||
raise UnauthorizedError()
|
||||
|
||||
|
||||
def get_hxops_login(directory: RoleDirectory = Depends(get_role_directory)) -> HxopsAssertionLogin:
|
||||
"""Provide HXOPS entry from server settings. Tests replace this dependency."""
|
||||
return HxopsAssertionLogin(get_settings(), directory)
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Reload Casdoor roles for a login name without keeping a user token.
|
||||
|
||||
Uses the application client to read one user. Tests replace the transport.
|
||||
Depends on settings and the shared HTTP transport used by password login.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from datetime import timedelta
|
||||
from typing import Protocol
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import Cookie, Depends, Request
|
||||
|
||||
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
|
||||
from watchman.auth.access import require_platform_write
|
||||
from watchman.auth.sessions import (
|
||||
SESSION_COOKIE_NAME,
|
||||
SessionStore,
|
||||
get_session_store,
|
||||
hash_cookie_token,
|
||||
read_session_token,
|
||||
utc_now,
|
||||
)
|
||||
from watchman.core.config import Settings, get_settings
|
||||
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||
|
||||
|
||||
class RoleDirectory(Protocol):
|
||||
"""Fetch the current role names for a Casdoor login name."""
|
||||
|
||||
def lookup_roles(self, *, login_name: str) -> list[str]:
|
||||
"""Return role names or raise ServiceUnavailableError. Never returns a token."""
|
||||
|
||||
|
||||
class CasdoorRoleDirectory:
|
||||
"""Read roles from Casdoor get-user using the application client."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Settings | None = None,
|
||||
transport: UrllibCasdoorHttpTransport | None = None,
|
||||
) -> None:
|
||||
self._settings = settings or get_settings()
|
||||
self._transport = transport or UrllibCasdoorHttpTransport()
|
||||
|
||||
def lookup_roles(self, *, login_name: str) -> list[str]:
|
||||
"""Load role names for organization/login_name.
|
||||
|
||||
Missing configuration, an empty login name, or a failed response raises
|
||||
ServiceUnavailableError and does not include credentials in the message.
|
||||
"""
|
||||
settings = self._settings
|
||||
# GUARD: never log the client secret or the Authorization header.
|
||||
if not (
|
||||
settings.casdoor_endpoint
|
||||
and settings.casdoor_client_id
|
||||
and settings.casdoor_client_secret
|
||||
and settings.casdoor_organization
|
||||
and login_name
|
||||
):
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
user_id = f"{quote(settings.casdoor_organization, safe='')}/{quote(login_name, safe='')}"
|
||||
url = f"{settings.casdoor_endpoint.rstrip('/')}/api/get-user?id={user_id}"
|
||||
basic = base64.b64encode(
|
||||
f"{settings.casdoor_client_id}:{settings.casdoor_client_secret}".encode()
|
||||
).decode("ascii")
|
||||
try:
|
||||
response = self._transport.request(
|
||||
method="GET",
|
||||
url=url,
|
||||
headers={"Accept": "application/json", "Authorization": f"Basic {basic}"},
|
||||
)
|
||||
except Exception as error:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable") from error
|
||||
if response.status_code < 200 or response.status_code >= 300:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
payload = DefaultCasdoorPort._decode_json(response.body)
|
||||
if payload.get("status") == "error":
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
data = payload.get("data")
|
||||
if not isinstance(data, dict):
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
return DefaultCasdoorPort._role_names(data.get("roles"))
|
||||
|
||||
|
||||
def get_role_directory() -> RoleDirectory:
|
||||
"""Provide the production role lookup; tests override this dependency."""
|
||||
return CasdoorRoleDirectory()
|
||||
|
||||
|
||||
ROLE_FRESHNESS = timedelta(minutes=5)
|
||||
|
||||
|
||||
def require_platform_writer(
|
||||
request: Request,
|
||||
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> None:
|
||||
"""Reject a platform write unless a fresh watchman-admin session is present.
|
||||
|
||||
A missing or expired session is 41000. A stale role snapshot is reloaded from
|
||||
Casdoor; if that reload fails the write is refused with 503 and the old
|
||||
roles are not used. Any other role is 42000.
|
||||
"""
|
||||
token = read_session_token(request, session_token)
|
||||
if token is None:
|
||||
raise UnauthorizedError()
|
||||
now = utc_now()
|
||||
row = sessions.get(token_hash=hash_cookie_token(token), now=now)
|
||||
if row is None:
|
||||
raise UnauthorizedError()
|
||||
roles = list(row.role_snapshot)
|
||||
if now - row.role_checked_at >= ROLE_FRESHNESS:
|
||||
roles = directory.lookup_roles(login_name=row.login_name)
|
||||
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
|
||||
require_platform_write(roles)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Session creation, lookup, and revocation for authenticated browsers.
|
||||
|
||||
Persists only token hashes and public identity snapshots through tenant-scoped SQLAlchemy sessions.
|
||||
Depends on the auth-session model and server-side Watchman settings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Protocol
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.auth.casdoor import CasdoorIdentity
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.core.db import get_db_session
|
||||
from watchman.models.auth_session import AuthSession
|
||||
|
||||
SESSION_LIFETIME = timedelta(hours=8)
|
||||
SESSION_COOKIE_NAME = "watchman_session"
|
||||
|
||||
|
||||
class SessionStore(Protocol):
|
||||
"""Persist and retrieve browser sessions without exposing their raw cookie token."""
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
token_hash: str,
|
||||
identity: CasdoorIdentity,
|
||||
now: datetime,
|
||||
login_name: str,
|
||||
) -> AuthSession:
|
||||
"""Store one identity snapshot and return its new session record."""
|
||||
|
||||
def get(self, *, token_hash: str, now: datetime) -> AuthSession | None:
|
||||
"""Return a live session or remove and hide an expired session."""
|
||||
|
||||
def invalidate(self, *, token_hash: str) -> None:
|
||||
"""Invalidate a browser session identified by its hashed cookie token."""
|
||||
|
||||
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
|
||||
"""Replace a live session's role snapshot after a successful Casdoor refresh."""
|
||||
|
||||
|
||||
class SqlAlchemySessionStore:
|
||||
"""Tenant-scoped session store backed by the application database session."""
|
||||
|
||||
def __init__(self, session: Session) -> None:
|
||||
self._session = session
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
token_hash: str,
|
||||
identity: CasdoorIdentity,
|
||||
now: datetime,
|
||||
login_name: str,
|
||||
) -> AuthSession:
|
||||
"""Save a server-owned session using only the configured tenant identity."""
|
||||
row = AuthSession(
|
||||
token_hash=token_hash,
|
||||
subject=identity.subject,
|
||||
issuer=identity.issuer,
|
||||
display_name=identity.display_name,
|
||||
login_name=login_name,
|
||||
role_snapshot=list(identity.role_names),
|
||||
role_checked_at=now,
|
||||
expires_at=now + SESSION_LIFETIME,
|
||||
tenant_id=get_settings().tenant_id,
|
||||
)
|
||||
self._session.add(row)
|
||||
self._session.commit()
|
||||
return row
|
||||
|
||||
def get(self, *, token_hash: str, now: datetime) -> AuthSession | None:
|
||||
"""Read a live session and remove stale rows so expiry cannot be reused."""
|
||||
row = self._session.scalar(
|
||||
select(AuthSession).where(
|
||||
AuthSession.token_hash == token_hash,
|
||||
AuthSession.expires_at > now,
|
||||
)
|
||||
)
|
||||
if row is not None:
|
||||
return row
|
||||
self._session.execute(
|
||||
delete(AuthSession).where(
|
||||
AuthSession.token_hash == token_hash,
|
||||
AuthSession.expires_at <= now,
|
||||
)
|
||||
)
|
||||
self._session.commit()
|
||||
return None
|
||||
|
||||
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
|
||||
"""Persist a refreshed role snapshot without changing who the session belongs to."""
|
||||
row = self._session.scalar(select(AuthSession).where(AuthSession.token_hash == token_hash))
|
||||
if row is None:
|
||||
return
|
||||
row.role_snapshot = list(role_names)
|
||||
row.role_checked_at = now
|
||||
self._session.commit()
|
||||
|
||||
def invalidate(self, *, token_hash: str) -> None:
|
||||
"""Delete the row so logout takes effect before the cookie itself expires."""
|
||||
self._session.execute(delete(AuthSession).where(AuthSession.token_hash == token_hash))
|
||||
self._session.commit()
|
||||
|
||||
|
||||
def get_session_store(session: Session = Depends(get_db_session)) -> SessionStore:
|
||||
"""Provide the tenant-scoped SQLAlchemy store; tests replace this dependency."""
|
||||
return SqlAlchemySessionStore(session)
|
||||
|
||||
|
||||
def issue_cookie_token() -> str:
|
||||
"""Return an unguessable token that is sent only in the HttpOnly cookie."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_cookie_token(token: str) -> str:
|
||||
"""Hash a raw browser token before it is used as a database lookup key."""
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def read_session_token(request: Request, cookie_token: str | None) -> str | None:
|
||||
"""Prefer the bearer token the browser stored, and fall back to the cookie."""
|
||||
authorization = request.headers.get("authorization", "")
|
||||
if authorization.lower().startswith("bearer "):
|
||||
token = authorization[7:].strip()
|
||||
if token:
|
||||
return token
|
||||
return cookie_token
|
||||
|
||||
|
||||
def utc_now() -> datetime:
|
||||
"""Return the current timezone-aware UTC instant for session expiry checks."""
|
||||
return datetime.now(timezone.utc)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Verify signed JWT identity assertions with local public keys.
|
||||
Only validates tokens; session creation and Casdoor communication remain outside this module.
|
||||
Depends on PyJWT and watchman.core.errors.UnauthorizedError."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
import jwt
|
||||
|
||||
from watchman.core.errors import UnauthorizedError
|
||||
|
||||
|
||||
def verify_rs256_token(
|
||||
token: str,
|
||||
*,
|
||||
public_key: str,
|
||||
issuer: str,
|
||||
audience: str,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Return claims only after local signature and identity checks succeed.
|
||||
|
||||
Inputs are an RS256 token, trusted public key, expected issuer/audience, and optional UTC clock;
|
||||
invalid signatures, algorithms, claims, or expiry raise UnauthorizedError without exposing details.
|
||||
"""
|
||||
current_time = now or datetime.now(timezone.utc)
|
||||
if current_time.tzinfo is None or current_time.utcoffset() is None:
|
||||
raise ValueError("now must be timezone-aware")
|
||||
|
||||
try:
|
||||
header = jwt.get_unverified_header(token)
|
||||
if header.get("alg") != "RS256":
|
||||
raise UnauthorizedError()
|
||||
claims = jwt.decode(
|
||||
token,
|
||||
public_key,
|
||||
# GUARD: RS256 only; never include none or HS*.
|
||||
algorithms=["RS256"],
|
||||
audience=audience,
|
||||
issuer=issuer,
|
||||
options={"require": ["exp"], "verify_exp": False},
|
||||
)
|
||||
_verify_expiration(claims, now=current_time)
|
||||
except (jwt.PyJWTError, TypeError, ValueError):
|
||||
raise UnauthorizedError() from None
|
||||
|
||||
return dict(claims)
|
||||
|
||||
|
||||
def _verify_expiration(claims: Mapping[str, Any], *, now: datetime) -> None:
|
||||
"""Reject expired or malformed expiry claims using the injected deterministic clock.
|
||||
|
||||
Input is a signature-verified claim mapping and UTC clock; returns only for a future numeric expiry;
|
||||
malformed, missing, or expired values raise ValueError for the public verifier to map to UnauthorizedError.
|
||||
"""
|
||||
expires_at = claims["exp"]
|
||||
if isinstance(expires_at, bool) or not isinstance(expires_at, int | float):
|
||||
raise ValueError("exp must be a numeric date")
|
||||
if expires_at <= now.timestamp():
|
||||
raise ValueError("token has expired")
|
||||
@@ -103,6 +103,14 @@ class Settings(BaseSettings):
|
||||
default="amqp://guest:CHANGE-ME@127.0.0.1:56729//",
|
||||
alias="CELERY_BROKER_URL",
|
||||
)
|
||||
casdoor_endpoint: str = Field(default="", alias="CASDOOR_ENDPOINT")
|
||||
casdoor_issuer: str = Field(default="", alias="CASDOOR_ISSUER")
|
||||
casdoor_client_id: str = Field(default="", alias="CASDOOR_CLIENT_ID")
|
||||
casdoor_client_secret: str = Field(default="", alias="CASDOOR_CLIENT_SECRET")
|
||||
casdoor_organization: str = Field(default="", alias="CASDOOR_ORGANIZATION")
|
||||
hxops_sso_issuer: str = Field(default="", alias="HXOPS_SSO_ISSUER")
|
||||
hxops_sso_audience: str = Field(default="", alias="HXOPS_SSO_AUDIENCE")
|
||||
hxops_sso_public_key: str = Field(default="", alias="HXOPS_SSO_PUBLIC_KEY")
|
||||
|
||||
|
||||
def _settings_from_env_map(env: dict[str, str]) -> Settings:
|
||||
@@ -125,6 +133,14 @@ def _settings_from_env_map(env: dict[str, str]) -> Settings:
|
||||
"CELERY_BROKER_URL",
|
||||
"amqp://guest:CHANGE-ME@127.0.0.1:56729//",
|
||||
),
|
||||
casdoor_endpoint=env.get("CASDOOR_ENDPOINT", ""),
|
||||
casdoor_issuer=env.get("CASDOOR_ISSUER", ""),
|
||||
casdoor_client_id=env.get("CASDOOR_CLIENT_ID", ""),
|
||||
casdoor_client_secret=env.get("CASDOOR_CLIENT_SECRET", ""),
|
||||
casdoor_organization=env.get("CASDOOR_ORGANIZATION", ""),
|
||||
hxops_sso_issuer=env.get("HXOPS_SSO_ISSUER", ""),
|
||||
hxops_sso_audience=env.get("HXOPS_SSO_AUDIENCE", ""),
|
||||
hxops_sso_public_key=env.get("HXOPS_SSO_PUBLIC_KEY", ""),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""SQLAlchemy models for the Watchman service package."""
|
||||
|
||||
from watchman.models.auth_session import AuthSession
|
||||
from watchman.models.platform import AuditEvent, RunRecord
|
||||
|
||||
__all__ = ["AuditEvent", "RunRecord"]
|
||||
__all__ = ["AuthSession", "AuditEvent", "RunRecord"]
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Server-side authentication session persistence.
|
||||
|
||||
Stores only public identity snapshots and a hash of the browser token; it never stores credentials.
|
||||
Depends on SQLAlchemy and the shared Watchman declarative base.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, String, func, text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from watchman.models.base import Base
|
||||
|
||||
|
||||
class AuthSession(Base):
|
||||
"""A tenant-scoped browser session with an opaque, hashed lookup token."""
|
||||
|
||||
__tablename__ = "auth_sessions"
|
||||
|
||||
token_hash: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
subject: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
issuer: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
login_name: Mapped[str] = mapped_column(String(255), nullable=False, server_default="")
|
||||
role_snapshot: Mapped[list[str]] = mapped_column(
|
||||
JSONB,
|
||||
nullable=False,
|
||||
server_default=text("'[]'::jsonb"),
|
||||
)
|
||||
role_checked_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=func.now(),
|
||||
)
|
||||
@@ -0,0 +1,364 @@
|
||||
"""Acceptance tests for M02 S2 password sessions without external Casdoor calls.
|
||||
|
||||
Uses injected in-memory ports so API tests do not require a network or local PostgreSQL.
|
||||
Depends on FastAPI dependency overrides and public authentication interfaces.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from watchman.api.app import create_app
|
||||
from watchman.auth.casdoor import CasdoorIdentity, DefaultCasdoorPort, HttpResponse, get_casdoor_port
|
||||
from watchman.auth.sessions import SESSION_LIFETIME, SessionStore, get_session_store
|
||||
from watchman.core.config import Settings
|
||||
from watchman.core.errors import ServiceUnavailableError, UnauthorizedError
|
||||
|
||||
FAKE_PASSWORD = "fixed-fake-password"
|
||||
FAKE_ACCESS_TOKEN = "fixed-fake-access-token"
|
||||
|
||||
|
||||
@dataclass
|
||||
class StoredSession:
|
||||
"""Minimal stored-session shape used by the in-memory API-test port."""
|
||||
|
||||
token_hash: str
|
||||
subject: str
|
||||
issuer: str
|
||||
display_name: str
|
||||
login_name: str
|
||||
role_snapshot: list[str]
|
||||
role_checked_at: datetime
|
||||
expires_at: datetime
|
||||
|
||||
|
||||
class InMemorySessionStore:
|
||||
"""Test-only session store preserving the production port contract."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.rows: dict[str, StoredSession] = {}
|
||||
|
||||
def create(
|
||||
self,
|
||||
*,
|
||||
token_hash: str,
|
||||
identity: CasdoorIdentity,
|
||||
now: datetime,
|
||||
login_name: str,
|
||||
) -> StoredSession:
|
||||
row = StoredSession(
|
||||
token_hash=token_hash,
|
||||
subject=identity.subject,
|
||||
issuer=identity.issuer,
|
||||
display_name=identity.display_name,
|
||||
login_name=login_name,
|
||||
role_snapshot=list(identity.role_names),
|
||||
role_checked_at=now,
|
||||
expires_at=now + SESSION_LIFETIME,
|
||||
)
|
||||
self.rows[token_hash] = row
|
||||
return row
|
||||
|
||||
def get(self, *, token_hash: str, now: datetime) -> StoredSession | None:
|
||||
row = self.rows.get(token_hash)
|
||||
if row is not None and row.expires_at > now:
|
||||
return row
|
||||
self.rows.pop(token_hash, None)
|
||||
return None
|
||||
|
||||
def invalidate(self, *, token_hash: str) -> None:
|
||||
self.rows.pop(token_hash, None)
|
||||
|
||||
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
|
||||
row = self.rows.get(token_hash)
|
||||
if row is None:
|
||||
return
|
||||
row.role_snapshot = list(role_names)
|
||||
row.role_checked_at = now
|
||||
|
||||
|
||||
class AcceptingCasdoor:
|
||||
"""Stand-in that returns only safe identity values and never contacts Casdoor."""
|
||||
|
||||
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
|
||||
if password != FAKE_PASSWORD:
|
||||
raise UnauthorizedError()
|
||||
return CasdoorIdentity(
|
||||
subject="casdoor-subject-1",
|
||||
issuer="https://casdoor.test",
|
||||
display_name="Test Operator",
|
||||
role_names=["watchman-operator", "watchman-viewer"],
|
||||
)
|
||||
|
||||
|
||||
class RejectingCasdoor:
|
||||
"""Stand-in for generic upstream credential rejection."""
|
||||
|
||||
def authenticate_password(self, *, username: str, password: str) -> CasdoorIdentity:
|
||||
raise UnauthorizedError()
|
||||
|
||||
|
||||
class FakeCasdoorTransport:
|
||||
"""Queue controlled HTTP results so Casdoor adapter tests never use the network."""
|
||||
|
||||
def __init__(self, responses: list[HttpResponse | Exception]) -> None:
|
||||
self._responses = iter(responses)
|
||||
self.calls: list[tuple[str, str, dict[str, str], bytes | None]] = []
|
||||
|
||||
def request(
|
||||
self,
|
||||
*,
|
||||
method: str,
|
||||
url: str,
|
||||
headers: dict[str, str],
|
||||
data: bytes | None = None,
|
||||
) -> HttpResponse:
|
||||
self.calls.append((method, url, headers, data))
|
||||
result = next(self._responses)
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
return result
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def auth_client() -> tuple[TestClient, InMemorySessionStore]:
|
||||
"""Return a client with only local stand-ins, avoiding database and network access."""
|
||||
app = create_app(validate_runtime=False)
|
||||
store = InMemorySessionStore()
|
||||
app.dependency_overrides[get_casdoor_port] = lambda: AcceptingCasdoor()
|
||||
app.dependency_overrides[get_session_store] = lambda: store
|
||||
with TestClient(app) as client:
|
||||
yield client, store
|
||||
|
||||
|
||||
def test_password_login_creates_session_returns_roles_and_hides_password(
|
||||
auth_client: tuple[TestClient, InMemorySessionStore],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Successful injected login must create a session without leaking the submitted password."""
|
||||
client, store = auth_client
|
||||
caplog.set_level(logging.DEBUG)
|
||||
|
||||
response = client.post(
|
||||
"/auth/login",
|
||||
json={"username": "operator", "password": FAKE_PASSWORD},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["success"] is True
|
||||
assert body["data"]["subject"] == "casdoor-subject-1"
|
||||
assert body["data"]["display_name"] == "Test Operator"
|
||||
assert body["data"]["login_name"] == "operator"
|
||||
assert body["data"]["roles"] == ["watchman-operator", "watchman-viewer"]
|
||||
assert body["data"]["token_type"] == "Bearer"
|
||||
assert body["data"]["expires_in"] == 8 * 60 * 60
|
||||
assert body["data"]["access_token"]
|
||||
assert FAKE_PASSWORD not in body["data"]["access_token"]
|
||||
assert len(store.rows) == 1
|
||||
assert FAKE_PASSWORD not in response.text
|
||||
assert FAKE_PASSWORD not in caplog.text
|
||||
cookie = response.headers["set-cookie"].lower()
|
||||
assert "httponly" in cookie
|
||||
assert "samesite=lax" in cookie
|
||||
assert "path=/" in cookie
|
||||
assert "secure" not in cookie
|
||||
|
||||
|
||||
def test_bearer_token_reads_current_user_without_cookie(
|
||||
auth_client: tuple[TestClient, InMemorySessionStore],
|
||||
) -> None:
|
||||
"""The access token returned to the browser can authorize a later request."""
|
||||
client, _store = auth_client
|
||||
login = client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD})
|
||||
token = login.json()["data"]["access_token"]
|
||||
bare = TestClient(client.app)
|
||||
response = bare.get("/auth/me", headers={"Authorization": f"Bearer {token}"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["data"]["subject"] == "casdoor-subject-1"
|
||||
assert "access_token" not in response.json()["data"]
|
||||
|
||||
|
||||
def test_rejected_login_is_unauthorized_and_creates_no_session() -> None:
|
||||
"""Casdoor credential rejection must map to 41000 without persisting a session."""
|
||||
app = create_app(validate_runtime=False)
|
||||
store = InMemorySessionStore()
|
||||
app.dependency_overrides[get_casdoor_port] = lambda: RejectingCasdoor()
|
||||
app.dependency_overrides[get_session_store] = lambda: store
|
||||
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
response = client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD})
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == 41000
|
||||
assert len(store.rows) == 0
|
||||
|
||||
|
||||
def test_unconfigured_default_port_returns_retryable_503_without_session() -> None:
|
||||
"""Incomplete Casdoor settings must fail closed before session creation."""
|
||||
app = create_app(validate_runtime=False)
|
||||
store = InMemorySessionStore()
|
||||
incomplete_settings = Settings(
|
||||
casdoor_endpoint="",
|
||||
casdoor_client_id="",
|
||||
casdoor_client_secret="",
|
||||
)
|
||||
app.dependency_overrides[get_casdoor_port] = lambda: DefaultCasdoorPort(incomplete_settings)
|
||||
app.dependency_overrides[get_session_store] = lambda: store
|
||||
|
||||
with TestClient(app, raise_server_exceptions=False) as client:
|
||||
response = client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD})
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["code"] == 50000
|
||||
assert response.json()["error"]["retryable"] is True
|
||||
assert len(store.rows) == 0
|
||||
|
||||
|
||||
def test_default_port_password_grant_returns_safe_identity_and_roles() -> None:
|
||||
"""A discovered password grant returns userinfo roles without retaining credentials."""
|
||||
transport = FakeCasdoorTransport(
|
||||
[
|
||||
HttpResponse(
|
||||
200,
|
||||
b'{"token_endpoint":"https://casdoor.test/token","userinfo_endpoint":"https://casdoor.test/userinfo"}',
|
||||
),
|
||||
HttpResponse(200, b'{"access_token":"fixed-fake-access-token"}'),
|
||||
HttpResponse(200, b'{"sub":"employee-1","name":"Employee","roles":["watchman-admin"]}'),
|
||||
]
|
||||
)
|
||||
port = DefaultCasdoorPort(
|
||||
Settings(
|
||||
casdoor_endpoint="https://casdoor.test/",
|
||||
casdoor_issuer="https://issuer.casdoor.test",
|
||||
casdoor_client_id="test-client",
|
||||
casdoor_client_secret="test-secret",
|
||||
),
|
||||
transport,
|
||||
)
|
||||
|
||||
identity = port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
|
||||
|
||||
assert identity == CasdoorIdentity(
|
||||
subject="employee-1",
|
||||
issuer="https://issuer.casdoor.test",
|
||||
display_name="Employee",
|
||||
role_names=["watchman-admin"],
|
||||
)
|
||||
assert FAKE_PASSWORD not in repr(identity)
|
||||
assert FAKE_ACCESS_TOKEN not in repr(identity)
|
||||
assert [call[0] for call in transport.calls] == ["GET", "POST", "GET"]
|
||||
assert transport.calls[0][1] == "https://casdoor.test/.well-known/openid-configuration"
|
||||
assert b"grant_type=password" in transport.calls[1][3]
|
||||
assert transport.calls[2][2]["Authorization"] == f"Bearer {FAKE_ACCESS_TOKEN}"
|
||||
|
||||
|
||||
def test_default_port_invalid_grant_is_unauthorized() -> None:
|
||||
"""Casdoor invalid_grant is a generic credential rejection."""
|
||||
transport = FakeCasdoorTransport(
|
||||
[
|
||||
HttpResponse(
|
||||
200,
|
||||
b'{"token_endpoint":"https://casdoor.test/token","userinfo_endpoint":"https://casdoor.test/userinfo"}',
|
||||
),
|
||||
HttpResponse(400, b'{"error":"invalid_grant","error_description":"upstream secret detail"}'),
|
||||
]
|
||||
)
|
||||
port = DefaultCasdoorPort(
|
||||
Settings(
|
||||
casdoor_endpoint="https://casdoor.test",
|
||||
casdoor_client_id="test-client",
|
||||
casdoor_client_secret="test-secret",
|
||||
),
|
||||
transport,
|
||||
)
|
||||
|
||||
with pytest.raises(UnauthorizedError, match="Invalid username or password"):
|
||||
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
|
||||
|
||||
|
||||
def test_default_port_unsupported_grant_is_unavailable() -> None:
|
||||
"""A disabled grant type is a configuration failure, not a wrong password."""
|
||||
transport = FakeCasdoorTransport(
|
||||
[
|
||||
HttpResponse(
|
||||
200,
|
||||
b'{"token_endpoint":"https://casdoor.test/token","userinfo_endpoint":"https://casdoor.test/userinfo"}',
|
||||
),
|
||||
HttpResponse(400, b'{"error":"unsupported_grant_type"}'),
|
||||
]
|
||||
)
|
||||
port = DefaultCasdoorPort(
|
||||
Settings(
|
||||
casdoor_endpoint="https://casdoor.test",
|
||||
casdoor_client_id="test-client",
|
||||
casdoor_client_secret="test-secret",
|
||||
),
|
||||
transport,
|
||||
)
|
||||
|
||||
with pytest.raises(ServiceUnavailableError):
|
||||
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
|
||||
|
||||
|
||||
def test_default_port_transport_failure_is_retryable() -> None:
|
||||
"""Network failures are mapped to the retryable integration error."""
|
||||
transport = FakeCasdoorTransport([OSError("network unavailable")])
|
||||
port = DefaultCasdoorPort(
|
||||
Settings(
|
||||
casdoor_endpoint="https://casdoor.test",
|
||||
casdoor_client_id="test-client",
|
||||
casdoor_client_secret="test-secret",
|
||||
),
|
||||
transport,
|
||||
)
|
||||
|
||||
with pytest.raises(ServiceUnavailableError):
|
||||
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
|
||||
|
||||
|
||||
def test_unconfigured_default_port_does_not_call_transport() -> None:
|
||||
"""Missing Casdoor configuration fails before the injected transport is used."""
|
||||
transport = FakeCasdoorTransport([])
|
||||
port = DefaultCasdoorPort(Settings(), transport)
|
||||
|
||||
with pytest.raises(ServiceUnavailableError):
|
||||
port.authenticate_password(username="employee-1", password=FAKE_PASSWORD)
|
||||
|
||||
assert transport.calls == []
|
||||
|
||||
|
||||
def test_logout_invalidates_session_and_me_then_returns_41000(
|
||||
auth_client: tuple[TestClient, InMemorySessionStore],
|
||||
) -> None:
|
||||
"""Logout must remove the server-side session before a later current-user request."""
|
||||
client, _store = auth_client
|
||||
assert client.post("/auth/login", json={"username": "operator", "password": FAKE_PASSWORD}).status_code == 200
|
||||
assert client.get("/auth/me").status_code == 200
|
||||
|
||||
logout = client.post("/auth/logout")
|
||||
assert logout.status_code == 200
|
||||
assert "max-age=0" in logout.headers["set-cookie"].lower()
|
||||
|
||||
me = client.get("/auth/me")
|
||||
assert me.status_code == 401
|
||||
assert me.json()["error"]["code"] == 41000
|
||||
|
||||
|
||||
def test_health_remains_anonymous_and_missing_login_fields_are_40000() -> None:
|
||||
"""The auth router must not introduce a global auth requirement or bypass validation envelopes."""
|
||||
app = create_app(validate_runtime=False)
|
||||
app.dependency_overrides[get_casdoor_port] = lambda: AcceptingCasdoor()
|
||||
app.dependency_overrides[get_session_store] = lambda: InMemorySessionStore()
|
||||
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/health").status_code == 200
|
||||
response = client.post("/auth/login", json={"username": "operator"})
|
||||
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == 40000
|
||||
@@ -0,0 +1,221 @@
|
||||
"""HXOPS assertion entry tests.
|
||||
|
||||
Uses an in-memory session and a scripted role directory. No network and no .env.local.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import jwt
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from watchman.api.app import create_app
|
||||
from watchman.auth.casdoor import CasdoorIdentity
|
||||
from watchman.auth.hxops import HxopsAssertionLogin, get_hxops_login
|
||||
from watchman.auth.sessions import SESSION_LIFETIME, get_session_store
|
||||
from watchman.core.config import Settings
|
||||
from watchman.core.errors import ServiceUnavailableError
|
||||
|
||||
ISSUER = "https://hxops.test"
|
||||
AUDIENCE = "watchman"
|
||||
CASDOOR_ISSUER = "https://casdoor.test"
|
||||
NOW = datetime(2030, 1, 1, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
class MemoryStore:
|
||||
"""Small session stand-in for the assertion route."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.rows: dict[str, object] = {}
|
||||
|
||||
def create(self, *, token_hash: str, identity: CasdoorIdentity, now: datetime, login_name: str) -> object:
|
||||
row = type(
|
||||
"Row",
|
||||
(),
|
||||
{
|
||||
"subject": identity.subject,
|
||||
"display_name": identity.display_name,
|
||||
"role_snapshot": list(identity.role_names),
|
||||
"login_name": login_name,
|
||||
"expires_at": now + SESSION_LIFETIME,
|
||||
},
|
||||
)()
|
||||
self.rows[token_hash] = row
|
||||
return row
|
||||
|
||||
def get(self, *, token_hash: str, now: datetime) -> object | None:
|
||||
row = self.rows.get(token_hash)
|
||||
if row is not None and row.expires_at > now:
|
||||
return row
|
||||
return None
|
||||
|
||||
def invalidate(self, *, token_hash: str) -> None:
|
||||
self.rows.pop(token_hash, None)
|
||||
|
||||
def update_roles(self, *, token_hash: str, role_names: list[str], now: datetime) -> None:
|
||||
del token_hash, role_names, now
|
||||
|
||||
|
||||
class Directory:
|
||||
def __init__(self, roles: list[str] | None = None, fail: bool = False) -> None:
|
||||
self.roles = roles or ["watchman-viewer"]
|
||||
self.fail = fail
|
||||
self.login_name = ""
|
||||
|
||||
def lookup_roles(self, *, login_name: str) -> list[str]:
|
||||
if self.fail:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
self.login_name = login_name
|
||||
return list(self.roles)
|
||||
|
||||
|
||||
def _keys() -> tuple[rsa.RSAPrivateKey, str]:
|
||||
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
public_pem = private_key.public_key().public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
).decode()
|
||||
return private_key, public_pem
|
||||
|
||||
|
||||
def _settings(public_pem: str) -> Settings:
|
||||
return Settings(
|
||||
hxops_sso_issuer=ISSUER,
|
||||
hxops_sso_audience=AUDIENCE,
|
||||
hxops_sso_public_key=public_pem,
|
||||
casdoor_issuer=CASDOOR_ISSUER,
|
||||
)
|
||||
|
||||
|
||||
def _token(private_key: rsa.RSAPrivateKey, **overrides: object) -> str:
|
||||
claims: dict[str, object] = {
|
||||
"iss": ISSUER,
|
||||
"aud": AUDIENCE,
|
||||
"sub": "1001",
|
||||
"casdoor_sub": "casdoor-subject-1",
|
||||
"identity_issuer": CASDOOR_ISSUER,
|
||||
"preferred_username": "26110002",
|
||||
"name": "Worker",
|
||||
"user_id": 1001,
|
||||
"roles": ["watchman-admin"],
|
||||
"exp": int((NOW + timedelta(seconds=60)).timestamp()),
|
||||
}
|
||||
claims.update(overrides)
|
||||
return jwt.encode(claims, private_key, algorithm="RS256")
|
||||
|
||||
|
||||
def _client(entry: HxopsAssertionLogin, store: MemoryStore) -> TestClient:
|
||||
app = create_app(validate_runtime=False)
|
||||
app.dependency_overrides[get_hxops_login] = lambda: entry
|
||||
app.dependency_overrides[get_session_store] = lambda: store
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_valid_assertion_uses_directory_roles_not_assertion_roles() -> None:
|
||||
"""A signed assertion opens a session, and Casdoor roles replace assertion roles."""
|
||||
private_key, public_pem = _keys()
|
||||
directory = Directory(["watchman-viewer"])
|
||||
store = MemoryStore()
|
||||
entry = HxopsAssertionLogin(_settings(public_pem), directory)
|
||||
client = _client(entry, store)
|
||||
|
||||
response = client.post("/auth/hxops-entry", json={"assertion": _token(private_key)})
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["data"]["roles"] == ["watchman-viewer"]
|
||||
assert response.json()["data"]["subject"] == "casdoor-subject-1"
|
||||
assert directory.login_name == "26110002"
|
||||
assert len(store.rows) == 1
|
||||
assert "watchman-admin" not in response.text
|
||||
|
||||
|
||||
def test_local_user_id_cannot_impersonate_casdoor_subject() -> None:
|
||||
"""Using the HXOPS primary key as the Casdoor subject does not create a session."""
|
||||
private_key, public_pem = _keys()
|
||||
store = MemoryStore()
|
||||
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
|
||||
client = _client(entry, store)
|
||||
|
||||
response = client.post(
|
||||
"/auth/hxops-entry",
|
||||
json={"assertion": _token(private_key, casdoor_sub="1001")},
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == 41000
|
||||
assert len(store.rows) == 0
|
||||
|
||||
|
||||
def test_hxops_subject_without_casdoor_sub_is_unauthorized() -> None:
|
||||
"""The HXOPS token subject is not accepted when casdoor_sub is absent."""
|
||||
private_key, public_pem = _keys()
|
||||
store = MemoryStore()
|
||||
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
|
||||
client = _client(entry, store)
|
||||
|
||||
response = client.post(
|
||||
"/auth/hxops-entry",
|
||||
json={"assertion": _token(private_key, sub="1001", casdoor_sub="", user_id=None)},
|
||||
)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert response.json()["error"]["code"] == 41000
|
||||
assert len(store.rows) == 0
|
||||
|
||||
|
||||
def test_missing_casdoor_reference_is_unauthorized() -> None:
|
||||
"""An assertion without a Casdoor issuer reference is rejected."""
|
||||
private_key, public_pem = _keys()
|
||||
store = MemoryStore()
|
||||
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
|
||||
client = _client(entry, store)
|
||||
token = _token(private_key, identity_issuer="", casdoor_iss="")
|
||||
|
||||
response = client.post("/auth/hxops-entry", json={"assertion": token})
|
||||
|
||||
assert response.status_code == 401
|
||||
assert len(store.rows) == 0
|
||||
|
||||
|
||||
def test_bad_signature_creates_no_session() -> None:
|
||||
"""A token signed by another key cannot enter."""
|
||||
_, public_pem = _keys()
|
||||
other, _ = _keys()
|
||||
store = MemoryStore()
|
||||
entry = HxopsAssertionLogin(_settings(public_pem), Directory())
|
||||
client = _client(entry, store)
|
||||
|
||||
response = client.post("/auth/hxops-entry", json={"assertion": _token(other)})
|
||||
|
||||
assert response.status_code == 401
|
||||
assert len(store.rows) == 0
|
||||
|
||||
|
||||
def test_directory_failure_creates_no_session() -> None:
|
||||
"""If Casdoor cannot supply roles, the assertion does not become a session."""
|
||||
private_key, public_pem = _keys()
|
||||
store = MemoryStore()
|
||||
entry = HxopsAssertionLogin(_settings(public_pem), Directory(fail=True))
|
||||
client = _client(entry, store)
|
||||
|
||||
response = client.post("/auth/hxops-entry", json={"assertion": _token(private_key)})
|
||||
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["retryable"] is True
|
||||
assert len(store.rows) == 0
|
||||
|
||||
|
||||
def test_unconfigured_hxops_entry_is_unavailable() -> None:
|
||||
"""Missing HXOPS key material fails before role lookup."""
|
||||
directory = Directory()
|
||||
entry = HxopsAssertionLogin(Settings(), directory)
|
||||
try:
|
||||
entry.authenticate("not-a-token")
|
||||
except ServiceUnavailableError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("unconfigured entry did not fail")
|
||||
assert directory.login_name == ""
|
||||
@@ -5,14 +5,18 @@ from __future__ import annotations
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from watchman.api.app import create_app
|
||||
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
|
||||
from watchman.core.config import get_settings, reload_settings
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.core.db import get_session_factory, reset_engine, set_tenant
|
||||
from watchman.models.auth_session import AuthSession
|
||||
from watchman.models.platform import AuditEvent
|
||||
from watchman.services import platform_records
|
||||
from sqlalchemy import select
|
||||
@@ -34,10 +38,45 @@ def _count_for_key(table: str, key: str) -> int:
|
||||
return int(value)
|
||||
|
||||
|
||||
def _admin_token() -> str:
|
||||
"""Insert a fresh admin session and return the raw cookie token."""
|
||||
token = issue_cookie_token()
|
||||
now = datetime.now(timezone.utc)
|
||||
settings = get_settings()
|
||||
factory = get_session_factory()
|
||||
session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
session.add(
|
||||
AuthSession(
|
||||
token_hash=hash_cookie_token(token),
|
||||
subject="idem-admin",
|
||||
issuer="https://casdoor.test",
|
||||
display_name="Idem Admin",
|
||||
login_name="idem-admin",
|
||||
role_snapshot=["watchman-admin"],
|
||||
role_checked_at=now,
|
||||
expires_at=now + timedelta(hours=1),
|
||||
tenant_id=settings.tenant_id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
return token
|
||||
|
||||
|
||||
def _admin_client() -> TestClient:
|
||||
"""Return an API client that already carries a fresh admin session."""
|
||||
client = TestClient(create_app())
|
||||
client.cookies.set(SESSION_COOKIE_NAME, _admin_token())
|
||||
return client
|
||||
|
||||
|
||||
def test_duplicate_idempotency_key_returns_same_audit() -> None:
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
client = TestClient(create_app())
|
||||
client = _admin_client()
|
||||
key = f"idem-audit-{uuid.uuid4().hex}"
|
||||
headers = {"x-idempotency-key": key, "X-Request-Id": "req-idem-1"}
|
||||
body = {"action": "idem-test", "payload": {"n": 1}}
|
||||
@@ -52,7 +91,7 @@ def test_duplicate_idempotency_key_returns_same_audit() -> None:
|
||||
def test_duplicate_idempotency_key_returns_same_run_record() -> None:
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
client = TestClient(create_app())
|
||||
client = _admin_client()
|
||||
key = f"idem-run-{uuid.uuid4().hex}"
|
||||
headers = {"x-idempotency-key": key, "X-Request-Id": "req-idem-2"}
|
||||
body = {"kind": "idem-test", "status": "ok", "detail": {"n": 1}}
|
||||
@@ -67,7 +106,7 @@ def test_duplicate_idempotency_key_returns_same_run_record() -> None:
|
||||
def test_missing_idempotency_key_is_40000() -> None:
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
client = TestClient(create_app())
|
||||
client = _admin_client()
|
||||
response = client.post("/platform/audit-events", json={"action": "no-key", "payload": {}})
|
||||
assert response.status_code == 400
|
||||
assert response.json()["error"]["code"] == 40000
|
||||
@@ -79,8 +118,11 @@ def test_concurrent_duplicate_audit_returns_same_id() -> None:
|
||||
key = f"idem-race-{uuid.uuid4().hex}"
|
||||
body = {"action": "race", "payload": {}}
|
||||
|
||||
token = _admin_token()
|
||||
|
||||
def _post() -> str:
|
||||
client = TestClient(create_app())
|
||||
client.cookies.set(SESSION_COOKIE_NAME, token)
|
||||
response = client.post(
|
||||
"/platform/audit-events",
|
||||
json=body,
|
||||
@@ -99,7 +141,7 @@ def test_caller_tenant_id_is_ignored() -> None:
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
settings = get_settings()
|
||||
client = TestClient(create_app())
|
||||
client = _admin_client()
|
||||
key = f"tenant-inject-{uuid.uuid4().hex}"
|
||||
response = client.post(
|
||||
"/platform/audit-events",
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""Platform write authorization and object-access checks.
|
||||
|
||||
Covers anonymous denial, role denial, admin allowance, and stale role refresh.
|
||||
Depends on a local Postgres session row and an injected role directory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from watchman.api.app import create_app
|
||||
from watchman.auth.access import (
|
||||
OBJECT_READ_NODE,
|
||||
PLATFORM_WRITE_NODE,
|
||||
allows_enter,
|
||||
require_object_access,
|
||||
)
|
||||
from watchman.auth.casdoor import HttpResponse
|
||||
from watchman.auth.principal import CasdoorRoleDirectory, get_role_directory
|
||||
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
|
||||
from watchman.core.config import Settings, get_settings, reload_settings
|
||||
from watchman.core.db import get_session_factory, reset_engine, set_tenant
|
||||
from watchman.core.errors import ForbiddenError, ServiceUnavailableError
|
||||
from watchman.models.auth_session import AuthSession
|
||||
|
||||
|
||||
def _seed(roles: list[str], *, age: timedelta = timedelta(0), login_name: str = "worker") -> str:
|
||||
"""Insert one session and return its raw cookie token."""
|
||||
token = issue_cookie_token()
|
||||
now = datetime.now(timezone.utc)
|
||||
settings = get_settings()
|
||||
session = get_session_factory()()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
session.add(
|
||||
AuthSession(
|
||||
token_hash=hash_cookie_token(token),
|
||||
subject=f"subject-{uuid.uuid4().hex}",
|
||||
issuer="https://casdoor.test",
|
||||
display_name="Worker",
|
||||
login_name=login_name,
|
||||
role_snapshot=list(roles),
|
||||
role_checked_at=now - age,
|
||||
expires_at=now + timedelta(hours=1),
|
||||
tenant_id=settings.tenant_id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
return token
|
||||
|
||||
|
||||
def _client(token: str | None, directory: object | None = None) -> TestClient:
|
||||
"""Build a client, optionally replacing Casdoor role lookup."""
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
app = create_app()
|
||||
if directory is not None:
|
||||
app.dependency_overrides[get_role_directory] = lambda: directory
|
||||
client = TestClient(app)
|
||||
if token is not None:
|
||||
client.cookies.set(SESSION_COOKIE_NAME, token)
|
||||
return client
|
||||
|
||||
|
||||
def test_anonymous_platform_write_is_401_without_permission_node() -> None:
|
||||
"""A missing session is unauthorized and must not name a permission node."""
|
||||
client = _client(None)
|
||||
response = client.post(
|
||||
"/platform/audit-events",
|
||||
json={"action": "hidden", "payload": {}},
|
||||
headers={"x-idempotency-key": f"anon-{uuid.uuid4().hex}"},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
error = response.json()["error"]
|
||||
assert error["code"] == 41000
|
||||
assert "permission_node" not in error
|
||||
|
||||
|
||||
def test_viewer_platform_write_is_forbidden() -> None:
|
||||
"""A viewer session cannot create an audit event."""
|
||||
client = _client(_seed(["watchman-viewer"]))
|
||||
response = client.post(
|
||||
"/platform/audit-events",
|
||||
json={"action": "hidden", "payload": {}},
|
||||
headers={"x-idempotency-key": f"viewer-{uuid.uuid4().hex}"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
assert response.json()["error"]["permission_node"] == PLATFORM_WRITE_NODE
|
||||
|
||||
|
||||
def test_admin_platform_write_is_allowed() -> None:
|
||||
"""A fresh admin session can create a run record."""
|
||||
client = _client(_seed(["watchman-admin"]))
|
||||
response = client.post(
|
||||
"/platform/run-records",
|
||||
json={"kind": "check", "status": "ok", "detail": {}},
|
||||
headers={"x-idempotency-key": f"admin-{uuid.uuid4().hex}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["success"] is True
|
||||
|
||||
|
||||
def test_stale_roles_fail_closed_when_directory_is_down() -> None:
|
||||
"""An expired role snapshot is not reused when Casdoor cannot be asked."""
|
||||
|
||||
class DownDirectory:
|
||||
def lookup_roles(self, *, login_name: str) -> list[str]:
|
||||
raise ServiceUnavailableError("Casdoor login is unavailable")
|
||||
|
||||
client = _client(_seed(["watchman-admin"], age=timedelta(minutes=6)), DownDirectory())
|
||||
response = client.post(
|
||||
"/platform/audit-events",
|
||||
json={"action": "stale", "payload": {}},
|
||||
headers={"x-idempotency-key": f"stale-{uuid.uuid4().hex}"},
|
||||
)
|
||||
assert response.status_code == 503
|
||||
assert response.json()["error"]["retryable"] is True
|
||||
|
||||
|
||||
def test_stale_roles_refresh_before_write() -> None:
|
||||
"""A successful refresh replaces the snapshot and then allows the admin write."""
|
||||
|
||||
class AdminDirectory:
|
||||
def lookup_roles(self, *, login_name: str) -> list[str]:
|
||||
assert login_name == "worker"
|
||||
return ["watchman-admin"]
|
||||
|
||||
client = _client(_seed(["watchman-viewer"], age=timedelta(minutes=6)), AdminDirectory())
|
||||
response = client.post(
|
||||
"/platform/audit-events",
|
||||
json={"action": "refreshed", "payload": {}},
|
||||
headers={"x-idempotency-key": f"refresh-{uuid.uuid4().hex}"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_enter_and_object_rules() -> None:
|
||||
"""Enter allows only the three roles. Object ids never authorize themselves."""
|
||||
assert allows_enter(["watchman-admin"])
|
||||
assert allows_enter(["watchman-operator"])
|
||||
assert allows_enter(["watchman-viewer"])
|
||||
assert not allows_enter([])
|
||||
assert not allows_enter(["someone-else"])
|
||||
for object_id in ("object-a", "object-b"):
|
||||
try:
|
||||
require_object_access(["watchman-admin"], object_id)
|
||||
except ForbiddenError as exc:
|
||||
assert exc.permission_node == OBJECT_READ_NODE
|
||||
else:
|
||||
raise AssertionError(object_id)
|
||||
|
||||
|
||||
class _ScriptedTransport:
|
||||
def __init__(self, response: HttpResponse) -> None:
|
||||
self.response = response
|
||||
self.calls = 0
|
||||
|
||||
def request(self, *, method: str, url: str, headers: dict[str, str], data: bytes | None = None) -> HttpResponse:
|
||||
self.calls += 1
|
||||
return self.response
|
||||
|
||||
|
||||
def test_role_directory_reads_names_without_calling_when_unconfigured() -> None:
|
||||
"""Role lookup parses Casdoor role names and does not run without configuration."""
|
||||
transport = _ScriptedTransport(
|
||||
HttpResponse(200, b'{"status":"ok","data":{"roles":[{"name":"watchman-admin"}]}}')
|
||||
)
|
||||
directory = CasdoorRoleDirectory(
|
||||
Settings(
|
||||
casdoor_endpoint="https://casdoor.test",
|
||||
casdoor_client_id="client",
|
||||
casdoor_client_secret="secret",
|
||||
casdoor_organization="organization_HX",
|
||||
),
|
||||
transport,
|
||||
)
|
||||
assert directory.lookup_roles(login_name="worker") == ["watchman-admin"]
|
||||
assert transport.calls == 1
|
||||
bare = CasdoorRoleDirectory(Settings(), transport)
|
||||
try:
|
||||
bare.lookup_roles(login_name="worker")
|
||||
except ServiceUnavailableError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("unconfigured lookup called the transport")
|
||||
assert transport.calls == 1
|
||||
@@ -0,0 +1,205 @@
|
||||
"""Acceptance tests for local RS256 JWT verification.
|
||||
Locks requirement criterion 1 without HTTP routes, sessions, or external identity providers.
|
||||
Depends on in-memory RSA keys, PyJWT, and the Watchman verifier."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
from watchman.auth.token_verifier import verify_rs256_token
|
||||
from watchman.core.errors import UnauthorizedError
|
||||
|
||||
ISSUER = "https://issuer.test/watchman"
|
||||
AUDIENCE = "watchman-test"
|
||||
NOW = datetime(2030, 1, 1, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rsa_keys() -> tuple[rsa.RSAPrivateKey, str, bytes]:
|
||||
"""Create test-only RSA material without persisting any key data.
|
||||
|
||||
Returns private signing material plus PEM and DER public representations for local verification;
|
||||
key generation failures fail the test process before any token assertion can run.
|
||||
"""
|
||||
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
public_key = private_key.public_key()
|
||||
public_pem = public_key.public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
).decode()
|
||||
public_der = public_key.public_bytes(
|
||||
encoding=serialization.Encoding.DER,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
)
|
||||
return private_key, public_pem, public_der
|
||||
|
||||
|
||||
def _claims(**overrides: Any) -> dict[str, Any]:
|
||||
"""Build signed-token claims that satisfy the local verifier's expected identity contract.
|
||||
|
||||
Optional overrides replace the default issuer, audience, or expiry values; callers use them to create
|
||||
a specific rejection case while retaining a valid claim shape.
|
||||
"""
|
||||
claims: dict[str, Any] = {
|
||||
"sub": "test-subject",
|
||||
"iss": ISSUER,
|
||||
"aud": AUDIENCE,
|
||||
"exp": int((NOW + timedelta(minutes=5)).timestamp()),
|
||||
}
|
||||
claims.update(overrides)
|
||||
return claims
|
||||
|
||||
|
||||
def _signed_token(private_key: rsa.RSAPrivateKey, **overrides: Any) -> str:
|
||||
"""Sign a valid baseline claim set so each test isolates one acceptance condition.
|
||||
|
||||
Input is in-memory RSA material and optional claim replacements; signing failures surface to the test
|
||||
rather than being confused with the verifier's unauthorized result.
|
||||
"""
|
||||
return jwt.encode(_claims(**overrides), private_key, algorithm="RS256")
|
||||
|
||||
|
||||
def test_verifier_returns_claims_after_valid_rs256_signature_and_checks(
|
||||
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
|
||||
) -> None:
|
||||
"""Locks acceptance criterion 1's required success case after all verification checks pass."""
|
||||
private_key, public_pem, _ = rsa_keys
|
||||
|
||||
claims = verify_rs256_token(
|
||||
_signed_token(private_key),
|
||||
public_key=public_pem,
|
||||
issuer=ISSUER,
|
||||
audience=AUDIENCE,
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
assert claims["sub"] == "test-subject"
|
||||
|
||||
|
||||
def test_verifier_rejects_invalid_signature(
|
||||
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
|
||||
) -> None:
|
||||
"""Locks acceptance criterion 1: a token signed by another key cannot authenticate."""
|
||||
_, public_pem, _ = rsa_keys
|
||||
other_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
|
||||
with pytest.raises(UnauthorizedError):
|
||||
verify_rs256_token(
|
||||
_signed_token(other_private_key),
|
||||
public_key=public_pem,
|
||||
issuer=ISSUER,
|
||||
audience=AUDIENCE,
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
|
||||
def test_verifier_rejects_wrong_issuer(
|
||||
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
|
||||
) -> None:
|
||||
"""Locks acceptance criterion 1: a signed token from another issuer cannot authenticate."""
|
||||
private_key, public_pem, _ = rsa_keys
|
||||
|
||||
with pytest.raises(UnauthorizedError):
|
||||
verify_rs256_token(
|
||||
_signed_token(private_key, iss="https://issuer.test/other"),
|
||||
public_key=public_pem,
|
||||
issuer=ISSUER,
|
||||
audience=AUDIENCE,
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
|
||||
def test_verifier_rejects_wrong_audience(
|
||||
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
|
||||
) -> None:
|
||||
"""Locks acceptance criterion 1: a signed token for another audience cannot authenticate."""
|
||||
private_key, public_pem, _ = rsa_keys
|
||||
|
||||
with pytest.raises(UnauthorizedError):
|
||||
verify_rs256_token(
|
||||
_signed_token(private_key, aud="another-service"),
|
||||
public_key=public_pem,
|
||||
issuer=ISSUER,
|
||||
audience=AUDIENCE,
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
|
||||
def test_verifier_rejects_clearly_expired_token(
|
||||
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
|
||||
) -> None:
|
||||
"""Locks acceptance criterion 1: deterministic expiry before now cannot authenticate."""
|
||||
private_key, public_pem, _ = rsa_keys
|
||||
|
||||
with pytest.raises(UnauthorizedError):
|
||||
verify_rs256_token(
|
||||
_signed_token(private_key, exp=int((NOW - timedelta(days=1)).timestamp())),
|
||||
public_key=public_pem,
|
||||
issuer=ISSUER,
|
||||
audience=AUDIENCE,
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
|
||||
def test_verifier_rejects_unsigned_none_algorithm_token(
|
||||
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Locks the explicit S1 algorithm policy: unsigned alg none tokens cannot authenticate."""
|
||||
_, public_pem, _ = rsa_keys
|
||||
token = jwt.encode(_claims(), key=None, algorithm="none")
|
||||
monkeypatch.setattr(
|
||||
jwt,
|
||||
"decode",
|
||||
lambda *args, **kwargs: pytest.fail("jwt.decode must not process alg none tokens"),
|
||||
)
|
||||
|
||||
with pytest.raises(UnauthorizedError):
|
||||
verify_rs256_token(
|
||||
token,
|
||||
public_key=public_pem,
|
||||
issuer=ISSUER,
|
||||
audience=AUDIENCE,
|
||||
now=NOW,
|
||||
)
|
||||
|
||||
|
||||
def test_verifier_rejects_hs256_public_key_confusion(
|
||||
rsa_keys: tuple[rsa.RSAPrivateKey, str, bytes],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""Locks the explicit S1 algorithm policy: public-key-as-HMAC tokens cannot authenticate."""
|
||||
_, public_pem, public_der = rsa_keys
|
||||
encoded_header = base64.urlsafe_b64encode(
|
||||
json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode()
|
||||
).rstrip(b"=")
|
||||
encoded_claims = base64.urlsafe_b64encode(
|
||||
json.dumps(_claims(), separators=(",", ":")).encode()
|
||||
).rstrip(b"=")
|
||||
signing_input = encoded_header + b"." + encoded_claims
|
||||
signature = hmac.new(public_der, signing_input, hashlib.sha256).digest()
|
||||
token = f"{signing_input.decode()}.{base64.urlsafe_b64encode(signature).rstrip(b'=').decode()}"
|
||||
monkeypatch.setattr(
|
||||
jwt,
|
||||
"decode",
|
||||
lambda *args, **kwargs: pytest.fail("jwt.decode must not process HS256 tokens"),
|
||||
)
|
||||
|
||||
with pytest.raises(UnauthorizedError):
|
||||
verify_rs256_token(
|
||||
token,
|
||||
public_key=public_pem,
|
||||
issuer=ISSUER,
|
||||
audience=AUDIENCE,
|
||||
now=NOW,
|
||||
)
|
||||
@@ -7,8 +7,23 @@ const evidenceDir = path.resolve(
|
||||
"../../../../docs/evidence/M01/ui",
|
||||
);
|
||||
|
||||
async function signedInAdmin(page: import("@playwright/test").Page) {
|
||||
await page.route("**/auth/me", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
success: true,
|
||||
data: { subject: "admin-1", display_name: "Admin", roles: ["watchman-admin"] },
|
||||
request_id: "pw-me",
|
||||
}),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test.describe("health three states", () => {
|
||||
test("loading then success", async ({ page }) => {
|
||||
await signedInAdmin(page);
|
||||
await page.route("**/health", async (route) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
await route.fulfill({
|
||||
@@ -38,6 +53,7 @@ test.describe("health three states", () => {
|
||||
});
|
||||
|
||||
test("failure state", async ({ page }) => {
|
||||
await signedInAdmin(page);
|
||||
await page.route("**/health", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 500,
|
||||
@@ -66,6 +82,7 @@ test.describe("health three states", () => {
|
||||
});
|
||||
|
||||
test("english locale via query override is readable", async ({ page }) => {
|
||||
await signedInAdmin(page);
|
||||
await page.addInitScript(() => {
|
||||
window.localStorage.setItem("watchman.lang", "en");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const evidenceDir = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"../../../../docs/evidence/M02/ui",
|
||||
);
|
||||
|
||||
function envelope(data: unknown) {
|
||||
return JSON.stringify({ success: true, data, request_id: "pw-login" });
|
||||
}
|
||||
|
||||
test.describe("login shell", () => {
|
||||
test("sign in as an admin, see the shell, then sign out", async ({ page }) => {
|
||||
await page.route("**/auth/me", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
success: false,
|
||||
error: { code: 41000, message: "Unauthorized", details: {}, retryable: false },
|
||||
request_id: "pw-anon",
|
||||
}),
|
||||
});
|
||||
});
|
||||
await page.route("**/auth/login", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: envelope({
|
||||
subject: "casdoor-subject-1",
|
||||
display_name: "高昊宇",
|
||||
roles: ["watchman-admin"],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await page.route("**/health", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: envelope({ status: "ok", app: "watchman", version: "0.1.0" }),
|
||||
});
|
||||
});
|
||||
await page.route("**/auth/logout", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: envelope({ logged_out: true }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await expect(page.getByTestId("login-submit")).toBeVisible();
|
||||
await page.getByTestId("login-username").locator("input").fill("26110002");
|
||||
await page.getByTestId("login-password").locator("input").fill("simulated-password");
|
||||
await page.getByTestId("login-submit").click();
|
||||
|
||||
await expect(page.getByTestId("shell-welcome")).toContainText("已登录:高昊宇");
|
||||
await expect(page.getByTestId("health-success")).toBeVisible();
|
||||
await expect(page.getByTestId("health-tag")).toContainText("健康检查成功");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "login-success.png"), fullPage: true });
|
||||
|
||||
await page.getByTestId("logout").click();
|
||||
await expect(page.getByTestId("login-submit")).toBeVisible();
|
||||
await expect(page.getByTestId("shell-welcome")).toHaveCount(0);
|
||||
});
|
||||
|
||||
test("failed sign-in stays on the form", async ({ page }) => {
|
||||
await page.route("**/auth/me", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
success: false,
|
||||
error: { code: 41000, message: "Unauthorized", details: {}, retryable: false },
|
||||
request_id: "pw-anon",
|
||||
}),
|
||||
});
|
||||
});
|
||||
await page.route("**/auth/login", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: "application/json",
|
||||
body: JSON.stringify({
|
||||
success: false,
|
||||
error: { code: 41000, message: "Invalid username or password", details: {}, retryable: false },
|
||||
request_id: "pw-bad",
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await expect(page.getByTestId("login-submit")).toBeVisible();
|
||||
await page.getByTestId("login-username").locator("input").fill("26110002");
|
||||
await page.getByTestId("login-password").locator("input").fill("wrong-password");
|
||||
await page.getByTestId("login-submit").click();
|
||||
await expect(page.getByTestId("login-error")).toContainText("登录失败");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "login-failed.png"), fullPage: true });
|
||||
});
|
||||
|
||||
test("a session without a Watchman role can sign out", async ({ page }) => {
|
||||
await page.route("**/auth/me", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: envelope({ subject: "user-1", display_name: "No Role", roles: [] }),
|
||||
});
|
||||
});
|
||||
await page.route("**/auth/logout", async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: "application/json",
|
||||
body: envelope({ logged_out: true }),
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto("/");
|
||||
await expect(page.getByTestId("forbidden")).toBeVisible();
|
||||
await page.screenshot({ path: path.join(evidenceDir, "login-forbidden.png"), fullPage: true });
|
||||
await page.getByTestId("logout").click();
|
||||
await expect(page.getByTestId("login-submit")).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,31 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"login": {
|
||||
"title": "Sign in to Watchman",
|
||||
"subtitle": "Use your company account to open the alert platform",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"heroEm": "visible",
|
||||
"heroBefore": "Make exceptions ",
|
||||
"submitting": "Signing in",
|
||||
"account": "Account",
|
||||
"accountPlaceholder": "Employee ID",
|
||||
"passwordPlaceholder": "Password",
|
||||
"cardTitle": "Sign in",
|
||||
"theme": "Toggle theme",
|
||||
"footer": "© 2026 和信精密 · HEXIN PRECISION",
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"submit": "Sign in",
|
||||
"failed": "Sign-in failed. Check the account and password.",
|
||||
"unavailable": "Sign-in is temporarily unavailable. Try again shortly.",
|
||||
"logout": "Sign out",
|
||||
"forbiddenTitle": "No access",
|
||||
"forbiddenBody": "This account is signed in, but it does not have a Watchman view, operate, or admin role.",
|
||||
"fixture": "Local identity mode. This is not a production sign-in."
|
||||
},
|
||||
"shell": {
|
||||
"welcome": "Signed in: {name}"
|
||||
},
|
||||
"health": {
|
||||
"loading": "Checking health",
|
||||
"success": "Health check succeeded",
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"login": {
|
||||
"title": "เข้าสู่ Watchman",
|
||||
"subtitle": "ใช้บัญชีบริษัทเพื่อเข้าสู่แพลตฟอร์มแจ้งเตือน",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"heroEm": "เห็นได้",
|
||||
"heroBefore": "ทำให้ความผิดปกติ",
|
||||
"submitting": "กำลังเข้าสู่ระบบ",
|
||||
"account": "บัญชี",
|
||||
"accountPlaceholder": "รหัสพนักงาน",
|
||||
"passwordPlaceholder": "รหัสผ่าน",
|
||||
"cardTitle": "เข้าสู่ระบบ",
|
||||
"theme": "สลับธีม",
|
||||
"footer": "© 2026 和信精密 · HEXIN PRECISION",
|
||||
"username": "ชื่อผู้ใช้",
|
||||
"password": "รหัสผ่าน",
|
||||
"submit": "เข้าสู่ระบบ",
|
||||
"failed": "เข้าสู่ระบบไม่สำเร็จ โปรดตรวจสอบบัญชีและรหัสผ่าน",
|
||||
"unavailable": "บริการเข้าสู่ระบบไม่พร้อมชั่วคราว โปรดลองอีกครั้ง",
|
||||
"logout": "ออกจากระบบ",
|
||||
"forbiddenTitle": "ไม่มีสิทธิ์เข้าใช้",
|
||||
"forbiddenBody": "บัญชีนี้เข้าสู่ระบบแล้ว แต่ไม่มีบทบาทดู ดำเนินการ หรือผู้ดูแลของ Watchman",
|
||||
"fixture": "โหมดตัวตนภายในเครื่อง ไม่ใช่การเข้าสู่ระบบจริง"
|
||||
},
|
||||
"shell": {
|
||||
"welcome": "เข้าสู่ระบบแล้ว: {name}"
|
||||
},
|
||||
"health": {
|
||||
"loading": "กำลังตรวจสอบสถานะ",
|
||||
"success": "ตรวจสอบสถานะสำเร็จ",
|
||||
|
||||
@@ -1,5 +1,32 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"login": {
|
||||
"title": "登录 Watchman",
|
||||
"subtitle": "使用公司账号进入预警平台",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"hero": "让异常{em}被看见{/em}",
|
||||
"heroEm": "被看见",
|
||||
"heroBefore": "让异常",
|
||||
"submitting": "登录中",
|
||||
"account": "账号",
|
||||
"accountPlaceholder": "工号 / 域账号",
|
||||
"passwordPlaceholder": "请输入密码",
|
||||
"cardTitle": "登录账户",
|
||||
"theme": "切换昼夜",
|
||||
"footer": "© 2026 和信精密 · HEXIN PRECISION",
|
||||
"username": "用户名",
|
||||
"password": "密码",
|
||||
"submit": "登录",
|
||||
"failed": "登录失败,请检查账号和密码",
|
||||
"unavailable": "登录服务暂不可用,请稍后再试",
|
||||
"logout": "退出",
|
||||
"forbiddenTitle": "没有访问权限",
|
||||
"forbiddenBody": "当前账号已登录,但没有 Watchman 的查看、处理或管理角色。",
|
||||
"fixture": "本地身份模式,不能当作正式登录"
|
||||
},
|
||||
"shell": {
|
||||
"welcome": "已登录:{name}"
|
||||
},
|
||||
"health": {
|
||||
"loading": "健康检查加载中",
|
||||
"success": "健康检查成功",
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
{
|
||||
"appName": "Watchman",
|
||||
"login": {
|
||||
"title": "登入 Watchman",
|
||||
"subtitle": "使用公司帳號進入預警平台",
|
||||
"eyebrow": "WATCHMAN · EARLY WARNING",
|
||||
"heroEm": "被看見",
|
||||
"heroBefore": "讓異常",
|
||||
"submitting": "登入中",
|
||||
"account": "帳號",
|
||||
"accountPlaceholder": "工號 / 網域帳號",
|
||||
"passwordPlaceholder": "請輸入密碼",
|
||||
"cardTitle": "登入帳戶",
|
||||
"theme": "切換晝夜",
|
||||
"footer": "© 2026 和信精密 · HEXIN PRECISION",
|
||||
"username": "使用者名稱",
|
||||
"password": "密碼",
|
||||
"submit": "登入",
|
||||
"failed": "登入失敗,請檢查帳號和密碼",
|
||||
"unavailable": "登入服務暫不可用,請稍後再試",
|
||||
"logout": "登出",
|
||||
"forbiddenTitle": "沒有存取權限",
|
||||
"forbiddenBody": "目前帳號已登入,但沒有 Watchman 的查看、處理或管理角色。",
|
||||
"fixture": "本地身分模式,不能當作正式登入"
|
||||
},
|
||||
"shell": {
|
||||
"welcome": "已登入:{name}"
|
||||
},
|
||||
"health": {
|
||||
"loading": "健康檢查載入中",
|
||||
"success": "健康檢查成功",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { flushPromises, mount } from "@vue/test-utils";
|
||||
import { createPinia } from "pinia";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { BusinessError } from "@watchman/api";
|
||||
@@ -18,6 +19,21 @@ import { requestJson } from "@watchman/api";
|
||||
|
||||
const mockedRequestJson = vi.mocked(requestJson);
|
||||
|
||||
const adminSession = {
|
||||
subject: "admin-1",
|
||||
display_name: "Admin",
|
||||
roles: ["watchman-admin"],
|
||||
};
|
||||
|
||||
function mockSessionThenHealth(health: () => Promise<unknown> | unknown) {
|
||||
mockedRequestJson.mockImplementation((input: string) => {
|
||||
if (String(input).includes("/auth/me")) {
|
||||
return Promise.resolve(adminSession);
|
||||
}
|
||||
return Promise.resolve(health());
|
||||
});
|
||||
}
|
||||
|
||||
function mountApp(locale = "zh-CN") {
|
||||
const i18n = createI18n({
|
||||
legacy: false,
|
||||
@@ -31,7 +47,7 @@ function mountApp(locale = "zh-CN") {
|
||||
});
|
||||
return mount(App, {
|
||||
global: {
|
||||
plugins: [i18n],
|
||||
plugins: [i18n, createPinia()],
|
||||
stubs: {
|
||||
ElConfigProvider: { template: "<div><slot /></div>" },
|
||||
ElCard: {
|
||||
@@ -54,29 +70,33 @@ function mountApp(locale = "zh-CN") {
|
||||
|
||||
describe("App health three states", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
mockedRequestJson.mockReset();
|
||||
});
|
||||
|
||||
it("shows loading before the request settles", async () => {
|
||||
let resolveRequest: (value: unknown) => void = () => undefined;
|
||||
mockedRequestJson.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}),
|
||||
);
|
||||
it("shows loading before the health request settles", async () => {
|
||||
let resolveHealth: (value: unknown) => void = () => undefined;
|
||||
mockedRequestJson.mockImplementation((input: string) => {
|
||||
if (String(input).includes("/auth/me")) {
|
||||
return Promise.resolve(adminSession);
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
resolveHealth = resolve;
|
||||
});
|
||||
});
|
||||
const wrapper = mountApp();
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-testid=health-loading]").text()).toContain("健康检查加载中");
|
||||
resolveRequest({ status: "ok", app: "watchman", version: "0.1.0" });
|
||||
resolveHealth({ status: "ok", app: "watchman", version: "0.1.0" });
|
||||
await flushPromises();
|
||||
});
|
||||
|
||||
it("shows success after a healthy response", async () => {
|
||||
mockedRequestJson.mockResolvedValue({
|
||||
mockSessionThenHealth(() => ({
|
||||
status: "ok",
|
||||
app: "watchman",
|
||||
version: "0.1.0",
|
||||
});
|
||||
}));
|
||||
const wrapper = mountApp();
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("健康检查成功");
|
||||
@@ -84,14 +104,19 @@ describe("App health three states", () => {
|
||||
});
|
||||
|
||||
it("shows failure after a BusinessError", async () => {
|
||||
mockedRequestJson.mockRejectedValue(
|
||||
new BusinessError({
|
||||
code: 50000,
|
||||
message: "Internal server error",
|
||||
status: 500,
|
||||
requestId: "req-fail",
|
||||
}),
|
||||
);
|
||||
mockedRequestJson.mockImplementation((input: string) => {
|
||||
if (String(input).includes("/auth/me")) {
|
||||
return Promise.resolve(adminSession);
|
||||
}
|
||||
return Promise.reject(
|
||||
new BusinessError({
|
||||
code: 50000,
|
||||
message: "Internal server error",
|
||||
status: 500,
|
||||
requestId: "req-fail",
|
||||
}),
|
||||
);
|
||||
});
|
||||
const wrapper = mountApp();
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("健康检查失败");
|
||||
@@ -99,25 +124,36 @@ describe("App health three states", () => {
|
||||
});
|
||||
|
||||
it("falls back to zh-CN when locale messages are missing", async () => {
|
||||
mockedRequestJson.mockResolvedValue({
|
||||
mockSessionThenHealth(() => ({
|
||||
status: "ok",
|
||||
app: "watchman",
|
||||
version: "0.1.0",
|
||||
});
|
||||
}));
|
||||
const wrapper = mountApp("th");
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("健康检查成功");
|
||||
});
|
||||
|
||||
it("shows english health copy when locale is en", async () => {
|
||||
mockedRequestJson.mockResolvedValue({
|
||||
mockSessionThenHealth(() => ({
|
||||
status: "ok",
|
||||
app: "watchman",
|
||||
version: "0.1.0",
|
||||
});
|
||||
}));
|
||||
const wrapper = mountApp("en");
|
||||
await flushPromises();
|
||||
expect(wrapper.get("[data-testid=health-tag]").text()).toContain("Health check succeeded");
|
||||
expect(wrapper.get("[data-testid=health-success]").text()).toContain("Service available");
|
||||
});
|
||||
|
||||
it("shows the no-access screen when the session has no Watchman role", async () => {
|
||||
mockedRequestJson.mockResolvedValue({
|
||||
subject: "user-1",
|
||||
display_name: "No Role",
|
||||
roles: [],
|
||||
});
|
||||
const wrapper = mountApp();
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).toContain("没有访问权限");
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,22 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ElAlert, ElCard, ElConfigProvider, ElTag } from "element-plus";
|
||||
import { ElAlert, ElButton, ElCard, ElConfigProvider, ElTag } from "element-plus";
|
||||
import zhCn from "element-plus/es/locale/lang/zh-cn";
|
||||
import zhTw from "element-plus/es/locale/lang/zh-tw";
|
||||
import en from "element-plus/es/locale/lang/en";
|
||||
import th from "element-plus/es/locale/lang/th";
|
||||
import { requestJson } from "@watchman/api";
|
||||
import { BusinessError } from "@watchman/api";
|
||||
import { api } from "./api";
|
||||
import {
|
||||
healthFailureView,
|
||||
healthSuccessView,
|
||||
type HealthPayload,
|
||||
type HealthState,
|
||||
} from "./health";
|
||||
import LoginPanel from "./LoginPanel.vue";
|
||||
import { allowsEnter, loadSession, type SessionUser } from "./session";
|
||||
import { useAuthStore } from "./stores/auth";
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const elementLocale = computed(() => {
|
||||
@@ -28,12 +32,34 @@ const elementLocale = computed(() => {
|
||||
}
|
||||
});
|
||||
|
||||
type Screen = "booting" | "login" | "forbidden" | "shell";
|
||||
|
||||
const auth = useAuthStore();
|
||||
const screen = ref<Screen>("booting");
|
||||
const identity = ref<SessionUser | null>(null);
|
||||
const state = ref<HealthState>("loading");
|
||||
const detail = ref("");
|
||||
|
||||
onMounted(async () => {
|
||||
function applyIdentity(user: SessionUser): void {
|
||||
const stored = loadSession();
|
||||
const next = {
|
||||
...user,
|
||||
access_token: user.access_token ?? stored?.access_token,
|
||||
expires_in: user.expires_in ?? stored?.expires_in,
|
||||
token_expires_at: user.token_expires_at ?? stored?.token_expires_at,
|
||||
};
|
||||
auth.login(next);
|
||||
identity.value = auth.user;
|
||||
screen.value = allowsEnter(next.roles) ? "shell" : "forbidden";
|
||||
if (screen.value === "shell") {
|
||||
void loadHealth();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadHealth(): Promise<void> {
|
||||
state.value = "loading";
|
||||
try {
|
||||
const data = await requestJson<HealthPayload>("/health");
|
||||
const data = await api<HealthPayload>("/health");
|
||||
const view = healthSuccessView(data);
|
||||
state.value = view.state;
|
||||
detail.value = view.detail;
|
||||
@@ -42,20 +68,65 @@ onMounted(async () => {
|
||||
state.value = view.state;
|
||||
detail.value = view.detail;
|
||||
}
|
||||
}
|
||||
|
||||
async function signOut(): Promise<void> {
|
||||
try {
|
||||
await api("/auth/logout", { method: "POST" });
|
||||
} catch {
|
||||
// The local screen still returns to the login form.
|
||||
}
|
||||
auth.logout();
|
||||
identity.value = null;
|
||||
screen.value = "login";
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
applyIdentity(await api<SessionUser>("/auth/me"));
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && error.status !== 401) {
|
||||
detail.value = String(error.code);
|
||||
}
|
||||
screen.value = "login";
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ElConfigProvider :locale="elementLocale">
|
||||
<main class="min-h-screen p-8 bg-[var(--bg-surface-soft)] text-[length:var(--font-size-base)] text-[var(--text-primary)]">
|
||||
<p v-if="screen === 'booting'" data-testid="session-loading">{{ t("health.loading") }}</p>
|
||||
<LoginPanel v-else-if="screen === 'login'" @authenticated="applyIdentity" />
|
||||
<main
|
||||
v-else-if="screen === 'forbidden'"
|
||||
class="flex min-h-screen items-center justify-center bg-[var(--bg-surface-soft)] p-6"
|
||||
>
|
||||
<section class="w-full max-w-2xl rounded-3xl bg-white p-8 shadow-xl">
|
||||
<ElAlert
|
||||
type="warning"
|
||||
data-testid="forbidden"
|
||||
:title="t('login.forbiddenTitle')"
|
||||
:description="t('login.forbiddenBody')"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ElButton class="mt-6" data-testid="logout" @click="signOut">{{ t("login.logout") }}</ElButton>
|
||||
</section>
|
||||
</main>
|
||||
<main
|
||||
v-else
|
||||
class="min-h-screen bg-[var(--bg-surface-soft)] p-8 text-[length:var(--font-size-base)] text-[var(--text-primary)]"
|
||||
>
|
||||
<div class="mb-4 flex items-center justify-between gap-4">
|
||||
<p data-testid="shell-welcome">{{ t("shell.welcome", { name: identity?.display_name }) }}</p>
|
||||
<ElButton data-testid="logout" @click="signOut">{{ t("login.logout") }}</ElButton>
|
||||
</div>
|
||||
<ElCard>
|
||||
<template #header>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<span>{{ t("appName") }}</span>
|
||||
<span data-testid="health-tag">
|
||||
<ElTag
|
||||
:type="state === 'loading' ? 'info' : state === 'success' ? 'success' : 'danger'"
|
||||
>
|
||||
<ElTag :type="state === 'loading' ? 'info' : state === 'success' ? 'success' : 'danger'">
|
||||
{{
|
||||
state === "loading"
|
||||
? t("health.loading")
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { ElAlert } from "element-plus";
|
||||
import { BusinessError } from "@watchman/api";
|
||||
import { api } from "./api";
|
||||
import type { SessionUser } from "./session";
|
||||
import logoUrl from "./assets/logo.jpg";
|
||||
|
||||
const emit = defineEmits<{
|
||||
authenticated: [user: SessionUser];
|
||||
}>();
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const locales = ["zh-CN", "zh-TW", "en", "th"] as const;
|
||||
const localeLabel: Record<(typeof locales)[number], string> = {
|
||||
"zh-CN": "中文",
|
||||
"zh-TW": "繁體",
|
||||
en: "EN",
|
||||
th: "ไทย",
|
||||
};
|
||||
const theme = ref<"light" | "dark">(
|
||||
localStorage.getItem("watchman.theme") === "dark" ? "dark" : "light",
|
||||
);
|
||||
const username = ref("");
|
||||
const password = ref("");
|
||||
const showPassword = ref(false);
|
||||
const submitting = ref(false);
|
||||
const errorKey = ref("");
|
||||
const fixtureMode = import.meta.env.VITE_AUTH_MODE === "fixture";
|
||||
|
||||
async function signIn(): Promise<void> {
|
||||
errorKey.value = "";
|
||||
submitting.value = true;
|
||||
try {
|
||||
const user = await api<SessionUser>("/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: username.value, password: password.value }),
|
||||
});
|
||||
password.value = "";
|
||||
emit("authenticated", user);
|
||||
} catch (error) {
|
||||
const unavailable = !(error instanceof BusinessError) || error.status === 503 || error.status >= 500;
|
||||
errorKey.value = unavailable ? "login.unavailable" : "login.failed";
|
||||
} finally {
|
||||
submitting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTheme(): void {
|
||||
theme.value = theme.value === "light" ? "dark" : "light";
|
||||
localStorage.setItem("watchman.theme", theme.value);
|
||||
}
|
||||
|
||||
function cycleLocale(): void {
|
||||
const index = locales.indexOf(locale.value as (typeof locales)[number]);
|
||||
const next = locales[(index + 1) % locales.length];
|
||||
locale.value = next;
|
||||
localStorage.setItem("watchman.lang", next);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="pulse" :data-theme="theme">
|
||||
<div class="stage" aria-hidden="true">
|
||||
<div class="sky-glow sg1"></div>
|
||||
<div class="sky-glow sg2"></div>
|
||||
<svg class="arcs" viewBox="0 0 1440 320" preserveAspectRatio="xMidYMax slice">
|
||||
<path class="arc dim" d="M70 218 Q 170 130 300 178" />
|
||||
<path class="arc" d="M300 178 Q 400 96 520 148" />
|
||||
<path class="arc dim" d="M520 148 Q 610 60 760 92" />
|
||||
<path class="arc" d="M760 92 Q 880 46 990 128" />
|
||||
<path class="arc dim" d="M990 128 Q 1120 60 1250 158" />
|
||||
<path class="arc" d="M1250 158 Q 1330 110 1400 168" />
|
||||
<circle class="nd" cx="300" cy="178" r="3.2" />
|
||||
<circle class="nd" cx="760" cy="92" r="3.2" />
|
||||
<circle class="nd" cx="1250" cy="158" r="3.2" />
|
||||
</svg>
|
||||
<svg class="skyline" viewBox="0 0 1440 260" preserveAspectRatio="xMidYMax slice">
|
||||
<defs>
|
||||
<linearGradient id="watchmanSil" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="var(--skyline-a)" />
|
||||
<stop offset="1" stop-color="var(--skyline-b)" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path
|
||||
class="sil"
|
||||
d="M0 260 V196 H70 V120 h42 V196 H250 V158 h82 V196 H360 V128 h84 V196 H580 V88 h72 V196 H770 V110 h210 V196 H1190 V104 h76 V196 H1440 V260 Z"
|
||||
/>
|
||||
</svg>
|
||||
<div class="groundline"></div>
|
||||
</div>
|
||||
|
||||
<header class="topbar">
|
||||
<div class="logo-mini">
|
||||
<img class="logo-img" :src="logoUrl" alt="" />
|
||||
<span>{{ t("appName") }}</span>
|
||||
</div>
|
||||
<div class="tools">
|
||||
<button class="tool-btn" type="button" :aria-label="t('login.theme')" @click="toggleTheme">
|
||||
{{ theme === "light" ? "☾" : "☀" }}
|
||||
</button>
|
||||
<button class="tool-btn" type="button" data-testid="login-lang" @click="cycleLocale">
|
||||
{{ localeLabel[locale as (typeof locales)[number]] ?? "中文" }}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main class="frame">
|
||||
<div class="hero">
|
||||
<span class="cap">{{ t("login.eyebrow") }}</span>
|
||||
<h1>
|
||||
{{ t("login.heroBefore") }}<em>{{ t("login.heroEm") }}</em>
|
||||
</h1>
|
||||
<p>{{ t("login.subtitle") }}</p>
|
||||
</div>
|
||||
|
||||
<form class="card" @submit.prevent="signIn">
|
||||
<div class="card-head">
|
||||
<img class="lg" :src="logoUrl" alt="" />
|
||||
<div>
|
||||
<div class="tt">{{ t("login.cardTitle") }}</div>
|
||||
<div class="ss">{{ t("login.subtitle") }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<ElAlert
|
||||
v-if="fixtureMode"
|
||||
class="mb-3"
|
||||
type="warning"
|
||||
data-testid="local-identity"
|
||||
:title="t('login.fixture')"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<ElAlert
|
||||
v-if="errorKey"
|
||||
class="mb-3"
|
||||
type="error"
|
||||
data-testid="login-error"
|
||||
:title="t(errorKey)"
|
||||
show-icon
|
||||
:closable="false"
|
||||
/>
|
||||
<div class="field">
|
||||
<label for="watchman-user">{{ t("login.account") }}</label>
|
||||
<div class="control" data-testid="login-username">
|
||||
<input
|
||||
id="watchman-user"
|
||||
v-model="username"
|
||||
name="username"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
:placeholder="t('login.accountPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="watchman-pass">{{ t("login.password") }}</label>
|
||||
<div class="control" data-testid="login-password">
|
||||
<input
|
||||
id="watchman-pass"
|
||||
v-model="password"
|
||||
name="current-password"
|
||||
:type="showPassword ? 'text' : 'password'"
|
||||
autocomplete="current-password"
|
||||
:placeholder="t('login.passwordPlaceholder')"
|
||||
@keyup.enter="signIn"
|
||||
/>
|
||||
<button type="button" class="eye" :aria-label="showPassword ? 'hide' : 'show'" @click="showPassword = !showPassword">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7">
|
||||
<path d="M2.5 12S6 5.8 12 5.8 21.5 12 21.5 12 18 18.2 12 18.2 2.5 12 2.5 12Z" />
|
||||
<circle cx="12" cy="12" r="2.8" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn-primary" type="submit" data-testid="login-submit" :disabled="submitting">
|
||||
<span>{{ submitting ? t("login.submitting") : t("login.submit") }}</span>
|
||||
</button>
|
||||
</form>
|
||||
</main>
|
||||
<footer class="foot">{{ t("login.footer") }}</footer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pulse {
|
||||
--brand-600: #2563eb;
|
||||
--brand-400: #60a5fa;
|
||||
--bg: #eef3f9;
|
||||
--sky-hi: rgba(37, 99, 235, 0.1);
|
||||
--sky-lo: rgba(34, 211, 238, 0.06);
|
||||
--skyline-a: #243244;
|
||||
--skyline-b: #182231;
|
||||
--arc: #2563eb;
|
||||
--arc-dim: rgba(37, 99, 235, 0.3);
|
||||
--node: #0891b2;
|
||||
--text-hi: #0f172a;
|
||||
--text-mid: #475569;
|
||||
--text-low: #94a3b8;
|
||||
--card-bg: rgba(255, 255, 255, 0.86);
|
||||
--card-border: rgba(15, 23, 42, 0.08);
|
||||
--field-bg: #ffffff;
|
||||
--field-border: #cbd5e1;
|
||||
--tool-bg: rgba(255, 255, 255, 0.8);
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
overflow: hidden;
|
||||
background: var(--bg);
|
||||
color: var(--text-mid);
|
||||
font-size: 14px;
|
||||
}
|
||||
.pulse[data-theme="dark"] {
|
||||
--bg: #0a1120;
|
||||
--sky-hi: rgba(37, 99, 235, 0.16);
|
||||
--sky-lo: rgba(34, 211, 238, 0.07);
|
||||
--skyline-a: #0e1729;
|
||||
--skyline-b: #060b16;
|
||||
--arc: #60a5fa;
|
||||
--arc-dim: rgba(96, 165, 250, 0.35);
|
||||
--node: #22d3ee;
|
||||
--text-hi: #f8fafc;
|
||||
--text-mid: #a3b1c6;
|
||||
--text-low: #8b99af;
|
||||
--card-bg: rgba(13, 20, 38, 0.66);
|
||||
--card-border: rgba(255, 255, 255, 0.12);
|
||||
--field-bg: rgba(255, 255, 255, 0.05);
|
||||
--field-border: rgba(255, 255, 255, 0.14);
|
||||
--tool-bg: rgba(13, 20, 38, 0.6);
|
||||
}
|
||||
.stage { position: absolute; inset: 0; }
|
||||
.sky-glow { position: absolute; width: 900px; height: 900px; border-radius: 50%; filter: blur(90px); }
|
||||
.sg1 { left: -240px; top: -380px; background: radial-gradient(circle, var(--sky-hi), transparent 65%); }
|
||||
.sg2 { right: -260px; top: -320px; background: radial-gradient(circle, var(--sky-lo), transparent 65%); }
|
||||
.arcs { position: absolute; left: 0; right: 0; bottom: 15vh; height: 40vh; width: 100%; }
|
||||
.arc { stroke: var(--arc); stroke-width: 1.4; fill: none; stroke-dasharray: 4 8; animation: flow 5s linear infinite; }
|
||||
.arc.dim { stroke: var(--arc-dim); animation-duration: 7.5s; }
|
||||
.nd { fill: var(--node); }
|
||||
@keyframes flow { to { stroke-dashoffset: -96; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.arc { animation: none; }
|
||||
}
|
||||
.skyline { position: absolute; left: 0; right: 0; bottom: 0; width: 100%; height: 28vh; min-height: 170px; }
|
||||
.sil { fill: url(#watchmanSil); stroke: rgba(148, 163, 184, 0.14); }
|
||||
.groundline {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; height: 2px;
|
||||
background: linear-gradient(90deg, transparent, rgba(96, 165, 250, 0.35) 25%, rgba(96, 165, 250, 0.35) 75%, transparent);
|
||||
}
|
||||
.topbar { position: absolute; top: 0; left: 0; right: 0; z-index: 3; display: flex; justify-content: space-between; align-items: center; padding: 22px 32px; }
|
||||
.logo-mini { display: flex; align-items: center; gap: 10px; color: var(--text-hi); font-weight: 650; }
|
||||
.logo-img { width: 36px; height: 36px; object-fit: contain; background: white; border-radius: 8px; }
|
||||
.tools { display: flex; gap: 8px; }
|
||||
.tool-btn {
|
||||
display: flex; align-items: center; justify-content: center; height: 36px; min-width: 36px; padding: 0 11px;
|
||||
border-radius: 999px; border: 1px solid var(--card-border); background: var(--tool-bg);
|
||||
color: var(--text-mid); font-size: 12.5px;
|
||||
}
|
||||
.lg { width: 36px; height: 36px; object-fit: contain; background: white; border-radius: 10px; }
|
||||
.frame {
|
||||
position: relative; z-index: 2; height: 100%;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
padding: 64px 24px 18vh;
|
||||
}
|
||||
.hero { text-align: center; margin-bottom: 28px; }
|
||||
.cap { font-size: 12px; font-weight: 600; letter-spacing: 0.28em; color: var(--brand-400); }
|
||||
.hero h1 { font-size: clamp(30px, 3.8vw, 46px); font-weight: 700; letter-spacing: -0.02em; color: var(--text-hi); margin: 14px 0 10px; }
|
||||
.hero em {
|
||||
font-style: normal;
|
||||
background: linear-gradient(100deg, #3b82f6, #22d3ee);
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
.card {
|
||||
width: 396px; max-width: 100%; padding: 30px 32px 24px; border-radius: 18px;
|
||||
background: var(--card-bg); border: 1px solid var(--card-border);
|
||||
backdrop-filter: blur(20px) saturate(150%);
|
||||
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.08) inset, 0 28px 72px -20px rgba(0, 0, 0, 0.6);
|
||||
}
|
||||
.card-head { display: flex; align-items: center; gap: 12px; margin-bottom: 20px; }
|
||||
.tt { font-size: 17px; font-weight: 650; color: var(--text-hi); }
|
||||
.ss { font-size: 12.5px; color: var(--text-low); }
|
||||
.field { margin-bottom: 14px; }
|
||||
.field label { display: block; font-size: 13px; font-weight: 500; margin-bottom: 6px; }
|
||||
.control input {
|
||||
width: 100%; height: 44px; border-radius: 10px; border: 1px solid var(--field-border);
|
||||
background: var(--field-bg); color: var(--text-hi); font-size: 14.5px; padding: 0 44px 0 14px;
|
||||
}
|
||||
.control input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.16); }
|
||||
.control { position: relative; }
|
||||
.eye {
|
||||
position: absolute; right: 8px; top: 6px; width: 32px; height: 32px; border: 0; border-radius: 8px;
|
||||
background: transparent; color: var(--text-low); display: grid; place-items: center;
|
||||
}
|
||||
.eye svg { width: 17px; height: 17px; }
|
||||
.btn-primary {
|
||||
width: 100%; height: 44px; margin-top: 8px; border: 0; border-radius: 10px;
|
||||
background: var(--brand-600); color: white; font-size: 15px; font-weight: 600;
|
||||
}
|
||||
.btn-primary:disabled { opacity: 0.7; }
|
||||
.foot {
|
||||
position: absolute; left: 0; right: 0; bottom: 14px; z-index: 3;
|
||||
padding: 0 32px; font-size: 11.5px; color: var(--text-low);
|
||||
}
|
||||
@media (max-width: 760px) {
|
||||
.frame { justify-content: flex-start; padding-top: 88px; }
|
||||
.skyline { min-height: 120px; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Console API calls attach the stored Watchman session token.
|
||||
* The token is the one returned by login, not a Casdoor credential.
|
||||
*/
|
||||
|
||||
import { requestJson } from "@watchman/api";
|
||||
import { authHeaders } from "./session";
|
||||
|
||||
export async function api<T>(input: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
for (const [key, value] of Object.entries(authHeaders())) {
|
||||
if (!headers.has(key)) {
|
||||
headers.set(key, value);
|
||||
}
|
||||
}
|
||||
return requestJson<T>(input, { ...init, headers });
|
||||
}
|
||||
|
After Width: | Height: | Size: 54 KiB |
@@ -0,0 +1,24 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { authHeaders, clearSession, loadSession, saveSession } from "./session";
|
||||
|
||||
describe("session token storage", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
});
|
||||
|
||||
it("keeps the Watchman access token for later requests", () => {
|
||||
saveSession({
|
||||
subject: "user-1",
|
||||
display_name: "Ada",
|
||||
roles: ["watchman-admin"],
|
||||
access_token: "session-token",
|
||||
expires_in: 60,
|
||||
});
|
||||
|
||||
expect(loadSession()?.access_token).toBe("session-token");
|
||||
expect(authHeaders()).toEqual({ Authorization: "Bearer session-token" });
|
||||
clearSession();
|
||||
expect(loadSession()).toBeNull();
|
||||
expect(authHeaders()).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
/** Browser copy of the Watchman session. This is not a Casdoor token. */
|
||||
|
||||
export type SessionUser = {
|
||||
subject: string;
|
||||
display_name: string;
|
||||
login_name?: string;
|
||||
roles: string[];
|
||||
access_token?: string;
|
||||
token_type?: string;
|
||||
expires_in?: number;
|
||||
token_expires_at?: number;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "watchman_user";
|
||||
const ENTER_ROLES = new Set(["watchman-admin", "watchman-operator", "watchman-viewer"]);
|
||||
|
||||
export function allowsEnter(roles: string[]): boolean {
|
||||
return roles.some((role) => ENTER_ROLES.has(role));
|
||||
}
|
||||
|
||||
export function saveSession(user: SessionUser): void {
|
||||
const next = { ...user };
|
||||
if (next.expires_in && !next.token_expires_at) {
|
||||
next.token_expires_at = Date.now() + next.expires_in * 1000;
|
||||
}
|
||||
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
}
|
||||
|
||||
export function loadSession(): SessionUser | null {
|
||||
const raw = sessionStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const user = JSON.parse(raw) as SessionUser;
|
||||
if (user.token_expires_at && user.token_expires_at <= Date.now()) {
|
||||
sessionStorage.removeItem(STORAGE_KEY);
|
||||
return null;
|
||||
}
|
||||
return user;
|
||||
} catch {
|
||||
sessionStorage.removeItem(STORAGE_KEY);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function clearSession(): void {
|
||||
sessionStorage.removeItem(STORAGE_KEY);
|
||||
}
|
||||
|
||||
export function authHeaders(): Record<string, string> {
|
||||
const token = loadSession()?.access_token;
|
||||
if (!token) {
|
||||
return {};
|
||||
}
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Login state for the console. Storage stays in session.ts so requests can read it
|
||||
* without waiting for Pinia.
|
||||
*/
|
||||
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, ref } from "vue";
|
||||
import { clearSession, loadSession, saveSession, type SessionUser } from "../session";
|
||||
|
||||
export const useAuthStore = defineStore("auth", () => {
|
||||
const user = ref<SessionUser | null>(loadSession());
|
||||
const token = computed(() => user.value?.access_token ?? "");
|
||||
|
||||
function login(next: SessionUser): void {
|
||||
saveSession(next);
|
||||
user.value = loadSession();
|
||||
}
|
||||
|
||||
function logout(): void {
|
||||
clearSession();
|
||||
user.value = null;
|
||||
}
|
||||
|
||||
return { user, token, login, logout };
|
||||
});
|
||||
@@ -10,6 +10,7 @@ export default defineConfig({
|
||||
proxy: {
|
||||
"/health": "http://127.0.0.1:8000",
|
||||
"/platform": "http://127.0.0.1:8000",
|
||||
"/auth": "http://127.0.0.1:8000",
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -58,7 +58,11 @@ export async function requestJson<T>(
|
||||
if (!headers.has("Accept")) {
|
||||
headers.set("Accept", "application/json");
|
||||
}
|
||||
const response = await fetch(input, { ...init, headers });
|
||||
const response = await fetch(input, {
|
||||
...init,
|
||||
headers,
|
||||
credentials: init.credentials ?? "include",
|
||||
});
|
||||
let body: ApiSuccess<T> | ApiFailure;
|
||||
try {
|
||||
body = (await response.json()) as ApiSuccess<T> | ApiFailure;
|
||||
|
||||