Files
sso/rust/crates/plugin-sso/src/oauth_state.rs
T
admin 1e2b117218 refactor(paths): 拆 source/ 包层,顶层与 ipass/ipass 对齐
- source/rust   → rust/
- source/conf   → conf/
- source/www    → www/
- source/data-seed → data-seed/
- source/data   → data/
- scripts/ 保留(语义不对应 ipass deploy/)
- /build/ 加入 .gitignore(本机 nginx 源码树)
- README.md 目录树同步 + build 路径 /tmp/sso-build → ./build
- Cargo.toml path 依赖 '../../deps/ipass' → '../deps/ipass'
- CLAUDE.md 同步路径示例

cargo check 通过(52s);release build 通过(1m26s),产物 libsso_gateway.dylib
2026-09-21 15:44:55 +08:00

211 lines
8.3 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.
//! OAuth 状态与存储(SSO 插件个性,**不进内核**)。
//!
//! 内核只提供通用共享内存原语 `state::put/get/remove/clear_prefix` 与通用文件
//! 接口 `store::read_plugin/update_plugin`,本模块用它们实现 OAuth 专属读写:
//!
//! * `ocl:<client_id>` 接入方注册表镜像(`get/put/remove_oauth_client`)
//! * `oac:<code>` 授权码(`put/take_oauth_code`,一次性)
//! * `sso:<token>` 终端用户会话(`get/put/remove_oauth_session`)
//! * `data/oauth_clients.json` 注册表真源(`read/update_oauth_clients`)
//!
//! 这些原本是内核 `state` / `store` 里的 OAuth 段;收窄内核时按「个性代码
//! 插件自己实现」整体迁到此处。语义(前缀、TTL、一次性消费)与迁移前完全一致。
use serde::{Deserialize, Serialize};
use crate::oauth_keys::{
KEY_OAUTH_CLIENT_PREFIX, KEY_OAUTH_CODE_PREFIX, KEY_OAUTH_SESS_PREFIX,
};
use ipass_core::state;
use crate::storex;
// ===========================================================================
// 数据模型(原内核 `models::OAuthClient`;属插件个性,迁到本插件)
// ===========================================================================
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct OAuthClient {
pub client_id: String,
pub client_secret: String,
pub name: String,
pub redirect_uris: Vec<String>,
pub grant_types: Vec<String>,
pub scopes: Vec<String>,
pub confidential: bool,
pub created_at: i64,
// ---- 应用管理增强(2026-09-14):以下字段全部 `#[serde(default)]`,
// 保证存量 `oauth_clients.json`(无这些键)照旧能反序列化。
/// 协议类型:`oauth2`(缺省,含 OIDC)| `cas`。决定管理台给出的接入说明,
/// 以及门户里「点击卡片如何进入应用」。
#[serde(default)]
pub protocol: String,
/// 应用描述(门户卡片副标题)。
#[serde(default)]
pub description: String,
/// 应用图标 URL(门户卡片)。
#[serde(default)]
pub logo_url: String,
/// 应用访问地址(门户点击直达)。OAuth 应用由**应用侧**发起授权,网关无从
/// 推导入口地址,所以要显式登记。
#[serde(default)]
pub home_url: String,
/// 可见范围:三项**全空 = 全员可见**;非空则「属于任一白名单」即可见。
#[serde(default)]
pub visible_roles: Vec<String>,
#[serde(default)]
pub visible_depts: Vec<String>,
#[serde(default)]
pub visible_groups: Vec<String>,
}
pub type OAuthClientTable = Vec<OAuthClient>;
impl OAuthClient {
/// 校验 scope 是否全部落在白名单内(openid 始终允许,OIDC 必备)
pub fn allows_scope(&self, scope: &str) -> bool {
if scope == "openid" {
return true;
}
self.scopes.iter().any(|s| s == scope)
}
/// 校验重定向地址是否在注册清单内(精确匹配,不做前缀/通配)
pub fn allows_redirect(&self, uri: &str) -> bool {
self.redirect_uris.iter().any(|u| u == uri)
}
/// 是否允许该授权类型
pub fn allows_grant(&self, grant: &str) -> bool {
self.grant_types.iter().any(|g| g == grant)
}
/// 协议类型(缺省视为 `oauth2`)。
pub fn protocol_or_default(&self) -> &str {
if self.protocol.is_empty() { "oauth2" } else { &self.protocol }
}
/// 展示名:名称优先,回落 client_id(门户排序/卡片标题共用)。
pub fn display_name(&self) -> &str {
if self.name.is_empty() { &self.client_id } else { &self.name }
}
/// 是否为 CAS service 白名单成员。
///
/// 匹配规则:**精确相等**,或**去掉 query/fragment 后**相等。后者是必要的——
/// CAS 客户端的 `service` 常带自定义参数(`https://app/cb?tab=1`),而登记时
/// 只填基地址(`https://app/cb`);不做归一化会把合法客户端挡在门外。
/// 但绝不做前缀/通配匹配:`https://app/cb` 不能命中 `https://app/cb-evil`。
pub fn allows_service(&self, service: &str) -> bool {
let base = |u: &str| -> String {
u.split(['?', '#'])
.next()
.unwrap_or("")
.trim_end_matches('/')
.to_owned()
};
let target = base(service);
if target.is_empty() {
return false;
}
self.redirect_uris
.iter()
.any(|u| u == service || base(u) == target)
}
/// 门户可见性。三项白名单全空 = 全员可见;否则当前用户的角色 / 部门 /
/// 用户组**落在任一白名单内**即可见(OR 语义,便于「角色 + 例外人员」组合)。
pub fn visible_to(&self, role: &str, dept: &str, groups: &[String]) -> bool {
if self.visible_roles.is_empty()
&& self.visible_depts.is_empty()
&& self.visible_groups.is_empty()
{
return true;
}
if self.visible_roles.iter().any(|r| r == role) {
return true;
}
if !dept.is_empty() && self.visible_depts.iter().any(|d| d == dept) {
return true;
}
groups
.iter()
.any(|g| self.visible_groups.iter().any(|w| w == g))
}
}
// ===========================================================================
// 注册表(文件真源:data/oauth_clients.json)
// ===========================================================================
/// 读取注册表文件(内核只提供带锁原子读,不认识结构)。
pub fn read_oauth_clients() -> OAuthClientTable {
storex::read_plugin::<OAuthClientTable>("oauth_clients.json")
}
/// 加锁「读-改-写」注册表文件,闭包返回新值;`Err` 不落盘。
pub fn update_oauth_clients<T, F>(f: F) -> Result<T, String>
where
F: FnOnce(&mut OAuthClientTable) -> Result<T, String>,
{
let mut table = read_oauth_clients();
let out = f(&mut table)?;
storex::write_plugin("oauth_clients.json", &table)?;
Ok(out)
}
// ===========================================================================
// 注册表共享内存镜像(`ocl:`)
// ===========================================================================
/// 按 client_id 取客户端 JSON(低频:授权/令牌端点各一次)。
pub fn get_oauth_client(client_id: &str) -> Option<String> {
state::get(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes()).map(|(p, _)| p)
}
/// 写入/覆盖客户端 JSON。
pub fn put_oauth_client(client_id: &str, payload: &str) -> bool {
state::put(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes(), payload.as_bytes(), 0)
}
/// 删除客户端(重载/删除时)。
pub fn remove_oauth_client(client_id: &str) -> bool {
state::remove(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes())
}
// ===========================================================================
// 授权码(`oac:`,一次性)
// ===========================================================================
/// 写入授权码上下文(含 sub / client_id / redirect_uri / scope / nonce / PKCE 挑战)。
pub fn put_oauth_code(code: &str, ctx: &str, expires_at: i64) -> bool {
state::put(KEY_OAUTH_CODE_PREFIX, code.as_bytes(), ctx.as_bytes(), expires_at)
}
/// 取出并消费授权码(一次性):过期或不存在返回 None。
pub fn take_oauth_code(code: &str, now: i64) -> Option<String> {
let raw = state::get_live(KEY_OAUTH_CODE_PREFIX, code.as_bytes(), now)?;
state::remove(KEY_OAUTH_CODE_PREFIX, code.as_bytes());
Some(raw)
}
// ===========================================================================
// 终端用户会话(`sso:`,对应 SSO 登录态)
// ===========================================================================
/// 写入 SSO 会话。
pub fn put_oauth_session(token: &str, payload: &str, expires_at: i64) -> bool {
state::put(KEY_OAUTH_SESS_PREFIX, token.as_bytes(), payload.as_bytes(), expires_at)
}
/// 读取(未过期才返回)。
pub fn get_oauth_session(token: &str, now: i64) -> Option<String> {
state::get_live(KEY_OAUTH_SESS_PREFIX, token.as_bytes(), now)
}
/// 删除会话。
pub fn remove_oauth_session(token: &str) -> bool {
state::remove(KEY_OAUTH_SESS_PREFIX, token.as_bytes())
}