Files
ssw-platform/crates/tests/tests/auth_it.rs
T
admin acf076df5a refactor: 内核瘦身 —— 示例搬成业务包 + 装配/测试各归其位
- 内核只有 lib:启动装配 → crates/sspf-admin(bin sspf-admin);37 个集成测试 → crates/tests(package sspf-tests)。
- demo/shop/books 的 spec/菜单/DDL/面 B 路由搬进 packs/{demo,shop,books};内核 modules/*.rs 只剩「面 A 适配器 + pub use」⇒ 内核零业务知识,示例可整目录搬走。面 A 与前端零改动。
- 示例表 DDL 按平台规则补 f_tenant_id + 复合主键(spec 不加 ⇒ JSON 键与响应逐字不变)。
- 修 is_builtin_table 只认 schema.sql 的漏洞:包表(含 asset_data_resource)此前可被建模页删除/改;现为「平台 DDL ∪ 包表」。
- sspf-compat-online_dev → onlinedev(包名/模块/文件/路由别名同步);6 个 5 行转发壳合并为 forward.rs。
- 新增 AR16 闸门 + lib.rs「30 秒地图」+ src/backend/README.md;pack-sync 补两处判据(module_key=None 的 urlAddress、apiFile 查存在性)。
- 回归:704 tests / 6 道静态闸门全绿;health 181 表;四个包面 A/面 B 运行时全部 200。
2026-11-04 14:46:12 +08:00

558 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! auth 集成测试 —— 登录 / 当前用户 / 两个守卫。
//!
//! 🔴 pglite-rs 0.2.7 是**进程级全局标志**:一个进程一辈子只能开一个实例
//! (第二次 `open()` ⇒ `Error::AlreadyOpen`)⇒ 全文件**共用一个临时库**
//! (`OnceCell` 起一次),不每个测试函数各开一个。
//!
//! 🔴 **测试之间必须串行**:Rust 的 test harness 把同一个 `tests/*.rs` 里的
//! `#[tokio::test]` **并发**跑(不同线程)⇒ 共用一个库时它们会互相踩数据。
//! ⇒ 用一把进程级 `tokio::sync::Mutex` 把每个测试**整体**串起来。
//! 🔴 **不依赖测试执行顺序**:每个测试自己造前置条件(自己的 token / 自己的用户)。
use std::path::PathBuf;
use std::sync::Arc;
use axum::body::Bytes;
use axum::http::{HeaderMap, HeaderValue};
use axum::Json;
use sspf_core::auth::{
current_user, login, login_from_bytes, require_login, require_module, LoginForm,
};
use sspf_core::cipher::{encrypt_password, md5_hex};
use sspf_core::config::Config;
use sspf_core::db::Db;
use sspf_core::envelope::ActionResult;
use sspf_core::ids::new_uuid;
use ssw_platform::bootstrap::ensure_base;
use sspf_core::seed::first_seed;
use sspf_core::session::{SessionStore, TokenUser, TicketStore};
use sspf_core::state::AppState;
use tokio::sync::{Mutex, OnceCell};
/// 全文件共享的临时库。
static DB: OnceCell<Db> = OnceCell::const_new();
/// 把同文件的测试**整体**串行化(共用一个库 ⇒ 必须串行)。
static LOCK: Mutex<()> = Mutex::const_new(());
/// 管理员账号(契约 §8.6 的 `admin`)。
const ADMIN_ACCOUNT: &str = "admin";
/// 管理员口令(契约 §8.6:种子口令 `123456`)。
const ADMIN_PLAIN: &str = "123456";
async fn db() -> &'static Db {
DB.get_or_init(|| async {
let db = Db::open_temp().await.expect("打开 pglite 临时库失败");
ssw_platform::bootstrap::ensure_schema_all(&db)
.await
.expect("ensure_schema_all 失败");
ensure_base(&db).await.expect("ensure_base 失败");
first_seed(&db, "123456").await.expect("first_seed 失败");
db
})
.await
}
/// 造一个应用状态(**每个测试自己一份** ⇒ token 表互不干扰)。
fn new_state(db: &Db) -> AppState {
AppState {
config: Arc::new(Config::from_env(PathBuf::from("/tmp/ssw-platform-auth-it"))),
db: Arc::new(db.clone()),
sessions: Arc::new(SessionStore::new()),
tickets: Arc::new(TicketStore::default()),
}
}
/// 带 `bearer <token>` 的请求头。
fn auth_headers(token: &str) -> HeaderMap {
let mut headers = HeaderMap::new();
let value =
HeaderValue::from_str(&format!("bearer {}", token)).expect("token 必须是合法 header 值");
headers.insert("authorization", value);
headers
}
/// 守卫的**失败**分支(`ActionResult` / `TokenUser` 都不实现 `Debug` ⇒ 不用 `expect_err`)。
fn expect_guard_err(res: Result<TokenUser, Json<ActionResult>>, ctx: &str) -> ActionResult {
match res {
Ok(_) => panic!("{ctx}:必须失败,却放行了"),
Err(e) => e.0,
}
}
/// 守卫的**放行**分支。
fn expect_guard_ok(res: Result<TokenUser, Json<ActionResult>>, ctx: &str) -> TokenUser {
match res {
Ok(user) => user,
Err(e) => panic!(
"{ctx}:必须放行,实际 code={} msg={}",
e.0.code, e.0.msg
),
}
}
/// 造一个**非管理员**用户(口令 `123456`),返回它的 id。
async fn insert_plain_user(db: &Db, account: &str) -> String {
let id = new_uuid();
let password = md5_hex(ADMIN_PLAIN);
let is_admin = "0".to_string();
let delete_mark = "0".to_string();
let params: [&(dyn sspf_core::db::pglite::ToSql + Sync); 5] = [
&id,
&account.to_string(),
&password,
&is_admin,
&delete_mark,
];
db.exec_params(
"INSERT INTO base_user \
(f_id, f_account, f_password, f_is_administrator, f_delete_mark, f_tenant_id) \
VALUES ($1::text, $2::text, $3::text, $4::text::integer, $5::text::integer, '0')",
&params,
)
.await
.expect("插入测试用户失败");
id
}
/// 把 `base_user` 的**表 + 二级索引**从 `schema.sql` 里捞出来重建(测试专用)。
///
/// 🔴 **整词匹配**:只捞「`CREATE TABLE base_user (`」与「`CREATE INDEX … ON base_user(`」。
/// 绝不能用 `contains("base_user")` —— 那会**误伤 `base_user_relation`**(名字里也含 `base_user`)。
/// 🔴 **必须连二级索引一起恢复**:`DROP TABLE` 会连带删掉索引 `i_bu_fa`,
/// 只重建表 ⇒ 索引**静默**丢失。
async fn restore_base_user(db: &Db) {
let mut ddl: Vec<String> = Vec::new();
for stmt in sspf_core::db::split_sql_statements(sspf_core::db::SCHEMA_SQL) {
let head = stmt.trim_start();
let is_table = head.starts_with("CREATE TABLE base_user (");
let is_index = head.starts_with("CREATE INDEX") && head.contains(" ON base_user(");
if is_table || is_index {
ddl.push(stmt);
}
}
assert_eq!(
ddl.len(),
2,
"schema.sql 里必须恰好有 base_user 的建表 + 索引两条:{ddl:?}"
);
for stmt in ddl {
db.exec(&stmt).await.expect("恢复 base_user 失败");
}
}
// ---- 登录 ----
/// 空 body ⇒ `code=400`、`msg="缺少 account / password"`。
///
/// 🔴 空 body **能**解析成功(`serde_urlencoded::from_bytes::<LoginForm>(b"")` 返 `Ok`,
/// 三个字段全 `None`)⇒ 本条钉的是「**解析成功但 account/password 缺失**」这条分支。
/// 「**整个 body 解析失败**」那条分支由 `login_with_unparsable_body_fails` 单独钉住。
#[tokio::test]
async fn login_with_empty_body_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let res = login_from_bytes(&state, Bytes::new()).await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "缺少 account / password");
assert_eq!(res.0.data, serde_json::Value::Null);
}
/// 🔴 **整个 body 解析失败** ⇒ 同样 `400 "缺少 account / password"`(不是 axum 默认的 400 文本)。
///
/// 用**重复键**(`account=a&account=b`)触发 serde 的 `duplicate field` 错误。
/// 先单独断言 `from_bytes` **确实**返 `Err` ⇒ 将来 serde 行为变了这条测试会**响亮地挂掉**,
/// 而不是悄悄变成空转。
#[tokio::test]
async fn login_with_unparsable_body_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
// 前置条件:重复键 ⇒ serde 派生的 struct visitor 报 `duplicate field \`account\``。
assert!(
serde_urlencoded::from_bytes::<LoginForm>(b"account=a&account=b").is_err(),
"重复键必须让 serde_urlencoded 解析失败(否则本测试是空转)"
);
let res = login_from_bytes(&state, Bytes::from_static(b"account=a&account=b")).await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "缺少 account / password");
assert_eq!(res.0.data, serde_json::Value::Null);
}
/// 🔴 **校验顺序**:缺 `password` **且** `grant_type=foo` ⇒ 必须是「缺少 account / password」。
///
/// 顺序 1(缺 account/password)先于顺序 2(grant_type 不支持)
/// ⇒ 缺 password 时**永远**看不到 `不支持的 grant_type`。
/// (把 1、2 调换 ⇒ 本条测试会挂。)
#[tokio::test]
async fn login_checks_missing_credentials_before_unsupported_grant_type() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let res = login_from_bytes(
&state,
Bytes::from_static(b"account=admin&grant_type=foo"),
)
.await;
assert_eq!(res.0.code, 400);
assert_eq!(
res.0.msg, "缺少 account / password",
"校验顺序 1 必须先于顺序 2"
);
}
/// 解析成功但 `account` / `password` 缺一 ⇒ 同样 `400 "缺少 account / password"`。
#[tokio::test]
async fn login_without_credentials_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
// 只有 account,没有 password。
let res = login_from_bytes(&state, Bytes::from_static(b"account=admin")).await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "缺少 account / password");
// 已解析的表单走同一条分支。
let res = login(
&state,
LoginForm {
account: Some(ADMIN_ACCOUNT.to_string()),
password: None,
grant_type: None,
},
)
.await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "缺少 account / password");
}
/// `grant_type=foo` ⇒ `code=400`、`msg="不支持的 grant_type"`。
#[tokio::test]
async fn login_with_unsupported_grant_type_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let body = format!(
"account={}&password={}&grant_type=foo",
ADMIN_ACCOUNT,
encrypt_password(ADMIN_PLAIN)
);
let res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "不支持的 grant_type");
}
/// 口令错 ⇒ `code=400`、`msg="账号或密码错误"`。
#[tokio::test]
async fn login_with_wrong_password_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let body = format!(
"account={}&password={}&grant_type=password",
ADMIN_ACCOUNT,
encrypt_password("wrong-password")
);
let res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "账号或密码错误");
}
/// 🔴 密文非法(非法 hex)⇒ **同一条** `400 "账号或密码错误"`(不许另造文案)。
#[tokio::test]
async fn login_with_invalid_ciphertext_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let body = format!("account={}&password=not-hex&grant_type=password", ADMIN_ACCOUNT);
let res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "账号或密码错误");
}
/// 账号不存在 ⇒ `code=400`、`msg="账号或密码错误"`。
#[tokio::test]
async fn login_with_unknown_account_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let body = format!(
"account=auth_it_no_such_user&password={}&grant_type=password",
encrypt_password(ADMIN_PLAIN)
);
let res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "账号或密码错误");
}
/// 口令正确 ⇒ `code=200`,`data.token` 非空、`expiresIn==7200`、`tokenTypeName=="bearer"`。
#[tokio::test]
async fn login_with_correct_password_succeeds() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let body = format!(
"account={}&password={}&grant_type=password",
ADMIN_ACCOUNT,
encrypt_password(ADMIN_PLAIN)
);
let res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(res.0.code, 200);
assert_eq!(res.0.msg, "成功");
let data = res.0.data.as_object().expect("data 必须是对象");
let token = data["token"].as_str().expect("token 必须是字符串");
assert!(!token.is_empty(), "token 不得为空");
assert_eq!(data["expiresIn"], serde_json::json!(7200));
assert_eq!(data["tokenTypeName"], serde_json::json!("bearer"));
// 🔴 口令**不得外泄**:响应里不得出现密文或 md5。
let serialized = serde_json::to_string(&res.0.data).unwrap();
assert!(
!serialized.contains(&encrypt_password(ADMIN_PLAIN)),
"响应里不得回显密文"
);
assert!(
!serialized.contains(&md5_hex(ADMIN_PLAIN)),
"响应里不得回显口令摘要"
);
}
/// 🔴 `grant_type` **缺失是允许的**(只有「存在且 ≠ password」才失败)。
#[tokio::test]
async fn login_without_grant_type_is_allowed() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let body = format!(
"account={}&password={}",
ADMIN_ACCOUNT,
encrypt_password(ADMIN_PLAIN)
);
let res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(res.0.code, 200, "缺 grant_type 必须放行");
}
/// 🔴 **DB 报错** ⇒ `code=400`、`msg="系统异常,请联系管理员"`(契约 §R1.2 / §6.5)。
///
/// 🔴 **不是** `"账号或密码错误"` —— DB 挂了不该伪装成「你密码错了」:
/// 用户会反复重试、运维也看不到告警信号;两条消息必须能区分。
#[tokio::test]
async fn login_with_db_error_returns_system_error_message() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
// 造前置条件:把 base_user 删掉 ⇒ 查用户这条 SQL 必然失败。
db.exec("DROP TABLE base_user").await.expect("临时删表失败");
let body = format!(
"account={}&password={}&grant_type=password",
ADMIN_ACCOUNT,
encrypt_password(ADMIN_PLAIN)
);
let res = login_from_bytes(&state, Bytes::from(body)).await;
// 🔴 **先恢复表(含二级索引)+ 重跑种子,再断言** ——
// 恢复必须在本测试内做完,断言失败也不能污染同文件的其它测试。
restore_base_user(db).await;
ensure_base(db).await.expect("恢复后 ensure_base 失败");
first_seed(db, "123456").await.expect("恢复后 first_seed 失败");
assert_eq!(res.0.code, 400);
assert_eq!(res.0.msg, "系统异常,请联系管理员");
assert_ne!(
res.0.msg, "账号或密码错误",
"DB 报错不得伪装成口令错"
);
// 恢复后 admin 用户必须重新可登录(证明表 + 种子真的回来了)。
let body = format!(
"account={}&password={}&grant_type=password",
ADMIN_ACCOUNT,
encrypt_password(ADMIN_PLAIN)
);
let res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(res.0.code, 200, "恢复后 admin 必须能登录");
}
// ---- CurrentUser ----
/// CurrentUser 无 token ⇒ `code=600`、`msg="未登录"`。
#[tokio::test]
async fn current_user_without_token_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let res = current_user(&state, HeaderMap::new()).await;
assert_eq!(res.0.code, 600);
assert_eq!(res.0.msg, "未登录");
assert_eq!(res.0.data, serde_json::Value::Null);
}
/// CurrentUser 有 token ⇒ `code=200`,`userInfo` 形状正确、`menuList` 是 4 个根菜单的数组。
#[tokio::test]
async fn current_user_with_token_returns_user_info_and_menu() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
// 先登录拿 token。
let body = format!(
"account={}&password={}&grant_type=password",
ADMIN_ACCOUNT,
encrypt_password(ADMIN_PLAIN)
);
let login_res = login_from_bytes(&state, Bytes::from(body)).await;
assert_eq!(login_res.0.code, 200);
let token = login_res.0.data["token"]
.as_str()
.expect("token 必须是字符串")
.to_string();
let res = current_user(&state, auth_headers(&token)).await;
assert_eq!(res.0.code, 200);
let data = res.0.data.as_object().expect("data 必须是对象");
let user_info = data["userInfo"].as_object().expect("userInfo 必须是对象");
assert_eq!(user_info["userAccount"], serde_json::json!("admin"));
assert_eq!(user_info["userName"], serde_json::json!("admin"));
assert!(
user_info["isAdministrator"].is_boolean(),
"isAdministrator 必须是 JSON 布尔:{:?}",
user_info["isAdministrator"]
);
assert_eq!(user_info["isAdministrator"], serde_json::json!(true));
assert!(
user_info["userId"].as_str().is_some_and(|s| !s.is_empty()),
"userId 必须是非空字符串"
);
let menu = data["menuList"].as_array().expect("menuList 必须是数组");
// 🔴 根节点数 = 1 个系统管理目录 + N 个业务根菜单(业务模块数由业务层决定,
// 钉 `>= 4` 而不是写死 ⇒ 加业务模块不用改这条测试)。
assert!(
menu.len() >= 4,
"管理员应看到至少 4 个根菜单,实际 {}",
menu.len()
);
assert_eq!(
data["currentSystemId"],
serde_json::json!(sspf_core::registry::MAIN_SYSTEM_ID),
"无 App-Code 头 ⇒ 回落主系统"
);
}
// ---- 守卫 ----
/// `require_login`:无 token ⇒ `code=600`。
#[tokio::test]
async fn require_login_without_token_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let err = expect_guard_err(
require_login(&state, &HeaderMap::new()).await,
"无 token 的 require_login",
);
assert_eq!(err.code, 600);
assert_eq!(err.msg, "未登录");
}
/// `require_login`:有 token ⇒ `Ok(TokenUser)`(账号 = admin)。
#[tokio::test]
async fn require_login_with_token_succeeds() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let token = state.sessions.issue(ADMIN_ACCOUNT, "auth_it_uid", 1);
let user = expect_guard_ok(
require_login(&state, &auth_headers(&token)).await,
"有 token 的 require_login",
);
assert_eq!(user.account, ADMIN_ACCOUNT);
assert_eq!(user.is_admin, 1);
}
/// `require_module`:无 token ⇒ `code=600`(**先**判登录)。
#[tokio::test]
async fn require_module_without_token_fails() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let err = expect_guard_err(
require_module(&state, &HeaderMap::new(), "system/User").await,
"无 token 的 require_module",
);
assert_eq!(err.code, 600);
assert_eq!(err.msg, "未登录");
}
/// `require_module`:管理员短路放行(不需要任何授权行)。
#[tokio::test]
async fn require_module_allows_administrator() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let token = state.sessions.issue(ADMIN_ACCOUNT, "auth_it_admin_uid", 1);
let user = expect_guard_ok(
require_module(&state, &auth_headers(&token), "system/User").await,
"管理员的 require_module",
);
assert_eq!(user.account, ADMIN_ACCOUNT);
}
/// `require_module`:非管理员 + 菜单已映射 + 无授权 ⇒ `code=403`。
#[tokio::test]
async fn require_module_denies_plain_user_without_grant() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let account = "auth_it_plain_user";
let user_id = insert_plain_user(db, account).await;
let token = state.sessions.issue(account, &user_id, 0);
let err = expect_guard_err(
require_module(&state, &auth_headers(&token), "system/User").await,
"非管理员无授权的 require_module",
);
assert_eq!(err.code, 403);
assert_eq!(err.msg, "无菜单权限");
}
/// `require_module`:菜单**未映射** ⇒ 放行(对齐 `SswPermissionGuard` 的 warn 路径)。
#[tokio::test]
async fn require_module_allows_unmapped_module_key() {
let db = db().await;
let _guard = LOCK.lock().await;
let state = new_state(db);
let account = "auth_it_unmapped_user";
let user_id = insert_plain_user(db, account).await;
let token = state.sessions.issue(account, &user_id, 0);
expect_guard_ok(
require_module(&state, &auth_headers(&token), "not/mapped/anywhere").await,
"未映射 key 的 require_module",
);
}