Files
sso/source/rust/crates/plugin-sso/src/oauth_state.rs
T
ssw a988cc3763 refactor: 网关拆分为 ipass-core 内核 + plugin-sso/plugin-domain 插件 + gateway
原 source/rust/src/ 单体 crate 拆为 Cargo workspace:

  crates/ipass-core/    内核:state(共享内存) / store(JSON 原子写) /
                        users(账号唯一写入口) / models(共性字段 + extra 透传) /
                        config(共性常量) / plugin(装配契约) / loc(开关) /
                        session / audit / http / util
  crates/plugin-sso/    身份插件:OAuth2 / OIDC / IAP / TOTP / RSA 等个性代码
  crates/plugin-domain/ 域名插件:企业域名「子域名 → 后端」转发 + 申请/审核
  gateway/              **唯一** cdylib,module 壳 + PLUGINS 装配数组

收窄原则:内核只留共性,个性代码下放插件。收窄后内核不再提供原单体的
bump_window / put_ukey / put_upstream / reload_shm 等,改由插件用 state 泛型
原语自行重建;OAuth 常量与前缀(如 OAUTH_SESSION_COOKIE=sso_sid、
IAP_TOKEN_AUDIENCE=sso-gateway)与历史取值严格一致。

插件一律 crate-type=["rlib"] 由 gateway 静态链入,产出单个
libsso_gateway.dylib —— 不各自出 .so(nginx 动态模块无稳定 ABI,
跨 .so 传 String 即双重 free)。

插件装配点集中在 gateway 5 处:use / PLUGINS 数组 / ModuleConfig 字段 /
Merge / loc_switch 分支,外加指令数组(长度 +1,新增 sso_domain 等开关)。
2026-09-13 10:23:34 +08:00

134 lines
5.2 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 ipass_core::store;
// ===========================================================================
// 数据模型(原内核 `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,
}
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)
}
}
// ===========================================================================
// 注册表(文件真源:data/oauth_clients.json)
// ===========================================================================
/// 读取注册表文件(内核只提供带锁原子读,不认识结构)。
pub fn read_oauth_clients() -> OAuthClientTable {
store::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)?;
store::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())
}