commit c8a02b8c4960933053b01805187a38192ca24fe1 Author: ssw Date: Sat Sep 12 21:42:06 2026 +0800 feat: 从网关项目剥离为独立 SSO 统一认证服务 定位:身份层(IdP + IAP),不含动态域名转发 / LLM 上游代理 / 用量计费。 代码(source/rust,nginx 动态模块 + Rust,单进程零外部依赖) - IdP:authorization_code(含 PKCE)/ refresh_token / client_credentials / password 四种 grant,含 discovery / introspect / userinfo / jwks 占位 - IAP:access 阶段门禁,注入 X-Auth-* 到后端,客户端伪造同名头被覆盖 - MaxKey 互通:/oauth/v20/* 与 /oauth2.0/* 别名 + context-path 归一化 + 扁平字段 - 管理接口:账号(含角色/部门/用户组)与 OAuth 接入方注册表,热写穿共享内存 - 模块改名 ngx_http_sso_module,指令 sso_state / sso_data_dir / sso_api / sso_iap, Cookie sso_sid(终端用户)与 sso_admin_session(管理员)两套身份两套会话 配置(source/conf) - nginx.conf 生产模板(TLS、IAP 子域、含 auth_sub 的日志格式) - nginx.test.conf 本机验证配置(明文 18095-18099) - tls/README.md 证书约定与公钥比对校验 前端(source/www/admin.html) - 三 tab:账号管理 / 接入方 / 接入指南;去掉审核队列、域名、LLM 上游、用量统计 测试与脚本 - tests/ 三套端到端:协议基线 14 项 · MaxKey 互通与接入 24 项 · 管理接口 31 项,全绿 - tests/demo-system 演示业务系统(Python 标准库),覆盖应用自建客户端与 IAP 零改造两种姿势 - scripts/run-local-e2e.sh 本机一键起停;scripts/seed-data.sh 物化运行时数据目录 文档 - README.md 概览与快速开始;CLAUDE.md 硬约定与排障速查 - docs/design.md 完整设计;docs/roadmap.md 待执行任务(v2 RS256+JWKS、用户管理界面) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4d7ca27 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +# --------------------------------------------------------------------------- +# 构建产物 +# --------------------------------------------------------------------------- +/source/rust/target/ +**/*.dylib +**/*.so +**/*.o +**/*.a + +# --------------------------------------------------------------------------- +# 运行时数据(含真实口令散列与 API Key,禁止入库) +# 种子模板在 source/data-seed/,用 scripts/seed-data.sh 物化 +# --------------------------------------------------------------------------- +/source/data/ + +# --------------------------------------------------------------------------- +# 参考资料:来源项目与第三方实现,仅本地阅读,不入库 +# refs/ipass —— 被剥离的网关项目(来源) +# refs/MaxKey —— MaxKey 参考实现(协议对齐用) +# --------------------------------------------------------------------------- +/refs/ + +# --------------------------------------------------------------------------- +# 工具与临时文件 +# --------------------------------------------------------------------------- +.workbuddy/ +.DS_Store +*.log +*.pid +*.swp +*~ +.idea/ +.vscode/ + +# 环境文件(可能含密钥) +.env +.env.* +!.env.example diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..d5f13f6 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,250 @@ +# CLAUDE.md + +给 AI 协作者(Claude Code / WorkBuddy 等)的项目说明。人读文档见 [`README.md`](README.md), +设计细节见 [`docs/design.md`](docs/design.md),待办见 [`docs/roadmap.md`](docs/roadmap.md)。 + +## 一句话定位 + +**统一认证服务(SSO)**:nginx 动态模块(`ngx-rust`)+ Rust,单进程,无数据库 / Redis / MQ。 + +- **IdP**:OAuth2.0 / OIDC 授权服务器 —— 发 token、登录、introspect、discovery。 +- **IAP**:nginx `access` 阶段门禁,把身份以 `X-Auth-*` 注入后端,业务系统零改造。 +- **协议对齐 MaxKey**:端点别名 + 扁平响应,照抄 MaxKey 文档的应用可直接对接。 + +状态 = `data/` 下两个 JSON(`users.json` / `oauth_clients.json`); +**客户端注册表与会话常驻共享内存,热路径零文件 I/O**。 + +> **定位差异(不要越界)**:本项目**不做**动态域名转发、LLM 上游代理、用量计费。 +> 代码由内部网关项目剥离而来(`refs/ipass`,仅本地参考、不入库)。 +> 因此这里没有 `$proxy_backend_addr` 这类动态上游变量,`proxy_pass` 由 nginx 配置写死。 + +--- + +## 构建与运行(踩过的坑都在这) + +### 硬约定:`ngx` 必须用 vendored 源码,不能走 crates.io,也不能走 git + +1. **crates.io 直接编译失败**。`ngx = "0.5"`(crates.io **0.5.1**)只发布了配置阶段接口 `HttpModule`; + 请求阶段 API(`add_phase_handler` / `HttpPhase` / `HttpRequestHandler`)**尚未发版**, + 报 `unresolved imports ngx::http::HttpPhase`。 +2. **git 依赖会永久挂起(最隐蔽的坑)**。`ngx-rust` 挂了一个指向**完整 nginx 仓库**的 submodule, + cargo 解析 git 依赖时会 `update_submodules` 去克隆几十 MB 的 nginx 仓库。国内网络下卡死 —— + **实测 5 分钟 0% CPU、无网络活动、无产物**,`sample` 抓栈停在 + `GitCheckout::update_submodules → fetch → wait4`。 +3. **正解**:源码 vendor 到 `source/rust/vendor/ngx-rust/`(已剥离 `.git`,103 个文件 / 696K), + `Cargo.toml` 用 `path` 依赖;`[workspace] exclude = ["vendor/ngx-rust"]` 处理嵌套 workspace。 + +### 为什么要 `--with-pcre=<绝对路径>`,以及路径不能随便挪 + +`ngx-rust` 的 `nginx-sys/build/main.rs` 会从 **`objs/Makefile`** 抽出编译参数去预处理 `ngx_core.h`, +其中带 `-I /src/`。所以: + +- nginx 的 `./configure --with-pcre=...` 路径,与模块编译时的源码树**必须同一份**; +- **把源码树 `mv` 到别处后,必须重新 `./configure && make`**(只改环境变量不够)。 + 不重新 configure 的报错形态是模块编译期: + `fatal error: 'pcre2.h' file not found`(`-I` 还指着旧路径)。 + +### 本机构建 + +```bash +cd source/rust +export LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib # macOS,bindgen 需要 +export NGINX_SOURCE_DIR=/tmp/sso-build/src/nginx-1.30.4 +export NGINX_BUILD_DIR=/tmp/sso-build/src/nginx-1.30.4/objs +cargo build --release +# 产物:source/rust/target/release/libsso_gateway.{dylib,so} +``` + +冷编译约 40 秒,增量 1~2 秒。 + +> `source/rust/build.rs` **不可删**:macOS 必须 `-undefined dynamic_lookup`——动态模块引用的 +> nginx 运行时符号由主程序在 `load_module` 时提供,链接时必然未定义。 +> `ngx` crate 的 build.rs 也设了,但 `rustc-link-arg` **只对设置它的 crate 生效**、不传给依赖方。 + +### 跑测试 + +```bash +bash scripts/run-local-e2e.sh # 三套 e2e 全跑(自动起停 nginx + demo 系统) +bash scripts/run-local-e2e.sh --keep # 保留进程手工排查 +``` + +--- + +## 目录地图(改代码前先看这里) + +| 路径 | 职责 | +| --- | --- | +| `source/rust/src/lib.rs` | **模块入口**:指令解析、共享内存建表(`state_zone_init`,fork 前一次)、变量注册、两个阶段处理器(IAP access / API content)、`init_process` 播种 admin | +| `source/rust/src/api.rs` | **API 统一分发器**:路由表(精确匹配)+ 鉴权分流(`Guard::Public/User/Admin`)+ 全部 handler | +| `source/rust/src/oauth.rs` | **OAuth2 AS 全部逻辑**:client/code/token 模型、HS256 JWT 签名/验签、PKCE、端点 handler、IAP 身份解析 | +| `source/rust/src/oauth_clients.rs` | 接入方注册表(`reload_shm` / `get` / `all` / `upsert` / `delete` / `view`) | +| `source/rust/src/users.rs` | 账号:播种 admin、创建、改密、重置 Key、角色、部门/用户组校验 | +| `source/rust/src/session.rs` | 管理员登录会话(`sess:` 键 + HttpOnly Cookie,滑动续期) | +| `source/rust/src/state.rs` | 共享内存:根结构、键值编解码(栈上拼 key)、业务包装函数 | +| `source/rust/src/store.rs` | JSON 原子读写(`.tmp` + `rename`)+ 跨 worker 文件锁 + data 目录 | +| `source/rust/src/http.rs` | 请求辅助:参数合并、**两段式请求体读取**、JSON 响应输出 | +| `source/rust/src/util.rs` | 随机数、SHA-256、口令哈希、常量时间比较、时间格式化、日志 | +| `source/rust/src/config.rs` | **全部策略常量**:TTL、长度上限、共享内存键前缀、cookie 名 | +| `source/rust/src/models.rs` | `User` / `OAuthClient` 结构;`groups` 用宽容反序列化(同时接受 `["a"]` 与 `"a,b"`) | + +其余: + +| 路径 | 职责 | +| --- | --- | +| `source/conf/nginx.conf` | 生产模板:IdP + 管理台 443、IAP 子域、80→443、含 `auth_sub` 的日志格式 | +| `source/conf/nginx.test.conf` | 本机/CI 验证配置(明文 18095-18099),`scripts/run-local-e2e.sh` 会渲染它 | +| `source/conf/tls/README.md` | 证书约定、acme.sh 签发、公钥比对校验(**ECC 不能用 `openssl rsa -modulus`**) | +| `source/www/admin.html` | 管理台单页(三个 tab:账号 / 接入方 / 接入指南),纯静态 + fetch | +| `source/data-seed/` | 种子模板(进版本库):`oauth_clients.json` + `users.json.example` | +| `source/data/` | 运行时数据(**不进版本库**,含真实口令散列与 API Key) | +| `scripts/seed-data.sh` | 物化数据目录:`data-seed/` → `data/`,并生成 admin/alice 真实散列 | +| `tests/demo-system/` | 演示用「简单业务系统」(Python 标准库),验证两种接入姿势 | +| `refs/` | **不入版本库**:`refs/ipass`(来源项目)、`refs/MaxKey`(协议对齐参考) | + +容器内路径约定:模块装 `/usr/local/nginx/modules/`,data 默认 `/usr/local/nginx/data` +(`sso_data_dir` 可覆盖)。**别在宿主机上按容器路径找文件。** + +--- + +## 核心机制(理解这几条就够) + +1. **请求分流靠「location 开关 + 阶段」**。阶段处理器注册在 http 主配置上(全局生效), + **必须靠 location 指令收敛**,否则管理台与静态页也会走认证逻辑: + - **IAP**(access,`sso_iap on`):取 Bearer 或 `sso_sid` cookie → 校验 → 写 `$auth_*` → 放行/401。 + - **API/协议**(content,`sso_api on`):**先异步读请求体**再分发(access 阶段拿不到 body)。 + +2. **共享内存是运行期真源,JSON 文件只是持久化副本**。所有写操作**同时**写 shm 与文件 + (write-through)。**写穿不是优化,是正确性要求**:漏掉 `sync_shm` 等于配置没生效, + 而且**没有缓存 TTL 兜底**——漏了就一直是错的,直到重启。 + - ⚠️ 语义代价:绕过 API 直接改 `data/*.json` **不热生效**,需重启或走管理接口。 + +3. **两套身份、两套会话,别混**: + - **终端用户**:共享内存 `sso:` 前缀 + Cookie `sso_sid`(`OAUTH_SESSION_COOKIE`)。 + - **管理员**:共享内存 `sess:` 前缀 + Cookie `sso_admin_session`(`COOKIE_NAME`)。 + 键前缀还有 `fail:`(登录失败计数)、`oac:`(授权码)、`ocl:`(接入方登记)。 + +4. **nginx 变量注册必须两步,缺一步就读成空**: + - 先 `ngx_http_add_variable`(登记名字 + `get_handler`),再 `ngx_http_get_variable_index` + (取写入槽位)。只调后者:变量被推进 `cmcf->variables` 但 `get_handler=NULL`, + `ngx_http_variables_init_vars` 会直接 `exit()` 报「unknown variable」。 + - 只调前者:拿不到 index,`r->variables[idx]` 没地方写。 + - 注入变量**不能**标 `NGX_HTTP_VAR_NOCACHEABLE`,否则 `ngx_http_get_flushed_variable` + 每次读取都清缓存并回调 get_handler,而 handler 拿不到注入值 → 变量读成空。 + - 注册时机在 **preconfiguration**:request 阶段才 `add_variable` 时, + `proxy_pass http://$auth_user` 之类早就解析失败了。 + +5. **IAP 防伪造靠「覆盖」而不是「过滤」**。`X-Auth-*` 是网关断言,由 `proxy_set_header` + 写入,客户端伪造的同名头会被覆盖。**新增注入头时必须同时在这两处加**: + `lib.rs` 的 `AUTH_VAR_NAMES` / `set_auth_vars`,以及每个受保护 location 的 `proxy_set_header`。 + +6. **IAP 重签令牌的 aud / scope 有专用常量**:`IAP_TOKEN_AUDIENCE = "sso-gateway"`、 + `IAP_TOKEN_SCOPE = "openid profile email"`。改动会影响所有依赖方,改前先全局搜索。 + +7. **口令哈希必须逐位一致**:`sha256("salt:password")` 之后再迭代 `HASH_ROUNDS`(=1000) 次 + `sha256(x + salt)`。注意**第一轮有冒号**。 + 改轮数或拼接顺序会让存量 `users.json` 全部登录失败 + (已用独立 Python 实现逐字节核对;`scripts/seed-data.sh` 里是同一套算法的 Python 版)。 + +--- + +## 硬约定(改代码必须遵守) + +**安全与生命周期** + +- **不要在 worker 里 panic**。`Cargo.toml` 设了 `panic = "abort"`——一次 panic 直接打死整个 worker + (不是 500,是 worker 进程消失)。热路径禁止 `unwrap()` / `expect()` / 越界索引, + 错误一律走 `Result` + 显式降级。管理接口也照此办理。 +- **不要在 worker 里起子进程或 shell**。文件落盘靠 `store` 的原子写(`.tmp` + `rename`)。 +- **热路径禁止同步文件 I/O**。`users::get` 会读文件 + 全表解码,**只能用在管理接口**, + 不要顺手用在 IAP 鉴权(IAP 走共享内存会话)。 + +**改配置/接口时的硬规矩** + +- **新增接口三步**:① 在 `api.rs` 写 handler,统一用 `http::ok/fail`; + ② 在 `route()` 表加一行,`Guard` 选 `Public` / `User` / `Admin`; + ③ 涉及接入方/账号变更的,**必须调对应的 `sync_shm`**。鉴权由分发器统一兜底, + **不要在单个 handler 里重复实现**。 +- **所有写操作必须同时更新 shm 与 JSON 文件**。只写一边 = 「重启后回滚」或「改了不生效」。 +- **写共享内存失败必须出声**。`state::put_*` 返回 `false`(zone 满 / 分配失败)时要 `log_err` + (带对象标识与后果);`reload_shm` 要核对「期望条数 vs 实际装载」。**别丢掉返回值**—— + 没有回源兜底,写失败就是「刚建好却调不通,日志里什么都没有」,属于最难查的一类形态。 +- **`env` 白名单必须在 `nginx.conf` main 上下文**。缺 `env OAUTH_ISSUER;` 会导致 + discovery 的 `issuer` 与第三方实际校验的值不一致——**这是最容易踩的坑**。 +- **`client_body_buffer_size` 必须大于最大 API 请求体**,否则超出的部分落到临时文件, + 而 `collect_body` 只读内存 buf → **body 被静默截断**(表现为 JSON 解析失败)。 + 当前管理 server 设 1m。 +- **JSON 空数组必须序列化成 `[]`**。`serde_json` 对空 `Vec` 本来就输出 `[]`, + 但**别用 `json!({})` 顶替列表字段**——前端直接 `.map/.filter`,拿到 `{}` 会报错。 +- **改 `source/rust/` 或 `source/conf/` 后必须重启 nginx**。动态模块在 `load_module` 时载入, + **reload 不会重新加载 `.so`**;`data/` 是写穿语义,重启后从文件重建。 +- **`location @name` 不能写成 `location = @name`**。带 `=` 时 nginx 会把它注册成 + 「精确匹配普通 location」而 `clcf->named` 仍为 0,于是 `error_page 401 = @oauth_login` + 的内部跳转在 `named_locations[]` 里找不到该 location → 500。 +- **自建 nginx 不能 `--without-http_rewrite_module`**:`return` / `error_page` 内部跳转都来自它。 +- **前端隐藏元素必须靠 `[hidden]{display:none!important}` 兜底**:author 样式的 `display` + 会盖掉 UA 的 `display:none`。 + +**文档与仓库卫生** + +- 不要在文档里写真实口令、API Key 或内网拓扑明细。 +- **不要把 `source/data/`(含口令散列与全部 Key)提交进版本库**;`refs/`、`.workbuddy/`、 + `target/` 已忽略。 +- 改行为后同步更新 `docs/design.md` 对应小节;**待办项写进 `docs/roadmap.md`**,别散在代码注释里。 + +--- + +## 排障速查 + +| 现象 | 原因 / 处置 | +| --- | --- | +| **改了代码但行为没变** | 90% 是**没重启**。动态模块 `load_module` 时载入,reload 不重载 `.so` | +| **worker 进程静默消失 / 全站 502** | worker 里 panic 了(`panic = "abort"`)。看 error.log 的 panic 栈,多半是热路径 `unwrap()` | +| 编译报 `unresolved imports ngx::http::HttpPhase` | 又用 crates.io 的 `ngx` 0.5.1 了。必须用 `source/rust/vendor/ngx-rust` | +| `cargo build` 卡住数分钟 0% CPU | 又把 `ngx` 改回 git 依赖了 —— 它挂的 submodule 会去克隆完整 nginx 仓库 | +| 链接报 `ld: symbol(s) not found` | `source/rust/build.rs` 的 `-undefined dynamic_lookup` 被删了(macOS 必需) | +| nginx 启动即报 `unknown "auth_user" variable` | 变量注册漏了 `add_variable` 那一步(见「核心机制」第 4 条) | +| `proxy_set_header X-Auth-User $auth_user;` 注入成了空 | 变量被标了 `NGX_HTTP_VAR_NOCACHEABLE`,或注册时机不在 preconfiguration | +| 授权码换发报 `invalid_client` | 接入方注册表没热加载(写操作漏 `sync_shm`),或回调地址逐字符不一致 | +| 管理接口 `401` | 管理员会话 Cookie 缺失/过期(**重启会清空会话,属预期**) | +| 终端用户 `401` 但 Cookie 看着在 | 两套身份别混:终端用户看 `sso_sid`,管理员看 `sso_admin_session` | +| 新增客户端「管理台显示已保存,授权时报未知 client_id」 | 写穿共享内存时把旧值原样写回了。`tests/admin-oauth-clients-e2e.sh` 第 4 组专门盯这个 | +| `429 登录失败次数过多` | 同一 IP 窗口内失败次数超限(`fail:` 前缀),等窗口过期或重启 | +| 第三方报 `issuer mismatch` | `env OAUTH_ISSUER;` 缺失,或值与浏览器实际访问的 host 不一致 | +| 跨子域登录不生效(每个子域都要重新登录) | 没设 `OAUTH_COOKIE_DOMAIN`(不设 = 主机级 cookie) | +| 证书看着没过期却报 TLS 错 | 先 `openssl s_client -servername <域名>` 看链路**实际**收到的证书;acme.sh 产物在 `~/.acme.sh/`,与 `conf/tls/` 是两份,续期后必须拷过去再 reload | +| `--with-pcre` 源码树挪位置后编译报 `pcre2.h not found` | 见「构建」小节:必须重新 `./configure && make` | + +--- + +## 常用操作 + +```bash +# ---- 本机 ---- +bash scripts/run-local-e2e.sh # 三套 e2e 全跑 +bash scripts/run-local-e2e.sh --keep # 保留进程手工排查 +bash scripts/seed-data.sh # 物化 source/data/ +bash scripts/seed-data.sh --force # 重建 users.json(丢已有账号) + +# 手工打几个关键接口(网关在跑时) +curl -s http://127.0.0.1:18098/.well-known/openid-configuration | python3 -m json.tool +curl -s -D- -o/dev/null -X POST http://127.0.0.1:18098/login \ + --data-urlencode 'username=alice' --data-urlencode 'password=alice123' # 看 Set-Cookie: sso_sid +curl -s -b 'sso_sid=<值>' http://127.0.0.1:18098/api/v1/me + +# ---- 生产 ---- +/usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx # 改完先 -t 再起 +``` + +--- + +## 边界:不要做的事 + +- **不要**引入数据库、Redis、消息队列或额外常驻进程 —— 本项目的价值就是单进程、零依赖。 +- **不要**把流量层能力搬回来(动态域名转发、LLM 上游代理、用量计费)。这是与来源项目的**定位分界**。 +- **不要**在 `source/data/` 里手工改文件后期待热生效 —— **共享内存才是运行期真源**,改文件需重启。 +- **不要**把 `source/data/` 提交进版本库,也不要在 `refs/` 里提交参考项目。 +- **不要**重写整个 `nginx.conf` —— 它很短,**逐点修改**。 +- **不要**在未确认需求前动 `source/data/users.json`,那会直接影响登录。 +- **不要**为了「顺手」把 HS256 换成 RS256(或反之):签名算法是给第三方的契约, + 切换要走 `docs/roadmap.md` 里的 v2 计划(新旧并行 + `kid` 轮换)。 +- 测试不要复用生产 data 目录:用 `source/data/` + 非特权端口(18095-18099),不要占用 80/443。 diff --git a/README.md b/README.md new file mode 100644 index 0000000..c99b484 --- /dev/null +++ b/README.md @@ -0,0 +1,226 @@ +# SSO —— 统一认证服务(nginx 动态模块 + Rust) + +自包含的 **OAuth2.0 / OIDC 身份提供者(IdP)** 与 **身份感知代理(IAP)**, +以 nginx 动态模块形式运行:加载进 nginx,不引入数据库、Redis、消息队列或任何额外常驻进程。 + +- **IdP**:签发 access / refresh / id_token,支持 `authorization_code`(含 PKCE)、 + `refresh_token`、`client_credentials`、`password` 四种 grant,附带 discovery / introspect / userinfo。 +- **IAP**:在 nginx `access` 阶段做门禁,把身份以 `X-Auth-*` 请求头**注入**到后端, + 既有业务系统改一行 nginx 配置即可接入,**业务代码零改造**。 +- **协议兼容 MaxKey**:提供 `/oauth/v20/*`、`/oauth2.0/*` 端点别名与 context-path 归一化, + 照抄 MaxKey 文档的第三方应用不用改一行代码。 + +> **定位**:身份层,不是流量层。本服务**不做**动态域名转发、LLM 上游代理、用量计费。 +> 代码由内部网关项目剥离而来(来源存档见 `refs/ipass`,不入版本库)。 + +--- + +## 快速开始 + +### 依赖 + +- 一棵已 `./configure` 过的 **nginx 1.30.4 源码树**(模块须与 nginx 二进制同源编译) +- Rust 工具链 + `libclang`(bindgen 用) +- `curl`、`python3`(只用于测试脚本与种子生成) + +### 本机跑通端到端(不依赖 Docker) + +```bash +# ① 准备 nginx 源码树(只需 configure,一次即可) +mkdir -p /tmp/sso-build/src && cd /tmp/sso-build/src +curl -fsSL https://nginx.org/download/nginx-1.30.4.tar.gz -o nginx.tar.gz && tar xzf nginx.tar.gz +curl -fsSL https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.44/pcre2-10.44.tar.gz -o pcre2.tar.gz && tar xzf pcre2.tar.gz + +# ② 编译 nginx(必须含 rewrite 模块:`return` / `error_page` 内部跳转都靠它) +cd nginx-1.30.4 +./configure --prefix=/tmp/sso-build/nginx \ + --with-pcre=/tmp/sso-build/src/pcre2-10.44 --with-http_realip_module \ + --without-http_gzip_module --without-http_ssi_module --without-http_userid_module \ + --without-http_autoindex_module --without-http_geo_module \ + --without-http_split_clients_module --without-http_referer_module \ + --without-http_uwsgi_module --without-http_scgi_module --without-http_grpc_module \ + && make -j"$(sysctl -n hw.ncpu)" + +# ③ 编译 Rust 模块 +cd <本仓库>/source/rust +export LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib # macOS +export NGINX_SOURCE_DIR=/tmp/sso-build/src/nginx-1.30.4 +export NGINX_BUILD_DIR=/tmp/sso-build/src/nginx-1.30.4/objs +cargo build --release # 产物 source/rust/target/release/libsso_gateway.dylib + +# ④ 一键跑三套端到端(自动播种数据、起 nginx + demo 系统、跑完自动清理) +cd <本仓库> && bash scripts/run-local-e2e.sh +``` + +### 手工观察 IdP / 管理台 + +```bash +bash scripts/run-local-e2e.sh --keep # 保留进程不清理 +# 管理台 http://127.0.0.1:18098/admin 账号 admin / 123456 +# 演示用户 alice / alice123 +# discovery http://127.0.0.1:18098/.well-known/openid-configuration +kill <打印出的 pid> +``` + +--- + +## 目录结构 + +``` +sso/ +├── docs/ +│ ├── design.md 设计文档:端点、token 模型、共享内存、MaxKey 互通、构建与测试 +│ ├── roadmap.md 待执行任务(v2 RS256+JWKS、用户管理界面) +│ └── screenshots/ 管理台与登录页截图 +├── source/ 可部署产物(代码 + 配置 + 静态页) +│ ├── rust/ 动态模块源码(Cargo workspace,vendor 了 ngx-rust) +│ ├── conf/ +│ │ ├── nginx.conf 生产模板(TLS、IAP 子域、日志字段) +│ │ ├── nginx.test.conf 本机/CI 验证配置(明文端口 18095-18099) +│ │ └── tls/README.md 证书约定、acme.sh 签发与校验 +│ ├── www/admin.html 管理台单页(纯静态 + fetch) +│ ├── data-seed/ 种子模板(进版本库) +│ └── data/ 运行时数据(**不进版本库**,由 scripts/seed-data.sh 生成) +├── tests/ 测试程序与测试应用 +│ ├── oauth2-e2e.sh 协议基线(discovery/grant/token/IAP 注入) +│ ├── oauth2-maxkey-e2e.sh MaxKey 互通 + demo 系统接入 +│ ├── admin-oauth-clients-e2e.sh 管理接口(接入方注册表) +│ └── demo-system/ 演示用「简单业务系统」(Python 标准库) +├── scripts/ +│ ├── run-local-e2e.sh 本机一键起停 + 跑三套 e2e +│ └── seed-data.sh 物化运行时数据目录 +└── refs/ 参考资料(**不进版本库**):ipass 来源项目、MaxKey +``` + +--- + +## 端点一览 + +### 认证协议端点 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| GET | `/oauth/authorize` | 授权端点(未登录跳登录页) | +| POST | `/oauth/token` | 换发令牌(四种 grant) | +| GET/POST | `/oauth/userinfo` | 当前令牌对应用户声明 | +| POST | `/oauth/introspect` | RFC 7662 令牌自省(第三方校验,需客户端鉴权) | +| GET | `/.well-known/openid-configuration` | OIDC discovery | +| GET | `/oauth/jwks` · `/.well-known/jwks.json` | 公钥集合(**当前 HS256,返回 404 + 原因**,见路线图) | +| GET/POST | `/login` | 登录页与表单提交(建立 `sso_sid` 会话) | +| GET/POST | `/oauth/logout` | 注销会话 | + +### MaxKey 兼容别名 + +| 别名 | 说明 | +| --- | --- | +| `/oauth/v20/authorize` · `/oauth2.0/authorize` | 授权端点 | +| `/oauth/v20/token` · `/oauth2.0/accessToken` | 换发(**裸对象响应**,不套 `{code,msg,data}`) | +| `/oauth/v20/me` | 扁平字段 `username`/`userid`/`realname`/`email`/`mobile`,令牌走 `access_token` 参数 | +| `/oauth2.0/profile` · `/oauth/v20/logout` | 同上 | +| `/maxkey/...` · `/sign/authz/...` · `/sign/...` · `/authz/...` · `/api/...` 前缀 | context-path 自动归一化 | + +### 管理接口(`/api/admin/*`,需管理员会话 Cookie) + +| 分类 | 路径 | +| --- | --- | +| 会话 | `login` · `logout` · `session` | +| 账号 | `users`(列表)· `users/create` · `users/key` · `users/password` · `users/display` · `users/profile`(部门/用户组)· `users/role` · `users/delete` | +| 接入方 | `oauth-clients`(列表)· `oauth-clients/save` · `oauth-clients/rotate` · `oauth-clients/delete` | + +账号态 API:`GET /api/v1/me`(`X-API-Key` 或 Bearer 鉴权)。 + +--- + +## 两种接入姿势 + +**方式一:应用自己当 OAuth2 客户端** —— 应用实现授权码流程,拿到令牌代用户调用 API。 +适合需要令牌的场景(示例见 `tests/demo-system/app.py`,支持 `maxkey` / `standard` 两种端点风格)。 + +**方式二:前置 IAP,零改造** —— 在业务 location 上加两段配置即可: + +```nginx +location / { + sso_iap on; # access 阶段门禁 + proxy_pass http://127.0.0.1:8080; + + # ⚠️ 这组 header 由网关断言覆盖,客户端伪造同名头会被盖掉 + proxy_set_header X-Auth-User $auth_user; + proxy_set_header X-Auth-Email $auth_email; + proxy_set_header X-Auth-Groups $auth_groups; + proxy_set_header X-Auth-Sub $auth_sub; + proxy_set_header X-Auth-Token $auth_token; + + error_page 401 = @oauth_login; # 未登录 → 跳登录页并回跳 +} +location @oauth_login { # 注意:named location 不能写 `location = @name` + return 302 "https://sso.yourdomain.com/login?redirect=$scheme://$host$request_uri"; +} +``` + +后端只读 `X-Auth-*`,不接触令牌。跨子域 SSO 用 `OAUTH_COOKIE_DOMAIN=.yourdomain.com` 打开。 + +--- + +## 生产部署 + +```bash +# 1. 模块装到 nginx +install -m 755 source/rust/target/release/libsso_gateway.so /usr/local/nginx/modules/ + +# 2. 配置(按环境改域名与证书路径) +cp source/conf/nginx.conf /usr/local/nginx/conf/nginx.conf +cp -r source/www /usr/local/nginx/www +cp -r source/data-seed /usr/local/nginx/data-seed + +# 3. 播种账号(生产务必覆盖默认口令) +DATA_DIR=/usr/local/nginx/data ADMIN_PASSWORD='<强口令>' bash scripts/seed-data.sh + +# 4. 证书:见 source/conf/tls/README.md(acme.sh 签发 + 公钥比对校验) + +# 5. 启动/重载 +/usr/local/nginx/sbin/nginx -t && /usr/local/nginx/sbin/nginx +``` + +**改代码后必须重启,不能 reload** —— 动态模块在 `load_module` 时载入,`reload` 不会重新读取 `.so`。 + +### 必须显式声明的环境变量 + +nginx 默认剥离所有环境变量,`nginx.conf` 的 main 上下文里必须有: + +```nginx +env ADMIN_INIT_PASSWORD; # 缺了这行模块读到的初始口令恒为空 +env OAUTH_SIGNING_SECRET; # 令牌签名密钥(HS256 对称密钥) +env OAUTH_ISSUER; # 必须与浏览器实际访问的 host 一致,否则第三方校验 issuer 失败 +env OAUTH_COOKIE_DOMAIN; # 跨子域 SSO 才需要;不设 = 主机级 cookie +``` + +--- + +## 测试 + +```bash +bash scripts/run-local-e2e.sh # 三套全跑(推荐) +bash tests/oauth2-e2e.sh http://127.0.0.1:18098 http://127.0.0.1:18099 # 协议基线 +bash tests/oauth2-maxkey-e2e.sh # MaxKey 互通 + demo 接入 +bash tests/admin-oauth-clients-e2e.sh # 管理接口 +``` + +客户端密钥**不硬编码在脚本里**,运行时从 `$DATA_DIR/oauth_clients.json` 读取。 + +--- + +## 待执行任务 + +见 [`docs/roadmap.md`](docs/roadmap.md)。当前两项: + +1. **v2:RS256 签名 + `/oauth/jwks`** —— 让第三方本地验签,不必回源 introspect。 +2. **用户管理界面** —— 管理台「账号管理」目前只管账号与密钥,缺**角色 / 部门 / 用户组**的可视化维护 + (后端接口已可用:`users/profile`、`users/role`)。 + +--- + +## 深入阅读 + +- [`docs/design.md`](docs/design.md) —— 完整设计:token 模型、共享内存布局、防伪造机制、 + MaxKey 差异说明、构建踩坑、测试覆盖清单 +- [`CLAUDE.md`](CLAUDE.md) —— 给 AI 协作者的项目说明:硬约定、目录地图、排障速查 diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..193e769 --- /dev/null +++ b/docs/design.md @@ -0,0 +1,706 @@ +# SSO 统一认证设计(自包含 IdP + IAP) + +> 目标:**直接实现** OAuth2.0 / OIDC 授权服务器能力,**不依赖 MaxKey 运行时**, +> 但协议层面对齐 MaxKey 的 OAuth2.0 实现,使第三方应用可以像对接 MaxKey 一样对接本服务。 +> 同时保留 nginx 反向代理的「自动注入认证信息」能力(Identity-Aware Proxy,IAP)。 +> +> **定位**:身份层,不是流量层 —— 不做动态域名转发、不做 LLM 上游代理、不做用量计费。 +> 本项目由内部网关项目 `refs/ipass` 剥离而来,砍掉全部流量层能力后独立成库。 + +--- + +## 1. 角色定位 + +| 组件 | 职责 | +| --- | --- | +| **sso(本仓库)** | ① OAuth2.0 / OIDC **授权服务器(IdP)**:发 token、登录、introspect、discovery
② **Identity-Aware Proxy(IAP)**:在 access 阶段做门禁,并在 `proxy_set_header` 自动注入 `X-Auth-*` 身份头到后端 | +| **后端服务** | 零改造:只读网关注入的 `X-Auth-*` 头,信任网关身份(不自己做 OAuth) | +| **第三方应用** | OAuth2 客户端:`/oauth/authorize` 跳转登录 → 拿 `code` → `/oauth/token` 换 token → 调资源服务器或 `/oauth/introspect` 校验 | + + +**与 MaxKey 的关系**:仅作为协议对齐参考(端点路径、声明字段、grant 集合),运行时完全不连 MaxKey。 + +--- + +## 2. 设计决策 + +- **自包含 IdP**:自己签发 token、校验密码、维护客户端注册表,不依赖任何外部 IdP。 +- **零新增 crate**:HS256 JWT 的签名 / 验签用手写 `HMAC-SHA256`(复用已有 `sha2`)+ 手写 `base64url` 实现,**不引入任何新依赖**,契合 vendor 离线约束。 +- **无共享存储验签**:token 自带签名,`iat/exp/jti` 内嵌,任意 worker 本地验签即可,**不回读用户文件 / 不查库**。 +- **HS256 对称签名**:签名密钥来自环境变量 `OAUTH_SIGNING_SECRET`。第三方**不应**持有该密钥,统一走 `/oauth/introspect` 自省(标准、无需密钥)。 +- **IAP 防伪造**:复用 LLM 槽位「网关断言身份头、覆盖客户端伪造同名头」模型——后端只信网关注入的 `X-Auth-*`。 + +--- + +## 3. 端点(对齐 MaxKey discovery 基准) + +| 方法 | 路径 | 说明 | Guard | +| --- | --- | --- | --- | +| GET | `/oauth/authorize` | 授权端点(授权码流程入口,未登录则跳登录页) | Public | +| POST | `/oauth/token` | 换 token:`authorization_code` / `refresh_token` / `client_credentials` / `password` | Public(client 鉴权) | +| GET | `/oauth/userinfo` | 返回当前 Bearer token 对应用户声明 | Public(Bearer) | +| POST | `/oauth/introspect` | RFC 7662 token 自省(第三方校验用,需 client 鉴权) | Public(client 鉴权) | +| GET | `/.well-known/openid-configuration` | OIDC discovery | Public | +| GET | `/oauth/jwks` | 公钥(**HS256 无公钥**,返回 404 + 说明) | Public | +| GET/POST | `/login` | SSO 登录页 + 表单提交(建立 `sso_sid` 会话 cookie) | Public | +| POST | `/oauth/logout` | 注销 SSO 会话(清 cookie + 清共享内存) | Public | + +> 所有协议端点走 content 阶段 `sso_api`(与管理/API server 同 location 收敛); +> IAP 门禁走 access 阶段 `sso_iap`,与协议端点**互不干扰**。 + +--- + +## 4. Token 模型(零新增依赖、无共享存储验签) + +全部 token 均做成 **HS256 签名的 JWT**,由服务器密钥 `OAUTH_SIGNING_SECRET` 签名。 + +| token | 声明 `token_type` | 有效期(常量) | 备注 | +| --- | --- | --- | --- | +| access_token | `access` | `OAUTH_ACCESS_TTL` = 3600s | 资源服务器 / introspect 校验;`aud=client_id` | +| refresh_token | `refresh` | `OAUTH_REFRESH_TTL` = 30d | 续期用,含 `jti`;`jwt_verify` 校验 `typ=refresh` | +| id_token | (无 typ,OIDC) | `OAUTH_ID_TOKEN_TTL` = 3600s | 仅 scope 含 `openid` 时随 token 响应一并返回;含 `nonce` | +| authorization code | (**非 JWT**,随机 id) | `OAUTH_CODE_TTL` = 60s | 写入共享内存 `oac:` 前缀(值是该码的授权上下文 JSON),**`take_oauth_code` 取一次即删** | + +**JWT 头部**:`{"alg":"HS256","typ":"JWT"}`。 +**access_token claims 示例**: +```json +{ + "iss": "http://localhost:18098", + "sub": "alice", + "aud": "spa-demo", + "client_id": "spa-demo", + "preferred_username": "爱丽丝", + "email": "alice@yourdomain.com", + "department": "研发部", + "groups": ["rd", "eng"], + "scope": "openid profile email", + "token_type": "access", + "iat": 1768000000, + "exp": 1768003600, + "jti": "a1b2...16hex" +} +``` + +**第三方本地验证升级路径(v2)**:引入 `rsa`/`pkcs8` + 发布 `/oauth/jwks`,第三方即可本地验签、无需持有密钥。当前 v1 走 introspect。 + +--- + +## 5. 客户端模型(`source/data/oauth_clients.json`) + +顶层是 `OAuthClient` 数组(与 `users.json` / `domains.json` 同构:文件是唯一真源,启动时全量装载进共享内存 `ocl:` 前缀,热路径只读内存)。 + +```json +[ + { + "client_id": "grafana", + "client_secret": "cs_grafana_demo_secret_0000000000000000", + "name": "Grafana(演示机密客户端)", + "redirect_uris": ["https://grafana.yourdomain.com/login/generic_oauth"], + "grant_types": ["authorization_code", "refresh_token"], + "scopes": ["openid", "profile", "email"], + "confidential": true, + "created_at": 1768000000 + }, + { + "client_id": "spa-demo", + "client_secret": "", + "name": "单页应用(演示公开客户端,走 PKCE)", + "redirect_uris": ["https://app.yourdomain.com/callback"], + "grant_types": ["authorization_code", "refresh_token"], + "scopes": ["openid", "profile", "email"], + "confidential": false, + "created_at": 1768000000 + }, + { + "client_id": "machine", + "client_secret": "cs_machine_demo_secret_0000000000000000", + "name": "机器对机器(演示 client_credentials / password)", + "redirect_uris": [], + "grant_types": ["authorization_code", "refresh_token", "client_credentials", "password"], + "scopes": ["openid", "profile", "email"], + "confidential": true, + "created_at": 1768000000 + } +] +``` + +字段语义: +- `confidential`:`true` 必须带 `client_secret`(`client_secret_basic` / `client_secret_post`);`false` 为公开客户端,授权码流程**强制 PKCE**。 +- `grant_types`:实际允许的 grant 白名单(`token` 端点会校验 `allows_grant`)。 +- `redirect_uris`:授权码回跳白名单(`authorize`/`token` 均校验)。 +- `scopes`:该客户端被允许申请的 scope 集合(`allows_scope`)。 + +**管理**:本期为**静态 JSON + 手动编辑**,修改后**重启 nginx** 即由 `oauth_clients::reload_shm()` 重新装载(在 `state_zone_init` 阶段调用)。管理台 CRUD API(`/api/admin/oauth-clients/*`)为后续增强项,见 §11。 + +--- + +## 6. 用户模型(`source/data/users.json` 新增身份字段) + +在既有用户结构基础上,`User` 新增三个 `#[serde(default)]` 字段,支撑 token 声明与 IAP 注入: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `email` | string | 用户邮箱,写入 `email` 声明 | +| `department` | string | 部门,写入 `department` 声明 | +| `groups` | **string 数组**(如 `["rd","eng"]`) | 用户组,写入 `groups` 声明 | + +> ⚠️ `groups` 必须是 JSON 数组。若误写成字符串(`"[rd,eng]"`),`serde` 反序列化 +> `Vec` 会整表失败 → `users.json` 被当作损坏、读成空表 → **登录一律 +> 「账号或密码错误」**。这类错误不会在启动时报错(`store` 读失败回落 default)。 + +`User::oauth_claims(issuer, now)` 负责把上述字段拼成标准声明。密码仍沿用既有 `salt + sha256(1000 轮)` 哈希,登录走 `/login` 与 `password` grant 共用 `util::verify_password`。 + +--- + +## 7. 授权码流程(浏览器 SSO + PKCE) + +``` +1. 第三方 app 跳转 https://sso/oauth/authorize? + response_type=code&client_id=spa-demo + &redirect_uri=https://app.yourdomain.com/callback + &scope=openid+profile+email&state=xyz + &code_challenge=&code_challenge_method=S256 +2. authorize 端点检查 `sso_sid` 会话 cookie: + - 无会话 → 302 → /login?redirect=<原始请求 URL> + - 有会话 → 生成 code(随机 id,60s 内有效;共享内存里存 PKCE 挑战 + + client_id + redirect_uri + scope + nonce 上下文) + → 302 → redirect_uri?code=...&state=xyz +3. app 后端 POST /oauth/token + grant_type=authorization_code&code=...&code_verifier=...&redirect_uri=...&client_id=spa-demo + (公开客户端不带 client_secret;机密客户端用 Basic 或表单带 secret) +4. token 端点验 code(take_oauth_code 单次失效)+ 验 PKCE + 校验 client/redirect + → 返回 { access_token, refresh_token, id_token, expires_in, token_type:"Bearer" } +5. app 带 Authorization: Bearer 调资源服务器(过本服务的后端) + 或调 /oauth/introspect 自省 +``` + +**IAP 门禁(后端被本服务反向代理时)**: +``` +客户端请求 受保护域名 → sso_iap access 阶段 IAPHandler: + - 取 Authorization: Bearer 或 sso_sid 会话 cookie + - Bearer:本地 jwt_verify → 验签 + exp + - Cookie:取 sso: 共享内存会话 → 平铺身份 → 现场重签一个 access_token(aud=sso-gateway) + - 通过 → 设置 $auth_user/$auth_email/$auth_groups/$auth_sub/$auth_token + → proxy_set_header X-Auth-* 注入上游 + - 未通过且浏览器 → 返回 401 + WWW-Authenticate: Bearer realm="sso" + → nginx error_page 401 = @oauth_login → 302 /login?redirect=<原始 URL> + - API 客户端 → 直接 401 + WWW-Authenticate +``` + +> IAP 注入的 `$auth_sub` 与 `$auth_user` 均为用户标识(username);`$auth_token` 为网关重签的 access_token(Cookie 路径)或原始 Bearer(Bearer 路径)。 + +--- + +## 8. 其它 grant + +- **refresh_token**:`refresh_token`(验 `typ=refresh`)+ client 鉴权 → 重新签发整套 token。 +- **client_credentials**:仅 `confidential` 且 `allows_grant("client_credentials")` 的客户端可用;`sub=client_id`、无 `groups`;返回的 access_token `aud=client_id`。 +- **password**:client 允许 `password` + 校验资源所有者账号密码 → 签发标准 token 套件。 + +客户端鉴权(`authenticate_client`):支持 `Authorization: Basic ` 与表单/JSON 的 `client_id`+`client_secret`;公开客户端仅校验 `client_id` 存在。 + +--- + +## 9. nginx 配置(`conf/nginx.conf`) + +新增两个 server(与既有管理/LLM/转发 server 同端口 18098 / 独立 18099): + +**IdP server(承载协议端点,明文便于本地启动)** +```nginx +server { + listen 18098; + server_name sso.yourdomain.com; + location /oauth/ { sso_api on; } # 协议端点 + location /.well-known/ { sso_api on; } # discovery + location = /login { sso_api on; } # SSO 登录页 +} +``` + +**IAP 受保护代理示例 server** +```nginx +server { + listen 18099; + server_name ~^(?.+)\.app\.yourdomain\.com$; + location / { + sso_iap on; # access 阶段门禁 + 设置 $auth_* + proxy_pass http://127.0.0.1:8080; # 后端地址写死(本层不做动态上游) + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + # ---- IAP 身份注入:网关断言覆盖客户端伪造同名头 ---- + proxy_set_header X-Auth-User $auth_user; + proxy_set_header X-Auth-Email $auth_email; + proxy_set_header X-Auth-Groups $auth_groups; + proxy_set_header X-Auth-Sub $auth_sub; + proxy_set_header X-Auth-Token $auth_token; + error_page 401 = @oauth_login; + } + # 注意:named location 不能带 `=` 修饰符 + location @oauth_login { + return 302 "https://sso.yourdomain.com/login?redirect=$scheme://$host$request_uri"; + } +} +``` + +> ⚠️ **后端地址不做动态解析**。剥离前的网关有 `$proxy_backend_addr` 这类变量(按域名查表 + `resolver`), +> 本层已删除:sso 只管身份,`proxy_pass` 由 nginx 配置写死或由运维按环境生成。 + +> ⚠️ **`location @name` 不能写成 `location = @name`**。带 `=` 时 nginx 会把它注册成 +> 「精确匹配普通 location」而 `clcf->named` 仍为 0,于是 `error_page 401 = @oauth_login` +> 的内部跳转在 `named_locations[]` 里找不到该 location → 500。`return` 指令来自 +> rewrite 模块,自建 nginx 时**不能** `--without-http_rewrite_module`。 + +> 把任意既有业务接入统一认证:仅在其 location 加 `sso_iap on;` + 这组 `proxy_set_header X-Auth-*`,后端即收到标准化身份头,**后端零改造**。 + +--- + +## 10. 共享内存与配置常量 + +| 前缀 / 常量 | 用途 | +| --- | --- | +| `sso:` | SSO 会话(`put/get/remove_oauth_session`),payload 平铺 `\n\n\n\n`(分隔符 `\n`,见下方规则) | +| `oac:` | 授权码(`put/take_oauth_code`,单次失效) | +| `ocl:` | OAuth 客户端注册表(`reload_shm` 全量装载,热路径只读) | +| `OAUTH_SIGNING_SECRET`(env `OAUTH_SIGNING_SECRET`) | HS256 签名密钥(**未设置时进程内随机生成**,多 worker 一致但重启即变,生产必须显式设置) | +| `OAUTH_ISSUER`(env `OAUTH_ISSUER`,默认 `http://localhost:18098`) | `iss` 与 discovery 的 issuer | +| `OAUTH_SESSION_COOKIE = "sso_sid"` | SSO 会话 cookie 名 | +| TTL 常量 | `OAUTH_SESSION_TTL=8h` / `OAUTH_CODE_TTL=60` / `OAUTH_ACCESS_TTL=3600` / `OAUTH_REFRESH_TTL=30d` / `OAUTH_ID_TOKEN_TTL=3600` | +| `OAUTH_SCOPES_SUPPORTED` | `["openid","profile","email","address","phone"]` | +| `OAUTH_CODE_CHALLENGE_METHODS` | `["S256","plain"]` | + +### 10.1 共享内存 value 的两条硬规则 + +1. **payload 里不能出现 `VAL_SEP`(`0x1f`)**。共享内存 value 的格式是 + ` \x1f `,`state::split_value` 按**最后一个** `0x1f` 切分 + (`rposition`,因为到期时刻恒在末尾)。若 payload 内含 `0x1f`,早期用 `position` + (第一个分隔符)实现会把 payload 腰斩、把残段当 expiry 解析而失败—— + 表现为**刚写入的会话立刻查不到**(`authorize` 永远判定「未登录」)。 + 故 `sso:` 的身份字段串用 `\n` 分隔,`ukey:` 的身份 payload 同样用 `\n`。 +2. **变量名与写入槽位要分别登记**。`$auth_*` 这类「由模块写、nginx 读」的变量必须 + 两步都做: + - `ngx_http_add_variable()` —— 把名字登记进 `cmcf->variables_keys` **并挂一个 + `get_handler`**;否则 `ngx_http_variables_init_vars` 在启动时报 + `unknown "auth_user" variable`(EMERG,直接起不来)。 + - `ngx_http_get_variable_index()` —— 拿到 `r->variables[]` 的写入下标。 + + 且**不能**给这类变量加 `NGX_HTTP_VAR_NOCACHEABLE`:`ngx_http_get_flushed_variable` + 对 NOCACHEABLE 变量每次读取都会清掉 `valid` 并回调 `get_handler`, + 而 handler 拿不到注入值 → 变量读出来是空的。`set_auth_vars` 里写入的 + `no_cacheable` 也必须为 0,与变量定义保持一致。 + (对比:`$proxy_backend_addr` / `$llm_*` 是「读时计算」,所以它们**要** NOCACHEABLE + 且 handler 里现算;两种模式不可混用。) + +--- + +## 11. 代码改动清单(已落地) + +| 文件 | 改动 | +| --- | --- | +| `source/rust/src/oauth.rs` | **新增**:OAuth2 AS 全部逻辑(client/code/token 模型、HS256 JWT 签名/验签、PKCE、端点 handler、IAP 身份解析) | +| `source/rust/src/oauth_clients.rs` | **新增**:客户端注册表模块(`reload_shm` / `get` / `all` / `upsert` / `delete` / `view`) | +| `source/rust/src/api.rs` | `route()` 增加 `/oauth/authorize`、`/oauth/token`、`/oauth/userinfo`、`/oauth/introspect`、`.well-known`、`/oauth/jwks`、`/login`、`/oauth/logout`,转发到 `oauth::*` | +| `source/rust/src/lib.rs` | 新增 `sso_iap` 指令 + `IapHandler`(access 阶段门禁 + 写 `$auth_*` 变量);`AUTH_VAR_INDEX[5]` + `AUTH_VAR_NAMES`;`register_auth_vars()`(`add_variable` 挂 `auth_var_get` + `get_variable_index`)在 preconfiguration 注册;`state_zone_init` 调 `oauth_clients::reload_shm()` | +| `source/rust/src/config.rs` | 新增 OAuth 常量区(`KEY_OAUTH_*` 前缀、TTL、cookie、env 名、scopes、challenge 方法) | +| `source/rust/src/models.rs` | `User` 增 `email`/`department`/`groups` + `oauth_claims()`;新增 `OAuthClient` + `OAuthClientTable`(`allows_scope/allows_redirect/allows_grant`) | +| `source/rust/src/state.rs` | 新增 `oauth_session` / `oauth_code` / `oauth_client` 共享内存封装;`split_value` 改用 `rposition` | +| `source/rust/src/store.rs` | 新增 `oauth_clients_path` / `read/write/update_oauth_clients` | +| `source/rust/src/util.rs` | 新增 `url_encode`/`html_escape`;`HEX` 常量提升为模块级 | +| `conf/nginx.conf` | 新增 IdP server(18098)+ IAP 代理 server(18099) | +| `source/conf/nginx.test.conf` | **新增**:本地最小验证配置(IdP 18098 + IAP 18099 + 回显后端 18097) | +| `tests/oauth2-e2e.sh` | **新增**:14 项端到端断言(客户端密钥运行时从种子读取,不硬编码) | +| `scripts/run-local-e2e.sh` | **新增**:macOS 本机 nginx + 模块一键起停并跑 e2e | +| `source/data/users.json` | 种子用户补充 `email`/`department`/`groups`(数组) | +| `source/data/oauth_clients.json`(及 `source/data-seed/`) | 新增 OAuth 客户端注册表(grafana / spa-demo / machine) | +| `rust/vendor/ngx-rust/nginx-sys/build/` | **补回**:`main.rs` + `wrapper.h`(官方 0.5.0 crate 的 bindgen 构建脚本,原被 `.gitignore` 的 `build/` 规则吞掉) | +| `.gitignore` | 加 `!rust/vendor/ngx-rust/nginx-sys/build/` 例外,并放行 `source/data/oauth_clients.json` | + +--- + +## 12. 构建与验证 + +### 12.1 为什么本机可以直编(不必进容器) + +nginx 动态模块的本质约束是:模块 `.dylib`/`.so` 必须针对**同一份 nginx 源码 + +相同 configure 参数**的 nginx 二进制编译加载(ngx-rust 的 `nginx-sys` 用 bindgen +读 `NGINX_SOURCE_DIR` / `NGINX_BUILD_DIR` 生成 ABI 绑定)。所以本机自编一份 +nginx 1.30.4 即可,无需 Docker: + +```bash +# ① 依赖:PCRE2(rewrite 模块必需)+ nginx 源码 +curl -fsSL https://nginx.org/download/nginx-1.30.4.tar.gz -o nginx.tar.gz && tar xzf nginx.tar.gz +curl -fsSL https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.44/pcre2-10.44.tar.gz -o pcre2.tar.gz && tar xzf pcre2.tar.gz + +# ② 编 nginx(须含 rewrite 模块,`return` 指令来自它) +cd nginx-1.30.4 && ./configure --prefix=/tmp/sso-build/nginx \ + --with-pcre=/tmp/sso-build/src/pcre2-10.44 --with-http_realip_module \ + --without-http_gzip_module --without-http_ssi_module --without-http_userid_module \ + --without-http_autoindex_module --without-http_geo_module \ + --without-http_split_clients_module --without-http_referer_module \ + --without-http_uwsgi_module --without-http_scgi_module --without-http_grpc_module \ + && make -j"$(sysctl -n hw.ncpu)" +# 建 prefix 临时目录(没跑 make install 时 nginx 起不来) +mkdir -p /tmp/sso-build/nginx/{client_body_temp,proxy_temp,fastcgi_temp,uwsgi_temp,scgi_temp,logs,conf} + +# ③ 编 Rust 模块(输出 source/rust/target/release/libsso_gateway.dylib) +cd source/rust +export LIBCLANG_PATH=/Library/Developer/CommandLineTools/usr/lib +export NGINX_SOURCE_DIR=/tmp/sso-build/src/nginx-1.30.4 +export NGINX_BUILD_DIR=/tmp/sso-build/src/nginx-1.30.4/objs +cargo build --release +``` + +> `--with-pcre=<绝对路径>` 必须与后面编模块时的源码树**同一个路径**:ngx-rust 的 +> `build/main.rs` 会从 `objs/Makefile` 抽出编译参数去预处理 `ngx_core.h`, +> 其中带 `-I /src/`。把源码树挪位置而不重新 `./configure && make`, +> 模块编译会报 `fatal error: 'pcre2.h' file not found`。 + +### 12.2 一键跑端到端 + +```bash +# 起 nginx(IdP 18098 / IAP 18099 / IAP→demo 18095 / 回显后端 18097) +# + 起 demo-system(18096)→ 跑三套 e2e → 全部停掉 +bash scripts/run-local-e2e.sh + +# 单独跑某一套(对已运行的网关) +bash tests/oauth2-e2e.sh http://127.0.0.1:18098 http://127.0.0.1:18099 +bash tests/oauth2-maxkey-e2e.sh http://127.0.0.1:18098 http://127.0.0.1:18096 http://127.0.0.1:18095 +bash tests/admin-oauth-clients-e2e.sh http://127.0.0.1:18098 +``` + +脚本自动完成:`scripts/seed-data.sh` 物化 `source/data/`(生成 admin/alice 口令散列)、 +生成 macOS 本机配置(替换 `load_module` / `mime.types` / `sso_data_dir` / `pid` / +`error_log`,注释掉 TLS include,regex `server_name` 降级为 `_`)、注入 +`OAUTH_SIGNING_SECRET` + `OAUTH_ISSUER`(可选 `OAUTH_COOKIE_DOMAIN`)、 +拉起 demo-system 并等 `/healthz`、等 IdP discovery 就绪、跑三套断言、汇总退出码。 + +> 配置改写用 **python 而非 sed**:BSD sed 对 `/re/{s###;}` 这类块命令 + `#` 分隔符 +> 解析很脆(实测报 `bad flag in substitute command: '}'`),逐行替换更确定。 + +### 12.3 测试覆盖(基线 14 项 + 互通/接入 24 项 + 管理接口 31 项) + +**基线(`tests/oauth2-e2e.sh`,14 项)**:discovery 元数据 / 登录下发会话 Cookie / +授权码 + PKCE(公开客户端) / 授权码(机密客户端 Basic 鉴权) / userinfo / +introspect / client_credentials / password / refresh_token / IAP 无身份拦截 +(302 跳登录) / IAP Bearer 注入 / IAP Cookie 注入 / IAP 伪造同名头被覆盖。 + +**互通/接入(`tests/oauth2-maxkey-e2e.sh`,24 项)**: +- A. MaxKey 别名与传参:`/oauth/v20/authorize`、`/maxkey/...`、`/sign/authz/...`、 + `/oauth2.0/authorize` 均命中;token 端点别名命中;表单传 `client_id/secret` + 换发成功(无 Basic);`/oauth/v20/me?access_token=` 返回 MaxKey 扁平字段且 + **账号语义正确**;`/oauth2.0/profile` 命中;标准端点回归。 +- B. demo-system 自建客户端:首页登录入口、`/login` 跳 MaxKey 端点、state 防 CSRF、 + 授权码回调换发、建本地会话、`/api/me` 取到身份、非法 state 被拒。 +- C. IAP 零改造接入:无身份拦截、带会话放行、网关注入 `X-Auth-User`、 + 业务系统按注入头识别身份、**客户端伪造同名头被覆盖**。 + +**管理接口(`tests/admin-oauth-clients-e2e.sh`,31 项)**:未登录一律 401 / +管理员登录 / 列表含种子客户端与 issuer、MaxKey 端点别名 / 新建机密客户端生成 +`cs_` 密钥 / **热生效**(新建完立刻能授权,专盯「写穿共享内存」)/ 未知 client_id +返回 `invalid_client` / 未注册回调地址返回 `invalid_redirect_uri` / 更新时密钥 +留空保留原值 / 参数校验(非 http(s)、带 `#fragment`、未知 grant、授权码模式缺回调) +且**校验失败不污染注册表** / 公开客户端不生成密钥并自动剔除 +`client_credentials`·`password` / 重置密钥(新密钥不同、公开客户端拒绝、不存在报错)/ +删除后授权请求立即失效。 + +> 客户端密钥**不在测试脚本里硬编码**:运行时从 `$DATA_DIR/oauth_clients.json` 读取, +> 避免密钥散落。 + +### 12.4 跑法 + +本仓库**不提供容器编排**:动态模块必须与 nginx 二进制同源编译,容器里那套 +「宿主机编模块、镜像里换 nginx」的路径比直接用本机跑更绕。验证统一走 + +```bash +bash scripts/run-local-e2e.sh # 起服务 + 三套 e2e + 关服务 +bash scripts/run-local-e2e.sh --keep # 保留进程手工排查 +``` + +生产部署见 `source/conf/nginx.conf` + `source/conf/tls/README.md`。 + +--- + +## 13. 已知限制 / 后续 + +- **客户端热管理已落地**:管理台「OAuth 应用」tab + `/api/admin/oauth-clients/{save,rotate,delete}`,保存即生效(写穿共享内存)。文件仍是唯一真源,只是在每次写入时同步,不再需要改文件重启。 +- **HS256 对称**:第三方无法本地验签,统一走 introspect;v2 升级 RS256 + `/oauth/jwks`。 +- **会话为内存态**:`sso:` 存于共享内存,worker 重启即失效(与现有转发映射一致,属预期)。 +- **生产 TLS**:IdP/IAP 示例为明文,生产需在前面套 TLS 或收进内网(参见 `conf/tls/` 机制)。 + +--- + +## 14. 首次编译 / 联调暴露并修复的缺陷 + +以下 6 个问题**都是在第一次真正编译 + 端到端跑通时才暴露**的(此前仅静态审阅, +全部漏过)。记录在此,避免重复踩: + +| # | 症状 | 根因 | 修复 | +| --- | --- | --- | --- | +| 1 | 启动即 EMERG `unknown "auth_user" variable` | 只调了 `ngx_http_get_variable_index`(给写入槽位),没调 `ngx_http_add_variable`(登记名字+handler);`ngx_http_variables_init_vars` 找不到 handler 就报 EMERG | `register_auth_vars` 改为「先 `add_variable` 挂 `auth_var_get`,再取 index」 | +| 2 | IAP 变量注入后读到空值 | 给变量标了 `NGX_HTTP_VAR_NOCACHEABLE` → `ngx_http_get_flushed_variable` 每次读取都清缓存并回调 handler,而 handler 无从拿到注入值 | 变量不加 NOCACHEABLE,且 `set_auth_vars` 写 `no_cacheable=0` | +| 3 | `authorize` 永远判定「未登录」,登录后仍 302 回登录页 | `sso_payload` 用 `0x1f` 分隔字段,与共享内存 value 的 `payload/expiry` 分隔符撞车;`split_value` 用 `position`(首个)切分 → payload 腰斩、expiry 解析失败 → `get` 返回 None | `split_value` 改 `rposition`;`sso_payload` 改用 `\n` | +| 4 | 登录一律「账号或密码错误」 | 种子 `users.json` 的 `groups` 被写成字符串 `"[rd,eng]"`,`Vec` 反序列化整表失败 → 用户表读成空(静默回落 default) | 种子改为 JSON 数组 `["rd","eng"]`,并加校验脚本 | +| 5 | `error_page 401 = @oauth_login` 跳不过去 | `location = @oauth_login` 的 `=` 使其成为「精确匹配普通 location」,`clcf->named=0`,`named_locations[]` 里查不到 | 改为 `location @oauth_login` | +| 6 | 全新 checkout 编不过:`vendor/.../nginx-sys/build/main.rs` 不存在 | 根 `.gitignore` 的 `build/` 规则把 vendored 依赖的 bindgen 构建脚本一起吞了(本地磁盘有、git 里没有) | 补回官方 crate 的 `build/`,`.gitignore` 加例外 | + +--- + +## 15. MaxKey OAuth2 互通 + +目标:**照抄 MaxKey 文档写出来的应用/客户端,不改一行代码就能对接本 IdP**; +反之,本 IdP 的标准端点也仍是标准 OIDC。 + +### 15.1 MaxKey 自己的端点命名并不统一 + +MaxKey 各版本/各部署的端点路径彼此不同,社区教程里的写法也跟着分叉: + +| 来源 | 授权 | 换发 | 用户信息 | +| --- | --- | --- | --- | +| MaxKey 主线 | `/oauth/v20/authorize` | `/oauth/v20/token` | `/oauth/v20/me` | +| 部分部署/衍生文档 | `/oauth2.0/authorize` | `/oauth2.0/accessToken` | `/oauth2.0/profile` | +| 带 context-path | `/maxkey/oauth/v20/authorize` | `/sign/authz/oauth/v20/token` | `/api/oauth/v20/me` | +| 新版(标准 OIDC) | `/oauth/authorize` | `/oauth/token` | `/oauth/userinfo` | + +前两族在 §15.2 映射为别名;第三族的 context-path 在 §15.3 归一化。 + +### 15.2 端点别名映射 + +| MaxKey 命名 | 映射到 | 与标准端的差异 | +| --- | --- | --- | +| `GET /oauth/v20/authorize`
`GET /oauth2.0/authorize` | `authorize` | 无(纯别名) | +| `GET\|POST /oauth/v20/token`
`GET\|POST /oauth2.0/accessToken` | `token_v20` | **响应不套 `{code,msg,data}` 信封**,直接返回 `{"access_token":…}` | +| `GET\|POST /oauth/v20/me`
`GET\|POST /oauth2.0/profile` | `userinfo_v20` | 令牌可用 `access_token` 查询/表单参数;返回 **MaxKey 扁平字段** | +| `GET /oauth/v20/logout` | `logout` | 无 | + +两个「差异」都是必需的,不是顺手加的: + +1. **响应形状**。MaxKey 的 `/oauth/v20/token` 返回裸对象,客户端按顶层键取 + `access_token`;标准端点了带信封(`{code,msg,data}`)。若别名也带信封, + 照抄 MaxKey 文档的客户端会解析失败(实测表现:拿不到令牌 → 后续全挂)。 + 故别名走 `send_token_body(r, body, bare=true)`,标准端保持 `bare=false`。 +2. **令牌位置与客户端鉴权**。MaxKey 把 `access_token` 放查询/表单参数(不是 + Bearer 头),把 `client_id`/`client_secret` 放表单(不是 Basic)。 + `access_token_of` 与 `authenticate_client` 两种都收,于是同一套实现同时服务两类客户端。 + +### 15.3 context-path 归一化 + +应用的配置项常常是照抄文档的**完整 URL**,把 context-path 一起写进端点地址 +(`/maxkey/oauth/v20/token`、`/sign/authz/oauth/v20/authorize`、`/api/oauth/v20/me`)。 +为此在路由 miss 之后剥一层已知前缀再试一次: + +```rust +const MAXKEY_CONTEXT_PREFIXES: [&str; 5] = ["/maxkey", "/sign/authz", "/sign", "/authz", "/api"]; +``` + +只在**精确路由 miss 之后**调用,所以不会遮蔽真实存在的 `/api/v1/*`、`/api/admin/*`。 + +### 15.4 配套的 nginx 侧要求 + +归一化只在请求能到达模块时才生效。原先 IdP server 是 + +```nginx +location /oauth/ { sso_api on; } +location /.well-known/ { sso_api on; } +location = /login { sso_api on; } +``` + +`/maxkey/oauth/v20/authorize`、`/oauth2.0/authorize` **不匹配 `/oauth/` 前缀**, +直接吃 nginx 的 HTML 404(模组里的归一化根本没机会跑)。故 IdP server 改为整站交给模块: + +```nginx +location / { sso_api on; } +``` + +> 教训:**协议端点的 location 不要逐条枚举**——每加一个别名都要改 nginx 配置 + reload, +> 且漏掉时表现为「nginx 404」而不是「接口不存在」的 JSON 404,容易误判为模块 bug。 + +### 15.5 声明语义(互通里最隐蔽的一条) + +`preferred_username` 一度被写成**显示名**(`爱丽丝`),而 `sub` 是登录账号(`alice`)。 +字段名齐全、数据也都在,但第三方系统(Grafana 等)普遍用 `preferred_username` +做**账号绑定与查找**,拿到显示名就匹配不上本地账号。 + +修正为: + +| 声明 | 含义 | +| --- | --- | +| `sub` | 登录账号(`alice`) | +| `preferred_username` | 登录账号,便于第三方直接绑定 | +| `name` | 显示名(`爱丽丝`) | +| `username` / `userid`(仅 MaxKey `/me`) | 登录账号 | +| `realname`(仅 MaxKey `/me`) | 显示名 | + +`models.rs::User::oauth_claims` 原本就是正确语义,但令牌签发走的是 +`oauth.rs::mint_access_token`,两条路径不一致才漏出去 —— 已统一。 + +### 15.6 代码落点 + +| 文件 | 改动 | +| --- | --- | +| `source/rust/src/api.rs` | 别名路由表 + `MAXKEY_CONTEXT_PREFIXES` / `strip_maxkey_ctx`,`dispatch` 在 miss 后归一化重试 | +| `source/rust/src/oauth.rs` | `access_token_of`(Bearer → `access_token` 参数回退);`userinfo_v20`(MaxKey 扁平字段);`token_v20` + `send_token_body(bare)`;`mint_access_token` 声明语义修正 | +| `conf/nginx.conf`、`source/conf/nginx.test.conf` | IdP server 整站 `location / { sso_api on; }` | +| `source/data/oauth_clients.json`、`source/data-seed/` | 新增 `demo-system`(机密)、`demo-spa`(公开 + PKCE) | + +--- + +## 16. 把一个业务系统接进来(demo-system,两种模式) + +样例应用在 `examples/demo-system/app.py`(**仅 Python 标准库**,无第三方依赖), +演示同一个业务系统的两种接入姿势。 + +### 16.1 模式 A:应用自己做 OAuth2 客户端(RP) + +``` +浏览器 → /login → IdP /authorize → 用户登录 → 302 redirect_uri?code&state + → 应用 /oauth2/callback:code 换 token → 取 userinfo → 建本地会话 → 首页 +``` + +- `DEMO_STYLE=maxkey`:端点用 `/oauth/v20/*`,`client_id/secret` 走表单,`/me` 用 `access_token` 参数; +- `DEMO_STYLE=standard`:端点用 `/oauth/*`,Basic 鉴权 + Bearer; +- 未配置 `client_secret` 时自动启用 **PKCE(S256)**,按公开客户端走。 + +适合:有自己会话体系、需要拿到令牌代用户调后端 API 的系统。 + +### 16.2 模式 B:前置 IAP,业务系统零改造 + +```nginx +server { + listen 18095; + location / { + sso_iap on; # access 阶段门禁 + proxy_pass http://127.0.0.1:18096; # 业务系统 + proxy_set_header X-Auth-User $auth_user; + proxy_set_header X-Auth-Email $auth_email; + proxy_set_header X-Auth-Groups $auth_groups; + proxy_set_header X-Auth-Sub $auth_sub; + proxy_set_header X-Auth-Token $auth_token; + error_page 401 = @oauth_login_demo; # 未登录 → 跳 IdP 登录并回跳 + } + location @oauth_login_demo { + return 302 "https://sso.yourdomain.com/login?redirect=$scheme://$host$request_uri"; + } +} +``` + +业务系统不写一行 OAuth 代码,只读 `X-Auth-*`(见 `/api/me` 的 `source=iap` 分支)。 +未登录请求在网关就被拦下,**根本不会到达业务系统**;客户端伪造的同名头由网关覆盖。 + +适合:既有系统改造代价大、或后端是异构技术栈的场景。 + +> ⚠️ **模式 B 的前提**:业务系统端口**不可被客户端直达**。它无条件信任 +> `X-Auth-*`,一旦能直连(如样例里同时暴露 18096 供模式 A 演示),就等于把 +> 身份伪造口子敞开。生产上要 `listen 127.0.0.1` / 防火墙白名单 / 只走网关。 +> 本样例的 `DEMO_BIND` 默认即 `127.0.0.1`。 + +### 16.3 环境变量 + +| 变量 | 默认 | 说明 | +| --- | --- | --- | +| `DEMO_PORT` | `18096` | 监听端口 | +| `DEMO_BIND` | `127.0.0.1` | 绑定地址(见上方安全提示) | +| `DEMO_STYLE` | `maxkey` | `maxkey` \| `standard`,决定端点与传参风格 | +| `DEMO_IDP_BASE` | `http://127.0.0.1:18098` | IdP 地址 | +| `DEMO_CLIENT_ID` | `demo-system` | 客户端 ID | +| `DEMO_CLIENT_SECRET` | 空 | 机密客户端密钥;为空则自动用 PKCE | +| `DEMO_REDIRECT_URI` | `http://127.0.0.1:/oauth2/callback` | 须与注册的 `redirect_uris` **逐字符一致** | +| `DEMO_TRUST_IAP` | `1` | 是否信任 `X-Auth-*`(模式 B) | + +端点:`/`(首页)、`/login`、`/oauth2/callback`、`/api/me`、`/api/echo`(回显收到的 +`X-Auth-*`,用于验证注入)、`/healthz`、`/logout`。 + +### 16.4 单独起 + +```bash +python3 examples/demo-system/app.py # 用默认:maxkey + 18096 + 本地 IdP +# 或 +DEMO_STYLE=standard DEMO_CLIENT_ID=demo-spa DEMO_PORT=18096 python3 examples/demo-system/app.py +``` + +一键端到端(含本文件 §12.2)由 `scripts/run-local-e2e.sh` 覆盖。 + +--- + +## 17. 管理台与接入方热管理 + +### 17.1 界面落在哪 + +管理台是**单页静态文件** `www/admin.html`(nginx `location = /admin` 直出), +数据全部通过 `/api/admin/*` 拉取,所以: + +- 加一个功能 = 加一个 tab(section)+ 一段渲染函数 + 接口调用,无需构建工具链; +- 页面里没有内联密钥/口令,刷新即重新拉取,权限只在后端(`Guard::Admin`)。 + +本次新增「**OAuth 应用**」tab(在「账号管理」与「LLM 上游」之间),包含三块: + +| 区块 | 作用 | +| --- | --- | +| 统一认证端点 | 列出 Discovery / 授权 / 令牌 / 用户信息 的标准端点与 MaxKey 别名,各带「复制」 | +| 新建 / 更新接入方 | client_id、名称、机密/公开、密钥、回调地址(一行一个)、授权类型勾选、scope | +| 接入方列表 | 类型徽标、回调地址、授权类型、scope、脱敏密钥 + 复制、重置密钥、编辑、删除 | + +顶部统计卡新增「OAuth 接入方」计数。 + +![管理台 · OAuth 应用](screenshots/admin-oauth-apps.png) + +登录页重做为与管理台同色系的卡片(登录失败时错误条落在卡片内部): + +| 正常 | 口令错误 | +| --- | --- | +| ![登录页](screenshots/sso-login.png) | ![登录失败](screenshots/sso-login-error.png) | + +截图取自本机运行实例(`scripts/run-local-e2e.sh` 起服务后访问 +`http://127.0.0.1:18098/admin`),用系统 Chrome 无头 + CDP 抓取,非设计稿。 + +### 17.2 管理接口 + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| GET | `/api/admin/oauth-clients` | 列表 + `issuer` + `endpoints`(含 MaxKey 别名) | +| POST | `/api/admin/oauth-clients/save` | 新建或更新;`client_secret` 缺省 = 保留原值,新建时自动生成 | +| POST | `/api/admin/oauth-clients/rotate` | 重置密钥,返回新密钥明文(旧密钥立即失效) | +| POST | `/api/admin/oauth-clients/delete` | 删除 | + +列表类字段(`redirect_uris` / `grant_types` / `scopes`)**传字符串**即可:逗号、顿号、 +分号、空格、换行都是分隔符——前端 textarea 一行一个回调地址的自然写法直接可用。 +之所以不传 JSON 数组:`http::params` 解析 JSON body 时只收 String/Number/Bool, +数组会被跳过(见 `source/rust/src/http.rs`)。 + +### 17.3 校验规则(写死在 `oauth_clients::upsert`) + +拒绝而不是静默纠正,避免「配了但不生效」的幽灵配置: + +- `client_id` 非空;授权类型必须在白名单(`authorization_code` / `refresh_token` / + `client_credentials` / `password`)内; +- 用授权码模式时至少一个回调地址; +- 回调地址必须是 `http(s)://` 绝对地址且不带 `#fragment`——它会被原样用于 302, + 白名单里混进 `javascript:` 就等于把授权码送给任意站点; +- **公开客户端不持有密钥**:不生成、改成公开时清掉旧的,并剔除 + `client_credentials` / `password`(这两者都要用密钥证明身份)。 + +### 17.4 热生效与「写穿共享内存」 + +管理台保存后立刻能授权,靠的是把新值写进 `ocl:` 前缀的共享内存。这里有一个 +**曾经踩过的坑**(本次才暴露): + +```rust +// ✗ 错:get() 读的就是共享内存,等于把旧值原样写回 +if let Some(c) = get(&out.client_id) { state::put_oauth_client(&c.client_id, &payload(&c)); } + +// ✓ 对:写本次落盘后的新值 +state::put_oauth_client(&out.client_id, &client_payload(&out)); +``` + +症状是「管理台显示已保存,但拿着 client_id 去授权仍报 `invalid_client`」,而重启 +网关后又一切正常——因为启动时 `reload_shm()` 从文件全量装载。凡是「文件是唯一真源 + +内存是热路径」的结构,写穿时必须写**新值**,不能读回来再写。 + +写失败必须出声(项目硬规矩):`put_oauth_client` / `remove_oauth_client` 返回 +`false` 时打 error 日志并说明「需重载才生效」,不静默吞掉。 + +### 17.5 验证 + +`tests/admin-oauth-clients-e2e.sh`(并入 `scripts/run-local-e2e.sh` 第 3 套, +20 项)覆盖:未登录 401、列表/新建/更新/重置/删除、**新建后立刻可授权** +(热生效,含未知 client_id 与未注册回调的对照断言)、四类参数校验、 +公开客户端无密钥且剔除不可用授权类型。 diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..2ae27d4 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,148 @@ +# 路线图 / 待执行任务 + +> 状态标记:`[ ]` 待开工 · `[~]` 进行中 · `[x]` 已完成 +> 每项都在「为什么 / 做什么 / 验收 / 注意」四段内自洽,可直接开工。 + +--- + +## v1(已完成) + +- [x] 从内部网关项目剥离出独立 SSO 服务(去掉动态域名转发 / LLM 上游代理 / 用量计费) +- [x] 目录重组:`docs/` `source/` `tests/` `scripts/` +- [x] 自包含 IdP:四种 grant + PKCE + discovery + introspect + userinfo +- [x] IAP 身份注入:`X-Auth-*` 五头,客户端伪造同名头被覆盖 +- [x] MaxKey 端点别名与 context-path 归一化 +- [x] 管理台:账号管理 + OAuth 接入方管理 + 接入指南 +- [x] 三套端到端回归(协议基线 14 · 互通/接入 24 · 管理接口 31) + +--- + +## [ ] v2:升级 RS256 签名 + `/oauth/jwks`,让第三方本地验签 + +### 为什么 + +当前 access_token / id_token 用 **HS256(对称密钥)** 签名,密钥即 `OAUTH_SIGNING_SECRET`。 +对称密钥的根本问题是**不能给第三方**——给了就等于把签发能力也给了。所以现状是: + +- 第三方拿到令牌后**无法本地验签**,只能每请求回源 `POST /oauth/introspect`; +- 每个业务系统都要经一次网络往返 + 本服务的可用性依赖,横向扩展时自省成为热点; +- OIDC 生态里的标准库(各类 `jwks` 缓存实现)**用不上**——它们默认 RS256 + JWKS。 + +`GET /oauth/jwks` 与 `/.well-known/jwks.json` 路由**已在 v1 占位**,当前行为是 +「显式 404 + 说明原因」(不返回空 `{"keys":[]}`,避免客户端静默失败)。 + +### 做什么 + +1. **密钥对与轮换模型** + - 配置:`OAUTH_JWK_DIR`(默认 `$data_dir/jwks`)下放 `active.pem` + 可选的历史公钥。 + - 启动时(`state_zone_init`,fork 前)载入私钥;缺私钥则**首次启动自动生成** 2048-bit RSA + (`openssl` 命令行不可用,需纯 Rust 生成——见「注意」)。 + - 支持 `kid`:每把密钥一个稳定 `kid`(如公钥 SHA-256 前 16 位 hex),签发时写进 JWT header。 + - 轮换:把新密钥设为 active,旧私钥移出签名集但**公钥保留在 JWKS**,直到最后一批旧令牌过期 + (≥ `OAUTH_REFRESH_TTL` = 30 天)。 + +2. **签名算法抽象** + - 在 `oauth.rs` 抽出 `mint` / `verify` 的算法分支:`HS256`(兼容旧密钥)| `RS256`(默认)。 + - `jwt_verify` 按 JWT header 的 `alg` 选择验签方式;**必须白名单校验 `alg`**, + 禁止 `none`,禁止拿公钥当 HMAC 密钥(`alg` 混淆攻击)。 + - `alg` 决策走配置(`OAUTH_JWT_ALG`,默认 `RS256`),便于灰度:新旧并行期内 + 用 HS256 签发的存量令牌仍可验签通过。 + +3. **JWKS 端点** + - 输出标准 JWK:`{"keys":[{"kty":"RSA","use":"sig","alg":"RS256","kid":...,"n":...,"e":...}]}`。 + - `n`/`e` 用 **base64url 无填充**(不是标准 base64)。 + - 加 `Cache-Control`(如 `public, max-age=3600`),并保证轮换后客户端能及时刷新。 + - discovery 的 `jwks_uri` 指向 `/.well-known/jwks.json`,`id_token_signing_alg_values_supported` + 改为 `["RS256","HS256"]`。 + +4. **依赖与体积** + - RSA 需要大数运算。优先评估 **手写**(`modpow` + 已有的 `sha2`)还是引入 + `rsa` / `ring` / `num-bigint`——v1 的硬约定是「零新增依赖 / vendor 离线可编译」, + 引入前先确认能否 vendor 进 `source/rust/vendor/`。 + - 若用手写:`rsa` crate 的 PKCS#1 v1.5 + SHA-256 + RSASSA-PKCS1-v1_5 编码是固定长度填充, + 实现量可控;签名的 `DigestInfo` DER 前缀是常量,可直接内联。 + +### 验收 + +- [ ] `GET /.well-known/jwks.json` 返回可用 JWKS,`n`/`e` 为 base64url; +- [ ] 用 JWKS 公钥在**不访问本服务**的前提下,本地验签通过 access_token 与 id_token; +- [ ] `alg` 传 `none` / 传 HS256 但用公钥当密钥 → 一律拒绝; +- [ ] 轮换后:新令牌带新 `kid`,旧令牌仍能验签直到过期; +- [ ] 现有三套 e2e 全绿(HS256 存量路径不回归); +- [ ] 新增一套 e2e:抓 JWKS → 本地验签 → 断言 `iss`/`aud`/`exp`。 + +### 注意 + +- **`iss` 一致性**是历史上最容易踩的坑:`OAUTH_ISSUER` 必须与浏览器实际访问的 host 一致。 + 第三方本地验签会把 `iss` 与 discovery 的 `issuer` 逐字符比对,不一致直接失败。 +- 私钥**绝对不进版本库**(`.gitignore` 放行规则要写对,别把 `jwks/` 加进白名单)。 +- 不要返回空 JWKS:客户端会缓存住「无密钥」状态,问题排查时表现为「一直验签失败、日志无异常」。 + +--- + +## [ ] 用户管理界面:角色 / 部门 / 用户组的可视化维护 + +### 为什么 + +管理台的「账号管理」现在只能建账号、改显示名、重置口令/密钥、删除, +**角色 / 部门 / 用户组三个字段是只读展示**(表格里注明「接口已可用,界面待做」)。 + +但这三个字段恰恰是 IAP 的实际价值所在:后端收到 `X-Auth-Groups` 后要据此做本地鉴权, +若只能改 `users.json` 文件(还不热生效,必须重启),等于「有分组机制但没法运营」。 + +**后端接口在 v1 已经就绪且已测**: + +| 接口 | 作用 | 校验 | +| --- | --- | --- | +| `POST /api/admin/users/role` | 改角色 | 不允许降级最后一个管理员 | +| `POST /api/admin/users/profile` | 改部门 / 用户组 | 均禁控制字符;部门长度 ≤ `DEPARTMENT_MAX_LEN`;组数 ≤ `GROUPS_MAX`,单组名 ≤ `GROUP_NAME_MAX_LEN` | +| `GET /api/admin/users` | 列表 | 已回显 `departments` / `groups` 取值集合(供前端做候选提示) | + +所以本项**纯前端 + 少量交互打磨**,不需要动 Rust。 + +### 做什么 + +1. **账号表行内编辑**(或在侧滑面板里): + - `role`:下拉(`admin` / `user`);目标账号是最后一个管理员时**禁用降级**并给出原因, + 与后端校验保持一致的文案,避免「点了才报错」。 + - `department`:单值,带已有部门的下拉候选 + 允许新建(datalist)。 + - `groups`:多值标签输入(逗号或回车确认、可删),候选来自列表接口回显的集合。 +2. **列表里的筛选与批量** + - 按角色 / 部门 / 用户组筛选; + - 批量加组 / 移组(按行多选 → 一次提交多条 `users/profile`)。 +3. **一致性** + - 提交后立即用返回值刷新本地行数据(不做乐观更新后不回读,避免与「最后一个管理员」这类 + 服务端裁决不一致); + - 错误提示直接透出后端 `msg`(校验文案已经写得很具体,不要再包一层泛化提示)。 +4. **顺手补齐**(同一批改动内,成本很低) + - 统计卡已有「部门 / 用户组」两个数字,点击应能下钻筛选到对应列表。 + +### 验收 + +- [ ] 能给账号改角色、部门、用户组,刷新页面后仍在; +- [ ] 最后一个管理员无法被降级(前端禁用 + 后端兜底都生效); +- [ ] 非法输入(含控制字符 / 超长部门名 / 超组数上限)被拒且提示明确; +- [ ] 按角色 / 部门 / 用户组能筛出正确结果; +- [ ] 改完用户组后,经 IAP 访问后端拿到的 `X-Auth-Groups` 同步变化 + (端到端验证:改组 → 带会话请求 demo 系统的 `/api/echo` → 断言头部); +- [ ] `admin.html` 内无内联 `onclick`,无未清理的全局状态(沿用 v1 的写法约定)。 + +### 注意 + +- 前端**不能**把 `salt` / `pwd_hash` 带到任何请求或日志里:列表接口刻意不返回它们。 +- 用户组名会进 HTTP 头(`X-Auth-Groups`)。后端 `check_groups` 把 + `,` `、` `;` 换行/制表/空格**当分隔符切开**(而不是报错),所以组名里永远不可能含逗号—— + 前端的标签输入要与之一致:用户敲 `a,b` 应得到两个标签「a」「b」,不是一个标签「a,b」; + 否则「界面显示一个组、实际存了两个」会很难查。 +- 改角色 / 部门 / 组都是**写穿共享内存 + 写文件**,写完即生效(无需重启); + 若发现「改完不生效」,先查是不是漏了 `sync_shm` 而不是去重启。 + +--- + +## 备注:不建议做的事 + +- **不要为分组引入树形 / 多级组织架构**。当前模型是「部门(单值)+ 用户组(多值平铺)」, + 足以支撑 IAP 的 header 注入与后端本地鉴权;升级成组织树会同时放大前端、校验与同步三处复杂度, + 且与本服务「身份层」的定位不符。确有需要时,让下游业务系统用 `X-Auth-Groups` 自己做映射。 +- **不要把 OIDC 的 scope / claim 自定义能力做成界面配置**。claim 形状是第三方客户端的契约, + 改动需要双方同步,属于「按需改代码」而不是「运营自助」。 diff --git a/docs/screenshots/admin-oauth-apps.png b/docs/screenshots/admin-oauth-apps.png new file mode 100644 index 0000000..d791d10 Binary files /dev/null and b/docs/screenshots/admin-oauth-apps.png differ diff --git a/docs/screenshots/sso-login-error.png b/docs/screenshots/sso-login-error.png new file mode 100644 index 0000000..df192ff Binary files /dev/null and b/docs/screenshots/sso-login-error.png differ diff --git a/docs/screenshots/sso-login.png b/docs/screenshots/sso-login.png new file mode 100644 index 0000000..d71d009 Binary files /dev/null and b/docs/screenshots/sso-login.png differ diff --git a/scripts/run-local-e2e.sh b/scripts/run-local-e2e.sh new file mode 100644 index 0000000..5435b81 --- /dev/null +++ b/scripts/run-local-e2e.sh @@ -0,0 +1,229 @@ +#!/usr/bin/env bash +# ============================================================================ +# 本地(macOS / Linux)端到端验证:本机编的 nginx 1.30.4 +# + 本机 cargo 编的 SSO 动态模块 +# + tests/demo-system(简单业务系统) +# +# 不依赖 Docker。动态模块必须对着「同一份 nginx 源码 + 相同 configure」的 +# nginx 二进制编译加载,所以本脚本假定: +# - nginx 源码树:${NGINX_SRC}(默认 /tmp/sso-build/src/nginx-1.30.4) +# - nginx 二进制:${NGINX_BIN}(默认 $NGINX_SRC/objs/nginx) +# - Rust 模块 :$ROOT/source/rust/target/release/libsso_gateway.{dylib,so} +# +# 会一并拉起 demo-system(Python 标准库,:18096),用于验证: +# - MaxKey 端点别名 / context-path 归一化 (tests/oauth2-maxkey-e2e.sh) +# - 业务系统自己当 OAuth2 客户端(授权码流) +# - 业务系统经 IAP(:18095)零改造接入 +# +# 用法: +# bash scripts/run-local-e2e.sh # 起服务 + 跑三套 e2e + 关服务 +# bash scripts/run-local-e2e.sh --keep # 测试后保留进程(手动排查) +# NGINX_BIN=/path/to/nginx bash scripts/run-local-e2e.sh +# OAUTH_COOKIE_DOMAIN=.example.com bash scripts/run-local-e2e.sh # 跨子域 SSO +# ============================================================================ +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/.." && pwd)" + +NGINX_SRC="${NGINX_SRC:-/tmp/sso-build/src/nginx-1.30.4}" +NGINX_BIN="${NGINX_BIN:-$NGINX_SRC/objs/nginx}" +MIME_TYPES="${MIME_TYPES:-$NGINX_SRC/conf/mime.types}" +PYTHON="${PYTHON:-python3}" + +# macOS 上 cdylib 产物是 .dylib;Linux 是 .so。优先 .dylib,回退 .so。 +MODULE_DIR="$ROOT/source/rust/target/release" +if [ -f "$MODULE_DIR/libsso_gateway.dylib" ]; then + MODULE="$MODULE_DIR/libsso_gateway.dylib" +else + MODULE="$MODULE_DIR/libsso_gateway.so" +fi + +CONF_SRC="$ROOT/source/conf/nginx.test.conf" +WWW_DIR="$ROOT/source/www" +DEMO_APP="$ROOT/tests/demo-system/app.py" +DATA_DIR="$ROOT/source/data" + +CONF_LOCAL="/tmp/sso-nginx-test.conf" +PID="/tmp/sso-nginx.pid" +ERR_LOG="/tmp/sso-nginx-error.log" +DEMO_LOG="/tmp/sso-demo-app.log" + +HOST_IDP="http://127.0.0.1:18098" +HOST_IAP="http://127.0.0.1:18099" +HOST_DEMO="http://127.0.0.1:18096" +HOST_IAP_DEMO="http://127.0.0.1:18095" +KEEP=0 +for a in "$@"; do [ "$a" = "--keep" ] && KEEP=1; done + +echo "## [precheck]" +# nginx prefix 临时目录(源码 make 出来的二进制没跑 make install,需自建) +NGINX_PREFIX="$(dirname "$(dirname "$NGINX_BIN")")" +mkdir -p "$NGINX_PREFIX"/{client_body_temp,proxy_temp,fastcgi_temp,uwsgi_temp,scgi_temp,logs,conf} +[ -x "$NGINX_BIN" ] || { + echo "!! nginx 二进制缺失:$NGINX_BIN" >&2 + echo " 先编译(源码树内直接 make,不要 --prefix):" >&2 + echo " cd $NGINX_SRC && ./configure --with-pcre=$(dirname "$NGINX_SRC")/pcre2-10.44 \\" >&2 + echo " --with-http_realip_module --without-http_gzip_module --without-http_ssi_module \\" >&2 + echo " --without-http_userid_module --without-http_autoindex_module --without-http_geo_module \\" >&2 + echo " --without-http_split_clients_module --without-http_referer_module \\" >&2 + echo " --without-http_uwsgi_module --without-http_scgi_module --without-http_grpc_module && make" >&2 + exit 1 +} +[ -f "$MODULE" ] || { + echo "!! Rust 模块缺失:$MODULE" >&2 + echo " cd $ROOT/source/rust && NGINX_SOURCE_DIR=$NGINX_SRC NGINX_BUILD_DIR=$NGINX_SRC/objs cargo build --release" >&2 + exit 1 +} +[ -f "$MIME_TYPES" ] || { echo "!! mime.types 缺失:$MIME_TYPES" >&2; exit 1; } +[ -f "$DEMO_APP" ] || { echo "!! demo 系统缺失:$DEMO_APP" >&2; exit 1; } + +# --------------------------------------------------------------------------- +# 种子数据:source/data-seed/ -> source/data/(幂等,不覆盖已有 users.json) +# --------------------------------------------------------------------------- +echo "## [seed] 物化数据目录 $DATA_DIR" +bash "$HERE/seed-data.sh" + +# 生成本机配置(把模板里的绝对路径换成本机路径) +# +# 用 python 而不是 sed:BSD sed 对 `/re/{s###;}` 这类块命令 + `#` 分隔符的解析 +# 很脆(会报 `bad flag in substitute command: '}'`),改一行踩一次坑。这里做确定性的 +# 逐行替换,顺带把正则 server_name 降级为普通 server_name(本机无 PCRE 也能起)。 +echo "## [conf] 生成本机配置 $CONF_LOCAL" +MODULE="$MODULE" MIME_TYPES="$MIME_TYPES" DATA_DIR="$DATA_DIR" ERR_LOG="$ERR_LOG" PID="$PID" \ +CONF_SRC="$CONF_SRC" CONF_LOCAL="$CONF_LOCAL" WWW_DIR="$WWW_DIR" \ +"$PYTHON" - <<'PYEOF' +import os + +src = open(os.environ["CONF_SRC"], encoding="utf-8").read().splitlines() +out = [] +for ln in src: + s = ln.strip() + if s.startswith("load_module "): + out.append("load_module %s;" % os.environ["MODULE"]); continue + if s.startswith("include ") and "mime.types" in s: + out.append(" include %s;" % os.environ["MIME_TYPES"]); continue + # 生产模板里的 TLS 子目录本机不存在,跳过(否则 nginx 起不来) + if s.startswith("include ") and "/conf/tls/" in s: + out.append(" # include conf/tls/*.conf; # 本机验证配置不需要 TLS") + continue + if s.startswith("sso_data_dir"): + out.append(" sso_data_dir %s;" % os.environ["DATA_DIR"]); continue + if s.startswith("error_log"): + out.append("error_log %s info;" % os.environ["ERR_LOG"]); continue + if s.startswith("pid "): + out.append("pid %s;" % os.environ["PID"]); continue + # 管理台静态页:模板里的 /usr/local/nginx/www → 仓库 source/www/ + if "/usr/local/nginx/www/" in ln: + out.append(ln.replace("/usr/local/nginx/www/", os.environ["WWW_DIR"] + "/")); continue + # 正则 server_name(生产用子域捕获)→ 普通 server_name:本机 nginx 无 PCRE + if s.startswith("server_name ~"): + out.append(" server_name _;"); continue + if s == "env ADMIN_INIT_PASSWORD;": + out.append(ln) + out.append("env OAUTH_SIGNING_SECRET;") + out.append("env OAUTH_ISSUER;") + continue + out.append(ln) + +open(os.environ["CONF_LOCAL"], "w", encoding="utf-8").write("\n".join(out) + "\n") +print(" wrote %s (%d lines)" % (os.environ["CONF_LOCAL"], len(out))) +PYEOF + +# 设置 OAuth 环境变量(确定性密钥 + 与访问 host 一致的 issuer) +export OAUTH_SIGNING_SECRET="${OAUTH_SIGNING_SECRET:-local-test-secret-CHANGE-ME}" +export OAUTH_ISSUER="${OAUTH_ISSUER:-http://127.0.0.1:18098}" +# 跨子域 SSO 时才需要;不设 = 不写 Domain(主机级 cookie) +if [ -n "${OAUTH_COOKIE_DOMAIN:-}" ]; then export OAUTH_COOKIE_DOMAIN; fi + +# 关掉可能残留的旧实例 +if [ -f "$PID" ]; then kill "$(cat "$PID")" 2>/dev/null || true; sleep 0.5; fi +pkill -f "demo-system/app.py" 2>/dev/null || true + +# --------------------------------------------------------------------------- +# 启动 demo-system(简单业务系统) +# --------------------------------------------------------------------------- +echo "## [demo] 启动 demo-system(style=maxkey, :18096)" +DEMO_SECRET="$("$PYTHON" - "$DATA_DIR/oauth_clients.json" <<'PY' +import json, sys +for c in json.load(open(sys.argv[1])): + if c["client_id"] == "demo-system": + print(c.get("client_secret", "")); break +PY +)" +: > "$DEMO_LOG" +DEMO_CLIENT_SECRET="$DEMO_SECRET" \ +DEMO_STYLE=maxkey \ +DEMO_PORT=18096 \ +DEMO_IDP_BASE="$HOST_IDP" \ +DEMO_REDIRECT_URI="$HOST_DEMO/oauth2/callback" \ + "$PYTHON" "$DEMO_APP" >> "$DEMO_LOG" 2>&1 & +DEMO_PID=$! +echo " demo pid=$DEMO_PID (日志 $DEMO_LOG)" + +# 后面几处失败分支都要清理 demo 进程,否则脚本退出后残留端口占用 +cleanup_demo() { kill "${DEMO_PID:-0}" 2>/dev/null || true; } + +for i in $(seq 1 25); do + if curl -sf -o /dev/null "$HOST_DEMO/healthz" 2>/dev/null; then echo " demo 就绪"; break; fi + if [ "$i" = "25" ]; then + echo "!! demo-system 未就绪,日志:" >&2; tail -20 "$DEMO_LOG" >&2 + cleanup_demo; exit 1 + fi + sleep 0.4 +done + +echo "## [run] 启动 nginx(daemon off)" +"$NGINX_BIN" -c "$CONF_LOCAL" -g 'daemon off;' -e "$ERR_LOG" & +NGX_PID=$! +sleep 1.5 +if ! kill -0 "$NGX_PID" 2>/dev/null; then + echo "!! nginx 启动失败,错误日志:" >&2; tail -30 "$ERR_LOG" >&2 + cleanup_demo; exit 1 +fi +echo " nginx pid=$NGX_PID" + +echo "## [wait] 等待 IdP discovery 就绪 ..." +for i in $(seq 1 30); do + code="$(curl -s -o /dev/null -w '%{http_code}' "$HOST_IDP/.well-known/openid-configuration" || true)" + if [ "$code" = "200" ]; then echo " IdP 就绪"; break; fi + if [ "$i" = "30" ]; then + echo "!! IdP 未就绪,日志:" >&2; tail -30 "$ERR_LOG" >&2 + kill "$NGX_PID" 2>/dev/null || true; cleanup_demo; exit 1 + fi + sleep 1 +done + +# --------------------------------------------------------------------------- +# 跑测试(三套,各自独立计分) +# --------------------------------------------------------------------------- +RC=0 +set +e +echo +echo "############### [1/3] OAuth2 / OIDC 基线 ###############" +bash "$ROOT/tests/oauth2-e2e.sh" "$HOST_IDP" "$HOST_IAP" "$DATA_DIR" +RC1=$? +echo +echo "############### [2/3] MaxKey 互通 + demo 系统接入 ###############" +bash "$ROOT/tests/oauth2-maxkey-e2e.sh" "$HOST_IDP" "$HOST_DEMO" "$HOST_IAP_DEMO" "$DATA_DIR" +RC2=$? +echo +echo "############### [3/3] 管理接口:OAuth 接入方 ###############" +bash "$ROOT/tests/admin-oauth-clients-e2e.sh" "$HOST_IDP" "$DATA_DIR" +RC3=$? +set -e +[ "$RC1" != "0" ] && RC=1 +[ "$RC2" != "0" ] && RC=1 +[ "$RC3" != "0" ] && RC=1 + +echo +echo "## [summary] 基线 rc=$RC1 互通/接入 rc=$RC2 管理接口 rc=$RC3" +if [ "$KEEP" = "1" ]; then + echo "## [done] 测试完成 (rc=$RC);进程保留,手动排查:" + echo " kill $NGX_PID $DEMO_PID" +else + kill "$NGX_PID" 2>/dev/null || true + kill "$DEMO_PID" 2>/dev/null || true + echo "## [done] nginx + demo-system 已停止 (rc=$RC)" +fi +exit $RC diff --git a/scripts/seed-data.sh b/scripts/seed-data.sh new file mode 100644 index 0000000..85a3cad --- /dev/null +++ b/scripts/seed-data.sh @@ -0,0 +1,152 @@ +#!/usr/bin/env bash +# ============================================================================ +# 物化运行时数据目录:source/data-seed/ -> source/data/ +# +# 为什么需要这一步 +# source/data/ 是**运行时**目录(可写、含真实口令散列),不进版本库; +# source/data-seed/ 是**种子模板**(只放演示客户端与示例账号),进版本库。 +# 本脚本把两者接起来,并顺便把示例里的占位符换成真实值。 +# +# 做的事: +# 1. source/data/oauth_clients.json <- source/data-seed/oauth_clients.json +# 2. source/data/users.json <- 由本脚本生成(admin / alice 两个账号) +# 3. source/data/users.json.example <- 同步一份示例(占位符,不含真实散列) +# +# 幂等:users.json 已存在时**默认不动**(避免覆盖你手工改过的账号),要重建加 --force。 +# +# 用法: +# bash scripts/seed-data.sh # 缺什么补什么 +# bash scripts/seed-data.sh --force # 重建 users.json(会丢已有账号) +# DATA_DIR=/path ADMIN_PASSWORD=xxx bash scripts/seed-data.sh +# +# 口令来源:ADMIN_PASSWORD(默认 123456)、ALICE_PASSWORD(默认 alice123)。 +# 这两个默认值只用于**本机/CI 演示**,生产部署必须覆盖。 +# ============================================================================ +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +ROOT="$(cd "$HERE/.." && pwd)" +SEED_DIR="${SEED_DIR:-$ROOT/source/data-seed}" +DATA_DIR="${DATA_DIR:-$ROOT/source/data}" + +ADMIN_PASSWORD="${ADMIN_PASSWORD:-123456}" +ALICE_PASSWORD="${ALICE_PASSWORD:-alice123}" + +FORCE=0 +for a in "$@"; do [ "$a" = "--force" ] && FORCE=1; done + +PYTHON="${PYTHON:-python3}" + +[ -d "$SEED_DIR" ] || { echo "!! 种子目录缺失:$SEED_DIR" >&2; exit 1; } +mkdir -p "$DATA_DIR" + +# --------------------------------------------------------------------------- +# 1. OAuth 接入方注册表:直接拷贝(没有则视为空表) +# --------------------------------------------------------------------------- +if [ -f "$SEED_DIR/oauth_clients.json" ]; then + if [ ! -f "$DATA_DIR/oauth_clients.json" ] || [ "$FORCE" = "1" ]; then + cp "$SEED_DIR/oauth_clients.json" "$DATA_DIR/oauth_clients.json" + echo " [seed] oauth_clients.json 已写入 $DATA_DIR/oauth_clients.json" + else + echo " [seed] oauth_clients.json 已存在,跳过" + fi +else + echo " [seed] 警告:$SEED_DIR/oauth_clients.json 不存在,注册表留空" +fi + +# --------------------------------------------------------------------------- +# 2. 账号表:生成真实散列。 +# +# ⚠️ 散列算法必须与 source/rust/src/util.rs::hash_password 逐位一致, +# 否则生成的账号永远登录不上: +# x = sha256("salt:password") ← 注意中间是冒号 +# 重复 HASH_ROUNDS(=1000,见 config.rs) 次:x = sha256(x + salt) +# 改了拼接顺序或轮数,存量 users.json 会全部失效。 +# --------------------------------------------------------------------------- +if [ -f "$DATA_DIR/users.json" ] && [ "$FORCE" != "1" ]; then + echo " [seed] users.json 已存在,跳过(要重建加 --force)" +else + ADMIN_PASSWORD="$ADMIN_PASSWORD" ALICE_PASSWORD="$ALICE_PASSWORD" \ + OUT="$DATA_DIR/users.json" USERS_EXAMPLE="$SEED_DIR/users.json.example" \ + "$PYTHON" - <<'PYEOF' +import hashlib, json, os, secrets + +HASH_ROUNDS = 1000 # 必须与 source/rust/src/config.rs 的 HASH_ROUNDS 一致 + +def pwd_hash(salt, password): + x = hashlib.sha256(("%s:%s" % (salt, password)).encode()).hexdigest() + for _ in range(HASH_ROUNDS): + x = hashlib.sha256((x + salt).encode()).hexdigest() + return x + +def entry(username, display_name, password, role, email, department, groups, + api_key, created_at=1768000000): + salt = secrets.token_hex(16) # 32 位 hex + return { + "username": username, + "display_name": display_name, + "role": role, + "salt": salt, + "pwd_hash": pwd_hash(salt, password), + "api_key": api_key, + "email": email, + "department": department, + "groups": groups, + "created_at": created_at, + } + +users = { + "admin": entry( + "admin", "管理员", os.environ["ADMIN_PASSWORD"], "admin", + "admin@yourdomain.com", "平台", ["admin"], + "sk_" + secrets.token_hex(20), + ), + "alice": entry( + "alice", "爱丽丝", os.environ["ALICE_PASSWORD"], "user", + "alice@yourdomain.com", "研发部", ["rd", "eng"], + "sk_" + secrets.token_hex(20), + ), +} + +out = os.environ["OUT"] +with open(out, "w", encoding="utf-8") as f: + json.dump(users, f, ensure_ascii=False, indent=2) + f.write("\n") + +# 同步一份「占位符版」示例回种子目录,让后来人一眼看懂字段含义 +HASH_NOTE = "sha256(':') 后迭代 1000 轮 sha256(x + salt)" +example = { + "admin": { + "username": "admin", + "display_name": "管理员", + "role": "admin", + "salt": "", + "pwd_hash": "<%s>" % HASH_NOTE, + "api_key": "sk_<随机>", + "email": "admin@yourdomain.com", + "department": "平台", + "groups": ["admin"], + "created_at": 0, + }, + "alice": { + "username": "alice", + "display_name": "爱丽丝", + "role": "user", + "salt": "", + "pwd_hash": "<%s>" % HASH_NOTE, + "api_key": "sk_<随机>", + "email": "alice@yourdomain.com", + "department": "研发部", + "groups": ["rd", "eng"], + "created_at": 0, + }, +} +with open(os.environ["USERS_EXAMPLE"], "w", encoding="utf-8") as f: + json.dump(example, f, ensure_ascii=False, indent=2) + f.write("\n") + +print(" [seed] users.json 已生成 %s(admin + alice)" % out) +PYEOF +fi + +echo " [seed] 数据目录就绪:$DATA_DIR" diff --git a/source/conf/nginx.conf b/source/conf/nginx.conf new file mode 100644 index 0000000..d9d4563 --- /dev/null +++ b/source/conf/nginx.conf @@ -0,0 +1,163 @@ +# ============================================================================ +# SSO 统一认证网关 —— 生产配置模板 +# +# 两个 server,对应两层能力: +# sso.<域名> IdP + 管理台:签发令牌、管理账号与接入方 +# *.<域名>(或 *.<子域>)IAP:转发前完成认证并注入 X-Auth-* +# +# 部署前必须替换:域名、证书路径、上游 proxy_pass 地址、OAUTH_* 环境变量。 +# 本文件**不参与**本机 e2e(那是 conf/nginx.test.conf)。 +# +# 阶段处理器注册在 http 级,靠 `sso_api` / `sso_iap` 两个开关按 location 收敛: +# 少了开关,管理台自己也会被 IAP 门禁 401 掉。 +# ============================================================================ + +load_module /usr/local/nginx/modules/libsso_gateway.so; + +worker_processes auto; +error_log /usr/local/nginx/logs/error.log info; +pid /usr/local/nginx/logs/nginx.pid; + +# nginx 会剥掉所有环境变量,机制类配置必须显式白名单。 +# 未设置时不报错,模块按各自缺省值兜底(见 source/rust/src/config.rs)。 +env ADMIN_INIT_PASSWORD; # 播种管理员口令,仅首次启动用 +env OAUTH_SIGNING_SECRET; # HS256 对称密钥;不设则每次重启令牌全失效 +env OAUTH_ISSUER; # 令牌 iss 与 discovery 的 issuer,必须等于对外访问地址 +env OAUTH_COOKIE_DOMAIN; # 跨子域 SSO 用,如 .example.com + +events { + worker_connections 2048; +} + +http { + include mime.types; + default_type application/json; # 业务侧默认 JSON,HTML 在对应 location 单独覆盖 + + # 转发 location 里的 `proxy_set_header Connection $connection_upgrade` 依赖此变量; + # 缺它 nginx -t 直接报 unknown "connection_upgrade" variable,服务起不来。 + map $http_upgrade $connection_upgrade { + default upgrade; + '' close; + } + + # $auth_sub 来自模块注入(access 阶段)。没有它,日志里只能看到「谁被拦了」, + # 看不到「谁访问了哪个后端」——排查越权时这两个信息缺一不可。 + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" "$http_user_agent" ' + '"$http_x_forwarded_for" "$upstream_addr" auth_sub=$auth_sub'; + + access_log /usr/local/nginx/logs/access.log main; + + sendfile on; + keepalive_timeout 65; + + # ========== 共享内存(管理会话 / SSO 会话 / 授权码 / 接入方注册表)========== + # 一张表按前缀共用,容量实测约 124 B/条,10m 足够放约 8 万条。 + sso_state state 10m; + sso_data_dir /usr/local/nginx/data; + + # 可选 TLS:conf/tls/ 下放任意 *.conf(完整的 443 server 块)即启用对应域名的 HTTPS。 + # 目录为空时 include 空匹配,不影响启动。说明见 conf/tls/README.md + include /usr/local/nginx/conf/tls/*.conf; + + # ================================================================== + # IdP + 管理台 + # + # 一个 server 同时承载授权端点与管理接口:接入方与终端用户访问的是同一份 + # issuer,分成两个域名会让 discovery 文档里的地址与 Cookie 作用域都不一致。 + # ================================================================== + server { + listen 443 ssl; + http2 on; + server_name sso.example.com; + + ssl_certificate /usr/local/nginx/conf/tls/example.com/fullchain.cer; + ssl_certificate_key /usr/local/nginx/conf/tls/example.com/example.com.key; + ssl_protocols TLSv1.2 TLSv1.3; + + client_max_body_size 2m; + client_body_buffer_size 1m; + + # 管理台单页(只读静态资源,数据全部走 /api/admin/*) + location = /admin { + default_type text/html; + alias /usr/local/nginx/www/admin.html; + } + location = /admin/ { + default_type text/html; + alias /usr/local/nginx/www/admin.html; + } + location = / { + return 302 /admin; + } + + # 其余全部交给模块分发。**不要**逐条列 location: + # 除标准端点外还有 MaxKey 别名(/oauth/v20/*、/oauth2.0/*)以及带 + # context-path 的写法(/maxkey/oauth/v20/*,模块内做前缀归一化), + # 逐条列举必然漏,漏掉的表现是接入方拿到 HTML 404。 + location / { sso_api on; } + } + + # 明文 80 只做跳转,避免用户在浏览器里手敲地址后停在错误页 + server { + listen 80; + server_name sso.example.com; + return 301 https://$host$request_uri; + } + + # ================================================================== + # IAP:受保护的业务系统 + # + # 应用完全不写认证代码,只读 X-Auth-* 头。 + # 后端地址按环境写死(本项目不做动态上游路由——那是流量层网关的职责)。 + # 多后端时按 server/location 拆分即可,不要引入动态变量: + # 那样会把「谁能在哪台机器上开洞」变成运行时数据。 + # ================================================================== + server { + listen 443 ssl; + http2 on; + server_name app.example.com; + + ssl_certificate /usr/local/nginx/conf/tls/example.com/fullchain.cer; + ssl_certificate_key /usr/local/nginx/conf/tls/example.com/example.com.key; + ssl_protocols TLSv1.2 TLSv1.3; + + location / { + # 门禁:access 阶段判定身份,未登录 → 401 → error_page 跳登录页 + sso_iap on; + + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection $connection_upgrade; + + # ---- 身份注入:网关断言覆盖客户端伪造同名头 ---- + # 后端只信这五个头。它们由模块在 access 阶段写入(见 lib.rs set_auth_vars)。 + proxy_set_header X-Auth-User $auth_user; + proxy_set_header X-Auth-Email $auth_email; + proxy_set_header X-Auth-Groups $auth_groups; + proxy_set_header X-Auth-Sub $auth_sub; + proxy_set_header X-Auth-Token $auth_token; + + proxy_connect_timeout 5s; + proxy_send_timeout 300s; + proxy_read_timeout 300s; + } + + error_page 401 = @oauth_login; + location @oauth_login { + return 302 "https://sso.example.com/login?redirect=$scheme://$host$request_uri"; + } + } + + # 明文 80 跳转(同 IdP) + server { + listen 80; + server_name app.example.com; + return 301 https://$host$request_uri; + } +} diff --git a/source/conf/nginx.test.conf b/source/conf/nginx.test.conf new file mode 100644 index 0000000..99e7ca8 --- /dev/null +++ b/source/conf/nginx.test.conf @@ -0,0 +1,153 @@ +# ============================================================================ +# SSO 统一认证网关 —— 本机/容器验证配置 +# +# 只启「认证层」,不含生产 TLS、不含真实业务后端。用途: +# * 手工观察 IdP 与 IAP 行为 +# * `scripts/run-local-e2e.sh` 起停本配置跑三套端到端 +# +# 明文 server: +# 18098 IdP + 管理台:/oauth/*、/oauth/v20/*(MaxKey 别名)、 +# /.well-known/*、/login、/admin、/api/* +# 18099 IAP:受保护代理,注入 X-Auth-* 到 18097 回显后端(断言用) +# 18097 echo-backend:把收到的请求头原样回显为 JSON(用于断言 IAP 注入) +# 18095 IAP 接入 demo 业务系统:前置认证 + 注入 X-Auth-* → 18096 +# 18096 demo 系统本体(**不由 nginx 监听**,是 tests/demo-system/app.py +# 自己起的进程;直连 18096 时它自己做 OAuth2 客户端,经 18095 访问时 +# 网关已完成认证并注入身份,应用零改造) +# +# 跑法:scripts/run-local-e2e.sh(会自动把下面的绝对路径改成本机路径) +# ============================================================================ + +load_module /usr/local/nginx/modules/libsso_gateway.so; + +worker_processes auto; +error_log /usr/local/nginx/logs/error.log info; +pid /usr/local/nginx/logs/nginx.pid; + +# nginx 默认会剥掉所有环境变量,机制类配置必须显式白名单。 +# 未设置时不报错,模块按各自缺省值兜底(见 source/rust/src/config.rs)。 +env ADMIN_INIT_PASSWORD; +env OAUTH_SIGNING_SECRET; +env OAUTH_ISSUER; +env OAUTH_COOKIE_DOMAIN; + +events { + worker_connections 1024; +} + +http { + include mime.types; + default_type application/json; + + # TLS 子配置目录(生产用;本验证配置不依赖,空目录不影响启动) + include /usr/local/nginx/conf/tls/*.conf; + + # 共享内存 + 数据目录(OAuth 接入方注册表从这里加载) + sso_state state 10m; + sso_data_dir /usr/local/nginx/data; + + # ------------------------------------------------------------------ + # 18097 回显后端:把注入进来的 X-Auth-* 请求头回显成 JSON,供断言 + # ------------------------------------------------------------------ + server { + listen 18097; + location / { + default_type application/json; + return 200 '{"x_auth_user":"$http_x_auth_user","x_auth_email":"$http_x_auth_email","x_auth_groups":"$http_x_auth_groups","x_auth_sub":"$http_x_auth_sub","x_auth_token":"$http_x_auth_token","remote_addr":"$remote_addr"}'; + } + } + + # ------------------------------------------------------------------ + # 18098 IdP + 管理台 + # ------------------------------------------------------------------ + server { + listen 18098 default_server; + server_name sso.yourdomain.com; + + client_max_body_size 2m; + client_body_buffer_size 1m; + + # 管理台单页(数据全部通过 /api/admin/* 拉取,故与 IdP 同端口不影响端点语义) + location = /admin { + default_type text/html; + alias /usr/local/nginx/www/admin.html; + } + location = /admin/ { + default_type text/html; + alias /usr/local/nginx/www/admin.html; + } + + # 全部交给模块分发:MaxKey 别名在 /oauth/v20/*、/oauth2.0/*,还有 + # /maxkey/oauth/v20/* 这类带 context-path 的写法(模块内做前缀归一化), + # 逐条列 location 必然漏,故整站交给 sso_api。 + location / { sso_api on; } + } + + # ------------------------------------------------------------------ + # 18099 IAP:受保护代理示例(注入 X-Auth-* 到回显后端) + # ------------------------------------------------------------------ + server { + listen 18099 default_server; + server_name ~^(?.+)\.app\.yourdomain\.com$; + + location / { + # 门禁:IAP 身份感知代理开关(access 阶段) + sso_iap on; + + # 本验证配置用固定后端;生产用按环境生成的 proxy_pass + proxy_pass http://127.0.0.1:18097; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + # ---- IAP 身份注入:网关断言覆盖客户端伪造同名头 ---- + # 后端只信这五个头,它们由网关在 access 阶段写入(见 lib.rs set_auth_vars) + proxy_set_header X-Auth-User $auth_user; + proxy_set_header X-Auth-Email $auth_email; + proxy_set_header X-Auth-Groups $auth_groups; + proxy_set_header X-Auth-Sub $auth_sub; + proxy_set_header X-Auth-Token $auth_token; + + # 无身份(401)→ 内部跳登录页并回跳 + error_page 401 = @oauth_login; + } + + location @oauth_login { + return 302 "http://127.0.0.1:18098/login?redirect=$scheme://$host$request_uri"; + } + } + + # ------------------------------------------------------------------ + # 18095 IAP 接入:把统一认证前置于 demo 业务系统 + # + # 与 18099 的区别:18099 指向回显后端(只为断言请求头),本 server 指向真正的 + # 业务系统,演示**应用零改造接入**——应用不写 OAuth 代码,只读 X-Auth-* 头。 + # ------------------------------------------------------------------ + server { + listen 18095 default_server; + server_name 127.0.0.1; + + location / { + sso_iap on; + + proxy_pass http://127.0.0.1:18096; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + + proxy_set_header X-Auth-User $auth_user; + proxy_set_header X-Auth-Email $auth_email; + proxy_set_header X-Auth-Groups $auth_groups; + proxy_set_header X-Auth-Sub $auth_sub; + proxy_set_header X-Auth-Token $auth_token; + + error_page 401 = @oauth_login_demo; + } + + location @oauth_login_demo { + return 302 "http://127.0.0.1:18098/login?redirect=$scheme://$host$request_uri"; + } + } +} diff --git a/source/conf/tls/README.md b/source/conf/tls/README.md new file mode 100644 index 0000000..19b6e96 --- /dev/null +++ b/source/conf/tls/README.md @@ -0,0 +1,39 @@ +# conf/tls —— TLS 证书 + +生产 `conf/nginx.conf` 的 443 server 直接引用本目录下的证书文件。 +**证书与私钥绝不入库**——`.gitignore` 已排除常见后缀与本目录下的证书子目录; +本 README 是目录里唯一入库的文件。 + +## 约定 + +* 一个域名一个子目录:`conf/tls/<域名>/fullchain.cer` + `conf/tls/<域名>/<域名>.key`。 +* `conf/nginx.conf` 里的路径就是按这个约定写的,换证书只换文件、不改配置。 +* 目录为空时 `include /usr/local/nginx/conf/tls/*.conf;` 是空匹配,不影响启动。 + +## 签发(acme.sh DNS-01,泛域名) + +```bash +acme.sh --issue --dns dns_ali -d example.com -d '*.example.com' +mkdir -p conf/tls/example.com +acme.sh --install-cert -d example.com \ + --fullchain-file conf/tls/example.com/fullchain.cer \ + --key-file conf/tls/example.com/example.com.key +``` + +## 校验配对(重要) + +证书与私钥**必须用公钥比对**: + +```bash +openssl x509 -in fullchain.cer -noout -pubkey | openssl md5 +openssl pkey -in example.com.key -pubout | openssl md5 +``` + +两条 md5 必须一致。注意:如果证书是 ECC 的,**不要**用 `openssl rsa -modulus` +——它对 EC 私钥输出为空,会误报「不匹配」。 + +## 生效方式 + +只换证书:`nginx -s reload` 即可(新 worker 重新加载证书文件)。 +改 `conf/*.conf` 或 Rust 源码才需要重启进程——动态模块常驻内存,`reload` 不会 +重新 `load_module`,改了 `.so` 必须真重启。 diff --git a/source/data-seed/oauth_clients.json b/source/data-seed/oauth_clients.json new file mode 100644 index 0000000..04fc8e4 --- /dev/null +++ b/source/data-seed/oauth_clients.json @@ -0,0 +1,97 @@ +[ + { + "client_id": "grafana", + "client_secret": "cs_grafana_demo_secret_0000000000000000", + "name": "Grafana(演示机密客户端)", + "redirect_uris": [ + "https://grafana.yourdomain.com/login/generic_oauth" + ], + "grant_types": [ + "authorization_code", + "refresh_token" + ], + "scopes": [ + "openid", + "profile", + "email" + ], + "confidential": true, + "created_at": 1768000000 + }, + { + "client_id": "spa-demo", + "client_secret": "", + "name": "单页应用(演示公开客户端,走 PKCE)", + "redirect_uris": [ + "https://app.yourdomain.com/callback" + ], + "grant_types": [ + "authorization_code", + "refresh_token" + ], + "scopes": [ + "openid", + "profile", + "email" + ], + "confidential": false, + "created_at": 1768000000 + }, + { + "client_id": "machine", + "client_secret": "cs_machine_demo_secret_0000000000000000", + "name": "机器对机器(演示 client_credentials / password)", + "redirect_uris": [], + "grant_types": [ + "authorization_code", + "refresh_token", + "client_credentials", + "password" + ], + "scopes": [ + "openid", + "profile", + "email" + ], + "confidential": true, + "created_at": 1768000000 + }, + { + "client_id": "demo-system", + "client_secret": "cs_f5efeab3c50a6332b462561034c55401", + "name": "demo-system 简单业务系统(机密客户端,MaxKey 风格表单传参)", + "redirect_uris": [ + "http://127.0.0.1:18096/oauth2/callback" + ], + "grant_types": [ + "authorization_code", + "refresh_token" + ], + "scopes": [ + "openid", + "profile", + "email" + ], + "confidential": true, + "created_at": 1789000000 + }, + { + "client_id": "demo-spa", + "client_secret": "", + "name": "demo-system 公开客户端(PKCE / S256)", + "redirect_uris": [ + "http://127.0.0.1:18096/oauth2/callback" + ], + "grant_types": [ + "authorization_code", + "refresh_token" + ], + "scopes": [ + "openid", + "profile", + "email" + ], + "confidential": false, + "created_at": 1789000000 + } +] \ No newline at end of file diff --git a/source/data-seed/users.json.example b/source/data-seed/users.json.example new file mode 100644 index 0000000..46c5508 --- /dev/null +++ b/source/data-seed/users.json.example @@ -0,0 +1,31 @@ +{ + "admin": { + "username": "admin", + "display_name": "管理员", + "role": "admin", + "salt": "", + "pwd_hash": ":') 后迭代 1000 轮 sha256(x + salt)>", + "api_key": "sk_<随机>", + "email": "admin@yourdomain.com", + "department": "平台", + "groups": [ + "admin" + ], + "created_at": 0 + }, + "alice": { + "username": "alice", + "display_name": "爱丽丝", + "role": "user", + "salt": "", + "pwd_hash": ":') 后迭代 1000 轮 sha256(x + salt)>", + "api_key": "sk_<随机>", + "email": "alice@yourdomain.com", + "department": "研发部", + "groups": [ + "rd", + "eng" + ], + "created_at": 0 + } +} diff --git a/source/rust/Cargo.lock b/source/rust/Cargo.lock new file mode 100644 index 0000000..f283a13 --- /dev/null +++ b/source/rust/Cargo.lock @@ -0,0 +1,477 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c880a97d28a3681c0267bd29cff89621202715b065127cd445fa0f0fe0aa2880" + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cc" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005ec2760ca554fae18df7a11195552ec576cd665632a881bc011d5bb2fd4d80" +dependencies = [ + "find-msvc-tools", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "nginx-sys" +version = "0.5.0" +dependencies = [ + "bindgen", + "cc", + "dunce", + "errno", + "regex", + "shlex 2.0.1", +] + +[[package]] +name = "ngx" +version = "0.5.0" +dependencies = [ + "allocator-api2", + "lock_api", + "nginx-sys", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.5", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "sso-gateway" +version = "1.0.0" +dependencies = [ + "getrandom", + "libc", + "nginx-sys", + "ngx", + "serde", + "serde_json", + "sha2", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/source/rust/Cargo.toml b/source/rust/Cargo.toml new file mode 100644 index 0000000..4d147ed --- /dev/null +++ b/source/rust/Cargo.toml @@ -0,0 +1,52 @@ +# 独立 workspace:vendored 的 ngx-rust 本身是 workspace 根,需显式排除以免歧义 +[workspace] +exclude = ["vendor/ngx-rust"] + +[package] +name = "sso-gateway" +version = "1.0.0" +edition = "2021" +publish = false +description = "SSO 统一认证网关 —— nginx + Rust 动态模块(自带 OAuth2/OIDC IdP + IAP 身份注入)" + +[lib] +# cdylib 给 nginx 加载;rlib 便于单元测试 +name = "sso_gateway" +crate-type = ["cdylib", "rlib"] + +[features] +default = ["export-modules"] +# 脱离 nginx 构建系统、单独产出动态模块时必须开启(生成 ngx_modules 表) +export-modules = [] + +[dependencies] +# ⚠️ 依赖必须用 vendored 源码,不能走 crates.io,也不能走 git: +# +# 1) `ngx = "0.5"`(crates.io 0.5.1)只发布了配置阶段接口(HttpModule), +# 请求阶段 API(add_phase_handler / HttpPhase / HttpRequestHandler)尚未发版, +# 实测直接编译失败:unresolved imports `ngx::http::HttpPhase` +# +# 2) git 依赖会永久挂起:ngx-rust 挂了一个指向完整 nginx 仓库的 submodule +# [submodule "nginx-src/nginx"] url = https://github.com/nginx/nginx.git +# cargo 解析 git 依赖时会 update_submodules,去克隆几十 MB 的 nginx 仓库, +# 国内网络下卡死(实测 cargo 5 分钟 0% CPU,调用栈停在 +# GitCheckout::update_submodules -> fetch -> wait4)。 +# +# 因此 vendor 到 vendor/ngx-rust/,用 path 依赖:离线可编译、无子模块、版本锁定。 +ngx = { path = "vendor/ngx-rust" } +nginx-sys = { path = "vendor/ngx-rust/nginx-sys" } + +# 业务层依赖:全部是纯 Rust 实现,不引入任何系统库或常驻依赖 +serde = { version = "1", features = ["derive"] } +serde_json = "1" # 空 Vec / Vec 天然序列化为 [] / {},前后端契约简单 +sha2 = "0.10" # 口令哈希 + JWT 的 HMAC-SHA256 + PKCE S256 +getrandom = "0.2" # 会话 token / 授权码 / 客户端密钥;不可退化成可预测伪随机 +libc = "0.2" # 仅用于 localtime_r / time / strftime + +[profile.release] +opt-level = 3 +lto = true +codegen-units = 1 +# 模块被加载进 nginx 这个 C 进程,panic 绝不能跨 FFI 边界展开 +panic = "abort" +strip = true diff --git a/source/rust/build.rs b/source/rust/build.rs new file mode 100644 index 0000000..bc4930b --- /dev/null +++ b/source/rust/build.rs @@ -0,0 +1,20 @@ +//! 构建脚本:让 cdylib 允许「未定义符号」。 +//! +//! nginx 动态模块的运行时符号(`ngx_palloc` / `ngx_http_add_variable` / +//! `ngx_shared_memory_add` …)由 nginx 主程序在 `load_module` 时提供, +//! 链接本模块时它们必然是未定义的——这是动态模块的固有属性,不是错误。 +//! +//! * Linux:cdylib 默认允许未定义符号,无需处理。 +//! * macOS:必须显式 `-undefined dynamic_lookup`,否则 ld 直接报 +//! `symbol(s) not found for architecture x86_64`。 +//! +//! 注意:vendored 的 `ngx` crate 的 build.rs 也设了这两项,但 +//! `rustc-link-arg` 只对「设置它的那个 crate」生效,不会传递给依赖它的 +//! crate,所以本 crate 必须自己再设一次。 + +fn main() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + println!("cargo::rustc-link-arg=-undefined"); + println!("cargo::rustc-link-arg=dynamic_lookup"); + } +} diff --git a/source/rust/src/api.rs b/source/rust/src/api.rs new file mode 100644 index 0000000..2a467ed --- /dev/null +++ b/source/rust/src/api.rs @@ -0,0 +1,603 @@ +//! API 统一分发器。 +//! +//! 三类调用方、三套鉴权: +//! +//! ```text +//! /oauth/* 公开:OAuth2 / OIDC 端点(授权服务器自身) +//! /api/v1/* 账号态:请求头 X-API-Key(账号级机器凭据) +//! /api/admin/* 管理员态:登录会话 Cookie(除 login 外均需 role=admin) +//! ``` +//! +//! 写操作完成后由各模块自行同步共享内存(如 `oauth_clients::upsert` 写 `ocl:`), +//! 做到「登记完立刻可授权」——本项目**没有**回源读文件这条兜底路径, +//! 所以写穿不是优化而是正确性要求。 + +use ngx::core::Status; +use ngx::ffi::ngx_http_request_t; +use ngx::http::HTTPStatus; +use serde_json::{Value, json}; + +use crate::config; +use crate::http; +use crate::models::User; +use crate::oauth; +use crate::oauth_clients; +use crate::session; +use crate::state; +use crate::users; +use crate::util; + +// =========================================================================== +// 路由 +// =========================================================================== + +/// 鉴权后传给处理器的身份 +pub enum Actor { + /// 公开接口,无身份 + None, + /// 账号态(X-API-Key) + User(User), + /// 管理员态(登录会话) + Admin(User), +} + +impl Actor { + /// 操作者名称:审计日志用 + fn admin_name(&self) -> &str { + match self { + Actor::Admin(u) => &u.username, + Actor::User(u) => &u.username, + Actor::None => "", + } + } +} + +#[derive(Clone, Copy, PartialEq)] +enum Guard { + Public, + User, + Admin, +} + +type Handler = fn(*mut ngx_http_request_t, Actor) -> Status; + +/// 路由表。刻意用精确匹配而非正则——接口路径是固定的, +/// 正则只会引入「写错锚点导致前缀误匹配」的风险。 +fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> { + let entry: (Guard, Handler) = match (method, uri) { + // ---- 管理台:登录 / 会话 ---------------------------------------- + ("POST", "/api/admin/login") => (Guard::Public, h_login), + ("POST", "/api/admin/logout") => (Guard::Admin, h_logout), + ("GET", "/api/admin/session") => (Guard::Admin, h_session), + + // ---- 管理台:账号 ----------------------------------------------- + ("GET", "/api/admin/users") => (Guard::Admin, h_admin_users), + ("POST", "/api/admin/users/create") => (Guard::Admin, h_admin_user_create), + ("POST", "/api/admin/users/key") => (Guard::Admin, h_admin_user_key), + ("POST", "/api/admin/users/password") => (Guard::Admin, h_admin_user_password), + ("POST", "/api/admin/users/display") => (Guard::Admin, h_admin_user_display), + ("POST", "/api/admin/users/profile") => (Guard::Admin, h_admin_user_profile), + ("POST", "/api/admin/users/role") => (Guard::Admin, h_admin_user_role), + ("POST", "/api/admin/users/delete") => (Guard::Admin, h_admin_user_delete), + + // ---- 管理台:统一认证接入方(OAuth 客户端)---------------------- + ("GET", "/api/admin/oauth-clients") => (Guard::Admin, h_admin_oauth_clients), + ("POST", "/api/admin/oauth-clients/save") => (Guard::Admin, h_admin_oauth_client_save), + ("POST", "/api/admin/oauth-clients/rotate") => (Guard::Admin, h_admin_oauth_client_rotate), + ("POST", "/api/admin/oauth-clients/delete") => (Guard::Admin, h_admin_oauth_client_delete), + + // ---- 账号态 API ------------------------------------------------- + ("GET", "/api/v1/me") => (Guard::User, h_me), + + // ---- OAuth2 / OIDC(公开端点)---------------------------------- + ("GET", "/oauth/authorize") => (Guard::Public, h_oauth_authorize), + ("POST", "/oauth/token") => (Guard::Public, h_oauth_token), + ("GET", "/oauth/userinfo") => (Guard::Public, h_oauth_userinfo), + ("POST", "/oauth/userinfo") => (Guard::Public, h_oauth_userinfo), + ("POST", "/oauth/introspect") => (Guard::Public, h_oauth_introspect), + ("GET", "/.well-known/openid-configuration") => (Guard::Public, h_oauth_discovery), + ("GET", "/.well-known/jwks.json") => (Guard::Public, h_oauth_jwks), + ("GET", "/oauth/jwks") => (Guard::Public, h_oauth_jwks), + ("GET", "/login") => (Guard::Public, h_oauth_login_get), + ("POST", "/login") => (Guard::Public, h_oauth_login_post), + ("POST", "/oauth/logout") => (Guard::Public, h_oauth_logout), + ("GET", "/oauth/logout") => (Guard::Public, h_oauth_logout), + + // ---- MaxKey OAuth2 互通别名 ------------------------------------ + // MaxKey 各族版本的端点命名彼此不同,第三方应用常直接照抄文档里的 + // URL。这里把常见命名都映射到同一套实现,客户端不改一行代码即可切换。 + // /oauth/v20/* MaxKey 2.x/3.x 主线(authorize/token/me) + // /oauth2.0/* 部分部署与 MaxKey 衍生文档使用 + // 注:`me` 走 MaxKey 扁平响应,`profile` 与标准 userinfo 同形。 + ("GET", "/oauth/v20/authorize") => (Guard::Public, h_oauth_authorize), + ("GET", "/oauth/v20/token") => (Guard::Public, h_oauth_token_v20), + ("POST", "/oauth/v20/token") => (Guard::Public, h_oauth_token_v20), + ("GET", "/oauth/v20/me") => (Guard::Public, h_oauth_me_v20), + ("POST", "/oauth/v20/me") => (Guard::Public, h_oauth_me_v20), + ("GET", "/oauth/v20/logout") => (Guard::Public, h_oauth_logout), + ("GET", "/oauth2.0/authorize") => (Guard::Public, h_oauth_authorize), + ("GET", "/oauth2.0/accessToken") => (Guard::Public, h_oauth_token_v20), + ("POST", "/oauth2.0/accessToken") => (Guard::Public, h_oauth_token_v20), + ("GET", "/oauth2.0/profile") => (Guard::Public, h_oauth_me_v20), + ("POST", "/oauth2.0/profile") => (Guard::Public, h_oauth_me_v20), + _ => return None, + }; + Some(entry) +} + +/// MaxKey 各版本把 OAuth 端点挂在不同的 context-path 下。 +/// +/// 第三方应用的配置项往往就是照抄文档里的完整 URL(`/maxkey/oauth/v20/token` +/// 或 `/sign/authz/oauth/v20/authorize`),把 context-path 一起写进了端点地址。 +/// 精确路由 miss 时剥掉一层已知前缀再试,省得为改一个前缀去给每个应用打补丁。 +/// +/// 只在 miss 之后调用,所以不会遮蔽真实存在的 `/api/v1/*`、`/api/admin/*`。 +const MAXKEY_CONTEXT_PREFIXES: [&str; 5] = ["/maxkey", "/sign/authz", "/sign", "/authz", "/api"]; + +/// 剥掉一层已知的 MaxKey context-path(返回 None 表示没有可剥的前缀)。 +fn strip_maxkey_ctx(uri: &str) -> Option<&str> { + for p in MAXKEY_CONTEXT_PREFIXES { + if let Some(rest) = uri.strip_prefix(p) { + if rest.starts_with('/') { + return Some(rest); + } + } + } + None +} + +// =========================================================================== +// OAuth2 / OIDC 端点(公开,直接转交 oauth 模块,忽略 Actor) +// =========================================================================== + +fn h_oauth_authorize(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::authorize(r) +} +fn h_oauth_token(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::token(r) +} +fn h_oauth_token_v20(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::token_v20(r) +} +fn h_oauth_userinfo(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::userinfo(r) +} +fn h_oauth_me_v20(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::userinfo_v20(r) +} +fn h_oauth_introspect(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::introspect(r) +} +fn h_oauth_discovery(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::discovery(r) +} +fn h_oauth_jwks(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::jwks(r) +} +fn h_oauth_login_get(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::login_get(r) +} +fn h_oauth_login_post(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::login_post(r) +} +fn h_oauth_logout(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + oauth::logout(r) +} + +/// 一次请求的完整处理:路由 → 鉴权 → 执行 +pub fn dispatch(r: *mut ngx_http_request_t) -> Status { + let method = http::method_str(r); + let uri = http::uri(r); + + // 精确路由;miss 时按 MaxKey context-path 归一化再试一次(见 strip_maxkey_ctx) + let routed = route(&method, &uri).or_else(|| { + let stripped = strip_maxkey_ctx(&uri)?; + let hit = route(&method, stripped); + if hit.is_some() { + util::log_warn(&format!("[api] MaxKey context-path 归一化 {uri} -> {stripped}")); + } + hit + }); + + let Some((guard, handler)) = routed else { + return http::fail( + r, + HTTPStatus::NOT_FOUND, + &format!("接口不存在:{method} {uri}"), + ); + }; + + let actor = match guard { + Guard::Public => Actor::None, + + Guard::User => { + let key = http::header(r, "x-api-key").unwrap_or_default(); + match users::find_by_key(&key) { + Some(u) => Actor::User(u), + None => { + util::log_warn(&format!( + "[api] API Key 校验失败 client={}", + http::remote_addr(r) + )); + return http::fail( + r, + HTTPStatus::UNAUTHORIZED, + "API Key 无效或缺失,请在请求头携带 X-API-Key", + ); + } + } + } + + Guard::Admin => { + let cookie = http::header(r, "cookie"); + match session::authenticate(cookie.as_deref()).and_then(|name| users::get(&name)) { + Some(u) if u.is_admin() => Actor::Admin(u), + // 会话有效但非管理员:403 而不是 401,便于前端区分 + Some(_) => return http::fail(r, HTTPStatus::FORBIDDEN, "需要管理员权限"), + None => { + return http::fail( + r, + HTTPStatus::UNAUTHORIZED, + "未登录或会话已过期,请重新登录", + ); + } + } + } + }; + + handler(r, actor) +} + +// =========================================================================== +// 管理员:登录 / 会话 +// =========================================================================== + +fn h_login(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let ip = http::remote_addr(r); + let now = util::now(); + + if state::get_login_fail(&ip, now) >= config::LOGIN_MAX_FAIL { + return http::fail(r, HTTPStatus::TOO_MANY_REQUESTS, "登录失败次数过多,请 5 分钟后再试"); + } + + let p = http::params(r); + let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); + let password = p.get("password").cloned().unwrap_or_default(); + + if username.is_empty() || password.is_empty() { + return http::fail(r, HTTPStatus::BAD_REQUEST, "请输入账号和密码"); + } + + let Some(user) = users::get(&username) else { + state::bump_login_fail(&ip, now); + util::log_warn(&format!("[api] 登录失败 user={username} client={ip}")); + return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); + }; + + if !util::verify_password(&password, &user.salt, &user.pwd_hash) { + state::bump_login_fail(&ip, now); + util::log_warn(&format!("[api] 登录失败 user={username} client={ip}")); + return http::fail(r, HTTPStatus::UNAUTHORIZED, "账号或密码错误"); + } + + if !user.is_admin() { + return http::fail(r, HTTPStatus::FORBIDDEN, "该账号不是管理员,无法登录管理台"); + } + + state::clear_login_fail(&ip); + let token = session::create(&username); + let cookie = session::set_cookie(&token); + util::log_notice(&format!("[api] 管理员登录 user={username} client={ip}")); + + http::ok_with(r, users::view(&user), "登录成功", &[("Set-Cookie", &cookie)]) +} + +fn h_logout(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let cookie = http::header(r, "cookie"); + session::destroy(cookie.as_deref()); + let cleared = session::clear_cookie(); + http::ok_with(r, json!({}), "已退出登录", &[("Set-Cookie", &cleared)]) +} + +fn h_session(r: *mut ngx_http_request_t, actor: Actor) -> Status { + let Actor::Admin(user) = actor else { + return http::fail(r, HTTPStatus::UNAUTHORIZED, "未登录或会话已过期,请重新登录"); + }; + http::ok(r, users::view(&user), "ok") +} + +// =========================================================================== +// 管理员:账号管理 +// =========================================================================== + +fn h_admin_users(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + // 只读一次 users.json:列表、部门取值、用户组取值都从这一份快照里算。 + let all = users::all(); + + // 部门与组的「已有取值」一并回显:管理台据此给出可选值提示, + // 避免同一个人手输成「研发部 / 研发中心 / RD」三种写法。 + let mut departments: Vec = Vec::new(); + let mut groups: Vec = Vec::new(); + for u in &all { + if !u.department.is_empty() && !departments.iter().any(|d| d == &u.department) { + departments.push(u.department.clone()); + } + for g in &u.groups { + if !groups.iter().any(|x| x == g) { + groups.push(g.clone()); + } + } + } + departments.sort(); + groups.sort(); + + let items: Vec = all.iter().map(users::view).collect(); + + http::ok( + r, + json!({ + "items": items, + "departments": departments, + "groups": groups, + }), + "ok", + ) +} + +fn h_admin_user_create(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + + match users::create( + p.get("username").map(String::as_str).unwrap_or(""), + p.get("display_name").map(String::as_str).unwrap_or(""), + p.get("password").map(String::as_str).unwrap_or(""), + p.get("role").map(String::as_str).unwrap_or("user"), + p.get("email").map(String::as_str).unwrap_or(""), + p.get("department").map(String::as_str).unwrap_or(""), + p.get("groups").map(String::as_str).unwrap_or(""), + ) { + Ok(user) => { + util::log_notice(&format!( + "[api] 创建账号 {} name={} role={} dept={}", + user.username, user.display_name, user.role, user.department + )); + http::ok(r, users::view(&user), "账号创建成功") + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +/// 设置展示名(中文姓名等)。传空串 = 清空,前端回落到账号名。 +fn h_admin_user_display(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); + + match users::set_display_name(&username, p.get("display_name").map(String::as_str).unwrap_or("")) { + Ok(u) => http::ok(r, users::view(&u), "已更新展示名"), + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +/// 设置身份声明(邮箱 / 部门 / 用户组)。这三个字段直接进 OIDC claims 与 +/// `X-Auth-*` 注入头,是下游系统授权的依据,因此必须可在线维护。 +fn h_admin_user_profile(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); + + // display_name 缺省 = 不动(避免「只改部门却把姓名清空」这类误伤) + let display_name = p.get("display_name").map(String::as_str); + + match users::set_profile( + &username, + p.get("email").map(String::as_str).unwrap_or(""), + p.get("department").map(String::as_str).unwrap_or(""), + p.get("groups").map(String::as_str).unwrap_or(""), + display_name, + ) { + Ok(u) => { + util::log_notice(&format!( + "[api] 更新身份 {username} email={} dept={} groups={:?}", + u.email, u.department, u.groups + )); + http::ok(r, users::view(&u), "已更新身份信息") + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +/// 设置角色(admin / user)。不允许把最后一个管理员降级。 +fn h_admin_user_role(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); + let role = p.get("role").map(String::as_str).unwrap_or(""); + + if role != "admin" && role != "user" { + return http::fail(r, HTTPStatus::BAD_REQUEST, "角色只能是 admin 或 user"); + } + match users::set_role(&username, role) { + Ok(u) => { + util::log_notice(&format!("[api] 设置角色 {username} -> {}", u.role)); + http::ok(r, users::view(&u), "已更新角色") + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +fn h_admin_user_key(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); + + match users::regenerate_key(&username) { + Ok(key) => http::ok(r, json!({ "username": username, "api_key": key }), "已重置 API Key"), + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +fn h_admin_user_password(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); + let password = p.get("password").map(String::as_str).unwrap_or(""); + + match users::set_password(&username, password) { + Ok(()) => http::ok(r, json!({}), "密码已重置"), + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +fn h_admin_user_delete(r: *mut ngx_http_request_t, actor: Actor) -> Status { + let p = http::params(r); + let username = p.get("username").map(|s| util::trim(s).to_owned()).unwrap_or_default(); + + match users::delete(&username, actor.admin_name()) { + Ok(()) => { + util::log_notice(&format!("[api] 删除账号 {username}")); + http::ok(r, json!({ "username": username }), "账号已删除") + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +// =========================================================================== +// 管理员:统一认证接入方(OAuth 客户端)管理 +// +// 对应 MaxKey 的「应用管理」:第三方应用在这里登记 client_id/密钥/回调地址, +// 之后按标准 OAuth2 / OIDC 流程对接,无需感知本网关的用户存储。 +// +// 三条不变量: +// 1. 列表读注册表**真源**(store::read_oauth_clients),不是共享内存快照—— +// 管理台显示的必须就是「重启后还在」的那份; +// 2. 保存/删除由 oauth_clients 内部写穿共享内存,做到「登记完立刻能授权」, +// 不需要重启 nginx; +// 3. 密钥只在创建时/显式重置时返回明文,列表里给的是脱敏值。 +// =========================================================================== + +/// 拆分管理台传入的列表字段(回调地址 / 授权类型 / scope)。 +/// +/// 回调地址常写成 textarea 里一行一个,scope 常写成 `openid profile`, +/// 所以逗号、顿号、分号、空白、换行全都认。 +fn parse_list(raw: &str) -> Vec { + raw.split(|c: char| { + c == ',' || c == '、' || c == ';' || c == '\n' || c == '\r' || c == '\t' || c == ' ' + }) + .map(|s| util::trim(s).to_owned()) + .filter(|s| !s.is_empty()) + .collect() +} + +fn h_admin_oauth_clients(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let items: Vec = oauth_clients::all().iter().map(oauth_clients::view).collect(); + let iss = oauth::issuer(); + http::ok( + r, + json!({ + "items": items, + "issuer": iss, + // 给接入方抄的端点清单:标准一组 + MaxKey 一组(照抄 MaxKey 文档 + // 配好的应用可以原样切换过来,见 docs/design.md §15) + "endpoints": { + "discovery": format!("{iss}/.well-known/openid-configuration"), + "authorize": format!("{iss}/oauth/authorize"), + "token": format!("{iss}/oauth/token"), + "userinfo": format!("{iss}/oauth/userinfo"), + "introspect": format!("{iss}/oauth/introspect"), + "logout": format!("{iss}/oauth/logout"), + "authorize_v20": format!("{iss}/oauth/v20/authorize"), + "token_v20": format!("{iss}/oauth/v20/token"), + "profile_v20": format!("{iss}/oauth/v20/me"), + }, + }), + "ok", + ) +} + +fn h_admin_oauth_client_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let client_id = p + .get("client_id") + .map(|s| util::trim(s).to_owned()) + .unwrap_or_default(); + let confidential = util::to_bool(p.get("confidential")); + // 先记录「此前是否存在」:管理台据此决定要不要弹「请立即复制密钥」 + let existed = oauth_clients::all().iter().any(|c| c.client_id == client_id); + + match oauth_clients::upsert( + &client_id, + p.get("name").map(String::as_str).unwrap_or(""), + parse_list(p.get("redirect_uris").map(String::as_str).unwrap_or("")), + parse_list(p.get("grant_types").map(String::as_str).unwrap_or("")), + parse_list(p.get("scopes").map(String::as_str).unwrap_or("")), + confidential, + p.get("client_secret").map(String::as_str).unwrap_or(""), + ) { + Ok(c) => { + util::log_notice(&format!( + "[api] 保存 OAuth 客户端 {}({},回调 {} 个,授权类型 {} 种)", + c.client_id, + if c.confidential { "机密" } else { "公开" }, + c.redirect_uris.len(), + c.grant_types.len() + )); + let mut v = oauth_clients::view(&c); + if let Value::Object(ref mut m) = v { + m.insert("existed".to_owned(), json!(existed)); + } + http::ok(r, v, if existed { "已更新" } else { "已创建" }) + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +/// 重置客户端密钥(应急:怀疑密钥泄漏时)。旧密钥立即失效。 +fn h_admin_oauth_client_rotate(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let client_id = p + .get("client_id") + .map(|s| util::trim(s).to_owned()) + .unwrap_or_default(); + match oauth_clients::rotate_secret(&client_id) { + Ok(secret) => { + util::log_notice(&format!("[api] 重置 OAuth 客户端密钥 {client_id}")); + http::ok( + r, + json!({ "client_id": client_id, "client_secret": secret }), + "密钥已重置,请立即更新接入方配置", + ) + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +fn h_admin_oauth_client_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status { + let p = http::params(r); + let client_id = p + .get("client_id") + .map(|s| util::trim(s).to_owned()) + .unwrap_or_default(); + match oauth_clients::delete(&client_id) { + Ok(()) => { + util::log_notice(&format!("[api] 删除 OAuth 客户端 {client_id}")); + http::ok(r, json!({ "client_id": client_id }), "已删除") + } + Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e), + } +} + +// =========================================================================== +// 账号态 API +// =========================================================================== + +/// 账号态:看看自己的身份声明。 +/// +/// 刻意**不回显 OAuth 客户端侧的任何密钥**——账号与接入方是两条独立的信任线。 +fn h_me(r: *mut ngx_http_request_t, actor: Actor) -> Status { + let Actor::User(user) = actor else { + return http::fail(r, HTTPStatus::UNAUTHORIZED, "API Key 无效或缺失,请在请求头携带 X-API-Key"); + }; + + let mut v = users::view(&user); + if let Value::Object(ref mut m) = v { + m.insert("sub".to_owned(), json!(user.username)); + m.insert("issuer".to_owned(), json!(oauth::issuer())); + } + http::ok(r, v, "ok") +} diff --git a/source/rust/src/config.rs b/source/rust/src/config.rs new file mode 100644 index 0000000..8ade1ba --- /dev/null +++ b/source/rust/src/config.rs @@ -0,0 +1,120 @@ +//! 全局策略常量(唯一真源)。 +//! +//! **改策略只改这里**,不要散落到 users / oauth / api 里,否则行为会出现多处真源。 + +// =========================================================================== +// 会话与口令 +// =========================================================================== + +/// 管理员登录会话时长(秒) +pub const SESSION_TTL: i64 = 8 * 3600; +/// 口令哈希迭代轮数。 +/// +/// 沿用被剥离项目的历史算法(`sha256` 迭代加盐),使存量 `users.json` +/// 可以原样接管,不必强制所有人改口令。 +pub const HASH_ROUNDS: usize = 1000; + +/// 首次启动播种的管理员账号名 +pub const INIT_ADMIN_USER: &str = "admin"; +/// 初始管理员口令的环境变量名。 +/// nginx.conf 里必须有对应的 `env ADMIN_INIT_PASSWORD;`,否则会被 nginx 剥离。 +pub const INIT_ADMIN_PASSWORD_ENV: &str = "ADMIN_INIT_PASSWORD"; +/// 播种口令的缺省值。**仅用于本机/首次启动**,生产必须用环境变量覆盖。 +pub const INIT_ADMIN_PASSWORD_DEFAULT: &str = "123456"; + +/// 口令最短长度 +pub const PASSWORD_MIN_LEN: usize = 6; +pub const USERNAME_MIN_LEN: usize = 2; +pub const USERNAME_MAX_LEN: usize = 32; +/// 展示名(中文姓名等)长度上限。按**字符数**算,一个汉字算 1。 +pub const DISPLAY_NAME_MAX_LEN: usize = 32; +/// 部门名长度上限 +pub const DEPARTMENT_MAX_LEN: usize = 64; +/// 单个账号可归属的用户组数量上限(挡住把整张目录灌进去的手滑) +pub const GROUPS_MAX: usize = 32; +/// 单个用户组名长度上限 +pub const GROUP_NAME_MAX_LEN: usize = 64; + +/// 管理会话 Cookie 名(HttpOnly + SameSite=Strict) +pub const COOKIE_NAME: &str = "sso_admin_session"; + +/// 同一 IP 在窗口内最多登录失败次数 +pub const LOGIN_MAX_FAIL: i64 = 10; +/// 登录失败计数窗口(秒) +pub const LOGIN_FAIL_TTL: i64 = 300; + +/// 默认状态目录,可被 `sso_data_dir` 指令覆盖 +pub const DEFAULT_DATA_DIR: &str = "/usr/local/nginx/data"; + +// =========================================================================== +// 共享内存键/值编码 +// =========================================================================== + +/// 键前缀:管理会话 token → 用户名 +pub const KEY_SESS_PREFIX: &[u8] = b"sess:"; +/// 键前缀:登录失败计数(按 IP) +pub const KEY_FAIL_PREFIX: &[u8] = b"fail:"; + +/// 共享内存 value 内部分隔符(ASCII US)。 +/// +/// 用户名只含 `[A-Za-z0-9_-]`,**不可能**包含该字节,所以切分是安全的。 +/// 但 SSO 会话的身份 payload 含姓名/邮箱等自由文本,那里必须改用 `\n` +/// 分隔(见 `oauth::sso_payload`)——两者不可混用。 +pub const VAL_SEP: u8 = 0x1f; + +/// 键缓冲区上限:`sess:` + 32 字节 token 的 64 位 hex 最长为 69,留足余量 +pub const KEY_BUF_LEN: usize = 128; + +// =========================================================================== +// OAuth2 / OIDC(统一认证能力) +// =========================================================================== + +/// 键前缀:SSO 终端用户会话 token → ` \n \n \n \n ` +/// +/// 字段分隔符用 `\n` 而非 `VAL_SEP`(0x1f)——后者是 value 里 payload 与 expiry 的 +/// 分隔符,用作字段分隔会让 `state::get` 切错位置。 +/// +/// 与 `sess:`(管理员会话)分开——OAuth2 的「终端用户」与「管理员」是两套身份, +/// 会话生命周期与校验逻辑都不同,混用前缀会互相踩。 +pub const KEY_OAUTH_SESS_PREFIX: &[u8] = b"sso:"; +/// 键前缀:授权码(随机 id)→ 授权上下文 JSON(sub / client_id / scope / code_challenge 等) +/// +/// 授权码一次性:token 端点换取后即删除(`take_oauth_code`)。 +pub const KEY_OAUTH_CODE_PREFIX: &[u8] = b"oac:"; +/// 键前缀:OAuth 客户端注册表(client_id)→ 客户端 JSON(无 TTL,跟随文件生命周期) +pub const KEY_OAUTH_CLIENT_PREFIX: &[u8] = b"ocl:"; + +/// SSO 终端用户会话 Cookie 名(HttpOnly + SameSite=Lax,Domain 由 `OAUTH_COOKIE_DOMAIN` 控制) +pub const OAUTH_SESSION_COOKIE: &str = "sso_sid"; +/// SSO 会话时长(秒) +pub const OAUTH_SESSION_TTL: i64 = 8 * 3600; +/// 授权码有效期(秒)——极短,防截获重放 +pub const OAUTH_CODE_TTL: i64 = 60; +/// access_token 有效期(秒) +pub const OAUTH_ACCESS_TTL: i64 = 3600; +/// refresh_token 有效期(秒) +pub const OAUTH_REFRESH_TTL: i64 = 30 * 86400; +/// id_token 有效期(秒) +pub const OAUTH_ID_TOKEN_TTL: i64 = 3600; + +/// 签名密钥环境变量名:HS256 共用一把对称密钥。不设则启动时随机生成并打告警, +/// 重启会使所有已签发 token 失效(生产必须显式设置)。 +/// +/// v2 升级项:改为 RS256 并由 `/oauth/jwks` 暴露公钥,见 `docs/roadmap.md`。 +pub const OAUTH_SIGNING_SECRET_ENV: &str = "OAUTH_SIGNING_SECRET"; +/// 签发者(issuer)环境变量名:discovery 文档与 token 的 `iss` 用它。 +pub const OAUTH_ISSUER_ENV: &str = "OAUTH_ISSUER"; +pub const OAUTH_DEFAULT_ISSUER: &str = "http://localhost:18098"; +/// SSO Cookie 的 Domain(跨主机单点登录用,如 `.yourdomain.com`)。 +/// 留空则 Cookie 绑定签发主机;同域多子站共享 SSO 时必须设成带点的父域。 +pub const OAUTH_COOKIE_DOMAIN_ENV: &str = "OAUTH_COOKIE_DOMAIN"; + +/// 支持的 scope(openid 是 OIDC 必备) +pub const OAUTH_SCOPES_SUPPORTED: &[&str] = &["openid", "profile", "email", "address", "phone"]; +/// 支持的 PKCE 挑战方法(S256 优先,plain 仅兼容遗留客户端) +pub const OAUTH_CODE_CHALLENGE_METHODS: &[&str] = &["S256", "plain"]; + +/// IAP 重新签发 access_token 时用的 `aud`(下游资源服据此判断令牌来源)。 +pub const IAP_TOKEN_AUDIENCE: &str = "sso-gateway"; +/// IAP 重新签发 access_token 时用的 scope。 +pub const IAP_TOKEN_SCOPE: &str = "openid profile email"; diff --git a/source/rust/src/http.rs b/source/rust/src/http.rs new file mode 100644 index 0000000..d9ff834 --- /dev/null +++ b/source/rust/src/http.rs @@ -0,0 +1,205 @@ +//! 请求/响应辅助:参数解析、请求体读取、JSON 响应输出。 +//! +//! 这一层承担旧版 `util.params` / `util.respond` 的职责,但有一处本质差异: +//! **ngx crate 没有暴露请求体读取**,必须直接走 +//! `ngx_http_read_client_request_body` 的两段式异步接口。 + +use std::collections::HashMap; +use std::ptr; + +use ngx::core::{Buffer, Status}; +use ngx::ffi::{ngx_chain_t, ngx_http_request_t}; +use ngx::http::{HTTPStatus, Request}; +use serde_json::{Value, json}; + +use crate::util; + +// =========================================================================== +// 取请求信息 +// =========================================================================== + +pub fn uri(r: *mut ngx_http_request_t) -> String { + // SAFETY: r 由 nginx 保证有效;uri 是请求内存池中的字符串 + unsafe { String::from_utf8_lossy((*r).uri.as_bytes()).into_owned() } +} + +/// HTTP 方法名。直接读 nginx 已解析好的 `method_name`, +/// 避免依赖 Method 枚举的全部变体名(少一个就编译不过)。 +pub fn method_str(r: *mut ngx_http_request_t) -> String { + // SAFETY: 同上 + unsafe { String::from_utf8_lossy((*r).method_name.as_bytes()).into_owned() } +} + +pub fn args_raw(r: *mut ngx_http_request_t) -> Vec { + // SAFETY: 同上 + unsafe { (*r).args.as_bytes().to_vec() } +} + +/// 请求头(大小写不敏感) +pub fn header(r: *mut ngx_http_request_t, name: &str) -> Option { + // SAFETY: 迭代器只在本函数存续期内使用 + let request = unsafe { Request::from_ngx_http_request(r) }; + for (k, v) in request.headers_in_iterator() { + if k.as_bytes().eq_ignore_ascii_case(name.as_bytes()) { + return Some(String::from_utf8_lossy(v.as_bytes()).into_owned()); + } + } + None +} + +/// 客户端地址(登录限速的分组键) +pub fn remote_addr(r: *mut ngx_http_request_t) -> String { + // SAFETY: r 有效;connection 在请求生命周期内必然存在 + unsafe { + let conn = (*r).connection; + if conn.is_null() { + return "-".to_owned(); + } + String::from_utf8_lossy((*conn).addr_text.as_bytes()).into_owned() + } +} + +// =========================================================================== +// 请求体 +// =========================================================================== + +/// 收集已读入的请求体。 +/// +/// **调用前提**:本函数只应在 `ngx_http_read_client_request_body` 的 +/// post_handler 里调用(见 `api::read_body_then`)。 +/// +/// 请求体可能跨越多个 `ngx_buf_t`(chain)。被刷写到临时文件的大请求体 +/// 这里直接忽略——管理台 API 的请求体都是几百字节的小 JSON, +/// 且管理 server 已把 `client_body_buffer_size` 调到 1m 覆盖边界。 +pub unsafe fn collect_body(r: *mut ngx_http_request_t) -> Vec { + let mut out = Vec::new(); + + let rb = unsafe { (*r).request_body }; + if rb.is_null() { + return out; + } + + let mut chain = unsafe { (*rb).bufs }; + while !chain.is_null() { + // SAFETY: chain 由 nginx 构建,节点与 buf 均有效 + unsafe { + let buf = (*chain).buf; + if !buf.is_null() && (*buf).in_file() == 0 { + let (pos, last) = ((*buf).pos, (*buf).last); + if !pos.is_null() && !last.is_null() && last > pos { + let len = last.offset_from(pos) as usize; + out.extend_from_slice(std::slice::from_raw_parts(pos, len)); + } + } + chain = (*chain).next; + } + } + out +} + +/// 合并 query string 与请求体参数。 +/// +/// 优先级与旧版一致:**请求体覆盖 query**(同名时以 body 为准)。 +pub fn params(r: *mut ngx_http_request_t) -> HashMap { + let mut map = HashMap::new(); + + for (k, v) in util::parse_kv(&args_raw(r)) { + map.insert(k, v); + } + + let body = unsafe { collect_body(r) }; + if body.is_empty() { + return map; + } + + let ctype = header(r, "content-type").unwrap_or_default(); + if ctype.to_ascii_lowercase().contains("application/json") { + if let Ok(Value::Object(obj)) = serde_json::from_slice::(&body) { + for (k, v) in obj { + let s = match v { + Value::String(s) => s, + Value::Number(n) => n.to_string(), + Value::Bool(b) => b.to_string(), + _ => continue, + }; + map.insert(k, s); + } + } + } else { + for (k, v) in util::parse_kv(&body) { + map.insert(k, v); + } + } + + map +} + +// =========================================================================== +// 响应 +// =========================================================================== + +/// 发送 JSON 响应体(含额外响应头,如 Set-Cookie)。 +/// +/// `body` 的字节会被复制进 nginx 的请求内存池,随请求自动回收。 +pub fn send_with( + r: *mut ngx_http_request_t, + status: HTTPStatus, + body: &str, + extra_headers: &[(&str, &str)], +) -> Status { + // SAFETY: r 有效 + unsafe { + let request = Request::from_ngx_http_request(r); + let pool = request.pool(); + + let mut buf = match pool.create_buffer_from_str(body) { + Some(b) => b, + None => return Status::NGX_ERROR, + }; + buf.set_last_buf(true); + + let mut chain = ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: ptr::null_mut() }; + + request.set_status(status); + request.add_header_out("Content-Type", "application/json; charset=utf-8"); + request.add_header_out("Cache-Control", "no-store"); + for (name, value) in extra_headers { + request.add_header_out(name, value); + } + request.set_content_length_n(body.len()); + + let st = request.send_header(); + if st != Status::NGX_OK { + return st; + } + request.output_filter(&mut chain) + } +} + +pub fn send(r: *mut ngx_http_request_t, status: HTTPStatus, body: &str) -> Status { + send_with(r, status, body, &[]) +} + +/// 统一成功响应:`{code:200, msg, data}` +pub fn ok(r: *mut ngx_http_request_t, data: Value, msg: &str) -> Status { + let body = json!({ "code": 200, "msg": msg, "data": data }).to_string(); + send(r, HTTPStatus::OK, &body) +} + +pub fn ok_with( + r: *mut ngx_http_request_t, + data: Value, + msg: &str, + extra_headers: &[(&str, &str)], +) -> Status { + let body = json!({ "code": 200, "msg": msg, "data": data }).to_string(); + send_with(r, HTTPStatus::OK, &body, extra_headers) +} + +/// 统一失败响应:`{code:, msg}`(与旧版 `util.fail` 一致) +pub fn fail(r: *mut ngx_http_request_t, status: HTTPStatus, msg: &str) -> Status { + // HTTPStatus 是 newtype(`pub struct HTTPStatus(pub ngx_uint_t)`),直接取内层值 + let code = status.0 as u16; + let body = json!({ "code": code, "msg": msg }).to_string(); + send(r, status, &body) +} diff --git a/source/rust/src/lib.rs b/source/rust/src/lib.rs new file mode 100644 index 0000000..892f63d --- /dev/null +++ b/source/rust/src/lib.rs @@ -0,0 +1,498 @@ +//! SSO 统一认证网关 —— nginx + Rust 动态模块。 +//! +//! 本模块把 nginx 变成一台**自带 IdP 的身份感知代理**: +//! +//! | 能力 | 阶段 | 开关 | 说明 | +//! | --- | --- | --- | --- | +//! | OAuth2 / OIDC 授权服务器 | content | `sso_api` | 本网关自己签发令牌,不依赖外部 IdP | +//! | IAP 身份感知代理 | access | `sso_iap` | 转发前判定身份并注入 `X-Auth-*` | +//! | 管理 API | content | `sso_api` | 账号 / 接入方 / 服务发现 | +//! +//! ## 与「网关」类项目的定位差异 +//! +//! 本项目自 iPass 网关剥离而来,但**定位是身份层,不是流量层**: +//! 它不做动态域名转发、不做 LLM 上游代理、不做用量计费,只回答两个问题—— +//! 「你是谁」(认证)与「把这个身份告诉后端」(授权上下文传递)。 +//! 因此这里没有 `$proxy_backend_addr` 这类动态上游变量, +//! 后端地址由 nginx 配置写死(或由运维按环境生成)。 +//! +//! ## 关键实现约束(均为实测/查证确认,详见 CLAUDE.md) +//! +//! * `ngx_http_add_variable` 必须在 **preconfiguration** 阶段调用, +//! 否则配置里的 `proxy_set_header X-Auth-User $auth_user` 无法解析。 +//! * 阶段处理器在 postconfiguration 阶段注册,且**必须按 location 开关** +//! (`sso_api` / `sso_iap`),否则管理台与 IdP 端点也会被 IAP 门禁 401 掉。 +//! * 注入变量**不能**标 `NGX_HTTP_VAR_NOCACHEABLE`:标了以后 +//! `ngx_http_get_flushed_variable` 每次读取都会清缓存并回调 get_handler, +//! 而 handler 无从拿到注入值 → 变量读成空。 +//! * 共享内存只有 `RwLock, _>` 一种安全形态; +//! `SlabPool` 只能在 zone 初始化回调里取出,锁本身也必须用 +//! `ngx::allocator::allocate` 放进共享内存,否则各 worker 拿到的是各自的副本。 +//! * ngx crate **没有**暴露请求体读取,必须走 +//! `ngx_http_read_client_request_body` 的两段式异步接口(见 `ApiHandler`)。 + +mod api; +mod config; +mod http; +mod models; +mod oauth; +mod oauth_clients; +mod session; +mod state; +mod store; +mod util; +mod users; + +use core::ffi::{c_char, c_void}; +use core::ptr; +use core::sync::atomic::{AtomicUsize, Ordering}; +use std::ffi::CString; + +use ngx::core::{NGX_CONF_ERROR, NGX_CONF_OK, Pool, Status}; +use ngx::ffi::{ + NGX_CONF_TAKE1, NGX_CONF_TAKE2, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MAIN_CONF, + NGX_HTTP_MAIN_CONF_OFFSET, NGX_HTTP_MODULE, NGX_HTTP_VAR_CHANGEABLE, NGX_LOG_EMERG, + ngx_command_t, ngx_conf_t, ngx_cycle_t, ngx_http_add_variable, ngx_http_get_variable_index, + ngx_http_module_t, ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t, ngx_module_t, + ngx_parse_size, ngx_shared_memory_add, ngx_shm_zone_t, ngx_str_t, ngx_uint_t, +}; +use ngx::http::{ + HTTPStatus, HttpModule, HttpModuleLocationConf, HttpPhase, HttpRequestHandler, Merge, + MergeConfigError, +}; +use ngx::{ngx_conf_log_error, ngx_string}; + +/// IAP 注入变量 `$auth_user/$auth_email/$auth_groups/$auth_sub/$auth_token` 的下标。 +/// +/// 顺序固定对应 `AUTH_VAR_NAMES`,与 `set_auth_vars` 一一对应。 +static AUTH_VAR_INDEX: [AtomicUsize; 5] = [ + AtomicUsize::new(usize::MAX), + AtomicUsize::new(usize::MAX), + AtomicUsize::new(usize::MAX), + AtomicUsize::new(usize::MAX), + AtomicUsize::new(usize::MAX), +]; +static AUTH_VAR_NAMES: [&str; 5] = + ["auth_user", "auth_email", "auth_groups", "auth_sub", "auth_token"]; + +// =========================================================================== +// 阶段处理器 +// =========================================================================== + +/// OAuth2 身份感知代理(IAP)热路径:access 阶段完成「门禁 + 身份注入」。 +/// +/// 与 MaxKey / OAuth2 Proxy 同构——网关在转发前判定身份,并把身份写进 +/// `$auth_*` 变量,下游 `proxy_set_header X-Auth-*` 据此注入(后端只信网关, +/// 客户端伪装的同名头被覆盖)。无有效身份时返回 401,由 nginx `error_page` +/// 内部跳转 `@oauth_login` 完成登录重定向(见 conf/*.conf),与模块解耦。 +struct IapHandler; + +impl HttpRequestHandler for IapHandler { + const PHASE: HttpPhase = HttpPhase::Access; + type Output = Status; + + fn handler(request: &mut ngx::http::Request) -> Self::Output { + if !Module::location_conf(request).map(|c| c.iap).unwrap_or(false) { + return Status::NGX_DECLINED; + } + + let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t; + + match oauth::iap_identity(r) { + Some((user, email, groups, sub, token)) => { + let vals = [user, email, groups, sub, token]; + set_auth_vars(r, &vals); + Status::NGX_DECLINED + } + None => { + // 无身份:返回 401,带 login 提示;浏览器由 error_page 跳登录页, + // API 客户端按 WWW-Authenticate 走 Bearer / 登录换码。 + let login = format!("{}/login", oauth::issuer()); + request.add_header_out( + "WWW-Authenticate", + &format!("Bearer realm=\"sso\", login=\"{login}\""), + ); + HTTPStatus::UNAUTHORIZED.into() + } + } + } +} + +/// 把身份写入 `$auth_user/$auth_email/$auth_groups/$auth_sub/$auth_token`, +/// 供 `proxy_set_header X-Auth-*` 求值时取到。 +fn set_auth_vars(r: *mut ngx_http_request_t, vals: &[String; 5]) { + for i in 0..5 { + let idx = AUTH_VAR_INDEX[i].load(Ordering::SeqCst); + if idx == usize::MAX { + continue; + } + // SAFETY: idx 由 ngx_http_get_variable_index 分配且在 r->variables 内; + // 值分配在请求池,随请求回收。 + unsafe { + let pool = Pool::from_ngx_pool((*r).pool); + let bytes = vals[i].as_bytes(); + let data = pool.alloc(bytes.len()) as *mut u8; + if data.is_null() { + continue; + } + ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len()); + let vv: *mut ngx_http_variable_value_t = (*r).variables.add(idx); + (*vv).data = data; + (*vv).set_len(bytes.len() as _); + (*vv).set_valid(1); + (*vv).set_not_found(0); + // 必须为 0:变量定义侧也刻意不含 NGX_HTTP_VAR_NOCACHEABLE, + // 保证 content 阶段读取时直接命中缓存,不回落到 auth_var_get + // (回调拿不到注入值,会把变量读成空)。 + (*vv).set_no_cacheable(0); + } + } +} + +/// 管理 API / OAuth 端点:content 阶段先读请求体,读完后交给 `api::dispatch`。 +/// +/// 这是本项目唯一需要异步的地方。`ngx_http_read_client_request_body` 是 +/// **两段式**接口:请求体已在缓冲区时会**同步**调用 post_handler, +/// 否则挂起等 socket 事件后回调。两条路径都必须正确,所以不能假设 +/// 「回调一定晚于本次返回」。 +struct ApiHandler; + +impl HttpRequestHandler for ApiHandler { + const PHASE: HttpPhase = HttpPhase::Content; + type Output = Status; + + fn handler(request: &mut ngx::http::Request) -> Self::Output { + if !Module::location_conf(request).map(|c| c.api).unwrap_or(false) { + return Status::NGX_DECLINED; + } + + let r: *mut ngx_http_request_t = request.as_mut() as *mut ngx_http_request_t; + + // SAFETY: r 有效;回调只会在请求内存池存活期间被调用 + let rc = unsafe { nginx_sys::ngx_http_read_client_request_body(r, Some(api_body_ready)) }; + + // 读体失败(请求体超限等):把原始状态码交回 nginx,由它生成对应错误页 + if rc >= nginx_sys::NGX_HTTP_SPECIAL_RESPONSE as ngx_int_t { + return Status(rc); + } + + // 响应由回调发出,本阶段到此挂起 + Status::NGX_DONE + } +} + +/// 请求体就绪回调:执行路由分发并终结请求。 +unsafe extern "C" fn api_body_ready(r: *mut ngx_http_request_t) { + let status = api::dispatch(r); + // SAFETY: r 由 nginx 传入且仍然有效;NGX_OK 表示响应已完整发出 + unsafe { nginx_sys::ngx_http_finalize_request(r, status.0) }; +} + +// =========================================================================== +// 模块定义 +// =========================================================================== + +struct Module; + +/// 按 location 生效的开关。 +/// +/// 必须存在:阶段处理器注册在 http 主配置上,若不按 location 收敛, +/// 管理台与 IdP 端点也会走 IAP 门禁并被 401。 +#[derive(Debug, Default)] +struct ModuleConfig { + /// 该 location 暴露管理 API 与 OAuth 端点(`/api/*`、`/oauth/*`、`/login`) + api: bool, + /// 该 location 开启 OAuth2 身份感知代理(IAP):未登录 → 跳转登录 / 401, + /// 已登录 → 注入 `$auth_*` 变量由 `proxy_set_header` 转成 `X-Auth-*` 头。 + iap: bool, +} + +unsafe impl HttpModuleLocationConf for Module { + type LocationConf = ModuleConfig; +} + +impl Merge for ModuleConfig { + fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> { + if prev.api { + self.api = true; + } + if prev.iap { + self.iap = true; + } + Ok(()) + } +} + +/// 注册 IAP 注入变量(运行时名,需手动构造 `ngx_str_t`)。 +/// +/// 必须在配置解析前注册,否则 `proxy_set_header X-Auth-User $auth_user` 无法解析。 +unsafe fn register_auth_vars(cf: *mut ngx_conf_t) -> bool { + let cf = &mut *cf; + for i in 0..AUTH_VAR_NAMES.len() { + let name = AUTH_VAR_NAMES[i]; + let c = match CString::new(name) { + Ok(c) => c, + Err(_) => return false, + }; + let mut ns = ngx_str_t { + len: name.len() as ngx_uint_t, + data: c.as_ptr() as *mut u8, + }; + + // 1) 先登记变量名 + get_handler。只调 ngx_http_get_variable_index 是 + // 不够的:它会往 cmcf->variables 里推一项(get_handler=NULL),而 + // nginx 的 ngx_http_variables_init_vars 随后要求每个这样的名字都能在 + // cmcf->variables_keys(由 ngx_http_add_variable 填充)里找到 handler, + // 否则启动即 EMERG `unknown "auth_user" variable`。 + // + // 刻意**不加** NGX_HTTP_VAR_NOCACHEABLE,理由见 `set_auth_vars`。 + let var = + unsafe { ngx_http_add_variable(cf, &mut ns, NGX_HTTP_VAR_CHANGEABLE as ngx_uint_t) }; + if var.is_null() { + return false; + } + // SAFETY: var 非空且由本函数独占初始化 + unsafe { + (*var).get_handler = Some(auth_var_get); + (*var).set_handler = None; + (*var).data = 0; + } + + // 2) 取写入槽位下标(IAP 热路径直接写 r->variables[idx],见 set_auth_vars) + let idx = unsafe { ngx_http_get_variable_index(cf, &mut ns) }; + if idx == -1 { + return false; + } + AUTH_VAR_INDEX[i].store(idx as usize, Ordering::SeqCst); + } + true +} + +/// `$auth_*` 的兜底 get_handler:IAP 未注入时返回 DECLINED(等价于空变量)。 +/// +/// 正常路径下永不被调用——IAP 已在 access 阶段把 `r->variables[idx]` 标为 +/// valid(见 `set_auth_vars`),读取时走缓存短路。此函数只为满足 +/// `ngx_http_variables_init_vars` 对「已登记变量必须有 handler」的硬性要求。 +extern "C" fn auth_var_get( + _r: *mut ngx_http_request_t, + _v: *mut ngx_http_variable_value_t, + _data: usize, +) -> ngx_int_t { + Status::NGX_DECLINED.into() +} + +impl HttpModule for Module { + fn module() -> &'static ngx_module_t { + // SAFETY: 模块定义是静态的,生命周期贯穿进程 + unsafe { &*ptr::addr_of!(ngx_http_sso_module) } + } + + /// 必须在配置解析前注册变量,否则 `proxy_set_header X-Auth-User $auth_user` 无法解析 + unsafe extern "C" fn preconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { + // IAP 注入变量:$auth_user / $auth_email / $auth_groups / $auth_sub / $auth_token + if !register_auth_vars(cf) { + ngx_conf_log_error!(NGX_LOG_EMERG, unsafe { &mut *cf }, "注册身份注入变量失败"); + return Status::NGX_ERROR.into(); + } + Status::NGX_OK.into() + } + + unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { + let cf = unsafe { &mut *cf }; + // IAP 门禁先注册:无身份直接 401(由 error_page 跳登录) + if ngx::http::add_phase_handler::(cf).is_err() { + return Status::NGX_ERROR.into(); + } + if ngx::http::add_phase_handler::(cf).is_err() { + return Status::NGX_ERROR.into(); + } + Status::NGX_OK.into() + } +} + +static mut NGX_HTTP_SSO_COMMANDS: [ngx_command_t; 5] = [ + ngx_command_t { + name: ngx_string!("sso_state"), + type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t, + set: Some(set_state_zone), + conf: NGX_HTTP_MAIN_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("sso_data_dir"), + type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(set_data_dir), + conf: NGX_HTTP_MAIN_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("sso_api"), + type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(set_flag_api), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("sso_iap"), + type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(set_flag_iap), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t::empty(), +]; + +static NGX_HTTP_SSO_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { + preconfiguration: Some(Module::preconfiguration), + postconfiguration: Some(Module::postconfiguration), + create_main_conf: None, + init_main_conf: None, + create_srv_conf: None, + merge_srv_conf: None, + create_loc_conf: Some(Module::create_loc_conf), + merge_loc_conf: Some(Module::merge_loc_conf), +}; + +// 脱离 nginx 构建系统、单独产出 cdylib 时必须靠这个宏导出 ngx_modules 表 +#[cfg(feature = "export-modules")] +ngx::ngx_modules!(ngx_http_sso_module); + +#[used] +#[allow(non_upper_case_globals)] +pub static mut ngx_http_sso_module: ngx_module_t = ngx_module_t { + ctx: &raw const NGX_HTTP_SSO_MODULE_CTX as _, + commands: unsafe { &raw mut NGX_HTTP_SSO_COMMANDS[0] }, + type_: NGX_HTTP_MODULE as _, + init_process: Some(init_process), + ..ngx_module_t::default() +}; + +/// 每个 worker 启动后执行一次。管理员播种是**幂等**的: +/// 文件里已有任何账号就直接跳过,所以多 worker 同时跑不会重复创建。 +unsafe extern "C" fn init_process(_cycle: *mut ngx_cycle_t) -> ngx_int_t { + match users::seed_admin() { + Ok(true) => util::log_warn( + "[sso] 已创建初始管理员 admin,请首次登录后立即修改密码", + ), + Ok(false) => {} + Err(e) => util::log_err(&format!("[sso] 初始化管理员失败: {e}")), + } + Status::NGX_OK.into() +} + +// =========================================================================== +// 指令处理 +// =========================================================================== + +/// 读第 2 个参数并转成 bool(on/off/1/0/yes/no)。 +unsafe fn arg_flag(cf: *mut ngx_conf_t, idx: usize) -> Option { + let cf_ref = unsafe { cf.as_mut() }?; + let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() }; + let raw = args.get(idx)?.as_bytes(); + let s = core::str::from_utf8(raw).ok()?; + Some(matches!(s.to_ascii_lowercase().as_str(), "on" | "1" | "true" | "yes")) +} + +extern "C" fn set_flag_api( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + let Some(flag) = (unsafe { arg_flag(cf, 1) }) else { + return NGX_CONF_ERROR; + }; + // SAFETY: nginx 保证 conf 指向本模块的 loc conf 结构 + unsafe { (*(conf as *mut ModuleConfig)).api = flag }; + NGX_CONF_OK +} + +extern "C" fn set_flag_iap( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + let Some(flag) = (unsafe { arg_flag(cf, 1) }) else { + return NGX_CONF_ERROR; + }; + // SAFETY: 同上 + unsafe { (*(conf as *mut ModuleConfig)).iap = flag }; + NGX_CONF_OK +} + +extern "C" fn set_state_zone( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + _conf: *mut c_void, +) -> *mut c_char { + // SAFETY: 配置回调必然拿到有效的 cf + let cf_ref = unsafe { cf.as_mut().unwrap() }; + let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() }; + + let mut name: ngx_str_t = args[1]; + let size = unsafe { ngx_parse_size(&raw mut args[2]) }; + if size == -1 { + ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "sso_state: 共享内存大小非法"); + return NGX_CONF_ERROR; + } + + let zone = unsafe { + ngx_shared_memory_add( + cf, + &raw mut name, + size as usize, + (&raw mut ngx_http_sso_module).cast(), + ) + }; + if zone.is_null() { + return NGX_CONF_ERROR; + } + + unsafe { + (*zone).init = Some(state_zone_init); + } + state::set_zone(zone); + NGX_CONF_OK +} + +/// 共享内存初始化:由 nginx 在 **fork 之前**调用一次。 +/// +/// 在这里把接入方注册表装载进 `ocl:`,所有 worker 直接共享结果——比放在 +/// `init_process`(每个 worker 各跑一遍)省掉 N-1 次文件读与 JSON 解析。 +extern "C" fn state_zone_init(zone: *mut ngx_shm_zone_t, _data: *mut c_void) -> ngx_int_t { + let status = state::init_zone(zone); + if status != Status::NGX_OK { + return status.into(); + } + + // OAuth2 客户端注册表进 `ocl:`——第三方应用发起授权前必须可读到。 + // 未命中即 404/invalid_client,没有回源兜底(写穿语义见 oauth_clients)。 + let clients = oauth_clients::reload_shm(); + util::log_notice(&format!("[sso] 已装载 {clients} 个 OAuth2 接入方")); + + Status::NGX_OK.into() +} + +extern "C" fn set_data_dir( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + _conf: *mut c_void, +) -> *mut c_char { + // SAFETY: 配置回调必然拿到有效的 cf + let cf_ref = unsafe { cf.as_mut().unwrap() }; + let args: &mut [ngx_str_t] = unsafe { (*cf_ref.args).as_slice_mut() }; + + match core::str::from_utf8(args[1].as_bytes()) { + Ok(dir) => { + store::set_data_dir(dir); + NGX_CONF_OK + } + Err(_) => { + ngx_conf_log_error!(NGX_LOG_EMERG, cf_ref, "sso_data_dir: 路径不是合法 UTF-8"); + NGX_CONF_ERROR + } + } +} diff --git a/source/rust/src/models.rs b/source/rust/src/models.rs new file mode 100644 index 0000000..2441df4 --- /dev/null +++ b/source/rust/src/models.rs @@ -0,0 +1,163 @@ +//! 持久化数据模型。 +//! +//! 字段名与来源项目(iPass)的 `users.json` / `oauth_clients.json` +//! **逐字对应**,以便直接接管存量账号与接入方登记,管理台前端也无需改字段。 + +use serde::{Deserialize, Deserializer, Serialize}; +use std::collections::BTreeMap; + +/// 账号表(`users.json`):以账号名为 key 的对象。 +pub type UserTable = BTreeMap; + +/// 单个账号。 +/// +/// 统一认证场景下,账号同时承载两层含义: +/// * **认证凭据**——`salt` / `pwd_hash`(登录)、`api_key`(机器调用); +/// * **身份声明**——`display_name` / `email` / `department` / `groups`, +/// 它们原样进入 OIDC claims 与 IAP 注入的 `X-Auth-*` 头, +/// 是下游系统做授权判断的依据(因此必须是可维护数据,不能写死在代码里)。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct User { + pub username: String, + /// 中文姓名等展示名。**只用于展示**,不参与鉴权、不参与热路径查询。 + /// + /// `username` 规则是 ASCII,中文名塞不进账号名,所以「张三」这类实名单独放 + /// 这里;留空时前端与 claims 回落到 `username`。 + #[serde(default)] + pub display_name: String, + /// `admin` | `user` + #[serde(default = "default_role")] + pub role: String, + pub salt: String, + /// 迭代加盐 SHA-256 + pub pwd_hash: String, + /// `sk_<48 位 hex>`:账号级机器凭据(`X-API-Key`)。 + /// + /// 面向脚本/CI 这类不方便走浏览器登录的调用方,用于账号态接口(`/api/v1/*`)。 + #[serde(default)] + pub api_key: String, + // ---- 统一认证身份字段(OAuth2 / OIDC 终端用户声明)---- + /// 用户邮箱(OIDC `email` 声明;userinfo / 注入头 `X-Auth-Email`) + #[serde(default)] + pub email: String, + /// 所属部门(注入头所需;OIDC 非标声明 `department`) + #[serde(default)] + pub department: String, + /// 用户组 / 角色集合(OIDC `groups`;注入头 `X-Auth-Groups` 为逗号串)。 + /// + /// 反序列化接受两种写法:JSON 数组 `["rd","eng"]`,以及逗号分隔字符串 + /// `"rd,eng"`。后者是外部目录(MaxKey / Excel)导出时的常见形状, + /// 只认数组会让整张 users.json 反序列化失败 → 表现为「账号全部消失」。 + #[serde(default, deserialize_with = "de_groups")] + pub groups: Vec, + #[serde(default)] + pub created_at: i64, +} + +fn default_role() -> String { + "user".to_owned() +} + +/// 容忍 `["a","b"]` 与 `"a,b"` 两种写法的字段反序列化。 +fn de_groups<'de, D>(d: D) -> Result, D::Error> +where + D: Deserializer<'de>, +{ + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + List(Vec), + Csv(String), + Null, + } + Ok(match Option::::deserialize(d)? { + None | Some(Raw::Null) => Vec::new(), + Some(Raw::List(v)) => v.into_iter().map(|s| s.trim().to_owned()).filter(|s| !s.is_empty()).collect(), + Some(Raw::Csv(s)) => s + .split(|c: char| c == ',' || c == '、' || c == ';' || c == ' ') + .map(|x| x.trim().to_owned()) + .filter(|x| !x.is_empty()) + .collect(), + }) +} + +impl User { + pub fn is_admin(&self) -> bool { + self.role == "admin" + } + + /// 展示名优先,留空回落账号名。前端渲染与 OIDC `name` 共用同一规则。 + pub fn display_or_username(&self) -> String { + if self.display_name.is_empty() { + self.username.clone() + } else { + self.display_name.clone() + } + } + + /// `groups` 的逗号串(注入头与 SSO 会话 payload 用)。 + pub fn groups_csv(&self) -> String { + self.groups.join(",") + } +} + +// =========================================================================== +// OAuth2 客户端注册表(`oauth_clients.json`) +// =========================================================================== + +/// 单个 OAuth2 / OIDC 客户端(第三方应用)。 +/// +/// 对应 MaxKey 的 `application` / Authz 的 `client`。第三方应用拿 `client_id` + +/// `client_secret`(机密客户端)走标准 OAuth2 流程对接本网关,无需关心底层用户存储。 +#[derive(Debug, Clone, Serialize, Deserialize, Default)] +pub struct OAuthClient { + /// 客户端标识(如 `grafana`、`crm-web`)。作为注册表键与 token 的 `aud`。 + pub client_id: String, + /// 客户端密钥(机密客户端校验用)。公开客户端(SPA / 原生 App)恒为空。 + #[serde(default)] + pub client_secret: String, + /// 展示名 + #[serde(default)] + pub name: String, + /// 允许的回调地址(授权码重定向目标),注册时收紧以防开放重定向。 + #[serde(default)] + pub redirect_uris: Vec, + /// 允许的授权类型:`authorization_code` / `refresh_token` / `client_credentials` / `password` + #[serde(default)] + pub grant_types: Vec, + /// 允许的 scope 白名单(必须覆盖 `openid` 才发 id_token) + #[serde(default)] + pub scopes: Vec, + /// 是否机密客户端:true 要求 `client_secret`;false 走 PKCE(S256)即可。 + #[serde(default = "default_true")] + pub confidential: bool, + #[serde(default)] + pub created_at: i64, +} + +fn default_true() -> bool { + true +} + +/// 客户端注册表:数组存储,便于全量装载进共享内存。 +pub type OAuthClientTable = Vec; + +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) + } +} diff --git a/source/rust/src/oauth.rs b/source/rust/src/oauth.rs new file mode 100644 index 0000000..15e0449 --- /dev/null +++ b/source/rust/src/oauth.rs @@ -0,0 +1,1108 @@ +//! OAuth2 / OIDC 授权服务器(本项目就是 IdP)。 +//! +//! 本协议层**对齐 MaxKey 的 OAuth2 实现**(端点命名、grant type、scope、claims), +//! 但**完全不依赖 MaxKey 运行时**——第三方应用按标准 OAuth2 / OIDC 流程对接即可, +//! 照抄 MaxKey 文档配好的应用也能零改造切过来(见 `api.rs` 的端点别名)。 +//! +//! 端点(均走 `sso_api` content 阶段,公开无管理员态): +//! +//! | 端点 | 方法 | 说明 | +//! | --- | --- | --- | +//! | `/oauth/authorize` | GET | 授权码流程入口(浏览器) | +//! | `/oauth/token` | POST | 换发 access_token / id_token / refresh_token | +//! | `/oauth/userinfo` | GET | Bearer token → 用户声明 | +//! | `/oauth/introspect` | POST | RFC 7662 令牌自省(IAP / 资源服校验用) | +//! | `/.well-known/openid-configuration` | GET | OIDC discovery | +//! | `/login` | GET/POST | SSO 登录页(建立 `sso_sid` 会话) | +//! | `/oauth/logout` | GET/POST | 销毁 SSO 会话 | +//! +//! 令牌格式:**HS256 签名 JWT**(对称密钥取自 `OAUTH_SIGNING_SECRET`)。零新增 +//! 依赖——HMAC-SHA256 用现成的 `sha2`,base64url 自实现。多 worker 无共享状态也能 +//! 验证(契合「无数据库」哲学)。 +//! +//! > ⚠️ **已知限制**:HS256 是对称签名,第三方无法本地验签(必须回源调 +//! > `/oauth/introspect`,或拿 `client_secret` 当密钥)。升级 RS256 + `/oauth/jwks` +//! > 是既定 v2 项,见 `docs/roadmap.md`。 +//! +//! ## 两类身份,两套会话,不可混用 +//! +//! * **终端用户**(OAuth2 主体):`sso:` 前缀 + `sso_sid` Cookie, +//! 生命周期由 `OAUTH_SESSION_TTL` 控制,供授权码流程与 IAP 使用; +//! * **管理员**(管理台主体):`sess:` 前缀 + `sso_admin_session` Cookie, +//! 见 `session` 模块。 +//! +//! 把两者合成一套会让「登录管理台 = 具备 SSO 身份」,权限边界直接消失。 + +use std::sync::OnceLock; + +use sha2::{Digest, Sha256}; +use serde_json::{Value, json}; + +use ngx::core::{Buffer, Status}; +use ngx::ffi::ngx_http_request_t; +use ngx::http::HTTPStatus; + +use crate::config::{ + IAP_TOKEN_AUDIENCE, IAP_TOKEN_SCOPE, OAUTH_ACCESS_TTL, OAUTH_CODE_CHALLENGE_METHODS, + OAUTH_CODE_TTL, OAUTH_COOKIE_DOMAIN_ENV, OAUTH_DEFAULT_ISSUER, OAUTH_ID_TOKEN_TTL, + OAUTH_ISSUER_ENV, OAUTH_REFRESH_TTL, OAUTH_SESSION_COOKIE, OAUTH_SESSION_TTL, + OAUTH_SIGNING_SECRET_ENV, +}; +use crate::http; +use crate::models::User; +use crate::oauth_clients; +use crate::state; +use crate::users; +use crate::util; + +// =========================================================================== +// 配置(环境变量,启动时固化) +// =========================================================================== + +static SECRET: OnceLock = OnceLock::new(); +static ISSUER: OnceLock = OnceLock::new(); + +/// HS256 对称密钥。未设置则随机生成并告警(重启使旧 token 失效)。 +fn signing_secret() -> String { + SECRET + .get_or_init(|| match std::env::var(OAUTH_SIGNING_SECRET_ENV) { + Ok(s) if !s.is_empty() => s, + _ => { + let g = util::rand_hex(32); + util::log_warn(&format!( + "[oauth] 未设置 {OAUTH_SIGNING_SECRET_ENV},临时随机密钥(重启后已签发 token 失效):{}…", + &g[..8] + )); + g + } + }) + .clone() +} + +/// 签发者(issuer),discovery 与 token `iss` 用它。 +pub(crate) fn issuer() -> String { + ISSUER + .get_or_init(|| { + std::env::var(OAUTH_ISSUER_ENV).unwrap_or_else(|_| OAUTH_DEFAULT_ISSUER.to_owned()) + }) + .clone() +} + +/// SSO Cookie 的 Domain(跨主机单点登录用,如 `.yourdomain.com`)。 +/// +/// 留空则 Cookie 绑定签发主机——同域多子站共享 SSO 时必须设成带点的父域, +/// 否则 `app.a.com` 拿不到 `sso.a.com` 登录时下发的 Cookie,表现为「登录了但一直 +/// 被弹回登录页」(重定向循环)。 +fn cookie_domain() -> String { + std::env::var(OAUTH_COOKIE_DOMAIN_ENV).unwrap_or_default() +} + +// =========================================================================== +// base64url + HMAC-SHA256(零新增依赖) +// =========================================================================== + +fn b64url_encode(input: &[u8]) -> String { + const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let mut out = String::with_capacity((input.len() + 2) / 3 * 4); + let mut i = 0; + while i + 3 <= input.len() { + let n = u32::from_be_bytes([input[i], input[i + 1], input[i + 2], 0]); + out.push(T[((n >> 26) & 0x3f) as usize] as char); + out.push(T[((n >> 20) & 0x3f) as usize] as char); + out.push(T[((n >> 14) & 0x3f) as usize] as char); + out.push(T[((n >> 8) & 0x3f) as usize] as char); + i += 3; + } + let rem = input.len() - i; + if rem == 1 { + let n = input[i] as u32; + out.push(T[((n >> 2) & 0x3f) as usize] as char); + out.push(T[((n << 4) & 0x3f) as usize] as char); + } else if rem == 2 { + let n = ((input[i] as u32) << 8) | input[i + 1] as u32; + out.push(T[((n >> 10) & 0x3f) as usize] as char); + out.push(T[((n >> 4) & 0x3f) as usize] as char); + out.push(T[((n << 2) & 0x3f) as usize] as char); + } + out +} + +fn b64url_decode(input: &str) -> Option> { + let mut buf: Vec = Vec::with_capacity(input.len()); + for c in input.chars() { + let v = match c { + 'A'..='Z' => c as u8 - b'A', + 'a'..='z' => c as u8 - b'a' + 26, + '0'..='9' => c as u8 - b'0' + 52, + '-' => 62, + '_' => 63, + '=' | ' ' => continue, + _ => return None, + }; + buf.push(v); + } + // 6 位一组 → 8 位;buf.len()*6 必须能被 8 整除(忽略尾部不足字节) + let bits = buf.len() * 6; + let out_len = bits / 8; + let mut out = vec![0u8; out_len]; + let mut acc = 0u32; + let mut acc_bits = 0; + let mut idx = 0; + for &b in &buf { + acc = (acc << 6) | b as u32; + acc_bits += 6; + if acc_bits >= 8 { + acc_bits -= 8; + if idx < out_len { + out[idx] = ((acc >> acc_bits) & 0xff) as u8; + idx += 1; + } + } + } + Some(out) +} + +/// HMAC-SHA256(RFC 2104)。 +fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] { + const BLOCK: usize = 64; + let mut k = [0u8; BLOCK]; + if key.len() > BLOCK { + let h = Sha256::digest(key); + k[..32].copy_from_slice(&h); + } else { + k[..key.len()].copy_from_slice(key); + } + for b in k.iter_mut() { + *b ^= 0x36; + } + let mut inner = Sha256::new(); + inner.update(&k); + inner.update(data); + let inner_h = inner.finalize(); + + for b in k.iter_mut() { + *b ^= 0x36 ^ 0x5c; + } + let mut outer = Sha256::new(); + outer.update(&k); + outer.update(&inner_h); + let h = outer.finalize(); + let mut out = [0u8; 32]; + out.copy_from_slice(&h); + out +} + +/// SHA256(PKCE S256 挑战用)。 +fn sha256_raw(data: &[u8]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(data); + let d = h.finalize(); + let mut out = [0u8; 32]; + out.copy_from_slice(&d); + out +} + +// =========================================================================== +// JWT(HS256) +// =========================================================================== + +fn jwt_sign(claims: &Value) -> String { + let header = b64url_encode(br#"{"alg":"HS256","typ":"JWT"}"#); + let payload = b64url_encode(serde_json::to_string(claims).unwrap_or_default().as_bytes()); + let signing_input = format!("{header}.{payload}"); + let sig = hmac_sha256(signing_secret().as_bytes(), signing_input.as_bytes()); + let sig_b64 = b64url_encode(&sig); + format!("{signing_input}.{sig_b64}") +} + +/// 校验 HS256 签名并核对 `exp`;返回 claims(不含已过期/签名错)。 +fn jwt_verify(token: &str) -> Option { + let mut parts = token.splitn(3, '.'); + let h = parts.next()?; + let p = parts.next()?; + let s = parts.next()?; + if h.is_empty() || p.is_empty() || s.is_empty() { + return None; + } + let signing_input = format!("{h}.{p}"); + let expected = hmac_sha256(signing_secret().as_bytes(), signing_input.as_bytes()); + let got = b64url_decode(s)?; + if got.len() != expected.len() || !util::ct_eq(&util::to_hex(&got), &util::to_hex(&expected)) { + return None; + } + let payload = b64url_decode(p)?; + let claims: Value = serde_json::from_slice(&payload).ok()?; + let exp = claims.get("exp").and_then(|v| v.as_i64()).unwrap_or(i64::MAX); + if exp <= util::now() { + return None; + } + Some(claims) +} + +// =========================================================================== +// 令牌签发 +// =========================================================================== + +/// 颁发 access_token(HS256 JWT)。 +fn mint_access_token( + sub: &str, + email: &str, + name: &str, + groups: &[String], + department: &str, + client_id: &str, + scope: &str, + now: i64, +) -> String { + let claims = json!({ + "iss": issuer(), + "sub": sub, + "aud": client_id, + "client_id": client_id, + // `preferred_username` 必须是**登录账号**,不是显示名: + // 第三方系统(Grafana / 各类 SSO 对接)普遍用它做账号绑定与查找, + // 放显示名(如"爱丽丝")会导致账号匹配不上。显示名走 `name`。 + "preferred_username": sub, + "name": name, + "email": email, + "department": department, + "groups": groups, + "scope": scope, + "token_type": "access", + "iat": now, + "exp": now + OAUTH_ACCESS_TTL, + "jti": util::rand_hex(16), + }); + jwt_sign(&claims) +} + +/// 颁发 id_token(OIDC,HS256 JWT)。 +fn mint_id_token(sub: &str, email: &str, name: &str, client_id: &str, nonce: &str, now: i64) -> String { + let mut claims = json!({ + "iss": issuer(), + "sub": sub, + "aud": client_id, + "preferred_username": name, + "email": email, + "iat": now, + "exp": now + OAUTH_ID_TOKEN_TTL, + "jti": util::rand_hex(16), + }); + if !nonce.is_empty() { + claims["nonce"] = json!(nonce); + } + jwt_sign(&claims) +} + +/// 颁发 refresh_token(HS256 JWT,typ=refresh)。 +fn mint_refresh_token(sub: &str, client_id: &str, now: i64) -> String { + let claims = json!({ + "iss": issuer(), + "sub": sub, + "aud": client_id, + "client_id": client_id, + "typ": "refresh", + "iat": now, + "exp": now + OAUTH_REFRESH_TTL, + "jti": util::rand_hex(16), + }); + jwt_sign(&claims) +} + +// =========================================================================== +// SSO 会话(浏览器 IAP 用) +// =========================================================================== + +/// 构造 SSO 会话 payload:` \n \n \n \n `。 +/// 把身份平铺进共享内存,IAP 热路径只读内存、不回读 `users.json`。 +/// +/// 分隔符用 `\n`(与 `ukey:` 身份 payload 同一约定),**不能**用 `0x1f`: +/// 那是 `state::VAL_SEP`,即共享内存 value 里「payload / expiry」的分隔符, +/// 用作字段分隔会让 `state::get` 切错位置、读到的会话立刻判为无效。 +fn sso_payload(u: &User) -> String { + format!( + "{}\n{}\n{}\n{}\n{}", + u.username, + u.email, + u.groups.join(","), + u.department, + if u.display_name.is_empty() { + u.username.clone() + } else { + u.display_name.clone() + } + ) +} + +fn parse_cookie(header: Option<&str>, name: &str) -> Option { + let header = header?; + let needle = format!("{name}="); + for part in header.split(';') { + let part = part.trim(); + if let Some(v) = part.strip_prefix(&needle) { + if !v.is_empty() { + return Some(util::url_decode(v)); + } + } + } + None +} + +fn sso_cookie(token: &str, max_age: i64) -> String { + let dom = cookie_domain(); + let dom_part = if dom.is_empty() { String::new() } else { format!("; Domain={dom}") }; + format!( + "{OAUTH_SESSION_COOKIE}={token}; Path=/{dom_part}; HttpOnly; SameSite=Lax; Max-Age={max_age}" + ) +} + +// =========================================================================== +// 鉴权辅助 +// =========================================================================== + +/// 从 `Authorization: Bearer ` 取令牌。 +fn bearer_token(r: *mut ngx_http_request_t) -> Option { + let h = http::header(r, "authorization")?; + let h = h.trim(); + if let Some(t) = h.strip_prefix("Bearer ") { + Some(t.trim().to_owned()) + } else if let Some(t) = h.strip_prefix("Bearer:") { + Some(t.trim().to_owned()) + } else { + None + } +} + +/// 取访问令牌:优先 `Authorization: Bearer`,回退 `access_token` 查询/表单参数。 +/// +/// 回退分支是为 **MaxKey 互通** 准备的:MaxKey 的 userinfo 端点是 +/// `POST /api/oauth/v20/me`,令牌放在表单体里(`access_token=...`), +/// 而非标准 OIDC 的 Bearer 头。缺了这条,照抄 MaxKey 文档的应用会 401。 +fn access_token_of(r: *mut ngx_http_request_t) -> Option { + if let Some(t) = bearer_token(r) { + return Some(t); + } + let p = http::params(r); + p.get("access_token") + .map(|s| s.trim().to_owned()) + .filter(|s| !s.is_empty()) +} + +/// 校验客户端身份(confidential 需 secret,public 仅 client_id)。 +/// 返回客户端,或 None(无效)。 +fn authenticate_client(r: *mut ngx_http_request_t, body: &std::collections::HashMap) -> Option { + let mut cid = String::new(); + let mut csec = String::new(); + + // 1) Basic Authorization: client_id:client_secret + if let Some(auth) = http::header(r, "authorization") { + if let Some(b64) = auth.strip_prefix("Basic ") { + if let Some(decoded) = b64url_decode_safe(b64) { + if let Some((id, sec)) = decoded.split_once(':') { + cid = id.to_owned(); + csec = sec.to_owned(); + } + } + } + } + // 2) 表单/JSON 覆盖 + if let Some(v) = body.get("client_id") { + cid = v.clone(); + } + if let Some(v) = body.get("client_secret") { + csec = v.clone(); + } + + if cid.is_empty() { + return None; + } + let client = oauth_clients::get(&cid)?; + if client.confidential { + if csec.is_empty() || !util::ct_eq(&csec, &client.client_secret) { + util::log_warn(&format!("[oauth] 客户端 {cid} 密钥校验失败")); + return None; + } + } + Some(client) +} + +/// 宽松 base64 解码(允许标准字母表与 padding),仅供 Basic Auth。 +fn b64url_decode_safe(input: &str) -> Option { + let bytes = std_base64_decode(input)?; + String::from_utf8(bytes).ok() +} + +/// 标准 base64(+/ 字母表 + 可选 padding)→ 字节。先规整成 url-safe 再复用 `b64url_decode`。 +fn std_base64_decode(input: &str) -> Option> { + let norm: String = input.chars().map(|c| match c { '+' => '-', '/' => '_', _ => c }).collect(); + b64url_decode(&norm) +} + +// =========================================================================== +// 端点处理 +// =========================================================================== + +/// GET /oauth/authorize —— 授权码流程入口。 +pub fn authorize(r: *mut ngx_http_request_t) -> Status { + let p = http::params(r); + let client_id = p.get("client_id").cloned().unwrap_or_default(); + let redirect_uri = p.get("redirect_uri").cloned().unwrap_or_default(); + let response_type = p.get("response_type").map(String::as_str).unwrap_or("code"); + let state_param = p.get("state").cloned().unwrap_or_default(); + let scope = p.get("scope").cloned().unwrap_or_else(|| "openid".to_owned()); + let nonce = p.get("nonce").cloned().unwrap_or_default(); + let code_challenge = p.get("code_challenge").cloned().unwrap_or_default(); + let code_challenge_method = p.get("code_challenge_method").map(String::as_str).unwrap_or("plain"); + + let client = match oauth_clients::get(&client_id) { + Some(c) => c, + None => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_client", "未知 client_id"), + }; + + if !client.allows_redirect(&redirect_uri) { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_redirect_uri", "回调地址未注册"); + } + if response_type != "code" { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "unsupported_response_type", "仅支持 code"); + } + // scope 必须全部在白名单内 + for s in scope.split_whitespace() { + if !client.allows_scope(s) { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_scope", &format!("不允许的 scope: {s}")); + } + } + // PKCE:公开客户端强制 S256;机密客户端也建议 + if client.confidential && code_challenge.is_empty() { + // 机密客户端允许无 PKCE(靠 client_secret) + } else if code_challenge.is_empty() { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_request", "公开客户端必须携带 code_challenge"); + } else if !OAUTH_CODE_CHALLENGE_METHODS.contains(&code_challenge_method) { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_request", "不支持的 code_challenge_method"); + } + + // 已登录?查 SSO 会话(payload 为 `user\nemail\ngroups\ndept\nname`, + // 与 `sso_payload` / `iap_identity` 同构;这里只取首个字段即 username 作为 sub)。 + let now = util::now(); + let username = match parse_cookie(http::header(r, "cookie").as_deref(), OAUTH_SESSION_COOKIE) + .and_then(|tok| state::get_oauth_session(&tok, now)) + { + Some(payload) => payload.split('\n').next().unwrap_or("").to_owned(), + None => { + // 未登录 → 302 到登录页,登录后跳回本授权地址 + let back = current_url(r); + let loc = format!("{}/login?redirect={}", issuer(), util::url_encode(&back)); + return redirect(r, &loc); + } + }; + + // 已登录 → 发授权码(随机 id,存上下文 60s,单次使用) + let code = util::rand_hex(32); + let ctx = json!({ + "sub": username, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "nonce": nonce, + "code_challenge": code_challenge, + "code_challenge_method": code_challenge_method, + }) + .to_string(); + if !state::put_oauth_code(&code, &ctx, now + OAUTH_CODE_TTL) { + return oauth_error(r, HTTPStatus::INTERNAL_SERVER_ERROR, "server_error", "授权码存储失败"); + } + + let mut loc = format!("{redirect_uri}?code={code}"); + if !state_param.is_empty() { + loc.push_str(&format!("&state={}", util::url_encode(&state_param))); + } + redirect(r, &loc) +} + +/// POST /oauth/token —— 换发令牌。 +/// POST /oauth/token —— 换发令牌(标准端点,响应带 `{code,msg,data}` 信封)。 +pub fn token(r: *mut ngx_http_request_t) -> Status { + token_impl(r, false) +} + +/// `GET|POST /oauth/v20/token`、`/oauth2.0/accessToken` —— **MaxKey 兼容**的换发端点。 +/// +/// 与标准端的唯一差别:响应体**不套** `{code,msg,data}` 信封,直接返回 +/// `{"access_token":…,"token_type":…,"expires_in":…}`,与 MaxKey 的 +/// `/oauth/v20/token` 一致。照抄 MaxKey 文档、按顶层键取令牌的应用才能零改造跑通。 +/// +/// 鉴权方式两种都收:表单里的 `client_id`/`client_secret`(MaxKey 惯例) +/// 与 `Authorization: Basic`(标准),见 `authenticate_client`。 +pub fn token_v20(r: *mut ngx_http_request_t) -> Status { + token_impl(r, true) +} + +fn token_impl(r: *mut ngx_http_request_t, bare: bool) -> Status { + let p = http::params(r); + let grant_type = p.get("grant_type").map(String::as_str).unwrap_or(""); + let now = util::now(); + + match grant_type { + "authorization_code" => { + let code = p.get("code").cloned().unwrap_or_default(); + let code_verifier = p.get("code_verifier").cloned().unwrap_or_default(); + let redirect_uri = p.get("redirect_uri").cloned().unwrap_or_default(); + + let ctx_raw = match state::take_oauth_code(&code, now) { + Some(c) => c, + None => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "授权码无效或已使用"), + }; + let ctx: Value = match serde_json::from_str(&ctx_raw) { + Ok(v) => v, + Err(_) => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "授权码损坏"), + }; + let sub = ctx.get("sub").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + let client_id = ctx.get("client_id").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + let stored_redirect = ctx.get("redirect_uri").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + let scope = ctx.get("scope").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + let nonce = ctx.get("nonce").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + let ch = ctx.get("code_challenge").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + let chm = ctx.get("code_challenge_method").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + + // 客户端必须一致 + let client = match authenticate_client(r, &p) { + Some(c) if c.client_id == client_id => c, + _ => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), + }; + if !redirect_uri.is_empty() && redirect_uri != stored_redirect { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "redirect_uri 不匹配"); + } + // PKCE 校验 + if !ch.is_empty() { + if !verify_pkce(&code_verifier, &ch, &chm) { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "PKCE 校验失败"); + } + } else if client.confidential { + // 机密客户端无 PKCE 但已通过 client_secret 校验,放行 + } else { + return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "缺少 PKCE"); + } + + issue_tokens(r, &sub, &client, &scope, &nonce, now, bare) + } + + "refresh_token" => { + let refresh = p.get("refresh_token").cloned().unwrap_or_default(); + let claims = match jwt_verify(&refresh) { + Some(c) if c.get("typ").and_then(|v| v.as_str()) == Some("refresh") => c, + _ => return oauth_error(r, HTTPStatus::BAD_REQUEST, "invalid_grant", "refresh_token 无效"), + }; + let sub = claims.get("sub").and_then(|v| v.as_str()).unwrap_or_default().to_owned(); + let client = match authenticate_client(r, &p) { + Some(c) => c, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), + }; + let scope = claims.get("scope").and_then(|v| v.as_str()).unwrap_or("openid").to_owned(); + issue_tokens(r, &sub, &client, &scope, "", now, bare) + } + + "client_credentials" => { + let client = match authenticate_client(r, &p) { + Some(c) => c, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), + }; + if !client.allows_grant("client_credentials") { + return oauth_error(r, HTTPStatus::UNAUTHORIZED, "unauthorized_client", "该客户端不允许 client_credentials"); + } + let scope = p.get("scope").cloned().unwrap_or_else(|| "openid".to_owned()); + let access = mint_access_token( + &client.client_id, "", &client.name, &[], "", &client.client_id, &scope, now, + ); + let body = json!({ + "access_token": access, + "token_type": "Bearer", + "expires_in": OAUTH_ACCESS_TTL, + "scope": scope, + }); + send_token_body(r, body, bare) + } + + "password" => { + let client = match authenticate_client(r, &p) { + Some(c) => c, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_client", "客户端校验失败"), + }; + if !client.allows_grant("password") { + return oauth_error(r, HTTPStatus::UNAUTHORIZED, "unauthorized_client", "该客户端不允许 password"); + } + let uname = p.get("username").cloned().unwrap_or_default(); + let pass = p.get("password").cloned().unwrap_or_default(); + let user = match users::get(&uname) { + Some(u) => u, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_grant", "用户不存在"), + }; + if !util::verify_password(&pass, &user.salt, &user.pwd_hash) { + return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_grant", "密码错误"); + } + let scope = p.get("scope").cloned().unwrap_or_else(|| "openid profile email".to_owned()); + issue_tokens(r, &user.username, &client, &scope, "", now, bare) + } + + _ => oauth_error(r, HTTPStatus::BAD_REQUEST, "unsupported_grant_type", "不支持的 grant_type"), + } +} + +/// 发 access_token + id_token + refresh_token。 +/// 令牌响应体:`bare=true` 输出裸对象(MaxKey 形状),否则套 `{code,msg,data}` 信封。 +fn send_token_body(r: *mut ngx_http_request_t, body: Value, bare: bool) -> Status { + if bare { + http::send(r, HTTPStatus::OK, &body.to_string()) + } else { + http::ok(r, body, "ok") + } +} + +fn issue_tokens( + r: *mut ngx_http_request_t, + sub: &str, + client: &crate::models::OAuthClient, + scope: &str, + nonce: &str, + now: i64, + bare: bool, +) -> Status { + let user = users::get(sub); + let (email, name, groups, department) = match &user { + Some(u) => (u.email.clone(), if u.display_name.is_empty() { u.username.clone() } else { u.display_name.clone() }, u.groups.clone(), u.department.clone()), + None => (String::new(), sub.to_owned(), vec![], String::new()), + }; + let access = mint_access_token(sub, &email, &name, &groups, &department, &client.client_id, scope, now); + let refresh = mint_refresh_token(sub, &client.client_id, now); + let has_openid = scope.split_whitespace().any(|s| s == "openid"); + let mut body = json!({ + "access_token": access, + "token_type": "Bearer", + "expires_in": OAUTH_ACCESS_TTL, + "refresh_token": refresh, + "scope": scope, + }); + if has_openid { + let idt = mint_id_token(sub, &email, &name, &client.client_id, nonce, now); + body["id_token"] = json!(idt); + } + send_token_body(r, body, bare) +} + +/// GET /oauth/userinfo —— Bearer token → 用户声明。 +pub fn userinfo(r: *mut ngx_http_request_t) -> Status { + let token = match access_token_of(r) { + Some(t) => t, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "缺少 Bearer 或 access_token"), + }; + let claims = match jwt_verify(&token) { + Some(c) => c, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "令牌无效或过期"), + }; + let out = json!({ + "sub": claims.get("sub").cloned().unwrap_or(Value::Null), + "preferred_username": claims.get("preferred_username").cloned().unwrap_or(Value::Null), + "name": claims.get("name").cloned().unwrap_or(Value::Null), + "email": claims.get("email").cloned().unwrap_or(Value::Null), + "department": claims.get("department").cloned().unwrap_or(Value::Null), + "groups": claims.get("groups").cloned().unwrap_or(Value::Null), + }); + http::ok(r, out, "ok") +} + +/// `GET|POST /oauth/v20/me` —— **MaxKey 兼容**的用户信息端点。 +/// +/// 与标准 `userinfo` 的两点差异,都是为了照抄 MaxKey 文档的应用能直接跑通: +/// 1. 令牌可走 `access_token` 查询/表单参数(MaxKey 惯例),不必 Bearer 头; +/// 2. 返回**扁平** JSON(`username`/`userid`/`realname`/`email`/`mobile`), +/// 不套本服务的 `{code,msg,data}` 信封 —— MaxKey 的 `/me` 就是裸对象。 +/// +/// 标准 OIDC 声明同时保留(`sub`/`preferred_username`/`email`…), +/// 于是同一个响应既能被 MaxKey 客户端解析,也能被标准 OIDC 客户端解析。 +pub fn userinfo_v20(r: *mut ngx_http_request_t) -> Status { + let token = match access_token_of(r) { + Some(t) => t, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "缺少 access_token"), + }; + let claims = match jwt_verify(&token) { + Some(c) => c, + None => return oauth_error(r, HTTPStatus::UNAUTHORIZED, "invalid_token", "令牌无效或过期"), + }; + let g = |k: &str| claims.get(k).cloned().unwrap_or(Value::Null); + let out = json!({ + // MaxKey 语义:username / userid 是**登录账号**,realname 才是真实姓名。 + // 显示名塞进 username 会让第三方系统按账号查找用户时匹配不上。 + "username": g("sub"), + "userid": g("sub"), + "realname": g("name"), + "email": g("email"), + "mobile": Value::Null, + // ---- 标准 OIDC 声明 ---- + "sub": g("sub"), + "preferred_username": g("preferred_username"), + "name": g("name"), + "department": g("department"), + "groups": g("groups"), + "iss": g("iss"), + "aud": g("aud"), + "exp": g("exp"), + }); + http::send(r, HTTPStatus::OK, &out.to_string()) +} + +/// POST /oauth/introspect —— RFC 7662 令牌自省。 +pub fn introspect(r: *mut ngx_http_request_t) -> Status { + let p = http::params(r); + let token = p.get("token").cloned().unwrap_or_default(); + // 自省端点也需客户端鉴权(防令牌探测) + if authenticate_client(r, &p).is_none() { + return http::fail(r, HTTPStatus::UNAUTHORIZED, "客户端校验失败"); + } + match jwt_verify(&token) { + Some(c) => { + let active = json!({ + "active": true, + "iss": c.get("iss").cloned().unwrap_or(Value::Null), + "sub": c.get("sub").cloned().unwrap_or(Value::Null), + "aud": c.get("aud").cloned().unwrap_or(Value::Null), + "client_id": c.get("client_id").cloned().unwrap_or(Value::Null), + "username": c.get("preferred_username").cloned().unwrap_or(Value::Null), + "email": c.get("email").cloned().unwrap_or(Value::Null), + "department": c.get("department").cloned().unwrap_or(Value::Null), + "groups": c.get("groups").cloned().unwrap_or(Value::Null), + "scope": c.get("scope").cloned().unwrap_or(Value::Null), + "token_type": "Bearer", + "iat": c.get("iat").cloned().unwrap_or(Value::Null), + "exp": c.get("exp").cloned().unwrap_or(Value::Null), + }); + http::ok(r, active, "ok") + } + None => http::ok(r, json!({ "active": false }), "ok"), + } +} + +/// GET /.well-known/openid-configuration —— OIDC discovery。 +pub fn discovery(r: *mut ngx_http_request_t) -> Status { + let iss = issuer(); + let doc = json!({ + "issuer": iss, + "authorization_endpoint": format!("{iss}/oauth/authorize"), + "token_endpoint": format!("{iss}/oauth/token"), + "userinfo_endpoint": format!("{iss}/oauth/userinfo"), + "introspection_endpoint": format!("{iss}/oauth/introspect"), + "jwks_uri": serde_json::Value::Null, + "response_types_supported": ["code"], + "grant_types_supported": ["authorization_code", "refresh_token", "client_credentials", "password"], + "scopes_supported": crate::config::OAUTH_SCOPES_SUPPORTED, + "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"], + "code_challenge_methods_supported": crate::config::OAUTH_CODE_CHALLENGE_METHODS, + "id_token_signing_alg_values_supported": ["HS256"], + "subject_types_supported": ["public"], + "claims_supported": [ + "sub", "iss", "aud", "exp", "iat", "preferred_username", + "email", "email_verified", "name", "department", "groups" + ], + }); + http::ok(r, doc, "ok") +} + +/// `GET /oauth/jwks`(别名 `/.well-known/jwks.json`)——当前为 HS256,无公钥可发布。 +/// +/// 明确返回 404 + 原因,而不是给一个空 JWKS:空 JWKS 会让第三方库以为 +/// 「支持非对称验签,只是还没轮换到密钥」,从而静默地一直验签失败。 +/// 有这条显式说明,接入方会立刻改走 `/oauth/introspect`。 +/// +/// v2 升 RS256 后,本端点改为返回标准 JWKS(`kty=RSA`/`n`/`e`/`kid`)。 +pub fn jwks(r: *mut ngx_http_request_t) -> Status { + http::fail( + r, + HTTPStatus::NOT_FOUND, + "当前为 HS256 对称签名,无公开 JWKS;请用 /oauth/introspect 校验令牌,\ + 或(机密客户端)用 client_secret 校验签名。RS256 + JWKS 见 docs/roadmap.md", + ) +} + +/// GET /login —— 最小化登录页。 +pub fn login_get(r: *mut ngx_http_request_t) -> Status { + let redirect = http::params(r).get("redirect").cloned().unwrap_or_default(); + let html = login_html(&redirect, ""); + // SAFETY: 直接输出 HTML 字符串 + unsafe { + let request = ngx::http::Request::from_ngx_http_request(r); + let pool = request.pool(); + let mut buf = match pool.create_buffer_from_str(&html) { + Some(b) => b, + None => return Status::NGX_ERROR, + }; + buf.set_last_buf(true); + let mut chain = ngx::ffi::ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: std::ptr::null_mut() }; + request.set_status(HTTPStatus::OK); + request.add_header_out("Content-Type", "text/html; charset=utf-8"); + request.set_content_length_n(html.len()); + let st = request.send_header(); + if st != Status::NGX_OK { + return st; + } + request.output_filter(&mut chain) + } +} + +/// POST /login —— 校验口令,建立 SSO 会话。 +pub fn login_post(r: *mut ngx_http_request_t) -> Status { + let p = http::params(r); + let username = p.get("username").cloned().unwrap_or_default(); + let password = p.get("password").cloned().unwrap_or_default(); + let redirect = p.get("redirect").cloned().unwrap_or_default(); + + let user = match users::get(&username) { + Some(u) => u, + None => return login_failed(r, "账号或密码错误", &redirect), + }; + if !util::verify_password(&password, &user.salt, &user.pwd_hash) { + return login_failed(r, "账号或密码错误", &redirect); + } + + let now = util::now(); + let token = util::rand_hex(32); + let payload = sso_payload(&user); + if !state::put_oauth_session(&token, &payload, now + OAUTH_SESSION_TTL) { + return login_failed(r, "会话创建失败", &redirect); + } + let cookie = sso_cookie(&token, OAUTH_SESSION_TTL); + util::log_notice(&format!("[oauth] SSO 登录 user={username} client={}", http::remote_addr(r))); + + if !redirect.is_empty() && is_safe_redirect(&redirect) { + let headers = vec![("Set-Cookie", cookie.as_str()), ("Location", redirect.as_str())]; + // 用 send_with 发 302 + return http::send_with(r, HTTPStatus(302), "{\"code\":302,\"msg\":\"登录成功\"}", &headers); + } + http::ok_with(r, json!({ "username": username }), "登录成功", &[("Set-Cookie", &cookie)]) +} + +/// POST /oauth/logout —— 销毁 SSO 会话。 +pub fn logout(r: *mut ngx_http_request_t) -> Status { + if let Some(tok) = parse_cookie(http::header(r, "cookie").as_deref(), OAUTH_SESSION_COOKIE) { + state::remove_oauth_session(&tok); + } + let cleared = format!( + "{OAUTH_SESSION_COOKIE}=deleted; Path=/; HttpOnly; SameSite=Lax; Max-Age=0" + ); + http::ok_with(r, json!({}), "已退出登录", &[("Set-Cookie", &cleared)]) +} + +// =========================================================================== +// IAP 身份解析(供 lib.rs 的 IapHandler 调用) +// =========================================================================== + +/// 解析 IAP 请求身份:Bearer token 或 SSO 会话。 +/// +/// 返回 `(sub_user, email, groups_csv, sub, access_token)`;无身份返回 None。 +/// - Bearer:直接校验 JWT,token 原样作为注入的 `X-Auth-Token`。 +/// - SSO 会话:读共享内存 payload,重新签发一个 access_token 供后端独立校验。 +pub fn iap_identity(r: *mut ngx_http_request_t) -> Option<(String, String, String, String, String)> { + let now = util::now(); + + if let Some(tok) = bearer_token(r) { + if let Some(c) = jwt_verify(&tok) { + let sub = c.get("sub").and_then(|v| v.as_str()).unwrap_or("").to_owned(); + let email = c.get("email").and_then(|v| v.as_str()).unwrap_or("").to_owned(); + let groups = c + .get("groups") + .and_then(|v| v.as_array()) + .map(|a| a.iter().filter_map(|x| x.as_str()).collect::>().join(",")) + .unwrap_or_default(); + if sub.is_empty() { + return None; + } + return Some((sub.clone(), email, groups, sub, tok)); + } + } + + if let Some(tok) = parse_cookie(http::header(r, "cookie").as_deref(), OAUTH_SESSION_COOKIE) { + if let Some(payload) = state::get_oauth_session(&tok, now) { + let parts: Vec<&str> = payload.split('\n').collect(); + let username = parts.first().copied().unwrap_or("").to_owned(); + let email = parts.get(1).copied().unwrap_or("").to_owned(); + let groups = parts.get(2).copied().unwrap_or("").to_owned(); + let department = parts.get(3).copied().unwrap_or("").to_owned(); + let name = parts.get(4).copied().unwrap_or("").to_owned(); + if username.is_empty() { + return None; + } + // 会话里没有 access_token(它只存身份),此处按同一套 claims 现签一个, + // 供后端独立验签——后端不必信任网关注入的头,但仍能自己验出同一个身份。 + let access = mint_access_token( + &username, + &email, + &name, + &groups.split(',').filter(|s| !s.is_empty()).map(|s| s.to_owned()).collect::>(), + &department, + IAP_TOKEN_AUDIENCE, + IAP_TOKEN_SCOPE, + now, + ); + return Some((username.clone(), email, groups, username, access)); + } + } + None +} + +// =========================================================================== +// 工具 +// =========================================================================== + +fn oauth_error(r: *mut ngx_http_request_t, status: HTTPStatus, err: &str, desc: &str) -> Status { + let body = json!({ "error": err, "error_description": desc }).to_string(); + http::fail(r, status, &body) +} + +fn redirect(r: *mut ngx_http_request_t, loc: &str) -> Status { + http::send_with(r, HTTPStatus(302), &format!("{{\"code\":302,\"msg\":\"redirect\",\"location\":\"{loc}\"}}"), &[("Location", loc)]) +} + +fn login_failed(r: *mut ngx_http_request_t, msg: &str, redirect: &str) -> Status { + // 失败时回到登录页并带错误提示。 + // + // 早先这里写成 `login_html("") + "

…"`——拼在 `` + // 之后,浏览器把整段当垃圾节点丢掉,于是「登录失败」和「页面没反应」长得 + // 一模一样。错误提示必须走 login_html 的结构化参数,落在卡片里面。 + let html = login_html(redirect, msg); + unsafe { + let request = ngx::http::Request::from_ngx_http_request(r); + let pool = request.pool(); + let mut buf = match pool.create_buffer_from_str(&html) { + Some(b) => b, + None => return Status::NGX_ERROR, + }; + buf.set_last_buf(true); + let mut chain = ngx::ffi::ngx_chain_t { buf: buf.as_ngx_buf_mut(), next: std::ptr::null_mut() }; + request.set_status(HTTPStatus::UNAUTHORIZED); + request.add_header_out("Content-Type", "text/html; charset=utf-8"); + request.set_content_length_n(html.len()); + let st = request.send_header(); + if st != Status::NGX_OK { + return st; + } + request.output_filter(&mut chain) + } +} + +/// 登录页样式(内联,不额外引入静态文件与一次请求)。 +/// +/// 配色与网关管理台一致:深蓝渐变底 + 白卡片 + 蓝色主按钮。 +const LOGIN_STYLE: &str = r#" + *{box-sizing:border-box} + body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px; + font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; + background:radial-gradient(1100px 560px at 50% -12%,#1e3a8a 0%,#0f172a 58%,#0b1220 100%);color:#1f2937} + .card{width:100%;max-width:380px;background:#fff;border-radius:16px;padding:34px 30px 24px; + box-shadow:0 20px 60px rgba(2,6,23,.45)} + .brand{display:flex;align-items:center;gap:11px;margin-bottom:20px} + .mark{width:34px;height:34px;border-radius:10px;background:linear-gradient(135deg,#2563eb,#38bdf8); + display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700; + font-size:12px;letter-spacing:.5px;flex:0 0 auto} + h1{font-size:16px;margin:0} + .sub{color:#6b7280;font-size:12px;margin-top:2px} + label{display:block;font-size:12.5px;color:#6b7280;margin:0 0 6px} + input[type=text],input[type=password]{width:100%;padding:10px 12px;margin:0 0 14px; + border:1px solid #cbd5e1;border-radius:8px;font-size:13.5px;outline:none; + transition:border-color .15s,box-shadow .15s} + input[type=text]:focus,input[type=password]:focus{border-color:#2563eb; + box-shadow:0 0 0 3px rgba(37,99,235,.12)} + button{width:100%;padding:11px;border:0;border-radius:8px;background:#2563eb;color:#fff; + font-size:15px;font-weight:600;cursor:pointer;transition:.15s;font-family:inherit} + button:hover{background:#1d4ed8} + .err{background:#fdecec;color:#b91c1c;border:1px solid #f7cfcf;border-radius:8px; + padding:9px 12px;font-size:12.5px;margin-bottom:16px} + .target{margin-top:18px;padding-top:14px;border-top:1px dashed #e3e8ef; + color:#6b7280;font-size:12px;line-height:1.7} + .target b{color:#1f2937} +"#; + +/// 登录页。`error` 非空时在卡片内显示错误条。 +/// +/// `redirect` / `username` / `password` 三个字段名与表单 `action="/login"` 是对外 +/// 契约(e2e 与接入方都在依赖),改样式时不要动。 +fn login_html(redirect: &str, error: &str) -> String { + let red = util::html_escape(redirect); + let err = if error.is_empty() { + String::new() + } else { + format!("

{}
", util::html_escape(error)) + }; + // 只取主机名展示:登录后要去哪,用户有权知道;但带 query 的长 URL 会铺满一屏。 + let target_block = match redirect + .split_once("://") + .and_then(|(_, rest)| rest.split('/').next()) + .filter(|h| !h.is_empty()) + { + Some(host) => format!( + "
登录成功后将返回 {}
", + util::html_escape(host) + ), + None => String::new(), + }; + format!( + "\ + \ + 登录 · 统一认证\ +
\ +
SSO
\ +

统一认证

一次登录,访问全部已接入的应用
\ + {err}\ +
\ + \ + \ + \ + \ + \ +
\ + {target_block}
" + ) +} + +/// 当前请求的完整 URL(用于登录回跳)。 +fn current_url(r: *mut ngx_http_request_t) -> String { + let host = http::header(r, "host").unwrap_or_else(|| "localhost".to_owned()); + let scheme = http::header(r, "x-forwarded-proto").unwrap_or_else(|| "http".to_owned()); + let scheme = if scheme == "https" { "https" } else { "http" }; + let uri = http::uri(r); + let args = http::args_raw(r); + let args = String::from_utf8_lossy(&args); + if args.is_empty() { + format!("{scheme}://{host}{uri}") + } else { + format!("{scheme}://{host}{uri}?{args}") + } +} + +/// 仅允许跳回同源(含 cookie domain)地址,防开放重定向。 +fn is_safe_redirect(url: &str) -> bool { + if !url.starts_with("http://") && !url.starts_with("https://") { + return false; + } + let dom = cookie_domain(); + if let Some((_, host)) = url.split_once("://") { + let host = host.split('/').next().unwrap_or(""); + if host.ends_with(&dom) && !dom.is_empty() { + return true; + } + if host == "localhost" || host.starts_with("localhost:") { + return true; + } + } + false +} + +/// PKCE S256/plain 校验。 +fn verify_pkce(verifier: &str, challenge: &str, method: &str) -> bool { + if verifier.is_empty() { + return false; + } + match method { + "S256" => { + let hash = sha256_raw(verifier.as_bytes()); + util::ct_eq(&b64url_encode(&hash), challenge) + } + "plain" => util::ct_eq(verifier, challenge), + _ => false, + } +} diff --git a/source/rust/src/oauth_clients.rs b/source/rust/src/oauth_clients.rs new file mode 100644 index 0000000..ad81666 --- /dev/null +++ b/source/rust/src/oauth_clients.rs @@ -0,0 +1,262 @@ +//! OAuth2 客户端注册表:第三方应用接入本网关统一认证的入口。 +//! +//! 对应 MaxKey 的「应用管理」。一个第三方应用(如 Grafana、内部 CRM)在此登记 +//! `client_id` / `client_secret` / 回调地址 / 授权类型 / scope,之后即可按标准 +//! OAuth2 / OIDC 流程对接本网关,无需感知底层用户存储。 +//! +//! 与 `users` 同构:文件是唯一真源,启动时全量装载进共享内存(`ocl:` 前缀), +//! 授权热路径只读内存;写入则**写穿**内存,做到「登记完立刻能授权」。 + +use serde_json::json; + +use crate::config::KEY_OAUTH_CLIENT_PREFIX; +use crate::models::{OAuthClient, OAuthClientTable}; +use crate::state; +use crate::store; +use crate::util; + +// =========================================================================== +// 共享内存同步 +// =========================================================================== + +/// 客户端 payload:客户端 JSON 原样进共享内存(低频读,直接反序列化)。 +fn client_payload(c: &OAuthClient) -> String { + serde_json::to_string(c).unwrap_or_default() +} + +/// 全量重载客户端注册表进 `ocl:`。返回装载条数。 +pub fn reload_shm() -> usize { + state::clear_prefix(KEY_OAUTH_CLIENT_PREFIX); + let table = store::read_oauth_clients(); + let total = table.len(); + let mut loaded = 0; + for c in &table { + if !c.client_id.is_empty() && state::put_oauth_client(&c.client_id, &client_payload(c)) { + loaded += 1; + } + } + if loaded != total { + util::log_err(&format!( + "[oauth_clients] 装载不全:{loaded}/{total} —— 有客户端将无法发起授权" + )); + } + loaded +} + +// =========================================================================== +// 查询 +// =========================================================================== + +/// 按 client_id 取客户端(低频:授权/令牌端点各一次)。 +pub fn get(client_id: &str) -> Option { + if client_id.is_empty() { + return None; + } + let raw = state::get_oauth_client(client_id)?; + serde_json::from_str(&raw).ok() +} + +/// 全部客户端(管理台列表用)。 +pub fn all() -> Vec { + store::read_oauth_clients() +} + +// =========================================================================== +// 写入(管理接口用) +// =========================================================================== + +/// 生成客户端密钥:`cs_` + 24 字节 hex。 +fn gen_secret() -> String { + format!("cs_{}", util::rand_hex(24)) +} + +/// 注册/更新客户端。传空 `client_secret` 时自动生成(机密客户端)。 +pub fn upsert( + client_id: &str, + name: &str, + redirect_uris: Vec, + grant_types: Vec, + scopes: Vec, + confidential: bool, + secret_in: &str, +) -> Result { + let client_id = util::trim(client_id).to_owned(); + if client_id.is_empty() { + return Err("client_id 不能为空".to_owned()); + } + // 公开客户端(SPA / 移动端,走 PKCE)按定义不持有密钥:既不生成,也在 + // 改为公开时清掉旧密钥——否则管理台上会躺着一个「看着能用、其实没人校验」 + // 的密钥,接入方拿去配到代码里就是白配。 + let secret = if !confidential { + String::new() + } else if secret_in.is_empty() { + gen_secret() + } else { + secret_in.to_owned() + }; + + // 缺省授权类型:标准 Web 客户端最小集 + let mut grant_types = if grant_types.is_empty() { + vec![ + "authorization_code".to_owned(), + "refresh_token".to_owned(), + ] + } else { + grant_types + }; + // client_credentials / password 都要用密钥证明身份,公开客户端用不了; + // 静默留着一个「配了也不会生效」的授权类型,比直接拒掉更难排查。 + if !confidential { + let before = grant_types.len(); + grant_types.retain(|g| g != "client_credentials" && g != "password"); + if grant_types.len() != before { + util::log_warn(&format!( + "[oauth_clients] {client_id} 是公开客户端,已忽略 client_credentials/password" + )); + } + } + // 缺省 scope:openid + 基础信息 + let scopes = if scopes.is_empty() { + vec!["openid".to_owned(), "profile".to_owned(), "email".to_owned()] + } else { + scopes + }; + + // ---- 校验:宁可在这里拒掉,也不要让一个配错的客户端在授权时才发现 ---- + const ALLOWED_GRANTS: [&str; 4] = [ + "authorization_code", + "refresh_token", + "client_credentials", + "password", + ]; + for g in &grant_types { + if !ALLOWED_GRANTS.contains(&g.as_str()) { + return Err(format!( + "不支持的授权类型:{g}(可选 {})", + ALLOWED_GRANTS.join(" / ") + )); + } + } + if grant_types.iter().any(|g| g == "authorization_code") && redirect_uris.is_empty() { + return Err("使用授权码模式时必须至少填一个回调地址".to_owned()); + } + // 回调地址会被原样用于 302 跳转,必须是绝对 http(s) 且不带 fragment—— + // 白名单里混进 `*` 或 `javascript:` 就等于把授权码送给任意站点。 + for u in &redirect_uris { + if !(u.starts_with("http://") || u.starts_with("https://")) { + return Err(format!("回调地址必须是 http(s) 绝对地址:{u}")); + } + if u.contains('#') { + return Err(format!("回调地址不能带 #fragment:{u}")); + } + } + + let created = client_id.clone(); + let out = store::update_oauth_clients(move |table: &mut OAuthClientTable| { + let now = util::now(); + if let Some(existing) = table.iter_mut().find(|c| c.client_id == created) { + existing.name = name.to_owned(); + existing.redirect_uris = redirect_uris; + existing.grant_types = grant_types; + existing.scopes = scopes; + existing.confidential = confidential; + if !confidential { + existing.client_secret = String::new(); + } else if !secret_in.is_empty() { + existing.client_secret = secret.clone(); + } + Ok(existing.clone()) + } else { + let c = OAuthClient { + client_id: created.clone(), + client_secret: secret.clone(), + name: name.to_owned(), + redirect_uris, + grant_types, + scopes, + confidential, + created_at: now, + }; + table.push(c.clone()); + Ok(c) + } + })?; + + // 写穿共享内存,使「登记完立刻可授权」,不必重启网关。 + // + // 必须写 `out`——本次落盘后的新值。早先这里写成「`get()` 出来再回写」, + // 而 `get()` 读的正是共享内存:等于把旧值原样写回去。后果是新建的客户端 + // 永远进不了热路径,表现为「管理台显示已保存,但授权请求仍报客户端不存在」。 + if !state::put_oauth_client(&out.client_id, &client_payload(&out)) { + util::log_err(&format!( + "[oauth_clients] 写共享内存失败:{} —— 本次改动需重载/重启才生效", + out.client_id + )); + } + Ok(out) +} + +/// 重新生成客户端密钥(管理台「重置密钥」)。返回新密钥明文,旧密钥立即失效。 +/// +/// 与 `upsert` 分开是因为 `upsert` 的语义是「传空密钥 = 保持原值」,没法用来 +/// 主动轮换;而重置密钥是常见的应急动作(怀疑泄漏时),不该需要先删再建。 +pub fn rotate_secret(client_id: &str) -> Result { + let id = util::trim(client_id).to_owned(); + if id.is_empty() { + return Err("client_id 不能为空".to_owned()); + } + let secret = gen_secret(); + let next = secret.clone(); + let out = store::update_oauth_clients(move |table: &mut OAuthClientTable| { + let Some(c) = table.iter_mut().find(|c| c.client_id == id) else { + return Err("客户端不存在".to_owned()); + }; + if !c.confidential { + return Err("公开客户端不持有密钥,无需重置".to_owned()); + } + c.client_secret = next; + Ok(c.clone()) + })?; + + if !state::put_oauth_client(&out.client_id, &client_payload(&out)) { + util::log_err(&format!( + "[oauth_clients] 重置密钥后写共享内存失败:{}", + out.client_id + )); + } + Ok(secret) +} + +pub fn delete(client_id: &str) -> Result<(), String> { + let id = client_id.to_owned(); + store::update_oauth_clients(move |table: &mut OAuthClientTable| { + let before = table.len(); + table.retain(|c| c.client_id != id); + if table.len() == before { + return Err("客户端不存在".to_owned()); + } + Ok(()) + })?; + if !state::remove_oauth_client(client_id) { + util::log_err(&format!( + "[oauth_clients] 从共享内存移除失败:{client_id} —— 该客户端在重载前仍可发起授权" + )); + } + Ok(()) +} + +/// 管理台可见投影(含脱敏后的 secret,便于复制)。 +pub fn view(c: &OAuthClient) -> serde_json::Value { + json!({ + "client_id": c.client_id, + "name": c.name, + "redirect_uris": c.redirect_uris, + "grant_types": c.grant_types, + "scopes": c.scopes, + "confidential": c.confidential, + "client_secret": c.client_secret, + "client_secret_masked": util::mask_key(&c.client_secret), + "created_at": c.created_at, + "created_at_text": util::fmt_time(c.created_at), + }) +} diff --git a/source/rust/src/session.rs b/source/rust/src/session.rs new file mode 100644 index 0000000..cf5080c --- /dev/null +++ b/source/rust/src/session.rs @@ -0,0 +1,59 @@ +//! 管理员登录会话。 +//! +//! 会话存在共享内存里:**nginx 重启即全部失效**,这是预期行为。 +//! +//! Cookie 为 `sso_admin_session=<64 位 hex>`,HttpOnly + SameSite=Strict, +//! 每次校验命中都会滑动续期。 +//! +//! 与 SSO 终端用户会话(`oauth` 模块的 `sso_sid`)**刻意分开**:管理台身份 +//! 与业务系统身份是两条信任线,共用一套会让「能登录业务系统」等价于「能改配置」。 + +use crate::config::{COOKIE_NAME, SESSION_TTL}; +use crate::state; +use crate::util; + +/// 从 Cookie 头里取出会话 token +pub fn parse_token(cookie_header: &str) -> Option { + let needle = format!("{COOKIE_NAME}="); + for part in cookie_header.split(';') { + let part = part.trim(); + if let Some(value) = part.strip_prefix(&needle) { + if !value.is_empty() { + return Some(value.to_owned()); + } + } + } + None +} + +/// 新建会话,返回 token +pub fn create(username: &str) -> String { + let token = util::rand_hex(32); + state::put_session(&token, username, util::now() + SESSION_TTL); + token +} + +pub fn set_cookie(token: &str) -> String { + format!("{COOKIE_NAME}={token}; Path=/; HttpOnly; SameSite=Strict; Max-Age={SESSION_TTL}") +} + +pub fn clear_cookie() -> String { + format!("{COOKIE_NAME}=deleted; Path=/; HttpOnly; SameSite=Strict; Max-Age=0") +} + +/// 鉴权:解析 Cookie → 查共享内存 → 命中则滑动续期。返回当前登录用户名。 +pub fn authenticate(cookie: Option<&str>) -> Option { + let token = parse_token(cookie?)?; + let now = util::now(); + let username = state::get_session(&token, now)?; + // 滑动续期:活跃使用不因固定 TTL 被踢出 + state::put_session(&token, &username, now + SESSION_TTL); + Some(username) +} + +/// 退出登录:销毁服务端会话(Cookie 由响应头清除) +pub fn destroy(cookie: Option<&str>) { + if let Some(token) = cookie.and_then(parse_token) { + state::remove_session(&token); + } +} diff --git a/source/rust/src/state.rs b/source/rust/src/state.rs new file mode 100644 index 0000000..7205928 --- /dev/null +++ b/source/rust/src/state.rs @@ -0,0 +1,340 @@ +//! 共享内存状态层。 +//! +//! 「配置放内存」的落点。全部派生状态集中在一张 `RbTreeMap` 里,用键前缀区分用途: +//! +//! ```text +//! sess: → \x1f 管理员会话 +//! fail: → \x1f 登录失败计数 +//! sso: → <身份 payload> \x1f SSO 终端用户会话 +//! oac: → <授权上下文 JSON> \x1f 授权码(一次性) +//! ocl: → <客户端 JSON> \x1f 0 OAuth 接入方注册表 +//! ``` +//! +//! 为什么这些派生状态不直接读文件?——`/oauth/authorize`、IAP 门禁(access 阶段) +//! 都是**每请求**路径,一次同步文件 I/O + 全表 JSON 解码就是明显的尾延迟。 +//! +//! ## 为什么过期时间写在 value 里,而不是靠字典的 TTL +//! +//! `RbTreeMap` 是纯数据结构,没有 TTL。因此把到期时刻编码进 value,读取时判断—— +//! 语义上反而更精确(到期即失效,不受回收延迟影响)。 +//! +//! ## 为什么锁必须放进共享内存 +//! +//! nginx 是多进程模型。`RwLock` 若放在普通静态变量里,每个 worker 会持有 +//! 各自的副本,跨进程互斥完全失效。锁与表都必须在 `ngx_shared_memory_add` +//! 创建的 slab 池里分配。 + +use core::ptr; +use core::sync::atomic::{AtomicPtr, Ordering}; + +use ngx::collections::RbTreeMap; +use ngx::core::{NgxStr, NgxString, SlabPool, Status}; +use ngx::ffi::ngx_shm_zone_t; +use ngx::sync::{RwLock, RwLockWriteGuard}; + +use crate::config::{ + KEY_BUF_LEN, KEY_OAUTH_CLIENT_PREFIX, KEY_OAUTH_CODE_PREFIX, KEY_OAUTH_SESS_PREFIX, VAL_SEP, +}; + +/// 全部映射的底层容器 +pub type ShmMap = RbTreeMap, NgxString, SlabPool>; + +/// 共享内存根对象:一张表 + 一把文件写锁。 +/// +/// 文件写锁**独立于表的读写锁**:文件 I/O 期间若持有表的写锁, +/// 会把所有读共享内存的请求(需要读锁)一起卡住。 +pub struct ShmRoot { + pub map: RwLock, + /// 保护 `store` 的「读-改-写」与落盘,跨 worker 互斥 + pub file_lock: RwLock<()>, +} + +/// 由 `sso_state ` 注册的共享内存区 +static STATE_ZONE: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + +pub fn set_zone(zone: *mut ngx_shm_zone_t) { + STATE_ZONE.store(zone, Ordering::SeqCst); +} + +/// 在 slab 池上构造 `ShmRoot` 并挂到 `shpool->data`;重复调用直接复用。 +fn init_root(zone: &mut ngx_shm_zone_t) -> Result<&'static ShmRoot, Status> { + // SAFETY: zone 由 ngx_shared_memory_add 注册,init 回调已使其 shm 可用 + let mut alloc = unsafe { SlabPool::from_shm_zone(zone) }.ok_or(Status::NGX_ERROR)?; + + if alloc.as_mut().data.is_null() { + let map = ShmMap::try_new_in(alloc.clone()).map_err(|_| Status::NGX_ERROR)?; + let root = ShmRoot { map: RwLock::new(map), file_lock: RwLock::new(()) }; + // 整块放进共享内存:两个锁与表必须对所有 worker 是同一份 + let placed = ngx::allocator::allocate(root, &alloc).map_err(|_| Status::NGX_ERROR)?; + alloc.as_mut().data = placed.as_ptr().cast(); + } + + // SAFETY: data 非空即指向一个已初始化、且存活于共享内存的 ShmRoot + unsafe { alloc.as_ref().data.cast::().as_ref().ok_or(Status::NGX_ERROR) } +} + +/// 取共享内存根对象;zone 未注册时返回 None +pub fn root() -> Option<&'static ShmRoot> { + let zone = STATE_ZONE.load(Ordering::SeqCst); + if zone.is_null() { + return None; + } + // SAFETY: 非空即代表 zone 已注册 + init_root(unsafe { &mut *zone }).ok() +} + +/// 取 slab 分配器(构造共享内存字符串用) +pub fn alloc() -> Option { + let zone = STATE_ZONE.load(Ordering::SeqCst); + if zone.is_null() { + return None; + } + // SAFETY: 同上 + unsafe { SlabPool::from_shm_zone(&mut *zone) } +} + +/// 初始化回调:由 nginx 在 fork 之前调用一次 +pub fn init_zone(zone: *mut ngx_shm_zone_t) -> Status { + // SAFETY: nginx 传入的 zone 有效 + match init_root(unsafe { &mut *zone }) { + Ok(_) => Status::NGX_OK, + Err(e) => e, + } +} + +/// 取全局文件写锁。所有「读文件 → 改 → 写文件」必须包在这里面。 +/// +/// nginx 侧只有一个写锁、且都是低频管理操作,串行化代价可忽略; +/// 而它换来的是多 worker 下不会出现「两边同时改、后写的覆盖前写的」。 +pub fn file_lock() -> Option> { + root().map(|r| r.file_lock.write()) +} + +// =========================================================================== +// 键构造 +// =========================================================================== + +/// 在栈上拼 `prefix + name`,避免热路径为键做堆分配。 +fn key_buf(prefix: &[u8], name: &[u8]) -> Option<([u8; KEY_BUF_LEN], usize)> { + let n = prefix.len() + name.len(); + if n > KEY_BUF_LEN { + return None; + } + let mut buf = [0u8; KEY_BUF_LEN]; + buf[..prefix.len()].copy_from_slice(prefix); + buf[prefix.len()..n].copy_from_slice(name); + Some((buf, n)) +} + +/// 拆 value:` \x1f ` +/// +/// 按**最后一个** `VAL_SEP` 切分(`rposition`)。到期时刻恒为 value 末尾的十进制 +/// 整数,而 payload 里可能合法地含有 `VAL_SEP`——例如 SSO 会话的身份字段串。 +/// 用 `position`(第一个分隔符)会把这类 payload 腰斩,并把后面的残段当 expiry +/// 解析而失败,表现为「刚写入就查不到」。 +fn split_value(bytes: &[u8]) -> Option<(&[u8], i64)> { + let sep = bytes.iter().rposition(|&b| b == VAL_SEP)?; + let payload = &bytes[..sep]; + let exp = core::str::from_utf8(&bytes[sep + 1..]).ok()?.parse::().ok()?; + Some((payload, exp)) +} + +// =========================================================================== +// 读写原语 +// =========================================================================== + +/// 查表。返回 `(payload, expires_at)`;键不存在或值损坏时返回 None。 +pub fn get(prefix: &[u8], name: &[u8]) -> Option<(String, i64)> { + let (buf, n) = key_buf(prefix, name)?; + let root = root()?; + let guard = root.map.read(); + let value = guard.get(NgxStr::from_bytes(&buf[..n]))?; + let (payload, exp) = split_value(value.as_bytes())?; + // 复制成 owned:guard 释放后共享内存可能被并发写覆盖, + // 直接返回引用会悬垂。 + Some((String::from_utf8_lossy(payload).into_owned(), exp)) +} + +/// 查表并校验未过期 +pub fn get_live(prefix: &[u8], name: &[u8], now: i64) -> Option { + let (payload, exp) = get(prefix, name)?; + if exp > 0 && exp <= now { + return None; + } + Some(payload) +} + +/// 写入(先删后插,语义为覆盖)。返回 false 表示共享内存不足或 zone 未就绪。 +pub fn put(prefix: &[u8], name: &[u8], payload: &[u8], expires_at: i64) -> bool { + let (Some(root), Some(a)) = (root(), alloc()) else { + return false; + }; + + let mut value = Vec::with_capacity(payload.len() + 24); + value.extend_from_slice(payload); + value.push(VAL_SEP); + value.extend_from_slice(expires_at.to_string().as_bytes()); + + let mut key = Vec::with_capacity(prefix.len() + name.len()); + key.extend_from_slice(prefix); + key.extend_from_slice(name); + + let (Ok(nk), Ok(nv)) = ( + NgxString::try_from_bytes_in(&key, a.clone()), + NgxString::try_from_bytes_in(&value, a), + ) else { + return false; + }; + + let mut guard = root.map.write(); + // 先删后插:try_insert 对已存在的键可能直接失败,而这里的语义是覆盖 + let _ = guard.remove(NgxStr::from_bytes(&key)); + guard.try_insert(nk, nv).is_ok() +} + +/// 删除一个键。返回它此前是否存在。 +pub fn remove(prefix: &[u8], name: &[u8]) -> bool { + let Some(root) = root() else { + return false; + }; + let mut key = Vec::with_capacity(prefix.len() + name.len()); + key.extend_from_slice(prefix); + key.extend_from_slice(name); + root.map.write().remove(NgxStr::from_bytes(&key)).is_some() +} + +/// 只清掉某一前缀下的所有键。 +/// +/// 重载注册表时用——**不能**用 `clear()`,那会把正在登录的管理员会话一起清掉。 +pub fn clear_prefix(prefix: &[u8]) { + let Some(root) = root() else { + return; + }; + let mut guard = root.map.write(); + // 先收集待删键:迭代器借用了 guard,不能边遍历边删 + let victims: Vec> = + guard.iter().filter(|p| p.0.as_bytes().starts_with(prefix)).map(|p| p.0.as_bytes().to_vec()).collect(); + for v in victims { + guard.remove(NgxStr::from_bytes(&v)); + } +} + +/// 遍历某前缀下的全部条目,返回 `(去掉前缀的键名, payload)`。 +/// +/// **低频读**接口(管理台/诊断),每次都会克隆字符串出来。 +#[allow(dead_code)] +pub fn iter_prefix(prefix: &[u8]) -> Vec<(String, String)> { + let Some(root) = root() else { + return Vec::new(); + }; + let guard = root.map.read(); + guard + .iter() + .filter_map(|(k, v)| { + let name = k.as_bytes().strip_prefix(prefix)?; + let (payload, _) = split_value(v.as_bytes())?; + Some(( + String::from_utf8_lossy(name).into_owned(), + String::from_utf8_lossy(payload).into_owned(), + )) + }) + .collect() +} + +/// 当前条目数(诊断用) +#[allow(dead_code)] +pub fn len() -> usize { + root().map(|r| r.map.read().iter().count()).unwrap_or(0) +} + +// =========================================================================== +// 管理会话 +// =========================================================================== + +/// 管理会话写入 +pub fn put_session(token: &str, username: &str, expires_at: i64) -> bool { + put(crate::config::KEY_SESS_PREFIX, token.as_bytes(), username.as_bytes(), expires_at) +} + +/// 管理会话读取(未过期才返回用户名) +pub fn get_session(token: &str, now: i64) -> Option { + get_live(crate::config::KEY_SESS_PREFIX, token.as_bytes(), now) +} + +pub fn remove_session(token: &str) -> bool { + remove(crate::config::KEY_SESS_PREFIX, token.as_bytes()) +} + +// =========================================================================== +// 登录失败计数(按 IP 限速) +// =========================================================================== + +/// 登录失败计数:返回自增后的值 +pub fn bump_login_fail(ip: &str, now: i64) -> i64 { + let current = get_login_fail(ip, now); + let next = current + 1; + put( + crate::config::KEY_FAIL_PREFIX, + ip.as_bytes(), + next.to_string().as_bytes(), + now + crate::config::LOGIN_FAIL_TTL, + ); + next +} + +pub fn get_login_fail(ip: &str, now: i64) -> i64 { + match get(crate::config::KEY_FAIL_PREFIX, ip.as_bytes()) { + Some((_, exp)) if exp > 0 && exp <= now => 0, + Some((payload, _)) => payload.parse::().unwrap_or(0), + None => 0, + } +} + +pub fn clear_login_fail(ip: &str) { + remove(crate::config::KEY_FAIL_PREFIX, ip.as_bytes()); +} + +// =========================================================================== +// OAuth2 / OIDC +// =========================================================================== + +/// SSO 终端用户会话:token → 身份 payload(见 `config::KEY_OAUTH_SESS_PREFIX`)。 +/// +/// payload 把身份字段平铺进 value,使 IAP 热路径**只读共享内存**、不回读 +/// `users.json`。 +pub fn put_oauth_session(token: &str, payload: &str, expires_at: i64) -> bool { + put(KEY_OAUTH_SESS_PREFIX, token.as_bytes(), payload.as_bytes(), expires_at) +} + +pub fn get_oauth_session(token: &str, now: i64) -> Option { + get_live(KEY_OAUTH_SESS_PREFIX, token.as_bytes(), now) +} + +pub fn remove_oauth_session(token: &str) -> bool { + remove(KEY_OAUTH_SESS_PREFIX, token.as_bytes()) +} + +/// 授权码:随机 id → 授权上下文 JSON。一次性(取出即删)。 +pub fn put_oauth_code(code: &str, payload: &str, expires_at: i64) -> bool { + put(KEY_OAUTH_CODE_PREFIX, code.as_bytes(), payload.as_bytes(), expires_at) +} + +/// 取并删除授权码(保证单次使用)。 +pub fn take_oauth_code(code: &str, now: i64) -> Option { + let payload = get_live(KEY_OAUTH_CODE_PREFIX, code.as_bytes(), now); + remove(KEY_OAUTH_CODE_PREFIX, code.as_bytes()); + payload +} + +/// OAuth 客户端注册:client_id → 客户端 JSON(无 TTL,跟随文件生命周期)。 +pub fn put_oauth_client(client_id: &str, payload: &str) -> bool { + put(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes(), payload.as_bytes(), 0) +} + +pub fn get_oauth_client(client_id: &str) -> Option { + get(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes()).map(|(p, _)| p) +} + +pub fn remove_oauth_client(client_id: &str) -> bool { + remove(KEY_OAUTH_CLIENT_PREFIX, client_id.as_bytes()) +} diff --git a/source/rust/src/store.rs b/source/rust/src/store.rs new file mode 100644 index 0000000..bf8b7f9 --- /dev/null +++ b/source/rust/src/store.rs @@ -0,0 +1,144 @@ +//! JSON 文件存储层:原子写 + 跨 worker 互斥。 +//! +//! **状态就是两个 JSON 文件**,不引入数据库。互斥锁用共享内存里的 `RwLock`。 +//! +//! 所有写操作统一走 `update_*`,流程固定为: +//! +//! ```text +//! 取全局文件写锁 → 读文件 → 闭包修改 → 原子写回 → 放锁 +//! ``` +//! +//! 闭包返回 `Err` 表示业务校验失败,此时**不落盘**。 +//! +//! ## 两个表的分工 +//! +//! | 文件 | 内容 | 是否进共享内存 | +//! | --- | --- | --- | +//! | `users.json` | 账号、口令哈希、身份声明(邮箱/部门/组) | 不整体进;登录时按需读 | +//! | `oauth_clients.json` | 接入方登记(client_id / 密钥 / 回调) | `ocl:` 进(授权热路径要它) | +//! +//! 两个文件都在 `data/` 下,都已 `.gitignore`(含口令哈希与客户端密钥)。 + +use std::path::PathBuf; +use std::sync::Mutex; + +use crate::config::DEFAULT_DATA_DIR; +use crate::models::{OAuthClientTable, UserTable}; +use crate::state; + +/// 状态目录。配置阶段由 `sso_data_dir` 指令设置一次,之后只读。 +static DATA_DIR: Mutex> = Mutex::new(None); + +pub fn set_data_dir(dir: &str) { + if let Ok(mut slot) = DATA_DIR.lock() { + *slot = Some(dir.to_owned()); + } +} + +pub fn data_dir() -> String { + DATA_DIR + .lock() + .ok() + .and_then(|s| s.clone()) + .unwrap_or_else(|| DEFAULT_DATA_DIR.to_owned()) +} + +fn path_of(name: &str) -> PathBuf { + PathBuf::from(data_dir()).join(name) +} + +pub fn users_path() -> PathBuf { + path_of("users.json") +} + +pub fn oauth_clients_path() -> PathBuf { + path_of("oauth_clients.json") +} + +// =========================================================================== +// 读写 +// =========================================================================== + +/// 读取并反序列化;文件缺失或损坏时回退 `default`(不抛错,保证认证侧可用) +fn read_json(path: &PathBuf, default: T) -> T { + let Ok(text) = std::fs::read_to_string(path) else { + return default; + }; + if text.trim().is_empty() { + return default; + } + match serde_json::from_str(&text) { + Ok(v) => v, + Err(e) => { + // 解析失败必须留痕:静默回退会让「数据看起来还在、实际全空」极难排查。 + // 典型触发是有人手工编辑 users.json 时把 groups 写成了非法形状。 + crate::util::log_err(&format!( + "[store] 解析失败,回退默认值:{} ({e})", + path.display() + )); + default + } + } +} + +/// 原子写:先写 `.tmp` 再 rename,避免读到写了一半的内容 +fn write_json(path: &PathBuf, value: &T) -> Result<(), String> { + let text = serde_json::to_string_pretty(value).map_err(|e| format!("序列化失败:{e}"))?; + let tmp = PathBuf::from(format!("{}.tmp", path.display())); + + std::fs::write(&tmp, text.as_bytes()).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + format!("写入临时文件失败:{e}") + })?; + + std::fs::rename(&tmp, path).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + format!("重命名失败:{e}") + }) +} + +// =========================================================================== +// 对外接口 +// =========================================================================== + +pub fn read_users() -> UserTable { + read_json(&users_path(), UserTable::new()) +} + +pub fn read_oauth_clients() -> OAuthClientTable { + read_json(&oauth_clients_path(), OAuthClientTable::new()) +} + +pub fn write_users(data: &UserTable) -> Result<(), String> { + write_json(&users_path(), data) +} + +pub fn write_oauth_clients(data: &OAuthClientTable) -> Result<(), String> { + write_json(&oauth_clients_path(), data) +} + +/// 加锁「读-改-写」账号表。 +/// +/// 闭包返回 `Ok(T)` 表示提交,`Err(msg)` 表示放弃(不写盘)。 +pub fn update_users(f: F) -> Result +where + F: FnOnce(&mut UserTable) -> Result, +{ + let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?; + let mut data = read_users(); + let out = f(&mut data)?; + write_users(&data)?; + Ok(out) +} + +/// 加锁「读-改-写」OAuth 客户端注册表 +pub fn update_oauth_clients(f: F) -> Result +where + F: FnOnce(&mut OAuthClientTable) -> Result, +{ + let _guard = state::file_lock().ok_or("内部错误:状态锁不可用")?; + let mut data = read_oauth_clients(); + let out = f(&mut data)?; + write_oauth_clients(&data)?; + Ok(out) +} diff --git a/source/rust/src/users.rs b/source/rust/src/users.rs new file mode 100644 index 0000000..b197472 --- /dev/null +++ b/source/rust/src/users.rs @@ -0,0 +1,346 @@ +//! 账号体系:管理员与普通账号共用一张表。 +//! +//! 数据结构见 `models::User`。本模块是**账号真源**,两条对外语义: +//! +//! 1. **认证**——`get` / `find_by_key` 供登录、OAuth `password` grant、 +//! 账号态 API 校验凭据; +//! 2. **身份声明**——`email` / `department` / `groups` 由 OIDC claims 与 +//! IAP 的 `X-Auth-*` 注入读取,是下游系统做授权的唯一依据。 +//! +//! ## 与共享内存的关系 +//! +//! 账号**不进共享内存**:登录是低频操作,直接读 `users.json` 即可; +//! 真正每请求的热路径(授权、IAP 门禁)只碰 `sso:` 会话与 `ocl:` 注册表。 +//! 这与被剥离项目里「API Key 索引进 `ukey:` 供 LLM 热路径查」的做法不同—— +//! 那是为每请求的转发决策服务的,本项目没有这一层。 + +use serde_json::{Value, json}; + +use crate::config::{ + DEPARTMENT_MAX_LEN, DISPLAY_NAME_MAX_LEN, GROUPS_MAX, GROUP_NAME_MAX_LEN, + INIT_ADMIN_PASSWORD_DEFAULT, INIT_ADMIN_PASSWORD_ENV, INIT_ADMIN_USER, PASSWORD_MIN_LEN, + USERNAME_MAX_LEN, USERNAME_MIN_LEN, +}; +use crate::models::{User, UserTable}; +use crate::store; +use crate::util; + +// =========================================================================== +// 校验 +// =========================================================================== + +/// 账号名:2-32 位字母、数字、下划线或短横线 +fn valid_username(name: &str) -> bool { + let n = name.chars().count(); + if n < USERNAME_MIN_LEN || n > USERNAME_MAX_LEN { + return false; + } + name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') +} + +/// 展示名:允许中文/空格,但**不允许换行或制表等控制字符**—— +/// 它会被塞进管理台 HTML(已转义)、JSON 与注入头,控制字符只会造成排版错乱 +/// 或头注入。 +pub fn check_display_name(raw: &str) -> Result { + let v = util::trim(raw).to_owned(); + if v.chars().count() > DISPLAY_NAME_MAX_LEN { + return Err(format!("展示名不能超过 {DISPLAY_NAME_MAX_LEN} 个字")); + } + if v.chars().any(|c| c.is_control()) { + return Err("展示名不能包含换行或控制字符".to_owned()); + } + Ok(v) +} + +/// 邮箱:只做「像不像」的宽松校验。**不接受控制字符**——它会被注入 HTTP 响应头。 +pub fn check_email(raw: &str) -> Result { + let v = util::trim(raw).to_owned(); + if v.is_empty() { + return Ok(v); + } + if v.len() > 254 || v.chars().any(|c| c.is_control() || c == ' ') { + return Err("邮箱格式不正确".to_owned()); + } + if !v.contains('@') || v.starts_with('@') || v.ends_with('@') { + return Err("邮箱格式不正确".to_owned()); + } + Ok(v) +} + +/// 部门名:同样禁止控制字符。 +pub fn check_department(raw: &str) -> Result { + let v = util::trim(raw).to_owned(); + if v.chars().count() > DEPARTMENT_MAX_LEN { + return Err(format!("部门名不能超过 {DEPARTMENT_MAX_LEN} 个字")); + } + if v.chars().any(|c| c.is_control()) { + return Err("部门名不能包含换行或控制字符".to_owned()); + } + Ok(v) +} + +/// 用户组:逗号/顿号/分号/空白分隔,去重后返回(顺序保留)。 +/// +/// 组名会进 OIDC `groups` 与注入头 `X-Auth-Groups`,因此同样禁止换行/逗号。 +pub fn check_groups(raw: &str) -> Result, String> { + let mut out: Vec = Vec::new(); + for part in raw.split(|c: char| c == ',' || c == '、' || c == ';' || c == '\n' || c == '\t' || c == ' ') { + let g = part.trim(); + if g.is_empty() { + continue; + } + if g.chars().count() > GROUP_NAME_MAX_LEN { + return Err(format!("组名不能超过 {GROUP_NAME_MAX_LEN} 个字:{g}")); + } + if !out.iter().any(|x| x == g) { + out.push(g.to_owned()); + } + } + if out.len() > GROUPS_MAX { + return Err(format!("单个账号最多归属 {GROUPS_MAX} 个用户组")); + } + Ok(out) +} + +// =========================================================================== +// 查询 +// =========================================================================== + +pub fn get(username: &str) -> Option { + if username.is_empty() { + return None; + } + store::read_users().remove(username) +} + +/// 全部账号,按账号名升序(`BTreeMap` 天然有序) +pub fn all() -> Vec { + store::read_users().into_values().collect() +} + +/// 按 API Key 反查账号(常量时间比较,避免时序侧信道)。 +/// +/// 每次都同步读 `users.json` 并全表解码,只适合管理/账号态接口这类低频调用方。 +pub fn find_by_key(key: &str) -> Option { + if key.is_empty() { + return None; + } + store::read_users() + .into_values() + .find(|u| util::ct_eq(&u.api_key, key)) +} + +// =========================================================================== +// 写入 +// =========================================================================== + +fn build_user(username: &str, display_name: &str, password: &str, role: &str) -> User { + let salt = util::gen_salt(); + User { + username: username.to_owned(), + display_name: display_name.to_owned(), + role: role.to_owned(), + pwd_hash: util::hash_password(password, &salt), + salt, + api_key: util::gen_key(), + email: String::new(), + department: String::new(), + groups: Vec::new(), + created_at: util::now(), + } +} + +/// 首次启动播种管理员。已有数据时原样返回,**不会覆盖**。 +/// +/// 返回 `Ok(true)` 表示「本次真的创建了」,用于打一条提醒日志。 +pub fn seed_admin() -> Result { + let password = std::env::var(INIT_ADMIN_PASSWORD_ENV) + .unwrap_or_else(|_| INIT_ADMIN_PASSWORD_DEFAULT.to_owned()); + + let mut created: Option = None; + store::update_users(|users| { + if !users.is_empty() { + return Ok(()); + } + let admin = build_user(INIT_ADMIN_USER, "", &password, "admin"); + users.insert(admin.username.clone(), admin.clone()); + created = Some(admin); + Ok(()) + })?; + + Ok(created.is_some()) +} + +pub fn create( + username: &str, + display_name: &str, + password: &str, + role: &str, + email: &str, + department: &str, + groups: &str, +) -> Result { + let username = util::trim(username).to_owned(); + if !valid_username(&username) { + return Err(format!( + "账号名只能是 {USERNAME_MIN_LEN}-{USERNAME_MAX_LEN} 位字母、数字、下划线或短横线" + )); + } + let display_name = check_display_name(display_name)?; + if password.len() < PASSWORD_MIN_LEN { + return Err(format!("密码至少 {PASSWORD_MIN_LEN} 位")); + } + let email = check_email(email)?; + let department = check_department(department)?; + let groups = check_groups(groups)?; + let role = if role == "admin" { "admin" } else { "user" }; + + // 先做一次存在性预检,省掉白算 1000 轮哈希;真正的判定仍在锁内 + if store::read_users().contains_key(&username) { + return Err(format!("账号 {username} 已存在")); + } + + let mut user = build_user(&username, &display_name, password, role); + user.email = email; + user.department = department; + user.groups = groups; + + let created = user.clone(); + store::update_users(move |users| { + if users.contains_key(&username) { + return Err(format!("账号 {username} 已存在")); + } + users.insert(username.clone(), user); + Ok(()) + })?; + + Ok(created) +} + +/// 设置展示名(中文姓名等)。只影响展示,不碰口令与凭据。 +pub fn set_display_name(username: &str, display_name: &str) -> Result { + let display_name = check_display_name(display_name)?; + store::update_users(move |users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + user.display_name = display_name; + Ok(user.clone()) + }) +} + +/// 设置身份声明(邮箱 / 部门 / 用户组)。 +/// +/// 三者原样进入 OIDC claims 与 IAP 注入头,所以这里是**授权数据的唯一写入口**, +/// 改动立即对下一次令牌签发 / 下一次请求生效(无需重启,也无需清会话—— +/// IAP 门禁读的 `sso:` 会话 payload 在登录时写入,见 `oauth::iap_identity` 的说明)。 +pub fn set_profile( + username: &str, + email: &str, + department: &str, + groups_raw: &str, + display_name: Option<&str>, +) -> Result { + let email = check_email(email)?; + let department = check_department(department)?; + let groups = check_groups(groups_raw)?; + let display_name = match display_name { + Some(d) => Some(check_display_name(d)?), + None => None, + }; + + store::update_users(move |users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + user.email = email; + user.department = department; + user.groups = groups; + if let Some(d) = display_name { + user.display_name = d; + } + Ok(user.clone()) + }) +} + +/// 设置角色(`admin` / `user`)。 +/// +/// 红线与 `delete` 一致:**不允许把最后一个管理员降级**,否则管理台会永久锁死。 +pub fn set_role(username: &str, role: &str) -> Result { + let role = if role == "admin" { "admin" } else { "user" }.to_owned(); + store::update_users(move |users: &mut UserTable| { + let current = users.get(username).ok_or("账号不存在")?.role.clone(); + if current == "admin" && role != "admin" { + let admins = users.values().filter(|u| u.role == "admin").count(); + if admins <= 1 { + return Err("至少需要保留一个管理员账号".to_owned()); + } + } + let user = users.get_mut(username).ok_or("账号不存在")?; + user.role = role; + Ok(user.clone()) + }) +} + +/// 重置 API Key,返回新 Key。旧 Key 立即失效。 +pub fn regenerate_key(username: &str) -> Result { + store::update_users(|users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + user.api_key = util::gen_key(); + Ok(user.api_key.clone()) + }) +} + +pub fn set_password(username: &str, password: &str) -> Result<(), String> { + if password.len() < PASSWORD_MIN_LEN { + return Err(format!("密码至少 {PASSWORD_MIN_LEN} 位")); + } + let salt = util::gen_salt(); + let hash = util::hash_password(password, &salt); + + store::update_users(move |users: &mut UserTable| { + let user = users.get_mut(username).ok_or("账号不存在")?; + user.salt = salt; + user.pwd_hash = hash; + Ok(()) + }) +} + +/// 删除账号。两条红线:不能删自己、必须至少保留一个管理员。 +pub fn delete(username: &str, operator: &str) -> Result<(), String> { + if username == operator { + return Err("不能删除当前登录的账号".to_owned()); + } + let username = username.to_owned(); + store::update_users(move |users| { + let user = users.get(&username).ok_or("账号不存在")?; + if user.role == "admin" { + let admins = users.values().filter(|u| u.role == "admin").count(); + if admins <= 1 { + return Err("至少需要保留一个管理员账号".to_owned()); + } + } + users.remove(&username); + Ok(()) + }) +} + +// =========================================================================== +// 对外投影 +// =========================================================================== + +/// 转成前端可见的字段(**绝不包含 salt / pwd_hash**) +pub fn view(user: &User) -> Value { + json!({ + "username": user.username, + "display_name": user.display_name, + // 前端统一用 name 渲染——展示名优先,没有就回落到账号名 + "name": user.display_or_username(), + "role": user.role, + "is_admin": user.is_admin(), + "email": user.email, + "department": user.department, + "groups": user.groups, + "groups_csv": user.groups_csv(), + "api_key": user.api_key, + "api_key_masked": util::mask_key(&user.api_key), + "created_at": user.created_at, + "created_at_text": util::fmt_time(user.created_at), + }) +} diff --git a/source/rust/src/util.rs b/source/rust/src/util.rs new file mode 100644 index 0000000..f98cc7e --- /dev/null +++ b/source/rust/src/util.rs @@ -0,0 +1,292 @@ +//! 通用工具:时间 / 随机 / 摘要 / 口令哈希 / 常量时间比较 / 格式化 / 参数解码。 +//! +//! 对应旧版的 `lua/util.lua`。其中 `hash_password` 的算法**必须逐位一致**, +//! 否则旧的 `data/users.json` 里的口令哈希将全部失效。 + +use sha2::{Digest, Sha256}; + +use crate::config::HASH_ROUNDS; + +// =========================================================================== +// 日志 +// =========================================================================== + +/// 写 nginx error log。 +/// +/// 形参顺序容易记错:`ngx_log_error_core(level, log, err, fmt, ...)`, +/// 其中 `err` 只在需要附带系统错误号时非 0。 +pub fn log_at(level: usize, msg: &str) { + // SAFETY: 传入的 CString 在本调用期间存活;日志接口不持有其引用 + unsafe { + let c = std::ffi::CString::new(msg).unwrap_or_default(); + let lg = if nginx_sys::ngx_cycle.is_null() { + core::ptr::null_mut() + } else { + (*nginx_sys::ngx_cycle).log + }; + nginx_sys::ngx_log_error_core(level, lg, 0, c"%s".as_ptr(), c.as_ptr()); + } +} + +pub fn log_err(msg: &str) { + log_at(nginx_sys::NGX_LOG_ERR as usize, msg); +} + +pub fn log_warn(msg: &str) { + log_at(nginx_sys::NGX_LOG_WARN as usize, msg); +} + +pub fn log_notice(msg: &str) { + log_at(nginx_sys::NGX_LOG_NOTICE as usize, msg); +} + +// =========================================================================== +// 时间 +// =========================================================================== + +/// 当前 Unix 时间戳(秒)。 +/// +/// nginx 的 `ngx_time()` 是宏,bindgen 拿不到;直接走 libc 的 `time()`, +/// 在 Linux/macOS 上都由 vDSO 提供,代价与读一个全局变量相当。 +#[inline] +pub fn now() -> i64 { + // SAFETY: time(NULL) 只读系统时钟,无副作用 + unsafe { libc::time(core::ptr::null_mut()) as i64 } +} + +/// `%Y-%m-%d %H:%M:%S`(本地时区,等价旧版 `os.date`);ts <= 0 返回 `-` +pub fn fmt_time(ts: i64) -> String { + if ts <= 0 { + return "-".to_owned(); + } + // SAFETY: 传入有效指针;localtime_r 不返回静态数据,线程安全 + unsafe { + let t = ts as libc::time_t; + let mut tm: libc::tm = core::mem::zeroed(); + if libc::localtime_r(&t, &mut tm).is_null() { + return "-".to_owned(); + } + let mut buf = [0 as libc::c_char; 40]; + let fmt = c"%Y-%m-%d %H:%M:%S"; + let n = libc::strftime(buf.as_mut_ptr(), buf.len(), fmt.as_ptr(), &tm); + if n == 0 { + return "-".to_owned(); + } + core::ffi::CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned() + } +} + +// =========================================================================== +// 随机与十六进制 +// =========================================================================== + +pub fn to_hex(bytes: &[u8]) -> String { + let mut out = String::with_capacity(bytes.len() * 2); + for &b in bytes { + out.push(HEX[(b >> 4) as usize] as char); + out.push(HEX[(b & 0x0f) as usize] as char); + } + out +} + +/// 小写十六进制字母表(模块级,供 `to_hex` / `url_encode` 共用) +const HEX: &[u8; 16] = b"0123456789abcdef"; + +/// 密码学安全随机字节。取不到随机源时返回 None(调用方必须显式处理, +/// **不允许**退化成可预测的伪随机——那等于把 API Key 直接送给攻击者)。 +fn rand_bytes(buf: &mut [u8]) -> Option<()> { + getrandom::getrandom(buf).ok() +} + +/// `n` 字节随机数的 hex 表示(会话 token 等场景) +pub fn rand_hex(n: usize) -> String { + let mut b = vec![0u8; n]; + if rand_bytes(&mut b).is_none() { + let mut seed = now() as u64 ^ 0x2545_f491_4f6c_dd1d; + for byte in b.iter_mut() { + // xorshift:随机源失效时的最后手段,至少不产出常量 + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + *byte = (seed & 0xff) as u8; + } + } + to_hex(&b) +} + +/// 口令盐:16 字节 → 32 位 hex +pub fn gen_salt() -> String { + let mut b = [0u8; 16]; + if rand_bytes(&mut b).is_none() { + // 极罕见:随机源不可用。此处不能 panic(会崩掉整个 worker), + // 退化为基于时间的混淆值并让上层记录失败。 + let n = now() as u64 ^ 0x9e37_79b9_7f4a_7c15; + b[..8].copy_from_slice(&n.to_le_bytes()); + b[8..].copy_from_slice(&n.rotate_left(17).to_le_bytes()); + } + to_hex(&b) +} + +/// 账号 API Key:`sk_` + 24 字节 → 48 位 hex +pub fn gen_key() -> String { + let mut b = [0u8; 24]; + if rand_bytes(&mut b).is_none() { + let n = now() as u64; + for (i, chunk) in b.chunks_mut(8).enumerate() { + chunk.copy_from_slice(&n.rotate_left((i as u32) * 13).to_le_bytes()); + } + } + format!("sk_{}", to_hex(&b)) +} + +// =========================================================================== +// 摘要与口令 +// =========================================================================== + +pub fn sha256_hex(data: &[u8]) -> String { + let mut h = Sha256::new(); + h.update(data); + to_hex(&h.finalize()) +} + +/// 迭代加盐哈希,降低撞库速度。 +/// +/// 算法(与旧版 `util.hash_password` 完全一致): +/// x = sha256(salt + ":" + password) +/// 重复 HASH_ROUNDS 次:x = sha256(x + salt) +pub fn hash_password(password: &str, salt: &str) -> String { + let mut x = sha256_hex(format!("{salt}:{password}").as_bytes()); + for _ in 0..HASH_ROUNDS { + x = sha256_hex(format!("{x}{salt}").as_bytes()); + } + x +} + +pub fn verify_password(password: &str, salt: &str, expected: &str) -> bool { + ct_eq(&hash_password(password, salt), expected) +} + +/// 常量时间比较:无论差异出现在第几位,都在同一轮数内完成。 +pub fn ct_eq(a: &str, b: &str) -> bool { + let (a, b) = (a.as_bytes(), b.as_bytes()); + if a.len() != b.len() { + return false; + } + let mut diff = 0u8; + for i in 0..a.len() { + diff |= a[i] ^ b[i]; + } + diff == 0 +} + +// =========================================================================== +// 文本 +// =========================================================================== + +pub fn trim(v: &str) -> &str { + v.trim() +} + +pub fn to_bool(v: Option<&String>) -> bool { + match v { + Some(s) => matches!(s.to_ascii_lowercase().as_str(), "1" | "true" | "on" | "yes"), + None => false, + } +} + +/// `sk_12345678...abcd` → `sk_12345...abcd` +pub fn mask_key(key: &str) -> String { + if key.len() < 12 { + return key.to_owned(); + } + format!("{}...{}", &key[..8], &key[key.len() - 4..]) +} + +/// percent-decode(`%XX`)并把 `+` 还原为空格。 +/// +/// 旧版由 `ngx.req.get_uri_args` / `get_post_args` 自动完成, +/// Rust 侧必须自己实现,否则带中文或特殊字符的参数会解析错误。 +pub fn url_decode(input: &str) -> String { + let bytes = input.as_bytes(); + let mut out: Vec = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + match bytes[i] { + b'+' => { + out.push(b' '); + i += 1; + } + b'%' if i + 2 < bytes.len() => { + let hi = (bytes[i + 1] as char).to_digit(16); + let lo = (bytes[i + 2] as char).to_digit(16); + match (hi, lo) { + (Some(h), Some(l)) => { + out.push((h * 16 + l) as u8); + i += 3; + } + _ => { + out.push(b'%'); + i += 1; + } + } + } + b => { + out.push(b); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +/// 解析 `a=1&b=2` 形式的键值对(自动 percent-decode)。 +pub fn parse_kv(raw: &[u8]) -> Vec<(String, String)> { + let mut out = Vec::new(); + let text = String::from_utf8_lossy(raw); + for pair in text.split('&') { + if pair.is_empty() { + continue; + } + let mut it = pair.splitn(2, '='); + let k = it.next().unwrap_or(""); + let v = it.next().unwrap_or(""); + out.push((url_decode(k), url_decode(v))); + } + out +} + +/// percent-encode(用于回调地址等放进查询参数前的转义)。 +/// +/// 只编码非「非保留字符」集(RFC 3986 unreserved:`A-Za-z0-9-._~`)。 +pub fn url_encode(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + for b in input.bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + out.push(b as char); + } + _ => { + out.push('%'); + out.push(HEX[(b >> 4) as usize] as char); + out.push(HEX[(b & 0x0f) as usize] as char); + } + } + } + out +} + +/// HTML 转义(防登录表单回显时的注入)。 +pub fn html_escape(input: &str) -> String { + let mut out = String::with_capacity(input.len()); + for c in input.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(c), + } + } + out +} diff --git a/source/rust/vendor/ngx-rust/.cargo/audit.toml b/source/rust/vendor/ngx-rust/.cargo/audit.toml new file mode 100644 index 0000000..e796859 --- /dev/null +++ b/source/rust/vendor/ngx-rust/.cargo/audit.toml @@ -0,0 +1,35 @@ +# audit config file +# +# It may be located in the user home (`~/.cargo/audit.toml`) or in the project +# root (`.cargo/audit.toml`). +# +# All of the options which can be passed via CLI arguments can also be +# permanently specified in this file. +# It may be located in the user home (`~/.cargo/audit.toml`) or in the project +# root (`.cargo/audit.toml`). + +[advisories] +ignore = ["RUSTSEC-2020-0071"] + +# # Advisory Database Configuration +# [database] +# path = "~/.cargo/advisory-db" # Path where advisory git repo will be cloned +# url = "https://github.com/RustSec/advisory-db.git" # URL to git repo +# fetch = true # Perform a `git fetch` before auditing (default: true) +# stale = false # Allow stale advisory DB (i.e. no commits for 90 days, default: false) + +# # Output Configuration +# [output] +# deny = ["unmaintained"] # exit on error if unmaintained dependencies are found +# format = "terminal" # "terminal" (human readable report) or "json" +# quiet = false # Only print information on error +# show_tree = true # Show inverse dependency trees along with advisories (default: true) + +# # Target Configuration +# [target] +# arch = "x86_64" # Ignore advisories for CPU architectures other than this one +# os = "linux" # Ignore advisories for operating systems other than this one + +# [yanked] +# enabled = true # Warn for yanked crates in Cargo.lock (default: true) +# update_index = true # Auto-update the crates.io index (default: true) diff --git a/source/rust/vendor/ngx-rust/.cargo/config.toml b/source/rust/vendor/ngx-rust/.cargo/config.toml new file mode 100644 index 0000000..910c3da --- /dev/null +++ b/source/rust/vendor/ngx-rust/.cargo/config.toml @@ -0,0 +1,2 @@ +[env] +CACHE_DIR = { value = ".cache", relative = true } diff --git a/source/rust/vendor/ngx-rust/.dockerignore b/source/rust/vendor/ngx-rust/.dockerignore new file mode 100644 index 0000000..d1c460e --- /dev/null +++ b/source/rust/vendor/ngx-rust/.dockerignore @@ -0,0 +1,23 @@ +**/.idea +.cargo +.dockerignore +.git +.github +CHANGELOG.md +CODE_OF_CONDUCT.md +CONTRIBUTING.md +Containerfile.debian +Dockerfile +GNUmakefile +LICENSE.txt +README.md +SECURITY.md +build + +.vscode/** + +**/target +target + +.cache/ +.nginx/ diff --git a/source/rust/vendor/ngx-rust/.git-blame-ignore-revs b/source/rust/vendor/ngx-rust/.git-blame-ignore-revs new file mode 100644 index 0000000..15ce9d0 --- /dev/null +++ b/source/rust/vendor/ngx-rust/.git-blame-ignore-revs @@ -0,0 +1,17 @@ +# This file specifies the revisions hidden from the blame view in GitHub UI. +# +# You can achieve the same effect locally with "--ignore-revs-file": +# +# git blame --ignore-revs-file .git-blame-ignore-revs +# +# or "blame.ignoreRevsFile" configuration option +# +# git config --local blame.ignoreRevsFile .git-blame-ignore-revs +# +# See also: +# https://docs.github.com/en/repositories/working-with-files/using-files/viewing-and-understanding-files + +# Tree-wide formatting change: max-width 120 -> 100 +d866b64a3c83105c20b0c005392f8e8fcaaf2066 +# Tree-wide formatting change: use_small_heuristics -> "Max" +4b30e402b0393dd4b888980d57ce6792adbb9455 diff --git a/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/bug_report.md b/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..a85753e --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,29 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. See my project that depends on this project +2. View logs on '....' +3. Run this test I created +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Your environment** +* Version of the repo - a specific commit or tag +* Version of ngx-rust +* Version of Rust +* Version of NGINX (and all dependencies if modified) +* OS and distribution +* Details about containerization, virtualization, or physical environment + +**Additional context** +Add any other context about the problem here. Any log files you want to share. diff --git a/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/feature_request.md b/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..6bcce42 --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +--- +name: Feature request +about: Suggest an idea for this project + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/.github/PULL_REQUEST_TEMPLATE.md b/source/rust/vendor/ngx-rust/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..0037d3d --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,15 @@ +### Proposed changes +Describe the use case and detail of the change. If this PR addresses an issue +on GitHub, make sure to include a link to that issue here in this description +(not in the title of the PR). + +### Checklist +Before creating a PR, run through this checklist and mark each as complete. + +- [ ] I have written my commit messages in the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format. +- [ ] I have read the [CONTRIBUTING](/CONTRIBUTING.md) doc +- [ ] I have added tests (when possible) that prove my fix is effective or that my feature works +- [ ] I have checked that all unit tests pass after adding my changes +- [ ] I have updated necessary documentation +- [ ] I have rebased my branch onto main +- [ ] I will ensure my PR is targeting the main branch and pulling from my branch from my own fork diff --git a/source/rust/vendor/ngx-rust/.github/dependabot.yml b/source/rust/vendor/ngx-rust/.github/dependabot.yml new file mode 100644 index 0000000..0b574cc --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/dependabot.yml @@ -0,0 +1,26 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + + - package-ecosystem: "cargo" + allow: + # Allow both direct and indirect updates for all packages. + - dependency-type: "all" + directory: "/" # Location of package manifests + schedule: + interval: "weekly" + groups: + all-dependencies: + patterns: + - "*" + # semver-incompatible updates will be handled manually + versioning-strategy: "lockfile-only" + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" diff --git a/source/rust/vendor/ngx-rust/.github/workflows/cargo-deny.yaml b/source/rust/vendor/ngx-rust/.github/workflows/cargo-deny.yaml new file mode 100644 index 0000000..1e44ade --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/workflows/cargo-deny.yaml @@ -0,0 +1,25 @@ +name: cargo-deny +on: + push: + branches: + - main + - "[0-9]+.[0-9]+.x" + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + strategy: + matrix: + checks: + - advisories + - bans licenses sources + + # Prevent sudden announcement of a new advisory from failing ci: + continue-on-error: ${{ matrix.checks == 'advisories' }} + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: EmbarkStudios/cargo-deny-action@3c6349835b2b7b196a839186cb8b78e02f7b5f25 # v2.1.1 + with: + command: check ${{ matrix.checks }} diff --git a/source/rust/vendor/ngx-rust/.github/workflows/ci.yaml b/source/rust/vendor/ngx-rust/.github/workflows/ci.yaml new file mode 100644 index 0000000..d02c3c5 --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/workflows/ci.yaml @@ -0,0 +1,194 @@ +name: Rust + +on: [ push, pull_request ] + +env: + CARGO_TERM_COLOR: 'always' + CARGO_TERM_VERBOSE: 'true' + RUSTFLAGS: '--deny warnings' + RUSTDOCFLAGS: '-Dwarnings' + +jobs: + rust-version: + name: Minimal supported Rust version + outputs: + version: ${{ steps.read_version.outputs.msrv }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - id: read_version + run: | + awk -F '=' \ + '/^rust-version[[:space:]]*=/ { gsub(/([" ]|#.*)/,"",$2); print ("msrv=" $2) }' \ + Cargo.toml \ + | tee -a "$GITHUB_OUTPUT" + + test-linux: + name: Test (Linux) + needs: rust-version + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + rust-version: + - ${{ needs.rust-version.outputs.version }} + - stable + steps: + - name: checkout source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: true + - name: set up cargo cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + continue-on-error: false + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ matrix.rust-version}}-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo-${{ matrix.rust-version }}- + - name: set up nginx deps cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + continue-on-error: false + with: + path: | + .cache/.gnupg + .cache/nginx + .cache/*.tar.gz + .cache/*.tar.asc + .cache/*.tar.sig + key: ${{ runner.os }}-deps-${{ hashFiles('**/nginx-sys/build.rs') }} + restore-keys: ${{ runner.os }}-deps- + + - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 + with: + components: rustfmt, clippy + toolchain: ${{ matrix.rust-version }} + + - name: build (all targets, all features) + id: build + run: cargo build --workspace --all-targets --all-features + + - name: check ngx, no default features (no_std) + run: cargo check -p ngx --no-default-features --features vendored + + - name: check ngx, alloc + run: cargo check -p ngx --no-default-features --features vendored,alloc + + - name: check ngx, std + run: cargo check -p ngx --no-default-features --features vendored,std + + - name: check ngx, alloc + serde + run: cargo check -p ngx --no-default-features --features vendored,alloc,serde + + - name: clippy + # always run if build succeeds + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + run: cargo clippy --workspace --all-targets --all-features -- -Dwarnings + + - name: test + # always run if build succeeds + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + run: cargo test --workspace --all-features + + - name: rustdoc + # always run if build succeeds + if: ${{ !cancelled() && steps.build.outcome == 'success' }} + run: cargo doc --all-features --no-deps + + examples-linux: + name: Examples (Linux) + runs-on: ubuntu-latest + steps: + - name: checkout source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: true + - name: set up cargo cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + continue-on-error: false + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo- + - name: set up nginx deps cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + continue-on-error: false + with: + path: | + .cache/.gnupg + .cache/nginx + .cache/*.tar.gz + .cache/*.tar.asc + .cache/*.tar.sig + key: ${{ runner.os }}-deps-${{ hashFiles('**/nginx-sys/build.rs') }} + restore-keys: ${{ runner.os }}-deps- + - name: compile examples + run: cargo build --release --package examples --examples --all-features + + test-macos: + name: Test (MacOS) + runs-on: macos-latest + steps: + - name: install command line dependencies + run: brew install make gnupg + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + submodules: true + - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 + with: + toolchain: stable + - name: set up cargo cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + continue-on-error: false + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + target/ + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo- + - name: set up nginx deps cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + continue-on-error: false + with: + path: | + .cache/*.tar.gz + .cache/*.tar.asc + .cache/*.tar.sig + key: ${{ runner.os }}-deps-${{ hashFiles('**/nginx-sys/build.rs') }} + restore-keys: ${{ runner.os }}-deps- + - name: current directory + run: pwd + - name: make cache directory + run: mkdir -p .cache/.gnupg + - name: disable ipv6 for gpg + run: echo "disable-ipv6" > .cache/.gnupg/dirmngr.conf + - name: build + run: cargo build --workspace --all-targets --features "async,vendored" + - name: run tests + run: cargo test --workspace --features "async,vendored" + + fmt: + name: Rustfmt + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 + with: + components: rustfmt + toolchain: stable + - name: rustfmt version + run: rustfmt --version + - name: cargo fmt + run: cargo fmt --all --check diff --git a/source/rust/vendor/ngx-rust/.github/workflows/nginx.yaml b/source/rust/vendor/ngx-rust/.github/workflows/nginx.yaml new file mode 100644 index 0000000..2f88fbc --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/workflows/nginx.yaml @@ -0,0 +1,238 @@ +name: NGINX + +on: + push: + branches: + - main + - "[0-9]+.[0-9]+.x" + pull_request: + +env: + CARGO_TERM_COLOR: 'always' + RUST_BACKTRACE: '1' + NGX_CONFIGURE_CMD: >- + auto/configure + --with-compat + --with-debug + --with-http_realip_module + --with-http_ssl_module + --with-http_v2_module + --with-stream + --with-stream_realip_module + --with-stream_ssl_module + + NGX_CONFIGURE_UNIX: >- + --with-threads + + NGX_CONFIGURE_WINDOWS: >- + --with-cc=cl + --prefix= + --conf-path=conf/nginx.conf + --pid-path=logs/nginx.pid + --http-log-path=logs/access.log + --error-log-path=logs/error.log + --sbin-path=nginx.exe + --http-client-body-temp-path=temp/client_body_temp + --http-proxy-temp-path=temp/proxy_temp + --http-fastcgi-temp-path=temp/fastcgi_temp + --http-scgi-temp-path=temp/scgi_temp + --http-uwsgi-temp-path=temp/uwsgi_temp + --with-cc-opt=-DFD_SETSIZE=1024 + --with-pcre=objs/lib/pcre + --with-zlib=objs/lib/zlib + --with-openssl=objs/lib/openssl + --with-openssl-opt="no-asm no-module no-tests no-makedepend -D_WIN32_WINNT=0x0601" + + NGX_CONFIGURE_DYNAMIC_MODULES: >- + --add-dynamic-module=${{ github.workspace }}/examples + NGX_CONFIGURE_STATIC_MODULES: >- + --add-module=${{ github.workspace }}/examples + + NGX_TEST_FILES: examples/t + NGX_TEST_GLOBALS_DYNAMIC: >- + load_module ${{ github.workspace }}/nginx/objs/ngx_http_async_module.so; + load_module ${{ github.workspace }}/nginx/objs/ngx_http_awssigv4_module.so; + load_module ${{ github.workspace }}/nginx/objs/ngx_http_curl_module.so; + load_module ${{ github.workspace }}/nginx/objs/ngx_http_shared_dict_module.so; + load_module ${{ github.workspace }}/nginx/objs/ngx_http_upstream_custom_module.so; + + OPENSSL_VERSION: '3.0.16' + PCRE2_VERSION: '10.45' + ZLIB_VERSION: '1.3.1' + +jobs: + linux: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + nginx-ref: + - master + - stable-1.30 + module: + - static + - dynamic + include: + # minimal supported nginx version (Debian bookworm: 1.22.1) + - nginx-ref: stable-1.22 + module: dynamic + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ matrix.nginx-ref }} + repository: 'nginx/nginx' + path: 'nginx' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: 'nginx/nginx-tests' + path: 'nginx/tests' + sparse-checkout: | + lib + + - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 + with: + toolchain: stable + + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + nginx/objs/**/CACHEDIR.TAG + nginx/objs/**/ngx-debug + nginx/objs/**/ngx-release + key: ${{ runner.os }}-nginx-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-nginx- + + - name: Update configure arguments + if: matrix.nginx-ref != 'stable-1.22' + run: | + echo NGX_CONFIGURE_UNIX="${NGX_CONFIGURE_UNIX} --with-http_v3_module" \ + >> "$GITHUB_ENV" + + - name: Configure nginx with static modules + if: matrix.module == 'static' + working-directory: nginx + run: | + ${NGX_CONFIGURE_CMD} \ + ${NGX_CONFIGURE_UNIX} \ + ${NGX_CONFIGURE_STATIC_MODULES} + + - name: Configure nginx with dynamic modules + if: matrix.module != 'static' + working-directory: nginx + run: | + ${NGX_CONFIGURE_CMD} \ + ${NGX_CONFIGURE_UNIX} \ + ${NGX_CONFIGURE_DYNAMIC_MODULES} + echo TEST_NGINX_GLOBALS="$NGX_TEST_GLOBALS_DYNAMIC" >> "$GITHUB_ENV" + + - name: Build nginx + working-directory: nginx + run: make -j$(nproc) + + - name: Run tests + env: + PERL5LIB: ${{ github.workspace }}/nginx/tests/lib + TEST_NGINX_BINARY: ${{ github.workspace }}/nginx/objs/nginx + TEST_NGINX_MODULES: ${{ github.workspace }}/nginx/objs + TEST_NGINX_VERBOSE: 1 + run: | + prove -j$(nproc) --state=save ${NGX_TEST_FILES} || prove -v --state=failed + + windows: + runs-on: windows-2022 + env: + TEMP: "C:\\TEMP" + TMP: "C:\\TEMP" + TMPDIR: "C:\\TEMP" + VCARCH: x64 + + strategy: + fail-fast: false + matrix: + nginx-ref: + - master + module: + - static + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ matrix.nginx-ref }} + repository: 'nginx/nginx' + path: 'nginx' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: 'nginx/nginx-tests' + path: 'nginx/tests' + sparse-checkout: | + lib + + - uses: dtolnay/rust-toolchain@e97e2d8cc328f1b50210efc529dca0028893a2d9 + with: + toolchain: stable + + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + nginx/objs/**/CACHEDIR.TAG + nginx/objs/**/ngx-debug + nginx/objs/**/ngx-release + key: ${{ runner.os }}-nginx-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-nginx- + + - name: Prepare build environment + shell: bash + working-directory: nginx + run: | + # Disable dynamic lookup of WSAPoll(); it crashes if the symbol is already imported by + # Rust stdlib. + sed 's/\(_WIN32_WINNT\s*\) 0x0501/\1 0x0601/' -i src/os/win32/ngx_win32_config.h + + echo VCVARSALL="$('C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe' -products \* -latest -property installationPath)\\VC\\Auxiliary\\Build\\vcvarsall.bat" \ + >> "$GITHUB_ENV" + + mkdir -p $TEMP + mkdir -p objs/lib + + curl -sLO https://github.com/PCRE2Project/pcre2/releases/download/pcre2-$PCRE2_VERSION/pcre2-$PCRE2_VERSION.tar.gz + tar -C objs/lib --transform "s/pcre2-$PCRE2_VERSION/pcre/" -xzf ./pcre2-$PCRE2_VERSION.tar.gz + echo '#include ' > objs/lib/pcre/src/inttypes.h + + curl -sLO https://github.com/madler/zlib/releases/download/v$ZLIB_VERSION/zlib-$ZLIB_VERSION.tar.gz + tar -C objs/lib --transform "s/zlib-$ZLIB_VERSION/zlib/" -xzf ./zlib-$ZLIB_VERSION.tar.gz + + curl -sLO https://github.com/openssl/openssl/releases/download/openssl-$OPENSSL_VERSION/openssl-$OPENSSL_VERSION.tar.gz + tar -C objs/lib --transform "s/openssl-$OPENSSL_VERSION/openssl/" -xzf ./openssl-$OPENSSL_VERSION.tar.gz + + - name: Configure and build nginx + shell: cmd + working-directory: nginx + run: | + @echo on + call "%VCVARSALL%" %VCARCH% + bash.exe ^ + %NGX_CONFIGURE_CMD% ^ + %NGX_CONFIGURE_WINDOWS% ^ + %NGX_CONFIGURE_STATIC_MODULES% + nmake -f objs/Makefile + + - name: Run tests + shell: cmd + env: + PERL5LIB: "${{ github.workspace }}\\nginx\\tests\\lib" + TEST_NGINX_BINARY: "${{ github.workspace }}\\nginx\\objs\\nginx.exe" + TEST_NGINX_VERBOSE: 1 + run: | + prove --state=save %NGX_TEST_FILES% || prove -v --state=failed diff --git a/source/rust/vendor/ngx-rust/.github/workflows/sanitizers.yaml b/source/rust/vendor/ngx-rust/.github/workflows/sanitizers.yaml new file mode 100644 index 0000000..d2bc2d1 --- /dev/null +++ b/source/rust/vendor/ngx-rust/.github/workflows/sanitizers.yaml @@ -0,0 +1,112 @@ +name: sanitizers + +on: + push: + branches: + - main + - "[0-9]+.[0-9]+.x" + pull_request: + +env: + CARGO_TERM_COLOR: 'always' + RUST_BACKTRACE: '1' + BUILDREQUIRES: >- + openssl-devel pcre2-devel zlib-devel + cargo rust-src rustfmt + clang compiler-rt llvm + git-core + make patch + perl-FindBin + perl-IO-Socket-SSL + perl-Test-Harness + perl-Test-Simple + perl-lib + +jobs: + test: + runs-on: ubuntu-latest + container: ghcr.io/almalinux/almalinux:10 + + strategy: + fail-fast: false + matrix: + nginx-ref: + # master + - stable-1.30 + + steps: + - name: Install dependencies + run: dnf install -y ${BUILDREQUIRES} + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ matrix.nginx-ref }} + repository: 'nginx/nginx' + path: 'nginx' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: 'nginx/nginx-tests' + path: 'nginx/tests' + + - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: | + ~/.cargo/bin/ + ~/.cargo/registry/index/ + ~/.cargo/registry/cache/ + ~/.cargo/git/db/ + nginx/objs/ngx_rust_examples + key: ${{ runner.os }}-cargo-asan-${{ hashFiles('**/Cargo.lock') }} + restore-keys: ${{ runner.os }}-cargo-asan- + + - name: Configure and build nginx + working-directory: nginx + env: + CFLAGS: >- + -DNGX_DEBUG_PALLOC=1 + -DNGX_SUPPRESS_WARN=1 + -O1 + -fno-omit-frame-pointer + -fsanitize=address,undefined + LDFLAGS: -fsanitize=address,undefined + RUSTFLAGS: -Zsanitizer=address -Zexternal-clangrt + # Pass --target to cargo to ensure that sanitizer flags are not + # applied to the build scripts and proc-macros. + NGX_RUST_TARGET: x86_64-unknown-linux-gnu + # Extra options passed to cargo rustc + NGX_RUSTC_OPT: -Zbuild-std + # Enable unstable features, such as the -Z options above, + # in the stable toolchain. + RUSTC_BOOTSTRAP: 1 + run: | + patch -p1 < $GITHUB_WORKSPACE/misc/nginx-sanitizer-support.patch + auto/configure \ + --with-cc=clang \ + --with-cc-opt="$CFLAGS" \ + --with-ld-opt="$LDFLAGS" \ + --with-compat \ + --with-debug \ + --with-http_ssl_module \ + --with-http_v2_module \ + --with-http_v3_module \ + --with-stream \ + --with-stream_ssl_module \ + --with-threads \ + --add-module=$(realpath ../examples) + make -j$(nproc) + + - name: Run tests + env: + ASAN_OPTIONS: detect_stack_use_after_return=1:detect_odr_violation=0 + # `container` job steps are running as root, and thus all the files + # created by the test scripts are owned by root. + # But the worker processes are spawned as "nobody" by default, + # resulting in permission errors. + TEST_NGINX_GLOBALS: >- + user root; + run: | + TEST_NGINX_BINARY="$PWD/nginx/objs/nginx" \ + LSAN_OPTIONS="suppressions=$PWD/misc/lsan-suppressions.txt" \ + UBSAN_OPTIONS="suppressions=$PWD/misc/ubsan-suppressions.txt" \ + prove -v -Inginx/tests/lib examples/t diff --git a/source/rust/vendor/ngx-rust/.gitignore b/source/rust/vendor/ngx-rust/.gitignore new file mode 100644 index 0000000..0a75edb --- /dev/null +++ b/source/rust/vendor/ngx-rust/.gitignore @@ -0,0 +1,256 @@ +# Created by https://www.toptal.com/developers/gitignore/api/c,rust,intellij+all,visualstudiocode,vim,emacs +# Edit at https://www.toptal.com/developers/gitignore?templates=c,rust,intellij+all,visualstudiocode,vim,emacs + +### C ### +# Prerequisites +*.d + +# Object files +*.o +*.ko +*.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +### Emacs ### +# -*- mode: gitignore; -*- +*~ +\#*\# +/.emacs.desktop +/.emacs.desktop.lock +*.elc +auto-save-list +tramp +.\#* + +# Org-mode +.org-id-locations +*_archive + +# flymake-mode +*_flymake.* + +# eshell files +/eshell/history +/eshell/lastdir + +# elpa packages +/elpa/ + +# reftex files +*.rel + +# AUCTeX auto folder +/auto/ + +# cask packages +.cask/ +dist/ + +# Flycheck +flycheck_*.el + +# server auth directory +/server/ + +# projectiles files +.projectile + +# directory configuration +.dir-locals.el + +# network security +/network-security.data + + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Rust ### +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +# End of https://www.toptal.com/developers/gitignore/api/c,rust,intellij+all,visualstudiocode,vim,emacs + +.vscode/c_cpp_properties.json +.cache/ +.nginx/ +.DS_Store diff --git a/source/rust/vendor/ngx-rust/.gitmodules b/source/rust/vendor/ngx-rust/.gitmodules new file mode 100644 index 0000000..d4fe729 --- /dev/null +++ b/source/rust/vendor/ngx-rust/.gitmodules @@ -0,0 +1,4 @@ +[submodule "nginx-src/nginx"] + path = nginx-src/nginx + url = https://github.com/nginx/nginx.git + branch = stable-1.28 diff --git a/source/rust/vendor/ngx-rust/CHANGELOG.md b/source/rust/vendor/ngx-rust/CHANGELOG.md new file mode 100644 index 0000000..6f23139 --- /dev/null +++ b/source/rust/vendor/ngx-rust/CHANGELOG.md @@ -0,0 +1,170 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +## Release 0.5.0 + +### Breaking changes + +The release contains too many breaking changes to offer a complete migration +guide. We will strive to do better in future releases; meanwhile, we suggest to +look at the changes in example modules: + + git diff v0.4.1..v0.5.0 -- examples/*.rs + +### Build experience + +In this release, we shifted the focus to an integration into the NGINX build +process. + +The default set of features now requires providing a preconfigured NGINX source +tree with `NGINX_SOURCE_DIR` and `NGINX_BUILD_DIR` variables ([#67], [#124]). + +The option to build a copy of NGINX as a part of the module process was +preserved as a feature flag `vendored` and no longer requires downloading +sources from the network ([#160]). +We encourage you to limit use of this feature to testing only. + +The [`examples`](./examples/) directory provides `config`, `config.make` and +`auto/rust` scripts to add a Rust-based module to the nginx build, linked +statically with `--add-module=` or dynamically with `--add-dynamic-module=`. +[nginx-acme] offers another, more complete example ([#67], [#95], [#124], +[#154], [#176]). + +In addition, we now have a proper detection of the features available in the +build of NGINX ([#97]). See [build.rs](./build.rs) for the necessary setup for +your project. + +[nginx-acme]: https://github.com/nginx/nginx-acme +[#67]: https://github.com/nginx/ngx-rust/pull/67 +[#95]: https://github.com/nginx/ngx-rust/pull/95 +[#97]: https://github.com/nginx/ngx-rust/pull/97 +[#124]: https://github.com/nginx/ngx-rust/pull/124 +[#154]: https://github.com/nginx/ngx-rust/pull/154 +[#160]: https://github.com/nginx/ngx-rust/pull/160 +[#176]: https://github.com/nginx/ngx-rust/pull/176 + +### Module declaration + +The traits for declaring a module and accessing module configuration underwent +significant changes in [#142] with the goal of reducing the amount of unsafe +code and enforcing type safety. + +See for a +summary and migration steps. + +[#142]: https://github.com/nginx/ngx-rust/pull/142 + +### Allocators + +`ngx` now offers custom allocator support based on the [allocator-api2] crate. +The `ngx::core::Pool` and `ngx::core::SlabPool` can be used for failible +allocations within the NGINX pools and shared zones correspondingly +([#164], [#171]). + +Most of the crates with [allocator-api2 support] are compatible with this +implementation. We also provide wrappers for common data structures implemented +in NGINX in [`ngx::collections`](./src/collections/) ([#164], [#181]). + +[allocator-api2]: https://crates.io/crates/allocator_api2 +[allocator-api2 support]: https://crates.io/crates/allocator_api2/reverse_dependencies +[#164]: https://github.com/nginx/ngx-rust/pull/164 +[#171]: https://github.com/nginx/ngx-rust/pull/171 +[#181]: https://github.com/nginx/ngx-rust/pull/181 + + +### Other + +* We audited the code and fixed or removed most of the methods that made wrong + assumptions and could panic or crash ([#91], [#152], [#183]). +* `no_std` build support ([#111]). +* Logging API improvements ([#113], [#187]) +* The SDK and the example modules can be built and are tested in CI on Windows + ([#124], [#161]). No further porting or testing work was done. +* Reimplementations for `nginx-sys` methods and macros that cannot be translated + with bindgen ([#131], [#162], [#167]) +* Initial work on the NGINX async runtime ([#170]) +* The default branch was renamed to `main`. + +[#91]: https://github.com/nginx/ngx-rust/pull/91 +[#111]: https://github.com/nginx/ngx-rust/pull/111 +[#113]: https://github.com/nginx/ngx-rust/pull/113 +[#131]: https://github.com/nginx/ngx-rust/pull/131 +[#152]: https://github.com/nginx/ngx-rust/pull/152 +[#161]: https://github.com/nginx/ngx-rust/pull/161 +[#162]: https://github.com/nginx/ngx-rust/pull/162 +[#167]: https://github.com/nginx/ngx-rust/pull/167 +[#170]: https://github.com/nginx/ngx-rust/pull/170 +[#183]: https://github.com/nginx/ngx-rust/pull/183 +[#187]: https://github.com/nginx/ngx-rust/pull/187 + +### Supported versions + +The minimum supported Rust version is 1.81.0. The version was chosen to support +the packaged Rust toolchain in the recent versions of popular Linux and BSD +distributions. + +The minimum supported NGINX version is 1.22. The bindings may compile with an +older version of NGINX, but we do not test that regularly. + +Full changelog: [v0.4.1..v0.5.0](https://github.com/nginx/ngx-rust/compare/v0.4.1...v0.5.0) + +## Release v0.4.1 + * release: ngx 0.4.1 (9d2ce0d) + * release: nginx-sys 0.2.1 (89eb277) + * fix(#50): user_agent method returns 'Option<&NgxStr>' and not '&NgxStr' (8706830) + * fix(#41): zlib version update (89e0fcc) + * fix: check user_agent for null (0ca0bc9) + * feat: (2 of 2) Upstream module example (#37) (840d789) + * feat: (1 of 2) Supporting changes for upstream example module. (#36) (8b3a119) + * Revert "ci: use GH cache for .cache folder on MAC OS" (7972ae7) + * docs: updated changelog (74604e2) + +## Release 0.4.0-beta + * realease: bump nginx-sys to 0.2.0 (ad093d8) + * feat: unsafe updates for raw pointer arguments (1b88323) + * feat: Add debug log mask support (#40) (57c68ff) + * docs: add support badge to README (4aa2e35) + * cargo: make macOS linker flags workaround apply to Apple silicon (f4ea26f) + * docs: added repostatus and crates badges (dd687a4) + + ## Initial release 0.3.0-beta + * docs: prepare ngx to be published to crates.io (a1bff29) + * fix: nginx-sys enable a few modules by default (f23e4b1) + * !misc: project refactor and new module structure (b3e8f45) + * update README (#18) (d2c0b3a) + * Fix usage example in README (#16) (8deaec0) + * use nginxinc namespace (9bb9ef6) + * upgrade to rust 1.26 (#15) (bbfc114) + * 1.39 upgrade (#12) (be9d532) + * add pkg-config (#11) (a33c329) + * upgrade to nginx 1.13.7 (#10) (8c6b968) + * update the README (#9) (7693ea2) + * Rust 1.21 (#8) (4fa395c) + * Rust 1.21 (#7) (9517b56) + * add rust docker tooling (8b4d492) + * revert back tool tag (82bd0d6) + * update the tag for rust tool image (f2418c0) + * bump up tool image to 1.22 (7db2ced) + * add rust tool on top of the nginx (9aa4fa0) + * add developer version of nginx which can do ps (994c703) + * upgrade nginx to 1.13.5 bump up cargo version number respectively separate out nginx make file (7095777) + * consolidate makefile by reducing duplicates simplify docker command (cfe1756) + * set default rust tooling to 1.20 generate linux binding in the cargo build fix the linux configuration (d396803) + * build nginx binary for darwin add target for darwin (d2e04ce) + * add configuration for linux (b3bf4da) + * remove unnecessary reference to libc invoke make for build.rs in the mac (8e1c544) + * add unit test for nginx server (d0ff3df) + * Merge branch 'master' into module (4f6ed43) + * update the README (a8cfe50) + * add license file (805e70b) + * add license file (8c574be) + * add nginx instance module where you can start and stop nginx sample test for instance (acfc545) + * upgrade bindgen to latest version remove redudant c module code update the nginx config (3102b5a) + * update the tools make file to use Dockerhub (36ae1ca) + * update the README (ba563fc) + * add tools directory to generate docker image for rust toolchain check for nginx directory when setting up source (6842329) + * add targets for building on linux (6176272) + * make target for setting up darwin source add os specific build path (fbc5e2f) + * initial check in generate binding (a38b8ab) + diff --git a/source/rust/vendor/ngx-rust/CODE_OF_CONDUCT.md b/source/rust/vendor/ngx-rust/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..4547fd8 --- /dev/null +++ b/source/rust/vendor/ngx-rust/CODE_OF_CONDUCT.md @@ -0,0 +1,129 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement as listed on the +github project page. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/CONTRIBUTING.md b/source/rust/vendor/ngx-rust/CONTRIBUTING.md new file mode 100644 index 0000000..5242d62 --- /dev/null +++ b/source/rust/vendor/ngx-rust/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing Guidelines + +The following is a set of guidelines for contributing. We really appreciate that you are considering contributing! + +#### Table Of Contents + +[Ask a Question](#ask-a-question) + +[Contributing](#contributing) + +[Style Guides](#style-guides) + * [Git Style Guide](#git-style-guide) + * [Rust Style Guide](#rust-style-guide) + +[Code of Conduct](CODE_OF_CONDUCT.md) + +## Ask a Question + +Please ask your question on github using discussions. + +## Contributing + +### Report a Bug + +To report a bug, open an issue on GitHub with the label `bug` using the available bug report issue template. Please ensure the issue has not already been reported. + +### Suggest an Enhancement + +To suggest an enhancement, please create an issue on GitHub with the label `enhancement` using the available feature issue template. + +### Open a Pull Request + +* Fork the repo, create a branch, submit a PR when your changes are tested and ready for review. +* Fill in [our pull request template](/.github/PULL_REQUEST_TEMPLATE.md) + +Note: if you’d like to implement a new feature, please consider creating a feature request issue first to start a discussion about the feature. + +## Style Guides + +### Git Style Guide + +* Keep a clean, concise and meaningful git commit history on your branch, rebasing locally and squashing before submitting a PR +* Use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format when writing a commit message, so that changelogs can be automatically generated +* Follow the guidelines of writing a good commit message as described [here](https://chris.beams.io/posts/git-commit/) and summarised in the next few points + * In the subject line, use the present tense ("Add feature" not "Added feature") + * In the subject line, use the imperative mood ("Move cursor to..." not "Moves cursor to...") + * Limit the subject line to 72 characters or less + * Reference issues and pull requests liberally after the subject line + * Add more detailed description in the body of the git message (`git commit -a` to give you more space and time in your text editor to write a good message instead of `git commit -am`) + +### Rust Style Guide + +* Rust code should be checked in after `cargo fmt` has been run. +* The code style broadly complies with the [official Rust Style Guide](https://doc.rust-lang.org/style-guide/index.html). +* Where feasible, include unit tests. diff --git a/source/rust/vendor/ngx-rust/Cargo.toml b/source/rust/vendor/ngx-rust/Cargo.toml new file mode 100644 index 0000000..1b1bcd2 --- /dev/null +++ b/source/rust/vendor/ngx-rust/Cargo.toml @@ -0,0 +1,84 @@ +[workspace] +members = [ + "nginx-src", + "nginx-sys", + "examples", +] + +[workspace.package] +edition = "2024" +license = "Apache-2.0" +homepage = "https://github.com/nginx/ngx-rust" +repository = "https://github.com/nginx/ngx-rust" +rust-version = "1.85.0" + +[workspace.lints.clippy] +alloc_instead_of_core = "warn" +borrow_as_ptr = "warn" +std_instead_of_alloc = "warn" +std_instead_of_core = "warn" + +[workspace.lints.rust] +rust-2024-compatibility = "warn" + +[package] +name = "ngx" +version = "0.5.0" +autoexamples = false +categories = ["api-bindings", "network-programming"] +description = "FFI bindings to NGINX" +include = [ + "/build.rs", + "/src", + "/*.md", + "LICENSE", +] +keywords = ["nginx", "module", "sys"] +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +rust-version.workspace = true + +[package.metadata.docs.rs] +all-features = true +default-target = "x86_64-unknown-linux-gnu" +targets = [] + +[dependencies] +allocator-api2 = { version = "0.4.0", default-features = false, features = ["fresh-rust"] } +async-task = { version = "4.7.1", optional = true } +lock_api = "0.4.13" +nginx-sys = { path = "nginx-sys", version = "0.5.0"} +pin-project-lite = { version = "0.2.16", optional = true } + +[features] +default = ["std"] +# Enables a minimal async runtime built on top of the NGINX event loop. +async = [ + "alloc", + "dep:async-task", + "dep:pin-project-lite", +] +# Provides APIs that require allocations via the `alloc` crate. +alloc = ["allocator-api2/alloc"] +# Enables serialization support for some of the provided and re-exported types. +serde = [ + "allocator-api2/serde", +] +# Provides APIs that require the standard library. +std = [ + "alloc", + "allocator-api2/std" +] +# Enables the build scripts to build a copy of nginx source and link against it. +vendored = ["nginx-sys/vendored"] + +[badges] +maintenance = { status = "experimental" } + +[dev-dependencies] +tempfile = { version = "3.20.0", default-features = false } + +[lints] +workspace = true diff --git a/source/rust/vendor/ngx-rust/Containerfile.debian b/source/rust/vendor/ngx-rust/Containerfile.debian new file mode 100644 index 0000000..7d8bca4 --- /dev/null +++ b/source/rust/vendor/ngx-rust/Containerfile.debian @@ -0,0 +1,16 @@ +FROM rust:slim-bullseye + +RUN set -eux \ + export DEBIAN_FRONTEND=noninteractive; \ + apt-get -qq update; \ + apt-get -qq install --yes --no-install-recommends --no-install-suggests \ + libclang-dev \ + libssl-dev \ + pkg-config \ + git \ + grep \ + gawk \ + gnupg2 \ + sed \ + make; \ + git config --global --add safe.directory /project \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/Dockerfile b/source/rust/vendor/ngx-rust/Dockerfile new file mode 100644 index 0000000..b08598d --- /dev/null +++ b/source/rust/vendor/ngx-rust/Dockerfile @@ -0,0 +1,51 @@ +ARG NGX_VERSION=1.30.4 +# NGINX official images are available for one specific release of Debian, +# e.g `nginx:1.30.4-trixie`. Please see the list of tags on Docker Hub +# if you need to change NGX_VERSION. +ARG DEBIAN_RELEASE=trixie + +# --- builder: build all examples +FROM rust:slim-${DEBIAN_RELEASE} AS build +ARG NGX_VERSION +ARG NGX_CONFIGURE_ARGS= +WORKDIR /project +RUN --mount=type=cache,target=/var/cache/apt < /dev/null || command -v grep 2> /dev/null) +SED ?= $(shell command -v gsed 2> /dev/null || command -v sed 2> /dev/null) +AWK ?= $(shell command -v gawk 2> /dev/null || command -v awk 2> /dev/null) +VERSION ?= $(shell $(GREP) -Po '^version\s+=\s+"\K.*?(?=")' $(CURDIR)/Cargo.toml) +CARGO ?= cargo +DOCKER ?= docker +DOCKER_BUILD_FLAGS ?= --load +COMMITSAR_DOCKER := $(DOCKER) run --tty --rm --workdir /src -v "$(CURDIR):/src" aevea/commitsar +COMMITSAR ?= $(shell command -v commitsar 2> /dev/null) +PROJECT_NAME ?= ngx-rust +GITHUB_REPOSITORY ?= nginx/$(PROJECT_NAME) +SRC_REPO := https://github.com/$(GITHUB_REPOSITORY) + +RELEASE_BUILD_FLAGS ?= --quiet --release + +Q = $(if $(filter 1,$V),,@) +M = $(shell printf "\033[34;1m▶\033[0m") + +UNAME_S := $(shell uname -s) +ifeq ($(UNAME_S),Linux) + FEATURES += --features=linux +endif + +# Use docker based commitsar if it isn't in the path +ifeq ($(COMMITSAR),) + COMMITSAR = $(COMMITSAR_DOCKER) +endif + +.PHONY: help +help: + @$(GREP) --no-filename -E '^[ a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \ + $(AWK) 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-28s\033[0m %s\n", $$1, $$2}' | sort + +.PHONY: clean +clean: clean-cache; $(info $(M) cleaning...) @ ## Cleanup everything + $Q rm -rf $(CURDIR)/target + $Q $(CARGO) clean + +.PHONY: clean-cache +clean-cache: ## Remove all cached dependencies and build artifacts + $(Q) rm -rf $(CACHE_DIR) + +.PHONY: commitsar +commitsar: ## Run git commit linter + $Q $(info $(M) running commitsar...) + $(COMMITSAR) + +target: + $Q mkdir -p $@ + +.PHONY: debug +debug: target/debug ## Build current platform target in debug mode + +target/debug: + $Q echo "$(M) building in debug mode for the current platform" + $Q $(CARGO) build --quiet + +.PHONY: release +release: target/release ## Build current platform target in release mode + +target/release: + $Q echo "$(M) building in release mode for the current platform" + $Q $(CARGO) build $(RELEASE_BUILD_FLAGS) + +.PHONY: test +test: ## Run tests + $Q $(CARGO) test + +.PHONY: format +format: ## Run rustfmt + $Q $(CARGO) fmt + +.PHONY: lint +lint: ## Run clippy + $Q $(CARGO) clippy + +.PHONY: examples-debug +examples-debug: + $Q echo "$(M) building all examples as debug" + $Q $(CARGO) build --quiet --package=examples --examples $(FEATURES) + +include $(CURDIR)/build/container.mk +include $(CURDIR)/build/release.mk +include $(CURDIR)/build/github.mk diff --git a/source/rust/vendor/ngx-rust/LICENSE b/source/rust/vendor/ngx-rust/LICENSE new file mode 100644 index 0000000..98f7217 --- /dev/null +++ b/source/rust/vendor/ngx-rust/LICENSE @@ -0,0 +1,201 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, +and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by +the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all +other entities that control, are controlled by, or are under common +control with that entity. For the purposes of this definition, +"control" means (i) the power, direct or indirect, to cause the +direction or management of such entity, whether by contract or +otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity +exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation +source, and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but +not limited to compiled object code, generated documentation, +and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or +Object form, made available under the License, as indicated by a +copyright notice that is included in or attached to the work +(an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including +the original version of the Work and any modifications or additions +to that Work or Derivative Works thereof, that is intentionally +submitted to Licensor for inclusion in the Work by the copyright owner +or by an individual or Legal Entity authorized to submit on behalf of +the copyright owner. For the purposes of this definition, "submitted" +means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, +and issue tracking systems that are managed by, or on behalf of, the +Licensor for the purpose of discussing and improving the Work, but +excluding communication that is conspicuously marked or otherwise +designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the +Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as stated in this section) patent license to make, have made, +use, offer to sell, sell, import, and otherwise transfer the Work, +where such license applies only to those patent claims licensable +by such Contributor that are necessarily infringed by their +Contribution(s) alone or by combination of their Contribution(s) +with the Work to which such Contribution(s) was submitted. If You +institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work +or a Contribution incorporated within the Work constitutes direct +or contributory patent infringement, then any patent licenses +granted to You under this License for that Work shall terminate +as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You +meet the following conditions: + +(a) You must give any other recipients of the Work or +Derivative Works a copy of this License; and + +(b) You must cause any modified files to carry prominent notices +stating that You changed the files; and + +(c) You must retain, in the Source form of any Derivative Works +that You distribute, all copyright, patent, trademark, and +attribution notices from the Source form of the Work, +excluding those notices that do not pertain to any part of +the Derivative Works; and + +(d) If the Work includes a "NOTICE" text file as part of its +distribution, then any Derivative Works that You distribute must +include a readable copy of the attribution notices contained +within such NOTICE file, excluding those notices that do not +pertain to any part of the Derivative Works, in at least one +of the following places: within a NOTICE text file distributed +as part of the Derivative Works; within the Source form or +documentation, if provided along with the Derivative Works; or, +within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents +of the NOTICE file are for informational purposes only and +do not modify the License. You may add Your own attribution +notices within Derivative Works that You distribute, alongside +or as an addendum to the NOTICE text from the Work, provided +that such additional attribution notices cannot be construed +as modifying the License. + +You may add Your own copyright statement to Your modifications and +may provide additional or different license terms and conditions +for use, reproduction, or distribution of Your modifications, or +for any such Derivative Works as a whole, provided Your use, +reproduction, and distribution of the Work otherwise complies with +the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work +by You to the Licensor shall be under the terms and conditions of +this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify +the terms of any separate license agreement you may have executed +with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or +agreed to in writing, Licensor provides the Work (and each +Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +implied, including, without limitation, any warranties or conditions +of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A +PARTICULAR PURPOSE. You are solely responsible for determining the +appropriateness of using or redistributing the Work and assume any +risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, +unless required by applicable law (such as deliberate and grossly +negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, +incidental, or consequential damages of any character arising as a +result of this License or out of the use or inability to use the +Work (including but not limited to damages for loss of goodwill, +work stoppage, computer failure or malfunction, or any and all +other commercial damages or losses), even if such Contributor +has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing +the Work or Derivative Works thereof, You may choose to offer, +and charge a fee for, acceptance of support, warranty, indemnity, +or other liability obligations and/or rights consistent with this +License. However, in accepting such obligations, You may act only +on Your own behalf and on Your sole responsibility, not on behalf +of any other Contributor, and only if You agree to indemnify, +defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason +of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following +boilerplate notice, with the fields enclosed by brackets "{}" +replaced with your own identifying information. (Don't include +the brackets!) The text should be enclosed in the appropriate +comment syntax for the file format. We also recommend that a +file or class name and description of purpose be included on the +same "printed page" as the copyright notice for easier +identification within third-party archives. + +Copyright 2016 Nginx, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/source/rust/vendor/ngx-rust/README.md b/source/rust/vendor/ngx-rust/README.md new file mode 100644 index 0000000..7175f67 --- /dev/null +++ b/source/rust/vendor/ngx-rust/README.md @@ -0,0 +1,256 @@ +[![Rust](https://github.com/nginx/ngx-rust/actions/workflows/ci.yaml/badge.svg)](https://github.com/nginx/ngx-rust/actions/workflows/ci.yaml) +[![crates.io](https://img.shields.io/crates/v/ngx.svg)](https://crates.io/crates/ngx) +[![docs.rs](https://img.shields.io/docsrs/ngx?label=docs(ngx))](https://docs.rs/ngx) +[![docs.rs](https://img.shields.io/docsrs/nginx-sys?label=docs(nginx-sys))](https://docs.rs/nginx-sys) +[![Project Status: WIP – Initial development is in progress, but there has not yet been a stable, usable release suitable for the public.](https://www.repostatus.org/badges/latest/wip.svg)](https://www.repostatus.org/#wip) +[![Community Support](https://badgen.net/badge/support/community/cyan?icon=awesome)](https://github.com/nginx/ngx-rust/discussions) + + + +# Rust bindings for NGINX + +The `ngx` crate provides a high-level Rust interface for the [NGINX] C APIs, +allowing creation of NGINX dynamic modules completely in Rust. + +[NGINX]: https://nginx.org/ + +## Project status + +This project is in active development. It is stable enough to be used in our +own products, but the APIs are not stabilized and breaking changes are expected. + +## Build + +NGINX modules can be built against a particular version of NGINX. The following +environment variables can be used to specify the NGINX build to use: + +- `NGINX_BUILD_DIR` - absolute path to the NGINX build directory. + Usually it's `objs` under the source directory, but can be changed with the + `--builddir=` argument of the configure script. + +- `NGINX_SOURCE_DIR` - absolute path to the NGINX source directory, configured + with the [`configure`](https://nginx.org/en/docs/configure.html) command. + +Only the `./configure` step of the NGINX build is mandatory because bindings +generator don't depend on any of the artifacts generated by `make`. + +For example, this is how you would compile the [examples](#examples) using a +specific version of NGINX: + +```sh +NGINX_BUILD_DIR=/path/to/nginx-1.30.4/objs cargo build --package=examples --examples +``` + +### Building with the NGINX build script + +You can build your Rust-based module as a part of the NGINX build process by +providing a `config` script implementation and passing the `--add-module`/ +`--add-dynamic-module` options to the configure script. + +See the following example integration scripts: [`examples/config`] and +[`examples/config.make`]. + +[`examples/config`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config +[`examples/config.make`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config.make + +### Building with vendored NGINX sources + +It is possible to build module with a vendored copy of the NGINX sources +provided in the `nginx-src` crate by enabling feature `vendored`: + +By default, this will use the latest stable release of NGINX and require +system-wide installation of build dependencies (OpenSSL, PCRE2, Zlib). + +The behavior of vendored builds can be customized with environment variables, +as documented in the [nginx-src] crate README. + +**NOTE**: We recommend to build the module binaries against the exact source and +configuration of the NGINX build that you are planning to use in production, +and that is unlikely to be possible with the vendored source. + +`configure` arguments alter the APIs and the symbols visible to the Rust code, +and some OS distributions are known to ship nginx packages with API-breaking +patches applied. + +[nginx-src]: https://docs.rs/nginx-src/ + +## Cargo features + +- `alloc` - **Enabled** by default. This provides APIs that require allocations + via the `alloc` crate. +- `async` - Enables a minimal async runtime built on top of the NGINX event loop. +- `serde` - Enables serialization support for some of the provided and + re-exported types. +- `std` - **Enabled** by default. This provides APIs that require the standard + library. +- `vendored`: Enables the build scripts to build a copy of nginx source and link + against it. See the [nginx-src] crate documentation for additional details. + +## Dependencies + +The following dependencies are required to build a Rust NGINX module on Linux +or BSD platform: + +- NGINX build dependencies: C compiler, make, OpenSSL, PCRE2, and Zlib. +- Rust toolchain (1.85.0 or later) +- [libclang] for rust-bindgen + +The installation process and the package names are system-dependent. Please, +consult the documentation for your distribution. + +Note that on some systems you will need `-devel` or `-dev` versions of the +packages. + +For example, [Dockerfile] contains the installation commands for Debian Linux. + +[Dockerfile]: https://github.com/nginx/ngx-rust/blob/main/Dockerfile +[libclang]: https://rust-lang.github.io/rust-bindgen/requirements.html + +### macOS dependencies + +In order to use the optional GNU make build process on macOS, you will need +to install additional tools. This can be done via [homebrew](https://brew.sh/) +with the following command: + +```sh +brew install make openssl grep +``` + +Additionally, you may need to set up LLVM and clang. Typically, this is done +as follows: + +```sh +# make sure xcode tools are installed +xcode-select --install +# instal llvm +brew install --with-toolchain llvm +``` + + + +### Examples + +Example modules are available in [examples] folder. +You can use `cargo build --package=examples --examples` to build these examples. +After compilation, the modules can be found in the path `target/debug/examples/` +(with the `.so` file extension for Linux or `.dylib` for macOS). +Add `--features=linux` to build Linux specific modules. + +**NOTE**: adding the "linux" feature on macOS will cause a build failure. + +For example (all examples plus linux specific): + +```sh +cargo build --package=examples --examples --features=linux +``` + +[examples]: https://github.com/nginx/ngx-rust/tree/main/examples + +### Docker + +We provide a multistage [Dockerfile]: + +```sh +# build all dynamic modules examples and specify NGINX version to use +docker buildx build --build-arg NGX_VERSION=1.29.1 -t ngx-rust . + +# start NGINX using [curl](examples/curl.conf) module example: +docker run --rm -d -p 8000:8000 ngx-rust nginx -c examples/curl.conf + +# test it - you should see 403 Forbidden +curl http://127.0.0.1:8000 -v -H "user-agent: curl" + +# test it - you should see 404 Not Found +curl http://127.0.0.1:8000 -v -H "user-agent: foo" +``` + +## Usage + +A complete module example using the SDK can be found [here](examples/curl.rs). +You can build it with `cargo build --package=examples --example=curl` then set +up NGINX to use it, as shown below: + +```nginx +daemon off; +error_log stderr debug; + +load_module modules/libcurl.so; + +events { +} + +http { + server { + listen 8000; + server_name localhost; + + access_log /dev/stdout; + + location / { + root /srv/http; + # ... Other config stuff ... + + curl on; + } + } +} +``` + +## Support + +This SDK is currently unstable. Right now, our primary goal is collect feedback +and stabilize it before offering support. +Feel free to [contribute](CONTRIBUTING.md) by creating issues, PRs, or github +discussions. + +Currently, the supported platforms are: + +- Darwin (macOS) +- FreeBSD +- Linux + +See the Rust toolchain [platform support] document for supported versions and +architectures. + +[platform support]: https://doc.rust-lang.org/rustc/platform-support.html + +### Tested OS and platforms + +In addition, we verified that the modules based on this SDK can be built and +work on the following platforms. + +- Illumos +- NetBSD 9-10 +- OpenBSD 7 +- Solaris 11.4 +- Windows 10+/Windows Server 2022+ + +## Roadmap + +If you have ideas for releases in the future, please suggest them in the github +discussions. + +## Contributing + +We welcome pull requests and issues! + +Please refer to the [Contributing Guidelines](CONTRIBUTING.md) when doing a PR. + +## Authors and acknowledgment + +This project uses some great work from: + +- [dcoles/nginx-rs](https://github.com/dcoles/nginx-rs), +- [arvancloud/nginx-rs](https://github.com/arvancloud/nginx-rs). + +## Projects using the SDK + +- [ngx-strict-sni](https://github.com/JyJyJcr/ngx-strict-sni) - Strict SNI validator for Nginx +- [nginx-acme](https://github.com/nginx/nginx-acme) - ACMEv2 client implementation + +## License + +All code in this repository is licensed under the +[Apache License, Version 2.0](./LICENSE). + +© [F5, Inc.](https://www.f5.com/) diff --git a/source/rust/vendor/ngx-rust/SECURITY.md b/source/rust/vendor/ngx-rust/SECURITY.md new file mode 100644 index 0000000..dd2be6b --- /dev/null +++ b/source/rust/vendor/ngx-rust/SECURITY.md @@ -0,0 +1,22 @@ +# Security Policy + +## General Guidance + +We advise users to run the most recent release of the NGINX Rust Module SDK, and we issue software updates to the +most recent release. + +## Support + +The NGINX Rust Module SDK is not officially supported. + +## Reporting a Vulnerability + +The F5 Security Incident Response Team (F5 SIRT) has an email alias that makes it easy to report potential security +vulnerabilities. + +- If you’re an F5 customer with an active support contract, please contact + [F5 Technical Support](https://www.f5.com/services/support). +- If you aren’t an F5 customer, please report any potential or current instances of security vulnerabilities with any + F5 product to the F5 Security Incident Response Team at F5SIRT@f5.com + +For more information visit https://www.f5.com/services/support/report-a-vulnerability diff --git a/source/rust/vendor/ngx-rust/build.rs b/source/rust/vendor/ngx-rust/build.rs new file mode 100644 index 0000000..3ffcf94 --- /dev/null +++ b/source/rust/vendor/ngx-rust/build.rs @@ -0,0 +1,67 @@ +/// Example buildscript for an nginx module. +/// +/// Due to the limitations of cargo[1], this buildscript _requires_ adding `nginx-sys` to the +/// direct dependencies of your crate. +/// +/// [1]: https://github.com/rust-lang/cargo/issues/3544 +fn main() { + // Generate `ngx_os` and `ngx_feature` cfg values + + // Specify acceptable values for `ngx_feature` + println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES_CHECK"); + println!( + "cargo::rustc-check-cfg=cfg(ngx_feature, values({}))", + std::env::var("DEP_NGINX_FEATURES_CHECK").unwrap_or("any()".to_string()) + ); + // Read feature flags detected by nginx-sys and pass to the compiler. + println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES"); + if let Ok(features) = std::env::var("DEP_NGINX_FEATURES") { + for feature in features.split(',').map(str::trim) { + println!("cargo::rustc-cfg=ngx_feature=\"{feature}\""); + } + } + + // Specify acceptable values for `ngx_os` + println!("cargo::rerun-if-env-changed=DEP_NGINX_OS_CHECK"); + println!( + "cargo::rustc-check-cfg=cfg(ngx_os, values({}))", + std::env::var("DEP_NGINX_OS_CHECK").unwrap_or("any()".to_string()) + ); + // Read operating system detected by nginx-sys and pass to the compiler. + println!("cargo::rerun-if-env-changed=DEP_NGINX_OS"); + if let Ok(os) = std::env::var("DEP_NGINX_OS") { + println!("cargo::rustc-cfg=ngx_os=\"{os}\""); + } + + // Generate cfg values for version checks + const VERSION_CHECKS: &[(u64, &str)] = &[ + // + (1_021_001, "nginx1_21_1"), + (1_025_001, "nginx1_25_1"), + ]; + VERSION_CHECKS.iter().for_each(|check| println!("cargo::rustc-check-cfg=cfg({})", check.1)); + + println!("cargo::rerun-if-env-changed=DEP_NGINX_VERSION_NUMBER"); + if let Ok(version) = std::env::var("DEP_NGINX_VERSION_NUMBER") { + let version: u64 = version.parse().unwrap(); + + for check in VERSION_CHECKS { + if version >= check.0 { + println!("cargo::rustc-cfg={}", check.1); + } + } + } + + // Pass build directory to the tests + println!("cargo::rerun-if-env-changed=DEP_NGINX_BUILD_DIR"); + if let Ok(build_dir) = std::env::var("DEP_NGINX_BUILD_DIR") { + println!("cargo::rustc-env=DEP_NGINX_BUILD_DIR={build_dir}"); + } + + // Generate required compiler flags + if cfg!(target_os = "macos") { + // https://stackoverflow.com/questions/28124221/error-linking-with-cc-failed-exit-code-1 + println!("cargo::rustc-link-arg=-undefined"); + println!("cargo::rustc-link-arg=dynamic_lookup"); + } +} diff --git a/source/rust/vendor/ngx-rust/deny.toml b/source/rust/vendor/ngx-rust/deny.toml new file mode 100644 index 0000000..a2b7132 --- /dev/null +++ b/source/rust/vendor/ngx-rust/deny.toml @@ -0,0 +1,27 @@ +[bans] +multiple-versions = "warn" + +[graph] +all-features = true + +[licenses] +allow = [ + "Apache-2.0", + "BSD-2-Clause", + "BSD-3-Clause", + "ISC", + "MIT", + "Unicode-3.0", +] +confidence-threshold = 0.8 + +[[licenses.exceptions]] +crate = "webpki-roots" +allow = ["CDLA-Permissive-2.0", "MPL-2.0"] + +[[licenses.clarify]] +crate = "ring" +expression = "MIT AND ISC AND OpenSSL" +license-files = [ + { path = "LICENSE", hash = 0xbd0eed23 } +] diff --git a/source/rust/vendor/ngx-rust/examples/Cargo.toml b/source/rust/vendor/ngx-rust/examples/Cargo.toml new file mode 100644 index 0000000..5419075 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/Cargo.toml @@ -0,0 +1,70 @@ +[package] +name = "examples" +version = "0.0.0" +publish = false +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +rust-version.workspace = true +# https://github.com/dependabot/dependabot-core/issues/1156 +autobins = false + +build = "../build.rs" + +[dependencies] +nginx-sys = { path = "../nginx-sys/" } +ngx = { path = "../", default-features = false, features = ["std"] } + +[dev-dependencies] +aws-sign-v4 = "0.3.0" +chrono = "0.4.27" +http = "1.1.0" +# use unicode-rs idna backend for lower MSRV and faster builds +idna_adapter = "=1.1.0" +libc = "0.2.168" +tokio = { version = "1.33.0", features = ["full"] } + +[[example]] +name = "curl" +path = "curl.rs" +crate-type = ["cdylib"] + +[[example]] +name = "awssig" +path = "awssig.rs" +crate-type = ["cdylib"] + +[[example]] +name = "httporigdst" +path = "httporigdst.rs" +crate-type = ["cdylib"] +required-features = ["linux"] + +[[example]] +name = "upstream" +path = "upstream.rs" +crate-type = ["cdylib"] + +[[example]] +name = "async" +path = "async.rs" +crate-type = ["cdylib"] + +[[example]] +name = "shared_dict" +path = "shared_dict.rs" +crate-type = ["cdylib"] + +[features] +default = ["export-modules", "ngx/vendored"] +# Generate `ngx_modules` table with module exports +# The exports table is required for building loadable modules with --crate-type cdylib +# outside of the NGINX buildsystem. However, cargo currently does not detect +# this configuration automatically. +# See https://github.com/rust-lang/rust/issues/20267 +export-modules = [] +linux = [] + +[lints] +workspace = true diff --git a/source/rust/vendor/ngx-rust/examples/README.md b/source/rust/vendor/ngx-rust/examples/README.md new file mode 100644 index 0000000..e40e4db --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/README.md @@ -0,0 +1,226 @@ +- [Examples](#examples) + - [CURL](#curl) + - [AWSSIG](#awssig) + - [HTTPORIGDST - NGINX Destination IP recovery module for HTTP](#httporigdst----nginx-destination-ip-recovery-module-for-http) + - [Dependencies](#dependencies) + - [Example Configuration](#example-configuration) + - [HTTP](#http) + - [Embedded Variables](#embedded-variables) + - [Usage](#usage) + - [Caveats](#caveats) + + +# Examples +This crate provides a couple of example using [ngx](https://crates.io/crates/ngx) crate: + +- [awssig.rs](./awssig.rs) - An example of NGINX dynamic module that can sign GET request using AWS Signature v4. +- [curl](./curl.rs) - An example of the Access Phase NGINX dynamic module that blocks HTTP requests if `user-agent` header starts with `curl`. +- [httporigdst](./httporigdst.rs) - A dynamic module recovers the original IP address and port number of the destination packet. +- [upstream](./upstream.rs) - A dynamic module demonstrating the setup code to write an upstream filter or load balancer. + +To build all these examples simply run: + +``` +cargo build --package=examples --examples +``` + + +## CURL + +This module demonstrates how to create a minimal dynamic module with `http_request_handler`, that checks for User-Agent headers and returns status code 403 if UA starts with `curl`, if a module is disabled then uses `core::Status::NGX_DECLINED` to indicate the operation is rejected, for example, because it is disabled in the configuration (`curl off`). Additionally, it demonstrates how to write a defective parser. + +An example of nginx configuration file that uses that module can be found at [curl.conf](./curl.conf). + +How to build and run in a [Docker](../Dockerfile) container curl example: +``` +# build all dynamic modules examples and specify NGINX version to use +docker buildx build --build-arg NGX_VERSION=1.23.3 -t ngx-rust . + +# start NGINX using curl.conf module example: +docker run --rm -d -p 8000:8000 ngx-rust nginx -c examples/curl.conf + +# test it - you should see 403 Forbidden +curl http://127.0.0.1:8000 -v -H "user-agent: curl" + + +# test it - you should see 404 Not Found +curl http://127.0.0.1:8000 -v -H "user-agent: foo" +``` + +## AWSSIG + +This module uses [NGX_HTTP_PRECONTENT_PHASE](https://nginx.org/en/docs/dev/development_guide.html#http_phases) and provides examples, of how to use external dependency and manipulate HTTP headers before sending client requests upstream. + +An example of nginx configuration file that uses that module can be found at [awssig.conf](./awssig.conf). + +## HTTPORIGDST - NGINX Destination IP recovery module for HTTP + +This dynamic module recovers the original IP address and port number of the destination packet. It is useful, for example, with container sidecars where all outgoing traffic is redirected to a separate container with iptables before reaching the target. + +This module can only be built with the "linux" feature enabled, and will only successfully build on a Linux OS. + +### Dependencies +This module uses the Rust crate libc and Linux **getsockopt** socket API. + +### Example Configuration +#### HTTP + +```nginx configuration +load_module "modules/libhttporigdst.so"; + +http { + server { + # use iptables to capture all outgoing traffic and REDIRECT + # to listening port 15501 + listen 15501; + + # binding variables provided by module will lazily activate it + # and store a context + # variables can be used in config + location / { + # Return if no backend is available or proxy_pass + # return 200 "recv'd: $server_addr:$server_port\n\nproxy_pass http://$server_orig_addr:$server_orig_port\n"; + proxy_pass http://$server_orig_addr:$server_orig_port; + } + } +} +``` + +### Embedded Variables + +The following embedded variables are provided: + +* **server_orig_addr** + * Original IP address +* **server_orig_port** + * Original port + +### Usage + +1. Clone the git repository. + ``` + git clone git@github.com:nginx/ngx-rust.git + ``` + +2. Compile the module from the cloned repo. + ``` + cd ${CLONED_DIRECTORY}/ngx-rust + cargo build --package=examples --example=httporigdst --features=linux + ``` + +3. Copy the shared object to the modules directory, /etc/nginx/modules. + ``` + cp ./target/debug/examples/libhttporigdst.so /etc/nginx/modules + ``` + +4. Add the `load_module` directive to your configuration. + ``` + load_module "modules/libhttporigdst.so"; + ``` + +5. Reload NGINX. + ``` + nginx -t && nginx -s reload + ``` + +6. Redirect traffic outbound. + ``` + iptables -t nat -N NGINX_REDIRECT && \ + iptables -t nat -A NGINX_REDIRECT -p tcp -j REDIRECT --to-port 15501 --dport 15001 && \ + iptables -t nat -N NGINX_OUTPUT && \ + iptables -t nat -A OUTPUT -p tcp -j NGINX_OUTPUT && \ + iptables -t nat -A NGINX_OUTPUT -j NGINX_REDIRECT + ``` + +7. Redirect traffic inbound. + ``` + iptables -t nat -N NGINX_IN_REDIRECT && \ + iptables -t nat -A NGINX_IN_REDIRECT -p tcp -j REDIRECT --to-port 15501 --dport 15001 && \ + iptables -t nat -N NGINX_INBOUND && \ + iptables -t nat -A PREROUTING -p tcp -j NGINX_INBOUND && \ + iptables -t nat -A NGINX_INBOUND -p tcp -j NGINX_IN_REDIRECT + ``` + +8. Test with `curl` (this step assumes you've uncommented the return directive). + ``` + curl --output - ${LISTEN_IP}:15001 + recv'd: ${LISTEN_IP}:15501 + + proxy_pass http://${LISTEN_IP}:15001 + ``` +### Caveats + +This module only supports IPv4. + +## UPSTREAM - Example upstream / load balancing module for HTTP + +This module simply proxies requests through a custom load balancer to the previously configured balancer. This is for demonstration purposes only. As a module writer, you can start with this structure and adjust to your needs, then implement the proper algorithm for your usage. + +The module replaces the `peer` callback functions with its own, logs, and then calls through to the originally saved `peer` functions. This may look confusing at first, but rest assured, it's intentionally not implementing an algorithm of its own. + +### Attributions + +This module was converted from https://github.com/gabihodoroaga/nginx-upstream-module and also highly inspired by the same techniques used in NGINX source: `ngx_http_upstream_keepalive_module.c`. + +### Example Configuration +#### HTTP + +```nginx configuration +load_module "modules/upstream.so" + +http { + upstream backend { + server localhost:15501; + custom 32; + } + + server { + listen 15500; + server_name _; + + location / { + proxy_pass http://backend; + } + } + + server { + listen 15501; + + location / { + return 418; + } + } +} +``` + +### Usage + +1. Clone the git repository. + ``` + git clone git@github.com:nginx/ngx-rust.git + ``` + +2. Compile the module from the cloned repo. + ``` + cd ${CLONED_DIRECTORY}/ngx-rust + cargo build --package=examples --example=upstream + ``` + +3. Copy the shared object to the modules directory, /etc/nginx/modules. + ``` + cp ./target/debug/examples/libupstream.so /etc/nginx/modules + ``` + +4. Add the `load_module` directive to your configuration. + ``` + load_module "modules/libupstream.so"; + ``` + +5. Add the example `server` and `upstream` block from the example above. + +6. Reload NGINX. + ``` + nginx -t && nginx -s reload + ``` + +7. Test with `curl`. Traffic should pass to your listener on port 8081 (this could be another NGINX server for example). With debug logging enabled you should notice the upstream log messages (see the source code for log examples, prefixed with "CUSTOM UPSTREAM"). diff --git a/source/rust/vendor/ngx-rust/examples/async.conf b/source/rust/vendor/ngx-rust/examples/async.conf new file mode 100644 index 0000000..d96876e --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/async.conf @@ -0,0 +1,24 @@ +daemon off; +master_process off; +# worker_processes 1; + +load_module modules/libasync.so; +error_log error.log debug; + +events { } + +http { + server { + listen *:8000; + server_name localhost; + location / { + root html; + index index.html index.htm; + async on; + } + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + } +} diff --git a/source/rust/vendor/ngx-rust/examples/async.rs b/source/rust/vendor/ngx-rust/examples/async.rs new file mode 100644 index 0000000..c1f9620 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/async.rs @@ -0,0 +1,237 @@ +extern crate alloc; + +use alloc::sync::Arc; +use core::ffi::{c_char, c_void}; +use core::mem; +use core::ptr; +use core::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; +use core::time::Duration; +use std::sync::OnceLock; +use std::time::Instant; + +use ngx::core::Status; +use ngx::ffi::{ + NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, NGX_LOG_EMERG, + ngx_command_t, ngx_conf_t, ngx_connection_t, ngx_event_t, ngx_http_module_t, ngx_int_t, + ngx_module_t, ngx_post_event, ngx_posted_events, ngx_posted_next_events, ngx_str_t, ngx_uint_t, +}; +use ngx::http::{self, HttpModule, HttpModuleLocationConf, HttpRequestHandler, MergeConfigError}; +use ngx::{ngx_conf_log_error, ngx_log_debug_http, ngx_string}; +use tokio::runtime::Runtime; + +struct Module; + +impl http::HttpModule for Module { + fn module() -> &'static ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_async_module) } + } + + unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { + // SAFETY: this function is called with non-NULL cf always + let cf = unsafe { &mut *cf }; + http::add_phase_handler::(cf) + .map_or(Status::NGX_ERROR, |_| Status::NGX_OK) + .into() + } +} + +#[derive(Debug, Default)] +struct ModuleConfig { + enable: bool, +} + +unsafe impl HttpModuleLocationConf for Module { + type LocationConf = ModuleConfig; +} + +static mut NGX_HTTP_ASYNC_COMMANDS: [ngx_command_t; 2] = [ + ngx_command_t { + name: ngx_string!("async"), + type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_async_commands_set_enable), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t::empty(), +]; + +static NGX_HTTP_ASYNC_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { + preconfiguration: Some(Module::preconfiguration), + postconfiguration: Some(Module::postconfiguration), + create_main_conf: None, + init_main_conf: None, + create_srv_conf: None, + merge_srv_conf: None, + create_loc_conf: Some(Module::create_loc_conf), + merge_loc_conf: Some(Module::merge_loc_conf), +}; + +// Generate the `ngx_modules` table with exported modules. +// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. +#[cfg(feature = "export-modules")] +ngx::ngx_modules!(ngx_http_async_module); + +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] +pub static mut ngx_http_async_module: ngx_module_t = ngx_module_t { + ctx: &raw const NGX_HTTP_ASYNC_MODULE_CTX as _, + commands: unsafe { &raw mut NGX_HTTP_ASYNC_COMMANDS[0] }, + type_: NGX_HTTP_MODULE as _, + ..ngx_module_t::default() +}; + +impl http::Merge for ModuleConfig { + fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> { + if prev.enable { + self.enable = true; + }; + Ok(()) + } +} + +unsafe extern "C" fn check_async_work_done(event: *mut ngx_event_t) { + let ctx = ngx::ngx_container_of!(event, RequestCTX, event); + let c: *mut ngx_connection_t = unsafe { (*event).data.cast() }; + + if unsafe { (*ctx).done.load(Ordering::Relaxed) } { + // Triggering async_access_handler again + unsafe { ngx_post_event((*c).write, &raw mut ngx_posted_events) }; + } else { + // this doesn't have have good performance but works as a simple thread-safe example and + // doesn't causes segfault. The best method that provides both thread-safety and + // performance requires an nginx patch. + unsafe { ngx_post_event(event, &raw mut ngx_posted_next_events) }; + } +} + +struct RequestCTX { + done: Arc, + event: ngx_event_t, + task: Option>, +} + +impl Default for RequestCTX { + fn default() -> Self { + Self { + done: AtomicBool::new(false).into(), + event: unsafe { mem::zeroed() }, + task: Default::default(), + } + } +} + +impl Drop for RequestCTX { + fn drop(&mut self) { + if let Some(handle) = self.task.take() { + handle.abort(); + } + + if self.event.posted() != 0 { + unsafe { ngx::ffi::ngx_delete_posted_event(&raw mut self.event) }; + } + } +} + +struct AsyncAccessHandler; + +impl HttpRequestHandler for AsyncAccessHandler { + const PHASE: ngx::http::HttpPhase = ngx::http::HttpPhase::Access; + type Output = Status; + + fn handler(request: &mut http::Request) -> Self::Output { + let co = Module::location_conf(request).expect("module config is none"); + + ngx_log_debug_http!(request, "async module enabled: {}", co.enable); + + if !co.enable { + return Status::NGX_DECLINED; + } + + if let Some(ctx) = request.get_module_ctx::(Module::module()) { + if !ctx.done.load(Ordering::Relaxed) { + return Status::NGX_AGAIN; + } + + return Status::NGX_OK; + } + + let ctx = request.pool().allocate(RequestCTX::default()); + if ctx.is_null() { + return Status::NGX_ERROR; + } + request.set_module_ctx(ctx.cast(), Module::module()); + + let ctx = unsafe { &mut *ctx }; + ctx.event.handler = Some(check_async_work_done); + ctx.event.data = request.connection().cast(); + ctx.event.log = unsafe { (*request.connection()).log }; + unsafe { ngx_post_event(&raw mut ctx.event, &raw mut ngx_posted_next_events) }; + + // Request is no longer needed and can be converted to something movable to the async block + let req = AtomicPtr::new(request.into()); + let done_flag = ctx.done.clone(); + + let rt = ngx_http_async_runtime(); + ctx.task = Some(rt.spawn(async move { + let start = Instant::now(); + tokio::time::sleep(Duration::from_secs(2)).await; + let req = unsafe { http::Request::from_ngx_http_request(req.load(Ordering::Relaxed)) }; + // not really thread safe, we should apply all these operation in nginx thread + // but this is just an example. proper way would be storing these headers in the request + // ctx and apply them when we get back to the nginx thread. + req.add_header_out("X-Async-Time", start.elapsed().as_millis().to_string().as_str()); + + done_flag.store(true, Ordering::Release); + // there is a small issue here. If traffic is low we may get stuck behind a 300ms timer + // in the nginx event loop. To workaround it we can notify the event loop using + // pthread_kill( nginx_thread, SIGIO ) to wake up the event loop. (or patch nginx + // and use the same trick as the thread pool) + })); + + Status::NGX_AGAIN + } +} + +extern "C" fn ngx_http_async_commands_set_enable( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + unsafe { + let conf = &mut *(conf as *mut ModuleConfig); + let args: &[ngx_str_t] = (*(*cf).args).as_slice(); + let val = match args[1].to_str() { + Ok(s) => s, + Err(_) => { + ngx_conf_log_error!(NGX_LOG_EMERG, cf, "`async` argument is not utf-8 encoded"); + return ngx::core::NGX_CONF_ERROR; + } + }; + + // set default value optionally + conf.enable = false; + + if val.eq_ignore_ascii_case("on") { + conf.enable = true; + } else if val.eq_ignore_ascii_case("off") { + conf.enable = false; + } + }; + + ngx::core::NGX_CONF_OK +} + +fn ngx_http_async_runtime() -> &'static Runtime { + // Should not be called from the master process + assert_ne!(unsafe { ngx::ffi::ngx_process }, ngx::ffi::NGX_PROCESS_MASTER as _); + + static RUNTIME: OnceLock = OnceLock::new(); + RUNTIME.get_or_init(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .expect("tokio runtime init") + }) +} diff --git a/source/rust/vendor/ngx-rust/examples/auto/rust b/source/rust/vendor/ngx-rust/examples/auto/rust new file mode 100644 index 0000000..f3f1032 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/auto/rust @@ -0,0 +1,351 @@ +#!/bin/sh +# +# Copyright 2025 Nginx, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# +# Utility library for integration of ngx-rust modules into the NGINX build +# configuration. +# +# Usage: +# +# In "config", +# +# ```sh +# . $ngx_addon_dir/auto/rust +# +# # ngx_addon_name determines the build directory and should be set before +# # any modules are defined +# +# ngx_addon_name="example" +# +# if [ $HTTP = YES ]; then +# # Regular NGINX module options, +# # http://nginx.org/en/docs/dev/development_guide.html#adding_new_modules +# +# ngx_module_type=HTTP +# # Should match the "ngx_module_t" static name(s) exported from the Rust code +# ngx_module_name=ngx_http_example_module +# ngx_module_incs= +# ngx_module_deps= +# ngx_module_libs= +# +# # Options specific to ngx-rust modules +# +# # Target type: LIB or EXAMPLE +# ngx_rust_target_type=LIB +# +# # Target name: crate name, lib.name or example.name +# ngx_rust_target_name=example +# +# # Whitespace-separated list of cargo features. +# # "default" should be specified explicitly if required. +# ngx_rust_target_features= +# +# ngx_rust_module +# fi +# ``` +# +# In "config.make", +# +# ```sh +# ngx_addon_name="example" +# ngx_cargo_manifest=$ngx_addon_dir/Cargo.toml +# +# # generate Makefile section for all the modules configured earlier +# +# ngx_rust_make_modules +# ``` +# +# The following environment variables can affect the generated Makefile: +# +# - NGX_CARGO sets the "cargo" binary to use, e.g. NGX_CARGO=cargo-1.82 +# - NGX_RUST_TARGET passes the --target to the Rust compiler if set +# - NGX_RUSTC_OPT passes additional options to "cargo rustc" + +# Prevent duplicate invocation unless it is a newer library version +if [ "${NGX_RUST_AUTO_VER:-0}" -ge 1 ]; then + return +fi + +NGX_RUST_AUTO_VER=1 + +echo $ngx_n "checking for Rust toolchain ...$ngx_c" + +NGX_CARGO=${NGX_CARGO:-cargo} + +NGX_RUST_VER=$($NGX_CARGO version 2>&1 \ + | grep 'cargo 1\.[0-9][0-9]*\.[0-9]*' 2>&1 \ + | sed -e 's/^.* \(1\.[0-9][0-9]*\.[0-9][0.9]*.*\)/\1/') + +NGX_RUST_VERSION=${NGX_RUST_VER%% *} + +if [ -z "$NGX_RUST_VERSION" ]; then + echo " not found" + echo + echo $0: error: cargo binary $NGX_CARGO is not found + echo + exit 1 +fi + +echo " found" +echo " + Rust version: $NGX_RUST_VER" + +case "$NGX_MACHINE" in + + amd64) + RUST_TARGET_ARCH=x86_64 + ;; + + arm64) + RUST_TARGET_ARCH=aarch64 + ;; + + i?86) + RUST_TARGET_ARCH=i686 + ;; + + *) + RUST_TARGET_ARCH=$NGX_MACHINE + ;; + +esac + +case "$NGX_PLATFORM" in + + OpenBSD:*) + # ld: error: undefined symbol: _Unwind_... + RUST_LIBS="$RUST_LIBS -lutil" + RUST_LIBS="$RUST_LIBS -lexecinfo" + RUST_LIBS="$RUST_LIBS -lc++abi" + ;; + + win32) + case "$NGX_CC_NAME" in + + msvc) + # as suggested by rustc --print native-static-libs, + # excluding entries already present in CORE_LIBS + RUST_LIBS="$RUST_LIBS bcrypt.lib" # ??? + RUST_LIBS="$RUST_LIBS ntdll.lib" # std::io, std::sys::pal::windows + RUST_LIBS="$RUST_LIBS userenv.lib" # std::env::home_dir + RUST_LIBS="$RUST_LIBS dbghelp.lib" # backtrace symbolization + + NGX_RUST_TARGET=${NGX_RUST_TARGET:-$RUST_TARGET_ARCH-pc-windows-msvc} + ;; + + gcc | clang) + RUST_LIBS="$RUST_LIBS -lbcrypt" + RUST_LIBS="$RUST_LIBS -lntdll" + RUST_LIBS="$RUST_LIBS -luserenv" + RUST_LIBS="$RUST_LIBS -ldbghelp" + # gnullvm on arm64? + NGX_RUST_TARGET=${NGX_RUST_TARGET:-$RUST_TARGET_ARCH-pc-windows-gnu} + ;; + + esac + ;; + +esac + + +# Prepare cargo configuration file + +if [ "$NGX_DEBUG" = YES ]; then + ngx_cargo_default_profile=ngx-debug +else + ngx_cargo_default_profile=ngx-release +fi + +ngx_cargo_config=$NGX_OBJS/.cargo/config.toml +ngx_cargo_profile=${ngx_cargo_profile:-$ngx_cargo_default_profile} + +mkdir -p "$NGX_OBJS/.cargo" + +cat << END > "$ngx_cargo_config" + +[profile.ngx-debug] +inherits = "dev" + +[profile.ngx-release] +inherits = "release" +strip = "none" + +# compatibility with LIBC=-MT set in auto/cc/msvc +[target.aarch64-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] + +[target.i686-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] + +[target.x86_64-pc-windows-msvc] +rustflags = ["-C", "target-feature=+crt-static"] + +[env] +NGINX_BUILD_DIR = { value = ".", force = true, relative = true } +END + +if [ "$NGX_PLATFORM" = win32 ] && command -v cygpath >/dev/null; then + printf >> "$ngx_cargo_config" 'NGINX_SOURCE_DIR = "%s"\n' \ + "$(cygpath -m "$PWD")" +else + printf >> "$ngx_cargo_config" 'NGINX_SOURCE_DIR = "%s"\n' "$PWD" +fi + + +# Reconstructs path to a static lib built with cargo rustc, +# relative to the --target-dir + +ngx_rust_target_path () { + ngx_rust_obj=$(echo "$ngx_rust_target_name" | tr - _) + + case "$NGX_CC_NAME" in + + msvc) + ngx_rust_obj=${ngx_rust_obj}.lib + ;; + + *) + ngx_rust_obj=lib${ngx_rust_obj}.a + ;; + + esac + + if [ "$ngx_rust_target_type" = EXAMPLE ]; then + ngx_rust_obj=examples/$ngx_rust_obj + fi + + echo "${NGX_RUST_TARGET:+$NGX_RUST_TARGET/}$ngx_cargo_profile/$ngx_rust_obj" +} + + +# Registers a module in the buildsystem. +# In addition to the regular auto/module parameters, the following variables +# are expected to be set: +# +# ngx_rust_target_type=LIB|EXAMPLE +# ngx_rust_target_name= +# ngx_rust_target_features= +# +# [^1]: https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-name-field) + +ngx_rust_module () { + ngx_addon_id=$(echo "$ngx_addon_name" | sed -e 's/[^A-Za-z0-9_]/_/g') + ngx_rust_obj=$NGX_OBJS/$ngx_addon_id/$(ngx_rust_target_path) + + ngx_module_deps_saved=$ngx_module_deps + ngx_module_deps="$ngx_rust_obj $ngx_module_deps" + + ngx_module_libs_saved=$ngx_module_libs + ngx_module_libs="$ngx_rust_obj $ngx_module_libs $RUST_LIBS" + + if [ -n "$ngx_rust_target_features" ]; then + eval ${ngx_addon_id}_RUST_FEATURES=\"\$${ngx_addon_id}_RUST_FEATURES \ + $ngx_rust_target_features\" + fi + + . auto/module + + ngx_rust_target=$ngx_rust_target_type:$ngx_rust_target_name + + # module deps are usually added to the object file targets, but we don't have any + + if [ "$ngx_module_link" = DYNAMIC ]; then + # remember the dynamic module name and generate dependency later + ngx_rust_target=$ngx_rust_target:$ngx_module + else + # add dependency to the binary target + LINK_DEPS="$LINK_DEPS $ngx_rust_obj" + fi + + eval ${ngx_addon_id}_RUST_TARGETS=\"\$${ngx_addon_id}_RUST_TARGETS \ + $ngx_rust_target\" + + ngx_module_deps=$ngx_module_deps_saved + ngx_module_libs=$ngx_module_libs_saved +} + + +# Writes a Makefile fragment for all the modules configured for "ngx_addon_name" + +ngx_rust_make_modules () { + ngx_addon_id=$(echo "$ngx_addon_name" | sed -e 's/[^A-Za-z0-9_]/_/g') + ngx_cargo_manifest=${ngx_cargo_manifest:-"$ngx_addon_dir/Cargo.toml"} + + eval ngx_rust_features="\$${ngx_addon_id}_RUST_FEATURES" + eval ngx_rust_targets="\$${ngx_addon_id}_RUST_TARGETS" + + for target in $ngx_rust_targets; do + IFS=':' read -r ngx_rust_target_type ngx_rust_target_name ngx_rust_module_name <> $NGX_MAKEFILE + +.NGX_RUST_PHONY: ; + +END + fi + + cat << END >> $NGX_MAKEFILE + +$ngx_rust_obj: .NGX_RUST_PHONY + $NGX_CARGO rustc \\ + --config $ngx_cargo_config \\ + --crate-type staticlib \\ + --manifest-path "$ngx_cargo_manifest" \\ + --no-default-features \\ + --profile $ngx_cargo_profile \\ + ${NGX_RUST_TARGET:+--target $NGX_RUST_TARGET} \\ + --target-dir $NGX_OBJS/$ngx_addon_id \\ + --features "$ngx_rust_features" \\ + $ngx_rustc_module_opt $NGX_RUSTC_OPT + +END + + # Ensure that the "auto"-generated dynamic module target depends on the + # static library. Normally this is achieved by attaching ADDON_DEPS to + # the module object files, but we don't have any suitable C sources. + + if [ -n "$ngx_rust_module_name" ]; then + cat << END >> $NGX_MAKEFILE +$NGX_OBJS$ngx_dirsep$ngx_rust_module_name$ngx_modext: $ngx_rust_obj +END + fi +} diff --git a/source/rust/vendor/ngx-rust/examples/awssig.conf b/source/rust/vendor/ngx-rust/examples/awssig.conf new file mode 100644 index 0000000..5ff331e --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/awssig.conf @@ -0,0 +1,50 @@ +daemon off; +master_process off; +# worker_processes 1; + +# on linix load a module: +load_module modules/libawssig.so; + +# error_log /dev/stdout debug; +error_log error.log debug; + +# working_directory /tmp/cores/; +# worker_rlimit_core 500M; + +events { } + +http { + server { + listen *:8000; + server_name localhost; + + awssigv4_access_key my-access-key; + awssigv4_secret_key my-secret-key; + awssigv4_s3_bucket my-bucket; + + location / { + awssigv4 on; + proxy_pass http://localhost:8777; + ## (on | off ) to enable aws sig v4 + location /some { + awssigv4 off; + } + ## awssigv4_s3_endpoint if not set then 's3.amazonaws.com' + # awssigv4_s3_endpoint s3.amazonaws.com; + } + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + } + server { + listen 8777; + server_name localhost; + location / { + add_header x-authorization $http_authorization; + add_header x-Amz-Date $http_x_amz_date; + return 204; + } + } +} diff --git a/source/rust/vendor/ngx-rust/examples/awssig.rs b/source/rust/vendor/ngx-rust/examples/awssig.rs new file mode 100644 index 0000000..0ff8c7c --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/awssig.rs @@ -0,0 +1,324 @@ +use core::ffi::{c_char, c_void}; +use core::ptr; + +use http::HeaderMap; +use ngx::core::Status; +use ngx::ffi::{ + NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, + NGX_HTTP_SRV_CONF, NGX_LOG_EMERG, ngx_command_t, ngx_conf_t, ngx_http_module_t, ngx_int_t, + ngx_module_t, ngx_str_t, ngx_uint_t, +}; +use ngx::http::*; +use ngx::{ngx_conf_log_error, ngx_log_debug_http, ngx_string}; + +struct Module; + +impl HttpModule for Module { + fn module() -> &'static ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_awssigv4_module) } + } + + unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { + // SAFETY: this function is called with non-NULL cf always + let cf = unsafe { &mut *cf }; + ngx::http::add_phase_handler::(cf) + .map_or(Status::NGX_ERROR, |_| Status::NGX_OK) + .into() + } +} + +#[derive(Debug, Default)] +struct ModuleConfig { + enable: bool, + access_key: String, + secret_key: String, + s3_bucket: String, + s3_endpoint: String, +} + +unsafe impl HttpModuleLocationConf for Module { + type LocationConf = ModuleConfig; +} + +static mut NGX_HTTP_AWSSIGV4_COMMANDS: [ngx_command_t; 6] = [ + ngx_command_t { + name: ngx_string!("awssigv4"), + type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_awssigv4_commands_set_enable), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("awssigv4_access_key"), + type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_awssigv4_commands_set_access_key), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("awssigv4_secret_key"), + type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_awssigv4_commands_set_secret_key), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("awssigv4_s3_bucket"), + type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_awssigv4_commands_set_s3_bucket), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("awssigv4_s3_endpoint"), + type_: (NGX_HTTP_LOC_CONF | NGX_HTTP_SRV_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_awssigv4_commands_set_s3_endpoint), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t::empty(), +]; + +static NGX_HTTP_AWSSIGV4_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { + preconfiguration: Some(Module::preconfiguration), + postconfiguration: Some(Module::postconfiguration), + create_main_conf: None, + init_main_conf: None, + create_srv_conf: None, + merge_srv_conf: None, + create_loc_conf: Some(Module::create_loc_conf), + merge_loc_conf: Some(Module::merge_loc_conf), +}; + +// Generate the `ngx_modules` table with exported modules. +// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. +#[cfg(feature = "export-modules")] +ngx::ngx_modules!(ngx_http_awssigv4_module); + +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] +pub static mut ngx_http_awssigv4_module: ngx_module_t = ngx_module_t { + ctx: &raw const NGX_HTTP_AWSSIGV4_MODULE_CTX as _, + commands: unsafe { &raw mut NGX_HTTP_AWSSIGV4_COMMANDS[0] }, + type_: NGX_HTTP_MODULE as _, + ..ngx_module_t::default() +}; + +impl Merge for ModuleConfig { + fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> { + if prev.enable { + self.enable = true; + }; + + if self.access_key.is_empty() { + self.access_key = + String::from(if !prev.access_key.is_empty() { &prev.access_key } else { "" }); + } + if self.enable && self.access_key.is_empty() { + return Err(MergeConfigError::NoValue); + } + + if self.secret_key.is_empty() { + self.secret_key = + String::from(if !prev.secret_key.is_empty() { &prev.secret_key } else { "" }); + } + if self.enable && self.secret_key.is_empty() { + return Err(MergeConfigError::NoValue); + } + + if self.s3_bucket.is_empty() { + self.s3_bucket = + String::from(if !prev.s3_bucket.is_empty() { &prev.s3_bucket } else { "" }); + } + if self.enable && self.s3_bucket.is_empty() { + return Err(MergeConfigError::NoValue); + } + + if self.s3_endpoint.is_empty() { + self.s3_endpoint = String::from(if !prev.s3_endpoint.is_empty() { + &prev.s3_endpoint + } else { + "s3.amazonaws.com" + }); + } + Ok(()) + } +} + +extern "C" fn ngx_http_awssigv4_commands_set_enable( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + unsafe { + let conf = &mut *(conf as *mut ModuleConfig); + let args: &[ngx_str_t] = (*(*cf).args).as_slice(); + let val = match args[1].to_str() { + Ok(s) => s, + Err(_) => { + ngx_conf_log_error!(NGX_LOG_EMERG, cf, "`awssigv4` argument is not utf-8 encoded"); + return ngx::core::NGX_CONF_ERROR; + } + }; + + // set default value optionally + conf.enable = false; + + if val.len() == 2 && val.eq_ignore_ascii_case("on") { + conf.enable = true; + } else if val.len() == 3 && val.eq_ignore_ascii_case("off") { + conf.enable = false; + } + }; + + ngx::core::NGX_CONF_OK +} + +extern "C" fn ngx_http_awssigv4_commands_set_access_key( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + unsafe { + let conf = &mut *(conf as *mut ModuleConfig); + let args: &[ngx_str_t] = (*(*cf).args).as_slice(); + conf.access_key = args[1].to_string(); + }; + + ngx::core::NGX_CONF_OK +} + +extern "C" fn ngx_http_awssigv4_commands_set_secret_key( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + unsafe { + let conf = &mut *(conf as *mut ModuleConfig); + let args: &[ngx_str_t] = (*(*cf).args).as_slice(); + conf.secret_key = args[1].to_string(); + }; + + ngx::core::NGX_CONF_OK +} + +extern "C" fn ngx_http_awssigv4_commands_set_s3_bucket( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + unsafe { + let conf = &mut *(conf as *mut ModuleConfig); + let args: &[ngx_str_t] = (*(*cf).args).as_slice(); + conf.s3_bucket = args[1].to_string(); + if conf.s3_bucket.len() == 1 { + println!("Validation failed"); + return ngx::core::NGX_CONF_ERROR; + } + }; + + ngx::core::NGX_CONF_OK +} + +extern "C" fn ngx_http_awssigv4_commands_set_s3_endpoint( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + unsafe { + let conf = &mut *(conf as *mut ModuleConfig); + let args = (*(*cf).args).elts as *mut ngx_str_t; + conf.s3_endpoint = (*args.add(1)).to_string(); + }; + + ngx::core::NGX_CONF_OK +} + +struct AwsSigV4HeaderHandler; + +impl HttpRequestHandler for AwsSigV4HeaderHandler { + const PHASE: HttpPhase = HttpPhase::PreContent; + type Output = Status; + + fn handler(request: &mut Request) -> Self::Output { + // get Module Config from request + let conf = Module::location_conf(request).expect("module conf"); + ngx_log_debug_http!(request, "AWS signature V4 module {}", { + if conf.enable { "enabled" } else { "disabled" } + }); + if !conf.enable { + return Status::NGX_DECLINED; + } + + // TODO: build url properly from the original URL from client + let method = request.method(); + if !matches!(method, ngx::http::Method::HEAD | ngx::http::Method::GET) { + return HTTPStatus::FORBIDDEN.into(); + } + + let datetime = chrono::Utc::now(); + let uri = match request.unparsed_uri().to_str() { + Ok(v) => format!("https://{}.{}{}", conf.s3_bucket, conf.s3_endpoint, v), + Err(_) => return Status::NGX_DECLINED, + }; + + let datetime_now = datetime.format("%Y%m%dT%H%M%SZ"); + let datetime_now = datetime_now.to_string(); + + let signature = { + // NOTE: aws_sign_v4::AwsSign::new() implementation requires a HeaderMap. + // Iterate over requests headers_in and copy into HeaderMap + // Copy only headers that will be used to sign the request + let mut headers = HeaderMap::new(); + for (name, value) in request.headers_in_iterator() { + if let Ok(name) = name.to_str() { + if name.to_lowercase() == "host" { + let Ok(value) = http::HeaderValue::from_bytes(value.as_bytes()) else { + return Status::NGX_DECLINED; + }; + + headers.insert(http::header::HOST, value); + } + } else { + return Status::NGX_DECLINED; + } + } + headers.insert("X-Amz-Date", datetime_now.parse().unwrap()); + ngx_log_debug_http!(request, "headers {:?}", headers); + ngx_log_debug_http!(request, "method {:?}", method); + ngx_log_debug_http!(request, "uri {:?}", uri); + ngx_log_debug_http!(request, "datetime_now {:?}", datetime_now); + + let s = aws_sign_v4::AwsSign::new( + method.as_str(), + &uri, + &datetime, + &headers, + "us-east-1", + conf.access_key.as_str(), + conf.secret_key.as_str(), + "s3", + "", + ); + s.sign() + }; + + request.add_header_in("authorization", signature.as_str()); + request.add_header_in("X-Amz-Date", datetime_now.as_str()); + + for (name, value) in request.headers_out_iterator() { + ngx_log_debug_http!(request, "headers_out {name}: {value}",); + } + for (name, value) in request.headers_in_iterator() { + ngx_log_debug_http!(request, "headers_in {name}: {value}",); + } + + Status::NGX_OK + } +} diff --git a/source/rust/vendor/ngx-rust/examples/awssig_curl_combined.conf b/source/rust/vendor/ngx-rust/examples/awssig_curl_combined.conf new file mode 100644 index 0000000..7956e0e --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/awssig_curl_combined.conf @@ -0,0 +1,53 @@ +daemon off; +master_process off; +# worker_processes 1; + +# on linix load a module: +load_module modules/libawssig.so; +load_module modules/libcurl.so; + +# error_log /dev/stdout debug; +error_log error.log debug; + +# working_directory /tmp/cores/; +# worker_rlimit_core 500M; + +events { } + +http { + server { + listen *:8000; + server_name localhost; + + awssigv4_access_key my-access-key; + awssigv4_secret_key my-secret-key; + awssigv4_s3_bucket my-bucket; + + location / { + awssigv4 on; + curl on; + + proxy_pass http://localhost:8777; + ## (on | off ) to enable aws sig v4 + location /some { + awssigv4 off; + } + ## awssigv4_s3_endpoint if not set then 's3.amazonaws.com' + # awssigv4_s3_endpoint s3.amazonaws.com; + } + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + } + server { + listen 8777; + server_name localhost; + location / { + add_header x-authorization $http_authorization; + add_header x-Amz-Date $http_x_amz_date; + return 204; + } + } +} diff --git a/source/rust/vendor/ngx-rust/examples/config b/source/rust/vendor/ngx-rust/examples/config new file mode 100644 index 0000000..6b76365 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/config @@ -0,0 +1,66 @@ +# shellcheck source=auto/rust +. $ngx_addon_dir/auto/rust + +# ngx_addon_name determines the build directory and should be set before +# any modules are defined + +ngx_addon_name=ngx_rust_examples + +if [ $HTTP = YES ]; then + ngx_module_type=HTTP + ngx_module_incs= + ngx_module_deps= + ngx_module_order= + + ngx_rust_target_type=EXAMPLE + ngx_rust_target_features= + + if :; then + ngx_module_name=ngx_http_async_module + ngx_module_libs="-lm" + ngx_rust_target_name=async + + ngx_rust_module + fi + + if :; then + ngx_module_name=ngx_http_awssigv4_module + ngx_module_libs="-lm" + ngx_rust_target_name=awssig + + ngx_rust_module + fi + + if :; then + ngx_module_name=ngx_http_curl_module + ngx_module_libs= + ngx_rust_target_name=curl + + ngx_rust_module + fi + + if :; then + ngx_module_name=ngx_http_shared_dict_module + ngx_module_libs= + ngx_rust_target_name=shared_dict + + ngx_rust_module + fi + + if :; then + ngx_module_name=ngx_http_upstream_custom_module + ngx_module_libs= + ngx_rust_target_name=upstream + + ngx_rust_module + fi + + if [ "$NGX_SYSTEM" = Linux ]; then + ngx_module_name=ngx_http_orig_dst_module + ngx_module_libs= + ngx_rust_target_name=httporigdst + ngx_rust_target_features=linux + + ngx_rust_module + fi +fi diff --git a/source/rust/vendor/ngx-rust/examples/config.make b/source/rust/vendor/ngx-rust/examples/config.make new file mode 100644 index 0000000..5e62127 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/config.make @@ -0,0 +1,6 @@ +ngx_addon_name=ngx_rust_examples +ngx_cargo_manifest=$ngx_addon_dir/Cargo.toml + +# generate Makefile section for all the modules configured earlier + +ngx_rust_make_modules diff --git a/source/rust/vendor/ngx-rust/examples/curl.conf b/source/rust/vendor/ngx-rust/examples/curl.conf new file mode 100644 index 0000000..603fc15 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/curl.conf @@ -0,0 +1,31 @@ +daemon off; +master_process off; +# worker_processes 1; + +# on linux load a module: +load_module modules/libcurl.so; + +# on mac os it would be dylib +# load_module modules/libcurl.dylib; + +# error_log /dev/stdout debug; +error_log error.log debug; + +events { } + +http { + server { + listen *:8000; + server_name localhost; + location / { + root html; + index index.html index.htm; + # libcurl module directive: + curl on; + } + error_page 500 502 503 504 /50x.html; + location = /50x.html { + root html; + } + } +} diff --git a/source/rust/vendor/ngx-rust/examples/curl.rs b/source/rust/vendor/ngx-rust/examples/curl.rs new file mode 100644 index 0000000..be77920 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/curl.rs @@ -0,0 +1,136 @@ +use core::ffi::{c_char, c_void}; +use core::ptr; + +use ngx::core::Status; +use ngx::ffi::{ + NGX_CONF_TAKE1, NGX_HTTP_LOC_CONF, NGX_HTTP_LOC_CONF_OFFSET, NGX_HTTP_MODULE, NGX_LOG_EMERG, + ngx_command_t, ngx_conf_t, ngx_http_module_t, ngx_int_t, ngx_module_t, ngx_str_t, ngx_uint_t, +}; +use ngx::http::{self, HttpModule, HttpModuleLocationConf, HttpRequestHandler, MergeConfigError}; +use ngx::{ngx_conf_log_error, ngx_log_debug_http, ngx_string}; + +struct Module; + +impl http::HttpModule for Module { + fn module() -> &'static ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_curl_module) } + } + + unsafe extern "C" fn postconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { + // SAFETY: this function is called with non-NULL cf always + let cf = unsafe { &mut *cf }; + http::add_phase_handler::(cf) + .map_or(Status::NGX_ERROR, |_| Status::NGX_OK) + .into() + } +} + +#[derive(Debug, Default)] +struct ModuleConfig { + enable: bool, +} + +unsafe impl HttpModuleLocationConf for Module { + type LocationConf = ModuleConfig; +} + +static mut NGX_HTTP_CURL_COMMANDS: [ngx_command_t; 2] = [ + ngx_command_t { + name: ngx_string!("curl"), + type_: (NGX_HTTP_LOC_CONF | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_curl_commands_set_enable), + conf: NGX_HTTP_LOC_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t::empty(), +]; + +static NGX_HTTP_CURL_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { + preconfiguration: Some(Module::preconfiguration), + postconfiguration: Some(Module::postconfiguration), + create_main_conf: None, + init_main_conf: None, + create_srv_conf: None, + merge_srv_conf: None, + create_loc_conf: Some(Module::create_loc_conf), + merge_loc_conf: Some(Module::merge_loc_conf), +}; + +// Generate the `ngx_modules` table with exported modules. +// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. +#[cfg(feature = "export-modules")] +ngx::ngx_modules!(ngx_http_curl_module); + +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] +pub static mut ngx_http_curl_module: ngx_module_t = ngx_module_t { + ctx: &raw const NGX_HTTP_CURL_MODULE_CTX as _, + commands: unsafe { &raw mut NGX_HTTP_CURL_COMMANDS[0] }, + type_: NGX_HTTP_MODULE as _, + ..ngx_module_t::default() +}; + +impl http::Merge for ModuleConfig { + fn merge(&mut self, prev: &ModuleConfig) -> Result<(), MergeConfigError> { + if prev.enable { + self.enable = true; + }; + Ok(()) + } +} + +struct CurlRequestHandler; + +impl HttpRequestHandler for CurlRequestHandler { + const PHASE: ngx::http::HttpPhase = ngx::http::HttpPhase::Access; + type Output = Status; + + fn handler(request: &mut http::Request) -> Self::Output { + let co = Module::location_conf(request).expect("module config is none"); + + ngx_log_debug_http!(request, "curl module enabled: {}", co.enable); + + match co.enable { + true => { + if request.user_agent().is_some_and(|ua| ua.as_bytes().starts_with(b"curl")) { + http::HTTPStatus::FORBIDDEN.into() + } else { + Status::NGX_DECLINED + } + } + false => Status::NGX_DECLINED, + } + } +} + +extern "C" fn ngx_http_curl_commands_set_enable( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + unsafe { + let conf = &mut *(conf as *mut ModuleConfig); + let args: &[ngx_str_t] = (*(*cf).args).as_slice(); + + let val = match args[1].to_str() { + Ok(s) => s, + Err(_) => { + ngx_conf_log_error!(NGX_LOG_EMERG, cf, "`curl` argument is not utf-8 encoded"); + return ngx::core::NGX_CONF_ERROR; + } + }; + + // set default value optionally + conf.enable = false; + + if val.len() == 2 && val.eq_ignore_ascii_case("on") { + conf.enable = true; + } else if val.len() == 3 && val.eq_ignore_ascii_case("off") { + conf.enable = false; + } + }; + + ngx::core::NGX_CONF_OK +} diff --git a/source/rust/vendor/ngx-rust/examples/httporigdst.conf b/source/rust/vendor/ngx-rust/examples/httporigdst.conf new file mode 100644 index 0000000..6fff8c2 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/httporigdst.conf @@ -0,0 +1,16 @@ +http { + server { + # use iptables to capture all outgoing traffic and REDIRECT + # to listening port 15501 + listen 15501; + + # binding variables provided by module will lazily activate it + # and store a context + # variables can be used in config + location / { + # Return if no backend is available or proxy_pass + # return 200 "recv'd: $server_addr:$server_port\n\nproxy_pass http://$server_orig_addr:$server_orig_port\n"; + proxy_pass http://$server_orig_addr:$server_orig_port; + } + } +} \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/examples/httporigdst.rs b/source/rust/vendor/ngx-rust/examples/httporigdst.rs new file mode 100644 index 0000000..2eda38d --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/httporigdst.rs @@ -0,0 +1,283 @@ +use core::ffi::{c_int, c_void}; +use core::mem; +use core::ptr::{self, NonNull}; + +use ngx::core::{Pool, Status}; +use ngx::ffi::{ + INET_ADDRSTRLEN, NGX_HTTP_MODULE, in_port_t, ngx_conf_t, ngx_connection_local_sockaddr, + ngx_http_add_variable, ngx_http_module_t, ngx_http_variable_t, ngx_inet_get_port, ngx_int_t, + ngx_module_t, ngx_sock_ntop, ngx_str_t, ngx_variable_value_t, sockaddr, sockaddr_storage, +}; +use ngx::http::{self, HttpModule}; +use ngx::{http_variable_get, ngx_log_debug_http, ngx_string}; + +const IPV4_STRLEN: usize = INET_ADDRSTRLEN as usize; + +#[derive(Debug, Default)] +struct NgxHttpOrigDstCtx { + orig_dst_addr: ngx_str_t, + orig_dst_port: ngx_str_t, +} + +impl NgxHttpOrigDstCtx { + pub fn save(&mut self, addr: &str, port: in_port_t, pool: &Pool) -> Status { + let addr_data = pool.alloc_unaligned(addr.len()); + if addr_data.is_null() { + return Status::NGX_ERROR; + } + unsafe { libc::memcpy(addr_data, addr.as_ptr() as *const c_void, addr.len()) }; + self.orig_dst_addr.len = addr.len(); + self.orig_dst_addr.data = addr_data as *mut u8; + + let port_str = port.to_string(); + let port_data = pool.alloc_unaligned(port_str.len()); + if port_data.is_null() { + return Status::NGX_ERROR; + } + unsafe { + libc::memcpy(port_data, port_str.as_bytes().as_ptr() as *const c_void, port_str.len()) + }; + self.orig_dst_port.len = port_str.len(); + self.orig_dst_port.data = port_data as *mut u8; + + Status::NGX_OK + } + + pub unsafe fn bind_addr(&self, v: *mut ngx_variable_value_t) { + let mut v = NonNull::new(v).unwrap(); + let v = unsafe { v.as_mut() }; + if self.orig_dst_addr.len == 0 { + v.set_not_found(1); + return; + } + + v.set_valid(1); + v.set_no_cacheable(0); + v.set_not_found(0); + v.set_len(self.orig_dst_addr.len as u32); + v.data = self.orig_dst_addr.data; + } + + pub unsafe fn bind_port(&self, v: *mut ngx_variable_value_t) { + let mut v = NonNull::new(v).unwrap(); + let v = unsafe { v.as_mut() }; + if self.orig_dst_port.len == 0 { + v.set_not_found(1); + return; + } + + v.set_valid(1); + v.set_no_cacheable(0); + v.set_not_found(0); + v.set_len(self.orig_dst_port.len as u32); + v.data = self.orig_dst_port.data; + } +} + +static NGX_HTTP_ORIG_DST_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { + preconfiguration: Some(Module::preconfiguration), + postconfiguration: Some(Module::postconfiguration), + create_main_conf: None, + init_main_conf: None, + create_srv_conf: None, + merge_srv_conf: None, + create_loc_conf: None, + merge_loc_conf: None, +}; + +// Generate the `ngx_modules` table with exported modules. +// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. +#[cfg(feature = "export-modules")] +ngx::ngx_modules!(ngx_http_orig_dst_module); + +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] +pub static mut ngx_http_orig_dst_module: ngx_module_t = ngx_module_t { + ctx: &raw const NGX_HTTP_ORIG_DST_MODULE_CTX as _, + commands: ptr::null_mut(), + type_: NGX_HTTP_MODULE as _, + ..ngx_module_t::default() +}; + +static mut NGX_HTTP_ORIG_DST_VARS: [ngx_http_variable_t; 2] = [ + // ngx_str_t name + // ngx_http_set_variable_pt set_handler + // ngx_http_get_variable_pt get_handler + // uintptr_t data + // ngx_uint_t flags + // ngx_uint_t index + ngx_http_variable_t { + name: ngx_string!("server_orig_addr"), + set_handler: None, + get_handler: Some(ngx_http_orig_dst_addr_variable), + data: 0, + flags: 0, + index: 0, + }, + ngx_http_variable_t { + name: ngx_string!("server_orig_port"), + set_handler: None, + get_handler: Some(ngx_http_orig_dst_port_variable), + data: 0, + flags: 0, + index: 0, + }, +]; + +unsafe fn ngx_get_origdst(request: &mut http::Request) -> Result<(String, in_port_t), Status> { + let c = request.connection(); + + if unsafe { (*c).type_ } != libc::SOCK_STREAM { + ngx_log_debug_http!(request, "httporigdst: connection is not type SOCK_STREAM"); + return Err(Status::NGX_DECLINED); + } + + if unsafe { ngx_connection_local_sockaddr(c, ptr::null_mut(), 0) } != Status::NGX_OK.into() { + ngx_log_debug_http!(request, "httporigdst: no local sockaddr from connection"); + return Err(Status::NGX_ERROR); + } + + let level: c_int; + let optname: c_int; + match unsafe { (*(*c).local_sockaddr).sa_family } as i32 { + libc::AF_INET => { + level = libc::SOL_IP; + optname = libc::SO_ORIGINAL_DST; + } + _ => { + ngx_log_debug_http!(request, "httporigdst: only support IPv4"); + return Err(Status::NGX_DECLINED); + } + } + + let mut addr: sockaddr_storage = unsafe { mem::zeroed() }; + let mut addrlen: libc::socklen_t = mem::size_of_val(&addr) as libc::socklen_t; + let rc = unsafe { + libc::getsockopt((*c).fd, level, optname, (&raw mut addr).cast(), &raw mut addrlen) + }; + if rc == -1 { + ngx_log_debug_http!(request, "httporigdst: getsockopt failed"); + return Err(Status::NGX_DECLINED); + } + let mut ip: Vec = vec![0; IPV4_STRLEN]; + let e = unsafe { + ngx_sock_ntop( + (&raw mut addr).cast(), + mem::size_of::() as u32, + ip.as_mut_ptr(), + IPV4_STRLEN, + 0, + ) + }; + if e == 0 { + ngx_log_debug_http!(request, "httporigdst: ngx_sock_ntop failed to convert sockaddr"); + return Err(Status::NGX_ERROR); + } + ip.truncate(e); + + let port = unsafe { ngx_inet_get_port((&raw mut addr).cast()) }; + + Ok((String::from_utf8(ip).unwrap(), port)) +} + +http_variable_get!( + ngx_http_orig_dst_addr_variable, + |request: &mut http::Request, v: *mut ngx_variable_value_t, _: usize| { + let ctx = request.get_module_ctx::(Module::module()); + if let Some(obj) = ctx { + ngx_log_debug_http!(request, "httporigdst: found context and binding variable",); + unsafe { obj.bind_addr(v) }; + return Status::NGX_OK; + } + // lazy initialization: + // get original dest information + // create context + // set context + // bind address + ngx_log_debug_http!(request, "httporigdst: context not found, getting address"); + let r = unsafe { ngx_get_origdst(request) }; + match r { + Err(e) => { + return e; + } + Ok((ip, port)) => { + // create context, + // set context + let new_ctx = request.pool().allocate::(Default::default()); + + if new_ctx.is_null() { + return Status::NGX_ERROR; + } + + ngx_log_debug_http!(request, "httporigdst: saving ip - {:?}, port - {}", ip, port,); + unsafe { (*new_ctx).save(&ip, port, &request.pool()) }; + unsafe { (*new_ctx).bind_addr(v) }; + request.set_module_ctx(new_ctx as *mut c_void, Module::module()); + } + } + Status::NGX_OK + } +); + +http_variable_get!( + ngx_http_orig_dst_port_variable, + |request: &mut http::Request, v: *mut ngx_variable_value_t, _: usize| { + let ctx = request.get_module_ctx::(Module::module()); + if let Some(obj) = ctx { + ngx_log_debug_http!(request, "httporigdst: found context and binding variable",); + unsafe { obj.bind_port(v) }; + return Status::NGX_OK; + } + // lazy initialization: + // get original dest information + // create context + // set context + // bind port + ngx_log_debug_http!(request, "httporigdst: context not found, getting address"); + let r = unsafe { ngx_get_origdst(request) }; + match r { + Err(e) => { + return e; + } + Ok((ip, port)) => { + // create context, + // set context + let new_ctx = request.pool().allocate::(Default::default()); + + if new_ctx.is_null() { + return Status::NGX_ERROR; + } + + ngx_log_debug_http!(request, "httporigdst: saving ip - {:?}, port - {}", ip, port,); + unsafe { (*new_ctx).save(&ip, port, &request.pool()) }; + unsafe { (*new_ctx).bind_port(v) }; + request.set_module_ctx(new_ctx as *mut c_void, Module::module()); + } + } + Status::NGX_OK + } +); + +struct Module; + +impl HttpModule for Module { + fn module() -> &'static ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_orig_dst_module) } + } + + // static ngx_int_t ngx_http_orig_dst_add_variables(ngx_conf_t *cf) + unsafe extern "C" fn preconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { + for mut v in unsafe { NGX_HTTP_ORIG_DST_VARS } { + let var = NonNull::new(unsafe { ngx_http_add_variable(cf, &raw mut v.name, v.flags) }); + if var.is_none() { + return Status::NGX_ERROR.into(); + } + let mut var = var.unwrap(); + let var = unsafe { var.as_mut() }; + var.get_handler = v.get_handler; + var.data = v.data; + } + Status::NGX_OK.into() + } +} diff --git a/source/rust/vendor/ngx-rust/examples/shared_dict.rs b/source/rust/vendor/ngx-rust/examples/shared_dict.rs new file mode 100644 index 0000000..d88ebdb --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/shared_dict.rs @@ -0,0 +1,425 @@ +#![no_std] +use core::ffi::{c_char, c_void}; +use core::mem; +use core::ptr::{self, NonNull}; + +use nginx_sys::{ + NGX_CONF_TAKE2, NGX_HTTP_DELETE, NGX_HTTP_MAIN_CONF, NGX_HTTP_MAIN_CONF_OFFSET, + NGX_HTTP_MODULE, NGX_HTTP_VAR_CHANGEABLE, NGX_HTTP_VAR_NOCACHEABLE, NGX_LOG_EMERG, + ngx_command_t, ngx_conf_t, ngx_http_add_variable, ngx_http_compile_complex_value_t, + ngx_http_complex_value, ngx_http_complex_value_t, ngx_http_module_t, ngx_http_request_t, + ngx_http_variable_t, ngx_http_variable_value_t, ngx_int_t, ngx_module_t, ngx_parse_size, + ngx_shared_memory_add, ngx_shm_zone_t, ngx_str_t, ngx_uint_t, +}; +use ngx::collections::RbTreeMap; +use ngx::core::{NGX_CONF_ERROR, NGX_CONF_OK, NgxStr, NgxString, Pool, SlabPool, Status}; +use ngx::http::{HttpModule, HttpModuleMainConf}; +use ngx::{ngx_conf_log_error, ngx_log_debug, ngx_string}; + +struct HttpSharedDictModule; + +impl HttpModule for HttpSharedDictModule { + fn module() -> &'static ngx_module_t { + unsafe { &*ptr::addr_of!(ngx_http_shared_dict_module) } + } + + unsafe extern "C" fn preconfiguration(cf: *mut ngx_conf_t) -> ngx_int_t { + for mut v in unsafe { NGX_HTTP_SHARED_DICT_VARS } { + let var = NonNull::new(unsafe { ngx_http_add_variable(cf, &raw mut v.name, v.flags) }); + if var.is_none() { + return Status::NGX_ERROR.into(); + } + let var = unsafe { var.unwrap().as_mut() }; + var.get_handler = v.get_handler; + var.set_handler = v.set_handler; + var.data = v.data; + } + Status::NGX_OK.into() + } +} + +unsafe impl HttpModuleMainConf for HttpSharedDictModule { + type MainConf = SharedDictMainConfig; +} + +static mut NGX_HTTP_SHARED_DICT_COMMANDS: [ngx_command_t; 3] = [ + ngx_command_t { + name: ngx_string!("shared_dict_zone"), + type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t, + set: Some(ngx_http_shared_dict_add_zone), + conf: NGX_HTTP_MAIN_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t { + name: ngx_string!("shared_dict"), + type_: (NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2) as ngx_uint_t, + set: Some(ngx_http_shared_dict_add_variable), + conf: NGX_HTTP_MAIN_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t::empty(), +]; + +static mut NGX_HTTP_SHARED_DICT_VARS: [ngx_http_variable_t; 1] = [ngx_http_variable_t { + name: ngx_string!("shared_dict_entries"), + set_handler: Some(ngx_http_shared_dict_set_entries), + get_handler: Some(ngx_http_shared_dict_get_entries), + data: 0, + flags: (NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t, + index: 0, +}]; + +static NGX_HTTP_SHARED_DICT_MODULE_CTX: ngx_http_module_t = ngx_http_module_t { + preconfiguration: Some(HttpSharedDictModule::preconfiguration), + postconfiguration: None, + create_main_conf: Some(HttpSharedDictModule::create_main_conf), + init_main_conf: None, + create_srv_conf: None, + merge_srv_conf: None, + create_loc_conf: None, + merge_loc_conf: None, +}; + +// Generate the `ngx_modules` table with exported modules. +// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. +#[cfg(feature = "export-modules")] +ngx::ngx_modules!(ngx_http_shared_dict_module); + +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] +pub static mut ngx_http_shared_dict_module: ngx_module_t = ngx_module_t { + ctx: &raw const NGX_HTTP_SHARED_DICT_MODULE_CTX as _, + commands: unsafe { &raw mut NGX_HTTP_SHARED_DICT_COMMANDS[0] }, + type_: NGX_HTTP_MODULE as _, + ..ngx_module_t::default() +}; + +type SharedData = ngx::sync::RwLock, NgxString, SlabPool>>; + +#[derive(Debug)] +struct SharedDictMainConfig { + shm_zone: *mut ngx_shm_zone_t, +} + +impl Default for SharedDictMainConfig { + fn default() -> Self { + Self { shm_zone: ptr::null_mut() } + } +} + +extern "C" fn ngx_http_shared_dict_add_zone( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + // SAFETY: configuration handlers always receive a valid `cf` pointer. + let cf = unsafe { cf.as_mut().unwrap() }; + let smcf = + unsafe { conf.cast::().as_mut().expect("shared dict main config") }; + + // SAFETY: + // - `cf.args` is guaranteed to be a pointer to an array with 3 elements (NGX_CONF_TAKE2). + // - The pointers are well-aligned by construction method (`ngx_palloc`). + debug_assert!(!cf.args.is_null() && unsafe { (*cf.args).nelts >= 3 }); + let args = unsafe { (*cf.args).as_slice_mut() }; + + let mut name: ngx_str_t = args[1]; + let size = unsafe { ngx_parse_size(&raw mut args[2]) }; + if size == -1 { + return NGX_CONF_ERROR; + } + + smcf.shm_zone = unsafe { + ngx_shared_memory_add( + cf, + &raw mut name, + size as usize, + (&raw mut ngx_http_shared_dict_module).cast(), + ) + }; + + let Some(shm_zone) = (unsafe { smcf.shm_zone.as_mut() }) else { + return NGX_CONF_ERROR; + }; + + shm_zone.init = Some(ngx_http_shared_dict_zone_init); + shm_zone.data = ptr::from_mut(smcf).cast(); + + NGX_CONF_OK +} + +fn ngx_http_shared_dict_get_shared(shm_zone: &mut ngx_shm_zone_t) -> Result<&SharedData, Status> { + let mut alloc = unsafe { SlabPool::from_shm_zone(shm_zone) }.ok_or(Status::NGX_ERROR)?; + + if alloc.as_mut().data.is_null() { + let shared: RbTreeMap, NgxString, SlabPool> = + RbTreeMap::try_new_in(alloc.clone()).map_err(|_| Status::NGX_ERROR)?; + + let shared = ngx::sync::RwLock::new(shared); + + alloc.as_mut().data = ngx::allocator::allocate(shared, &alloc) + .map_err(|_| Status::NGX_ERROR)? + .as_ptr() + .cast(); + } + + unsafe { alloc.as_ref().data.cast::().as_ref().ok_or(Status::NGX_ERROR) } +} + +extern "C" fn ngx_http_shared_dict_zone_init( + shm_zone: *mut ngx_shm_zone_t, + _data: *mut c_void, +) -> ngx_int_t { + let shm_zone = unsafe { &mut *shm_zone }; + + match ngx_http_shared_dict_get_shared(shm_zone) { + Err(e) => e.into(), + Ok(_) => Status::NGX_OK.into(), + } +} + +extern "C" fn ngx_http_shared_dict_add_variable( + cf: *mut ngx_conf_t, + _cmd: *mut ngx_command_t, + _conf: *mut c_void, +) -> *mut c_char { + // SAFETY: configuration handlers always receive a valid `cf` pointer. + let cf = unsafe { cf.as_mut().unwrap() }; + let pool = unsafe { Pool::from_ngx_pool(cf.pool) }; + + let key = pool.calloc_type::(); + if key.is_null() { + return NGX_CONF_ERROR; + } + + // SAFETY: + // - `cf.args` is guaranteed to be a pointer to an array with 3 elements (NGX_CONF_TAKE2). + // - The pointers are well-aligned by construction method (`ngx_palloc`). + debug_assert!(!cf.args.is_null() && unsafe { (*cf.args).nelts >= 3 }); + let args = unsafe { (*cf.args).as_slice_mut() }; + + let mut ccv: ngx_http_compile_complex_value_t = unsafe { mem::zeroed() }; + ccv.cf = cf; + ccv.value = &raw mut args[1]; + ccv.complex_value = key; + + if unsafe { nginx_sys::ngx_http_compile_complex_value(&raw mut ccv) } != Status::NGX_OK.into() { + return NGX_CONF_ERROR; + } + + let mut name = args[2]; + + if name.as_bytes()[0] != b'$' { + ngx_conf_log_error!(NGX_LOG_EMERG, cf, "invalid variable name \"{name}\""); + return NGX_CONF_ERROR; + } + + name.data = unsafe { name.data.add(1) }; + name.len -= 1; + + let var = unsafe { + ngx_http_add_variable( + cf, + &raw mut name, + (NGX_HTTP_VAR_CHANGEABLE | NGX_HTTP_VAR_NOCACHEABLE) as ngx_uint_t, + ) + }; + if var.is_null() { + return NGX_CONF_ERROR; + } + + unsafe { + (*var).get_handler = Some(ngx_http_shared_dict_get_variable); + (*var).set_handler = Some(ngx_http_shared_dict_set_variable); + (*var).data = key as usize; + } + + NGX_CONF_OK +} + +extern "C" fn ngx_http_shared_dict_get_variable( + r: *mut ngx_http_request_t, + v: *mut ngx_http_variable_value_t, + data: usize, +) -> ngx_int_t { + let r = unsafe { &mut *r }; + let v = unsafe { &mut *v }; + let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); + + let mut key = ngx_str_t::empty(); + if unsafe { ngx_http_complex_value(r, data as _, &raw mut key) } != Status::NGX_OK.into() { + return Status::NGX_ERROR.into(); + } + + let key = unsafe { NgxStr::from_ngx_str(key) }; + + let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { + return Status::NGX_ERROR.into(); + }; + + let value = + shared.read().get(key).and_then(|x| unsafe { ngx_str_t::from_bytes(r.pool, x.as_bytes()) }); + + ngx_log_debug!( + unsafe { (*r.connection).log }, + "shared dict: get \"{}\" -> {:?} w:{} p:{}", + key, + value.as_ref().map(|x| unsafe { NgxStr::from_ngx_str(*x) }), + unsafe { nginx_sys::ngx_worker }, + unsafe { nginx_sys::ngx_pid }, + ); + + let Some(value) = value else { + v.set_not_found(1); + return Status::NGX_ERROR.into(); + }; + + v.data = value.data; + v.set_len(value.len as _); + + v.set_valid(1); + v.set_no_cacheable(0); + v.set_not_found(0); + + Status::NGX_OK.into() +} + +extern "C" fn ngx_http_shared_dict_set_variable( + r: *mut ngx_http_request_t, + v: *mut ngx_http_variable_value_t, + data: usize, +) { + let r = unsafe { &mut *r }; + let v = unsafe { &mut *v }; + let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); + let mut key = ngx_str_t::empty(); + + if unsafe { ngx_http_complex_value(r, data as _, &raw mut key) } != Status::NGX_OK.into() { + return; + } + + let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { + return; + }; + + if r.method == NGX_HTTP_DELETE as _ { + let key = unsafe { NgxStr::from_ngx_str(key) }; + + ngx_log_debug!( + unsafe { (*r.connection).log }, + "shared dict: delete \"{}\" w:{} p:{}", + key, + unsafe { nginx_sys::ngx_worker }, + unsafe { nginx_sys::ngx_pid }, + ); + + let _ = shared.write().remove(key); + } else { + let alloc = unsafe { SlabPool::from_shm_zone(&*smcf.shm_zone).expect("slab pool") }; + + let Ok(key) = NgxString::try_from_bytes_in(key.as_bytes(), alloc.clone()) else { + return; + }; + + let Ok(value) = NgxString::try_from_bytes_in(v.as_bytes(), alloc.clone()) else { + return; + }; + + ngx_log_debug!( + unsafe { (*r.connection).log }, + "shared dict: set \"{}\" -> \"{}\" w:{} p:{}", + key, + value, + unsafe { nginx_sys::ngx_worker }, + unsafe { nginx_sys::ngx_pid }, + ); + + let _ = shared.write().try_insert(key, value); + } +} + +extern "C" fn ngx_http_shared_dict_get_entries( + r: *mut ngx_http_request_t, + v: *mut ngx_http_variable_value_t, + _data: usize, +) -> ngx_int_t { + use core::fmt::Write; + + let r = unsafe { &mut *r }; + let v = unsafe { &mut *v }; + let pool = unsafe { Pool::from_ngx_pool(r.pool) }; + let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); + + ngx_log_debug!(unsafe { (*r.connection).log }, "shared dict: get all entries"); + + let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { + return Status::NGX_ERROR.into(); + }; + + let mut str = NgxString::new_in(pool); + { + let dict = shared.read(); + + let mut len: usize = 0; + let mut values: usize = 0; + + for (key, value) in dict.iter() { + len += key.len() + value.len() + b" = ; ".len(); + values += 1; + } + + len += values.checked_ilog10().unwrap_or(0) as usize + b"0; ".len(); + + if str.try_reserve(len).is_err() { + return Status::NGX_ERROR.into(); + } + + if write!(str, "{values}; ").is_err() { + return Status::NGX_ERROR.into(); + } + + for (key, value) in dict.iter() { + if write!(str, "{key} = {value}; ").is_err() { + return Status::NGX_ERROR.into(); + } + } + } + + // The string is allocated on the `ngx_pool_t` and will be freed with the request. + let (data, len, _, _) = str.into_raw_parts(); + + v.data = data; + v.set_len(len as _); + + v.set_valid(1); + v.set_no_cacheable(1); + v.set_not_found(0); + + Status::NGX_OK.into() +} + +extern "C" fn ngx_http_shared_dict_set_entries( + r: *mut ngx_http_request_t, + _v: *mut ngx_http_variable_value_t, + _data: usize, +) { + let r = unsafe { &mut *r }; + let smcf = HttpSharedDictModule::main_conf_mut(r).expect("shared dict main config"); + + ngx_log_debug!(unsafe { (*r.connection).log }, "shared dict: clear"); + + let Ok(shared) = ngx_http_shared_dict_get_shared(unsafe { &mut *smcf.shm_zone }) else { + return; + }; + + let Ok(tree) = RbTreeMap::try_new_in(shared.read().allocator().clone()) else { + return; + }; + + // This would check both .clear() and the drop implementation + *shared.write() = tree; + // shared.write().clear() +} diff --git a/source/rust/vendor/ngx-rust/examples/t/async.t b/source/rust/vendor/ngx-rust/examples/t/async.t new file mode 100644 index 0000000..98505fd --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/t/async.t @@ -0,0 +1,56 @@ +#!/usr/bin/perl + +# (C) Nginx, Inc + +# Tests for ngx-rust example modules. + +############################################################################### + +use warnings; +use strict; + +use Test::More; + +BEGIN { use FindBin; chdir($FindBin::Bin); } + +use lib 'lib'; +use Test::Nginx; + +############################################################################### + +select STDERR; $| = 1; +select STDOUT; $| = 1; + +my $t = Test::Nginx->new()->has(qw/http/)->plan(1) + ->write_file_expand('nginx.conf', <<'EOF'); + +%%TEST_GLOBALS%% + +daemon off; + +events { +} + +http { + %%TEST_GLOBALS_HTTP%% + + server { + listen 127.0.0.1:8080; + server_name localhost; + + location / { + async on; + } + } +} + +EOF + +$t->write_file('index.html', ''); +$t->run(); + +############################################################################### + +like(http_get('/index.html'), qr/X-Async-Time:/, 'async handler'); + +############################################################################### diff --git a/source/rust/vendor/ngx-rust/examples/t/awssig.t b/source/rust/vendor/ngx-rust/examples/t/awssig.t new file mode 100644 index 0000000..ba43cd0 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/t/awssig.t @@ -0,0 +1,73 @@ +#!/usr/bin/perl + +# (C) Nginx, Inc + +# Tests for ngx-rust example modules. + +############################################################################### + +use warnings; +use strict; + +use Test::More; + +BEGIN { use FindBin; chdir($FindBin::Bin); } + +use lib 'lib'; +use Test::Nginx; + +############################################################################### + +select STDERR; $| = 1; +select STDOUT; $| = 1; + +my $t = Test::Nginx->new()->has(qw/http proxy/)->plan(1) + ->write_file_expand('nginx.conf', <<"EOF"); + +%%TEST_GLOBALS%% + +daemon off; + +events { +} + +http { + %%TEST_GLOBALS_HTTP%% + + server { + listen 127.0.0.1:8080; + server_name localhost; + + awssigv4_access_key my-access-key; + awssigv4_secret_key my-secret-key; + awssigv4_s3_bucket my-bucket; + awssigv4_s3_endpoint s3.example.com; + + location / { + awssigv4 on; + proxy_pass http://127.0.0.1:8081; + } + } + + server { + listen 127.0.0.1:8081; + server_name localhost; + + add_header x-amz-date \$http_x_amz_date; + add_header x-authorization \$http_authorization; + + location / { } + } +} + +EOF + +$t->write_file('index.html', ''); +$t->run(); + +############################################################################### + +like(http_get('/'), qr/x-authorization: AWS4.*Credential=my-access-key/i, + 'awssig header'); + +############################################################################### diff --git a/source/rust/vendor/ngx-rust/examples/t/curl.t b/source/rust/vendor/ngx-rust/examples/t/curl.t new file mode 100644 index 0000000..dffe5a0 --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/t/curl.t @@ -0,0 +1,70 @@ +#!/usr/bin/perl + +# (C) Nginx, Inc + +# Tests for ngx-rust example modules. + +############################################################################### + +use warnings; +use strict; + +use Test::More; + +BEGIN { use FindBin; chdir($FindBin::Bin); } + +use lib 'lib'; +use Test::Nginx; + +############################################################################### + +select STDERR; $| = 1; +select STDOUT; $| = 1; + +my $t = Test::Nginx->new()->has(qw/http/)->plan(2) + ->write_file_expand('nginx.conf', <<"EOF"); + +%%TEST_GLOBALS%% + +daemon off; + +events { +} + +http { + %%TEST_GLOBALS_HTTP%% + + server { + listen 127.0.0.1:8080; + server_name localhost; + + location / { + curl on; + } + } +} + +EOF + +$t->write_file('index.html', ''); +$t->run(); + +############################################################################### + +like(get('/', 'curl/1.2.3'), qr/403 Forbidden/, 'curl UA forbidden'); +like(get('/', 'MSIE 6.0'), qr/200 OK/, 'other UA allowed'); + +############################################################################### + +sub get { + my ($url, $ua, $extra) = @_; + return http(<new()->has(qw/http rewrite/)->plan(12) + ->write_file_expand('nginx.conf', <<'EOF'); + +%%TEST_GLOBALS%% + +daemon off; + +worker_processes 2; + +events { +} + +http { + %%TEST_GLOBALS_HTTP%% + + shared_dict_zone z 64k; + shared_dict $arg_key $foo; + + server { + listen 127.0.0.1:8080; + server_name localhost; + + add_header X-Value $foo; + add_header X-Process $pid; + + location /set/ { + add_header X-Process $pid; + set $foo $arg_value; + return 200; + } + + location /entries/ { + add_header X-Process $pid; + return 200 $shared_dict_entries; + } + + location /clear/ { + add_header X-Process $pid; + set $shared_dict_entries ""; + return 200; + } + } +} + +EOF + +$t->write_file('index.html', ''); +$t->run(); + +############################################################################### + +like(http_get('/set/?key=fst&value=hello'), qr/200 OK/, 'set value 1'); +like(http_get('/set/?key=snd&value=world'), qr/200 OK/, 'set value 2'); + +ok(check('/?key=fst', qr/X-Value: hello/i), 'check value 1'); +ok(check('/?key=snd', qr/X-Value: world/i), 'check value 2'); + +like(http_get('/set/?key=fst&value=new_value'), qr/200 OK/, 'update value 1'); +ok(check('/?key=fst', qr/X-Value: new_value/i), 'check updated value'); + +like(http_get('/entries/'), qr/^2; ((?:fst = new_value|snd = world); ){2}$/ms, + 'get entries'); + +like(http_delete('/set/?key=snd'), qr/200 OK/, 'delete value 2'); + +unlike(http_get('/?key=snd'), qr/X-Value:/i, 'check deleted value'); + +like(http_get('/entries/'), qr/^1; fst = new_value; $/ms, + 'get entries - deleted'); + +like(http_get('/clear/'), qr/200 OK/, 'clear'); + +like(http_get('/entries/'), qr/^0; $/ms, 'get entries - clear'); + +############################################################################### + +sub check { + my ($uri, $like) = @_; + + my $r = http_get($uri); + + return unless ($r =~ $like && $r =~ /X-Process: (\d+)/); + + return 1 if $^O eq 'MSWin32'; # only one active worker process + + my $pid = $1; + + for (1 .. 25) { + $r = http_get($uri); + + return unless ($r =~ $like && $r =~ /X-Process: (\d+)/); + return 1 if $pid != $1; + } +} + +sub http_delete { + my ($url, %extra) = @_; + return http(<new()->has(qw/http proxy/)->plan(2) + ->write_file_expand('nginx.conf', <<"EOF"); + +%%TEST_GLOBALS%% + +daemon off; + +events { +} + +http { + %%TEST_GLOBALS_HTTP%% + + upstream u { + server 127.0.0.1:8081; + custom 32; + } + + server { + listen 127.0.0.1:8080; + server_name localhost; + + error_log %%TESTDIR%%/e_debug.log debug; + + location / { + proxy_pass http://u; + } + } + + server { + listen 127.0.0.1:8081; + server_name localhost; + + location / { } + } +} + +EOF + +$t->write_file('index.html', ''); +$t->run(); + +############################################################################### + +like(http_get('/'), qr/200 OK/, 'custom upstream'); + +$t->stop(); + +SKIP: { + skip "no --with-debug", 1 unless $t->has_module('--with-debug'); + + like($t->read_file('e_debug.log'), qr/CUSTOM UPSTREAM request/, + 'log - custom upstream'); +} + +############################################################################### diff --git a/source/rust/vendor/ngx-rust/examples/upstream.conf b/source/rust/vendor/ngx-rust/examples/upstream.conf new file mode 100644 index 0000000..5a56b0d --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/upstream.conf @@ -0,0 +1,24 @@ +# example configuration block to test upstream.rs +http { + upstream backend { + server localhost:15501; + custom 32; + } + + server { + listen 15500; + server_name _; + + location / { + proxy_pass http://backend; + } + } + + server { + listen 15501; + + location / { + return 418; + } + } +} diff --git a/source/rust/vendor/ngx-rust/examples/upstream.rs b/source/rust/vendor/ngx-rust/examples/upstream.rs new file mode 100644 index 0000000..544ca1b --- /dev/null +++ b/source/rust/vendor/ngx-rust/examples/upstream.rs @@ -0,0 +1,331 @@ +/* + * This example is based on: + * https://github.com/gabihodoroaga/nginx-upstream-module + * as well as the NGINX keepalive module: ngx_http_upstream_keepalive_module.c. + * + * The NGINX authors are grateful to @gabihodoroaga for their contributions + * to the community at large. + */ +use core::ffi::{c_char, c_void}; +use core::mem; +use core::ptr; + +use ngx::core::{Pool, Status}; +use ngx::ffi::{ + NGX_CONF_NOARGS, NGX_CONF_TAKE1, NGX_CONF_UNSET, NGX_ERROR, NGX_HTTP_MODULE, + NGX_HTTP_SRV_CONF_OFFSET, NGX_HTTP_UPS_CONF, NGX_LOG_EMERG, ngx_atoi, ngx_command_t, + ngx_conf_t, ngx_connection_t, ngx_event_free_peer_pt, ngx_event_get_peer_pt, ngx_http_module_t, + ngx_http_upstream_init_peer_pt, ngx_http_upstream_init_pt, ngx_http_upstream_init_round_robin, + ngx_http_upstream_srv_conf_t, ngx_http_upstream_t, ngx_int_t, ngx_module_t, + ngx_peer_connection_t, ngx_str_t, ngx_uint_t, +}; +use ngx::http::{HttpModule, Merge, MergeConfigError, Request}; +use ngx::http::{HttpModuleServerConf, NgxHttpUpstreamModule}; +use ngx::{ + http_upstream_init_peer_pt, ngx_conf_log_error, ngx_log_debug_http, ngx_log_debug_mask, + ngx_string, +}; + +#[derive(Clone, Copy, Debug)] +#[repr(C)] +struct SrvConfig { + max: u32, + + original_init_upstream: ngx_http_upstream_init_pt, + original_init_peer: ngx_http_upstream_init_peer_pt, +} + +impl Default for SrvConfig { + fn default() -> Self { + SrvConfig { max: u32::MAX, original_init_upstream: None, original_init_peer: None } + } +} + +impl Merge for SrvConfig { + fn merge(&mut self, _prev: &SrvConfig) -> Result<(), MergeConfigError> { + Ok(()) + } +} + +#[derive(Clone, Copy, Debug)] +#[repr(C)] +struct UpstreamPeerData { + conf: Option<*const SrvConfig>, + upstream: Option<*mut ngx_http_upstream_t>, + client_connection: Option<*mut ngx_connection_t>, + original_get_peer: ngx_event_get_peer_pt, + original_free_peer: ngx_event_free_peer_pt, + data: *mut c_void, +} + +impl Default for UpstreamPeerData { + fn default() -> Self { + UpstreamPeerData { + conf: None, + upstream: None, + client_connection: None, + original_get_peer: None, + original_free_peer: None, + data: ptr::null_mut(), + } + } +} + +static NGX_HTTP_UPSTREAM_CUSTOM_CTX: ngx_http_module_t = ngx_http_module_t { + preconfiguration: Some(Module::preconfiguration), + postconfiguration: Some(Module::postconfiguration), + create_main_conf: None, + init_main_conf: None, + create_srv_conf: Some(Module::create_srv_conf), + merge_srv_conf: Some(Module::merge_srv_conf), + create_loc_conf: None, + merge_loc_conf: None, +}; + +static mut NGX_HTTP_UPSTREAM_CUSTOM_COMMANDS: [ngx_command_t; 2] = [ + ngx_command_t { + name: ngx_string!("custom"), + type_: (NGX_HTTP_UPS_CONF | NGX_CONF_NOARGS | NGX_CONF_TAKE1) as ngx_uint_t, + set: Some(ngx_http_upstream_commands_set_custom), + conf: NGX_HTTP_SRV_CONF_OFFSET, + offset: 0, + post: ptr::null_mut(), + }, + ngx_command_t::empty(), +]; + +// Generate the `ngx_modules` table with exported modules. +// This feature is required to build a 'cdylib' dynamic module outside of the NGINX buildsystem. +#[cfg(feature = "export-modules")] +ngx::ngx_modules!(ngx_http_upstream_custom_module); + +#[used] +#[allow(non_upper_case_globals)] +#[cfg_attr(not(feature = "export-modules"), unsafe(no_mangle))] +pub static mut ngx_http_upstream_custom_module: ngx_module_t = ngx_module_t { + ctx: &raw const NGX_HTTP_UPSTREAM_CUSTOM_CTX as _, + commands: unsafe { &raw mut NGX_HTTP_UPSTREAM_CUSTOM_COMMANDS[0] }, + type_: NGX_HTTP_MODULE as _, + ..ngx_module_t::default() +}; + +// http_upstream_init_custom_peer +// The module's custom peer.init callback. On HTTP request the peer upstream get and free callbacks +// are saved into peer data and replaced with this module's custom callbacks. +http_upstream_init_peer_pt!( + http_upstream_init_custom_peer, + |request: &mut Request, us: *mut ngx_http_upstream_srv_conf_t| { + ngx_log_debug_http!(request, "CUSTOM UPSTREAM request peer init"); + + let hcpd = request.pool().alloc_type::(); + if hcpd.is_null() { + return Status::NGX_ERROR; + } + + // SAFETY: this function is called with non-NULL uf always + let us = unsafe { &mut *us }; + let hccf = match Module::server_conf(us) { + Some(x) => x, + None => return Status::NGX_ERROR, + }; + + let original_init_peer = hccf.original_init_peer.unwrap(); + if unsafe { original_init_peer(request.into(), us) != Status::NGX_OK.into() } { + return Status::NGX_ERROR; + } + + let maybe_upstream = request.upstream(); + if maybe_upstream.is_none() { + return Status::NGX_ERROR; + } + let upstream_ptr = maybe_upstream.unwrap(); + + unsafe { + (*hcpd).conf = Some(hccf); + (*hcpd).upstream = maybe_upstream; + (*hcpd).data = (*upstream_ptr).peer.data; + (*hcpd).client_connection = Some(request.connection()); + (*hcpd).original_get_peer = (*upstream_ptr).peer.get; + (*hcpd).original_free_peer = (*upstream_ptr).peer.free; + + (*upstream_ptr).peer.data = hcpd as *mut c_void; + (*upstream_ptr).peer.get = Some(ngx_http_upstream_get_custom_peer); + (*upstream_ptr).peer.free = Some(ngx_http_upstream_free_custom_peer); + } + + ngx_log_debug_http!(request, "CUSTOM UPSTREAM end request peer init"); + Status::NGX_OK + } +); + +// ngx_http_usptream_get_custom_peer +// For demonstration purposes, use the original get callback, but log this callback proxies through +// to the original. +unsafe extern "C" fn ngx_http_upstream_get_custom_peer( + pc: *mut ngx_peer_connection_t, + data: *mut c_void, +) -> ngx_int_t { + let hcpd: *mut UpstreamPeerData = unsafe { mem::transmute(data) }; + + ngx_log_debug_mask!( + DebugMask::Http, + unsafe { (*pc).log }, + "CUSTOM UPSTREAM get peer, try: {}, conn: {:p}", + unsafe { (*pc).tries }, + unsafe { (*hcpd).client_connection.unwrap() }, + ); + + let original_get_peer = unsafe { (*hcpd).original_get_peer.unwrap() }; + let rc = unsafe { original_get_peer(pc, (*hcpd).data) }; + + if rc != Status::NGX_OK.into() { + return rc; + } + + ngx_log_debug_mask!(DebugMask::Http, unsafe { (*pc).log }, "CUSTOM UPSTREAM end get peer"); + Status::NGX_OK.into() +} + +// ngx_http_upstream_free_custom_peer +// For demonstration purposes, use the original free callback, but log this callback proxies +// through to the original. +unsafe extern "C" fn ngx_http_upstream_free_custom_peer( + pc: *mut ngx_peer_connection_t, + data: *mut c_void, + state: ngx_uint_t, +) { + ngx_log_debug_mask!(DebugMask::Http, unsafe { (*pc).log }, "CUSTOM UPSTREAM free peer"); + + let hcpd: *mut UpstreamPeerData = unsafe { mem::transmute(data) }; + + let original_free_peer = unsafe { (*hcpd).original_free_peer.unwrap() }; + + unsafe { original_free_peer(pc, (*hcpd).data, state) }; + + ngx_log_debug_mask!(DebugMask::Http, unsafe { (*pc).log }, "CUSTOM UPSTREAM end free peer"); +} + +// ngx_http_upstream_init_custom +// The module's custom `peer.init_upstream` callback. +// The original callback is saved in our SrvConfig data and reset to this module's `peer.init`. +unsafe extern "C" fn ngx_http_upstream_init_custom( + cf: *mut ngx_conf_t, + us: *mut ngx_http_upstream_srv_conf_t, +) -> ngx_int_t { + ngx_log_debug_mask!( + DebugMask::Http, + unsafe { (*cf).log }, + "CUSTOM UPSTREAM peer init_upstream" + ); + + // SAFETY: this function is called with non-NULL uf always + let us = unsafe { &mut *us }; + let hccf = Module::server_conf_mut(us); + if hccf.is_none() { + ngx_conf_log_error!(NGX_LOG_EMERG, cf, "CUSTOM UPSTREAM no upstream srv_conf"); + return isize::from(Status::NGX_ERROR); + } + let hccf = hccf.unwrap(); + // NOTE: ngx_conf_init_uint_value macro is unavailable + if hccf.max == u32::MAX { + hccf.max = 100; + } + + let init_upstream_ptr = hccf.original_init_upstream.unwrap(); + if unsafe { init_upstream_ptr(cf, us) } != Status::NGX_OK.into() { + ngx_conf_log_error!(NGX_LOG_EMERG, cf, "CUSTOM UPSTREAM failed calling init_upstream"); + return isize::from(Status::NGX_ERROR); + } + + hccf.original_init_peer = us.peer.init; + us.peer.init = Some(http_upstream_init_custom_peer); + + ngx_log_debug_mask!( + DebugMask::Http, + unsafe { (*cf).log }, + "CUSTOM UPSTREAM end peer init_upstream" + ); + isize::from(Status::NGX_OK) +} + +// ngx_http_upstream_commands_set_custom +// Entry point for the module, if this command is set our custom upstreams take effect. +// The original upstream initializer function is saved and replaced with this module's initializer. +unsafe extern "C" fn ngx_http_upstream_commands_set_custom( + cf: *mut ngx_conf_t, + cmd: *mut ngx_command_t, + conf: *mut c_void, +) -> *mut c_char { + // SAFETY: this function is called with non-NULL cf always + let cf = unsafe { &mut *cf }; + ngx_log_debug_mask!(DebugMask::Http, cf.log, "CUSTOM UPSTREAM module init"); + let args: &[ngx_str_t] = unsafe { (*cf.args).as_slice() }; + + let ccf = unsafe { &mut (*(conf as *mut SrvConfig)) }; + + if let Some(value) = args.get(1) { + let n = unsafe { ngx_atoi(value.data, value.len) }; + if n == (NGX_ERROR as isize) || n == 0 { + ngx_conf_log_error!( + NGX_LOG_EMERG, + cf, + "invalid value \"{}\" in \"{}\" directive", + value, + unsafe { &(*cmd).name } + ); + return ngx::core::NGX_CONF_ERROR; + } + ccf.max = n as u32; + } + + let uscf = NgxHttpUpstreamModule::server_conf_mut(cf).expect("http upstream srv conf"); + + ccf.original_init_upstream = if uscf.peer.init_upstream.is_some() { + uscf.peer.init_upstream + } else { + Some(ngx_http_upstream_init_round_robin) + }; + + uscf.peer.init_upstream = Some(ngx_http_upstream_init_custom); + + ngx_log_debug_mask!(DebugMask::Http, cf.log, "CUSTOM UPSTREAM end module init"); + + ngx::core::NGX_CONF_OK +} + +// The upstream module. +// Only server blocks are supported to trigger the module command; therefore, the only callback +// implemented is our `create_srv_conf` method. +struct Module; + +impl HttpModule for Module { + fn module() -> &'static ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_upstream_custom_module) } + } + + unsafe extern "C" fn create_srv_conf(cf: *mut ngx_conf_t) -> *mut c_void { + let pool = unsafe { Pool::from_ngx_pool((*cf).pool) }; + let conf = pool.alloc_type::(); + if conf.is_null() { + ngx_conf_log_error!( + NGX_LOG_EMERG, + cf, + "CUSTOM UPSTREAM could not allocate memory for config" + ); + return ptr::null_mut(); + } + + unsafe { (*conf).max = NGX_CONF_UNSET as u32 }; + + ngx_log_debug_mask!( + DebugMask::Http, + unsafe { (*cf).log }, + "CUSTOM UPSTREAM end create_srv_conf" + ); + conf as *mut c_void + } +} + +unsafe impl HttpModuleServerConf for Module { + type ServerConf = SrvConfig; +} diff --git a/source/rust/vendor/ngx-rust/misc/lsan-suppressions.txt b/source/rust/vendor/ngx-rust/misc/lsan-suppressions.txt new file mode 100644 index 0000000..4731e9b --- /dev/null +++ b/source/rust/vendor/ngx-rust/misc/lsan-suppressions.txt @@ -0,0 +1,17 @@ +# LeakSanitizer suppressions list for nginx +# +# To be used with -fsanitize=address and +# LSAN_OPTIONS=suppressions=lsan-suppressions.txt. +# +# https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer#suppressions + +# cycle->connections, cycle->read_events, cycle->write_events +leak:ngx_event_process_init + +# XXX: can silence leaks from nginx SSL callbacks +leak:SSL_do_handshake +leak:SSL_read + +# rcf->ranges not freed at process exit +leak:ngx_http_upstream_update_random +leak:ngx_stream_upstream_update_random diff --git a/source/rust/vendor/ngx-rust/misc/nginx-sanitizer-support.patch b/source/rust/vendor/ngx-rust/misc/nginx-sanitizer-support.patch new file mode 100644 index 0000000..02ba70d --- /dev/null +++ b/source/rust/vendor/ngx-rust/misc/nginx-sanitizer-support.patch @@ -0,0 +1,28 @@ +diff --git a/src/core/ngx_string.h b/src/core/ngx_string.h +index 713eb42a7..999c6b25f 100644 +--- a/src/core/ngx_string.h ++++ b/src/core/ngx_string.h +@@ -96,6 +96,23 @@ void ngx_explicit_memzero(void *buf, size_t n); + void *ngx_memcpy(void *dst, const void *src, size_t n); + #define ngx_cpymem(dst, src, n) (((u_char *) ngx_memcpy(dst, src, n)) + (n)) + ++#elif (NGX_SUPPRESS_WARN) ++ ++/* ++ * Checked versions for sanitizers. ++ * See https://mailman.nginx.org/pipermail/nginx-devel/2023-December/7VNQZEBNXEKAYTYE4Y65FORF4HNELM6V.html ++ */ ++ ++static ngx_inline void * ++ngx_memcpy(void *dst, const void *src, size_t n) { ++ return (n == 0) ? dst : memcpy(dst, src, n); ++} ++ ++static ngx_inline void * ++ngx_cpymem(void *dst, const void *src, size_t n) { ++ return (n == 0) ? dst : ((u_char *) memcpy(dst, src, n)) + n; ++} ++ + #else + + /* diff --git a/source/rust/vendor/ngx-rust/misc/ubsan-suppressions.txt b/source/rust/vendor/ngx-rust/misc/ubsan-suppressions.txt new file mode 100644 index 0000000..5da588f --- /dev/null +++ b/source/rust/vendor/ngx-rust/misc/ubsan-suppressions.txt @@ -0,0 +1,28 @@ +# UndefinedBehaviorSanitizer suppressions list for nginx +# +# To be used with -fsanitize=undefined and +# UBSAN_OPTIONS=suppressions=ubsan-suppressions.txt. +# +# https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#runtime-suppressions + +# src/http/v2/ngx_http_v2.c:2747:17: runtime error: store to misaligned address 0x7b35a1a19885 for type 'uint32_t' (aka 'unsigned int'), which requires 4 byte alignment +alignment:src/http/v2/ngx_http_v2.c +alignment:src/http/v2/ngx_http_v2_filter_module.c +alignment:ngx_http_huff_encode +alignment:ngx_http_parse_request_line + +# ngx_quic_write_uint32 at src/event/quic/ngx_event_quic_transport.c:642 +alignment:ngx_quic_create_long_header +alignment:ngx_quic_read_uint32 + +# src/core/ngx_output_chain.c:70:20: runtime error: call to function ngx_http_trailers_filter through pointer to incorrect function type 'long (*)(void *, struct ngx_chain_s *)' +# src/http/modules/ngx_http_headers_filter_module.c:249: note: ngx_http_trailers_filter defined here +function:ngx_output_chain + +# violates nonnull on memcmp +nonnull-attribute:ngx_http_upstream_zone_preresolve +nonnull-attribute:ngx_stream_upstream_zone_preresolve + +# src/http/ngx_http_script.c:800:16: runtime error: applying non-zero offset 112 to null pointer +pointer-overflow:ngx_http_script_add_code +pointer-overflow:ngx_stream_script_add_code diff --git a/source/rust/vendor/ngx-rust/misc/update-action-sha.sh b/source/rust/vendor/ngx-rust/misc/update-action-sha.sh new file mode 100755 index 0000000..30e8390 --- /dev/null +++ b/source/rust/vendor/ngx-rust/misc/update-action-sha.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +set -ex + +if [ $# -lt 2 ]; then + grep "uses:[[:space:]]*$1" .github/workflows/*.yaml + exit +fi + +sed -e "s|\\(uses:[[:space:]]*$1@\\).*|\\1$2|" -i .github/workflows/*.yaml diff --git a/source/rust/vendor/ngx-rust/nginx-src/Cargo.toml b/source/rust/vendor/ngx-rust/nginx-src/Cargo.toml new file mode 100644 index 0000000..0db238e --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-src/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "nginx-src" +# Version format: ..+ +version = "1.30.0+1.30.4" +# Crate sources are licensed under Apache-2.0, with exception of the +# NGINX submodule that is redistributed under BSD-2-Clause. +license = "Apache-2.0 AND BSD-2-Clause" +description = "Source of NGINX" +keywords = ["nginx", "module", "sys"] +exclude = [ + "/nginx/.git*", + "/nginx/contrib", + "/nginx/docs", + "/nginx/misc", + "!/nginx/docs/html", + "!/nginx/docs/man", +] +edition.workspace = true +homepage.workspace = true +repository.workspace = true +rust-version.workspace = true + +[dependencies] +duct = "1" +flate2 = "1.0.32" +tar = "0.4.45" +ureq = "3.2" + +[lints] +workspace = true diff --git a/source/rust/vendor/ngx-rust/nginx-src/LICENSE b/source/rust/vendor/ngx-rust/nginx-src/LICENSE new file mode 120000 index 0000000..ea5b606 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-src/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/nginx-src/README.md b/source/rust/vendor/ngx-rust/nginx-src/README.md new file mode 100644 index 0000000..334a44d --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-src/README.md @@ -0,0 +1,82 @@ +# nginx-src + +The crate contains a vendored copy of the NGINX source and a logic to build it. +It is intended to be consumed by the [nginx-sys] crate for CI builds, tests or +rustdoc generation. + +It is notably not intended for producing binaries suitable for production use. +For such scenarios we recommend building the `ngx-rust` based module against +the packages from or your preferred distribution. +See the [nginx-sys] documentation for building `ngx-rust` modules against an +existing pre-configured NGINX source tree. + +[nginx-sys]: https://docs.rs/nginx-sys/ + +## Versioning + +This crate follows the latest stable branch of NGINX. + + * The major and minor fields are taken from the NGINX version. + * The patch version is incremented on changes to the build logic or crate + metadata. + * The version metadata contains full version of NGINX. + +## Build Requirements + +The crate can be built on common Unix-like operating systems and requires all +the usual NGINX build dependencies (including development headers for the +libraries) installed in system paths: + + * C compiler and toolchain + * SSL library, OpenSSL or LibreSSL + * PCRE or PCRE2 + * Zlib or zlib-ng witn Zlib compatible API enabled + +We don't intend to support Windows at the moment, as NGINX does not support +dynamic modules for this target. + +## Environment variables + +Following variables can be set to customize the build. + + * `NGX_CONFIGURE_ARGS` — additional arguments to pass to the NGINX configure + script. + + Example: `export NGX_CONFIGURE_ARGS='--with-debug'; cargo build` + + * `NGX_CFLAGS`, `NGX_LDFLAGS` — additional C compiler and linker flags to + pass to the NGINX configure script. Internally, this is added to the + `--with-cc-opt=...` and `--with-ld-opt=...` configure arguments. + + Example: + ```sh + export NGX_CFLAGS='-I/opt/boringssl/include' + export NGX_LDFLAGS='-L/opt/boringssl/build -lstdc++' + cargo build + ``` + +## Download NGINX and dependency sources during build + +While we recommend using the system libraries, it is still possible to opt into +downloading the NGINX itself and the dependency sources from the network with +the help of the following variables: + + * `NGX_VERSION` — if specified, the version of NGINX to download and build + instead of the one bundled with the crate. + * `OPENSSL_VERSION` — if specified, the version of OpenSSL to download and use + use instead of the system-provided library. + * `PCRE2_VERSION` — if specified, the version of PCRE2 to download and use + instead of the system-provided library. + * `ZLIB_VERSION` — if specified, the version of Zlib to download and use + instead of the system-provided library. + +If the `gpg` executable is present in the path, the build script will verify +the integrity of the downloaded files using GPG signatures and a known set of +public keys. +This behavior can be disabled by setting `NGX_NO_SIGNATURE_CHECK`. + +## License + +The code in this crate is licensed under the [Apache License 2.0](../LICENSE). +The crate also contains the source code of NGINX, distributed under the +[BSD 2-Clause License](https://nginx.org/LICENSE). diff --git a/source/rust/vendor/ngx-rust/nginx-src/src/download.rs b/source/rust/vendor/ngx-rust/nginx-src/src/download.rs new file mode 100644 index 0000000..c64ca6c --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-src/src/download.rs @@ -0,0 +1,252 @@ +extern crate duct; + +use core::error::Error as StdError; +use std::fs::File; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; +use std::{env, fs}; + +use flate2::read::GzDecoder; +use tar::Archive; + +use crate::verifier::SignatureVerifier; + +const NGINX_URL_PREFIX: &str = "https://nginx.org/download"; +const OPENSSL_URL_PREFIX: &str = "https://github.com/openssl/openssl/releases/download"; +const PCRE1_URL_PREFIX: &str = "https://sourceforge.net/projects/pcre/files/pcre"; +const PCRE2_URL_PREFIX: &str = "https://github.com/PCRE2Project/pcre2/releases/download"; +const ZLIB_URL_PREFIX: &str = "https://github.com/madler/zlib/releases/download"; +const UBUNTU_KEYSEVER: &str = "hkps://keyserver.ubuntu.com"; + +struct SourceSpec<'a> { + url: fn(&str) -> String, + variable: &'a str, + signature: &'a str, + keyserver: &'a str, + key_ids: &'a [&'a str], +} + +const NGINX_SOURCE: SourceSpec = SourceSpec { + url: |version| format!("{NGINX_URL_PREFIX}/nginx-{version}.tar.gz"), + variable: "NGX_VERSION", + signature: "asc", + keyserver: UBUNTU_KEYSEVER, + key_ids: &[ + // Key 1: Konstantin Pavlov's public key. For Nginx 1.25.3 and earlier + "13C82A63B603576156E30A4EA0EA981B66B0D967", + // Key 2: Sergey Kandaurov's public key. For Nginx 1.25.4 + "D6786CE303D9A9022998DC6CC8464D549AF75C0A", + // Key 3: Maxim Dounin's public key. At least used for Nginx 1.18.0 + "B0F4253373F8F6F510D42178520A9993A1C052F8", + // Key 4: Roman Arutyunyan's public key. For Nginx 1.25.5 + "43387825DDB1BB97EC36BA5D007C8D7C15D87369", + ], +}; + +const DEPENDENCIES: &[(&str, SourceSpec)] = &[ + ( + "openssl", + SourceSpec { + url: |version| { + if version.starts_with("1.") { + let ver_hyphened = version.replace('.', "_"); + format!("{OPENSSL_URL_PREFIX}/OpenSSL_{ver_hyphened}/openssl-{version}.tar.gz") + } else { + format!("{OPENSSL_URL_PREFIX}/openssl-{version}/openssl-{version}.tar.gz") + } + }, + variable: "OPENSSL_VERSION", + signature: "asc", + keyserver: UBUNTU_KEYSEVER, + key_ids: &[ + "EFC0A467D613CB83C7ED6D30D894E2CE8B3D79F5", + "A21FAB74B0088AA361152586B8EF1A6BA9DA2D5C", + "8657ABB260F056B1E5190839D9C4D26D0E604491", + "B7C1C14360F353A36862E4D5231C84CDDCC69C45", + "95A9908DDFA16830BE9FB9003D30A3A9FF1360DC", + "7953AC1FBC3DC8B3B292393ED5E9E43F7DF9EE8C", + "E5E52560DD91C556DDBDA5D02064C53641C25E5D", + "C1F33DD8CE1D4CC613AF14DA9195C48241FBF7DD", + "BA5473A2B0587B07FB27CF2D216094DFD0CB81EF", + ], + }, + ), + ( + "pcre", + SourceSpec { + url: |version| { + // We can distinguish pcre1/pcre2 by checking whether the second character is '.', + // because the final version of pcre1 is 8.45 and the first one of pcre2 is 10.00. + if version.chars().nth(1).is_some_and(|c| c == '.') { + format!("{PCRE1_URL_PREFIX}/{version}/pcre-{version}.tar.gz") + } else { + format!("{PCRE2_URL_PREFIX}/pcre2-{version}/pcre2-{version}.tar.gz") + } + }, + variable: "PCRE2_VERSION", + signature: "sig", + keyserver: UBUNTU_KEYSEVER, + key_ids: &[ + // Key 1: Phillip Hazel's public key. For PCRE2 10.44 and earlier + "45F68D54BBE23FB3039B46E59766E084FB0F43D8", + // Key 2: Nicholas Wilson's public key. For PCRE2 10.45 + "A95536204A3BB489715231282A98E77EB6F24CA8", + ], + }, + ), + ( + "zlib", + SourceSpec { + url: |version| format!("{ZLIB_URL_PREFIX}/v{version}/zlib-{version}.tar.gz"), + variable: "ZLIB_VERSION", + signature: "asc", + keyserver: UBUNTU_KEYSEVER, + key_ids: &[ + // Key 1: Mark Adler's public key. For zlib 1.3.1 and earlier + "5ED46A6721D365587791E2AA783FCD8E58BCAFBA", + ], + }, + ), +]; + +static VERIFIER: LazyLock> = LazyLock::new(|| { + SignatureVerifier::new().inspect_err(|err| eprintln!("GnuPG verifier: {err}")).ok() +}); + +static CACHE_DIR: LazyLock = LazyLock::new(|| { + let base_dir = env::var("OUT_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| env::current_dir().expect("Failed to get current directory")); + // Choose `.cache` relative to the OUT_DIR of the caller (nginx-sys) as the default cache + // directory. Environment variable `CACHE_DIR` overrides this. + // Recommendation: set env "CACHE_DIR = { value = ".cache", relative = true }" in + // `.cargo/config.toml` in your project + let cache_dir = env::var("CACHE_DIR").map(PathBuf::from).unwrap_or(base_dir.join(".cache")); + + if !cache_dir.exists() { + fs::create_dir_all(&cache_dir) + .map_err(|err| format!("Failed to create {cache_dir:?}: {err}")) + .unwrap(); + } + + cache_dir +}); + +/// Downloads a tarball from the specified URL into the `.cache` directory. +fn download(cache_dir: &Path, url: &str) -> Result> { + fn proceed_with_download(file_path: &Path) -> bool { + // File does not exist or is zero bytes + !file_path.exists() || file_path.metadata().is_ok_and(|m| m.len() < 1) + } + let filename = url.split('/').next_back().unwrap(); + let file_path = cache_dir.join(filename); + if proceed_with_download(&file_path) { + println!("Downloading: {} -> {}", url, file_path.display()); + let mut response = ureq::get(url).call()?; + let mut reader = response.body_mut().as_reader(); + let mut file = File::create(&file_path)?; + std::io::copy(&mut reader, &mut file)?; + } + + if !file_path.exists() { + return Err( + format!("Downloaded file was not written to the expected location: {url}",).into() + ); + } + Ok(file_path) +} + +/// Gets a given tarball and signature file from a remote URL and copies it to the `.cache` +/// directory. +fn get_archive(cache_dir: &Path, source: &SourceSpec, version: &str) -> io::Result { + let archive_url = (source.url)(version); + let archive = download(cache_dir, &archive_url).map_err(io::Error::other)?; + + if let Some(verifier) = &*VERIFIER { + let signature = format!("{archive_url}.{}", source.signature); + + let verify = || -> io::Result<()> { + let signature = download(cache_dir, &signature).map_err(io::Error::other)?; + verifier.import_keys(source.keyserver, source.key_ids)?; + verifier.verify_signature(&archive, &signature)?; + Ok(()) + }; + + if let Err(err) = verify() { + let _ = fs::remove_file(&archive); + let _ = fs::remove_file(&signature); + return Err(err); + } + } + + Ok(archive) +} + +/// Extracts a tarball into a subdirectory based on the tarball's name under the source base +/// directory. +fn extract_archive(archive_path: &Path, extract_output_base_dir: &Path) -> io::Result { + if !extract_output_base_dir.exists() { + fs::create_dir_all(extract_output_base_dir)?; + } + let archive_file = File::open(archive_path) + .unwrap_or_else(|_| panic!("Unable to open archive file: {}", archive_path.display())); + let stem = archive_path + .file_name() + .and_then(|s| s.to_str()) + .and_then(|s| s.rsplitn(3, '.').last()) + .expect("Unable to determine archive file name stem"); + + let extract_output_dir = extract_output_base_dir.to_owned(); + let archive_output_dir = extract_output_dir.join(stem); + if !archive_output_dir.exists() { + Archive::new(GzDecoder::new(archive_file)).entries()?.filter_map(|e| e.ok()).for_each( + |mut entry| { + let path = entry.path().unwrap(); + let stripped_path = path.components().skip(1).collect::(); + entry.unpack(archive_output_dir.join(stripped_path)).unwrap(); + }, + ); + } else { + println!( + "Archive [{}] already extracted to directory: {}", + stem, + archive_output_dir.display() + ); + } + + Ok(archive_output_dir) +} + +/// Downloads and extracts all requested sources. +pub fn prepare(source_dir: &Path, build_dir: &Path) -> io::Result<(PathBuf, Vec)> { + let extract_output_base_dir = build_dir.join("lib"); + if !extract_output_base_dir.exists() { + fs::create_dir_all(&extract_output_base_dir)?; + } + + let mut options = vec![]; + + // Download NGINX only if NGX_VERSION is set. + let source_dir = if let Ok(version) = env::var(NGINX_SOURCE.variable) { + let archive_path = get_archive(&CACHE_DIR, &NGINX_SOURCE, version.as_str())?; + let output_base_dir: PathBuf = env::var("OUT_DIR").unwrap().into(); + extract_archive(&archive_path, &output_base_dir)? + } else { + source_dir.to_path_buf() + }; + + for (name, source) in DEPENDENCIES { + // Download dependencies if a corresponding DEPENDENCY_VERSION is set. + let Ok(requested) = env::var(source.variable) else { + continue; + }; + + let archive_path = get_archive(&CACHE_DIR, source, &requested)?; + let output_dir = extract_archive(&archive_path, &extract_output_base_dir)?; + let output_dir = output_dir.to_string_lossy(); + options.push(format!("--with-{name}={output_dir}")); + } + + Ok((source_dir, options)) +} diff --git a/source/rust/vendor/ngx-rust/nginx-src/src/lib.rs b/source/rust/vendor/ngx-rust/nginx-src/src/lib.rs new file mode 100644 index 0000000..52a4e60 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-src/src/lib.rs @@ -0,0 +1,214 @@ +#![doc = include_str!("../README.md")] +#![warn(missing_docs)] + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; +use std::process::Output; +use std::{env, io, thread}; + +mod download; +mod verifier; + +static NGINX_DEFAULT_SOURCE_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/nginx"); + +const NGINX_BUILD_INFO: &str = "last-build-info"; +const NGINX_BINARY: &str = "nginx"; + +static NGINX_CONFIGURE_BASE: &[&str] = &[ + "--with-compat", + "--with-http_realip_module", + "--with-http_ssl_module", + "--with-http_v2_module", + "--with-mail", + "--with-mail_ssl_module", + "--with-stream", + "--with-stream_realip_module", + "--with-stream_ssl_module", + "--with-threads", +]; + +const ENV_VARS_TRIGGERING_RECOMPILE: [&str; 10] = [ + "CACHE_DIR", + "CARGO_MANIFEST_DIR", + "CARGO_TARGET_TMPDIR", + "NGX_CONFIGURE_ARGS", + "NGX_CFLAGS", + "NGX_LDFLAGS", + "NGX_VERSION", + "OPENSSL_VERSION", + "PCRE2_VERSION", + "ZLIB_VERSION", +]; + +/* +########################################################################### +# NGINX Build Functions - Everything below here is for building NGINX # +########################################################################### + +In order to build Rust bindings for NGINX using the bindgen crate, we need +to do the following: + + 1. Obtain a copy of the NGINX source code and the necessary dependencies: + OpenSSL, PCRE2, Zlib. + 3. Run autoconf `configure` for NGINX. + 4. Compile NGINX. + 5. Read the autoconf generated makefile for NGINX and configure bindgen + to generate Rust bindings based on the includes in the makefile. +*/ + +/// Outputs cargo instructions required for using this crate from a buildscript. +pub fn print_cargo_metadata() { + for file in ["lib.rs", "download.rs", "verifier.rs"] { + println!("cargo::rerun-if-changed={path}/src/{file}", path = env!("CARGO_MANIFEST_DIR")) + } + + for var in ENV_VARS_TRIGGERING_RECOMPILE { + println!("cargo::rerun-if-env-changed={var}"); + } +} + +/// Builds a copy of NGINX sources, either bundled with the crate or downloaded from the network. +pub fn build(build_dir: impl AsRef) -> io::Result<(PathBuf, PathBuf)> { + let source_dir = PathBuf::from(NGINX_DEFAULT_SOURCE_DIR); + let build_dir = build_dir.as_ref().to_owned(); + + let (source_dir, vendored_flags) = download::prepare(&source_dir, &build_dir)?; + + let flags = nginx_configure_flags(&vendored_flags); + + configure(&source_dir, &build_dir, &flags)?; + + make(&source_dir, &build_dir, ["build"])?; + + Ok((source_dir, build_dir)) +} + +/// Returns the options NGINX was built with +fn build_info(source_dir: &Path, configure_flags: &[String]) -> String { + // Flags should contain strings pointing to OS/platform as well as dependency versions, + // so if any of that changes, it can trigger a rebuild + format!("{:?}|{}", source_dir, configure_flags.join(" ")) +} + +/// Generate the flags to use with autoconf `configure` for NGINX. +fn nginx_configure_flags(vendored: &[String]) -> Vec { + let mut nginx_opts: Vec = + NGINX_CONFIGURE_BASE.iter().map(|x| String::from(*x)).collect(); + + nginx_opts.extend(vendored.iter().map(Into::into)); + + if let Ok(extra_args) = env::var("NGX_CONFIGURE_ARGS") { + // FIXME: shell style split? + nginx_opts.extend(extra_args.split_whitespace().map(Into::into)); + } + + if let Ok(cflags) = env::var("NGX_CFLAGS") { + nginx_opts.push(format!("--with-cc-opt={cflags}")); + } + + if let Ok(ldflags) = env::var("NGX_LDFLAGS") { + nginx_opts.push(format!("--with-ld-opt={ldflags}")); + } + + nginx_opts +} + +/// Runs external process invoking autoconf `configure` for NGINX. +fn configure(source_dir: &Path, build_dir: &Path, flags: &[String]) -> io::Result<()> { + let build_info = build_info(source_dir, flags); + + if build_dir.join("Makefile").is_file() + && build_dir.join(NGINX_BINARY).is_file() + && matches!( + std::fs::read_to_string(build_dir.join(NGINX_BUILD_INFO)).map(|x| x == build_info), + Ok(true) + ) + { + println!("Build info unchanged, skipping configure"); + return Ok(()); + } + + println!("Using NGINX source at {source_dir:?}"); + + let configure = ["configure", "auto/configure"] + .into_iter() + .map(|x| source_dir.join(x)) + .find(|x| x.is_file()) + .ok_or(io::ErrorKind::NotFound)?; + + println!("Running NGINX configure script with flags: {:?}", flags.join(" ")); + + let mut build_dir_arg: OsString = "--builddir=".into(); + build_dir_arg.push(build_dir); + + let mut flags: Vec = flags.iter().map(|x| x.into()).collect(); + flags.push(build_dir_arg); + + let output = duct::cmd(configure, flags).dir(source_dir).stderr_to_stdout().run()?; + + if !output.status.success() { + println!("configure failed with {:?}", output.status); + return Err(io::ErrorKind::Other.into()); + } + + let _ = std::fs::write(build_dir.join(NGINX_BUILD_INFO), build_info); + + Ok(()) +} + +/// Runs `make` within the NGINX source directory as an external process. +fn make(source_dir: &Path, build_dir: &Path, extra_args: U) -> io::Result +where + U: IntoIterator, + U::Item: Into, +{ + // Level of concurrency to use when building nginx - cargo nicely provides this information + let num_jobs = match env::var("NUM_JOBS") { + Ok(s) => s.parse::().ok(), + Err(_) => thread::available_parallelism().ok().map(|n| n.get()), + } + .unwrap_or(1); + + let mut args = vec![ + OsString::from("-f"), + build_dir.join("Makefile").into(), + OsString::from("-j"), + num_jobs.to_string().into(), + ]; + args.extend(extra_args.into_iter().map(Into::into)); + + // Use MAKE passed from the parent process if set. Otherwise prefer `gmake` as it provides a + // better feature-wise implementation on some systems. + // Notably, we want to avoid SUN make on Solaris (does not support -j) or ancient GNU make 3.81 + // on MacOS. + let inherited = env::var("MAKE"); + let make_commands: &[&str] = match inherited { + Ok(ref x) => &[x.as_str(), "gmake", "make"], + _ => &["gmake", "make"], + }; + + // Give preference to the binary with the name of gmake if it exists because this is typically + // the GNU 4+ on MacOS (if it is installed via homebrew). + for make in make_commands { + /* Use the duct dependency here to merge the output of STDOUT and STDERR into a single stream, + and to provide the combined output as a reader which can be iterated over line-by-line. We + use duct to do this because it is a lot of work to implement this from scratch. */ + let result = duct::cmd(*make, &args).dir(source_dir).stderr_to_stdout().run(); + + match result { + Err(err) if err.kind() == io::ErrorKind::NotFound => { + eprintln!("make: command '{make}' not found"); + continue; + } + Ok(out) if !out.status.success() => { + return Err(io::Error::other(format!( + "make: '{}' failed with {:?}", + make, out.status + ))); + } + _ => return result, + } + } + + Err(io::ErrorKind::NotFound.into()) +} diff --git a/source/rust/vendor/ngx-rust/nginx-src/src/verifier.rs b/source/rust/vendor/ngx-rust/nginx-src/src/verifier.rs new file mode 100644 index 0000000..917c947 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-src/src/verifier.rs @@ -0,0 +1,107 @@ +use std::ffi::OsString; +use std::fs::{self, Permissions}; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::{env, io}; + +static GNUPG_COMMAND: &str = "gpg"; + +pub struct SignatureVerifier { + gnupghome: PathBuf, +} + +impl SignatureVerifier { + pub fn new() -> io::Result { + if env::var("NGX_NO_SIGNATURE_CHECK").is_ok() { + return Err(io::Error::other("signature check disabled by user".to_string())); + }; + + if let Err(x) = duct::cmd!(GNUPG_COMMAND, "--version").stdout_null().run() { + return Err(io::Error::other(format!( + "signature check disabled: \"{GNUPG_COMMAND}\" not found ({x})" + ))); + } + + // We do not want to mess with the default gpg data for the running user, + // so we store all gpg data within our build directory. + let gnupghome = + env::var("OUT_DIR").map(PathBuf::from).map_err(io::Error::other)?.join(".gnupg"); + + if !fs::exists(&gnupghome)? { + fs::create_dir_all(&gnupghome)?; + } + + change_permissions_recursively(gnupghome.as_path(), 0o700, 0o600)?; + + Ok(Self { gnupghome }) + } + + /// Imports all the required GPG keys into a temporary directory in order to + /// validate the integrity of the downloaded tarballs. + pub fn import_keys(&self, server: &str, key_ids: &[&str]) -> io::Result<()> { + println!("Importing {} GPG keys for key server: {}", key_ids.len(), server); + + let mut args = vec![ + OsString::from("--homedir"), + self.gnupghome.clone().into(), + OsString::from("--keyserver"), + server.into(), + OsString::from("--recv-keys"), + ]; + args.extend(key_ids.iter().map(OsString::from)); + + let cmd = duct::cmd(GNUPG_COMMAND, &args); + let output = cmd.stderr_to_stdout().stdout_capture().unchecked().run()?; + + if !output.status.success() { + eprintln!("{}", String::from_utf8_lossy(&output.stdout)); + return Err(io::Error::other(format!( + "Command: {:?}\nFailed to import GPG keys: {}", + cmd, + key_ids.join(" ") + ))); + } + + Ok(()) + } + + /// Validates the integrity of a file against the cryptographic signature associated with + /// the file. + pub fn verify_signature(&self, path: &Path, signature: &Path) -> io::Result<()> { + let cmd = + duct::cmd!(GNUPG_COMMAND, "--homedir", &self.gnupghome, "--verify", signature, path); + let output = cmd.stderr_to_stdout().stdout_capture().unchecked().run()?; + if !output.status.success() { + eprintln!("{}", String::from_utf8_lossy(&output.stdout)); + return Err(io::Error::other(format!( + "Command: {:?}\nGPG signature verification of archive failed [{}]", + cmd, + path.display() + ))); + } + Ok(()) + } +} + +fn change_permissions_recursively( + path: &Path, + dir_mode: u32, + file_mode: u32, +) -> std::io::Result<()> { + if path.is_dir() { + // Set directory permissions to 700 + fs::set_permissions(path, Permissions::from_mode(dir_mode))?; + + for entry in fs::read_dir(path)? { + let entry = entry?; + let path = entry.path(); + + change_permissions_recursively(&path, dir_mode, file_mode)?; + } + } else { + // Set file permissions to 600 + fs::set_permissions(path, Permissions::from_mode(file_mode))?; + } + + Ok(()) +} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/Cargo.toml b/source/rust/vendor/ngx-rust/nginx-sys/Cargo.toml new file mode 100644 index 0000000..3faf6c7 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "nginx-sys" +version = "0.5.0" +categories = ["external-ffi-bindings"] +description = "FFI bindings to NGINX" +keywords = ["nginx", "ffi", "sys"] +build = "build/main.rs" +# This field is required to export DEP_NGINX_ vars +# See https://github.com/rust-lang/cargo/issues/3544 +links = "nginx" +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +rust-version.workspace = true + +[package.metadata.docs.rs] +all-features = true +default-target = "x86_64-unknown-linux-gnu" +targets = [] + +[dependencies] + +[target.'cfg(not(windows))'.dependencies] +errno = { version = "0.3.10", default-features = false } + +[build-dependencies] +bindgen = "0.72.1" +cc = "1.2.0" +dunce = "1.0.5" +regex = "1.11.1" +nginx-src = { version = "~1.30.0", optional = true, path = "../nginx-src" } +shlex = "2" + +[features] +default = ["http"] +# Allows generation of bindings for the HTTP module. +http = [] +# Allows generation of bindings for the Mail module. +mail = [] +# Allows generation of bindings for the Stream module. +stream = [] +# Enables downloading and building a copy of NGINX in the build script. +vendored = ["dep:nginx-src"] + +[lints] +workspace = true diff --git a/source/rust/vendor/ngx-rust/nginx-sys/LICENSE b/source/rust/vendor/ngx-rust/nginx-sys/LICENSE new file mode 120000 index 0000000..ea5b606 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/LICENSE @@ -0,0 +1 @@ +../LICENSE \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/nginx-sys/README.md b/source/rust/vendor/ngx-rust/nginx-sys/README.md new file mode 100644 index 0000000..3750a79 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/README.md @@ -0,0 +1,173 @@ +# nginx-sys + +The `nginx-sys` crate provides low-level bindings for the nginx C API, allowing +Rust applications to interact with nginx servers and modules. + +## Usage + +Add `nginx-sys` as a dependency in your `Cargo.toml`: + +```toml +[dependencies] +nginx-sys = "0.5.0" +``` + +Set the path to your nginx sources and build directory using the +[environment variables](#input-variables), or enable the `nginx-sys/vendored` +feature to use a downloaded copy of the nginx sources. + +Note that it is recommended to use the exact source and `configure` arguments +of the nginx build you are planning to use in production. +`configure` arguments alter the APIs and the symbols visible to the Rust code, +and some OS distributions are known to ship nginx packages with API-breaking +patches applied. + +## Features + +- `http` - **Enabled** by default. Allows generation of bindings for the HTTP + module, `ngx_http.h`. + The feature will be ignored if NGINX is configured without HTTP support, + thus it may be necessary to check for `http` in + [`DEP_NGINX_FEATURES`](#dep_nginx_features). + +- `mail`: Allows generation of bindings for the Mail module, `ngx_mail.h`. + The feature will be ignored if NGINX is configured without Mail support, + thus it may be necessary to check for `mail` in + [`DEP_NGINX_FEATURES`](#dep_nginx_features). + +- `stream`: Allows generation of bindings for the Stream module, `ngx_stream.h`. + The feature will be ignored if NGINX is configured without Stream support, + thus it may be necessary to check for `stream` in + [`DEP_NGINX_FEATURES`](#dep_nginx_features). + +- `vendored`: Enables the build scripts to download and build a copy of nginx + source and link against it. + See `nginx-src` crate documentation for additional details. + +## Input variables + +`NGINX_SOURCE_DIR`, `NGINX_BUILD_DIR` control paths to an external nginx source +tree and a configured build directory. Normally, specifying either of these is +sufficient, as the build directory defaults to `objs` under the source dir. + +However, it's possible to set the latter to any valid path with +`configure --builddir=<...>`, and we need _both_ paths to support such +configuration. + +The variables above are optional, but take preference when the `vendored` crate +feature is enabled. + +## Output variables + +Following metadata variables are passed to the build scripts of any **direct** +dependents of the package. + +Check the [using another sys crate] and the [links manifest key] sections of the +Cargo Book for more details about passing metadata between packages. + +### `DEP_NGINX_FEATURES` + +nginx has various configuration options that may affect the availability of +functions, constants and structure fields. This is not something that can be +detected at runtime, as an attempt to use a symbol unavailable in the bindings +would result in compilation error. + +`DEP_NGINX_FEATURES_CHECK` contains the full list of feature flags supported +by `nginx-sys`, i.e. everything that can be used for feature checks. +The most common use for this variable is to specify [`cargo::rustc-check-cfg`]. + +`DEP_NGINX_FEATURES` contains the list of features enabled in the version of +nginx being built against. + +An example of a build script with these variables: + +```rust +// Specify acceptable values for `ngx_feature`. +println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES_CHECK"); +println!( + "cargo::rustc-check-cfg=cfg(ngx_feature, values({}))", + std::env::var("DEP_NGINX_FEATURES_CHECK").unwrap_or("any()".to_string()) +); +// Read feature flags detected by nginx-sys and pass to the compiler. +println!("cargo::rerun-if-env-changed=DEP_NGINX_FEATURES"); +if let Ok(features) = std::env::var("DEP_NGINX_FEATURES") { + for feature in features.split(',').map(str::trim) { + println!("cargo::rustc-cfg=ngx_feature=\"{}\"", feature); + } +} +``` + +And an usage example: + +```rust +#[cfg(ngx_feature = "debug")] +println!("this nginx binary was built with debug logging enabled"); +``` + +### `DEP_NGINX_OS` + +Version, as detected by the nginx configuration script. + +`DEP_NGINX_OS_CHECK` contains the full list of supported values, and +`DEP_NGINX_OS` the currently detected one. + +Usage examples: + +```rust +// Specify acceptable values for `ngx_os` +println!("cargo::rerun-if-env-changed=DEP_NGINX_OS_CHECK"); +println!( + "cargo::rustc-check-cfg=cfg(ngx_os, values({}))", + std::env::var("DEP_NGINX_OS_CHECK").unwrap_or("any()".to_string()) +); +// Read operating system detected by nginx-sys and pass to the compiler. +println!("cargo::rerun-if-env-changed=DEP_NGINX_OS"); +if let Ok(os) = std::env::var("DEP_NGINX_OS") { + println!("cargo::rustc-cfg=ngx_os=\"{}\"", os); +} +``` + +```rust +#[cfg(ngx_os = "freebsd")] +println!("this nginx binary was built on FreeBSD"); +``` + +### Version and build information + +- `DEP_NGINX_VERSION_NUMBER`: + a numeric representation with 3 digits for each component: `1026002` +- `DEP_NGINX_VERSION`: + human-readable string in a product/version format: `nginx/1.26.2` +- `DEP_NGINX_BUILD`: + version string with the optional build name (`--build=`) included: + `nginx/1.25.5 (nginx-plus-r32)` + +Usage example: + +```rust +println!("cargo::rustc-check-cfg=cfg(nginx1_27_0)"); +println!("cargo::rerun-if-env-changed=DEP_NGINX_VERSION_NUMBER"); +if let Ok(version) = std::env::var("DEP_NGINX_VERSION_NUMBER") { + let version: u64 = version.parse().unwrap(); + + if version >= 1_027_000 { + println!("cargo::rustc-cfg=nginx1_27_0"); + } +} +``` + +## Examples + +### Get nginx Version + +This example demonstrates how to retrieve the version of the nginx server. + +```rust,no_run +use nginx_sys::nginx_version; + +println!("nginx version: {}", nginx_version); +``` + +[using another sys crate]: https://doc.rust-lang.org/nightly/cargo/reference/build-script-examples.html#using-another-sys-crate +[links manifest key]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#the-links-manifest-key +[`cargo::rustc-check-cfg`]: https://doc.rust-lang.org/nightly/cargo/reference/build-scripts.html#rustc-check-cfg diff --git a/source/rust/vendor/ngx-rust/nginx-sys/build/main.rs b/source/rust/vendor/ngx-rust/nginx-sys/build/main.rs new file mode 100644 index 0000000..8f85bd0 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/build/main.rs @@ -0,0 +1,484 @@ +extern crate bindgen; + +use std::env; +use std::error::Error as StdError; +use std::fs::{read_to_string, File}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +const ENV_VARS_TRIGGERING_RECOMPILE: &[&str] = &["OUT_DIR", "NGINX_BUILD_DIR", "NGINX_SOURCE_DIR"]; + +/// The feature flags set by the nginx configuration script. +/// +/// This list is a subset of NGX_/NGX_HAVE_ macros known to affect the structure layout or module +/// avialiability. +/// +/// The flags will be exposed to the buildscripts of _direct_ dependendents of this crate as +/// `DEP_NGINX_FEATURES` environment variable. +/// The list of recognized values will be exported as `DEP_NGINX_FEATURES_CHECK`. +const NGX_CONF_FEATURES: &[&str] = &[ + "compat", + "debug", + "have_epollrdhup", + "have_file_aio", + "have_kqueue", + "have_memalign", + "have_posix_memalign", + "have_sched_yield", + "have_variadic_macros", + "http", + "http_cache", + "http_dav", + "http_gzip", + "http_realip", + "http_ssi", + "http_ssl", + "http_upstream_zone", + "http_v2", + "http_v3", + "http_x_forwarded_for", + "pcre", + "pcre2", + "quic", + "ssl", + "stream", + "stream_ssl", + "stream_upstream_zone", + "threads", +]; + +/// The operating systems supported by the nginx configuration script +/// +/// The detected value will be exposed to the buildsrcipts of _direct_ dependents of this crate as +/// `DEP_NGINX_OS` environment variable. +/// The list of recognized values will be exported as `DEP_NGINX_OS_CHECK`. +const NGX_CONF_OS: &[&str] = &[ + "darwin", "freebsd", "gnu_hurd", "hpux", "linux", "solaris", "tru64", "win32", +]; + +type BoxError = Box; + +/// Function invoked when `cargo build` is executed. +/// This function will download NGINX and all supporting dependencies, verify their integrity, +/// extract them, execute autoconf `configure` for NGINX, compile NGINX and finally install +/// NGINX in a subdirectory with the project. +fn main() -> Result<(), BoxError> { + // Hint cargo to rebuild if any of the these environment variables values change + // because they will trigger a recompilation of NGINX with different parameters + for var in ENV_VARS_TRIGGERING_RECOMPILE { + println!("cargo:rerun-if-env-changed={var}"); + } + println!("cargo:rerun-if-changed=build/main.rs"); + println!("cargo:rerun-if-changed=build/wrapper.h"); + + let nginx = NginxSource::from_env(); + println!( + "cargo:rerun-if-changed={}", + nginx.build_dir.join("Makefile").to_string_lossy() + ); + println!( + "cargo:rerun-if-changed={}", + nginx.build_dir.join("ngx_auto_config.h").to_string_lossy() + ); + // Read autoconf generated makefile for NGINX and generate Rust bindings based on its includes + generate_binding(&nginx); + Ok(()) +} + +pub struct NginxSource { + source_dir: PathBuf, + build_dir: PathBuf, +} + +impl NginxSource { + pub fn new(source_dir: impl AsRef, build_dir: impl AsRef) -> Self { + let source_dir = NginxSource::check_source_dir(source_dir).expect("source directory"); + let build_dir = NginxSource::check_build_dir(build_dir).expect("build directory"); + + Self { + source_dir, + build_dir, + } + } + + pub fn from_env() -> Self { + match ( + env::var_os("NGINX_SOURCE_DIR"), + env::var_os("NGINX_BUILD_DIR"), + ) { + (Some(source_dir), Some(build_dir)) => NginxSource::new(source_dir, build_dir), + (Some(source_dir), None) => Self::from_source_dir(source_dir), + (None, Some(build_dir)) => Self::from_build_dir(build_dir), + _ => Self::from_vendored(), + } + } + + pub fn from_source_dir(source_dir: impl AsRef) -> Self { + let build_dir = source_dir.as_ref().join("objs"); + + // todo!("Build from source"); + + Self::new(source_dir, build_dir) + } + + pub fn from_build_dir(build_dir: impl AsRef) -> Self { + let source_dir = build_dir + .as_ref() + .parent() + .expect("source directory") + .to_owned(); + Self::new(source_dir, build_dir) + } + + #[cfg(feature = "vendored")] + pub fn from_vendored() -> Self { + nginx_src::print_cargo_metadata(); + + let out_dir = env::var("OUT_DIR").unwrap(); + let build_dir = PathBuf::from(out_dir).join("objs"); + let (source_dir, build_dir) = nginx_src::build(build_dir).expect("nginx-src build"); + + Self { + source_dir, + build_dir, + } + } + + #[cfg(not(feature = "vendored"))] + pub fn from_vendored() -> Self { + panic!( + "\"nginx-sys/vendored\" feature is disabled and neither NGINX_SOURCE_DIR nor \ + NGINX_BUILD_DIR is set" + ); + } + + fn check_source_dir(source_dir: impl AsRef) -> Result { + match dunce::canonicalize(&source_dir) { + Ok(path) if path.join("src/core/nginx.h").is_file() => Ok(path), + Err(err) => Err(format!( + "Invalid nginx source directory: {:?}. {}", + source_dir.as_ref(), + err + ) + .into()), + _ => Err(format!( + "Invalid nginx source directory: {:?}. NGINX_SOURCE_DIR is not specified or \ + contains invalid value.", + source_dir.as_ref() + ) + .into()), + } + } + + fn check_build_dir(build_dir: impl AsRef) -> Result { + match dunce::canonicalize(&build_dir) { + Ok(path) if path.join("ngx_auto_config.h").is_file() => Ok(path), + Err(err) => Err(format!( + "Invalid nginx build directory: {:?}. {}", + build_dir.as_ref(), + err + ) + .into()), + _ => Err(format!( + "Invalid NGINX build directory: {:?}. NGINX_BUILD_DIR is not specified or \ + contains invalid value.", + build_dir.as_ref() + ) + .into()), + } + } +} + +/// Generates Rust bindings for NGINX +fn generate_binding(nginx: &NginxSource) { + let autoconf_makefile_path = nginx.build_dir.join("Makefile"); + let (includes, defines) = parse_makefile(&autoconf_makefile_path); + let includes: Vec<_> = includes + .into_iter() + .map(|path| { + if path.is_absolute() { + path + } else { + nginx.source_dir.join(path) + } + }) + .collect(); + let mut clang_args: Vec = includes + .iter() + .map(|path| format!("-I{}", path.to_string_lossy())) + .collect(); + + clang_args.extend(defines.iter().map(|(n, ov)| { + if let Some(v) = ov { + format!("-D{n}={v}") + } else { + format!("-D{n}") + } + })); + + print_cargo_metadata(nginx, &includes, &defines).expect("cargo dependency metadata"); + + // bindgen targets the latest known stable by default + let rust_target: bindgen::RustTarget = env::var("CARGO_PKG_RUST_VERSION") + .expect("rust-version set in Cargo.toml") + .parse() + .expect("rust-version is valid and supported by bindgen"); + + let bindings = bindgen::Builder::default() + // Bindings will not compile on Linux without block listing this item + // It is worth investigating why this is + .blocklist_item("IPPORT_RESERVED") + // will be restored later in build.rs + .blocklist_item("NGX_ALIGNMENT") + .generate_cstr(true) + // The input header we would like to generate bindings for. + .header("build/wrapper.h") + .clang_args(clang_args) + .layout_tests(false) + .rust_target(rust_target) + .use_core() + .generate() + .expect("Unable to generate bindings"); + + // Write the bindings to the $OUT_DIR/bindings.rs file. + let out_dir_env = + env::var("OUT_DIR").expect("The required environment variable OUT_DIR was not set"); + let out_path = PathBuf::from(out_dir_env); + bindings + .write_to_file(out_path.join("bindings.rs")) + .expect("Couldn't write bindings!"); +} + +/// Reads through the makefile generated by autoconf and finds all of the includes +/// and definitions used to compile nginx. This is used to generate the correct bindings +/// for the nginx source code. +pub fn parse_makefile( + nginx_autoconf_makefile_path: &PathBuf, +) -> (Vec, Vec<(String, Option)>) { + fn parse_line( + includes: &mut Vec, + defines: &mut Vec<(String, Option)>, + line: &str, + ) { + let mut words = shlex::Shlex::new(line); + + while let Some(word) = words.next() { + if let Some(inc) = word.strip_prefix("-I") { + let value = if inc.is_empty() { + words.next().expect("-I argument") + } else { + inc.to_string() + }; + includes.push(value); + } else if let Some(def) = word.strip_prefix("-D") { + let def = if def.is_empty() { + words.next().expect("-D argument") + } else { + def.to_string() + }; + + if let Some((name, value)) = def.split_once("=") { + defines.push((name.to_string(), Some(value.to_string()))); + } else { + defines.push((def.to_string(), None)); + } + } + } + } + + let mut all_incs = vec![]; + let mut cflags_includes = vec![]; + + let mut defines = vec![]; + + let makefile_contents = match read_to_string(nginx_autoconf_makefile_path) { + Ok(path) => path, + Err(e) => { + panic!( + "Unable to read makefile from path [{}]. Error: {}", + nginx_autoconf_makefile_path.to_string_lossy(), + e + ); + } + }; + + let lines = makefile_contents.lines(); + let mut line: String = "".to_string(); + for l in lines { + if let Some(part) = l.strip_suffix("\\") { + line += part; + continue; + } + + line += l; + + if let Some(tail) = line.strip_prefix("ALL_INCS") { + parse_line(&mut all_incs, &mut defines, tail); + } else if let Some(tail) = line.strip_prefix("CFLAGS") { + parse_line(&mut cflags_includes, &mut defines, tail); + } + + line.clear(); + } + + cflags_includes.extend(all_incs); + + ( + cflags_includes.into_iter().map(PathBuf::from).collect(), + defines, + ) +} + +/// Collect info about the nginx configuration and expose it to the dependents via +/// `DEP_NGINX_...` variables. +pub fn print_cargo_metadata>( + nginx: &NginxSource, + includes: &[T], + defines: &[(String, Option)], +) -> Result<(), Box> { + // Unquote and merge C string constants + let unquote_re = regex::Regex::new(r#""(.*?[^\\])"\s*"#).unwrap(); + let unquote = |data: &str| -> String { + unquote_re + .captures_iter(data) + .map(|c| c.get(1).unwrap().as_str()) + .collect::>() + .concat() + }; + + let mut ngx_features: Vec = vec![]; + let mut ngx_os = String::new(); + + let expanded = expand_definitions(includes, defines)?; + for line in String::from_utf8(expanded)?.lines() { + let Some((name, value)) = line + .trim() + .strip_prefix("RUST_CONF_") + .and_then(|x| x.split_once('=')) + else { + continue; + }; + + let name = name.trim().to_ascii_lowercase(); + let value = value.trim(); + + if name == "nginx_build" { + println!("cargo::metadata=build={}", unquote(value)); + } else if name == "nginx_version" { + println!("cargo::metadata=version={}", unquote(value)); + } else if name == "nginx_version_number" { + println!("cargo::metadata=version_number={value}"); + } else if NGX_CONF_OS.contains(&name.as_str()) { + ngx_os = name; + } else if NGX_CONF_FEATURES.contains(&name.as_str()) && value != "0" { + ngx_features.push(name); + } + } + + println!( + "cargo::metadata=build_dir={}", + nginx.build_dir.to_str().expect("Unicode build path") + ); + + println!( + "cargo::metadata=include={}", + // The str conversion is necessary because cargo directives must be valid UTF-8 + env::join_paths(includes.iter().map(|x| x.as_ref()))? + .to_str() + .expect("Unicode include paths") + ); + + println!( + "cargo:metadata=cflags={}", + defines + .iter() + .map(|(n, ov)| if let Some(v) = ov { + format!("-D{n}={v}") + } else { + format!("-D{n}") + }) + .collect::>() + .join(" ") + ); + + // A quoted list of all recognized features to be passed to rustc-check-cfg. + let values = NGX_CONF_FEATURES.join("\",\""); + println!("cargo::metadata=features_check=\"{values}\""); + println!("cargo::rustc-check-cfg=cfg(ngx_feature, values(\"{values}\"))"); + + // A list of features enabled in the nginx build we're using + println!("cargo::metadata=features={}", ngx_features.join(",")); + for feature in ngx_features { + println!("cargo::rustc-cfg=ngx_feature=\"{feature}\""); + } + + // A quoted list of all recognized operating systems to be passed to rustc-check-cfg. + let values = NGX_CONF_OS.join("\",\""); + println!("cargo::metadata=os_check=\"{values}\""); + println!("cargo::rustc-check-cfg=cfg(ngx_os, values(\"{values}\"))"); + // Current detected operating system + println!("cargo::metadata=os={ngx_os}"); + println!("cargo::rustc-cfg=ngx_os=\"{ngx_os}\""); + + Ok(()) +} + +fn expand_definitions>( + includes: &[T], + defines: &[(String, Option)], +) -> Result, Box> { + let path = PathBuf::from(env::var("OUT_DIR")?).join("expand.c"); + let mut writer = std::io::BufWriter::new(File::create(&path)?); + + write!( + writer, + " +#include +#include + +/* C23 or Clang/GCC/MSVC >= 15.3 extension */ +#if defined(__has_include) + +#if __has_include() +RUST_CONF_HTTP=1 +#endif + +#if __has_include() +RUST_CONF_STREAM=1 +#endif + +#else +/* fallback */ +RUST_CONF_HTTP=1 +#endif + +RUST_CONF_NGINX_BUILD=NGINX_VER_BUILD +RUST_CONF_NGINX_VERSION=NGINX_VER +RUST_CONF_NGINX_VERSION_NUMBER=nginx_version +" + )?; + + for flag in NGX_CONF_FEATURES.iter().chain(NGX_CONF_OS.iter()) { + let flag = flag.to_ascii_uppercase(); + write!( + writer, + " +#if defined(NGX_{flag}) +RUST_CONF_{flag}=NGX_{flag} +#endif" + )?; + } + + writer.flush()?; + drop(writer); + + let mut builder = cc::Build::new(); + + builder.includes(includes).file(path); + + for def in defines { + builder.define(&def.0, def.1.as_deref()); + } + + Ok(builder.try_expand()?) +} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/build/wrapper.h b/source/rust/vendor/ngx-rust/nginx-sys/build/wrapper.h new file mode 100644 index 0000000..552a793 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/build/wrapper.h @@ -0,0 +1,34 @@ +#include +#include + +/* __has_include was a compiler-specific extension until C23, + * but it's safe to assume that bindgen supports it via libclang. + */ +#if defined(__has_include) + +#if __has_include() +#include +#endif + +#if __has_include() +#include +#endif + +#else +#include +#endif + +const char *NGX_RS_MODULE_SIGNATURE = NGX_MODULE_SIGNATURE; + +// NGX_ALIGNMENT could be defined as a constant or an expression, with the +// latter being unsupported by bindgen. +const size_t NGX_RS_ALIGNMENT = NGX_ALIGNMENT; + +// `--prefix=` results in not emitting the declaration +#ifndef NGX_PREFIX +#define NGX_PREFIX "" +#endif + +#ifndef NGX_CONF_PREFIX +#define NGX_CONF_PREFIX NGX_PREFIX +#endif diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/detail.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/detail.rs new file mode 100644 index 0000000..c2cbe3f --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/detail.rs @@ -0,0 +1,153 @@ +//! Implementation details shared between nginx-sys and ngx. +#![allow(missing_docs)] + +use core::fmt; +use core::ptr::copy_nonoverlapping; + +use crate::bindings::{ngx_pnalloc, ngx_pool_t, u_char}; + +/// Convert a byte slice to a raw pointer (`*mut u_char`) allocated in the given nginx memory pool. +/// +/// # Safety +/// +/// The caller must provide a valid pointer to the memory pool. +pub unsafe fn bytes_to_uchar(pool: *mut ngx_pool_t, data: &[u8]) -> Option<*mut u_char> { + let ptr: *mut u_char = unsafe { ngx_pnalloc(pool, data.len()) as _ }; + if ptr.is_null() { + return None; + } + unsafe { copy_nonoverlapping(data.as_ptr(), ptr, data.len()) }; + Some(ptr) +} + +/// Convert a string slice (`&str`) to a raw pointer (`*mut u_char`) allocated in the given nginx +/// memory pool. +/// +/// # Arguments +/// +/// * `pool` - A pointer to the nginx memory pool (`ngx_pool_t`). +/// * `data` - The string slice to convert to a raw pointer. +/// +/// # Safety +/// This function is marked as unsafe because it involves raw pointer manipulation and direct memory +/// allocation using `ngx_pnalloc`. +/// +/// # Returns +/// A raw pointer (`*mut u_char`) to the allocated memory containing the converted string data. +/// +/// # Example +/// ```rust,ignore +/// let pool: *mut ngx_pool_t = ...; // Obtain a pointer to the nginx memory pool +/// let data: &str = "example"; // The string to convert +/// let ptr = str_to_uchar(pool, data); +/// ``` +pub unsafe fn str_to_uchar(pool: *mut ngx_pool_t, data: &str) -> *mut u_char { + let ptr: *mut u_char = unsafe { ngx_pnalloc(pool, data.len()) as _ }; + debug_assert!(!ptr.is_null()); + unsafe { copy_nonoverlapping(data.as_ptr(), ptr, data.len()) }; + ptr +} + +#[inline] +pub fn debug_bytes(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result { + if f.alternate() { + match bytes.len() { + 0 => Ok(()), + 1 => write!(f, "{:02x}", bytes[0]), + x => { + for b in &bytes[..x - 1] { + write!(f, "{b:02x},")?; + } + write!(f, "{:02x}", bytes[x - 1]) + } + } + } else { + f.write_str("\"")?; + display_bytes(f, bytes)?; + f.write_str("\"") + } +} + +#[inline] +pub fn display_bytes(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result { + // The implementation is similar to an inlined `String::from_utf8_lossy`, with two + // important differences: + // + // - it writes directly to the Formatter instead of allocating a temporary String + // - invalid sequences are represented as escaped individual bytes + for chunk in bytes.utf8_chunks() { + f.write_str(chunk.valid())?; + for byte in chunk.invalid() { + write!(f, "\\x{byte:02x}")?; + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + extern crate alloc; + use alloc::format; + use alloc::string::ToString; + + use super::*; + + struct TestStr(&'static [u8]); + + impl fmt::Debug for TestStr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("TestStr(")?; + debug_bytes(f, self.0)?; + f.write_str(")") + } + } + + impl fmt::Display for TestStr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + display_bytes(f, self.0) + } + } + + #[test] + fn test_display() { + let cases: &[(&[u8], &str)] = &[ + (b"", ""), + (b"Ferris the \xf0\x9f\xa6\x80", "Ferris the 🦀"), + (b"\xF0\x90\x80", "\\xf0\\x90\\x80"), + (b"\xF0\x90\x80Hello World", "\\xf0\\x90\\x80Hello World"), + (b"Hello \xF0\x90\x80World", "Hello \\xf0\\x90\\x80World"), + (b"Hello World\xF0\x90\x80", "Hello World\\xf0\\x90\\x80"), + ]; + + for (bytes, expected) in cases { + let str = TestStr(bytes); + assert_eq!(str.to_string(), *expected); + } + + // Check that the formatter arguments are ignored correctly + for (bytes, expected) in &cases[2..3] { + let str = TestStr(bytes); + assert_eq!(format!("{str:12.12}"), *expected); + } + } + + #[test] + fn test_debug() { + let cases: &[(&[u8], &str, &str)] = &[ + (b"", "TestStr(\"\")", "TestStr()"), + (b"a", "TestStr(\"a\")", "TestStr(61)"), + ( + b"Ferris the \xf0\x9f\xa6\x80", + "TestStr(\"Ferris the 🦀\")", + "TestStr(46,65,72,72,69,73,20,74,68,65,20,f0,9f,a6,80)", + ), + (b"\xF0\x90\x80", "TestStr(\"\\xf0\\x90\\x80\")", "TestStr(f0,90,80)"), + ]; + for (bytes, expected, alternate) in cases { + let str = TestStr(bytes); + assert_eq!(format!("{str:?}"), *expected); + assert_eq!(format!("{str:#?}"), *alternate); + } + } +} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/event.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/event.rs new file mode 100644 index 0000000..af7c0ff --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/event.rs @@ -0,0 +1,85 @@ +use core::ptr; + +use crate::{ + NGX_TIMER_LAZY_DELAY, ngx_current_msec, ngx_event_t, ngx_event_timer_rbtree, ngx_msec_t, + ngx_queue_insert_before, ngx_queue_remove, ngx_queue_t, ngx_rbtree_delete, ngx_rbtree_insert, +}; + +/// Sets a timeout for an event. +/// +/// # Safety +/// +///`ev` must be a valid pointer to an `ngx_event_t`. +#[inline] +pub unsafe fn ngx_add_timer(ev: *mut ngx_event_t, timer: ngx_msec_t) { + unsafe { + let key: ngx_msec_t = ngx_current_msec.wrapping_add(timer); + + if (*ev).timer_set() != 0 { + /* + * Use a previous timer value if difference between it and a new + * value is less than NGX_TIMER_LAZY_DELAY milliseconds: this allows + * to minimize the rbtree operations for fast connections. + */ + if key.abs_diff((*ev).timer.key) < NGX_TIMER_LAZY_DELAY as _ { + return; + } + + ngx_del_timer(ev); + } + + (*ev).timer.key = key; + + ngx_rbtree_insert(&raw mut ngx_event_timer_rbtree, &raw mut (*ev).timer); + + (*ev).set_timer_set(1); + } +} + +/// Deletes a previously set timeout. +/// +/// # Safety +/// +/// `ev` must be a valid pointer to an `ngx_event_t`, previously armed with [ngx_add_timer]. +#[inline] +pub unsafe fn ngx_del_timer(ev: *mut ngx_event_t) { + unsafe { + ngx_rbtree_delete(&raw mut ngx_event_timer_rbtree, &raw mut (*ev).timer); + + (*ev).timer.left = ptr::null_mut(); + (*ev).timer.right = ptr::null_mut(); + (*ev).timer.parent = ptr::null_mut(); + + (*ev).set_timer_set(0); + } +} + +/// Post the event `ev` to the post queue `q`. +/// +/// # Safety +/// +/// `ev` must be a valid pointer to an `ngx_event_t`. +/// `q` is a valid pointer to a queue head. +#[inline] +pub unsafe fn ngx_post_event(ev: *mut ngx_event_t, q: *mut ngx_queue_t) { + unsafe { + if (*ev).posted() == 0 { + (*ev).set_posted(1); + ngx_queue_insert_before(q, &raw mut (*ev).queue); + } + } +} + +/// Deletes the event `ev` from the queue it's currently posted in. +/// +/// # Safety +/// +/// `ev` must be a valid pointer to an `ngx_event_t`. +/// `ev.queue` is initialized with `ngx_queue_init`. +#[inline] +pub unsafe fn ngx_delete_posted_event(ev: *mut ngx_event_t) { + unsafe { + (*ev).set_posted(0); + ngx_queue_remove(&raw mut (*ev).queue); + } +} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/http.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/http.rs new file mode 100644 index 0000000..435cc79 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/http.rs @@ -0,0 +1,18 @@ +use core::mem::offset_of; + +use crate::bindings::ngx_http_conf_ctx_t; + +/// The offset of the `main_conf` field in the `ngx_http_conf_ctx_t` struct. +/// +/// This is used to access the main configuration context for an HTTP module. +pub const NGX_HTTP_MAIN_CONF_OFFSET: usize = offset_of!(ngx_http_conf_ctx_t, main_conf); + +/// The offset of the `srv_conf` field in the `ngx_http_conf_ctx_t` struct. +/// +/// This is used to access the server configuration context for an HTTP module. +pub const NGX_HTTP_SRV_CONF_OFFSET: usize = offset_of!(ngx_http_conf_ctx_t, srv_conf); + +/// The offset of the `loc_conf` field in the `ngx_http_conf_ctx_t` struct. +/// +/// This is used to access the location configuration context for an HTTP module. +pub const NGX_HTTP_LOC_CONF_OFFSET: usize = offset_of!(ngx_http_conf_ctx_t, loc_conf); diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/lib.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/lib.rs new file mode 100644 index 0000000..a3e3454 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/lib.rs @@ -0,0 +1,352 @@ +#![doc = include_str!("../README.md")] +#![warn(missing_docs)] +#![no_std] + +pub mod detail; +mod event; +#[cfg(all(feature = "http", ngx_feature = "http"))] +mod http; +#[cfg(all(feature = "mail", ngx_feature = "mail"))] +mod mail; +mod queue; +mod rbtree; +#[cfg(all(feature = "stream", ngx_feature = "stream"))] +mod stream; +mod string; + +use core::ptr; + +#[doc(hidden)] +mod bindings { + #![allow(unknown_lints)] // unnecessary_transmutes + #![allow(missing_docs)] + #![allow(non_upper_case_globals)] + #![allow(non_camel_case_types)] + #![allow(non_snake_case)] + #![allow(dead_code)] + #![allow(clippy::all)] + #![allow(improper_ctypes)] + #![allow(rustdoc::broken_intra_doc_links)] + #![allow(unnecessary_transmutes)] + include!(concat!(env!("OUT_DIR"), "/bindings.rs")); +} +#[doc(no_inline)] +pub use bindings::*; +pub use event::*; +#[cfg(all(feature = "http", ngx_feature = "http"))] +pub use http::*; +#[cfg(all(feature = "mail", ngx_feature = "mail"))] +pub use mail::*; +pub use queue::*; +pub use rbtree::*; +#[cfg(all(feature = "stream", ngx_feature = "stream"))] +pub use stream::*; + +/// Default alignment for pool allocations. +pub const NGX_ALIGNMENT: usize = NGX_RS_ALIGNMENT; + +/// Sentinel returned by `ngx_resolve_start()` when no resolver is configured. +/// +/// nginx's `NGX_NO_RESOLVER` macro expands to `(void *) -1`, which bindgen does +/// not emit. It is an address-only sentinel that must never be dereferenced; +/// callers compare the `ngx_resolve_start()` return value against it. +pub const NGX_NO_RESOLVER: *mut ngx_resolver_ctx_t = ptr::without_provenance_mut(usize::MAX); + +// Check if the allocations made with ngx_palloc are properly aligned. +// If the check fails, objects allocated from `ngx_pool` can violate Rust pointer alignment +// requirements. +const _: () = assert!(core::mem::align_of::() <= NGX_ALIGNMENT); + +impl ngx_array_t { + /// Returns the contents of this array as a slice of `T`. + /// + /// # Safety + /// + /// The array must be a valid, initialized array containing elements of type T or compatible in + /// layout with T (e.g. `#[repr(transparent)]` wrappers). + pub unsafe fn as_slice(&self) -> &[T] { + debug_assert_eq!( + core::mem::size_of::(), + self.size, + "ngx_array_t::as_slice(): element size mismatch" + ); + if self.nelts == 0 { + &[] + } else { + // SAFETY: in a valid array, `elts` is a valid well-aligned pointer to at least `nelts` + // elements of size `size` + unsafe { core::slice::from_raw_parts(self.elts.cast(), self.nelts) } + } + } + + /// Returns the contents of this array as a mutable slice of `T`. + /// + /// # Safety + /// + /// The array must be a valid, initialized array containing elements of type T or compatible in + /// layout with T (e.g. `#[repr(transparent)]` wrappers). + pub unsafe fn as_slice_mut(&mut self) -> &mut [T] { + debug_assert_eq!( + core::mem::size_of::(), + self.size, + "ngx_array_t::as_slice_mut(): element size mismatch" + ); + if self.nelts == 0 { + &mut [] + } else { + // SAFETY: in a valid array, `elts` is a valid well-aligned pointer to at least `nelts` + // elements of size `size` + unsafe { core::slice::from_raw_parts_mut(self.elts.cast(), self.nelts) } + } + } +} + +impl ngx_command_t { + /// Creates a new empty [`ngx_command_t`] instance. + /// + /// This method replaces the `ngx_null_command` C macro. This is typically used to terminate an + /// array of configuration directives. + /// + /// [`ngx_command_t`]: https://nginx.org/en/docs/dev/development_guide.html#config_directives + pub const fn empty() -> Self { + Self { + name: ngx_str_t::empty(), + type_: 0, + set: None, + conf: 0, + offset: 0, + post: ptr::null_mut(), + } + } +} + +impl ngx_module_t { + /// Create a new `ngx_module_t` instance with default values. + pub const fn default() -> Self { + Self { + ctx_index: ngx_uint_t::MAX, + index: ngx_uint_t::MAX, + name: ptr::null_mut(), + spare0: 0, + spare1: 0, + version: nginx_version as ngx_uint_t, + signature: NGX_RS_MODULE_SIGNATURE.as_ptr(), + ctx: ptr::null_mut(), + commands: ptr::null_mut(), + type_: 0, + init_master: None, + init_module: None, + init_process: None, + init_thread: None, + exit_thread: None, + exit_process: None, + exit_master: None, + spare_hook0: 0, + spare_hook1: 0, + spare_hook2: 0, + spare_hook3: 0, + spare_hook4: 0, + spare_hook5: 0, + spare_hook6: 0, + spare_hook7: 0, + } + } +} + +impl ngx_variable_value_t { + /// Returns the contents of this variable value as a byte slice. + pub fn as_bytes(&self) -> &[u8] { + match self.len() { + 0 => &[], + // SAFETY: data for non-empty value must be a valid well-aligned pointer. + len => unsafe { core::slice::from_raw_parts(self.data, len as usize) }, + } + } +} + +impl AsRef<[u8]> for ngx_variable_value_t { + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + +/// Returns the error code of the last failed operation (`errno`). +#[inline] +pub fn ngx_errno() -> ngx_err_t { + // SAFETY: GetLastError takes no arguments and reads a thread-local variable + #[cfg(windows)] + let err = unsafe { GetLastError() }; + + #[cfg(not(windows))] + let err = errno::errno().0; + + err as ngx_err_t +} + +/// Sets the error code (`errno`). +#[inline] +pub fn ngx_set_errno(err: ngx_err_t) { + #[cfg(windows)] + // SAFETY: SetLastError takes one argument by value and updates a thread-local variable + unsafe { + SetLastError(err as _) + } + #[cfg(not(windows))] + errno::set_errno(errno::Errno(err as _)) +} + +/// Returns the error code of the last failed sockets operation. +#[inline] +pub fn ngx_socket_errno() -> ngx_err_t { + // SAFETY: WSAGetLastError takes no arguments and reads a thread-local variable + #[cfg(windows)] + let err = unsafe { WSAGetLastError() }; + + #[cfg(not(windows))] + let err = errno::errno().0; + + err as ngx_err_t +} + +/// Sets the error code of the sockets operation. +#[inline] +pub fn ngx_set_socket_errno(err: ngx_err_t) { + #[cfg(windows)] + // SAFETY: WSaSetLastError takes one argument by value and updates a thread-local variable + unsafe { + WSASetLastError(err as _) + } + #[cfg(not(windows))] + errno::set_errno(errno::Errno(err as _)) +} + +/// Returns a non cryptograhpically-secure pseudo-random integer. +#[inline] +pub fn ngx_random() -> core::ffi::c_long { + #[cfg(windows)] + unsafe { + // Emulate random() as Microsoft CRT does not provide it. + // rand() should be thread-safe in the multi-threaded CRT we link to, but will not be seeded + // outside of the main thread. + let x: u32 = ((rand() as u32) << 16) ^ ((rand() as u32) << 8) ^ (rand() as u32); + (0x7fffffff & x) as _ + } + #[cfg(not(windows))] + unsafe { + random() + } +} + +/// Causes the calling thread to relinquish the CPU. +#[inline] +pub fn ngx_sched_yield() { + #[cfg(windows)] + unsafe { + SwitchToThread() + }; + #[cfg(all(not(windows), ngx_feature = "have_sched_yield"))] + unsafe { + sched_yield() + }; + #[cfg(not(any(windows, ngx_feature = "have_sched_yield")))] + unsafe { + usleep(1) + } +} + +/// Returns cached timestamp in seconds, updated at the start of the event loop iteration. +/// +/// Can be stale when accessing from threads, see [ngx_time_update]. +#[inline] +pub fn ngx_time() -> time_t { + // SAFETY: ngx_cached_time is initialized before any module code can run + unsafe { (*ngx_cached_time).sec } +} + +/// Returns cached time, updated at the start of the event loop iteration. +/// +/// Can be stale when accessing from threads, see [ngx_time_update]. +/// A cached reference to the ngx_timeofday() result is guaranteed to remain unmodified for the next +/// NGX_TIME_SLOTS seconds. +#[inline] +pub fn ngx_timeofday() -> &'static ngx_time_t { + // SAFETY: ngx_cached_time is initialized before any module code can run + unsafe { &*ngx_cached_time } +} + +/// Initialize a list, using a pool for the backing memory, with capacity to store the given number +/// of elements and element size. +/// +/// # Safety +/// * `list` must be non-null +/// * `pool` must be a valid pool +#[inline] +pub unsafe fn ngx_list_init( + list: *mut ngx_list_t, + pool: *mut ngx_pool_t, + n: ngx_uint_t, + size: usize, +) -> ngx_int_t { + unsafe { + (*list).part.elts = ngx_palloc(pool, n * size); + if (*list).part.elts.is_null() { + return NGX_ERROR as ngx_int_t; + } + (*list).part.nelts = 0; + (*list).part.next = ptr::null_mut(); + (*list).last = &raw mut (*list).part; + (*list).size = size; + (*list).nalloc = n; + (*list).pool = pool; + NGX_OK as ngx_int_t + } +} + +/// Add a key-value pair to an nginx table entry (`ngx_table_elt_t`) in the given nginx memory pool. +/// +/// # Arguments +/// +/// * `table` - A pointer to the nginx table entry (`ngx_table_elt_t`) to modify. +/// * `pool` - A pointer to the nginx memory pool (`ngx_pool_t`) for memory allocation. +/// * `key` - The key string to add to the table entry. +/// * `value` - The value string to add to the table entry. +/// +/// # Safety +/// This function is marked as unsafe because it involves raw pointer manipulation and direct memory +/// allocation using `str_to_uchar`. +/// +/// # Returns +/// An `Option<()>` representing the result of the operation. `Some(())` indicates success, while +/// `None` indicates a null table pointer. +/// +/// # Example +/// ```rust +/// # use nginx_sys::*; +/// # unsafe fn example(pool: *mut ngx_pool_t, headers: *mut ngx_list_t) { +/// // Obtain a pointer to the nginx table entry +/// let table: *mut ngx_table_elt_t = ngx_list_push(headers).cast(); +/// assert!(!table.is_null()); +/// let key: &str = "key"; // The key to add +/// let value: &str = "value"; // The value to add +/// let result = add_to_ngx_table(table, pool, key, value); +/// # } +/// ``` +pub unsafe fn add_to_ngx_table( + table: *mut ngx_table_elt_t, + pool: *mut ngx_pool_t, + key: impl AsRef<[u8]>, + value: impl AsRef<[u8]>, +) -> Option<()> { + if let Some(table) = unsafe { table.as_mut() } { + let key = key.as_ref(); + table.key = unsafe { ngx_str_t::from_bytes(pool, key)? }; + table.value = unsafe { ngx_str_t::from_bytes(pool, value.as_ref())? }; + table.lowcase_key = unsafe { ngx_pnalloc(pool, table.key.len).cast() }; + if table.lowcase_key.is_null() { + return None; + } + table.hash = unsafe { ngx_hash_strlow(table.lowcase_key, table.key.data, table.key.len) }; + return Some(()); + } + None +} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/mail.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/mail.rs new file mode 100644 index 0000000..7415fbe --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/mail.rs @@ -0,0 +1,13 @@ +use core::mem::offset_of; + +use crate::bindings::ngx_mail_conf_ctx_t; + +/// The offset of the `main_conf` field in the `ngx_mail_conf_ctx_t` struct. +/// +/// This is used to access the main configuration context for a MAIL module. +pub const NGX_MAIL_MAIN_CONF_OFFSET: usize = offset_of!(ngx_mail_conf_ctx_t, main_conf); + +/// The offset of the `srv_conf` field in the `ngx_mail_conf_ctx_t` struct. +/// +/// This is used to access the server configuration context for a MAIL module. +pub const NGX_MAIL_SRV_CONF_OFFSET: usize = offset_of!(ngx_mail_conf_ctx_t, srv_conf); diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/queue.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/queue.rs new file mode 100644 index 0000000..7dd3432 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/queue.rs @@ -0,0 +1,265 @@ +use core::ptr; + +use crate::bindings::ngx_queue_t; + +/// Get a reference to the beginning of a queue node data structure, +/// considering the queue field offset in it. +/// +/// # Safety +/// +/// `$q` must be a valid pointer to the field `$link` in the struct `$type` +#[macro_export] +macro_rules! ngx_queue_data { + ($q:expr, $type:path, $link:ident) => { + $q.byte_sub(::core::mem::offset_of!($type, $link)).cast::<$type>() + }; +} + +/// Initializes the queue head before use. +/// +/// # Safety +/// +/// `q` must be a valid pointer to [ngx_queue_t]. +#[inline] +pub unsafe fn ngx_queue_init(q: *mut ngx_queue_t) { + unsafe { + (*q).prev = q; + (*q).next = q; + } +} + +/// Returns `true` if the queue contains no elements. +/// +/// # Safety +/// +/// `q` must be a valid pointer to [ngx_queue_t], initialized with [ngx_queue_init]. +#[inline] +pub unsafe fn ngx_queue_empty(q: *const ngx_queue_t) -> bool { + unsafe { ptr::eq(q, (*q).prev) } +} + +/// Inserts a new node after the current. +/// +/// # Safety +/// +/// Both `q` and `x` must be valid pointers to [ngx_queue_t] +#[inline] +pub unsafe fn ngx_queue_insert_after(q: *mut ngx_queue_t, x: *mut ngx_queue_t) { + unsafe { + (*x).next = (*q).next; + (*(*x).next).prev = x; + (*x).prev = q; + (*q).next = x; + } +} + +/// Inserts a new node before the current. +/// +/// # Safety +/// +/// Both `q` and `x` must be valid pointers to [ngx_queue_t]. +#[inline] +pub unsafe fn ngx_queue_insert_before(q: *mut ngx_queue_t, x: *mut ngx_queue_t) { + unsafe { + (*x).prev = (*q).prev; + (*(*x).prev).next = x; + (*x).next = q; + (*q).prev = x; + } +} + +/// Removes a node from the queue. +/// +/// # Safety +/// +/// `q` must be a valid pointer to an [ngx_queue_t] node. +#[inline] +pub unsafe fn ngx_queue_remove(q: *mut ngx_queue_t) { + unsafe { + (*(*q).next).prev = (*q).prev; + (*(*q).prev).next = (*q).next; + (*q).prev = ptr::null_mut(); + (*q).next = ptr::null_mut(); + } +} + +/// Splits a queue at a node, returning the queue tail in a separate queue. +/// +/// # Safety +/// +/// `h` must be a valid pointer to a head queue node. +/// `q` must be a node in the queue `h`. +/// `n` must be a valid pointer to [ngx_queue_t]. +#[inline] +pub unsafe fn ngx_queue_split(h: *mut ngx_queue_t, q: *mut ngx_queue_t, n: *mut ngx_queue_t) { + unsafe { + (*n).prev = (*h).prev; + (*(*n).prev).next = n; + (*n).next = q; + (*h).prev = (*q).prev; + (*(*h).prev).next = h; + (*q).prev = n; + } +} + +/// Adds a second queue to the first queue. +/// +/// # Safety +/// +/// Both `h` and `n` must be valid pointers to queue heads, initialized with [ngx_queue_init]. +/// `n` will be left in invalid state, pointing to the subrange of `h` without back references. +#[inline] +pub unsafe fn ngx_queue_add(h: *mut ngx_queue_t, n: *mut ngx_queue_t) { + unsafe { + (*(*h).prev).next = (*n).next; + (*(*n).next).prev = (*h).prev; + (*h).prev = (*n).prev; + (*(*h).prev).next = h; + } +} + +impl ngx_queue_t { + /// Returns `true` if the queue contains no elements. + pub fn is_empty(&self) -> bool { + unsafe { ngx_queue_empty(self) } + } +} + +impl Default for ngx_queue_t { + fn default() -> ngx_queue_t { + ngx_queue_t { prev: ptr::null_mut(), next: ptr::null_mut() } + } +} + +#[cfg(test)] +mod tests { + extern crate alloc; + use alloc::boxed::Box; + + use super::*; + + struct TestData { + value: usize, + queue: ngx_queue_t, + } + + impl TestData { + pub fn new(value: usize) -> *mut Self { + // We should be using `ngx_pool_t` here, but that is not possible without linking to + // the nginx + let mut x = Box::new(Self { value, queue: Default::default() }); + unsafe { ngx_queue_init(&raw mut x.queue) }; + Box::into_raw(x) + } + + pub unsafe fn free(x: *mut Self) { + unsafe { + let _ = Box::from_raw(x); + } + } + } + + impl Drop for TestData { + fn drop(&mut self) { + if !self.queue.next.is_null() && !self.queue.is_empty() { + unsafe { ngx_queue_remove(&raw mut self.queue) }; + } + } + } + + struct Iter { + h: *mut ngx_queue_t, + q: *mut ngx_queue_t, + next: fn(*mut ngx_queue_t) -> *mut ngx_queue_t, + } + + impl Iter { + pub fn new(h: *mut ngx_queue_t) -> Self { + let next = |x: *mut ngx_queue_t| unsafe { (*x).next }; + Self { h, q: next(h), next } + } + + pub fn new_reverse(h: *mut ngx_queue_t) -> Self { + let next = |x: *mut ngx_queue_t| unsafe { (*x).prev }; + Self { h, q: next(h), next } + } + } + + impl Iterator for Iter { + type Item = *mut ngx_queue_t; + + fn next(&mut self) -> Option { + if ptr::eq(self.h, self.q) { + return None; + } + + let item = self.q; + self.q = (self.next)(self.q); + Some(item) + } + } + + #[test] + fn test_queue() { + fn value(q: *mut ngx_queue_t) -> usize { + unsafe { (*ngx_queue_data!(q, TestData, queue)).value } + } + + // Check forward and reverse iteration + fn cmp(h: *mut ngx_queue_t, other: &[usize]) -> bool { + Iter::new(h).map(value).eq(other.iter().cloned()) + && Iter::new_reverse(h).map(value).eq(other.iter().rev().cloned()) + } + + // Note how this test does not use references or borrows to avoid triggering UBs + // detectable by Miri. This does not mean that the code is safe or sound. + unsafe { + // Initialize and fill the queue + + let mut h1 = ngx_queue_t::default(); + ngx_queue_init(&raw mut h1); + + let mut h2 = ngx_queue_t::default(); + ngx_queue_init(&raw mut h2); + + for i in 1..=5 { + let elem = TestData::new(i); + ngx_queue_insert_before(&raw mut h1, &raw mut (*elem).queue); + + let elem = TestData::new(i); + ngx_queue_insert_after(&raw mut h2, &raw mut (*elem).queue); + } + + // Iterate and test the values + + assert!(cmp(&raw mut h1, &[1, 2, 3, 4, 5])); + assert!(cmp(&raw mut h2, &[5, 4, 3, 2, 1])); + + // Move nodes from h2 to h1 + + // h2 still points to the subrange of h1 after this operation + ngx_queue_add(&raw mut h1, &raw mut h2); + + assert!(cmp(&raw mut h1, &[1, 2, 3, 4, 5, 5, 4, 3, 2, 1])); + + ngx_queue_split(&raw mut h1, (*h2.next).next, &raw mut h2); + + assert!(cmp(&raw mut h1, &[1, 2, 3, 4, 5, 5])); + assert!(cmp(&raw mut h2, &[4, 3, 2, 1])); + + // Cleanup + + for q in Iter::new(&raw mut h1) { + let td = ngx_queue_data!(q, TestData, queue); + TestData::free(td); + } + assert!(h1.is_empty()); + + for q in Iter::new(&raw mut h2) { + let td = ngx_queue_data!(q, TestData, queue); + TestData::free(td); + } + assert!(h2.is_empty()); + }; + } +} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/rbtree.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/rbtree.rs new file mode 100644 index 0000000..daa28c4 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/rbtree.rs @@ -0,0 +1,85 @@ +use core::ptr; + +use crate::bindings::{ngx_rbtree_insert_pt, ngx_rbtree_node_t, ngx_rbtree_t}; + +/// Get a reference to the beginning of a tree element data structure, +/// considering the link field offset in it. +/// +/// # Safety +/// +/// `$node` must be a valid pointer to the field `$link` in the struct `$type` +#[macro_export] +macro_rules! ngx_rbtree_data { + ($node:expr, $type:path, $link:ident) => { + $node.byte_sub(::core::mem::offset_of!($type, $link)).cast::<$type>() + }; +} + +/// Initializes the RbTree with specified sentinel and insert function. +/// +/// # Safety +/// +/// All of the pointers passed must be valid. +/// `sentinel` is expected to be valid for the whole lifetime of the `tree`. +pub unsafe fn ngx_rbtree_init( + tree: *mut ngx_rbtree_t, + sentinel: *mut ngx_rbtree_node_t, + insert: ngx_rbtree_insert_pt, +) { + unsafe { + ngx_rbtree_sentinel_init(sentinel); + (*tree).root = sentinel; + (*tree).sentinel = sentinel; + (*tree).insert = insert; + } +} + +/// Marks the tree node as red. +/// +/// # Safety +/// +/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. +#[inline] +pub unsafe fn ngx_rbt_red(node: *mut ngx_rbtree_node_t) { + unsafe { (*node).color = 1 } +} + +/// Marks the tree node as black. +/// +/// # Safety +/// +/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. +#[inline] +pub unsafe fn ngx_rbt_black(node: *mut ngx_rbtree_node_t) { + unsafe { (*node).color = 0 } +} + +/// Initializes the sentinel node. +/// +/// # Safety +/// +/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. +#[inline] +pub unsafe fn ngx_rbtree_sentinel_init(node: *mut ngx_rbtree_node_t) { + unsafe { ngx_rbt_black(node) } +} + +/// Returns the least (leftmost) node of the tree. +/// +/// # Safety +/// +/// `node` must be a valid pointer to a [ngx_rbtree_node_t]. +/// `sentinel` must be a valid pointer to the sentinel node in the same Red-Black tree. +#[inline] +pub unsafe fn ngx_rbtree_min( + mut node: *mut ngx_rbtree_node_t, + sentinel: *mut ngx_rbtree_node_t, +) -> *mut ngx_rbtree_node_t { + unsafe { + while !ptr::addr_eq((*node).left, sentinel) { + node = (*node).left; + } + + node + } +} diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/stream.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/stream.rs new file mode 100644 index 0000000..6288fd4 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/stream.rs @@ -0,0 +1,13 @@ +use core::mem::offset_of; + +use crate::bindings::ngx_stream_conf_ctx_t; + +/// The offset of the `main_conf` field in the `ngx_stream_conf_ctx_t` struct. +/// +/// This is used to access the main configuration context for a STREAM module. +pub const NGX_STREAM_MAIN_CONF_OFFSET: usize = offset_of!(ngx_stream_conf_ctx_t, main_conf); + +/// The offset of the `srv_conf` field in the `ngx_stream_conf_ctx_t` struct. +/// +/// This is used to access the server configuration context for a STREAM module. +pub const NGX_STREAM_SRV_CONF_OFFSET: usize = offset_of!(ngx_stream_conf_ctx_t, srv_conf); diff --git a/source/rust/vendor/ngx-rust/nginx-sys/src/string.rs b/source/rust/vendor/ngx-rust/nginx-sys/src/string.rs new file mode 100644 index 0000000..a05d285 --- /dev/null +++ b/source/rust/vendor/ngx-rust/nginx-sys/src/string.rs @@ -0,0 +1,233 @@ +use core::cmp; +use core::fmt; +use core::hash; +use core::ptr; +use core::slice; +use core::str; + +use crate::bindings::{ngx_pool_t, ngx_str_t}; +use crate::detail; + +impl ngx_str_t { + /// Returns the contents of this `ngx_str_t` as a byte slice. + /// + /// The returned slice will **not** contain the optional nul terminator that `ngx_str_t.data` + /// may have. + #[inline] + pub fn as_bytes(&self) -> &[u8] { + if self.is_empty() { + &[] + } else { + // SAFETY: `ngx_str_t` with non-zero len must contain a valid correctly aligned pointer + unsafe { slice::from_raw_parts(self.data, self.len) } + } + } + + /// Returns the contents of this `ngx_str_t` as a mutable byte slice. + #[inline] + pub fn as_bytes_mut(&mut self) -> &mut [u8] { + if self.is_empty() { + &mut [] + } else { + // SAFETY: `ngx_str_t` with non-zero len must contain a valid correctly aligned pointer + unsafe { slice::from_raw_parts_mut(self.data, self.len) } + } + } + + /// Returns `true` if the string has a length of 0. + #[inline] + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Returns the contents of this `ngx_str_t` a string slice (`&str`) if + /// the contents are utf-8 encoded. + /// + /// # Returns + /// A string slice (`&str`) representing the nginx string, or else a + /// Utf8Error. + pub fn to_str(&self) -> Result<&str, str::Utf8Error> { + str::from_utf8(self.as_bytes()) + } + + /// Creates an empty `ngx_str_t` instance. + /// + /// This method replaces the `ngx_null_string` C macro. + pub const fn empty() -> Self { + ngx_str_t { len: 0, data: ptr::null_mut() } + } + + /// Create an `ngx_str_t` instance from a byte slice. + /// + /// # Safety + /// + /// The caller must provide a valid pointer to a memory pool. + pub unsafe fn from_bytes(pool: *mut ngx_pool_t, src: &[u8]) -> Option { + unsafe { detail::bytes_to_uchar(pool, src).map(|data| Self { data, len: src.len() }) } + } + + /// Create an `ngx_str_t` instance from a string slice (`&str`). + /// + /// # Arguments + /// + /// * `pool` - A pointer to the nginx memory pool (`ngx_pool_t`). + /// * `data` - The string slice from which to create the nginx string. + /// + /// # Safety + /// This function is marked as unsafe because it accepts a raw pointer argument. There is no + /// way to know if `pool` is pointing to valid memory. The caller must provide a valid pool to + /// avoid indeterminate behavior. + /// + /// # Returns + /// An `ngx_str_t` instance representing the given string slice. + pub unsafe fn from_str(pool: *mut ngx_pool_t, data: &str) -> Self { + unsafe { ngx_str_t { data: detail::str_to_uchar(pool, data), len: data.len() } } + } + + /// Divides one `ngx_str_t` into two at an index. + /// + /// # Safety + /// + /// The results will reference the original string; be wary of the ownership and lifetime. + pub fn split_at(&self, mid: usize) -> Option<(ngx_str_t, ngx_str_t)> { + if mid > self.len { + return None; + } + + Some(( + ngx_str_t { data: self.data, len: mid }, + ngx_str_t { data: unsafe { self.data.add(mid) }, len: self.len - mid }, + )) + } + + /// Returns an `ngx_str_t` with the prefix removed. + /// + /// If the string starts with the byte sequence `prefix`, returns the substring after the + /// prefix, wrapped in `Some`. The resulting substring can be empty. + /// + /// # Safety + /// + /// The result will reference the original string; be wary of the ownership and lifetime. + /// + /// The method is not marked as `unsafe` as everything it does is possible via safe interfaces. + pub fn strip_prefix(&self, prefix: impl AsRef<[u8]>) -> Option { + let prefix = prefix.as_ref(); + if self.as_bytes().starts_with(prefix) { + self.split_at(prefix.len()).map(|x| x.1) + } else { + None + } + } + + /// Returns an `ngx_str_t` with the suffix removed. + /// + /// If the string ends with the byte sequence `suffix`, returns the substring before the + /// suffix, wrapped in `Some`. The resulting substring can be empty. + /// + /// # Safety + /// + /// The result will reference the original string; be wary of the ownership and lifetime. + /// + /// The method is not marked as `unsafe` as everything it does is possible via safe interfaces. + pub fn strip_suffix(&self, suffix: impl AsRef<[u8]>) -> Option { + let suffix = suffix.as_ref(); + if self.as_bytes().ends_with(suffix) { + self.split_at(self.len - suffix.len()).map(|x| x.0) + } else { + None + } + } +} + +impl AsRef<[u8]> for ngx_str_t { + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + +impl AsMut<[u8]> for ngx_str_t { + fn as_mut(&mut self) -> &mut [u8] { + self.as_bytes_mut() + } +} + +impl Default for ngx_str_t { + fn default() -> Self { + Self::empty() + } +} + +impl fmt::Display for ngx_str_t { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + detail::display_bytes(f, self.as_bytes()) + } +} + +impl From for &[u8] { + fn from(s: ngx_str_t) -> Self { + if s.len == 0 || s.data.is_null() { + return Default::default(); + } + unsafe { slice::from_raw_parts(s.data, s.len) } + } +} + +impl hash::Hash for ngx_str_t { + fn hash(&self, state: &mut H) { + self.as_bytes().hash(state) + } +} + +impl PartialEq for ngx_str_t { + fn eq(&self, other: &Self) -> bool { + PartialEq::eq(self.as_bytes(), other.as_bytes()) + } +} + +impl Eq for ngx_str_t {} + +impl PartialOrd for ngx_str_t { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for ngx_str_t { + fn cmp(&self, other: &Self) -> cmp::Ordering { + Ord::cmp(self.as_bytes(), other.as_bytes()) + } +} + +impl TryFrom for &str { + type Error = str::Utf8Error; + + fn try_from(s: ngx_str_t) -> Result { + str::from_utf8(s.into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ngx_str_prefix() { + let s = "key=value"; + let s = ngx_str_t { data: s.as_ptr().cast_mut(), len: s.len() }; + + assert_eq!( + s.strip_prefix("key=").as_ref().map(ngx_str_t::as_bytes), + Some("value".as_bytes()) + ); + + assert_eq!(s.strip_prefix("test"), None); + + assert_eq!( + s.strip_suffix("value").as_ref().map(ngx_str_t::as_bytes), + Some("key=".as_bytes()) + ); + + assert_eq!(s.strip_suffix("test"), None); + } +} diff --git a/source/rust/vendor/ngx-rust/rustfmt.toml b/source/rust/vendor/ngx-rust/rustfmt.toml new file mode 100644 index 0000000..f1b45de --- /dev/null +++ b/source/rust/vendor/ngx-rust/rustfmt.toml @@ -0,0 +1,9 @@ +edition = "2024" +max_width = 100 +use_small_heuristics = "Max" + +# unstable options: +# comment_width = 100 +# group_imports = "StdExternalCrate" +# format_strings = true +# wrap_comments = true \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/src/allocator.rs b/source/rust/vendor/ngx-rust/src/allocator.rs new file mode 100644 index 0000000..d5702ff --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/allocator.rs @@ -0,0 +1,81 @@ +//! The allocator module. +//! +//! The module provides custom memory allocator support traits and utilities based on the unstable +//! [feature(allocator_api)]. +//! +//! Currently implemented as a reexport of parts of the [allocator_api2]. +//! +//! [feature(allocator_api)]: https://github.com/rust-lang/rust/issues/32838 + +use ::core::alloc::Layout; +use ::core::mem; +use ::core::ptr::{self, NonNull}; +pub use allocator_api2::alloc::{AllocError, Allocator}; +#[cfg(feature = "alloc")] +pub use allocator_api2::{alloc::Global, boxed::Box, unsize_box}; + +/// Explicitly duplicate an object using the specified Allocator. +pub trait TryCloneIn: Sized { + /// Target type, generic over an allocator. + type Target; + + /// Attempts to copy the value using `alloc` as an underlying Allocator. + fn try_clone_in(&self, alloc: A) -> Result, AllocError>; +} + +/// Moves `value` to the memory backed by `alloc` and returns a pointer. +/// +/// This should be similar to `Box::into_raw(Box::try_new_in(value, alloc)?)`, except without +/// `alloc` requirement and intermediate steps. +/// +/// # Note +/// +/// The resulting pointer has no owner. The caller is responsible for destroying `T` and releasing +/// the memory. +pub fn allocate(value: T, alloc: &A) -> Result, AllocError> +where + A: Allocator, +{ + let layout = Layout::for_value(&value); + let ptr: NonNull = alloc.allocate(layout)?.cast(); + + // SAFETY: the allocator succeeded and gave us a correctly aligned pointer to an uninitialized + // data + unsafe { ptr.cast::>().as_mut().write(value) }; + + Ok(ptr) +} +/// +/// Creates a [NonNull] that is dangling, but well-aligned for this [Layout]. +/// +/// See also [::core::alloc::Layout::dangling()] +#[inline(always)] +pub(crate) const fn dangling_for_layout(layout: &Layout) -> NonNull { + unsafe { + let ptr = ptr::null_mut::().byte_add(layout.align()); + NonNull::new_unchecked(ptr) + } +} + +#[cfg(feature = "alloc")] +mod impls { + use allocator_api2::boxed::Box; + + use super::*; + + impl TryCloneIn for Box + where + T: TryCloneIn, + OA: Allocator, + { + type Target = Box<::Target, A>; + + fn try_clone_in( + &self, + alloc: A, + ) -> Result, AllocError> { + let x = self.as_ref().try_clone_in(alloc.clone())?; + Box::try_new_in(x, alloc) + } + } +} diff --git a/source/rust/vendor/ngx-rust/src/async_/mod.rs b/source/rust/vendor/ngx-rust/src/async_/mod.rs new file mode 100644 index 0000000..3ec7832 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/async_/mod.rs @@ -0,0 +1,8 @@ +//! Async runtime and set of utilities on top of the NGINX event loop. +pub use self::sleep::{Sleep, sleep}; +pub use self::spawn::{Task, spawn}; + +pub mod resolver; + +mod sleep; +mod spawn; diff --git a/source/rust/vendor/ngx-rust/src/async_/resolver.rs b/source/rust/vendor/ngx-rust/src/async_/resolver.rs new file mode 100644 index 0000000..53bf55c --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/async_/resolver.rs @@ -0,0 +1,328 @@ +// Copyright (c) F5, Inc. +// +// This source code is licensed under the Apache License, Version 2.0 license found in the +// LICENSE file in the root directory of this source tree. + +//! Wrapper for the nginx resolver. +//! +//! See . + +use alloc::string::{String, ToString}; +use core::ffi::c_void; +use core::fmt; +use core::num::NonZero; +use core::pin::Pin; +use core::ptr::NonNull; +use core::task::{Context, Poll, Waker}; + +use nginx_sys::{ + NGX_NO_RESOLVER, NGX_RESOLVE_FORMERR, NGX_RESOLVE_NOTIMP, NGX_RESOLVE_NXDOMAIN, + NGX_RESOLVE_REFUSED, NGX_RESOLVE_SERVFAIL, NGX_RESOLVE_TIMEDOUT, +}; + +use crate::{ + allocator::Box, + collections::Vec, + core::{Pool, Status}, + ffi::{ + ngx_addr_t, ngx_msec_t, ngx_resolve_name, ngx_resolve_start, ngx_resolver_ctx_t, + ngx_resolver_t, ngx_str_t, + }, +}; + +/// Error type for all uses of `Resolver`. +#[derive(Debug)] +pub enum Error { + /// No resolver configured + NoResolver, + /// Resolver error, with context of name being resolved + Resolver(ResolverError, String), + /// Allocation failed + AllocationFailed, + /// Unknown internal error while starting name resolution + Internal, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Error::NoResolver => write!(f, "No resolver configured"), + Error::Resolver(err, context) => write!(f, "{err}: resolving `{context}`"), + Error::AllocationFailed => write!(f, "Allocation failed"), + Error::Internal => write!(f, "Internal error"), + } + } +} +impl core::error::Error for Error {} + +/// These cases directly reflect the NGX_RESOLVE_ error codes, +/// plus a timeout, and a case for an unknown error where a known +/// NGX_RESOLVE_ should be. +#[derive(Debug)] +pub enum ResolverError { + /// Format error (NGX_RESOLVE_FORMERR) + FormErr, + /// Server failure (NGX_RESOLVE_SERVFAIL) + ServFail, + /// Host not found (NGX_RESOLVE_NXDOMAIN) + NXDomain, + /// Unimplemented (NGX_RESOLVE_NOTIMP) + NotImp, + /// Operation refused (NGX_RESOLVE_REFUSED) + Refused, + /// Timed out (NGX_RESOLVE_TIMEDOUT) + TimedOut, + /// Unknown NGX_RESOLVE error + Unknown(isize), +} +impl fmt::Display for ResolverError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ResolverError::FormErr => write!(f, "Format error"), + ResolverError::ServFail => write!(f, "Server Failure"), + ResolverError::NXDomain => write!(f, "Host not found"), + ResolverError::NotImp => write!(f, "Unimplemented"), + ResolverError::Refused => write!(f, "Refused"), + ResolverError::TimedOut => write!(f, "Timed out"), + ResolverError::Unknown(code) => write!(f, "Unknown NGX_RESOLVE error {code}"), + } + } +} +impl core::error::Error for ResolverError {} + +/// Convert from the NGX_RESOLVE_ error codes. +impl From> for ResolverError { + fn from(code: NonZero) -> ResolverError { + match code.get() as u32 { + NGX_RESOLVE_FORMERR => ResolverError::FormErr, + NGX_RESOLVE_SERVFAIL => ResolverError::ServFail, + NGX_RESOLVE_NXDOMAIN => ResolverError::NXDomain, + NGX_RESOLVE_NOTIMP => ResolverError::NotImp, + NGX_RESOLVE_REFUSED => ResolverError::Refused, + NGX_RESOLVE_TIMEDOUT => ResolverError::TimedOut, + _ => ResolverError::Unknown(code.get()), + } + } +} + +type Res = Result, Error>; + +/// A wrapper for an ngx_resolver_t which provides an async Rust API +pub struct Resolver { + resolver: NonNull, + timeout: ngx_msec_t, +} + +impl Resolver { + /// Create a new `Resolver` from existing pointer to `ngx_resolver_t` and + /// timeout. + pub fn from_resolver(resolver: NonNull, timeout: ngx_msec_t) -> Self { + Self { resolver, timeout } + } + + /// Resolve a name into a set of addresses. + pub async fn resolve_name(&self, name: &ngx_str_t, pool: &Pool) -> Res { + let mut resolver = Resolution::new(name, &ngx_str_t::empty(), self, pool)?; + resolver.as_mut().await + } + + /// Resolve a service into a set of addresses. + pub async fn resolve_service(&self, name: &ngx_str_t, service: &ngx_str_t, pool: &Pool) -> Res { + let mut resolver = Resolution::new(name, service, self, pool)?; + resolver.as_mut().await + } +} + +struct Resolution<'a> { + // Storage for the result of the resolution `Res`. Populated by the + // callback handler, and taken by the Future::poll impl. + complete: Option, + // Storage for a pending Waker. Populated by the Future::poll impl, + // and taken by the callback handler. + waker: Option, + // Pool used for allocating `Vec` contents in `Res`. Read by + // the callback handler. + pool: &'a Pool, + // Owned pointer to the ngx_resolver_ctx_t. + ctx: Option, +} + +impl<'a> Resolution<'a> { + pub fn new( + name: &ngx_str_t, + service: &ngx_str_t, + resolver: &Resolver, + pool: &'a Pool, + ) -> Result>, Error> { + // Create a pinned Resolution on the Pool, so that we can make + // a stable pointer to the Resolution struct. + let mut this = + Box::pin_in(Resolution { complete: None, waker: None, pool, ctx: None }, pool.clone()); + + // Set up the ctx with everything the resolver needs to resolve a + // name, and the handler callback which is called on completion. + let mut ctx = ResolverCtx::new(resolver.resolver)?; + ctx.name = *name; + ctx.service = *service; + ctx.timeout = resolver.timeout; + ctx.set_cancelable(1); + ctx.handler = Some(Self::handler); + + { + // Safety: Self::handler, Future::poll, and Drop::drop will have + // access to &mut Resolution. Nginx is single-threaded and we are + // assured only one of those is on the stack at a time, except if + // Self::handler wakes a task which polls or drops the Future, + // which it only does after use of &mut Resolution is complete. + let ptr: &mut Resolution = unsafe { Pin::into_inner_unchecked(this.as_mut()) }; + ctx.data = ptr as *mut Resolution as *mut c_void; + } + + // Neither ownership nor borrows are tracked for this pointer, + // and ctxp will not be used after the ctx destruction. + let ctxp = ctx.0; + this.ctx = Some(ctx); + + // Start name resolution using the ctx. If the name is in the dns + // cache, the handler may get called from this stack. Otherwise, it + // will be called later by nginx when it gets a dns response or a + // timeout. + let ret = unsafe { Status(ngx_resolve_name(ctxp.as_ptr())) }; + if !ret.is_ok() { + // ngx_resolve_name will free the context on error. + core::mem::forget(this.ctx.take()); + return Err(Error::Internal); + } + + Ok(this) + } + + // Nginx will call this handler when name resolution completes. If the + // result is in the cache, this could be called from inside ngx_resolve_name. + // Otherwise, it will be called later on the event loop. + unsafe extern "C" fn handler(ctx: *mut ngx_resolver_ctx_t) { + let mut data = unsafe { NonNull::new_unchecked((*ctx).data as *mut Resolution) }; + let this: &mut Resolution = unsafe { data.as_mut() }; + + if let Some(ctx) = this.ctx.take() { + this.complete = Some(ctx.into_result(this.pool)); + } + + // Wake last, after all use of &mut Resolution, because wake may + // poll Resolution future on current stack. + if let Some(waker) = this.waker.take() { + waker.wake(); + } + } +} + +impl core::future::Future for Resolution<'_> { + type Output = Result, Error>; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + // Resolution is Unpin, so we can use it as just a &mut Resolution + let this: &mut Resolution = self.get_mut(); + + // The handler populates this.complete, and we consume it here: + match this.complete.take() { + Some(res) => Poll::Ready(res), + None => { + // If the handler has not yet fired, populate the waker field, + // which the handler will consume: + match &mut this.waker { + None => { + this.waker = Some(cx.waker().clone()); + } + Some(w) => w.clone_from(cx.waker()), + } + Poll::Pending + } + } + } +} + +/// An owned ngx_resolver_ctx_t. +struct ResolverCtx(NonNull); + +impl core::ops::Deref for ResolverCtx { + type Target = ngx_resolver_ctx_t; + + fn deref(&self) -> &Self::Target { + // SAFETY: this wrapper is always constructed with a valid non-empty resolve context + unsafe { self.0.as_ref() } + } +} + +impl core::ops::DerefMut for ResolverCtx { + fn deref_mut(&mut self) -> &mut Self::Target { + // SAFETY: this wrapper is always constructed with a valid non-empty resolve context + unsafe { self.0.as_mut() } + } +} + +impl Drop for ResolverCtx { + fn drop(&mut self) { + unsafe { + nginx_sys::ngx_resolve_name_done(self.0.as_mut()); + } + } +} + +impl ResolverCtx { + /// Creates a new resolver context. + /// + /// This implementation currently passes a null for the second argument `temp`. A non-null + /// `temp` provides a fast, non-callback-based path for immediately returning an addr if + /// `temp` contains a name which is textual form of an addr. + pub fn new(resolver: NonNull) -> Result { + let ctx = unsafe { ngx_resolve_start(resolver.as_ptr(), core::ptr::null_mut()) }; + if ctx == NGX_NO_RESOLVER { + return Err(Error::NoResolver); + } + NonNull::new(ctx).map(Self).ok_or(Error::AllocationFailed) + } + + /// Take the results in a ctx and make an owned copy as a + /// Result, Error>, where the Vec and the internals + /// of the ngx_addr_t are allocated on the given Pool + pub fn into_result(self, pool: &Pool) -> Result, Error> { + if let Some(e) = NonZero::new(self.state) { + return Err(Error::Resolver(ResolverError::from(e), self.name.to_string())); + } + if self.addrs.is_null() { + Err(Error::AllocationFailed)?; + } + + let mut out = Vec::new_in(pool.clone()); + + if self.naddrs > 0 { + out.try_reserve_exact(self.naddrs).map_err(|_| Error::AllocationFailed)?; + + for addr in unsafe { core::slice::from_raw_parts(self.addrs, self.naddrs) } { + out.push(copy_resolved_addr(addr, pool)?); + } + } + + Ok(out) + } +} + +/// Take the contents of an ngx_resolver_addr_t and make an owned copy as +/// an ngx_addr_t, using the Pool for allocation of the internals. +fn copy_resolved_addr( + addr: &nginx_sys::ngx_resolver_addr_t, + pool: &Pool, +) -> Result { + let sockaddr = pool.alloc(addr.socklen as usize) as *mut nginx_sys::sockaddr; + if sockaddr.is_null() { + Err(Error::AllocationFailed)?; + } + unsafe { + addr.sockaddr.cast::().copy_to_nonoverlapping(sockaddr.cast(), addr.socklen as usize) + }; + + let name = unsafe { ngx_str_t::from_bytes(pool.as_ptr(), addr.name.as_bytes()) } + .ok_or(Error::AllocationFailed)?; + + Ok(ngx_addr_t { sockaddr, socklen: addr.socklen, name }) +} diff --git a/source/rust/vendor/ngx-rust/src/async_/sleep.rs b/source/rust/vendor/ngx-rust/src/async_/sleep.rs new file mode 100644 index 0000000..39feded --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/async_/sleep.rs @@ -0,0 +1,135 @@ +use core::future::Future; +use core::mem; +use core::pin::Pin; +use core::ptr::NonNull; +use core::task::{self, Poll}; +use core::time::Duration; + +use nginx_sys::{ngx_add_timer, ngx_del_timer, ngx_event_t, ngx_log_t, ngx_msec_int_t, ngx_msec_t}; +use pin_project_lite::pin_project; + +use crate::{ngx_container_of, ngx_log_debug}; + +/// Maximum duration that can be achieved using [ngx_add_timer]. +const NGX_TIMER_DURATION_MAX: Duration = Duration::from_millis(ngx_msec_int_t::MAX as _); + +/// Puts the current task to sleep for at least the specified amount of time. +/// +/// The function is a shorthand for [Sleep::new] using the global logger for debug output. +#[inline] +pub fn sleep(duration: Duration) -> Sleep { + Sleep::new(duration, crate::log::ngx_cycle_log()) +} + +pin_project! { +/// Future returned by [sleep]. +pub struct Sleep { + #[pin] + timer: TimerEvent, + duration: Duration, +} +} + +impl Sleep { + /// Creates a new Sleep with the specified duration and logger for debug messages. + pub fn new(duration: Duration, log: NonNull) -> Self { + let timer = TimerEvent::new(log); + ngx_log_debug!(timer.event.log, "async: sleep for {duration:?}"); + Sleep { timer, duration } + } +} + +impl Future for Sleep { + type Output = (); + + #[cfg(not(target_pointer_width = "32"))] + fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll { + let msec = self.duration.min(NGX_TIMER_DURATION_MAX).as_millis() as ngx_msec_t; + let this = self.project(); + this.timer.poll_sleep(msec, cx) + } + + #[cfg(target_pointer_width = "32")] + fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll { + if self.duration.is_zero() { + return Poll::Ready(()); + } + let step = self.duration.min(NGX_TIMER_DURATION_MAX); + + let mut this = self.project(); + // Handle ngx_msec_t overflow on 32-bit platforms. + match this.timer.as_mut().poll_sleep(step.as_millis() as _, cx) { + // Last step + Poll::Ready(()) if this.duration == &step => Poll::Ready(()), + Poll::Ready(()) => { + *this.duration = this.duration.saturating_sub(step); + this.timer.event.set_timedout(0); // rearm + this.timer.as_mut().poll_sleep(step.as_millis() as _, cx) + } + x => x, + } + } +} + +struct TimerEvent { + event: ngx_event_t, + waker: Option, +} + +// SAFETY: Timer will only be used in a single-threaded environment +unsafe impl Send for TimerEvent {} +unsafe impl Sync for TimerEvent {} + +impl TimerEvent { + pub fn new(log: NonNull) -> Self { + static IDENT: [usize; 4] = [ + 0, 0, 0, 0x4153594e, // ASYN + ]; + + let mut ev: ngx_event_t = unsafe { mem::zeroed() }; + // The data is only used for `ngx_event_ident` and will not be mutated. + ev.data = (&raw const IDENT).cast_mut().cast(); + ev.handler = Some(Self::timer_handler); + ev.log = log.as_ptr(); + ev.set_cancelable(1); + + Self { event: ev, waker: None } + } + + pub fn poll_sleep( + mut self: Pin<&mut Self>, + duration: ngx_msec_t, + context: &mut task::Context<'_>, + ) -> Poll<()> { + if self.event.timedout() != 0 { + Poll::Ready(()) + } else if self.event.timer_set() != 0 { + if let Some(waker) = self.waker.as_mut() { + waker.clone_from(context.waker()); + } else { + self.waker = Some(context.waker().clone()); + } + Poll::Pending + } else { + unsafe { ngx_add_timer(&raw mut self.event, duration) }; + self.waker = Some(context.waker().clone()); + Poll::Pending + } + } + + unsafe extern "C" fn timer_handler(ev: *mut ngx_event_t) { + let timer = ngx_container_of!(ev, Self, event); + + if let Some(waker) = unsafe { (*timer).waker.take() } { + waker.wake(); + } + } +} + +impl Drop for TimerEvent { + fn drop(&mut self) { + if self.event.timer_set() != 0 { + unsafe { ngx_del_timer(&raw mut self.event) }; + } + } +} diff --git a/source/rust/vendor/ngx-rust/src/async_/spawn.rs b/source/rust/vendor/ngx-rust/src/async_/spawn.rs new file mode 100644 index 0000000..fa6008f --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/async_/spawn.rs @@ -0,0 +1,146 @@ +use alloc::collections::vec_deque::VecDeque; +use core::cell::UnsafeCell; +use core::future::Future; +use core::mem; +use core::ptr::{self, NonNull}; + +pub use async_task::Task; +use async_task::{Runnable, ScheduleInfo, WithInfo}; +use nginx_sys::{ + ngx_del_timer, ngx_delete_posted_event, ngx_event_t, ngx_post_event, ngx_posted_next_events, +}; + +use crate::log::ngx_cycle_log; +use crate::{ngx_container_of, ngx_log_debug}; + +static SCHEDULER: Scheduler = Scheduler::new(); + +struct Scheduler(UnsafeCell); + +// SAFETY: Scheduler must only be used from the main thread of a worker process. +unsafe impl Send for Scheduler {} +unsafe impl Sync for Scheduler {} + +impl Scheduler { + const fn new() -> Self { + Self(SchedulerInner::new()) + } + + pub fn schedule(&self, runnable: Runnable) { + // SAFETY: the cell is not empty, and we have exclusive access due to being a + // single-threaded application. + let inner = unsafe { &mut *UnsafeCell::raw_get(&raw const self.0) }; + inner.send(runnable) + } +} + +#[repr(C)] +struct SchedulerInner { + _ident: [usize; 4], // `ngx_event_ident` compatibility + event: ngx_event_t, + queue: VecDeque, +} + +impl SchedulerInner { + const fn new() -> UnsafeCell { + let mut event: ngx_event_t = unsafe { mem::zeroed() }; + event.handler = Some(Self::scheduler_event_handler); + + UnsafeCell::new(Self { + _ident: [ + 0, 0, 0, 0x4153594e, // ASYN + ], + event, + queue: VecDeque::new(), + }) + } + + pub fn send(&mut self, runnable: Runnable) { + // Cached `ngx_cycle.log` can be invalidated when reloading configuration in a single + // process mode. Update `log` every time to avoid using stale log pointer. + self.event.log = ngx_cycle_log().as_ptr(); + + // While this event is not used as a timer at the moment, we still want to ensure that it is + // compatible with `ngx_event_ident`. + if self.event.data.is_null() { + self.event.data = ptr::from_mut(self).cast(); + } + + // FIXME: VecDeque::push could panic on an allocation failure, switch to a datastructure + // which will not and propagate the failure. + self.queue.push_back(runnable); + unsafe { ngx_post_event(&raw mut self.event, &raw mut ngx_posted_next_events) } + } + + /// This event handler is called by ngx_event_process_posted at the end of + /// ngx_process_events_and_timers. + extern "C" fn scheduler_event_handler(ev: *mut ngx_event_t) { + let mut runnables = { + // SAFETY: + // This handler always receives a non-null pointer to an event embedded into a + // UnsafeCell instance. We modify the contents of the `UnsafeCell`, + // but we ensured that: + // - we access the cell correctly, as documented in https://doc.rust-lang.org/stable/std/cell/struct.UnsafeCell.html#memory-layout + // - the access is unique due to being single-threaded + // - the reference is dropped before we start processing queued runnables. + let cell: NonNull> = + ngx_container_of!(unsafe { NonNull::new_unchecked(ev) }, Self, event).cast(); + let this = unsafe { &mut *UnsafeCell::raw_get(cell.as_ptr()) }; + + ngx_log_debug!( + this.event.log, + "async: processing {} deferred wakeups", + this.queue.len() + ); + + // Move runnables to a new queue to avoid borrowing from the SchedulerInner and limit + // processing to already queued wakeups. This ensures that we correctly handle tasks + // that keep scheduling themselves (e.g. using yield_now() in a loop). + // We can't use drain() as it borrows from self and breaks aliasing rules. + mem::take(&mut this.queue) + }; + + for runnable in runnables.drain(..) { + runnable.run(); + } + } +} + +impl Drop for SchedulerInner { + fn drop(&mut self) { + if self.event.posted() != 0 { + unsafe { ngx_delete_posted_event(&raw mut self.event) }; + } + + if self.event.timer_set() != 0 { + unsafe { ngx_del_timer(&raw mut self.event) }; + } + } +} + +fn schedule(runnable: Runnable, _info: ScheduleInfo) { + // Always defer the wake via `ngx_post_event`; never re-poll synchronously. + // + // `Waker::wake()` may fire from arbitrary contexts, including a future's + // `Drop` while a lock is held (e.g. h2's `Streams::drop` wakes its parked + // `Connection` task while holding `Arc>`). A synchronous + // re-poll would re-enter the task and deadlock on that lock. Deferring + // costs one event-loop tick: `ngx_event_process_posted` drains the queue + // at the end of each cycle. + SCHEDULER.schedule(runnable); +} + +/// Creates a new task running on the NGINX event loop. +pub fn spawn(future: F) -> Task +where + F: Future + 'static, + T: 'static, +{ + ngx_log_debug!(ngx_cycle_log().as_ptr(), "async: spawning new task"); + let scheduler = WithInfo(schedule); + // Safety: single threaded embedding takes care of send/sync requirements for future and + // scheduler. Future and scheduler are both 'static. + let (runnable, task) = unsafe { async_task::spawn_unchecked(future, scheduler) }; + runnable.schedule(); + task +} diff --git a/source/rust/vendor/ngx-rust/src/collections/mod.rs b/source/rust/vendor/ngx-rust/src/collections/mod.rs new file mode 100644 index 0000000..ce36eb3 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/collections/mod.rs @@ -0,0 +1,16 @@ +//! Collection types. +//! +//! This module provides common collection types, mostly implemented as wrappers over the +//! corresponding NGINX types. + +#[cfg(feature = "alloc")] +pub use allocator_api2::{ + collections::{TryReserveError, TryReserveErrorKind}, + vec, // reexport both the module and the macro + vec::Vec, +}; +pub use queue::Queue; +pub use rbtree::RbTreeMap; + +pub mod queue; +pub mod rbtree; diff --git a/source/rust/vendor/ngx-rust/src/collections/queue.rs b/source/rust/vendor/ngx-rust/src/collections/queue.rs new file mode 100644 index 0000000..3adfe2a --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/collections/queue.rs @@ -0,0 +1,419 @@ +//! Types and utilities for working with [ngx_queue_t], an intrusive doubly-linked list. +//! +//! This module provides both the tools for interaction with the existing `ngx_queue_t` objects in +//! the NGINX, and useful high-level types built on top of the `ngx_queue_t`. +//! +//! See . + +use core::alloc::Layout; +use core::marker::PhantomData; +use core::mem; +use core::ptr::{self, NonNull}; + +use nginx_sys::{ + ngx_queue_data, ngx_queue_empty, ngx_queue_init, ngx_queue_insert_after, + ngx_queue_insert_before, ngx_queue_remove, ngx_queue_t, +}; + +use crate::allocator::{AllocError, Allocator}; + +/// Trait for pointer conversions between the queue entry and its container. +/// +/// # Safety +/// +/// This trait must only be implemented on types that contain a queue link or wrappers with +/// compatible layout. The type then can be used to access elements of a raw queue type +/// [NgxQueue] linked via specified field. +/// +/// If the struct can belong to several queues through multiple embedded `ngx_queue_t` fields, +/// a separate [NgxQueueEntry] implementation via wrapper type should be used for each queue. +pub unsafe trait NgxQueueEntry { + /// Gets a container pointer from queue node. + fn from_queue(queue: NonNull) -> NonNull; + /// Gets a queue node from a container reference. + fn to_queue(&mut self) -> &mut ngx_queue_t; +} + +unsafe impl NgxQueueEntry for ngx_queue_t { + fn from_queue(queue: NonNull) -> NonNull { + queue + } + + fn to_queue(&mut self) -> &mut ngx_queue_t { + self + } +} + +/// A wrapper over a raw `ngx_queue_t`, an intrusive doubly-linked list. +/// +/// This wrapper is defined in terms of type `T` that embeds and can be converted from or to the +/// list entries. +/// +/// Example: +/// ```rust,no_run +/// # use core::ptr::NonNull; +/// # use nginx_sys::{ngx_event_t, ngx_posted_events, ngx_queue_data, ngx_queue_t}; +/// # use ngx::collections::queue::{NgxQueue, NgxQueueEntry}; +/// // We need a wrapper type to define [NgxQueueEntry] on. +/// #[repr(transparent)] +/// struct PostedEvent(ngx_event_t); +/// +/// unsafe impl NgxQueueEntry for PostedEvent { +/// fn from_queue(queue: NonNull) -> NonNull { +/// // We can safely cast obtained ngx_event_t to a transparent wrapper. +/// unsafe { ngx_queue_data!(queue, ngx_event_t, queue) }.cast() +/// } +/// +/// fn to_queue(&mut self) -> &mut ngx_queue_t { +/// &mut self.0.queue +/// } +/// } +/// +/// // SAFETY: `ngx_posted_events` global static is a list of `ngx_event_t` linked via +/// // `ngx_event_t.queue`. +/// // NGINX is single-threaded, so we get exclusive access to the static. +/// let posted: &mut NgxQueue = +/// unsafe { NgxQueue::from_ptr_mut(&raw mut ngx_posted_events) }; +/// ``` +/// +/// See . +#[derive(Debug)] +#[repr(transparent)] +pub struct NgxQueue { + head: ngx_queue_t, + _type: PhantomData, +} + +impl NgxQueue +where + T: NgxQueueEntry, +{ + /// Creates a queue reference from a pointer to [ngx_queue_t]. + /// + /// # Safety + /// + /// `head` is a valid pointer to a list head, and `T::from_queue` on the list entries results in + /// valid pointers to `T`. + pub unsafe fn from_ptr<'a>(head: *const ngx_queue_t) -> &'a Self { + unsafe { &*head.cast() } + } + + /// Creates a mutable queue reference from a pointer to [ngx_queue_t]. + /// + /// # Safety + /// + /// `head` is a valid pointer to a list head, and `T::from_queue` on the list entries results in + /// valid pointers to `T`. + pub unsafe fn from_ptr_mut<'a>(head: *mut ngx_queue_t) -> &'a mut Self { + unsafe { &mut *head.cast() } + } + + /// Returns `true` if the queue contains no elements. + pub fn is_empty(&self) -> bool { + self.head.prev.is_null() || unsafe { ngx_queue_empty(&raw const self.head) } + } + + /// Appends an element to the end of the queue. + pub fn push_back(&mut self, entry: &mut T) { + if self.head.prev.is_null() { + unsafe { ngx_queue_init(&raw mut self.head) } + } + + unsafe { ngx_queue_insert_before(&raw mut self.head, entry.to_queue()) } + } + + /// Appends an element to the beginning of the queue. + pub fn push_front(&mut self, entry: &mut T) { + if self.head.prev.is_null() { + unsafe { ngx_queue_init(&raw mut self.head) } + } + + unsafe { ngx_queue_insert_after(&raw mut self.head, entry.to_queue()) } + } + + /// Returns an iterator over the entries of the queue. + pub fn iter(&self) -> NgxQueueIter<'_, T> { + NgxQueueIter::new(&self.head) + } + + /// Returns a mutable iterator over the entries of the queue. + pub fn iter_mut(&mut self) -> NgxQueueIterMut<'_, T> { + NgxQueueIterMut::new(&mut self.head) + } +} + +/// An iterator for the queue. +pub struct NgxQueueIter<'a, T> { + head: NonNull, + current: NonNull, + _lifetime: PhantomData<&'a T>, +} + +impl<'a, T> NgxQueueIter<'a, T> +where + T: NgxQueueEntry, +{ + /// Creates a new queue iterator. + pub fn new(head: &'a ngx_queue_t) -> Self { + let head = NonNull::from(head); + NgxQueueIter { head, current: head, _lifetime: PhantomData } + } +} + +impl<'a, T> Iterator for NgxQueueIter<'a, T> +where + T: NgxQueueEntry + 'a, +{ + type Item = &'a T; + + fn next(&mut self) -> Option { + unsafe { + let next = NonNull::new(self.current.as_ref().next)?; + if next == self.head { + return None; + } + + self.current = next; + Some(T::from_queue(self.current).as_ref()) + } + } +} + +/// A mutable iterator for the queue. +pub struct NgxQueueIterMut<'a, T> { + head: NonNull, + current: NonNull, + _lifetime: PhantomData<&'a T>, +} + +impl<'a, T> NgxQueueIterMut<'a, T> +where + T: NgxQueueEntry, +{ + /// Creates a new mutable queue iterator. + pub fn new(head: &'a mut ngx_queue_t) -> Self { + let head = NonNull::from(head); + NgxQueueIterMut { head, current: head, _lifetime: PhantomData } + } +} + +impl<'a, T> Iterator for NgxQueueIterMut<'a, T> +where + T: NgxQueueEntry + 'a, +{ + type Item = &'a mut T; + + fn next(&mut self) -> Option { + unsafe { + let next = NonNull::new(self.current.as_ref().next)?; + if next == self.head { + return None; + } + + self.current = next; + Some(T::from_queue(self.current).as_mut()) + } + } +} + +/// A doubly-linked list that owns elements of type `T` backed by the specified allocator `A`. +#[derive(Debug)] +pub struct Queue +where + A: Allocator, +{ + // The address of the NgxQueue with queue head has to be stable, as the queue elements will + // contain pointers to the head. + raw: NonNull>>, + len: usize, + alloc: A, +} + +impl Drop for Queue +where + A: Allocator, +{ + fn drop(&mut self) { + while self.pop_front().is_some() {} + + let layout = Layout::for_value(unsafe { self.raw.as_ref() }); + unsafe { self.allocator().deallocate(self.raw.cast(), layout) }; + } +} + +unsafe impl Send for Queue +where + A: Send + Allocator, + T: Send, +{ +} + +unsafe impl Sync for Queue +where + A: Sync + Allocator, + T: Sync, +{ +} + +impl Queue { + /// Creates a new list with specified allocator. + pub fn try_new_in(alloc: A) -> Result { + let raw = NgxQueue { head: unsafe { mem::zeroed() }, _type: PhantomData }; + let raw = crate::allocator::allocate(raw, &alloc)?; + Ok(Self { raw, len: 0, alloc }) + } + + /// Returns a reference to the underlying allocator. + pub fn allocator(&self) -> &A { + &self.alloc + } + + /// Returns `true` if the list contains no elements. + pub fn is_empty(&self) -> bool { + self.raw().is_empty() + } + + /// Returns the number of elements in the queue. + pub fn len(&self) -> usize { + self.len + } + + /// Returns an iterator over the entries of the list. + pub fn iter(&self) -> QueueIter<'_, T> { + QueueIter::new(&self.raw().head) + } + + /// Returns a mutable iterator over the entries of the list. + pub fn iter_mut(&mut self) -> QueueIterMut<'_, T> { + QueueIterMut::new(&mut self.raw_mut().head) + } + + /// Removes the last element and returns it or `None` if the list is empty. + pub fn pop_back(&mut self) -> Option { + if self.is_empty() { + return None; + } + let node = NonNull::new(self.raw_mut().head.prev)?; + Some(unsafe { self.remove(node) }) + } + + /// Removes the first element and returns it or `None` if the list is empty. + pub fn pop_front(&mut self) -> Option { + if self.is_empty() { + return None; + } + let node = NonNull::new(self.raw_mut().head.next)?; + Some(unsafe { self.remove(node) }) + } + + /// Appends an element to the end of the list. + pub fn push_back(&mut self, item: T) -> Result<&mut T, AllocError> { + let mut entry = QueueEntry::new_in(item, self.allocator())?; + let entry = unsafe { entry.as_mut() }; + self.raw_mut().push_back(entry); + self.len += 1; + Ok(&mut entry.item) + } + + /// Appends an element to the beginning of the list. + pub fn push_front(&mut self, item: T) -> Result<&mut T, AllocError> { + let mut entry = QueueEntry::new_in(item, self.allocator())?; + let entry = unsafe { entry.as_mut() }; + self.raw_mut().push_front(entry); + self.len += 1; + Ok(&mut entry.item) + } + + fn raw(&self) -> &NgxQueue> { + // SAFETY: we allocated this pointer as well-aligned and convertible to reference. + unsafe { self.raw.as_ref() } + } + + fn raw_mut(&mut self) -> &mut NgxQueue> { + // SAFETY: we allocated this pointer as well-aligned and convertible to reference. + unsafe { self.raw.as_mut() } + } + + /// Removes a node from the queue and returns the contained value. + /// + /// # Safety + /// + /// `node` must be an element of this list. + unsafe fn remove(&mut self, node: NonNull) -> T { + unsafe { ngx_queue_remove(node.as_ptr()) }; + self.len -= 1; + + let entry = QueueEntry::::from_queue(node); + let copy = unsafe { entry.read() }; + // Skip drop as QueueEntry is already copied to `x`. + unsafe { self.allocator().deallocate(entry.cast(), Layout::for_value(entry.as_ref())) }; + copy.item + } +} + +#[derive(Debug)] +struct QueueEntry { + queue: ngx_queue_t, + item: T, +} + +unsafe impl NgxQueueEntry for QueueEntry { + fn from_queue(queue: NonNull) -> NonNull { + unsafe { ngx_queue_data!(queue, Self, queue) } + } + + fn to_queue(&mut self) -> &mut ngx_queue_t { + &mut self.queue + } +} + +impl QueueEntry { + pub fn new_in(item: T, alloc: &impl Allocator) -> Result, AllocError> { + let p: NonNull = alloc.allocate(Layout::new::())?.cast(); + + unsafe { + let u = p.cast::>().as_mut(); + // does not read the uninitialized data + ngx_queue_init(&raw mut u.assume_init_mut().queue); + ptr::write(&raw mut u.assume_init_mut().item, item); + } + + Ok(p) + } +} + +/// An iterator for the linked list [Queue]. +pub struct QueueIter<'a, T>(NgxQueueIter<'a, QueueEntry>); + +impl<'a, T> QueueIter<'a, T> { + /// Creates a new iterator for the linked list. + pub fn new(head: &'a ngx_queue_t) -> Self { + Self(NgxQueueIter::new(head)) + } +} + +impl<'a, T> Iterator for QueueIter<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + Some(&self.0.next()?.item) + } +} + +/// A mutable iterator for the linked list [Queue]. +pub struct QueueIterMut<'a, T>(NgxQueueIterMut<'a, QueueEntry>); + +impl<'a, T> QueueIterMut<'a, T> { + /// Creates a new mutable iterator for the linked list. + pub fn new(head: &'a mut ngx_queue_t) -> Self { + Self(NgxQueueIterMut::new(head)) + } +} + +impl<'a, T> Iterator for QueueIterMut<'a, T> { + type Item = &'a mut T; + + fn next(&mut self) -> Option { + Some(&mut self.0.next()?.item) + } +} diff --git a/source/rust/vendor/ngx-rust/src/collections/rbtree.rs b/source/rust/vendor/ngx-rust/src/collections/rbtree.rs new file mode 100644 index 0000000..64692d5 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/collections/rbtree.rs @@ -0,0 +1,472 @@ +//! Types and utilities for working with [ngx_rbtree_t]. +//! +//! This module provides both the tools for interaction with the existing `ngx_rbtree_t` objects in +//! the NGINX, and useful high-level types built on top of the `ngx_rbtree_t`. +//! +//! See . + +use core::alloc::Layout; +use core::cmp::Ordering; +use core::hash::{self, BuildHasher, Hash}; +use core::marker::PhantomData; +use core::ptr::{self, NonNull}; +use core::{borrow, mem}; + +use nginx_sys::{ + ngx_rbt_red, ngx_rbtree_data, ngx_rbtree_delete, ngx_rbtree_init, ngx_rbtree_insert, + ngx_rbtree_key_t, ngx_rbtree_min, ngx_rbtree_next, ngx_rbtree_node_t, ngx_rbtree_t, +}; + +use crate::allocator::{self, AllocError, Allocator}; + +/// Trait for pointer conversions between the tree entry and its container. +/// +/// # Safety +/// +/// This trait must only be implemented on types that contain a tree node or wrappers with +/// compatible layout. The type then can be used to access elements of a raw rbtree type +/// [NgxRbTree] linked via specified field. +/// +/// If the struct can belong to several trees through multiple embedded `ngx_rbtree_node_t` fields, +/// a separate [NgxRbTreeEntry] implementation via wrapper type should be used for each tree. +pub unsafe trait NgxRbTreeEntry { + /// Gets a container pointer from tree node. + fn from_rbtree_node(node: NonNull) -> NonNull; + /// Gets an rbtree node from a container reference. + fn to_rbtree_node(&mut self) -> &mut ngx_rbtree_node_t; +} + +unsafe impl NgxRbTreeEntry for ngx_rbtree_node_t { + fn from_rbtree_node(node: NonNull) -> NonNull { + node + } + + fn to_rbtree_node(&mut self) -> &mut ngx_rbtree_node_t { + self + } +} + +/// A wrapper over a raw `ngx_rbtree_t`, a red-black tree implementation. +/// +/// This wrapper is defined in terms of type `T` that embeds and can be converted from or to the +/// tree nodes. +/// +/// See . +#[derive(Debug)] +#[repr(transparent)] +pub struct NgxRbTree { + inner: ngx_rbtree_t, + _type: PhantomData, +} + +impl NgxRbTree +where + T: NgxRbTreeEntry, +{ + /// Creates a tree reference from a pointer to [ngx_rbtree_t]. + /// + /// # Safety + /// + /// `tree` is a valid pointer to [ngx_rbtree_t], and `T::from_rbtree_node` on the tree nodes + /// results in valid pointers to `T`. + pub unsafe fn from_ptr<'a>(tree: *const ngx_rbtree_t) -> &'a Self { + unsafe { &*tree.cast() } + } + + /// Creates a mutable tree reference from a pointer to [ngx_rbtree_t]. + /// + /// # Safety + /// + /// `tree` is a valid pointer to [ngx_rbtree_t], and `T::from_rbtree_node` on the tree nodes + /// results in valid pointers to `T`. + pub unsafe fn from_ptr_mut<'a>(tree: *mut ngx_rbtree_t) -> &'a mut Self { + unsafe { &mut *tree.cast() } + } + + /// Returns `true` if the tree contains no elements. + pub fn is_empty(&self) -> bool { + ptr::addr_eq(self.inner.root, self.inner.sentinel) + } + + /// Appends a node to the tree. + pub fn insert(&mut self, node: &mut T) { + unsafe { ngx_rbtree_insert(&raw mut self.inner, node.to_rbtree_node()) }; + } + + /// Removes the specified node from the tree. + pub fn remove(&mut self, node: &mut T) { + unsafe { ngx_rbtree_delete(&raw mut self.inner, node.to_rbtree_node()) }; + } + + /// Returns an iterator over the nodes of the tree. + pub fn iter(&self) -> NgxRbTreeIter<'_> { + unsafe { NgxRbTreeIter::new(NonNull::from(&self.inner)) } + } + + /// Returns a mutable iterator over the nodes of the tree. + pub fn iter_mut(&mut self) -> NgxRbTreeIter<'_> { + unsafe { NgxRbTreeIter::new(NonNull::from(&mut self.inner)) } + } +} + +/// Raw iterator over the `ngx_rbtree_t` nodes. +/// +/// This iterator type can be used to access elements of any correctly initialized `ngx_rbtree_t` +/// instance, including those already embedded in the nginx structures. The iterator stores pointer +/// to the next node and thus remains valid and usable even if the last returned item is removed +/// from the tree. +pub struct NgxRbTreeIter<'a> { + tree: NonNull, + node: *mut ngx_rbtree_node_t, + _lifetime: PhantomData<&'a ()>, +} + +impl NgxRbTreeIter<'_> { + /// Creates an iterator for the `ngx_rbtree_t`. + /// + /// # Safety + /// + /// The tree must outlive the iterator. + pub unsafe fn new(tree: NonNull) -> Self { + let t = unsafe { tree.as_ref() }; + let node = if ptr::addr_eq(t.root, t.sentinel) { + // empty tree + ptr::null_mut() + } else { + unsafe { ngx_rbtree_min(t.root, t.sentinel) } + }; + + Self { tree, node, _lifetime: PhantomData } + } +} + +impl Iterator for NgxRbTreeIter<'_> { + type Item = NonNull; + + fn next(&mut self) -> Option { + let item = NonNull::new(self.node)?; + // ngx_rbtree_next does not mutate the tree + self.node = unsafe { ngx_rbtree_next(self.tree.as_mut(), self.node) }; + Some(item) + } +} + +#[allow(deprecated)] +type BuildMapHasher = core::hash::BuildHasherDefault; + +/// A map type based on the `ngx_rbtree_t`. +/// +/// This map implementation owns the stored keys and values and ensures that the data is dropped. +/// The order of the elements is an undocumented implementation detail. +/// +/// This is a `ngx`-specific high-level type with no direct counterpart in the NGINX code. +#[derive(Debug)] +pub struct RbTreeMap +where + A: Allocator, +{ + tree: NgxRbTree>, + sentinel: NonNull, + alloc: A, +} + +/// Entry type for the [RbTreeMap]. +/// +/// The struct is used from the Rust code only and thus does not need to be compatible with C. +#[derive(Debug)] +struct MapEntry { + node: ngx_rbtree_node_t, + key: K, + value: V, +} + +impl MapEntry +where + K: Hash, +{ + fn new(key: K, value: V) -> Self { + let mut node: ngx_rbtree_node_t = unsafe { mem::zeroed() }; + node.key = BuildMapHasher::default().hash_one(&key) as ngx_rbtree_key_t; + + Self { node, key, value } + } + + fn into_kv(self) -> (K, V) { + (self.key, self.value) + } +} + +unsafe impl NgxRbTreeEntry for MapEntry { + fn from_rbtree_node(node: NonNull) -> NonNull { + unsafe { ngx_rbtree_data!(node, Self, node) } + } + + fn to_rbtree_node(&mut self) -> &mut ngx_rbtree_node_t { + &mut self.node + } +} + +/// An iterator for the [RbTreeMap]. +pub struct MapIter<'a, K: 'a, V: 'a>(NgxRbTreeIter<'a>, PhantomData<(K, V)>); + +impl<'a, K: 'a, V: 'a> MapIter<'a, K, V> { + /// Creates an iterator for the [RbTreeMap]. + pub fn new(tree: &'a RbTreeMap) -> Self { + // msrv(1.89.0): NonNull::from_ref() + let rbtree = NonNull::from(&tree.tree.inner); + // SAFETY: Iter borrows from the tree, ensuring that the tree would outlive it. + Self(unsafe { NgxRbTreeIter::new(rbtree) }, Default::default()) + } +} + +impl<'a, K: 'a, V: 'a> Iterator for MapIter<'a, K, V> { + type Item = (&'a K, &'a V); + + fn next(&mut self) -> Option { + let item = self.0.next()?; + let item = unsafe { ngx_rbtree_data!(item, MapEntry, node).as_ref() }; + Some((&item.key, &item.value)) + } +} + +/// A mutable iterator for the [RbTreeMap]. +pub struct MapIterMut<'a, K: 'a, V: 'a>(NgxRbTreeIter<'a>, PhantomData<(K, V)>); + +impl<'a, K: 'a, V: 'a> MapIterMut<'a, K, V> { + /// Creates an iterator for the [RbTreeMap]. + pub fn new(tree: &'a mut RbTreeMap) -> Self { + // msrv(1.89.0): NonNull::from_mut() + let rbtree = NonNull::from(&mut tree.tree.inner); + // SAFETY: IterMut borrows from the tree, ensuring that the tree would outlive it. + Self(unsafe { NgxRbTreeIter::new(rbtree) }, Default::default()) + } +} + +impl<'a, K: 'a, V: 'a> Iterator for MapIterMut<'a, K, V> { + type Item = (&'a K, &'a mut V); + + fn next(&mut self) -> Option { + let mut item = MapEntry::::from_rbtree_node(self.0.next()?); + let item = unsafe { item.as_mut() }; + Some((&item.key, &mut item.value)) + } +} + +impl RbTreeMap +where + A: Allocator, +{ + /// Returns a reference to the underlying allocator. + pub fn allocator(&self) -> &A { + &self.alloc + } + + /// Clears the tree, removing all elements. + pub fn clear(&mut self) { + // SAFETY: the iter lives until the end of the scope + let iter = unsafe { NgxRbTreeIter::new(NonNull::from(&self.tree.inner)) }; + let layout = Layout::new::>(); + + for node in iter { + unsafe { + let mut data = MapEntry::::from_rbtree_node(node); + + ngx_rbtree_delete(&raw mut self.tree.inner, &raw mut data.as_mut().node); + ptr::drop_in_place(data.as_mut()); + self.allocator().deallocate(data.cast(), layout) + } + } + } + + /// Returns true if the tree contains no entries. + pub fn is_empty(&self) -> bool { + self.tree.is_empty() + } + + /// Returns an iterator over the entries of the tree. + #[inline] + pub fn iter(&self) -> MapIter<'_, K, V> { + MapIter::new(self) + } + + /// Returns a mutable iterator over the entries of the tree. + #[inline] + pub fn iter_mut(&mut self) -> MapIterMut<'_, K, V> { + MapIterMut::new(self) + } +} + +impl RbTreeMap +where + A: Allocator, + K: Hash + Ord, +{ + /// Attempts to create and initialize a new RbTreeMap with specified allocator. + pub fn try_new_in(alloc: A) -> Result { + let layout = Layout::new::(); + let sentinel: NonNull = alloc.allocate_zeroed(layout)?.cast(); + + let tree = NgxRbTree { inner: unsafe { mem::zeroed() }, _type: PhantomData }; + + let mut this = RbTreeMap { tree, sentinel, alloc }; + + unsafe { + ngx_rbtree_init(&raw mut this.tree.inner, this.sentinel.as_ptr(), Some(Self::insert)) + }; + + Ok(this) + } + + /// Returns a reference to the value corresponding to the key. + pub fn get(&self, key: &Q) -> Option<&V> + where + K: borrow::Borrow, + Q: Hash + Ord + ?Sized, + { + self.lookup(key).map(|x| unsafe { &x.as_ref().value }) + } + + /// Returns a mutable reference to the value corresponding to the key. + pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> + where + K: borrow::Borrow, + Q: Hash + Ord + ?Sized, + { + self.lookup(key).map(|mut x| unsafe { &mut x.as_mut().value }) + } + + /// Removes a key from the tree, returning the value at the key if the key was previously in the + /// tree. + pub fn remove(&mut self, key: &Q) -> Option + where + K: borrow::Borrow, + Q: Hash + Ord + ?Sized, + { + self.remove_entry(key).map(|(_, v)| v) + } + + /// Removes a key from the tree, returning the stored key and value if the key was previously in + /// the tree. + pub fn remove_entry(&mut self, key: &Q) -> Option<(K, V)> + where + K: borrow::Borrow, + Q: Hash + Ord + ?Sized, + { + let mut node = self.lookup(key)?; + unsafe { + self.tree.remove(node.as_mut()); + + let layout = Layout::for_value(node.as_ref()); + // SAFETY: we make a bitwise copy of the node and dispose of the original value without + // dropping it. + let copy = node.as_ptr().read(); + self.allocator().deallocate(node.cast(), layout); + Some(copy.into_kv()) + } + } + + /// Attempts to insert a new element into the tree. + pub fn try_insert(&mut self, key: K, value: V) -> Result<&mut V, AllocError> { + let mut node = if let Some(mut node) = self.lookup(&key) { + unsafe { node.as_mut().value = value }; + node + } else { + let node = MapEntry::new(key, value); + let mut node = allocator::allocate(node, self.allocator())?; + self.tree.insert(unsafe { node.as_mut() }); + node + }; + + Ok(unsafe { &mut node.as_mut().value }) + } + + extern "C" fn insert( + mut temp: *mut ngx_rbtree_node_t, + node: *mut ngx_rbtree_node_t, + sentinel: *mut ngx_rbtree_node_t, + ) { + let n = unsafe { &mut *ngx_rbtree_data!(node, MapEntry, node) }; + + loop { + let t = unsafe { &mut *ngx_rbtree_data!(temp, MapEntry, node) }; + let p = match Ord::cmp(&n.node.key, &t.node.key) { + Ordering::Less => &mut t.node.left, + Ordering::Greater => &mut t.node.right, + Ordering::Equal => match Ord::cmp(&n.key, &t.key) { + Ordering::Less => &mut t.node.left, + Ordering::Greater => &mut t.node.right, + // should be handled in try_insert + Ordering::Equal => &mut t.node.right, + }, + }; + + if ptr::addr_eq(*p, sentinel) { + *p = node; + break; + } + + temp = *p; + } + + n.node.parent = temp; + n.node.left = sentinel; + n.node.right = sentinel; + unsafe { ngx_rbt_red(node) }; + } + + fn lookup(&self, key: &Q) -> Option>> + where + K: borrow::Borrow, + Q: Hash + Ord + ?Sized, + { + let mut node = self.tree.inner.root; + let hash = BuildMapHasher::default().hash_one(key) as ngx_rbtree_key_t; + + while !ptr::addr_eq(node, self.tree.inner.sentinel) { + let n = unsafe { NonNull::new_unchecked(ngx_rbtree_data!(node, MapEntry, node)) }; + let nr = unsafe { n.as_ref() }; + + node = match Ord::cmp(&hash, &nr.node.key) { + Ordering::Less => nr.node.left, + Ordering::Greater => nr.node.right, + Ordering::Equal => match Ord::cmp(key, nr.key.borrow()) { + Ordering::Less => nr.node.left, + Ordering::Greater => nr.node.right, + Ordering::Equal => return Some(n), + }, + } + } + + None + } +} + +impl Drop for RbTreeMap +where + A: Allocator, +{ + fn drop(&mut self) { + self.clear(); + + unsafe { + self.allocator() + .deallocate(self.sentinel.cast(), Layout::for_value(self.sentinel.as_ref())) + }; + } +} + +unsafe impl Send for RbTreeMap +where + A: Send + Allocator, + K: Send, + V: Send, +{ +} + +unsafe impl Sync for RbTreeMap +where + A: Sync + Allocator, + K: Sync, + V: Sync, +{ +} diff --git a/source/rust/vendor/ngx-rust/src/core/buffer.rs b/source/rust/vendor/ngx-rust/src/core/buffer.rs new file mode 100644 index 0000000..cfd1282 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/core/buffer.rs @@ -0,0 +1,129 @@ +use core::slice; + +use crate::ffi::*; + +/// The `Buffer` trait provides methods for working with an nginx buffer (`ngx_buf_t`). +/// +/// See +pub trait Buffer { + /// Returns a raw pointer to the underlying `ngx_buf_t` of the buffer. + fn as_ngx_buf(&self) -> *const ngx_buf_t; + + /// Returns a mutable raw pointer to the underlying `ngx_buf_t` of the buffer. + fn as_ngx_buf_mut(&mut self) -> *mut ngx_buf_t; + + /// Returns the buffer contents as a byte slice. + fn as_bytes(&self) -> &[u8] { + let buf = self.as_ngx_buf(); + unsafe { slice::from_raw_parts((*buf).pos, self.len()) } + } + + /// Returns the length of the buffer contents. + fn len(&self) -> usize { + let buf = self.as_ngx_buf(); + unsafe { + let pos = (*buf).pos; + let last = (*buf).last; + assert!(last >= pos); + usize::wrapping_sub(last as _, pos as _) + } + } + + /// Returns `true` if the buffer is empty, i.e., it has zero length. + fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Sets the `last_buf` flag of the buffer. + /// + /// # Arguments + /// + /// * `last` - A boolean indicating whether the buffer is the last buffer in a request. + fn set_last_buf(&mut self, last: bool) { + let buf = self.as_ngx_buf_mut(); + unsafe { + (*buf).set_last_buf(if last { 1 } else { 0 }); + } + } + + /// Sets the `last_in_chain` flag of the buffer. + /// + /// # Arguments + /// + /// * `last` - A boolean indicating whether the buffer is the last buffer in a chain of buffers. + fn set_last_in_chain(&mut self, last: bool) { + let buf = self.as_ngx_buf_mut(); + unsafe { + (*buf).set_last_in_chain(if last { 1 } else { 0 }); + } + } +} + +/// The `MutableBuffer` trait extends the `Buffer` trait and provides methods for working with a +/// mutable buffer. +pub trait MutableBuffer: Buffer { + /// Returns a mutable reference to the buffer contents as a byte slice. + fn as_bytes_mut(&mut self) -> &mut [u8] { + let buf = self.as_ngx_buf_mut(); + unsafe { slice::from_raw_parts_mut((*buf).pos, self.len()) } + } +} + +/// Wrapper struct for a temporary buffer, providing methods for working with an `ngx_buf_t`. +pub struct TemporaryBuffer(*mut ngx_buf_t); + +impl TemporaryBuffer { + /// Creates a new `TemporaryBuffer` from an `ngx_buf_t` pointer. + /// + /// # Panics + /// Panics if the given buffer pointer is null. + pub fn from_ngx_buf(buf: *mut ngx_buf_t) -> TemporaryBuffer { + assert!(!buf.is_null()); + TemporaryBuffer(buf) + } +} + +impl Buffer for TemporaryBuffer { + /// Returns the underlying `ngx_buf_t` pointer as a raw pointer. + fn as_ngx_buf(&self) -> *const ngx_buf_t { + self.0 + } + + /// Returns a mutable reference to the underlying `ngx_buf_t` pointer. + fn as_ngx_buf_mut(&mut self) -> *mut ngx_buf_t { + self.0 + } +} + +impl MutableBuffer for TemporaryBuffer { + /// Returns a mutable reference to the buffer contents as a byte slice. + fn as_bytes_mut(&mut self) -> &mut [u8] { + unsafe { slice::from_raw_parts_mut((*self.0).pos, self.len()) } + } +} + +/// Wrapper struct for a memory buffer, providing methods for working with an `ngx_buf_t`. +pub struct MemoryBuffer(*mut ngx_buf_t); + +impl MemoryBuffer { + /// Creates a new `MemoryBuffer` from an `ngx_buf_t` pointer. + /// + /// # Panics + /// Panics if the given buffer pointer is null. + pub fn from_ngx_buf(buf: *mut ngx_buf_t) -> MemoryBuffer { + assert!(!buf.is_null()); + MemoryBuffer(buf) + } +} + +impl Buffer for MemoryBuffer { + /// Returns the underlying `ngx_buf_t` pointer as a raw pointer. + fn as_ngx_buf(&self) -> *const ngx_buf_t { + self.0 + } + + /// Returns a mutable reference to the underlying `ngx_buf_t` pointer. + fn as_ngx_buf_mut(&mut self) -> *mut ngx_buf_t { + self.0 + } +} diff --git a/source/rust/vendor/ngx-rust/src/core/conf.rs b/source/rust/vendor/ngx-rust/src/core/conf.rs new file mode 100644 index 0000000..6da4c47 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/core/conf.rs @@ -0,0 +1,179 @@ +use core::ptr::NonNull; + +use crate::ffi::{ngx_core_conf_t, ngx_module_t}; + +/// Trait for core-style modules. +/// +/// This is the foundational trait that identifies a type as representing a +/// concrete NGINX core module. +pub trait CoreModule { + /// Returns the global `ngx_module_t` describing this module. + fn module() -> &'static ngx_module_t; +} + +/// Raw access to core module main configuration slots. +/// +/// This trait is implemented for NGINX-owned types such as `ngx_cycle_t` and `ngx_conf_t` +/// that carry configuration context pointers. It exposes the low-level lookup step that +/// retrieves a module's main configuration as an untyped pointer. +/// +/// Most callers should not use this trait directly. Prefer `CoreModuleMainConf` to obtain a +/// typed reference for a specific core module. +pub trait CoreModuleConfExt { + /// Get a non-null pointer to a core module's main configuration. + /// + /// # Safety + /// Caller must ensure that type `T` matches the configuration type for the specified module. + /// Supplying the wrong type will produce an invalid typed pointer. + #[inline] + unsafe fn core_main_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { + None + } +} + +impl CoreModuleConfExt for crate::ffi::ngx_cycle_t { + #[inline] + unsafe fn core_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + let conf_ctx = NonNull::new(self.conf_ctx)?; + let conf = unsafe { *conf_ctx.as_ptr().add(module.index) }; + NonNull::new(conf.cast()) + } +} + +impl CoreModuleConfExt for crate::ffi::ngx_conf_t { + #[inline] + unsafe fn core_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { self.cycle.as_ref()?.core_main_conf_unchecked(module) } + } +} + +/// Typed access to a core module's main configuration. +/// +/// Implement this trait for a concrete core-style module to associate it with its main +/// configuration type and global `ngx_module_t`. The provided default methods build on top of +/// `CoreModuleConfExt` to turn the raw configuration slot lookup into typed references. +/// +/// # Safety +/// Caller must ensure that type `CoreModuleMainConf::MainConf` matches the configuration type +/// for the specified module. +pub unsafe trait CoreModuleMainConf: CoreModule { + /// Concrete type of this module's main configuration. + type MainConf; + + /// Get a typed shared reference to this module's main configuration. + fn main_conf(o: &impl CoreModuleConfExt) -> Option<&'static Self::MainConf> { + unsafe { Some(o.core_main_conf_unchecked(Self::module())?.as_ref()) } + } + + /// Get a typed mutable reference to this module's main configuration. + fn main_conf_mut(o: &impl CoreModuleConfExt) -> Option<&'static mut Self::MainConf> { + unsafe { Some(o.core_main_conf_unchecked(Self::module())?.as_mut()) } + } +} + +/// Auxiliary structure to access `ngx_core_module` configuration. +pub struct NgxCoreModule; + +impl CoreModule for NgxCoreModule { + fn module() -> &'static ngx_module_t { + unsafe { &*core::ptr::addr_of!(nginx_sys::ngx_core_module) } + } +} + +unsafe impl CoreModuleMainConf for NgxCoreModule { + type MainConf = ngx_core_conf_t; +} + +#[cfg(test)] +mod tests { + extern crate alloc; + extern crate std; + + use alloc::boxed::Box; + use core::ffi::c_void; + use core::mem::MaybeUninit; + + use super::{CoreModule, CoreModuleConfExt, CoreModuleMainConf}; + use crate::ffi::{ngx_conf_t, ngx_cycle_t, ngx_module_t}; + + type CoreConfSlot = *mut *mut *mut c_void; + + fn module_with_index(index: usize) -> ngx_module_t { + let mut module = ngx_module_t::default(); + module.index = index; + module + } + + #[test] + fn null_conf_ctx_returns_none() { + let cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; + let module = module_with_index(0); + assert!(unsafe { cycle.core_main_conf_unchecked::(&module) }.is_none()); + } + + #[test] + fn missing_module_slot_returns_none() { + let mut slots: [CoreConfSlot; 2] = [core::ptr::null_mut(); 2]; + let mut cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; + cycle.conf_ctx = slots.as_mut_ptr(); + + let module = module_with_index(1); + assert!(unsafe { cycle.core_main_conf_unchecked::(&module) }.is_none()); + } + + #[test] + fn populated_slot_returns_typed_reference() { + let mut value: u32 = 42; + let mut slots: [CoreConfSlot; 1] = [(&raw mut value).cast()]; + + let mut cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; + cycle.conf_ctx = slots.as_mut_ptr(); + + let mut conf: ngx_conf_t = unsafe { MaybeUninit::zeroed().assume_init() }; + conf.cycle = &raw mut cycle; + + let module = module_with_index(0); + + let got = unsafe { conf.core_main_conf_unchecked::(&module).map(|v| *v.as_ref()) }; + assert_eq!(got, Some(42)); + + let got_mut = + unsafe { conf.core_main_conf_unchecked::(&module).map(|mut v| v.as_mut()) }; + assert!(got_mut.is_some()); + if let Some(v) = got_mut { + *v = 99; + } + assert_eq!(value, 99); + } + + struct TestCoreModule; + + impl CoreModule for TestCoreModule { + fn module() -> &'static ngx_module_t { + Box::leak(Box::new(module_with_index(0))) + } + } + + unsafe impl CoreModuleMainConf for TestCoreModule { + type MainConf = u32; + } + + #[test] + fn main_conf_trait_accessors_return_typed_references() { + let mut value: u32 = 42; + let mut slots: [CoreConfSlot; 1] = [(&raw mut value).cast()]; + + let mut cycle: ngx_cycle_t = unsafe { MaybeUninit::zeroed().assume_init() }; + cycle.conf_ctx = slots.as_mut_ptr(); + + let mut conf: ngx_conf_t = unsafe { MaybeUninit::zeroed().assume_init() }; + conf.cycle = &raw mut cycle; + + assert_eq!(TestCoreModule::main_conf(&conf).copied(), Some(42)); + + if let Some(v) = TestCoreModule::main_conf_mut(&conf) { + *v = 99; + } + assert_eq!(value, 99); + } +} diff --git a/source/rust/vendor/ngx-rust/src/core/mod.rs b/source/rust/vendor/ngx-rust/src/core/mod.rs new file mode 100644 index 0000000..9b9a778 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/core/mod.rs @@ -0,0 +1,27 @@ +mod buffer; +mod conf; +mod pool; +pub mod slab; +mod status; +mod string; + +pub use buffer::*; +pub use conf::*; +pub use pool::*; +pub use slab::SlabPool; +pub use status::*; +pub use string::*; + +/// Gets an outer object pointer from a pointer to one of its fields. +/// While there is no corresponding C macro, the pattern is common in the NGINX source. +/// +/// # Safety +/// +/// `$ptr` must be a valid pointer to the field `$field` of `$type`. +#[macro_export] +macro_rules! ngx_container_of { + ($ptr:expr, $type:path, $field:ident) => {{ + let ptr = $ptr; + unsafe { ptr.byte_sub(::core::mem::offset_of!($type, $field)) }.cast::<$type>() + }}; +} diff --git a/source/rust/vendor/ngx-rust/src/core/pool.rs b/source/rust/vendor/ngx-rust/src/core/pool.rs new file mode 100644 index 0000000..efb283e --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/core/pool.rs @@ -0,0 +1,337 @@ +use core::alloc::Layout; +use core::ffi::c_void; +use core::mem; +use core::ptr::{self, NonNull}; + +use nginx_sys::{ + NGX_ALIGNMENT, ngx_buf_t, ngx_create_temp_buf, ngx_palloc, ngx_pcalloc, ngx_pfree, + ngx_pmemalign, ngx_pnalloc, ngx_pool_cleanup_add, ngx_pool_t, +}; + +use crate::allocator::{AllocError, Allocator, dangling_for_layout}; +use crate::core::buffer::{Buffer, MemoryBuffer, TemporaryBuffer}; + +/// Non-owning wrapper for an [`ngx_pool_t`] pointer, providing methods for working with memory +/// pools. +/// +/// See +#[derive(Clone, Debug)] +#[repr(transparent)] +pub struct Pool(NonNull); + +unsafe impl Allocator for Pool { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + // SAFETY: + // * This wrapper should be constructed with a valid pointer to ngx_pool_t. + // * The Pool type is !Send, thus we expect exclusive access for this call. + // * Pointers are considered mutable unless obtained from an immutable reference. + let ptr = if layout.size() == 0 { + // We can guarantee alignment <= NGX_ALIGNMENT for allocations of size 0 made with + // ngx_palloc_small. Any other cases are implementation-defined, and we can't tell which + // one will be used internally. + return Ok(NonNull::slice_from_raw_parts(dangling_for_layout(&layout), layout.size())); + } else if layout.align() == 1 { + unsafe { ngx_pnalloc(self.0.as_ptr(), layout.size()) } + } else if layout.align() <= NGX_ALIGNMENT { + unsafe { ngx_palloc(self.0.as_ptr(), layout.size()) } + } else if cfg!(any(ngx_feature = "have_posix_memalign", ngx_feature = "have_memalign")) { + // ngx_pmemalign is always defined, but does not guarantee the requested alignment + // unless memalign/posix_memalign exists. + unsafe { ngx_pmemalign(self.0.as_ptr(), layout.size(), layout.align()) } + } else { + return Err(AllocError); + }; + + // Verify the alignment of the result + debug_assert_eq!(ptr.align_offset(layout.align()), 0); + + let ptr = NonNull::new(ptr.cast()).ok_or(AllocError)?; + Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // ngx_pfree is noop for small allocations unless NGX_DEBUG_PALLOC is set. + // + // Note: there should be no cleanup handlers for the allocations made using this API. + // Violating that could result in the following issues: + // - use-after-free on large allocation + // - multiple cleanup handlers attached to a dangling ptr (these are not unique) + if layout.size() > 0 // 0 is dangling ptr + && (layout.size() > self.as_ref().max || layout.align() > NGX_ALIGNMENT) + { + unsafe { ngx_pfree(self.0.as_ptr(), ptr.as_ptr().cast()) }; + } + } + + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + debug_assert!( + new_layout.size() >= old_layout.size(), + "`new_layout.size()` must be greater than or equal to `old_layout.size()`" + ); + unsafe { self.resize(ptr, old_layout, new_layout) } + } + + unsafe fn grow_zeroed( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + debug_assert!( + new_layout.size() >= old_layout.size(), + "`new_layout.size()` must be greater than or equal to `old_layout.size()`" + ); + unsafe { + #[allow(clippy::manual_inspect)] + self.resize(ptr, old_layout, new_layout).map(|new_ptr| { + new_ptr + .cast::() + .byte_add(old_layout.size()) + .write_bytes(0, new_layout.size() - old_layout.size()); + new_ptr + }) + } + } + + unsafe fn shrink( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + debug_assert!( + new_layout.size() <= old_layout.size(), + "`new_layout.size()` must be smaller than or equal to `old_layout.size()`" + ); + unsafe { self.resize(ptr, old_layout, new_layout) } + } +} + +impl AsRef for Pool { + #[inline] + fn as_ref(&self) -> &ngx_pool_t { + // SAFETY: this wrapper should be constructed with a valid pointer to ngx_pool_t + unsafe { self.0.as_ref() } + } +} + +impl AsMut for Pool { + #[inline] + fn as_mut(&mut self) -> &mut ngx_pool_t { + // SAFETY: this wrapper should be constructed with a valid pointer to ngx_pool_t + unsafe { self.0.as_mut() } + } +} + +impl Pool { + /// Creates a new `Pool` from an `ngx_pool_t` pointer. + /// + /// # Safety + /// The caller must ensure that a valid `ngx_pool_t` pointer is provided, pointing to valid + /// memory and non-null. A null argument will cause an assertion failure and panic. + pub unsafe fn from_ngx_pool(pool: *mut ngx_pool_t) -> Pool { + unsafe { + debug_assert!(!pool.is_null()); + debug_assert!(pool.is_aligned()); + Pool(NonNull::new_unchecked(pool)) + } + } + + /// Expose the underlying `ngx_pool_t` pointer, for use with `ngx::ffi` + /// functions. + pub fn as_ptr(&self) -> *mut ngx_pool_t { + self.0.as_ptr() + } + + /// Creates a buffer of the specified size in the memory pool. + /// + /// Returns `Some(TemporaryBuffer)` if the buffer is successfully created, or `None` if + /// allocation fails. + pub fn create_buffer(&self, size: usize) -> Option { + let buf = unsafe { ngx_create_temp_buf(self.0.as_ptr(), size) }; + if buf.is_null() { + return None; + } + + Some(TemporaryBuffer::from_ngx_buf(buf)) + } + + /// Creates a buffer from a string in the memory pool. + /// + /// Returns `Some(TemporaryBuffer)` if the buffer is successfully created, or `None` if + /// allocation fails. + pub fn create_buffer_from_str(&self, str: &str) -> Option { + let mut buffer = self.create_buffer(str.len())?; + unsafe { + let buf = buffer.as_ngx_buf_mut(); + ptr::copy_nonoverlapping(str.as_ptr(), (*buf).pos, str.len()); + (*buf).last = (*buf).pos.add(str.len()); + } + Some(buffer) + } + + /// Creates a buffer from a static string in the memory pool. + /// + /// Returns `Some(MemoryBuffer)` if the buffer is successfully created, or `None` if allocation + /// fails. + pub fn create_buffer_from_static_str(&self, str: &'static str) -> Option { + let buf = self.calloc_type::(); + if buf.is_null() { + return None; + } + + // We cast away const, but buffers with the memory flag are read-only + let start = str.as_ptr() as *mut u8; + let end = unsafe { start.add(str.len()) }; + + unsafe { + (*buf).start = start; + (*buf).pos = start; + (*buf).last = end; + (*buf).end = end; + (*buf).set_memory(1); + } + + Some(MemoryBuffer::from_ngx_buf(buf)) + } + + /// Adds a cleanup handler for a value in the memory pool. + /// + /// Returns `Ok(())` if the cleanup handler is successfully added, or `Err(())` if the cleanup + /// handler cannot be added. + /// + /// # Safety + /// This function is marked as unsafe because it involves raw pointer manipulation. + unsafe fn add_cleanup_for_value(&self, value: *mut T) -> Result<(), ()> { + let cln = unsafe { ngx_pool_cleanup_add(self.0.as_ptr(), 0) }; + if cln.is_null() { + return Err(()); + } + + unsafe { + (*cln).handler = Some(cleanup_type::); + (*cln).data = value as *mut c_void; + } + + Ok(()) + } + + /// Allocates memory from the pool of the specified size. + /// The resulting pointer is aligned to a platform word size. + /// + /// Returns a raw pointer to the allocated memory. + pub fn alloc(&self, size: usize) -> *mut c_void { + unsafe { ngx_palloc(self.0.as_ptr(), size) } + } + + /// Allocates memory for a type from the pool. + /// The resulting pointer is aligned to a platform word size. + /// + /// Returns a typed pointer to the allocated memory. + pub fn alloc_type(&self) -> *mut T { + self.alloc(mem::size_of::()) as *mut T + } + + /// Allocates zeroed memory from the pool of the specified size. + /// The resulting pointer is aligned to a platform word size. + /// + /// Returns a raw pointer to the allocated memory. + pub fn calloc(&self, size: usize) -> *mut c_void { + unsafe { ngx_pcalloc(self.0.as_ptr(), size) } + } + + /// Allocates zeroed memory for a type from the pool. + /// The resulting pointer is aligned to a platform word size. + /// + /// Returns a typed pointer to the allocated memory. + pub fn calloc_type(&self) -> *mut T { + self.calloc(mem::size_of::()) as *mut T + } + + /// Allocates unaligned memory from the pool of the specified size. + /// + /// Returns a raw pointer to the allocated memory. + pub fn alloc_unaligned(&self, size: usize) -> *mut c_void { + unsafe { ngx_pnalloc(self.0.as_ptr(), size) } + } + + /// Allocates unaligned memory for a type from the pool. + /// + /// Returns a typed pointer to the allocated memory. + pub fn alloc_type_unaligned(&self) -> *mut T { + self.alloc_unaligned(mem::size_of::()) as *mut T + } + + /// Allocates memory for a value of a specified type and adds a cleanup handler to the memory + /// pool. + /// + /// Returns a typed pointer to the allocated memory if successful, or a null pointer if + /// allocation or cleanup handler addition fails. + pub fn allocate(&self, value: T) -> *mut T { + unsafe { + let p = self.alloc(mem::size_of::()) as *mut T; + ptr::write(p, value); + if self.add_cleanup_for_value(p).is_err() { + ptr::drop_in_place(p); + return ptr::null_mut(); + }; + p + } + } + + /// Resizes a memory allocation in place if possible. + /// + /// If resizing is requested for the last allocation in the pool, it may be + /// possible to adjust pool data and avoid any real allocations. + /// + /// # Safety + /// `ptr` must point to allocated address and `old_layout` must match the current layout + /// of the allocation. + #[inline(always)] + unsafe fn resize( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + if unsafe { + ptr.byte_add(old_layout.size()).as_ptr() == self.as_ref().d.last + && ptr.byte_add(new_layout.size()).as_ptr() <= self.as_ref().d.end + && ptr.align_offset(new_layout.align()) == 0 + } { + let pool = self.0.as_ptr(); + unsafe { (*pool).d.last = ptr.byte_add(new_layout.size()).as_ptr() }; + Ok(NonNull::slice_from_raw_parts(ptr, new_layout.size())) + } else { + let size = core::cmp::min(old_layout.size(), new_layout.size()); + let new_ptr = ::allocate(self, new_layout)?; + unsafe { + ptr.copy_to_nonoverlapping(new_ptr.cast(), size); + self.deallocate(ptr, old_layout); + } + Ok(new_ptr) + } + } +} + +/// Cleanup handler for a specific type `T`. +/// +/// This function is called when cleaning up a value of type `T` in an FFI context. +/// +/// # Safety +/// This function is marked as unsafe due to the raw pointer manipulation and the assumption that +/// `data` is a valid pointer to `T`. +/// +/// # Arguments +/// +/// * `data` - A raw pointer to the value of type `T` to be cleaned up. +unsafe extern "C" fn cleanup_type(data: *mut c_void) { + unsafe { + ptr::drop_in_place(data as *mut T); + } +} diff --git a/source/rust/vendor/ngx-rust/src/core/slab.rs b/source/rust/vendor/ngx-rust/src/core/slab.rs new file mode 100644 index 0000000..56bfb4e --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/core/slab.rs @@ -0,0 +1,151 @@ +//! Wrapper for the nginx slab pool allocator. +//! +//! See . +use core::alloc::Layout; +use core::cmp; +use core::ptr::NonNull; + +use nginx_sys::{ + ngx_shm_zone_t, ngx_shmtx_lock, ngx_shmtx_unlock, ngx_slab_alloc_locked, ngx_slab_free_locked, + ngx_slab_pool_t, +}; + +use crate::allocator::{AllocError, Allocator, dangling_for_layout}; + +/// Non-owning wrapper for an [`ngx_slab_pool_t`] pointer, providing methods for working with +/// shared memory slab pools. +/// +/// See . +#[derive(Clone, Debug)] +pub struct SlabPool(NonNull); + +unsafe impl Send for SlabPool {} +unsafe impl Sync for SlabPool {} + +unsafe impl Allocator for SlabPool { + #[inline] + fn allocate(&self, layout: Layout) -> Result, AllocError> { + self.lock().allocate(layout) + } + + #[inline] + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + unsafe { self.lock().deallocate(ptr, layout) } + } + + #[inline] + fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { + self.lock().allocate_zeroed(layout) + } + + #[inline] + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + unsafe { self.lock().grow(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn grow_zeroed( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + unsafe { self.lock().grow_zeroed(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn shrink( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + unsafe { self.lock().shrink(ptr, old_layout, new_layout) } + } +} + +impl AsRef for SlabPool { + #[inline] + fn as_ref(&self) -> &ngx_slab_pool_t { + // SAFETY: this wrapper should be constructed with a valid pointer to ngx_slab_pool_t + unsafe { self.0.as_ref() } + } +} + +impl AsMut for SlabPool { + #[inline] + fn as_mut(&mut self) -> &mut ngx_slab_pool_t { + // SAFETY: this wrapper should be constructed with a valid pointer to ngx_slab_pool_t + unsafe { self.0.as_mut() } + } +} + +impl SlabPool { + /// Creates a new `SlabPool` from an initialized shared zone. + /// + /// # Safety + /// + /// Shared zones are initialized and safe to use: + /// * between the zone init callback and configuration reload in the master process + /// * during the whole lifetime of a worker process. + /// + /// After the configuration reload (notably, in the cycle pool cleanup handlers), zone addresses + /// in the old cycle may become unmapped. + pub unsafe fn from_shm_zone(shm_zone: &ngx_shm_zone_t) -> Option { + let ptr = NonNull::new(shm_zone.shm.addr)?.cast(); + Some(Self(ptr)) + } + + /// Locks the slab pool mutex. + #[inline] + pub fn lock(&self) -> LockedSlabPool { + let shpool = self.0.as_ptr(); + unsafe { ngx_shmtx_lock(&raw mut (*shpool).mutex) }; + LockedSlabPool(self.0) + } +} + +/// Wrapper for a locked [`ngx_slab_pool_t`] pointer. +pub struct LockedSlabPool(NonNull); + +unsafe impl Allocator for LockedSlabPool { + fn allocate(&self, layout: Layout) -> Result, AllocError> { + if layout.size() == 0 { + return Ok(NonNull::slice_from_raw_parts(dangling_for_layout(&layout), layout.size())); + } + + // Small slab allocations (size <= ngx_pagesize / 2) are always aligned to the size rounded + // up to the nearest power of 2. + // If the requested alignment exceeds size, we can guarantee the alignment by allocating + // `align()` bytes. + let size = cmp::max(layout.size(), layout.align()); + + let ptr = unsafe { ngx_slab_alloc_locked(self.0.as_ptr(), size) }; + let ptr = NonNull::new(ptr.cast()).ok_or(AllocError)?; + + if ptr.align_offset(layout.align()) != 0 { + unsafe { self.deallocate(ptr, layout) }; + return Err(AllocError); + } + + Ok(NonNull::slice_from_raw_parts(ptr, layout.size())) + } + + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + if layout.size() != 0 { + unsafe { ngx_slab_free_locked(self.0.as_ptr(), ptr.as_ptr().cast()) } + } + } +} + +impl Drop for LockedSlabPool { + fn drop(&mut self) { + let shpool = unsafe { self.0.as_mut() }; + unsafe { ngx_shmtx_unlock(&raw mut shpool.mutex) } + } +} diff --git a/source/rust/vendor/ngx-rust/src/core/status.rs b/source/rust/vendor/ngx-rust/src/core/status.rs new file mode 100644 index 0000000..4cab884 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/core/status.rs @@ -0,0 +1,70 @@ +use core::ffi::c_char; +use core::fmt; +use core::ptr; + +use crate::ffi::*; + +/// Status +/// +/// Rust native wrapper for NGINX status codes. +#[derive(Ord, PartialOrd, Eq, PartialEq)] +pub struct Status(pub ngx_int_t); + +impl Status { + /// Is this Status equivalent to NGX_OK? + pub fn is_ok(&self) -> bool { + self == &Status::NGX_OK + } +} + +impl fmt::Debug for Status { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } +} + +impl From for ngx_int_t { + fn from(val: Status) -> Self { + val.0 + } +} + +macro_rules! ngx_codes { + ( + $( + $(#[$docs:meta])* + ($konst:ident); + )+ + ) => { + impl Status { + $( + $(#[$docs])* + pub const $konst: Status = Status($konst as ngx_int_t); + )+ + + } + } +} + +ngx_codes! { + /// NGX_OK - Operation succeeded. + (NGX_OK); + /// NGX_ERROR - Operation failed. + (NGX_ERROR); + /// NGX_AGAIN - Operation incomplete; call the function again. + (NGX_AGAIN); + /// NGX_BUSY - Resource is not available. + (NGX_BUSY); + /// NGX_DONE - Operation complete or continued elsewhere. Also used as an alternative success code. + (NGX_DONE); + /// NGX_DECLINED - Operation rejected, for example, because it is disabled in the configuration. + /// This is never an error. + (NGX_DECLINED); + /// NGX_ABORT - Function was aborted. Also used as an alternative error code. + (NGX_ABORT); +} + +/// An error occurred while parsing and validating configuration. +pub const NGX_CONF_ERROR: *mut c_char = ptr::null_mut::().wrapping_offset(-1); +/// Configuration handler succeeded. +pub const NGX_CONF_OK: *mut c_char = ptr::null_mut(); diff --git a/source/rust/vendor/ngx-rust/src/core/string.rs b/source/rust/vendor/ngx-rust/src/core/string.rs new file mode 100644 index 0000000..ad245df --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/core/string.rs @@ -0,0 +1,633 @@ +#[cfg(feature = "alloc")] +use alloc::{borrow::Cow, string::String}; +use core::cmp; +use core::fmt; +use core::str::{self, Utf8Error}; + +use crate::ffi::{ngx_str_t, u_char}; + +/// Static string initializer for [`ngx_str_t`]. +/// +/// The resulting byte string is always nul-terminated (just like a C string). +/// +/// [`ngx_str_t`]: https://nginx.org/en/docs/dev/development_guide.html#string_overview +#[macro_export] +macro_rules! ngx_string { + ($s:expr) => {{ $crate::ffi::ngx_str_t { len: $s.len() as _, data: concat!($s, "\0").as_ptr() as *mut u8 } }}; +} + +#[cfg(feature = "alloc")] +pub use self::_alloc::NgxString; + +/// Representation of a borrowed [Nginx string]. +/// +/// [Nginx string]: https://nginx.org/en/docs/dev/development_guide.html#string_overview +#[derive(Hash, PartialEq, Eq, PartialOrd, Ord)] +#[repr(transparent)] +pub struct NgxStr([u_char]); + +impl NgxStr { + /// Create an [`NgxStr`] from an [`ngx_str_t`]. + /// + /// [`ngx_str_t`]: https://nginx.org/en/docs/dev/development_guide.html#string_overview + /// + /// # Safety + /// + /// The caller has provided a valid `ngx_str_t` with a `data` pointer that points + /// to range of bytes of at least `len` bytes, whose content remains valid and doesn't + /// change for the lifetime of the returned `NgxStr`. + pub unsafe fn from_ngx_str<'a>(str: ngx_str_t) -> &'a NgxStr { + unsafe { + let bytes: &[u8] = str.as_bytes(); + &*(bytes as *const [u8] as *const NgxStr) + } + } + + /// Create an [NgxStr] from a borrowed byte slice. + #[inline] + pub fn from_bytes(bytes: &[u8]) -> &Self { + // SAFETY: An `NgxStr` is identical to a `[u8]` slice, given `u_char` is an alias for `u8` + unsafe { &*(bytes as *const [u8] as *const NgxStr) } + } + + /// Create a mutable [NgxStr] from a borrowed byte slice. + #[inline] + pub fn from_bytes_mut(bytes: &mut [u8]) -> &mut Self { + // SAFETY: An `NgxStr` is identical to a `[u8]` slice, given `u_char` is an alias for `u8` + unsafe { &mut *(bytes as *mut [u8] as *mut NgxStr) } + } + + /// Access the [`NgxStr`] as a byte slice. + pub fn as_bytes(&self) -> &[u8] { + &self.0 + } + + /// Yields a `&str` slice if the [`NgxStr`] contains valid UTF-8. + pub fn to_str(&self) -> Result<&str, Utf8Error> { + str::from_utf8(self.as_bytes()) + } + + /// Converts an [`NgxStr`] into a [`Cow`], replacing invalid UTF-8 sequences. + /// + /// See [`String::from_utf8_lossy`]. + #[cfg(feature = "alloc")] + pub fn to_string_lossy(&self) -> Cow<'_, str> { + String::from_utf8_lossy(self.as_bytes()) + } + + /// Returns `true` if the [`NgxStr`] is empty, otherwise `false`. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl AsRef<[u8]> for NgxStr { + #[inline] + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + +impl AsMut<[u8]> for NgxStr { + #[inline] + fn as_mut(&mut self) -> &mut [u8] { + &mut self.0 + } +} + +impl fmt::Debug for NgxStr { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // XXX: Use debug_tuple() and feature(debug_closure_helpers) once it's stabilized + f.write_str("NgxStr(")?; + nginx_sys::detail::debug_bytes(f, &self.0)?; + f.write_str(")") + } +} + +impl Default for &NgxStr { + fn default() -> Self { + NgxStr::from_bytes(&[]) + } +} + +impl fmt::Display for NgxStr { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + nginx_sys::detail::display_bytes(f, &self.0) + } +} + +macro_rules! impl_partial_ord_eq_from { + ($self:ty, $other:ty) => { impl_partial_ord_eq_from!($self, $other;); }; + + ($self:ty, $other:ty; $($args:tt)*) => { + impl<'a, $($args)*> From<$other> for &'a NgxStr { + #[inline] + fn from(other: $other) -> Self { + let other: &[u8] = other.as_ref(); + NgxStr::from_bytes(other) + } + } + + impl_partial_eq!($self, $other; $($args)*); + impl_partial_ord!($self, $other; $($args)*); + }; +} + +macro_rules! impl_partial_eq { + ($self:ty, $other:ty) => { impl_partial_eq!($self, $other;); }; + + ($self:ty, $other:ty; $($args:tt)*) => { + impl<'a, $($args)*> PartialEq<$other> for $self { + #[inline] + fn eq(&self, other: &$other) -> bool { + let other: &[u8] = other.as_ref(); + PartialEq::eq(self.as_bytes(), other) + } + } + + impl<'a, $($args)*> PartialEq<$self> for $other { + #[inline] + fn eq(&self, other: &$self) -> bool { + let this: &[u8] = self.as_ref(); + PartialEq::eq(this, other.as_bytes()) + } + } + }; +} + +macro_rules! impl_partial_ord { + ($self:ty, $other:ty) => { impl_partial_ord!($self, $other;); }; + + ($self:ty, $other:ty; $($args:tt)*) => { + impl<'a, $($args)*> PartialOrd<$other> for $self { + #[inline] + fn partial_cmp(&self, other: &$other) -> Option { + let other: &[u8] = other.as_ref(); + PartialOrd::partial_cmp(self.as_bytes(), other) + } + } + + impl<'a, $($args)*> PartialOrd<$self> for $other { + #[inline] + fn partial_cmp(&self, other: &$self) -> Option { + let this: &[u8] = self.as_ref(); + PartialOrd::partial_cmp(this, other.as_bytes()) + } + } + }; +} + +impl_partial_eq!(NgxStr, [u8]); +impl_partial_eq!(NgxStr, [u8; N]; const N: usize); +impl_partial_eq!(NgxStr, str); +impl_partial_eq!(NgxStr, ngx_str_t); +impl_partial_eq!(&'a NgxStr, ngx_str_t); +impl_partial_ord!(NgxStr, [u8]); +impl_partial_ord!(NgxStr, [u8; N]; const N: usize); +impl_partial_ord!(NgxStr, str); +impl_partial_ord!(NgxStr, ngx_str_t); +impl_partial_ord!(&'a NgxStr, ngx_str_t); +impl_partial_ord_eq_from!(NgxStr, &'a [u8]); +impl_partial_ord_eq_from!(NgxStr, &'a [u8; N]; const N: usize); +impl_partial_ord_eq_from!(NgxStr, &'a str); + +#[cfg(feature = "alloc")] +mod _alloc { + use core::borrow::Borrow; + use core::hash; + use core::ops; + use core::ptr; + + use super::*; + use crate::allocator::{self, Allocator}; + use crate::collections::{TryReserveError, Vec}; + + /// Owned byte string type with Allocator support. + /// + /// Inspired by [bstr] and unstable [feature(bstr)], with two important differences: + /// - Allocator always have to be specified, + /// - any allocating methods are failible and require explicit handling of the result. + /// + /// [bstr]: https://docs.rs/bstr/latest/bstr/ + /// [feature(bstr)]: https://github.com/rust-lang/rust/issues/134915 + #[derive(Clone)] + #[repr(transparent)] + pub struct NgxString(Vec) + where + A: Allocator + Clone; + + impl NgxString + where + A: Allocator + Clone, + { + /// Constructs a new, empty `NgxString`. + /// + /// No allocations will be made until data is added to the string. + pub fn new_in(alloc: A) -> Self { + Self(Vec::new_in(alloc)) + } + + /// Tries to construct a new `NgxString` from a byte slice. + #[inline] + pub fn try_from_bytes_in( + bytes: impl AsRef<[u8]>, + alloc: A, + ) -> Result { + let mut this = Self::new_in(alloc); + this.try_reserve_exact(bytes.as_ref().len())?; + this.0.extend_from_slice(bytes.as_ref()); + Ok(this) + } + + /// Returns a reference to the underlying allocator + #[inline] + pub fn allocator(&self) -> &A { + self.0.allocator() + } + + /// Returns this `NgxString`'s capacity, in bytes. + #[inline] + pub fn capacity(&self) -> usize { + self.0.capacity() + } + + /// Returns `true` if this `NgxString` has a length of zero, and `false` otherwise. + #[inline] + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Return this `NgxString`'s length, in bytes. + #[inline] + pub fn len(&self) -> usize { + self.0.len() + } + + /// Appends bytes if there is sufficient spare capacity. + /// + /// Returns the number of remaining bytes on overflow. + #[inline] + pub fn append_within_capacity(&mut self, other: impl AsRef<[u8]>) -> Result<(), usize> { + let other = other.as_ref(); + if self.0.len() == self.0.capacity() { + return Err(other.len()); + } + + let n = cmp::min(self.0.capacity() - self.0.len(), other.len()); + unsafe { + // SAFETY: + // - self.0 has at least n writable bytes allocated past self.0.len(), + // - other has at least n bytes available for reading. + // - self.0 internal buffer will be initialized until len + n after this operation + // - other is not borrowed from `self` + let p = self.0.as_mut_ptr().add(self.0.len()); + ptr::copy_nonoverlapping(other.as_ptr(), p, n); + self.0.set_len(self.0.len() + n); + } + + match other.len() - n { + 0 => Ok(()), + x => Err(x), + } + } + + /// Tries to append the bytes to the `NgxString`. + #[inline] + pub fn try_append(&mut self, other: impl AsRef<[u8]>) -> Result<(), TryReserveError> { + let other = other.as_ref(); + self.0.try_reserve_exact(other.len())?; + self.0.extend_from_slice(other); + Ok(()) + } + + /// Tries to reserve capacity for at least `additional` more bytes. + #[inline] + pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.0.try_reserve(additional) + } + + /// Tries to reserve the minimum capacity for at least `additional` more bytes. + #[inline] + pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> { + self.0.try_reserve_exact(additional) + } + + #[inline] + pub(crate) fn as_bytes(&self) -> &[u8] { + &self.0 + } + + #[inline] + pub(crate) fn as_bytes_mut(&mut self) -> &mut [u8] { + &mut self.0 + } + + #[inline] + pub(crate) fn as_ngx_str(&self) -> &NgxStr { + NgxStr::from_bytes(self.0.as_slice()) + } + + #[inline] + pub(crate) fn as_ngx_str_mut(&mut self) -> &mut NgxStr { + NgxStr::from_bytes_mut(self.0.as_mut_slice()) + } + + /// Creates NgxString directly from a pointer, a capacity, a length and an allocator. + /// + /// # Safety + /// + /// See [Vec::from_raw_parts_in] + #[inline] + pub unsafe fn from_raw_parts( + ptr: *mut u8, + length: usize, + capacity: usize, + alloc: A, + ) -> Self { + unsafe { Self(Vec::from_raw_parts_in(ptr, length, capacity, alloc)) } + } + + /// Splits the NgxString into its raw components. + /// + /// The caller becomes responsible for the memory previously managed by this NgxString. + #[inline] + pub fn into_raw_parts(self) -> (*mut u8, usize, usize, A) { + self.0.into_raw_parts_with_alloc() + } + } + + impl AsRef for NgxString + where + A: Allocator + Clone, + { + fn as_ref(&self) -> &NgxStr { + self.as_ngx_str() + } + } + + impl AsMut for NgxString + where + A: Allocator + Clone, + { + fn as_mut(&mut self) -> &mut NgxStr { + self.as_ngx_str_mut() + } + } + + impl AsRef<[u8]> for NgxString + where + A: Allocator + Clone, + { + #[inline] + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } + } + + impl AsMut<[u8]> for NgxString + where + A: Allocator + Clone, + { + #[inline] + fn as_mut(&mut self) -> &mut [u8] { + self.as_bytes_mut() + } + } + + impl Borrow for NgxString + where + A: Allocator + Clone, + { + fn borrow(&self) -> &NgxStr { + self.as_ngx_str() + } + } + + impl Borrow<[u8]> for NgxString + where + A: Allocator + Clone, + { + fn borrow(&self) -> &[u8] { + self.0.as_slice() + } + } + + impl fmt::Debug for NgxString + where + A: Allocator + Clone, + { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // XXX: Use debug_tuple() and feature(debug_closure_helpers) once it's stabilized + f.write_str("NgxString(")?; + nginx_sys::detail::debug_bytes(f, &self.0)?; + f.write_str(")") + } + } + + impl ops::Deref for NgxString + where + A: Allocator + Clone, + { + type Target = NgxStr; + + fn deref(&self) -> &Self::Target { + self.as_ngx_str() + } + } + + impl ops::DerefMut for NgxString + where + A: Allocator + Clone, + { + fn deref_mut(&mut self) -> &mut Self::Target { + self.as_ngx_str_mut() + } + } + + impl fmt::Display for NgxString + where + A: Allocator + Clone, + { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self.as_ngx_str(), f) + } + } + + impl hash::Hash for NgxString + where + A: Allocator + Clone, + { + fn hash(&self, state: &mut H) { + self.0.hash(state); + } + } + + // `NgxString`'s with different allocators should be comparable + + impl PartialEq> for NgxString + where + A1: Allocator + Clone, + A2: Allocator + Clone, + { + fn eq(&self, other: &NgxString) -> bool { + PartialEq::eq(self.as_bytes(), other.as_bytes()) + } + } + + impl Eq for NgxString where A: Allocator + Clone {} + + impl PartialOrd> for NgxString + where + A1: Allocator + Clone, + A2: Allocator + Clone, + { + fn partial_cmp(&self, other: &NgxString) -> Option { + Some(Ord::cmp(self.as_bytes(), other.as_bytes())) + } + } + + impl Ord for NgxString + where + A: Allocator + Clone, + { + fn cmp(&self, other: &Self) -> cmp::Ordering { + Ord::cmp(self.as_bytes(), other.as_bytes()) + } + } + + impl allocator::TryCloneIn for NgxString { + type Target = NgxString; + + fn try_clone_in( + &self, + alloc: A, + ) -> Result, allocator::AllocError> { + NgxString::try_from_bytes_in(self.as_bytes(), alloc).map_err(|_| allocator::AllocError) + } + } + + impl fmt::Write for NgxString + where + A: Allocator + Clone, + { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.append_within_capacity(s).map_err(|_| fmt::Error) + } + } + + // Implement byte comparisons directly, leave the rest to Deref. + + impl_partial_eq!(NgxString, &'a [u8]; A: Allocator + Clone); + impl_partial_eq!(NgxString, &'a [u8; N]; A: Allocator + Clone, const N: usize); + impl_partial_eq!(NgxString, &'a NgxStr; A: Allocator + Clone); + impl_partial_eq!(NgxString, ngx_str_t; A: Allocator + Clone); + + impl_partial_ord!(NgxString, &'a [u8]; A: Allocator + Clone); + impl_partial_ord!(NgxString, &'a [u8; N]; A: Allocator + Clone, const N: usize); + impl_partial_ord!(NgxString, &'a NgxStr; A: Allocator + Clone); + impl_partial_ord!(NgxString, ngx_str_t; A: Allocator + Clone); + + impl_partial_eq!(NgxStr, String); + impl_partial_eq!(&'a NgxStr, String); + impl_partial_ord!(NgxStr, String); + impl_partial_ord!(&'a NgxStr, String); + impl_partial_ord_eq_from!(NgxStr, &'a String); +} + +#[cfg(test)] +mod tests { + extern crate alloc; + + use alloc::string::ToString; + + use super::*; + + #[test] + fn test_str_comparisons() { + let string = "test".to_string(); + let ngx_string = ngx_str_t { data: string.as_ptr().cast_mut(), len: string.len() }; + let ns: &NgxStr = string.as_bytes().into(); + + #[cfg(feature = "alloc")] + assert_eq!(string, ns); + assert_eq!(ngx_string, ns); + assert_eq!(string.as_bytes(), ns); + assert_eq!(string.as_str(), ns); + assert_eq!(b"test", ns); + assert_eq!("test", ns); + + #[cfg(feature = "alloc")] + assert_eq!(ns, string); + assert_eq!(ns, ngx_string); + assert_eq!(ns, string.as_bytes()); + assert_eq!(ns, string.as_str()); + assert_eq!(ns, b"test"); + assert_eq!(ns, "test"); + } + + #[test] + #[cfg(feature = "alloc")] + fn test_string_comparisons() { + use crate::allocator::Global; + + let string = "test".to_string(); + let ngx_string = ngx_str_t { data: string.as_ptr().cast_mut(), len: string.len() }; + let borrowed: &NgxStr = string.as_bytes().into(); + let owned = NgxString::try_from_bytes_in(&string, Global).unwrap(); + + assert_eq!(string.as_bytes(), owned); + assert_eq!(ngx_string, owned); + assert_eq!(borrowed, owned); + assert_eq!(b"test", owned); + assert_eq!(owned, string.as_bytes()); + assert_eq!(owned, ngx_string); + assert_eq!(owned, borrowed); + assert_eq!(owned, b"test"); + + // String comparisons via Deref + assert_eq!(string, *owned); + assert_eq!(string.as_str(), *owned); + assert_eq!("test", *owned); + assert_eq!(*owned, string); + assert_eq!(*owned, string.as_str()); + assert_eq!(*owned, "test"); + } + + #[test] + #[cfg(feature = "alloc")] + fn test_string_write() { + use core::fmt::Write; + + use crate::allocator::Global; + + let h = NgxStr::from_bytes(b"Hello"); + let w = NgxStr::from_bytes(b"world"); + + let mut s = NgxString::new_in(Global); + s.try_reserve(16).expect("reserve"); + + // Remember ptr and len of internal buffer + let saved = (s.as_bytes().as_ptr(), s.capacity()); + + write!(s, "{h} {w}!").expect("write"); + + assert_eq!(s, b"Hello world!"); + assert_eq!((s.as_bytes().as_ptr(), s.capacity()), saved); + } + + #[test] + fn test_lifetimes() { + let a: &NgxStr = "Hello World!".into(); + + let s = "Hello World!".to_string(); + let b: &NgxStr = s.as_bytes().into(); + + // The compiler should detect that s is borrowed and fail. + // drop(s); // ☢️ + + assert_eq!(a.0, b.0); + } +} diff --git a/source/rust/vendor/ngx-rust/src/ffi/mod.rs b/source/rust/vendor/ngx-rust/src/ffi/mod.rs new file mode 100644 index 0000000..887a73e --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/ffi/mod.rs @@ -0,0 +1 @@ +pub use nginx_sys::*; diff --git a/source/rust/vendor/ngx-rust/src/http/conf.rs b/source/rust/vendor/ngx-rust/src/http/conf.rs new file mode 100644 index 0000000..c6e9d10 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/http/conf.rs @@ -0,0 +1,373 @@ +use ::core::ptr::NonNull; + +use crate::ffi::{ + ngx_http_conf_ctx_t, ngx_http_core_srv_conf_t, ngx_http_request_t, + ngx_http_upstream_srv_conf_t, ngx_module_t, +}; +use crate::http::HttpModule; + +/// Utility trait for types containing HTTP module configuration +pub trait HttpModuleConfExt { + /// Get a non-null reference to the main configuration structure for HTTP module + /// + /// # Safety + /// Caller must ensure that type `T` matches the configuration type for the specified module. + #[inline] + unsafe fn http_main_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { + None + } + + /// Get a non-null reference to the server configuration structure for HTTP module + /// + /// # Safety + /// Caller must ensure that type `T` matches the configuration type for the specified module. + #[inline] + unsafe fn http_server_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { + None + } + + /// Get a non-null reference to the location configuration structure for HTTP module + /// + /// Applies to a single `location`, `if` or `limit_except` block + /// + /// # Safety + /// Caller must ensure that type `T` matches the configuration type for the specified module. + #[inline] + unsafe fn http_location_conf_unchecked(&self, _module: &ngx_module_t) -> Option> { + None + } +} + +impl HttpModuleConfExt for crate::ffi::ngx_http_conf_ctx_t { + #[inline] + unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + NonNull::new(unsafe { *self.main_conf.add(module.ctx_index) }.cast()) + } + + #[inline] + unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + NonNull::new(unsafe { *self.srv_conf.add(module.ctx_index) }.cast()) + } + + #[inline] + unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + NonNull::new(unsafe { *self.loc_conf.add(module.ctx_index) }.cast()) + } +} + +impl HttpModuleConfExt for crate::ffi::ngx_cycle_t { + #[inline] + unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + let http_conf = unsafe { self.conf_ctx.add(nginx_sys::ngx_http_module.index).as_ref()? }; + let conf_ctx = (*http_conf).cast::(); + unsafe { conf_ctx.as_ref()?.http_main_conf_unchecked(module) } + } +} + +impl HttpModuleConfExt for crate::ffi::ngx_conf_t { + #[inline] + unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + let conf_ctx = self.ctx.cast::(); + unsafe { conf_ctx.as_ref()?.http_main_conf_unchecked(module) } + } + + #[inline] + unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + let conf_ctx = self.ctx.cast::(); + unsafe { + let conf_ctx = conf_ctx.as_ref()?; + NonNull::new((*conf_ctx.srv_conf.add(module.ctx_index)).cast()) + } + } + + #[inline] + unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + let conf_ctx = self.ctx.cast::(); + unsafe { conf_ctx.as_ref()?.http_location_conf_unchecked(module) } + } +} + +impl HttpModuleConfExt for crate::ffi::ngx_http_connection_t { + #[inline] + unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { self.conf_ctx.as_ref()?.http_main_conf_unchecked(module) } + } + + #[inline] + unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { self.conf_ctx.as_ref()?.http_server_conf_unchecked(module) } + } + + #[inline] + unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { self.conf_ctx.as_ref()?.http_location_conf_unchecked(module) } + } +} + +impl HttpModuleConfExt for ngx_http_core_srv_conf_t { + #[inline] + unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { self.ctx.as_ref()?.http_main_conf_unchecked(module) } + } + + #[inline] + unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { self.ctx.as_ref()?.http_server_conf_unchecked(module) } + } + + #[inline] + unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { self.ctx.as_ref()?.http_location_conf_unchecked(module) } + } +} + +impl HttpModuleConfExt for ngx_http_request_t { + #[inline] + unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + NonNull::new(unsafe { *self.main_conf.add(module.ctx_index) }.cast()) + } + + #[inline] + unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + NonNull::new(unsafe { *self.srv_conf.add(module.ctx_index) }.cast()) + } + + #[inline] + unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + NonNull::new(unsafe { *self.loc_conf.add(module.ctx_index) }.cast()) + } +} + +impl HttpModuleConfExt for ngx_http_upstream_srv_conf_t { + #[inline] + unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + let conf = self.srv_conf; + if conf.is_null() { + return None; + } + NonNull::new(unsafe { *conf.add(module.ctx_index) }.cast()) + } +} + +/// Trait to define and access main module configuration +/// +/// # Safety +/// Caller must ensure that type `HttpModuleMainConf::MainConf` matches the configuration type +/// for the specified module. +pub unsafe trait HttpModuleMainConf: HttpModule { + /// Type for main module configuration + type MainConf; + /// Get reference to main module configuration + fn main_conf(o: &impl HttpModuleConfExt) -> Option<&'static Self::MainConf> { + unsafe { Some(o.http_main_conf_unchecked(Self::module())?.as_ref()) } + } + /// Get mutable reference to main module configuration + fn main_conf_mut(o: &impl HttpModuleConfExt) -> Option<&'static mut Self::MainConf> { + unsafe { Some(o.http_main_conf_unchecked(Self::module())?.as_mut()) } + } +} + +/// Trait to define and access server-specific module configuration +/// +/// # Safety +/// Caller must ensure that type `HttpModuleServerConf::ServerConf` matches the configuration type +/// for the specified module. +pub unsafe trait HttpModuleServerConf: HttpModule { + /// Type for server-specific module configuration + type ServerConf; + /// Get reference to server-specific module configuration + fn server_conf(o: &impl HttpModuleConfExt) -> Option<&'static Self::ServerConf> { + unsafe { Some(o.http_server_conf_unchecked(Self::module())?.as_ref()) } + } + /// Get mutable reference to server-specific module configuration + fn server_conf_mut(o: &impl HttpModuleConfExt) -> Option<&'static mut Self::ServerConf> { + unsafe { Some(o.http_server_conf_unchecked(Self::module())?.as_mut()) } + } +} + +/// Trait to define and access location-specific module configuration +/// +/// Applies to a single `location`, `if` or `limit_except` block +/// +/// # Safety +/// Caller must ensure that type `HttpModuleLocationConf::LocationConf` matches the configuration +/// type for the specified module. +pub unsafe trait HttpModuleLocationConf: HttpModule { + /// Type for location-specific module configuration + type LocationConf; + /// Get reference to location-specific module configuration + fn location_conf(o: &impl HttpModuleConfExt) -> Option<&'static Self::LocationConf> { + unsafe { Some(o.http_location_conf_unchecked(Self::module())?.as_ref()) } + } + /// Get mutable reference to location-specific module configuration + fn location_conf_mut(o: &impl HttpModuleConfExt) -> Option<&'static mut Self::LocationConf> { + unsafe { Some(o.http_location_conf_unchecked(Self::module())?.as_mut()) } + } +} + +mod core { + use crate::allocator::AllocError; + use crate::{ + ffi::{ + ngx_http_core_loc_conf_t, ngx_http_core_main_conf_t, ngx_http_core_module, + ngx_http_core_srv_conf_t, + }, + http::{HttpModuleMainConf, HttpRequestHandler}, + ngx_conf_log_error, + }; + + /// Auxiliary structure to access `ngx_http_core_module` configuration. + pub struct NgxHttpCoreModule; + + impl crate::http::HttpModule for NgxHttpCoreModule { + fn module() -> &'static crate::ffi::ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_core_module) } + } + } + unsafe impl crate::http::HttpModuleMainConf for NgxHttpCoreModule { + type MainConf = ngx_http_core_main_conf_t; + } + unsafe impl crate::http::HttpModuleServerConf for NgxHttpCoreModule { + type ServerConf = ngx_http_core_srv_conf_t; + } + unsafe impl crate::http::HttpModuleLocationConf for NgxHttpCoreModule { + type LocationConf = ngx_http_core_loc_conf_t; + } + + /// HTTP phases in which a module can register handlers. + #[repr(usize)] + pub enum HttpPhase { + /// Post-read phase + PostRead = crate::ffi::ngx_http_phases_NGX_HTTP_POST_READ_PHASE as _, + /// Server rewrite phase + ServerRewrite = crate::ffi::ngx_http_phases_NGX_HTTP_SERVER_REWRITE_PHASE as _, + /// Find configuration phase + FindConfig = crate::ffi::ngx_http_phases_NGX_HTTP_FIND_CONFIG_PHASE as _, + /// Rewrite phase + Rewrite = crate::ffi::ngx_http_phases_NGX_HTTP_REWRITE_PHASE as _, + /// Post-rewrite phase + PostRewrite = crate::ffi::ngx_http_phases_NGX_HTTP_POST_REWRITE_PHASE as _, + /// Pre-access phase + Preaccess = crate::ffi::ngx_http_phases_NGX_HTTP_PREACCESS_PHASE as _, + /// Access phase + Access = crate::ffi::ngx_http_phases_NGX_HTTP_ACCESS_PHASE as _, + /// Post-access phase + PostAccess = crate::ffi::ngx_http_phases_NGX_HTTP_POST_ACCESS_PHASE as _, + /// Pre-content phase + PreContent = crate::ffi::ngx_http_phases_NGX_HTTP_PRECONTENT_PHASE as _, + /// Content phase + Content = crate::ffi::ngx_http_phases_NGX_HTTP_CONTENT_PHASE as _, + /// Log phase + Log = crate::ffi::ngx_http_phases_NGX_HTTP_LOG_PHASE as _, + } + + /// Register a request handler for a specified phase. + /// This function must be called from the module's `postconfiguration()` function. + pub fn add_phase_handler(cf: &mut nginx_sys::ngx_conf_t) -> Result<(), AllocError> + where + H: HttpRequestHandler, + { + let cmcf = NgxHttpCoreModule::main_conf_mut(cf).expect("http core main conf"); + let h: *mut nginx_sys::ngx_http_handler_pt = unsafe { + nginx_sys::ngx_array_push(&raw mut cmcf.phases[H::PHASE as usize].handlers).cast() + }; + if h.is_null() { + ngx_conf_log_error!( + nginx_sys::NGX_LOG_EMERG, + cf, + "failed to register {} handler", + H::name(), + ); + return Err(AllocError); + } + // set an H::PHASE phase handler + unsafe { + *h = Some(crate::http::raw_handler::); + } + Ok(()) + } +} + +pub use core::{HttpPhase, NgxHttpCoreModule, add_phase_handler}; + +#[cfg(ngx_feature = "http_ssl")] +mod ssl { + use crate::ffi::{ngx_http_ssl_module, ngx_http_ssl_srv_conf_t}; + + /// Auxiliary structure to access `ngx_http_ssl_module` configuration. + pub struct NgxHttpSslModule; + + impl crate::http::HttpModule for NgxHttpSslModule { + fn module() -> &'static crate::ffi::ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_ssl_module) } + } + } + unsafe impl crate::http::HttpModuleServerConf for NgxHttpSslModule { + type ServerConf = ngx_http_ssl_srv_conf_t; + } +} +#[cfg(ngx_feature = "http_ssl")] +pub use ssl::NgxHttpSslModule; + +mod upstream { + use crate::ffi::{ + ngx_http_upstream_main_conf_t, ngx_http_upstream_module, ngx_http_upstream_srv_conf_t, + }; + + /// Auxiliary structure to access `ngx_http_upstream_module` configuration. + pub struct NgxHttpUpstreamModule; + + impl crate::http::HttpModule for NgxHttpUpstreamModule { + fn module() -> &'static crate::ffi::ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_upstream_module) } + } + } + unsafe impl crate::http::HttpModuleMainConf for NgxHttpUpstreamModule { + type MainConf = ngx_http_upstream_main_conf_t; + } + unsafe impl crate::http::HttpModuleServerConf for NgxHttpUpstreamModule { + type ServerConf = ngx_http_upstream_srv_conf_t; + } +} + +pub use upstream::NgxHttpUpstreamModule; + +#[cfg(all(nginx1_25_1, ngx_feature = "http_v2"))] +mod http_v2 { + use crate::ffi::{ngx_http_v2_module, ngx_http_v2_srv_conf_t}; + + /// Auxiliary structure to access `ngx_http_v2_module` configuration. + pub struct NgxHttpV2Module; + + impl crate::http::HttpModule for NgxHttpV2Module { + fn module() -> &'static crate::ffi::ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_v2_module) } + } + } + unsafe impl crate::http::HttpModuleServerConf for NgxHttpV2Module { + type ServerConf = ngx_http_v2_srv_conf_t; + } +} +// ngx_http_v2_module was not exposed by default until aefd862a +#[cfg(all(nginx1_25_1, ngx_feature = "http_v2"))] +pub use http_v2::NgxHttpV2Module; + +#[cfg(ngx_feature = "http_v3")] +mod http_v3 { + use crate::ffi::{ngx_http_v3_module, ngx_http_v3_srv_conf_t}; + + /// Auxiliary structure to access `ngx_http_v3_module` configuration. + pub struct NgxHttpV3Module; + + impl crate::http::HttpModule for NgxHttpV3Module { + fn module() -> &'static crate::ffi::ngx_module_t { + unsafe { &*::core::ptr::addr_of!(ngx_http_v3_module) } + } + } + unsafe impl crate::http::HttpModuleServerConf for NgxHttpV3Module { + type ServerConf = ngx_http_v3_srv_conf_t; + } +} + +#[cfg(ngx_feature = "http_v3")] +pub use http_v3::NgxHttpV3Module; diff --git a/source/rust/vendor/ngx-rust/src/http/mod.rs b/source/rust/vendor/ngx-rust/src/http/mod.rs new file mode 100644 index 0000000..00c329a --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/http/mod.rs @@ -0,0 +1,10 @@ +mod conf; +mod module; +mod request; +mod status; +mod upstream; + +pub use conf::*; +pub use module::*; +pub use request::*; +pub use status::*; diff --git a/source/rust/vendor/ngx-rust/src/http/module.rs b/source/rust/vendor/ngx-rust/src/http/module.rs new file mode 100644 index 0000000..7a9292c --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/http/module.rs @@ -0,0 +1,173 @@ +use core::error; +use core::ffi::{c_char, c_void}; +use core::fmt; +use core::ptr; + +use crate::core::NGX_CONF_ERROR; +use crate::core::*; +use crate::ffi::*; + +/// MergeConfigError - configuration cannot be merged with levels above. +#[derive(Debug)] +pub enum MergeConfigError { + /// No value provided for configuration argument + NoValue, +} + +impl error::Error for MergeConfigError {} + +impl fmt::Display for MergeConfigError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match self { + MergeConfigError::NoValue => "no value".fmt(fmt), + } + } +} + +/// The `Merge` trait provides a method for merging configuration down through each level. +/// +/// A module configuration should implement this trait for setting its configuration throughout +/// each level. +pub trait Merge { + /// Module merge function. + /// + /// # Returns + /// Result, Ok on success or MergeConfigError on failure. + fn merge(&mut self, prev: &Self) -> Result<(), MergeConfigError>; +} + +impl Merge for () { + fn merge(&mut self, _prev: &Self) -> Result<(), MergeConfigError> { + Ok(()) + } +} + +/// The `HTTPModule` trait provides the NGINX configuration stage interface. +/// +/// These functions allocate structures, initialize them, and merge through the configuration +/// layers. +/// +/// See for details. +pub trait HttpModule { + /// Returns reference to a global variable of type [ngx_module_t] created for this module. + fn module() -> &'static ngx_module_t; + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn preconfiguration(_cf: *mut ngx_conf_t) -> ngx_int_t { + Status::NGX_OK.into() + } + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn postconfiguration(_cf: *mut ngx_conf_t) -> ngx_int_t { + Status::NGX_OK.into() + } + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn create_main_conf(cf: *mut ngx_conf_t) -> *mut c_void + where + Self: super::HttpModuleMainConf, + Self::MainConf: Default, + { + unsafe { + let pool = Pool::from_ngx_pool((*cf).pool); + pool.allocate::(Default::default()) as *mut c_void + } + } + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn init_main_conf(_cf: *mut ngx_conf_t, _conf: *mut c_void) -> *mut c_char + where + Self: super::HttpModuleMainConf, + Self::MainConf: Default, + { + ptr::null_mut() + } + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn create_srv_conf(cf: *mut ngx_conf_t) -> *mut c_void + where + Self: super::HttpModuleServerConf, + Self::ServerConf: Default, + { + unsafe { + let pool = Pool::from_ngx_pool((*cf).pool); + pool.allocate::(Default::default()) as *mut c_void + } + } + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn merge_srv_conf( + _cf: *mut ngx_conf_t, + prev: *mut c_void, + conf: *mut c_void, + ) -> *mut c_char + where + Self: super::HttpModuleServerConf, + Self::ServerConf: Merge, + { + unsafe { + let prev = &mut *(prev as *mut Self::ServerConf); + let conf = &mut *(conf as *mut Self::ServerConf); + match conf.merge(prev) { + Ok(_) => ptr::null_mut(), + Err(_) => NGX_CONF_ERROR as _, + } + } + } + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn create_loc_conf(cf: *mut ngx_conf_t) -> *mut c_void + where + Self: super::HttpModuleLocationConf, + Self::LocationConf: Default, + { + unsafe { + let pool = Pool::from_ngx_pool((*cf).pool); + pool.allocate::(Default::default()) as *mut c_void + } + } + + /// # Safety + /// + /// Callers should provide valid non-null `ngx_conf_t` arguments. Implementers must + /// guard against null inputs or risk runtime errors. + unsafe extern "C" fn merge_loc_conf( + _cf: *mut ngx_conf_t, + prev: *mut c_void, + conf: *mut c_void, + ) -> *mut c_char + where + Self: super::HttpModuleLocationConf, + Self::LocationConf: Merge, + { + unsafe { + let prev = &mut *(prev as *mut Self::LocationConf); + let conf = &mut *(conf as *mut Self::LocationConf); + match conf.merge(prev) { + Ok(_) => ptr::null_mut(), + Err(_) => NGX_CONF_ERROR as _, + } + } + } +} diff --git a/source/rust/vendor/ngx-rust/src/http/request.rs b/source/rust/vendor/ngx-rust/src/http/request.rs new file mode 100644 index 0000000..64d7e6e --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/http/request.rs @@ -0,0 +1,802 @@ +use core::error; +use core::ffi::c_void; +use core::fmt; +use core::ptr::NonNull; +use core::slice; +use core::str::FromStr; + +use crate::core::*; +use crate::ffi::*; +use crate::http::HttpPhase; +use crate::http::status::*; + +/// Define a static request handler. +/// +/// Handlers are expected to take a single [`Request`] argument and return a [`Status`]. +#[macro_export] +macro_rules! http_request_handler { + ( $name: ident, $handler: expr ) => { + extern "C" fn $name(r: *mut $crate::ffi::ngx_http_request_t) -> $crate::ffi::ngx_int_t { + let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; + let status: $crate::core::Status = $handler(request); + status.0 + } + }; +} + +/// Define a static post subrequest handler. +/// +/// Handlers are expected to take a single [`Request`] argument and return a [`Status`]. +#[macro_export] +macro_rules! http_subrequest_handler { + ( $name: ident, $handler: expr ) => { + unsafe extern "C" fn $name( + r: *mut $crate::ffi::ngx_http_request_t, + data: *mut ::core::ffi::c_void, + rc: $crate::ffi::ngx_int_t, + ) -> $crate::ffi::ngx_int_t { + $handler(r, data, rc) + } + }; +} + +/// Define a static variable setter. +/// +/// The set handler allows setting the property referenced by the variable. +/// The set handler expects a [`Request`], [`mut ngx_variable_value_t`], and a [`usize`]. +/// Variables: +#[macro_export] +macro_rules! http_variable_set { + ( $name: ident, $handler: expr ) => { + unsafe extern "C" fn $name( + r: *mut $crate::ffi::ngx_http_request_t, + v: *mut $crate::ffi::ngx_variable_value_t, + data: usize, + ) { + let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; + $handler(request, v, data); + } + }; +} + +/// Define a static variable evaluator. +/// +/// The get handler is responsible for evaluating a variable in the context of a specific request. +/// Variable evaluators accept a [`Request`] input argument and two output +/// arguments: [`ngx_variable_value_t`] and [`usize`]. +/// Variables: +#[macro_export] +macro_rules! http_variable_get { + ( $name: ident, $handler: expr ) => { + unsafe extern "C" fn $name( + r: *mut $crate::ffi::ngx_http_request_t, + v: *mut $crate::ffi::ngx_variable_value_t, + data: usize, + ) -> $crate::ffi::ngx_int_t { + let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; + let status: $crate::core::Status = $handler(request, v, data); + status.0 + } + }; +} + +/// Trait for converting handler return types into `ngx_int_t`. +/// Any desired error handling / logging logic can be implemented +/// in the `into_handler_status` method. +/// +/// There are predefined implementations for `ngx_int_t`, [`Status`], [`HTTPStatus`], +/// [`Option`] with value type implementing [`IntoHandlerStatus`]. +pub trait IntoHandlerStatus +where + Self: Sized, +{ + /// Convert the handler return type into an `ngx_int_t`. + fn into_handler_status(self, _r: &Request) -> ngx_int_t; +} + +impl IntoHandlerStatus for Option +where + T: IntoHandlerStatus, +{ + #[inline] + fn into_handler_status(self, r: &Request) -> ngx_int_t { + self.map(|val| val.into_handler_status(r)).unwrap_or(NGX_ERROR as _) + } +} + +impl IntoHandlerStatus for ngx_int_t { + #[inline] + fn into_handler_status(self, _r: &Request) -> ngx_int_t { + self + } +} + +impl IntoHandlerStatus for Status { + #[inline] + fn into_handler_status(self, _r: &Request) -> ngx_int_t { + self.0 + } +} + +impl IntoHandlerStatus for HTTPStatus { + #[inline] + fn into_handler_status(self, _r: &Request) -> ngx_int_t { + self.0 as _ + } +} + +/// Trait for static request handler. +pub trait HttpRequestHandler { + /// The phase in which the handler is invoked. + const PHASE: HttpPhase; + /// The return type of the handler. + type Output: IntoHandlerStatus; + /// The handler function. + fn handler(request: &mut Request) -> Self::Output; + /// Handler name for logging purposes. + /// [`core::any::type_name`] is used by default. + fn name() -> &'static str { + core::any::type_name::() + } +} + +/// The C-compatible handler wrapper function. +/// +/// # Safety +/// +/// The caller has provided a valid non-null pointer to an [`ngx_http_request_t`]. +pub(crate) unsafe extern "C" fn raw_handler(r: *mut ngx_http_request_t) -> ngx_int_t +where + H: HttpRequestHandler, +{ + let r = unsafe { Request::from_ngx_http_request(r) }; + H::handler(r).into_handler_status(r) +} + +/// Wrapper struct for an [`ngx_http_request_t`] pointer, providing methods for working with HTTP +/// requests. +/// +/// See +#[repr(transparent)] +pub struct Request(ngx_http_request_t); + +impl<'a> From<&'a Request> for *const ngx_http_request_t { + fn from(request: &'a Request) -> Self { + &raw const request.0 + } +} + +impl<'a> From<&'a mut Request> for *mut ngx_http_request_t { + fn from(request: &'a mut Request) -> Self { + &raw mut request.0 + } +} + +impl AsRef for Request { + fn as_ref(&self) -> &ngx_http_request_t { + &self.0 + } +} + +impl AsMut for Request { + fn as_mut(&mut self) -> &mut ngx_http_request_t { + &mut self.0 + } +} + +impl Request { + /// Create a [`Request`] from an [`ngx_http_request_t`]. + /// + /// # Safety + /// + /// The caller has provided a valid non-null pointer to a valid `ngx_http_request_t` + /// which shares the same representation as `Request`. + pub unsafe fn from_ngx_http_request<'a>(r: *mut ngx_http_request_t) -> &'a mut Request { + unsafe { &mut *r.cast::() } + } + + /// Is this the main request (as opposed to a subrequest)? + pub fn is_main(&self) -> bool { + let main = self.0.main.cast(); + core::ptr::eq(self, main) + } + + /// Request pool. + pub fn pool(&self) -> Pool { + // SAFETY: This request is allocated from `pool`, thus must be a valid pool. + unsafe { Pool::from_ngx_pool(self.0.pool) } + } + + /// Returns the result as an `Option` if it exists, otherwise `None`. + /// + /// The option wraps an ngx_http_upstream_t instance, it will be none when the underlying NGINX + /// request does not have a pointer to a [`ngx_http_upstream_t`] upstream structure. + /// + /// [`ngx_http_upstream_t`] is best described in + /// + pub fn upstream(&self) -> Option<*mut ngx_http_upstream_t> { + if self.0.upstream.is_null() { + return None; + } + Some(self.0.upstream) + } + + /// Pointer to a [`ngx_connection_t`] client connection object. + /// + /// [`ngx_connection_t`]: https://nginx.org/en/docs/dev/development_guide.html#connection + pub fn connection(&self) -> *mut ngx_connection_t { + self.0.connection + } + + /// Pointer to a [`ngx_log_t`]. + /// + /// [`ngx_log_t`]: https://nginx.org/en/docs/dev/development_guide.html#logging + pub fn log(&self) -> *mut ngx_log_t { + unsafe { (*self.connection()).log } + } + + /// Get Module context pointer + fn get_module_ctx_ptr(&self, module: &ngx_module_t) -> *mut c_void { + unsafe { *self.0.ctx.add(module.ctx_index) } + } + + /// Get Module context + pub fn get_module_ctx(&self, module: &ngx_module_t) -> Option<&T> { + let ctx = self.get_module_ctx_ptr(module).cast::(); + // SAFETY: ctx is either NULL or allocated with ngx_p(c)alloc and + // explicitly initialized by the module + unsafe { ctx.as_ref() } + } + + /// Sets the value as the module's context. + /// + /// See + pub fn set_module_ctx(&self, value: *mut c_void, module: &ngx_module_t) { + unsafe { + *self.0.ctx.add(module.ctx_index) = value; + }; + } + + /// Get the value of a [complex value]. + /// + /// [complex value]: https://nginx.org/en/docs/dev/development_guide.html#http_complex_values + pub fn get_complex_value(&self, cv: &ngx_http_complex_value_t) -> Option<&NgxStr> { + let r = (self as *const Request as *mut Request).cast(); + let val = cv as *const ngx_http_complex_value_t as *mut ngx_http_complex_value_t; + // SAFETY: `ngx_http_complex_value` does not mutate `r` or `val` and guarentees that + // a valid Nginx string is stored in `value` if it successfully returns. + unsafe { + let mut value = ngx_str_t::default(); + if ngx_http_complex_value(r, val, &raw mut value) != NGX_OK as ngx_int_t { + return None; + } + Some(NgxStr::from_ngx_str(value)) + } + } + + /// Discard (read and ignore) the [request body]. + /// + /// [request body]: https://nginx.org/en/docs/dev/development_guide.html#http_request_body + pub fn discard_request_body(&mut self) -> Status { + unsafe { Status(ngx_http_discard_request_body(&raw mut self.0)) } + } + + /// Client HTTP [User-Agent]. + /// + /// [User-Agent]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent + pub fn user_agent(&self) -> Option<&NgxStr> { + if !self.0.headers_in.user_agent.is_null() { + unsafe { Some(NgxStr::from_ngx_str((*self.0.headers_in.user_agent).value)) } + } else { + None + } + } + + /// Set HTTP status of response. + pub fn set_status(&mut self, status: HTTPStatus) { + self.0.headers_out.status = status.into(); + } + + /// Add header to the `headers_in` object. + /// + /// See + pub fn add_header_in(&mut self, key: &str, value: &str) -> Option<()> { + let table: *mut ngx_table_elt_t = + unsafe { ngx_list_push(&raw mut self.0.headers_in.headers).cast() }; + unsafe { add_to_ngx_table(table, self.0.pool, key, value) } + } + + /// Add header to the `headers_out` object. + /// + /// See + pub fn add_header_out(&mut self, key: &str, value: &str) -> Option<()> { + let table: *mut ngx_table_elt_t = + unsafe { ngx_list_push(&raw mut self.0.headers_out.headers).cast() }; + unsafe { add_to_ngx_table(table, self.0.pool, key, value) } + } + + /// Set response body [Content-Length]. + /// + /// [Content-Length]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length + pub fn set_content_length_n(&mut self, n: usize) { + self.0.headers_out.content_length_n = n as off_t; + } + + /// Send the output header. + /// + /// Do not call this function until all output headers are set. + pub fn send_header(&mut self) -> Status { + unsafe { Status(ngx_http_send_header(&raw mut self.0)) } + } + + /// Flag indicating that the output does not require a body. + /// + /// For example, this flag is used by `HTTP HEAD` requests. + pub fn header_only(&self) -> bool { + self.0.header_only() != 0 + } + + /// request method + pub fn method(&self) -> Method { + Method::from_ngx(self.0.method) + } + + /// path part of request only + pub fn path(&self) -> &NgxStr { + unsafe { NgxStr::from_ngx_str(self.0.uri) } + } + + /// full uri - containing path and args + pub fn unparsed_uri(&self) -> &NgxStr { + unsafe { NgxStr::from_ngx_str(self.0.unparsed_uri) } + } + + /// Send the [response body]. + /// + /// This function can be called multiple times. + /// Set the `last_buf` flag in the last body buffer. + /// + /// [response body]: https://nginx.org/en/docs/dev/development_guide.html#http_request_body + pub fn output_filter(&mut self, body: &mut ngx_chain_t) -> Status { + unsafe { Status(ngx_http_output_filter(&raw mut self.0, body)) } + } + + /// Perform internal redirect to a location + pub fn internal_redirect(&self, location: &str) -> Status { + assert!(!location.is_empty(), "uri location is empty"); + let uri_ptr = unsafe { &mut ngx_str_t::from_str(self.0.pool, location) as *mut _ }; + + // FIXME: check status of ngx_http_named_location or ngx_http_internal_redirect + if location.starts_with('@') { + unsafe { + ngx_http_named_location((self as *const Request as *mut Request).cast(), uri_ptr); + } + } else { + unsafe { + ngx_http_internal_redirect( + (self as *const Request as *mut Request).cast(), + uri_ptr, + core::ptr::null_mut(), + ); + } + } + Status::NGX_DONE + } + + /// Send a subrequest + pub fn subrequest( + &self, + uri: &str, + module: &ngx_module_t, + post_callback: unsafe extern "C" fn( + *mut ngx_http_request_t, + *mut c_void, + ngx_int_t, + ) -> ngx_int_t, + ) -> Status { + let uri_ptr = unsafe { &mut ngx_str_t::from_str(self.0.pool, uri) as *mut _ }; + // ------------- + // allocate memory and set values for ngx_http_post_subrequest_t + let sub_ptr = self.pool().alloc(core::mem::size_of::()); + + // assert!(sub_ptr.is_null()); + let post_subreq = + sub_ptr as *const ngx_http_post_subrequest_t as *mut ngx_http_post_subrequest_t; + unsafe { + (*post_subreq).handler = Some(post_callback); + // WARN: safety! ensure that ctx is already set + (*post_subreq).data = self.get_module_ctx_ptr(module); + } + // ------------- + + let mut psr: *mut ngx_http_request_t = core::ptr::null_mut(); + let r = unsafe { + ngx_http_subrequest( + (self as *const Request as *mut Request).cast(), + uri_ptr, + core::ptr::null_mut(), + &raw mut psr, + sub_ptr as *mut _, + NGX_HTTP_SUBREQUEST_WAITED as _, + ) + }; + + // previously call of ngx_http_subrequest() would ensure that the pointer is not null + // anymore + let sr = unsafe { &mut *psr }; + + /* + * allocate fake request body to avoid attempts to read it and to make + * sure real body file (if already read) won't be closed by upstream + */ + sr.request_body = + self.pool().alloc(core::mem::size_of::()) as *mut _; + + if sr.request_body.is_null() { + return Status::NGX_ERROR; + } + sr.set_header_only(1 as _); + Status(r) + } + + /// Iterate over headers_in + /// each header item is (&str, &str) (borrowed) + pub fn headers_in_iterator(&self) -> NgxListIterator<'_> { + unsafe { list_iterator(&self.0.headers_in.headers) } + } + + /// Iterate over headers_out + /// each header item is (&str, &str) (borrowed) + pub fn headers_out_iterator(&self) -> NgxListIterator<'_> { + unsafe { list_iterator(&self.0.headers_out.headers) } + } +} + +impl crate::http::HttpModuleConfExt for Request { + #[inline] + unsafe fn http_main_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { + // SAFETY: main_conf[module.ctx_index] is either NULL or allocated with ngx_p(c)alloc + // and explicitly initialized by the module + NonNull::new((*self.0.main_conf.add(module.ctx_index)).cast()) + } + } + + #[inline] + unsafe fn http_server_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { + // SAFETY: srv_conf[module.ctx_index] is either NULL or allocated with ngx_p(c)alloc and + // explicitly initialized by the module + NonNull::new((*self.0.srv_conf.add(module.ctx_index)).cast()) + } + } + + #[inline] + unsafe fn http_location_conf_unchecked(&self, module: &ngx_module_t) -> Option> { + unsafe { + // SAFETY: loc_conf[module.ctx_index] is either NULL or allocated with ngx_p(c)alloc and + // explicitly initialized by the module + NonNull::new((*self.0.loc_conf.add(module.ctx_index)).cast()) + } + } +} + +// trait OnSubRequestDone { + +// } + +impl fmt::Debug for Request { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Request").field("request_", &self.0).finish() + } +} + +/// Iterator for [`ngx_list_t`] types. +/// +/// Implementes the core::iter::Iterator trait. +pub struct NgxListIterator<'a> { + part: Option>, + i: ngx_uint_t, +} +struct ListPart<'a> { + raw: &'a ngx_list_part_t, + arr: &'a [ngx_table_elt_t], +} +impl<'a> From<&'a ngx_list_part_t> for ListPart<'a> { + fn from(raw: &'a ngx_list_part_t) -> Self { + let arr = if raw.nelts != 0 { + unsafe { slice::from_raw_parts(raw.elts.cast(), raw.nelts) } + } else { + &[] + }; + Self { raw, arr } + } +} + +/// Creates new HTTP header iterator +/// +/// # Safety +/// +/// The caller has provided a valid [`ngx_str_t`] which can be dereferenced validly. +pub unsafe fn list_iterator(list: &ngx_list_t) -> NgxListIterator<'_> { + NgxListIterator { part: Some((&list.part).into()), i: 0 } +} + +// iterator for ngx_list_t +impl<'a> Iterator for NgxListIterator<'a> { + // TODO: try to use struct instead of &str pair + // something like pub struct Header(ngx_table_elt_t); + // then header would have key and value + + type Item = (&'a NgxStr, &'a NgxStr); + + fn next(&mut self) -> Option { + let part = self.part.as_mut()?; + if self.i >= part.arr.len() { + if let Some(next_part_raw) = unsafe { part.raw.next.as_ref() } { + // loop back + *part = next_part_raw.into(); + self.i = 0; + } else { + self.part = None; + return None; + } + } + let header = &part.arr[self.i]; + self.i += 1; + unsafe { Some((NgxStr::from_ngx_str(header.key), NgxStr::from_ngx_str(header.value))) } + } +} + +/// A possible error value when converting `Method` +pub struct InvalidMethod { + _priv: (), +} + +/// Request method verb +#[derive(Clone, PartialEq, Eq, Hash)] +pub struct Method(MethodInner); + +impl Method { + /// UNKNOWN + pub const UNKNOWN: Method = Method(MethodInner::Unknown); + + /// GET + pub const GET: Method = Method(MethodInner::Get); + + /// HEAD + pub const HEAD: Method = Method(MethodInner::Head); + + /// POST + pub const POST: Method = Method(MethodInner::Post); + + /// PUT + pub const PUT: Method = Method(MethodInner::Put); + + /// DELETE + pub const DELETE: Method = Method(MethodInner::Delete); + + /// MKCOL + pub const MKCOL: Method = Method(MethodInner::Mkcol); + + /// COPY + pub const COPY: Method = Method(MethodInner::Copy); + + /// MOVE + pub const MOVE: Method = Method(MethodInner::Move); + + /// OPTIONS + pub const OPTIONS: Method = Method(MethodInner::Options); + + /// PROPFIND + pub const PROPFIND: Method = Method(MethodInner::Propfind); + + /// PROPPATCH + pub const PROPPATCH: Method = Method(MethodInner::Proppatch); + + /// LOCK + pub const LOCK: Method = Method(MethodInner::Lock); + + /// UNLOCK + pub const UNLOCK: Method = Method(MethodInner::Unlock); + + /// PATCH + pub const PATCH: Method = Method(MethodInner::Patch); + + /// TRACE + pub const TRACE: Method = Method(MethodInner::Trace); + + /// CONNECT + pub const CONNECT: Method = Method(MethodInner::Connect); + + /// Convert a Method to a &str. + #[inline] + pub fn as_str(&self) -> &str { + match self.0 { + MethodInner::Unknown => "UNKNOWN", + MethodInner::Get => "GET", + MethodInner::Head => "HEAD", + MethodInner::Post => "POST", + MethodInner::Put => "PUT", + MethodInner::Delete => "DELETE", + MethodInner::Mkcol => "MKCOL", + MethodInner::Copy => "COPY", + MethodInner::Move => "MOVE", + MethodInner::Options => "OPTIONS", + MethodInner::Propfind => "PROPFIND", + MethodInner::Proppatch => "PROPPATCH", + MethodInner::Lock => "LOCK", + MethodInner::Unlock => "UNLOCK", + MethodInner::Patch => "PATCH", + MethodInner::Trace => "TRACE", + MethodInner::Connect => "CONNECT", + } + } + + fn from_bytes(_t: &[u8]) -> Result { + todo!() + } + + fn from_ngx(t: ngx_uint_t) -> Method { + let t = t as _; + match t { + crate::ffi::NGX_HTTP_GET => Method(MethodInner::Get), + crate::ffi::NGX_HTTP_HEAD => Method(MethodInner::Head), + crate::ffi::NGX_HTTP_POST => Method(MethodInner::Post), + crate::ffi::NGX_HTTP_PUT => Method(MethodInner::Put), + crate::ffi::NGX_HTTP_DELETE => Method(MethodInner::Delete), + crate::ffi::NGX_HTTP_MKCOL => Method(MethodInner::Mkcol), + crate::ffi::NGX_HTTP_COPY => Method(MethodInner::Copy), + crate::ffi::NGX_HTTP_MOVE => Method(MethodInner::Move), + crate::ffi::NGX_HTTP_OPTIONS => Method(MethodInner::Options), + crate::ffi::NGX_HTTP_PROPFIND => Method(MethodInner::Propfind), + crate::ffi::NGX_HTTP_PROPPATCH => Method(MethodInner::Proppatch), + crate::ffi::NGX_HTTP_LOCK => Method(MethodInner::Lock), + crate::ffi::NGX_HTTP_UNLOCK => Method(MethodInner::Unlock), + crate::ffi::NGX_HTTP_PATCH => Method(MethodInner::Patch), + crate::ffi::NGX_HTTP_TRACE => Method(MethodInner::Trace), + #[cfg(nginx1_21_1)] + crate::ffi::NGX_HTTP_CONNECT => Method(MethodInner::Connect), + _ => Method(MethodInner::Unknown), + } + } +} + +impl AsRef for Method { + #[inline] + fn as_ref(&self) -> &str { + self.as_str() + } +} + +impl<'a> PartialEq<&'a Method> for Method { + #[inline] + fn eq(&self, other: &&'a Method) -> bool { + self == *other + } +} + +impl PartialEq for &Method { + #[inline] + fn eq(&self, other: &Method) -> bool { + *self == other + } +} + +impl PartialEq for Method { + #[inline] + fn eq(&self, other: &str) -> bool { + self.as_ref() == other + } +} + +impl PartialEq for str { + #[inline] + fn eq(&self, other: &Method) -> bool { + self == other.as_ref() + } +} + +impl<'a> PartialEq<&'a str> for Method { + #[inline] + fn eq(&self, other: &&'a str) -> bool { + self.as_ref() == *other + } +} + +impl PartialEq for &str { + #[inline] + fn eq(&self, other: &Method) -> bool { + *self == other.as_ref() + } +} + +impl fmt::Debug for Method { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_ref()) + } +} + +impl fmt::Display for Method { + fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt.write_str(self.as_ref()) + } +} + +impl<'a> From<&'a Method> for Method { + #[inline] + fn from(t: &'a Method) -> Self { + t.clone() + } +} + +impl<'a> TryFrom<&'a [u8]> for Method { + type Error = InvalidMethod; + + #[inline] + fn try_from(t: &'a [u8]) -> Result { + Method::from_bytes(t) + } +} + +impl<'a> TryFrom<&'a str> for Method { + type Error = InvalidMethod; + + #[inline] + fn try_from(t: &'a str) -> Result { + TryFrom::try_from(t.as_bytes()) + } +} + +impl FromStr for Method { + type Err = InvalidMethod; + + #[inline] + fn from_str(t: &str) -> Result { + TryFrom::try_from(t) + } +} + +impl InvalidMethod { + #[allow(dead_code)] + fn new() -> InvalidMethod { + InvalidMethod { _priv: () } + } +} + +impl fmt::Debug for InvalidMethod { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("InvalidMethod") + // skip _priv noise + .finish() + } +} + +impl fmt::Display for InvalidMethod { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("invalid HTTP method") + } +} + +impl error::Error for InvalidMethod {} + +#[derive(Clone, PartialEq, Eq, Hash)] +enum MethodInner { + Unknown, + Get, + Head, + Post, + Put, + Delete, + Mkcol, + Copy, + Move, + Options, + Propfind, + Proppatch, + Lock, + Unlock, + Patch, + Trace, + Connect, +} diff --git a/source/rust/vendor/ngx-rust/src/http/status.rs b/source/rust/vendor/ngx-rust/src/http/status.rs new file mode 100644 index 0000000..a545f65 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/http/status.rs @@ -0,0 +1,208 @@ +use core::{error, fmt}; + +use crate::core::Status; +use crate::ffi::*; + +/// Represents an HTTP status code. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct HTTPStatus(pub ngx_uint_t); + +/// A possible error value when converting a `HTTPStatus` from a `u16` or `&str` +/// +/// This error indicates that the supplied input was not a valid number, was less +/// than 100, or was greater than 599. +#[derive(Debug)] +pub struct InvalidHTTPStatusCode { + _priv: (), +} + +impl InvalidHTTPStatusCode { + fn new() -> InvalidHTTPStatusCode { + InvalidHTTPStatusCode { _priv: () } + } +} + +impl fmt::Display for InvalidHTTPStatusCode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("invalid status code") + } +} + +impl error::Error for InvalidHTTPStatusCode {} + +impl From for Status { + fn from(val: HTTPStatus) -> Self { + Status(val.0 as ngx_int_t) + } +} + +impl From for ngx_int_t { + fn from(val: HTTPStatus) -> Self { + val.0 as _ + } +} + +impl From for ngx_uint_t { + fn from(val: HTTPStatus) -> Self { + val.0 + } +} + +impl fmt::Debug for HTTPStatus { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } +} + +impl HTTPStatus { + /// Convets a u16 to a status code. + #[inline] + pub fn from_u16(src: u16) -> Result { + if !(100..600).contains(&src) { + return Err(InvalidHTTPStatusCode::new()); + } + + Ok(HTTPStatus(src.into())) + } + + /// Converts a &[u8] to a status code. + pub fn from_bytes(src: &[u8]) -> Result { + if src.len() != 3 { + return Err(InvalidHTTPStatusCode::new()); + } + + let a = src[0].wrapping_sub(b'0') as u16; + let b = src[1].wrapping_sub(b'0') as u16; + let c = src[2].wrapping_sub(b'0') as u16; + + if a == 0 || a > 5 || b > 9 || c > 9 { + return Err(InvalidHTTPStatusCode::new()); + } + + let status = (a * 100) + (b * 10) + c; + Ok(HTTPStatus(status.into())) + } +} + +macro_rules! http_status_codes { + ( + $( + $(#[$docs:meta])* + ($num:expr, $konst:ident, $phrase:expr); + )+ + ) => { + impl HTTPStatus { + $( + $(#[$docs])* + pub const $konst: HTTPStatus = HTTPStatus($num); + )+ + + } + } +} + +http_status_codes! { + /// 100 CONTINUE + (100, CONTINUE, "Continue"); + /// 101 SWITCHING_PROTOCOLS + (101, SWITCHING_PROTOCOLS, "Switching Protocols"); + /// 102 PROCESSING + (102, PROCESSING, "Processing"); + /// 200 OK + (200, OK, "OK"); + /// 201 Created + (201, CREATED, "Created"); + /// 202 Accepted + (202, ACCEPTED, "Accepted"); + /// 204 No Content + (204, NO_CONTENT, "No Content"); + /// 206 Partial Content + (206, PARTIAL_CONTENT, "Partial Content"); + + /// 300 SPECIAL_RESPONSE + (300, SPECIAL_RESPONSE, "SPECIAL_RESPONSE"); + /// 301 Moved Permanently + (301, MOVED_PERMANENTLY, "Moved Permanently"); + /// 302 Moved Temporarily + (302, MOVED_TEMPORARILY, "Moved Temporarily"); + /// 303 See Other + (303, SEE_OTHER, "See Other"); + /// 304 Not Modified + (304, NOT_MODIFIED, "Not Modified"); + /// 307 Temporary Redirect + (307, TEMPORARY_REDIRECT, "Temporary Redirect"); + /// 308 Permanent Redirect + (308, PERMANENT_REDIRECT, "Permanent Redirect"); + + /// 400 Bad Request + (400, BAD_REQUEST, "Bad Request"); + /// 401 Unauthorized + (401, UNAUTHORIZED, "Unauthorized"); + /// 403 Forbidden + (403, FORBIDDEN, "Forbidden"); + /// 404 Not Found + (404, NOT_FOUND, "Not Found"); + /// 405 Method Not Allowed + (405, NOT_ALLOWED, "Method Not Allowed"); + /// 408 Request Time Out + (408, REQUEST_TIME_OUT, "Request Time Out"); + /// 409 Conflict + (409, CONFLICT, "Conflict"); + /// 411 Length Required + (411, LENGTH_REQUIRED, "Length Required"); + /// 412 Precondition Failed + (412, PRECONDITION_FAILED, "Precondition Failed"); + /// 413 Payload Too Large + (413, REQUEST_ENTITY_TOO_LARGE, "Payload Too Large"); + /// 414 Request Uri Too Large + (414, REQUEST_URI_TOO_LARGE, "Request Uri Too Large"); + /// 415 Unsupported Media Type + (415, UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); + /// 416 Range Not Satisfiable + (416, RANGE_NOT_SATISFIABLE, "Range Not Satisfiable"); + /// 421 Misdirected Request + (421, MISDIRECTED_REQUEST, "Misdirected Request"); + /// 429 Too Many Requests + (429, TOO_MANY_REQUESTS, "Too Many Requests"); + + // /* Our own HTTP codes */ + // /* The special code to close connection without any response */ + /// 444 CLOSE + (444, CLOSE, "CLOSE"); + + /// 494 NGINX_CODES + (494, NGINX_CODES, "NGINX_CODES"); + + /// 494 REQUEST_HEADER_TOO_LARGE + (494, REQUEST_HEADER_TOO_LARGE, "REQUEST_HEADER_TOO_LARGE"); + + /// 495 NGX_HTTPS_CERT_ERROR + (495, HTTPS_CERT_ERROR, "NGX_HTTPS_CERT_ERROR"); + /// 496 NGX_HTTPS_NO_CERT + (496, HTTPS_NO_CERT, "NGX_HTTPS_NO_CERT"); + + // /* + // * We use the special code for the plain HTTP requests that are sent to + // * HTTPS port to distinguish it from 4XX in an error page redirection + // */ + /// 497 TO_HTTPS + (497, TO_HTTPS, "TO_HTTPS"); + + /// 499 CLIENT_CLOSED_REQUEST + (499, CLIENT_CLOSED_REQUEST, "CLIENT_CLOSED_REQUEST"); + + /// 500 INTERNAL_SERVER_ERROR + (500, INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR"); + /// 501 NOT_IMPLEMENTED + (501, NOT_IMPLEMENTED, "NOT_IMPLEMENTED"); + /// 502 BAD_GATEWAY + (502, BAD_GATEWAY, "BAD_GATEWAY"); + /// 503 SERVICE_UNAVAILABLE + (503, SERVICE_UNAVAILABLE, "SERVICE_UNAVAILABLE"); + /// 504 GATEWAY_TIME_OUT + (504, GATEWAY_TIME_OUT, "GATEWAY_TIME_OUT"); + /// 505 VERSION_NOT_SUPPORTED + (505, VERSION_NOT_SUPPORTED, "VERSION_NOT_SUPPORTED"); + /// 507 INSUFFICIENT_STORAGE + (507, INSUFFICIENT_STORAGE, "INSUFFICIENT_STORAGE"); +} diff --git a/source/rust/vendor/ngx-rust/src/http/upstream.rs b/source/rust/vendor/ngx-rust/src/http/upstream.rs new file mode 100644 index 0000000..cfd3986 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/http/upstream.rs @@ -0,0 +1,24 @@ +/// Define a static upstream peer initializer +/// +/// Initializes the upstream 'get', 'free', and 'session' callbacks and gives the module writer an +/// opportunity to set custom data. +/// +/// This macro will define the NGINX callback type: +/// `typedef ngx_int_t (*ngx_http_upstream_init_peer_pt)(ngx_http_request_t *r, +/// ngx_http_upstream_srv_conf_t *us)`, we keep this macro name in-sync with its underlying NGINX +/// type, this callback is required to initialize your peer. +/// +/// Load Balancing: +#[macro_export] +macro_rules! http_upstream_init_peer_pt { + ( $name: ident, $handler: expr ) => { + extern "C" fn $name( + r: *mut $crate::ffi::ngx_http_request_t, + us: *mut $crate::ffi::ngx_http_upstream_srv_conf_t, + ) -> $crate::ffi::ngx_int_t { + let request = unsafe { $crate::http::Request::from_ngx_http_request(r) }; + let status: $crate::core::Status = $handler(request, us); + status.0 + } + }; +} diff --git a/source/rust/vendor/ngx-rust/src/lib.rs b/source/rust/vendor/ngx-rust/src/lib.rs new file mode 100644 index 0000000..b0329b4 --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/lib.rs @@ -0,0 +1,189 @@ +//! # Rust bindings for NGINX +//! +//! The `ngx` crate provides a high-level Rust interface for the [NGINX] C APIs, +//! allowing creation of NGINX dynamic modules completely in Rust. +//! +//! [NGINX]: https://nginx.org/ +//! +//! ## Project status +//! +//! This project is in active development. It is stable enough to be used in our +//! own products, but the APIs are not stabilized and breaking changes are expected. +//! +//! ## Build +//! +//! NGINX modules can be built against a particular version of NGINX. The following +//! environment variables can be used to specify the NGINX build to use: +//! +//! - `NGINX_BUILD_DIR` - absolute path to the NGINX build directory. +//! Usually it's `objs` under the source directory, but can be changed with the +//! `--builddir=` argument of the configure script. +//! +//! - `NGINX_SOURCE_DIR` - absolute path to the NGINX source directory, configured +//! with the [`configure`](https://nginx.org/en/docs/configure.html) command. +//! +//! Only the `./configure` step of the NGINX build is mandatory because bindings +//! generator don't depend on any of the artifacts generated by `make`. +//! +//! For example, this is how you would compile the [examples](#examples) using a +//! specific version of NGINX: +//! +//! ```sh +//! NGINX_BUILD_DIR=/path/to/nginx-1.30.4/objs cargo build --package=examples --examples +//! ``` +//! +//! ### Building with the NGINX build script +//! +//! You can build your Rust-based module as a part of the NGINX build process by +//! providing a `config` script implementation and passing the `--add-module`/ +//! `--add-dynamic-module` options to the configure script. +//! +//! See the following example integration scripts: [`examples/config`] and +//! [`examples/config.make`]. +//! +//! [`examples/config`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config +//! [`examples/config.make`]: https://github.com/bavshin-f5/ngx-rust/blob/main/examples/config.make +//! +//! ### Building with vendored NGINX sources +//! +//! It is possible to build module with a vendored copy of the NGINX sources +//! provided in the `nginx-src` crate by enabling feature `vendored`: +//! +//! By default, this will use the latest stable release of NGINX and require +//! system-wide installation of build dependencies (OpenSSL, PCRE2, Zlib). +//! +//! The behavior of vendored builds can be customized with environment variables, +//! as documented in the [nginx-src] crate README. +//! +//! **NOTE**: We recommend to build the module binaries against the exact source and +//! configuration of the NGINX build that you are planning to use in production, +//! and that is unlikely to be possible with the vendored source. +//! +//! `configure` arguments alter the APIs and the symbols visible to the Rust code, +//! and some OS distributions are known to ship nginx packages with API-breaking +//! patches applied. +//! +//! [nginx-src]: https://docs.rs/nginx-src/ +//! +//! ## Cargo features +//! +//! - `alloc` - **Enabled** by default. This provides APIs that require allocations +//! via the `alloc` crate. +//! - `async` - Enables a minimal async runtime built on top of the NGINX event loop. +//! - `serde` - Enables serialization support for some of the provided and +//! re-exported types. +//! - `std` - **Enabled** by default. This provides APIs that require the standard +//! library. +//! - `vendored`: Enables the build scripts to build a copy of nginx source and link +//! against it. See the [nginx-src] crate documentation for additional details. +//! +//! ## Dependencies +//! +//! The following dependencies are required to build a Rust NGINX module on Linux +//! or BSD platform: +//! +//! - NGINX build dependencies: C compiler, make, OpenSSL, PCRE2, and Zlib. +//! - Rust toolchain (1.85.0 or later) +//! - [libclang] for rust-bindgen +//! +//! The installation process and the package names are system-dependent. Please, +//! consult the documentation for your distribution. +//! +//! Note that on some systems you will need `-devel` or `-dev` versions of the +//! packages. +//! +//! For example, [Dockerfile] contains the installation commands for Debian Linux. +//! +//! [Dockerfile]: https://github.com/nginx/ngx-rust/blob/main/Dockerfile +//! [libclang]: https://rust-lang.github.io/rust-bindgen/requirements.html +//! +//! ### macOS dependencies +//! +//! In order to use the optional GNU make build process on macOS, you will need +//! to install additional tools. This can be done via [homebrew](https://brew.sh/) +//! with the following command: +//! +//! ```sh +//! brew install make openssl grep +//! ``` +//! +//! Additionally, you may need to set up LLVM and clang. Typically, this is done +//! as follows: +//! +//! ```sh +//! # make sure xcode tools are installed +//! xcode-select --install +//! # instal llvm +//! brew install --with-toolchain llvm +//! ``` +#![warn(missing_docs)] +#![no_std] +#[cfg(feature = "alloc")] +extern crate alloc; + +pub mod allocator; +#[cfg(feature = "async")] +pub mod async_; +pub mod collections; + +/// The core module. +/// +/// This module provides fundamental utilities needed to interface with many NGINX primitives. +/// String conversions, the pool (memory interface) object, and buffer APIs are covered here. These +/// utilities will generally align with the NGINX 'core' files and APIs. +pub mod core; + +/// The ffi module. +/// +/// This module provides scoped FFI bindings for NGINX symbols. +pub mod ffi; + +/// The http module. +/// +/// This modules provides wrappers and utilities to NGINX http APIs, such as requests, +/// configuration access, and statuses. +#[cfg(ngx_feature = "http")] +pub mod http; + +/// The log module. +/// +/// This module provides an interface into the NGINX logger framework. +pub mod log; + +pub mod sync; + +/// Define modules exported by this library. +/// +/// These are normally generated by the Nginx module system, but need to be +/// defined when building modules outside of it. +#[macro_export] +macro_rules! ngx_modules { + ($( $mod:ident ),+) => { + #[unsafe(no_mangle)] + #[allow(non_upper_case_globals)] + pub static mut ngx_modules: [*const $crate::ffi::ngx_module_t; $crate::count!($( $mod, )+) + 1] = [ + $( unsafe { &$mod } as *const $crate::ffi::ngx_module_t, )+ + ::core::ptr::null() + ]; + + #[unsafe(no_mangle)] + #[allow(non_upper_case_globals)] + pub static mut ngx_module_names: [*const ::core::ffi::c_char; $crate::count!($( $mod, )+) + 1] = [ + $( concat!(stringify!($mod), "\0").as_ptr() as *const ::core::ffi::c_char, )+ + ::core::ptr::null() + ]; + + #[unsafe(no_mangle)] + #[allow(non_upper_case_globals)] + pub static mut ngx_module_order: [*const ::core::ffi::c_char; 1] = [ + ::core::ptr::null() + ]; + }; +} + +/// Count number of arguments +#[macro_export] +macro_rules! count { + () => { 0usize }; + ($x:tt, $( $xs:tt ),*) => { 1usize + $crate::count!($( $xs, )*) }; +} diff --git a/source/rust/vendor/ngx-rust/src/log.rs b/source/rust/vendor/ngx-rust/src/log.rs new file mode 100644 index 0000000..e461d6b --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/log.rs @@ -0,0 +1,342 @@ +use core::cmp; +use core::fmt::{self, Write}; +use core::mem::MaybeUninit; +use core::ptr::NonNull; + +use crate::ffi::{self, NGX_MAX_ERROR_STR, ngx_err_t, ngx_log_t, ngx_uint_t}; + +/// This constant is set to `true` if NGINX is compiled with debug logging (`--with-debug`). +pub const DEBUG: bool = cfg!(ngx_feature = "debug"); + +/// Size of the static buffer used to format log messages. +/// +/// Approximates the remaining space in `u_char[NGX_MAX_ERROR_STR]` after writing the standard +/// prefix +pub const LOG_BUFFER_SIZE: usize = + NGX_MAX_ERROR_STR as usize - b"1970/01/01 00:00:00 [info] 1#1: ".len(); + +/// Obtains a pointer to the global (cycle) log object. +/// +/// The returned pointer is tied to the current cycle lifetime, and will be invalidated by a +/// configuration reload in the master process or in a single-process mode. If you plan to store it, +/// make sure that your storage is also tied to the cycle lifetime (e.g. module configuration or +/// connection/request data). +/// +/// The function may panic if you call it before the main() in nginx creates an initial cycle. +#[inline(always)] +pub fn ngx_cycle_log() -> NonNull { + NonNull::new(unsafe { (*nginx_sys::ngx_cycle).log }).expect("global logger") +} + +/// Utility function to provide typed checking of the mask's field state. +#[inline(always)] +pub fn check_mask(mask: DebugMask, log_level: usize) -> bool { + let mask_bits: u32 = mask.into(); + if log_level & mask_bits as usize == 0 { + return false; + } + true +} + +/// Format args into a provided buffer +// May produce incomplete UTF-8 sequences. But any writes to `ngx_log_t` already can be truncated, +// so nothing we can do here. +#[inline] +pub fn write_fmt<'a>(buf: &'a mut [MaybeUninit], args: fmt::Arguments<'_>) -> &'a [u8] { + if let Some(str) = args.as_str() { + str.as_bytes() + } else { + let mut buf = LogBuf::from(buf); + // nothing we can or want to do on errors + let _ = buf.write_fmt(args); + buf.filled() + } +} + +/// Writes the provided buffer to the nginx logger at a specified level. +/// +/// # Safety +/// Requires a valid log pointer. +#[inline] +pub unsafe fn log_error(level: ngx_uint_t, log: *mut ngx_log_t, err: ngx_err_t, buf: &[u8]) { + unsafe { + #[cfg(ngx_feature = "have_variadic_macros")] + ffi::ngx_log_error_core(level, log, err, c"%*s".as_ptr(), buf.len(), buf.as_ptr()); + #[cfg(not(ngx_feature = "have_variadic_macros"))] + ffi::ngx_log_error(level, log, err, c"%*s".as_ptr(), buf.len(), buf.as_ptr()); + } +} + +/// Writes the provided buffer to the nginx logger at the debug level. +/// +/// # Safety +/// Requires a valid log pointer. +#[inline] +pub unsafe fn log_debug(log: *mut ngx_log_t, err: ngx_err_t, buf: &[u8]) { + unsafe { + #[cfg(ngx_feature = "have_variadic_macros")] + ffi::ngx_log_error_core( + ffi::NGX_LOG_DEBUG as _, + log, + err, + c"%*s".as_ptr(), + buf.len(), + buf.as_ptr(), + ); + #[cfg(not(ngx_feature = "have_variadic_macros"))] + ffi::ngx_log_debug_core(log, err, c"%*s".as_ptr(), buf.len(), buf.as_ptr()); + } +} + +/// Write to logger at a specified level. +/// +/// See [Logging](https://nginx.org/en/docs/dev/development_guide.html#logging) +/// for available log levels. +#[macro_export] +macro_rules! ngx_log_error { + ( $level:expr, $log:expr, $($arg:tt)+ ) => { + let log = $log; + let level = $level as $crate::ffi::ngx_uint_t; + if level <= unsafe { (*log).log_level } { + let mut buf = + [const { ::core::mem::MaybeUninit::::uninit() }; $crate::log::LOG_BUFFER_SIZE]; + let message = $crate::log::write_fmt(&mut buf, format_args!($($arg)+)); + unsafe { $crate::log::log_error(level, log, 0, message) }; + } + } +} + +/// Write to logger with the context of currently processed configuration file. +#[macro_export] +macro_rules! ngx_conf_log_error { + ( $level:expr, $cf:expr, $($arg:tt)+ ) => { + let cf: *mut $crate::ffi::ngx_conf_t = $cf; + let level = $level as $crate::ffi::ngx_uint_t; + if level <= unsafe { (*(*cf).log).log_level } { + let mut buf = + [const { ::core::mem::MaybeUninit::::uninit() }; $crate::log::LOG_BUFFER_SIZE]; + let message = $crate::log::write_fmt(&mut buf, format_args!($($arg)+)); + unsafe { + $crate::ffi::ngx_conf_log_error( + level, + cf, + 0, + c"%*s".as_ptr(), + message.len(), + message.as_ptr() + ); + } + } + } +} + +/// Write to logger at debug level. +#[macro_export] +macro_rules! ngx_log_debug { + ( mask: $mask:expr, $log:expr, $($arg:tt)+ ) => { + let log = $log; + if $crate::log::DEBUG && $crate::log::check_mask($mask, unsafe { (*log).log_level }) { + let mut buf = + [const { ::core::mem::MaybeUninit::::uninit() }; $crate::log::LOG_BUFFER_SIZE]; + let message = $crate::log::write_fmt(&mut buf, format_args!($($arg)+)); + unsafe { $crate::log::log_debug(log, 0, message) }; + } + }; + ( $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::All, $log, $($arg)+); + } +} + +/// Log to request connection log at level [`NGX_LOG_DEBUG_HTTP`]. +/// +/// [`NGX_LOG_DEBUG_HTTP`]: https://nginx.org/en/docs/dev/development_guide.html#logging +#[macro_export] +macro_rules! ngx_log_debug_http { + ( $request:expr, $($arg:tt)+ ) => { + let log = unsafe { (*$request.connection()).log }; + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Http, log, $($arg)+); + } +} + +/// Log with requested debug mask. +/// +/// **NOTE:** This macro supports [`DebugMask::Http`] (`NGX_LOG_DEBUG_HTTP`), however, if you have +/// access to a Request object via an http handler it can be more convenient and readable to use +/// the [`ngx_log_debug_http`] macro instead. +/// +/// See for details and available +/// masks. +#[macro_export] +macro_rules! ngx_log_debug_mask { + ( DebugMask::Core, $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Core, $log, $($arg)+); + }; + ( DebugMask::Alloc, $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Alloc, $log, $($arg)+); + }; + ( DebugMask::Mutex, $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Mutex, $log, $($arg)+); + }; + ( DebugMask::Event, $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Event, $log, $($arg)+); + }; + ( DebugMask::Http, $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Http, $log, $($arg)+); + }; + ( DebugMask::Mail, $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Mail, $log, $($arg)+); + }; + ( DebugMask::Stream, $log:expr, $($arg:tt)+ ) => { + $crate::ngx_log_debug!(mask: $crate::log::DebugMask::Stream, $log, $($arg)+); + }; +} + +/// Debug masks for use with [`ngx_log_debug_mask`], these represent the only accepted values for +/// the mask. +#[derive(Debug)] +pub enum DebugMask { + /// Aligns to the NGX_LOG_DEBUG_CORE mask. + Core, + /// Aligns to the NGX_LOG_DEBUG_ALLOC mask. + Alloc, + /// Aligns to the NGX_LOG_DEBUG_MUTEX mask. + Mutex, + /// Aligns to the NGX_LOG_DEBUG_EVENT mask. + Event, + /// Aligns to the NGX_LOG_DEBUG_HTTP mask. + Http, + /// Aligns to the NGX_LOG_DEBUG_MAIL mask. + Mail, + /// Aligns to the NGX_LOG_DEBUG_STREAM mask. + Stream, + /// Aligns to the NGX_LOG_DEBUG_ALL mask. + All, +} + +impl TryFrom for DebugMask { + type Error = u32; + + fn try_from(value: u32) -> Result { + match value { + crate::ffi::NGX_LOG_DEBUG_CORE => Ok(DebugMask::Core), + crate::ffi::NGX_LOG_DEBUG_ALLOC => Ok(DebugMask::Alloc), + crate::ffi::NGX_LOG_DEBUG_MUTEX => Ok(DebugMask::Mutex), + crate::ffi::NGX_LOG_DEBUG_EVENT => Ok(DebugMask::Event), + crate::ffi::NGX_LOG_DEBUG_HTTP => Ok(DebugMask::Http), + crate::ffi::NGX_LOG_DEBUG_MAIL => Ok(DebugMask::Mail), + crate::ffi::NGX_LOG_DEBUG_STREAM => Ok(DebugMask::Stream), + crate::ffi::NGX_LOG_DEBUG_ALL => Ok(DebugMask::All), + _ => Err(0), + } + } +} + +impl From for u32 { + fn from(value: DebugMask) -> Self { + match value { + DebugMask::Core => crate::ffi::NGX_LOG_DEBUG_CORE, + DebugMask::Alloc => crate::ffi::NGX_LOG_DEBUG_ALLOC, + DebugMask::Mutex => crate::ffi::NGX_LOG_DEBUG_MUTEX, + DebugMask::Event => crate::ffi::NGX_LOG_DEBUG_EVENT, + DebugMask::Http => crate::ffi::NGX_LOG_DEBUG_HTTP, + DebugMask::Mail => crate::ffi::NGX_LOG_DEBUG_MAIL, + DebugMask::Stream => crate::ffi::NGX_LOG_DEBUG_STREAM, + DebugMask::All => crate::ffi::NGX_LOG_DEBUG_ALL, + } + } +} + +/// Minimal subset of unstable core::io::{BorrowedBuf,BorrowedCursor} +struct LogBuf<'data> { + buf: &'data mut [MaybeUninit], + filled: usize, +} + +impl<'data> LogBuf<'data> { + pub fn filled(&self) -> &'data [u8] { + // SAFETY: valid bytes have been written to self.buf[..self.filled] + unsafe { + let buf = self.buf.get_unchecked(..self.filled); + // inlined MaybeUninit::slice_assume_init_ref + &*(buf as *const [MaybeUninit] as *const [u8]) + } + } + + pub fn append(&mut self, buf: &[u8]) -> &mut Self { + let n = cmp::min(self.buf.len() - self.filled, buf.len()); + unsafe { + // SAFETY: The source buf has at least n bytes + let src = buf.get_unchecked(..n); + // SAFETY: &[u8] and &[MaybeUninit] have the same layout + let src: &[MaybeUninit] = core::mem::transmute(src); + // SAFETY: self.buf has at least n bytes available after self.filled + self.buf.get_unchecked_mut(self.filled..self.filled + n).copy_from_slice(src); + } + self.filled += n; + self + } +} + +impl<'data> From<&'data mut [MaybeUninit]> for LogBuf<'data> { + fn from(buf: &'data mut [MaybeUninit]) -> Self { + Self { buf, filled: 0 } + } +} + +impl fmt::Write for LogBuf<'_> { + fn write_str(&mut self, s: &str) -> fmt::Result { + self.append(s.as_bytes()); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + + use super::*; + + #[test] + fn test_mask_lower_bound() { + assert!(>::into(DebugMask::Core) == crate::ffi::NGX_LOG_DEBUG_FIRST); + } + #[test] + fn test_mask_upper_bound() { + assert!( + >::into(DebugMask::Stream) == crate::ffi::NGX_LOG_DEBUG_LAST + ); + } + #[test] + fn test_check_mask() { + struct MockLog { + log_level: usize, + } + let mock = MockLog { log_level: 16 }; + + let mut r = check_mask(DebugMask::Core, mock.log_level); + assert!(r); + + r = check_mask(DebugMask::Alloc, mock.log_level); + assert!(!r); + } + + #[test] + fn log_buffer() { + use core::str; + + let mut buf = [const { MaybeUninit::::uninit() }; 32]; + let mut buf = LogBuf::from(&mut buf[..]); + let words = ["Hello", "World"]; + + // normal write + write!(&mut buf, "{} {}!", words[0], words[1]).unwrap(); + assert_eq!(str::from_utf8(buf.filled()), Ok("Hello World!")); + + // overflow results in truncated output + write!(&mut buf, " This is a test, {}", u64::MAX).unwrap(); + assert_eq!(str::from_utf8(buf.filled()), Ok("Hello World! This is a test, 184")); + + // and any following writes are still safe + write!(&mut buf, "test").unwrap(); + assert_eq!(str::from_utf8(buf.filled()), Ok("Hello World! This is a test, 184")); + } +} diff --git a/source/rust/vendor/ngx-rust/src/sync.rs b/source/rust/vendor/ngx-rust/src/sync.rs new file mode 100644 index 0000000..258357c --- /dev/null +++ b/source/rust/vendor/ngx-rust/src/sync.rs @@ -0,0 +1,118 @@ +//! Synchronization primitives over shared memory. +//! +//! This module provides an alternative implementation for the `ngx_atomic_t` type, +//! `ngx_atomic_*`/`ngx_rwlock_*` family of functions and related usage patterns from nginx. +//! +//! `` contains a wide variety of implementation variants for different platforms and +//! build configurations. It's not feasible to properly expose all of these to the Rust code, and we +//! are not going to. The implementation here uses similar logic on the foundation of the +//! [core::sync::atomic] types and is intentionally _not interoperable_ with the nginx atomics. +//! Thus, it's only suitable for use for new shared memory structures instead of, for example, +//! interacting with the upstream zones. +//! +//! One potential pitfall here is that atomics in Rust are specified in terms of threads, and we use +//! the types in this module for interprocess synchronization. This should not be an issue though, +//! as Rust refers to the C/C++11 memory model for atomics, and there's a following note in +//! [atomics.lockfree]: +//! +//! > [Note: Operations that are lock-free should also be address-free. That is, atomic operations +//! > on the same memory location via two different addresses will communicate atomically. The +//! > implementation should not depend on any per-process state. This restriction enables +//! > communication via memory that is mapped into a process more than once and by memory that is +//! > shared between two processes. — end note] +//! +//! In practice, this recommendation is applied in all the implementations that matter to us. +use core::sync::atomic::{self, Ordering}; + +use nginx_sys::ngx_sched_yield; + +const NGX_RWLOCK_SPIN: usize = 2048; +const NGX_RWLOCK_WLOCK: usize = usize::MAX; + +type NgxAtomic = atomic::AtomicUsize; + +/// Raw lock type. +pub struct RawSpinlock(NgxAtomic); + +/// Reader-writer lock over an atomic variable, based on the nginx rwlock implementation. +pub type RwLock = lock_api::RwLock; + +/// RAII structure used to release the shared read access of a lock when dropped. +pub type RwLockReadGuard<'a, T> = lock_api::RwLockReadGuard<'a, RawSpinlock, T>; + +/// RAII structure used to release the exclusive write access of a lock when dropped. +pub type RwLockWriteGuard<'a, T> = lock_api::RwLockWriteGuard<'a, RawSpinlock, T>; + +unsafe impl lock_api::RawRwLock for RawSpinlock { + // Only used for initialization, will not be mutated + #[allow(clippy::declare_interior_mutable_const)] + const INIT: RawSpinlock = RawSpinlock(NgxAtomic::new(0)); + + type GuardMarker = lock_api::GuardNoSend; + + fn lock_shared(&self) { + loop { + if self.try_lock_shared() { + return; + } + + if unsafe { nginx_sys::ngx_ncpu > 1 } { + for n in 0..NGX_RWLOCK_SPIN { + for _ in 0..n { + core::hint::spin_loop() + } + + if self.try_lock_shared() { + return; + } + } + } + + ngx_sched_yield() + } + } + + fn try_lock_shared(&self) -> bool { + let value = self.0.load(Ordering::Acquire); + + if value == NGX_RWLOCK_WLOCK { + return false; + } + + self.0.compare_exchange(value, value + 1, Ordering::Acquire, Ordering::Relaxed).is_ok() + } + + unsafe fn unlock_shared(&self) { + self.0.fetch_sub(1, Ordering::Release); + } + + fn lock_exclusive(&self) { + loop { + if self.try_lock_exclusive() { + return; + } + + if unsafe { nginx_sys::ngx_ncpu > 1 } { + for n in 0..NGX_RWLOCK_SPIN { + for _ in 0..n { + core::hint::spin_loop() + } + + if self.try_lock_exclusive() { + return; + } + } + } + + ngx_sched_yield() + } + } + + fn try_lock_exclusive(&self) -> bool { + self.0.compare_exchange(0, NGX_RWLOCK_WLOCK, Ordering::Acquire, Ordering::Relaxed).is_ok() + } + + unsafe fn unlock_exclusive(&self) { + self.0.store(0, Ordering::Release) + } +} diff --git a/source/rust/vendor/ngx-rust/tests/conditional-compilation.rs b/source/rust/vendor/ngx-rust/tests/conditional-compilation.rs new file mode 100644 index 0000000..156401d --- /dev/null +++ b/source/rust/vendor/ngx-rust/tests/conditional-compilation.rs @@ -0,0 +1,23 @@ +use ngx::ffi; + +#[test] +fn test_os_symbols() { + #[cfg(ngx_os = "freebsd")] + assert_eq!(ffi::NGX_FREEBSD, 1); + + #[cfg(ngx_os = "linux")] + assert_eq!(ffi::NGX_LINUX, 1); + + #[cfg(ngx_os = "darwin")] + assert_eq!(ffi::NGX_DARWIN, 1); +} + +#[test] +fn test_feature_symbols() { + let ev: ffi::ngx_event_t = unsafe { core::mem::zeroed() }; + + assert_eq!(ev.available, 0); + + #[cfg(ngx_feature = "have_kqueue")] + assert_eq!(ev.kq_errno, 0); +} diff --git a/source/rust/vendor/ngx-rust/tests/config/nginx.conf b/source/rust/vendor/ngx-rust/tests/config/nginx.conf new file mode 100644 index 0000000..8889ed7 --- /dev/null +++ b/source/rust/vendor/ngx-rust/tests/config/nginx.conf @@ -0,0 +1,43 @@ +#load_module modules/ngx_http_rust_module.so; + +#user nobody; +worker_processes 1; + +error_log logs/error.log; +#error_log logs/error.log notice; +#error_log logs/error.log info; + +#pid logs/nginx.pid; + + +events { + worker_connections 1024; +} + + +http { + include mime.types; + default_type application/octet-stream; + + + # rust test; + + + + server { + listen 8080; + server_name localhost; + + #charset koi8-r; + + #access_log logs/host.access.log main; + + location / { + root html; + index index.html index.htm; + } + + + } + +} diff --git a/source/rust/vendor/ngx-rust/tests/log_test.rs b/source/rust/vendor/ngx-rust/tests/log_test.rs new file mode 100644 index 0000000..0610169 --- /dev/null +++ b/source/rust/vendor/ngx-rust/tests/log_test.rs @@ -0,0 +1,148 @@ +use std::env; +use std::fs; +use std::io; +use std::io::Result; +#[cfg(unix)] +use std::os::unix::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::process::Output; + +const NGINX_BINARY_NAME: &str = "nginx"; + +/// Convert a CStr to a PathBuf +pub fn cstr_to_path(val: &core::ffi::CStr) -> Option { + if val.is_empty() { + return None; + } + + #[cfg(unix)] + let str = std::ffi::OsStr::from_bytes(val.to_bytes()); + #[cfg(not(unix))] + let str = std::str::from_utf8(val.to_bytes()).ok()?; + + Some(PathBuf::from(str)) +} + +/// Find nginx binary in the build directory +pub fn find_nginx_binary() -> io::Result { + let path = [ + // TEST_NGINX_BINARY is specified for tests + env::var("TEST_NGINX_BINARY").ok().map(PathBuf::from), + // The module is built against an external NGINX source tree + env::var("NGINX_BUILD_DIR").map(PathBuf::from).map(|x| x.join(NGINX_BINARY_NAME)).ok(), + env::var("NGINX_SOURCE_DIR") + .map(PathBuf::from) + .map(|x| x.join("objs").join(NGINX_BINARY_NAME)) + .ok(), + // Fallback to the build directory exposed by nginx-sys + option_env!("DEP_NGINX_BUILD_DIR").map(PathBuf::from).map(|x| x.join(NGINX_BINARY_NAME)), + ] + .into_iter() + .flatten() + .find(|x| x.is_file()) + .ok_or(io::ErrorKind::NotFound)?; + + Ok(path) +} + +/// harness to test nginx +pub struct Nginx { + pub prefix: tempfile::TempDir, + pub bin_path: PathBuf, + pub config_path: PathBuf, +} + +impl Default for Nginx { + /// create nginx with default + fn default() -> Nginx { + let binary = find_nginx_binary().expect("nginx binary"); + Nginx::new(binary).expect("test harness") + } +} + +impl Nginx { + pub fn new(binary: impl AsRef) -> io::Result { + let prefix = tempfile::tempdir()?; + let config = prefix.path().join("nginx.conf"); + + fs::create_dir(prefix.path().join("logs"))?; + + Ok(Nginx { prefix, bin_path: binary.as_ref().to_owned(), config_path: config }) + } + + /// start nginx process with arguments + pub fn cmd(&self, args: &[&str]) -> Result { + let prefix = self.prefix.path().to_string_lossy(); + let config_path = self.config_path.to_string_lossy(); + let args = [&["-p", &prefix, "-c", &config_path], args].concat(); + let result = Command::new(&self.bin_path).args(args).output(); + + match result { + Err(e) => Err(e), + + Ok(output) => { + println!("status: {}", output.status); + println!("stdout: {}", String::from_utf8_lossy(&output.stdout)); + println!("stderr: {}", String::from_utf8_lossy(&output.stderr)); + Ok(output) + } + } + } + + /// complete stop the nginx binary + pub fn stop(&mut self) -> Result { + self.cmd(&["-s", "stop"]) + } + + /// start the nginx binary + pub fn start(&mut self) -> Result { + self.cmd(&[]) + } + + // make sure we stop existing nginx and start new master process + // intentinally ignore failure in stop + pub fn restart(&mut self) -> Result { + let _ = self.stop(); + self.start() + } + + // replace config with another config + pub fn replace_config>(&mut self, from: P) -> Result { + println!("copying config from: {:?} to: {:?}", from.as_ref(), self.config_path); // replace with logging + fs::copy(from, &self.config_path) + } +} + +#[cfg(test)] +mod tests { + use std::env; + + use super::*; + + const TEST_NGINX_CONFIG: &str = "tests/nginx.conf"; + + #[test] + fn test() { + let mut nginx = Nginx::default(); + + let current_dir = env::current_dir().expect("Unable to get current directory"); + let test_config_path = current_dir.join(TEST_NGINX_CONFIG); + + assert!( + test_config_path.exists(), + "Config file not found: {}\nCurrent directory: {}", + test_config_path.to_string_lossy(), + current_dir.to_string_lossy() + ); + + nginx.replace_config(&test_config_path).unwrap_or_else(|_| { + panic!("Unable to load config file: {}", test_config_path.to_string_lossy()) + }); + let output = nginx.restart().expect("Unable to restart NGINX"); + assert!(output.status.success()); + + let output = nginx.stop().expect("Unable to stop NGINX"); + assert!(output.status.success()); + } +} diff --git a/source/rust/vendor/ngx-rust/tests/module/config b/source/rust/vendor/ngx-rust/tests/module/config new file mode 100644 index 0000000..88b592a --- /dev/null +++ b/source/rust/vendor/ngx-rust/tests/module/config @@ -0,0 +1,12 @@ +ngx_addon_name=ngx_http_rust_module + +ngx_module_type=HTTP_FILTER +ngx_module_name=ngx_http_rust_module +ngx_module_srcs="$ngx_addon_dir/ngx_http_rust_module.c" +ngx_module_deps="cargo" +ngx_module_libs="$ngx_addon_dir/../target/debug/libngx_rust.a" + + +. auto/module + + diff --git a/source/rust/vendor/ngx-rust/tests/module/config.make b/source/rust/vendor/ngx-rust/tests/module/config.make new file mode 100644 index 0000000..23559e8 --- /dev/null +++ b/source/rust/vendor/ngx-rust/tests/module/config.make @@ -0,0 +1,7 @@ + +cat << END >> $NGX_MAKEFILE + +cargo: + cargo build --manifest-path $ngx_addon_dir/../Cargo.toml --lib + +END diff --git a/source/rust/vendor/ngx-rust/tests/module/ngx_http_rust_module.c b/source/rust/vendor/ngx-rust/tests/module/ngx_http_rust_module.c new file mode 100644 index 0000000..374a606 --- /dev/null +++ b/source/rust/vendor/ngx-rust/tests/module/ngx_http_rust_module.c @@ -0,0 +1,92 @@ +/** + * @file ngx_rust.c + * @author Sehyo Chang + * @date + * + * @brief Dummy module + * + * @section LICENSE + * + * Copyright (C) 2011 by Nginx + * + */ +#include +#include +#include + + +/** + * @brief element mixer configuration + */ +typedef struct { + ngx_str_t name; /**< test name */ +} ngx_http_rust_main_conf_t; + + + +static void *ngx_http_rust_create_main_conf(ngx_conf_t *cf); + + +/* + * dummy rust + */ +static ngx_command_t ngx_http_rust_commands[] = { + { + ngx_string("rust"), /* dummy directive */ + NGX_HTTP_MAIN_CONF|NGX_CONF_TAKE1, // server takes 1 // + ngx_conf_set_str_slot, /* configuration setup function */ + NGX_HTTP_MAIN_CONF_OFFSET, + offsetof(ngx_http_rust_main_conf_t, name), + NULL + }, + ngx_null_command /* command termination */ +}; + + +/* The module context. */ +static ngx_http_module_t ngx_http_rust_module_ctx = { + NULL, /* preconfiguration */ + NULL, /* postconfiguration */ + ngx_http_rust_create_main_conf, /* create main configuration */ + NULL, /* init main configuration */ + + NULL, /* create server configuration */ + NULL, /* merge server configuration */ + + NULL, + NULL +}; + +/* Module definition. */ +ngx_module_t ngx_http_rust_module = { + NGX_MODULE_V1, + &ngx_http_rust_module_ctx, /* module context */ + ngx_http_rust_commands, /* module directives */ + NGX_HTTP_MODULE, /* module type */ + NULL, /* init master */ + NULL, /* init module */ + NULL, /* init process */ + NULL, /* init thread */ + NULL, /* exit thread */ + NULL, /* exit process */ + NULL, /* exit master */ + NGX_MODULE_V1_PADDING +}; + + + +static void *ngx_http_rust_create_main_conf(ngx_conf_t *cf) +{ + ngx_http_rust_main_conf_t *conf; + + ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "setting up main config"); + + + conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_rust_main_conf_t)); + if (conf == NULL) { + return NULL; + } + + + return conf; +} \ No newline at end of file diff --git a/source/rust/vendor/ngx-rust/tests/nginx.conf b/source/rust/vendor/ngx-rust/tests/nginx.conf new file mode 100644 index 0000000..be3e9c9 --- /dev/null +++ b/source/rust/vendor/ngx-rust/tests/nginx.conf @@ -0,0 +1,42 @@ +#load_module modules/ngx_http_rust_module.so; + +#user nobody; +worker_processes 1; + +error_log logs/error.log; +#error_log logs/error.log notice; +#error_log logs/error.log info; + +#pid logs/nginx.pid; + + +events { + worker_connections 1024; +} + + +http { + default_type application/octet-stream; + + + # rust test; + + + + server { + listen 30000; + server_name localhost; + + #charset koi8-r; + + #access_log logs/host.access.log main; + + location / { + root html; + index index.html index.htm; + } + + + } + +} diff --git a/source/www/admin.html b/source/www/admin.html new file mode 100644 index 0000000..9d5054d --- /dev/null +++ b/source/www/admin.html @@ -0,0 +1,826 @@ + + + + + +统一认证 · 管理台 + + + + + + + + + + +
+ + + + diff --git a/tests/admin-oauth-clients-e2e.sh b/tests/admin-oauth-clients-e2e.sh new file mode 100755 index 0000000..b69f600 --- /dev/null +++ b/tests/admin-oauth-clients-e2e.sh @@ -0,0 +1,207 @@ +#!/usr/bin/env bash +# ============================================================================ +# 管理接口端到端验证:OAuth 接入方(客户端注册表)管理 +# +# 覆盖: +# - 未登录访问管理接口被拒(401),登录后可读写 +# - 列表 / 新建 / 更新(保留密钥)/ 重置密钥 / 删除 +# - **热生效**:新建完立刻能发起授权,不需要重启网关 +# (这条专门盯住「写穿共享内存」——曾经把旧值原样写回,表现为 +# 管理台显示已保存、授权时却报未知 client_id) +# - 参数校验:非法回调地址 / 非法授权类型 / 授权码模式缺回调 +# - 公开客户端不持有密钥,且自动剔除 client_credentials / password +# +# 前置:网关以 source/conf/nginx.test.conf 运行(见 scripts/run-local-e2e.sh) +# 依赖:curl、python3 +# +# 用法:bash tests/admin-oauth-clients-e2e.sh [IDP_BASE] [DATA_DIR] +# ADMIN_USER / ADMIN_PASS 可覆盖(默认取管理台初始账号 admin / 123456) +# ============================================================================ +set -u + +BASE="${1:-http://127.0.0.1:18098}" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DATA_DIR="${2:-$ROOT/source/data}" +ADMIN_USER="${ADMIN_USER:-admin}" +ADMIN_PASS="${ADMIN_PASS:-123456}" + +JAR="$(mktemp -t sso_admin_cookies.XXXXXX.txt)" +trap 'rm -f "$JAR"' EXIT + +PASS=0; FAIL=0 +ok() { echo " ✅ $1"; PASS=$((PASS+1)); } +bad() { echo " ❌ $1"; FAIL=$((FAIL+1)); } +need() { command -v "$1" >/dev/null 2>&1 || { echo "缺少依赖: $1"; exit 2; }; } +need curl; need python3 + +echo "==> IdP: $BASE" +echo "==> data: $DATA_DIR" +echo "==> admin: $ADMIN_USER" + +# ---------- JSON 取值:`jget <点路径>` ---------- +# 支持顶层与 data 下的字段,例如 client_secret / data.client_secret / +# data.items.0.client_id +jget() { printf '%s' "$1" | python3 -c " +import sys,json +path=[k for k in sys.argv[1].split('.') if k] +try: d=json.loads(sys.stdin.read()) +except Exception: print(''); raise SystemExit +for k in path: + if isinstance(d,dict): d=d.get(k) + elif isinstance(d,list) and k.isdigit(): d=d[int(k)] if int(k) [JSON_BODY]` → 输出响应体 +areq() { + local m="$1" p="$2" b="${3:-}" + if [ -n "$b" ]; then + curl -s -b "$JAR" -X "$m" "$BASE$p" -H 'Content-Type: application/json' -d "$b" + else + curl -s -b "$JAR" -X "$m" "$BASE$p" + fi +} +# 同上,只取 HTTP 状态码 +acode() { + local m="$1" p="$2" b="${3:-}" + if [ -n "$b" ]; then + curl -s -o /dev/null -w '%{http_code}' -b "$JAR" -X "$m" "$BASE$p" -H 'Content-Type: application/json' -d "$b" + else + curl -s -o /dev/null -w '%{http_code}' -b "$JAR" -X "$m" "$BASE$p" + fi +} + +CID="e2e-app" +CID2="e2e-public" +REDIRECT="http://127.0.0.1:19999/callback" + +# ---------- 0. 未登录:管理接口一律拒绝 ---------- +echo "==> [0] 未登录拒绝" +code="$(curl -s -o /dev/null -w '%{http_code}' "$BASE/api/admin/oauth-clients")" +[ "$code" = "401" ] && ok "未登录读列表 → 401" || bad "未登录读列表应为 401,实际 $code" +code="$(curl -s -o /dev/null -w '%{http_code}' -X POST "$BASE/api/admin/oauth-clients/save" \ + -H 'Content-Type: application/json' -d "{\"client_id\":\"$CID\"}")" +[ "$code" = "401" ] && ok "未登录保存 → 401" || bad "未登录保存应为 401,实际 $code" + +# ---------- 1. 管理员登录 ---------- +echo "==> [1] 管理员登录" +LOGIN="$(curl -s -c "$JAR" -X POST "$BASE/api/admin/login" -H 'Content-Type: application/json' \ + -d "{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASS\"}")" +if [ "$(jget "$LOGIN" data.username)" = "$ADMIN_USER" ]; then + ok "登录成功(${ADMIN_USER})" +else + bad "登录失败:$LOGIN" + echo "!! 无法继续(管理接口需要管理员会话)"; exit 1 +fi + +# 清掉上次运行的残留,保证脚本可重复执行 +areq POST /api/admin/oauth-clients/delete "{\"client_id\":\"$CID\"}" >/dev/null +areq POST /api/admin/oauth-clients/delete "{\"client_id\":\"$CID2\"}" >/dev/null + +# ---------- 2. 列表 ---------- +echo "==> [2] 列表与端点" +LIST="$(areq GET /api/admin/oauth-clients)" +if printf '%s' "$LIST" | grep -q '"grafana"'; then + ok "列表含种子客户端 grafana" +else + bad "列表缺少种子客户端:$LIST" +fi +ISS="$(jget "$LIST" data.issuer)" +[ -n "$ISS" ] && ok "返回 issuer:$ISS" || bad "未返回 issuer" +EP="$(jget "$LIST" data.endpoints.authorize_v20)" +case "$EP" in */oauth/v20/authorize) ok "返回 MaxKey 端点别名:$EP" ;; *) bad "MaxKey 端点别名异常:$EP" ;; esac + +# ---------- 3. 新建机密客户端 ---------- +echo "==> [3] 新建机密客户端" +SAVE="$(areq POST /api/admin/oauth-clients/save "{\"client_id\":\"$CID\",\"name\":\"e2e 机密应用\",\"redirect_uris\":\"$REDIRECT\",\"grant_types\":\"authorization_code,refresh_token\",\"scopes\":\"openid profile\",\"confidential\":true}")" +SECRET="$(jget "$SAVE" data.client_secret)" +[ "${SECRET#cs_}" != "$SECRET" ] && ok "已生成客户端密钥(cs_ 前缀)" || bad "密钥异常:$SECRET" +[ "$(jget "$SAVE" data.existed)" = "false" ] && ok "标记 existed=false(新建)" || bad "existed 标记异常:$SAVE" +[ "$(jget "$SAVE" data.confidential)" = "true" ] && ok "类型为机密客户端" || bad "confidential 异常:$SAVE" + +# ---------- 4. 热生效:立刻可发起授权(不需要重启网关) ---------- +echo "==> [4] 热生效(写穿共享内存)" +LOC="$(curl -s -o /dev/null -w '%{redirect_url}' -G "$BASE/oauth/authorize" \ + --data-urlencode "response_type=code" \ + --data-urlencode "client_id=$CID" \ + --data-urlencode "redirect_uri=$REDIRECT")" +case "$LOC" in + */login?redirect=*) ok "新客户端立刻被识别(302 → 登录页)" ;; + *) bad "新客户端未被热加载,Location=$LOC" ;; +esac +# 对照:未注册的 client_id 必须是 invalid_client +BODY="$(curl -s -G "$BASE/oauth/authorize" \ + --data-urlencode "response_type=code" \ + --data-urlencode "client_id=no-such-client" \ + --data-urlencode "redirect_uri=$REDIRECT")" +case "$BODY" in *invalid_client*) ok "未知 client_id → invalid_client(对照)" ;; *) bad "未知 client_id 未报 invalid_client:$BODY" ;; esac +# 未注册的回调地址必须被拒 +BODY="$(curl -s -G "$BASE/oauth/authorize" \ + --data-urlencode "response_type=code" \ + --data-urlencode "client_id=$CID" \ + --data-urlencode "redirect_uri=http://evil.example.com/cb")" +case "$BODY" in *invalid_redirect_uri*) ok "未注册回调地址 → invalid_redirect_uri" ;; *) bad "回调地址白名单失效:$BODY" ;; esac + +# ---------- 5. 更新:密钥留空 = 保留原值 ---------- +echo "==> [5] 更新保留密钥" +SAVE2="$(areq POST /api/admin/oauth-clients/save "{\"client_id\":\"$CID\",\"name\":\"e2e 机密应用(改名)\",\"redirect_uris\":\"$REDIRECT\",\"grant_types\":\"authorization_code\",\"scopes\":\"openid\",\"confidential\":true}")" +[ "$(jget "$SAVE2" data.client_secret)" = "$SECRET" ] && ok "未传密钥时保留原密钥" || bad "密钥被意外改写:$SAVE2" +[ "$(jget "$SAVE2" data.existed)" = "true" ] && ok "标记 existed=true(更新)" || bad "existed 标记异常:$SAVE2" +[ "$(jget "$SAVE2" data.name)" = "e2e 机密应用(改名)" ] && ok "名称已更新" || bad "名称未更新:$SAVE2" + +# ---------- 6. 参数校验 ---------- +echo "==> [6] 参数校验" +BODY="$(areq POST /api/admin/oauth-clients/save "{\"client_id\":\"e2e-bad\",\"redirect_uris\":\"javascript:alert(1)\",\"confidential\":true}")" +case "$BODY" in *"必须是 http(s)"*) ok "非 http(s) 回调被拒" ;; *) bad "非法回调未被拒:$BODY" ;; esac +BODY="$(areq POST /api/admin/oauth-clients/save "{\"client_id\":\"e2e-bad\",\"redirect_uris\":\"http://127.0.0.1:1/cb#frag\",\"confidential\":true}")" +case "$BODY" in *fragment*) ok "带 #fragment 的回调被拒" ;; *) bad "fragment 未被拒:$BODY" ;; esac +BODY="$(areq POST /api/admin/oauth-clients/save "{\"client_id\":\"e2e-bad\",\"redirect_uris\":\"http://127.0.0.1:1/cb\",\"grant_types\":\"urn:ietf:params:oauth:grant-type:device_code\",\"confidential\":true}")" +case "$BODY" in *"不支持的授权类型"*) ok "未知授权类型被拒" ;; *) bad "未知授权类型未被拒:$BODY" ;; esac +BODY="$(areq POST /api/admin/oauth-clients/save "{\"client_id\":\"e2e-bad\",\"grant_types\":\"authorization_code\",\"confidential\":true}")" +case "$BODY" in *"回调地址"*) ok "授权码模式缺回调被拒" ;; *) bad "缺回调未被拒:$BODY" ;; esac +code="$(acode GET /api/admin/oauth-clients)" +[ "$code" = "200" ] && ok "校验失败未污染注册表(列表仍可读)" || bad "列表异常:$code" +printf '%s' "$(areq GET /api/admin/oauth-clients)" | grep -q 'e2e-bad' && bad "被拒的 e2e-bad 竟然入库了" || ok "被拒的客户端没有入库" + +# ---------- 7. 公开客户端:无密钥 + 剔除不可用授权类型 ---------- +echo "==> [7] 公开客户端" +SAVE3="$(areq POST /api/admin/oauth-clients/save "{\"client_id\":\"$CID2\",\"name\":\"e2e 公开应用\",\"redirect_uris\":\"$REDIRECT\",\"grant_types\":\"authorization_code,client_credentials,password\",\"scopes\":\"openid\",\"confidential\":false}")" +[ -z "$(jget "$SAVE3" data.client_secret)" ] && ok "公开客户端不生成密钥" || bad "公开客户端竟然有密钥:$SAVE3" +GT="$(jget "$SAVE3" data.grant_types)" +case "$GT" in + *client_credentials*|*password*) bad "公开客户端仍带不可用授权类型:$GT" ;; + *) ok "已剔除 client_credentials / password:$GT" ;; +esac + +# ---------- 8. 重置密钥 ---------- +echo "==> [8] 重置密钥" +ROT="$(areq POST /api/admin/oauth-clients/rotate "{\"client_id\":\"$CID\"}")" +NEW="$(jget "$ROT" data.client_secret)" +[ "${NEW#cs_}" != "$NEW" ] && ok "重置返回新密钥(cs_ 前缀)" || bad "重置未返回密钥:$ROT" +[ "$NEW" != "$SECRET" ] && ok "新密钥与旧密钥不同" || bad "新密钥与旧密钥相同" +BODY="$(areq POST /api/admin/oauth-clients/rotate "{\"client_id\":\"$CID2\"}")" +case "$BODY" in *"公开客户端"*) ok "公开客户端拒绝重置密钥" ;; *) bad "公开客户端重置未报错:$BODY" ;; esac +BODY="$(areq POST /api/admin/oauth-clients/rotate '{"client_id":"no-such-client"}')" +case "$BODY" in *"不存在"*) ok "重置不存在的客户端报错" ;; *) bad "重置不存在客户端未报错:$BODY" ;; esac + +# ---------- 9. 删除 ---------- +echo "==> [9] 删除" +DEL="$(areq POST /api/admin/oauth-clients/delete "{\"client_id\":\"$CID\"}")" +case "$DEL" in *已删除*) ok "删除成功" ;; *) bad "删除失败:$DEL" ;; esac +printf '%s' "$(areq GET /api/admin/oauth-clients)" | grep -q "\"$CID\"" && bad "删除后列表仍含 $CID" || ok "删除后列表不再含 $CID" +BODY="$(curl -s -G "$BASE/oauth/authorize" \ + --data-urlencode "response_type=code" \ + --data-urlencode "client_id=$CID" \ + --data-urlencode "redirect_uri=$REDIRECT")" +case "$BODY" in *invalid_client*) ok "删除后授权请求即失效(invalid_client)" ;; *) bad "删除后仍能授权:$BODY" ;; esac +BODY="$(areq POST /api/admin/oauth-clients/delete '{"client_id":"no-such-client"}')" +case "$BODY" in *"不存在"*) ok "删除不存在的客户端报错" ;; *) bad "删除不存在客户端未报错:$BODY" ;; esac + +# 收尾:清掉本次用的公开客户端 +areq POST /api/admin/oauth-clients/delete "{\"client_id\":\"$CID2\"}" >/dev/null + +echo +echo "==> 汇总:通过 ${PASS},失败 ${FAIL}" +[ "$FAIL" = "0" ] || exit 1 diff --git a/tests/demo-system/README.md b/tests/demo-system/README.md new file mode 100644 index 0000000..0ba7c1c --- /dev/null +++ b/tests/demo-system/README.md @@ -0,0 +1,67 @@ +# demo-system —— 一个「简单业务系统」 + +用来验证第三方系统如何接入 sso 统一认证。**仅 Python 3 标准库,无依赖。** + +```bash +python3 app.py # 默认:MaxKey 风格端点 + :18096 + 本地 IdP +``` + +配合 `tests/run-oauth2-local.sh` 会自动拉起本应用并跑完整端到端。 + +## 两种接入姿势 + +| | 模式 A:自己做 OAuth2 客户端 | 模式 B:前置 IAP,零改造 | +| --- | --- | --- | +| 谁做认证 | 本应用(授权码流程) | 网关(nginx + `sso_gateway`) | +| 应用做什么 | `/login` → 授权码 → 换 token → 取 userinfo → 建本地会话 | 只读 `X-Auth-*` 请求头 | +| 需要改代码 | 需要(OAuth 客户端逻辑) | 不需要 | +| 适用 | 需要拿令牌代用户调 API | 既有系统、异构栈、改造代价大 | + +代码里两种模式共存:`current_identity()` 先看 IAP 注入头,再看本地会话。 + +## 模式 A 的两种端点风格 + +`DEMO_STYLE` 控制(这就是「MaxKey 互通」的落点): + +| 风格 | 授权 | 换发 | 用户信息 | 客户端鉴权 | 令牌位置 | +| --- | --- | --- | --- | --- | --- | +| `maxkey` | `/oauth/v20/authorize` | `/oauth/v20/token` | `/oauth/v20/me` | 表单 `client_id/secret` | `access_token` 参数 | +| `standard` | `/oauth/authorize` | `/oauth/token` | `/oauth/userinfo` | `Authorization: Basic` | `Bearer` 头 | + +不带 `client_secret` 时自动启用 PKCE(S256),按公开客户端走。 + +## 端点 + +| 路径 | 说明 | +| --- | --- | +| `GET /` | 首页:未登录给登录入口,已登录展示身份(含来源标签) | +| `GET /login` | 生成 state + (可选)PKCE,302 到 IdP 授权端点 | +| `GET /oauth2/callback` | 收 code → 换 token → 取 userinfo → 建本地会话(也接受 `/callback`) | +| `GET /api/me` | 当前身份 JSON,`source` 为 `oauth2` 或 `iap` | +| `GET /api/echo` | 回显收到的 `X-Auth-*` 头(验证网关注入) | +| `GET /healthz` | 健康检查(含 style / idp / client_id) | +| `GET /logout` | 清本地会话 | + +## 配置 + +| 变量 | 默认 | 说明 | +| --- | --- | --- | +| `DEMO_PORT` | `18096` | 监听端口 | +| `DEMO_BIND` | `127.0.0.1` | 绑定地址 | +| `DEMO_STYLE` | `maxkey` | `maxkey` \| `standard` | +| `DEMO_IDP_BASE` | `http://127.0.0.1:18098` | IdP 地址 | +| `DEMO_CLIENT_ID` | `demo-system` | 客户端 ID | +| `DEMO_CLIENT_SECRET` | 空 | 为空则自动用 PKCE | +| `DEMO_REDIRECT_URI` | `http://127.0.0.1:/oauth2/callback` | 须与注册的 `redirect_uris` 逐字符一致 | +| `DEMO_TRUST_IAP` | `1` | 是否信任 `X-Auth-*` | + +## 安全提示 + +模式 B 下应用**无条件信任** `X-Auth-*`,因此端口不能让客户端直达,否则可伪造 +`X-Auth-User`。生产上请只绑 `127.0.0.1` / 只监听内网 / 防火墙白名单,或只经网关访问。 +本样例为了同时演示模式 A 才直接暴露端口,`DEMO_BIND` 默认已是回环。 + +## 身份字段语义 + +`sub` / `preferred_username` / `username`(MaxKey `/me`)= **登录账号**(如 `alice`); +`name` / `realname` = **显示名**(如 `爱丽丝`)。第三方系统按账号绑定用户时用前者。 diff --git a/tests/demo-system/app.py b/tests/demo-system/app.py new file mode 100644 index 0000000..aeb32a0 --- /dev/null +++ b/tests/demo-system/app.py @@ -0,0 +1,438 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +demo-system —— 一个「简单业务系统」,用来验证它与 sso 统一认证的对接。 + +两种接入姿势(同一份代码,靠环境变量切换): + + A. 自己当 OAuth2 客户端(RP) + /login -> 跳 IdP /authorize -> /oauth2/callback 收 code -> 换 token + -> 取 userinfo -> 建本地会话 -> 展示用户。 + 支持两种端点风格: + - style=maxkey : /oauth/v20/authorize | /oauth/v20/token | /oauth/v20/me + (client_id/client_secret 走表单,令牌走 access_token 参数) + - style=standard : /oauth/authorize | /oauth/token | /oauth/userinfo + (Basic 认证 + Bearer 令牌) + 未配置 client_secret 时自动启用 PKCE(S256),走公开客户端。 + + B. 前置 IAP,零改造接入 + 网关(nginx + sso_gateway 模块)在 access 阶段完成认证,并把身份以 + X-Auth-User / X-Auth-Email / X-Auth-Groups / X-Auth-Sub / X-Auth-Token + 注入请求头。业务系统不写一行 OAuth 代码,只读这几个头即可 + (见 /api/me 的 source=iap 分支)。 + +依赖:仅 Python 3 标准库。 + +安全提示:B 模式下这几个头**必须**被网关覆盖,因此业务系统端口不能让客户端 +直达(否则可伪造 X-Auth-User)。这里为了测试同时暴露了直连端口,生产上 +请用防火墙 / 只绑 127.0.0.1 / 只监听内网接口来限制。 +""" + +import base64 +import hashlib +import json +import os +import secrets +import sys +import urllib.error +import urllib.parse +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +# --------------------------------------------------------------------------- +# 配置 +# --------------------------------------------------------------------------- + +PORT = int(os.environ.get("DEMO_PORT", "18096")) +# 默认只绑回环:B 模式下应用信任 X-Auth-* 头,一旦端口直达就能伪造身份。 +BIND = os.environ.get("DEMO_BIND", "127.0.0.1") +IDP = os.environ.get("DEMO_IDP_BASE", "http://127.0.0.1:18098").rstrip("/") +CLIENT_ID = os.environ.get("DEMO_CLIENT_ID", "demo-system") +CLIENT_SECRET = os.environ.get("DEMO_CLIENT_SECRET", "") +REDIRECT_URI = os.environ.get( + "DEMO_REDIRECT_URI", "http://127.0.0.1:%d/oauth2/callback" % PORT +) +# maxkey | standard +STYLE = os.environ.get("DEMO_STYLE", "maxkey").strip().lower() +# 是否信任网关注入的 X-Auth-* 头(B 模式) +TRUST_IAP = os.environ.get("DEMO_TRUST_IAP", "1") not in ("0", "", "no", "false") +SCOPE = os.environ.get("DEMO_SCOPE", "openid profile email") + +SESSION_COOKIE = "demo_sess" + +# 按风格选择端点(这就是「MaxKey 互通」的落点:同一套代码、只换路径与传参方式) +if STYLE == "maxkey": + EP_AUTHORIZE = IDP + "/oauth/v20/authorize" + EP_TOKEN = IDP + "/oauth/v20/token" + EP_USERINFO = IDP + "/oauth/v20/me" +else: + EP_AUTHORIZE = IDP + "/oauth/authorize" + EP_TOKEN = IDP + "/oauth/token" + EP_USERINFO = IDP + "/oauth/userinfo" + +# 进程内状态(演示用:单进程单实例足够;多实例需换 Redis/共享内存) +SESSIONS = {} # sid -> {user, tokens} +PENDING = {} # state -> {verifier, redirect} + + +# --------------------------------------------------------------------------- +# OAuth2 客户端逻辑 +# --------------------------------------------------------------------------- + +def _b64url(raw): + return base64.urlsafe_b64encode(raw).decode().rstrip("=") + + +def _pkce_pair(): + """PKCE(S256):verifier 43-128 字符,challenge = base64url(sha256(verifier))。""" + verifier = _b64url(secrets.token_bytes(32)) + challenge = _b64url(hashlib.sha256(verifier.encode()).digest()) + return verifier, challenge + + +def build_authorize_url(state): + """拼授权地址。公开客户端(无 secret)自动带 PKCE。""" + params = { + "response_type": "code", + "client_id": CLIENT_ID, + "redirect_uri": REDIRECT_URI, + "scope": SCOPE, + "state": state, + } + entry = {"verifier": "", "redirect": "/"} + if not CLIENT_SECRET: + verifier, challenge = _pkce_pair() + params["code_challenge"] = challenge + params["code_challenge_method"] = "S256" + entry["verifier"] = verifier + PENDING[state] = entry + return EP_AUTHORIZE + "?" + urllib.parse.urlencode(params) + + +def _http(url, data=None, headers=None, method=None): + req = urllib.request.Request( + url, + data=data, + headers=headers or {}, + method=method or ("POST" if data else "GET"), + ) + try: + with urllib.request.urlopen(req, timeout=10) as resp: + return resp.status, resp.read().decode("utf-8", "replace") + except urllib.error.HTTPError as e: + return e.code, e.read().decode("utf-8", "replace") + + +def _json(text): + try: + return json.loads(text) + except Exception: + return None + + +def exchange_code(code, verifier): + """用授权码换令牌。两种风格的差别全在这个函数里。""" + form = { + "grant_type": "authorization_code", + "code": code, + "redirect_uri": REDIRECT_URI, + } + headers = {"Content-Type": "application/x-www-form-urlencoded"} + if CLIENT_SECRET: + if STYLE == "maxkey": + # MaxKey 惯例:client_id/client_secret 直接放表单,不用 Basic + form["client_id"] = CLIENT_ID + form["client_secret"] = CLIENT_SECRET + else: + basic = base64.b64encode( + ("%s:%s" % (CLIENT_ID, CLIENT_SECRET)).encode() + ).decode() + headers["Authorization"] = "Basic " + basic + else: + form["client_id"] = CLIENT_ID + if verifier: + form["code_verifier"] = verifier + + status, body = _http( + EP_TOKEN, urllib.parse.urlencode(form).encode(), headers + ) + if status != 200: + raise RuntimeError("换发令牌失败 HTTP %s: %s" % (status, body[:300])) + tok = _json(body) or {} + if isinstance(tok, dict) and "data" in tok and "code" in tok: + # 标准端点 /oauth/token 用 {code,msg,data} 信封;MaxKey 的 /oauth/v20/token + # 与 OIDC 惯例都是裸对象。两种都能解析,换端点不用改代码。 + tok = tok["data"] or {} + if "access_token" not in tok: + raise RuntimeError("响应中没有 access_token: %s" % body[:300]) + return tok + + +def fetch_userinfo(access_token): + """取用户信息。MaxKey 用 access_token 参数;标准用 Bearer 头。""" + if STYLE == "maxkey": + url = EP_USERINFO + "?" + urllib.parse.urlencode({"access_token": access_token}) + status, body = _http(url) + else: + status, body = _http( + EP_USERINFO, headers={"Authorization": "Bearer " + access_token} + ) + if status != 200: + raise RuntimeError("取用户信息失败 HTTP %s: %s" % (status, body[:300])) + data = _json(body) + if isinstance(data, dict) and "data" in data and "code" in data: + # sso 标准端点用 {code,msg,data} 信封;MaxKey 的 /me 是裸对象 + data = data["data"] + return data or {} + + +def identify_from_iap(headers): + """B 模式:从网关注入的头里取身份。""" + if not TRUST_IAP: + return None + user = (headers.get("X-Auth-User") or "").strip() + if not user: + return None + groups = (headers.get("X-Auth-Groups") or "").strip() + return { + "username": user, + "preferred_username": user, + "sub": (headers.get("X-Auth-Sub") or "").strip(), + "email": (headers.get("X-Auth-Email") or "").strip(), + "groups": [g for g in groups.split(",") if g], + "via": "iap", + } + + +def current_identity(handler): + """先看 IAP 注入头(B 模式),再看本地会话(A 模式)。""" + iap = identify_from_iap({k: v for k, v in handler.headers.items()}) + if iap: + return iap, None + sid = parse_cookie(handler.headers.get("Cookie"), SESSION_COOKIE) + sess = SESSIONS.get(sid) if sid else None + if sess: + return sess["user"], sess + return None, None + + +def parse_cookie(raw, name): + if not raw: + return None + for part in raw.split(";"): + k, _, v = part.strip().partition("=") + if k == name: + return v + return None + + +# --------------------------------------------------------------------------- +# 页面 +# --------------------------------------------------------------------------- + +PAGE = """ + +demo-system · 简单业务系统 +
{body}
""" + + +def render_home(ident, sess): + if not ident: + body = """ +

demo-system

+
未登录 · 一个用来验证统一认证对接的简单业务系统
+

方式 A(自己做 OAuth2 客户端):点下面的按钮跳转 IdP 登录。

+
使用统一认证登录 +
方式 B(前置 IAP):经网关访问时,网关已完成认证并注入 + X-Auth-User 等请求头,本系统直接读取、零 OAuth 代码。
+ """ + else: + iap = ident.get("via") == "iap" + rows = [ + ("账号", ident.get("preferred_username") or ident.get("username") or "-"), + ("姓名", ident.get("name") or ident.get("realname") or "-"), + ("用户 ID (sub)", ident.get("sub") or "-"), + ("邮箱", ident.get("email") or "-"), + ("用户组", "、".join(ident.get("groups") or []) or "-"), + ("部门", ident.get("department") or "-"), + ] + if sess and sess.get("access_token"): + rows.append(("令牌前缀", sess["access_token"][:28] + "…")) + rows.append(("令牌类型", "%s / 有效期 %ss" % ( + sess.get("token_type", "Bearer"), sess.get("expires_in", "-")))) + dl = "".join("
%s
%s
" % (k, v) for k, v in rows) + tag = ('来源:IAP 网关注入' if iap + else '来源:OAuth2 授权码流程') + body = """ +

demo-system

+
已登录 %s
+
%s
+ 查看 /api/me + 查看收到的身份头 + 退出 +
方式 A 的令牌已换到本系统会话里;方式 B 下本系统只知道网关 + 注入的身份头,从不接触令牌(除非网关同时注入了 X-Auth-Token)。
+ """ % (tag, dl) + return PAGE.format(body=body) + + +# --------------------------------------------------------------------------- +# HTTP 处理 +# --------------------------------------------------------------------------- + +class Handler(BaseHTTPRequestHandler): + server_version = "demo-system/1.0" + + def log_message(self, fmt, *args): + sys.stderr.write("[demo-system] %s %s\n" % (self.address_string(), fmt % args)) + + # -- 响应助手 --------------------------------------------------------- + def _send(self, status, body, ctype="application/json; charset=utf-8", extra=None): + raw = body if isinstance(body, bytes) else body.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(raw))) + for k, v in (extra or {}).items(): + self.send_header(k, v) + self.end_headers() + if self.command != "HEAD": + self.wfile.write(raw) + + def _json(self, status, obj, extra=None): + self._send(status, json.dumps(obj, ensure_ascii=False, indent=2), extra=extra) + + def _redirect(self, loc, extra=None): + self._send(302, b"", extra=dict({"Location": loc}, **(extra or {}))) + + def _html(self, status, html): + self._send(status, html, "text/html; charset=utf-8") + + # -- 路由 ------------------------------------------------------------- + def do_GET(self): + self._route("GET") + + def do_POST(self): + self._route("POST") + + def do_HEAD(self): + self._route("HEAD") + + def _route(self, method): + parsed = urllib.parse.urlparse(self.path) + path = parsed.path.rstrip("/") or "/" + + if path == "/healthz": + return self._json(200, {"ok": True, "style": STYLE, + "idp": IDP, "client_id": CLIENT_ID}) + + if path == "/": + ident, sess = current_identity(self) + return self._html(200, render_home(ident, sess)) + + if path == "/login": + qs = urllib.parse.parse_qs(parsed.query) + state = secrets.token_urlsafe(16) + url = build_authorize_url(state) + PENDING[state]["redirect"] = (qs.get("redirect") or ["/"])[0] + return self._redirect(url) + + if path in ("/oauth2/callback", "/callback"): + return self._callback(parsed) + + if path == "/api/me": + ident, sess = current_identity(self) + if not ident: + return self._json(401, {"code": 401, "msg": "未登录"}) + return self._json(200, {"source": ident.get("via", "oauth2"), + "user": ident, + "has_access_token": bool(sess and sess.get("access_token"))}) + + if path == "/api/echo": + # 把收到的请求头原样回显 —— 用来证明「网关确实注入了身份头」 + interesting = {k: v for k, v in self.headers.items() + if k.lower().startswith("x-auth-") or k.lower() in ("host", "x-real-ip")} + return self._json(200, {"injected_headers": interesting}) + + if path == "/logout": + sid = parse_cookie(self.headers.get("Cookie"), SESSION_COOKIE) + if sid: + SESSIONS.pop(sid, None) + return self._redirect("/", {"Set-Cookie": "%s=; Path=/; Max-Age=0" % SESSION_COOKIE}) + + return self._json(404, {"code": 404, "msg": "接口不存在:%s" % path}) + + # -- 授权码回调 ------------------------------------------------------- + def _callback(self, parsed): + qs = urllib.parse.parse_qs(parsed.query) + err = (qs.get("error") or [""])[0] + if err: + return self._html(400, "

授权失败

%s: %s

" % ( + err, (qs.get("error_description") or [""])[0])) + code = (qs.get("code") or [""])[0] + state = (qs.get("state") or [""])[0] + if not code: + return self._html(400, "

缺少 code

") + + # state 校验(防 CSRF)——同时取回 PKCE verifier + entry = PENDING.pop(state, None) if state else None + if state and entry is None: + return self._html(400, "

state 不匹配

可能的 CSRF,已拒绝。

") + verifier = (entry or {}).get("verifier", "") + target = (entry or {}).get("redirect", "/") + + try: + tok = exchange_code(code, verifier) + user = fetch_userinfo(tok["access_token"]) + except Exception as e: + return self._html(502, "

对接 IdP 失败

%s
" % e) + + sid = secrets.token_urlsafe(24) + SESSIONS[sid] = { + "user": user, + "access_token": tok.get("access_token", ""), + "refresh_token": tok.get("refresh_token", ""), + "token_type": tok.get("token_type", "Bearer"), + "expires_in": tok.get("expires_in", ""), + } + return self._redirect(target, { + "Set-Cookie": "%s=%s; Path=/; HttpOnly; SameSite=Lax" % (SESSION_COOKIE, sid) + }) + + +def main(): + srv = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) + sys.stderr.write( + "[demo-system] listening :%d\n" + "[demo-system] style=%s idp=%s\n" + "[demo-system] client_id=%s secret=%s pkce=%s\n" + "[demo-system] redirect_uri=%s trust_iap=%s\n" + % (PORT, STYLE, IDP, CLIENT_ID, + "已配置" if CLIENT_SECRET else "无(公开客户端)", + "否" if CLIENT_SECRET else "S256", + REDIRECT_URI, TRUST_IAP) + ) + try: + srv.serve_forever() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/tests/oauth2-e2e.sh b/tests/oauth2-e2e.sh new file mode 100644 index 0000000..320c9ce --- /dev/null +++ b/tests/oauth2-e2e.sh @@ -0,0 +1,297 @@ +#!/usr/bin/env bash +# ============================================================================ +# SSO 统一认证 —— OAuth2.0 / OIDC 端到端验证脚本 +# +# 覆盖:discovery / 登录建会话 / 授权码+PKCE / 授权码(机密) / token / +# userinfo / introspect / client_credentials / password / refresh_token / +# IAP 身份注入(无身份拦截、Bearer、Cookie、伪造头覆盖) +# +# 前置: +# - 网关以 source/conf/nginx.test.conf(或等价生产配置)运行 +# - 种子:source/data/users.json(alice/alice123)、source/data/oauth_clients.json +# (grafana / spa-demo / machine) +# - 依赖:curl、python3 +# +# 客户端密钥**不在本脚本内硬编码**,运行时从 $DATA_DIR/oauth_clients.json 读取, +# 避免密钥散落在测试代码里。 +# +# 用法: +# bash tests/oauth2-e2e.sh [IDP_BASE] [IAP_BASE] [DATA_DIR] +# ============================================================================ +set -u + +BASE="${1:-http://127.0.0.1:18098}" +IAP="${2:-http://127.0.0.1:18099}" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DATA_DIR="${3:-$ROOT/source/data}" + +JAR="$(mktemp -t sso_e2e_cookies.XXXXXX.txt)" +HDR="$(mktemp -t sso_e2e_hdr.XXXXXX.txt)" +PASS=0; FAIL=0 + +ok() { echo " ✅ $1"; PASS=$((PASS+1)); } +bad() { echo " ❌ $1"; FAIL=$((FAIL+1)); } +need() { command -v "$1" >/dev/null 2>&1 || { echo "缺少依赖: $1"; exit 2; }; } +need curl; need python3 + +echo "==> IdP: $BASE" +echo "==> IAP: $IAP" +echo "==> data: $DATA_DIR" + +# ---------- JSON 取值:支持信封 {code,msg,data:{...}} ---------- +# dj 取 .data. +# tj 取顶层 +dj() { printf '%s' "$1" | python3 -c " +import sys,json +k=sys.argv[1] +try: d=json.loads(sys.stdin.read()) +except Exception: print(''); raise SystemExit +v=(d.get('data') or {}) if isinstance(d,dict) else {} +v=v.get(k) if isinstance(v,dict) else None +print(v if isinstance(v,str) else (json.dumps(v) if v is not None else '')) +" "$2"; } +tj() { printf '%s' "$1" | python3 -c " +import sys,json +k=sys.argv[1] +try: d=json.loads(sys.stdin.read()) +except Exception: print(''); raise SystemExit +v=d.get(k) if isinstance(d,dict) else None +print(v if isinstance(v,str) else (json.dumps(v) if v is not None else '')) +" "$2"; } + +# 从响应头文件取 Set-Cookie 的某个 cookie 值(curl 对 HttpOnly cookie 会写成 +# `#HttpOnly_ ...`,故不能简单按 `^[^#]` 过滤) +hdr_cookie() { + local name="$1" file="$2" + awk -F'\t' -v n="$name" '!/^#(?!HttpOnly)/ { } { if ($6==n) v=$7 } END { print v }' "$file" +} +# 从 -D 头文件里取 Set-Cookie 行(更直接) +setcookie_val() { + local name="$1" file="$2" + python3 - "$name" "$file" <<'PY' +import sys +name, path = sys.argv[1], sys.argv[2] +out = '' +for ln in open(path, errors='replace'): + if ln.lower().startswith('set-cookie'): + first = ln.split(':', 1)[1].strip().split(';')[0] + k, _, v = first.partition('=') + if k.strip() == name: + out = v +print(out) +PY +} +# 取 Location 头的值 +hdr_location() { + python3 - "$1" <<'PY' +import sys +for ln in open(sys.argv[1], errors='replace'): + if ln.lower().startswith('location'): + print(ln.split(':', 1)[1].strip()); break +PY +} +# 从 URL 里取查询参数 +url_param() { + python3 - "$1" "$2" <<'PY' +import sys, urllib.parse as u +url, key = sys.argv[1], sys.argv[2] +q = u.urlparse(url).query +print(u.parse_qs(q).get(key, [''])[0]) +PY +} +# JWT 段数 +jwt_parts() { + printf '%s' "$1" | python3 -c "import sys;t=sys.stdin.read().strip();print(len(t.split('.')) if t else 0)" +} +# client_secret +client_secret() { + python3 -c " +import json,sys +d=json.load(open('$DATA_DIR/oauth_clients.json')) +for c in d: + if c['client_id']==sys.argv[1]: print(c['client_secret']); break +" "$1" +} + +# PKCE +pkce_verifier="$(python3 -c "import secrets;print(secrets.token_urlsafe(48))")" +pkce_challenge="$(python3 -c " +import hashlib,base64,sys +v=sys.argv[1].encode() +print(base64.urlsafe_b64encode(hashlib.sha256(v).digest()).rstrip(b'=').decode()) +" "$pkce_verifier")" + +SPA_REDIRECT="https://app.yourdomain.com/callback" +GRAFANA_REDIRECT="https://grafana.yourdomain.com/login/generic_oauth" + +# =========================================================================== +echo "## 1. discovery(OIDC 元数据)" +DISC="$(curl -s "$BASE/.well-known/openid-configuration")" +if [ "$(dj "$DISC" issuer)" = "$BASE" ] \ + && [ "$(dj "$DISC" token_endpoint)" = "$BASE/oauth/token" ] \ + && [ "$(dj "$DISC" authorization_endpoint)" = "$BASE/oauth/authorize" ] \ + && [ "$(dj "$DISC" userinfo_endpoint)" = "$BASE/oauth/userinfo" ] \ + && [ "$(dj "$DISC" introspection_endpoint)" = "$BASE/oauth/introspect" ] \ + && [[ "$(dj "$DISC" code_challenge_methods_supported)" == *S256* ]]; then + ok "discovery 字段齐全(issuer/token/authorize/userinfo/introspect + S256)" +else + bad "discovery 异常: $DISC" +fi + +# =========================================================================== +echo "## 2. 登录建 SSO 会话(alice)" +curl -s -D "$HDR" -o /dev/null -c "$JAR" -X POST "$BASE/login" \ + --data-urlencode 'username=alice' \ + --data-urlencode 'password=alice123' \ + --data-urlencode 'redirect=/' +SSO="$(setcookie_val sso_sid "$HDR")" +COOKIE_CT="$(python3 -c " +for ln in open('$HDR',errors='replace'): + if ln.lower().startswith('content-type'): print(ln.split(':',1)[1].strip()) +")" +if [ -n "$SSO" ]; then + ok "登录成功并下发会话 Cookie(sso_sid, ${#SSO} 字符)" +else + bad "登录未拿到会话 Cookie(headers: $(grep -ci set-cookie "$HDR" 2>/dev/null) 个 set-cookie)" +fi +CK="sso_sid=$SSO" + +# =========================================================================== +echo "## 3. 授权码 + PKCE(公开客户端 spa-demo)" +curl -s -D "$HDR" -o /dev/null -b "$CK" \ + "$BASE/oauth/authorize?response_type=code&client_id=spa-demo&redirect_uri=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=''))" "$SPA_REDIRECT")&scope=openid%20profile%20email&state=xyz&code_challenge=$pkce_challenge&code_challenge_method=S256" +LOC="$(hdr_location "$HDR")" +CODE="$(url_param "$LOC" code)" +STATE="$(url_param "$LOC" state)" +if [ -n "$CODE" ] && [ "$STATE" = "xyz" ] && [[ "$LOC" == "$SPA_REDIRECT"* ]]; then + ok "拿到授权码并回跳(state 原样带回)" +else + bad "未拿到授权码 (Location=$LOC)" +fi + +TOK="$(curl -s -X POST "$BASE/oauth/token" \ + -d "grant_type=authorization_code&code=$CODE&redirect_uri=$SPA_REDIRECT&client_id=spa-demo&code_verifier=$pkce_verifier")" +AT="$(dj "$TOK" access_token)" +IT="$(dj "$TOK" id_token)" +RT="$(dj "$TOK" refresh_token)" +if [ "$(jwt_parts "$AT")" = "3" ] && [ "$(jwt_parts "$IT")" = "3" ] && [ -n "$RT" ]; then + ok "授权码换发成功(access/id/refresh 三件套,access 为 HS256 JWT)" +else + bad "授权码换发失败: $TOK" +fi + +# =========================================================================== +echo "## 4. userinfo(Bearer access_token)" +UI="$(curl -s -H "Authorization: Bearer $AT" "$BASE/oauth/userinfo")" +if [ "$(dj "$UI" sub)" = "alice" ] && [ "$(dj "$UI" email)" = "alice@yourdomain.com" ]; then + ok "userinfo 返回 sub=alice / email 正确" +else + bad "userinfo 异常: $UI" +fi + +# =========================================================================== +echo "## 5. introspect(RFC 7662,需客户端鉴权)" +IS="$(curl -s -X POST "$BASE/oauth/introspect" -d "client_id=spa-demo&token=$AT")" +if [ "$(dj "$IS" active)" = "true" ] && [ "$(dj "$IS" sub)" = "alice" ]; then + ok "introspect: active=true, sub=alice" +else + bad "introspect 异常: $IS" +fi + +# =========================================================================== +echo "## 6. 授权码(机密客户端 grafana,Basic 鉴权、无 PKCE)" +curl -s -D "$HDR" -o /dev/null -b "$CK" \ + "$BASE/oauth/authorize?response_type=code&client_id=grafana&redirect_uri=$(python3 -c "import urllib.parse,sys;print(urllib.parse.quote(sys.argv[1],safe=''))" "$GRAFANA_REDIRECT")&scope=openid%20profile%20email&state=abc" +LOC2="$(hdr_location "$HDR")" +CODE2="$(url_param "$LOC2" code)" +GSEC="$(client_secret grafana)" +TOK2="$(curl -s -X POST "$BASE/oauth/token" -u "grafana:$GSEC" \ + -d "grant_type=authorization_code&code=$CODE2&redirect_uri=$GRAFANA_REDIRECT")" +AT2="$(dj "$TOK2" access_token)" +if [ -n "$CODE2" ] && [ "$(jwt_parts "$AT2")" = "3" ]; then + ok "机密客户端授权码换取成功(Basic 鉴权)" +else + bad "机密客户端流程失败 (code=${CODE2:0:8}…, body=$TOK2)" +fi + +# =========================================================================== +echo "## 7. client_credentials(machine 客户端)" +MSEC="$(client_secret machine)" +CC="$(curl -s -X POST "$BASE/oauth/token" -u "machine:$MSEC" \ + -d 'grant_type=client_credentials&scope=openid')" +CC_AT="$(dj "$CC" access_token)" +CC_IS="$(curl -s -X POST "$BASE/oauth/introspect" -u "machine:$MSEC" -d "token=$CC_AT")" +if [ "$(jwt_parts "$CC_AT")" = "3" ] && [ "$(dj "$CC_IS" active)" = "true" ] && [ "$(dj "$CC_IS" sub)" = "machine" ]; then + ok "client_credentials 签发 + 自省 active=true(sub=machine)" +else + bad "client_credentials 异常: $CC / $CC_IS" +fi + +# =========================================================================== +echo "## 8. password grant(machine 客户端代资源所有者)" +PW="$(curl -s -X POST "$BASE/oauth/token" -u "machine:$MSEC" \ + -d 'grant_type=password&username=alice&password=alice123&scope=openid profile email')" +PW_AT="$(dj "$PW" access_token)" +PW_ID="$(dj "$PW" id_token)" +PW_UI="$(curl -s -H "Authorization: Bearer $PW_AT" "$BASE/oauth/userinfo")" +if [ "$(jwt_parts "$PW_AT")" = "3" ] && [ "$(jwt_parts "$PW_ID")" = "3" ] && [ "$(dj "$PW_UI" sub)" = "alice" ]; then + ok "password grant 签发 access+id_token,且 token 可用于 userinfo" +else + bad "password grant 异常: $PW / $PW_UI" +fi + +# =========================================================================== +echo "## 9. refresh_token(spa-demo 刷新)" +RF="$(curl -s -X POST "$BASE/oauth/token" \ + -d "grant_type=refresh_token&refresh_token=$RT&client_id=spa-demo")" +RF_AT="$(dj "$RF" access_token)" +if [ "$(jwt_parts "$RF_AT")" = "3" ] && [ "$RF_AT" != "$AT" ]; then + ok "refresh_token 换发成功(新 access_token)" +else + bad "refresh_token 失败: $RF" +fi + +# =========================================================================== +echo "## 10. IAP:无身份 → 门禁拦截(302 跳登录,绝不直达后端)" +curl -s -D "$HDR" -o /dev/null "$IAP/" +ST="$(head -1 "$HDR" | awk '{print $2}')" +LI="$(hdr_location "$HDR")" +if [ "$ST" = "302" ] && [[ "$LI" == *"/login"* ]]; then + ok "无身份被拦截并跳登录(302 → ${LI})" +else + bad "无身份行为异常 (http=$ST, location=$LI)" +fi + +# =========================================================================== +echo "## 11. IAP:Bearer access_token → 注入 X-Auth-* 到后端" +R11="$(curl -s -H "Authorization: Bearer $AT" "$IAP/")" +if [[ "$R11" == *'"x_auth_user":"alice"'* ]] && [[ "$R11" == *'"x_auth_email":"alice@yourdomain.com"'* ]]; then + ok "Bearer 注入成功(x_auth_user=alice)" +else + bad "IAP Bearer 注入异常: $R11" +fi + +# =========================================================================== +echo "## 12. IAP:SSO 会话 Cookie → 注入 X-Auth-* 到后端" +R12="$(curl -s -b "$CK" "$IAP/")" +if [[ "$R12" == *'"x_auth_user":"alice"'* ]]; then + ok "Cookie 注入成功(x_auth_user=alice)" +else + bad "IAP Cookie 注入异常: $R12" +fi + +# =========================================================================== +echo "## 13. IAP:客户端伪造同名头被网关覆盖" +R13="$(curl -s -H "Authorization: Bearer $AT" -H "X-Auth-User: evil" -H "X-Auth-Groups: root" "$IAP/")" +if [[ "$R13" == *'"x_auth_user":"alice"'* ]] && [[ "$R13" != *'"x_auth_user":"evil"'* ]] && [[ "$R13" != *'"x_auth_groups":"root"'* ]]; then + ok "伪造的 X-Auth-User / X-Auth-Groups 被网关断言覆盖" +else + bad "IAP 未覆盖伪造头: $R13" +fi + +# =========================================================================== +echo +echo "======================== 结果 ========================" +echo " 通过: $PASS 失败: $FAIL" +rm -f "$JAR" "$HDR" +[ "$FAIL" = "0" ] diff --git a/tests/oauth2-maxkey-e2e.sh b/tests/oauth2-maxkey-e2e.sh new file mode 100755 index 0000000..01aa7cb --- /dev/null +++ b/tests/oauth2-maxkey-e2e.sh @@ -0,0 +1,329 @@ +#!/usr/bin/env bash +# ============================================================================ +# MaxKey OAuth2 互通 + demo-system 接入 端到端验证 +# +# 三组断言: +# A. MaxKey 端点别名与传参约定(/oauth/v20/*、/oauth2.0/*、context-path 归一化) +# —— 照抄 MaxKey 文档的应用不改一行代码即可对接 +# B. demo-system 自己当 OAuth2 客户端:授权码流全链路(style=maxkey) +# C. demo-system 经 IAP 零改造接入:网关认证 + X-Auth-* 注入 + 伪造头被覆盖 +# +# 前置: +# - scripts/run-local-e2e.sh 已拉起 nginx(:18098 IdP / :18095 IAP) +# 与 demo-system(:18096) +# - 种子:source/data/users.json(alice/alice123)、source/data/oauth_clients.json +# (demo-system 机密 / demo-spa 公开) +# - 依赖:curl、python3 +# +# 客户端密钥不硬编码,运行时从 $DATA_DIR/oauth_clients.json 读取。 +# +# 用法: +# bash tests/oauth2-maxkey-e2e.sh [IDP_BASE] [DEMO_BASE] [IAP_DEMO_BASE] [DATA_DIR] +# ============================================================================ +set -u + +IDP="${1:-http://127.0.0.1:18098}" +DEMO="${2:-http://127.0.0.1:18096}" +IAPD="${3:-http://127.0.0.1:18095}" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DATA_DIR="${4:-$ROOT/source/data}" + +JAR="$(mktemp -t sso_mk_cookies.XXXXXX.txt)" +H1="$(mktemp -t sso_mk_h1.XXXXXX.txt)" +H2="$(mktemp -t sso_mk_h2.XXXXXX.txt)" +H3="$(mktemp -t sso_mk_h3.XXXXXX.txt)" +PASS=0; FAIL=0 + +ok() { echo " ✅ $1"; PASS=$((PASS+1)); } +bad() { echo " ❌ $1"; FAIL=$((FAIL+1)); } +need() { command -v "$1" >/dev/null 2>&1 || { echo "缺少依赖: $1"; exit 2; }; } +need curl; need python3 + +echo "==> IdP : $IDP" +echo "==> demo : $DEMO" +echo "==> IAP+demo : $IAPD" +echo "==> data : $DATA_DIR" + +# ---------- 助手 ----------------------------------------------------------- +# 顶层键取值(MaxKey /me 是裸对象,不套 {code,msg,data} 信封) +tj() { printf '%s' "$1" | python3 -c " +import sys,json +k=sys.argv[1] +try: d=json.loads(sys.stdin.read()) +except Exception: print(''); raise SystemExit +v=d.get(k) if isinstance(d,dict) else None +print(v if isinstance(v,str) else (json.dumps(v) if v is not None else '')) +" "$2"; } + +# 取 Location 头 +hdr_location() { + python3 - "$1" <<'PY' +import sys +for ln in open(sys.argv[1], errors='replace'): + if ln.lower().startswith('location'): + print(ln.split(':', 1)[1].strip()); break +PY +} + +# 从 Set-Cookie 取某个 cookie 值(curl 对 HttpOnly 会写 `#HttpOnly_` 前缀,不能用 ^[^#] 过滤) +setcookie_val() { + python3 - "$1" "$2" <<'PY' +import sys +name, path = sys.argv[1], sys.argv[2] +out = '' +for ln in open(path, errors='replace'): + if ln.lower().startswith('set-cookie'): + first = ln.split(':', 1)[1].strip().split(';')[0] + k, _, v = first.partition('=') + if k.strip() == name: + out = v +print(out) +PY +} + +# 从 curl cookie jar 读某个 cookie 值。 +# jar 里 HttpOnly cookie 写成 `#HttpOnly_\t...`,普通行也可能以 `#` 开头, +# 所以要剥前缀而不是简单按 `^[^#]` 过滤。 +jar_cookie() { + python3 - "$1" "$2" <<'PY' +import sys +name, path = sys.argv[1], sys.argv[2] +out = '' +for ln in open(path, errors='replace'): + ln = ln.rstrip('\n') + if ln.startswith('#HttpOnly_'): + ln = ln[len('#HttpOnly_'):] + elif ln.startswith('#') or not ln.strip(): + continue + f = ln.split('\t') + if len(f) >= 7 and f[5] == name: + out = f[6] +print(out) +PY +} + +# 从 URL 取查询参数 +qget() { + python3 - "$1" "$2" <<'PY' +import sys, urllib.parse as u +q = u.urlparse(sys.argv[1]).query +print((u.parse_qs(q).get(sys.argv[2]) or [''])[0]) +PY +} + +# 读客户端密钥(不硬编码) +secret_of() { + python3 - "$DATA_DIR/oauth_clients.json" "$1" <<'PY' +import json, sys +for c in json.load(open(sys.argv[1])): + if c["client_id"] == sys.argv[2]: + print(c.get("client_secret", "")); break +PY +} + +DEMO_SECRET="$(secret_of demo-system)" +REDIRECT="http://127.0.0.1:18096/oauth2/callback" +STATE="mk-state-$$" + +# =========================================================================== +echo +echo "## A. MaxKey 端点别名与传参约定" +# =========================================================================== + +# A1. /oauth/v20/authorize 存在(未登录 → 302 到登录页) +CODE="$(curl -s -o /dev/null -w '%{http_code}' "$IDP/oauth/v20/authorize?client_id=demo-system&response_type=code&redirect_uri=$REDIRECT")" +if [ "$CODE" = "302" ]; then ok "GET /oauth/v20/authorize 命中(302 跳登录)"; else bad "GET /oauth/v20/authorize 期望 302,实得 $CODE"; fi + +# A2. context-path 归一化:/maxkey/... 与 /sign/authz/... 都能命中 +for P in "/maxkey/oauth/v20/authorize" "/sign/authz/oauth/v20/authorize" "/oauth2.0/authorize"; do + CODE="$(curl -s -o /dev/null -w '%{http_code}' "$IDP$P?client_id=demo-system&response_type=code&redirect_uri=$REDIRECT")" + if [ "$CODE" = "302" ]; then ok "GET $P 命中(context-path 归一化)"; else bad "GET $P 期望 302,实得 $CODE"; fi +done + +# A3. token 端点别名存在(缺参数应 4xx,而不是 404) +CODE="$(curl -s -o /dev/null -w '%{http_code}' -X POST "$IDP/sign/authz/oauth/v20/token" -d 'grant_type=authorization_code')" +if [ "$CODE" != "404" ] && [ "$CODE" != "000" ]; then ok "POST /sign/authz/oauth/v20/token 命中(${CODE},非 404)"; else bad "token 别名未命中(${CODE})"; fi + +# A4. 登录 IdP 建立 SSO 会话(MaxKey 风格的客户端不会走 /login,这里只是为了拿到会话) +curl -s -o /dev/null -D "$H1" -c "$JAR" -X POST "$IDP/login" \ + --data-urlencode "username=alice" --data-urlencode "password=alice123" \ + --data-urlencode "redirect=/" +SSO="$(setcookie_val sso_sid "$H1")" +if [ -n "$SSO" ]; then ok "IdP 登录成功,下发 SSO 会话 Cookie"; else bad "IdP 登录未下发会话 Cookie"; fi + +# A5. 带会话走 MaxKey authorize → 拿到授权码 +curl -s -o /dev/null -D "$H1" -b "$JAR" \ + "$IDP/oauth/v20/authorize?client_id=demo-system&response_type=code&redirect_uri=$REDIRECT&scope=openid+profile+email&state=$STATE" +LOC="$(hdr_location "$H1")" +CODE_AUTH="$(qget "$LOC" code)" +RET_STATE="$(qget "$LOC" state)" +if [ -n "$CODE_AUTH" ] && [ "$RET_STATE" = "$STATE" ]; then + ok "MaxKey authorize 返回授权码(state 原样回传)" +else + bad "MaxKey authorize 未返回 code/state:$LOC" +fi + +# A6. MaxKey token:client_id/client_secret 走表单,**不用 Basic** +TOK_JSON="$(curl -s -X POST "$IDP/oauth/v20/token" \ + -d "grant_type=authorization_code" \ + --data-urlencode "client_id=demo-system" \ + --data-urlencode "client_secret=$DEMO_SECRET" \ + --data-urlencode "code=$CODE_AUTH" \ + --data-urlencode "redirect_uri=$REDIRECT")" +AT="$(tj "$TOK_JSON" access_token)" +case "$AT" in + *.*.*) ok "MaxKey token 换发成功(表单传密钥,access_token 为 JWT)" ;; + *) bad "MaxKey token 换发异常:$TOK_JSON" ;; +esac + +# A7. MaxKey /me:令牌走 access_token 参数,返回 MaxKey 扁平字段 +# username/userid 必须是**登录账号**(alice),realname 才是显示名 +ME_JSON="$(curl -s "$IDP/oauth/v20/me?access_token=$AT")" +U_NAME="$(tj "$ME_JSON" username)" +U_ID="$(tj "$ME_JSON" userid)" +U_MAIL="$(tj "$ME_JSON" email)" +U_REAL="$(tj "$ME_JSON" realname)" +if [ "$U_NAME" = "alice" ] && [ "$U_ID" = "alice" ] && [ -n "$U_MAIL" ] && [ -n "$U_REAL" ]; then + ok "MaxKey /me 账号语义正确(username=alice, realname=${U_REAL})" +else + bad "MaxKey /me 字段异常(username=${U_NAME}, userid=$U_ID, email=$U_MAIL, realname=${U_REAL})" +fi + +# A8. /oauth2.0/profile 别名(另一族命名) +ME2="$(curl -s "$IDP/oauth2.0/profile?access_token=$AT")" +if [ "$(tj "$ME2" username)" = "alice" ]; then ok "GET /oauth2.0/profile 别名命中"; else bad "/oauth2.0/profile 别名异常:$ME2"; fi + +# A9. 标准端点不受影响(回归):Bearer 头 + userinfo 信封 +STD="$(curl -s "$IDP/oauth/userinfo" -H "Authorization: Bearer $AT")" +if [ "$(printf '%s' "$STD" | python3 -c " +import sys,json +d=json.loads(sys.stdin.read()) +print((d.get('data') or {}).get('preferred_username','')) +")" = "alice" ]; then ok "标准 /oauth/userinfo(Bearer + 信封)仍正常"; else bad "标准 userinfo 回归失败:$STD"; fi + +# =========================================================================== +echo +echo "## B. demo-system 自己当 OAuth2 客户端(授权码流)" +# =========================================================================== + +HEALTH="$(curl -s "$DEMO/healthz")" +if [ "$(tj "$HEALTH" style)" = "maxkey" ] && [ "$(tj "$HEALTH" client_id)" = "demo-system" ]; then + ok "demo-system 就绪(style=maxkey, client_id=demo-system)" +else + bad "demo-system /healthz 异常:$HEALTH" +fi + +HOME="$(curl -s "$DEMO/")" +case "$HOME" in + *"统一认证登录"*) ok "未登录访问首页显示登录入口" ;; + *) bad "首页未显示登录入口" ;; +esac + +# B3. /login 跳转到 IdP 的 MaxKey authorize(而非标准路径) +curl -s -o /dev/null -D "$H2" "$DEMO/login" +AUTH_URL="$(hdr_location "$H2")" +case "$AUTH_URL" in + *"/oauth/v20/authorize"*) ok "demo-system /login 跳 MaxKey 端点 /oauth/v20/authorize" ;; + *) bad "demo-system /login 跳转异常:$AUTH_URL" ;; +esac +D_STATE="$(qget "$AUTH_URL" state)" +if [ -n "$D_STATE" ]; then ok "demo-system 生成并携带 state(防 CSRF)"; else bad "demo-system 未带 state"; fi + +# B5. 带 SSO 会话完成授权 → 回调地址带 code +curl -s -o /dev/null -D "$H3" -b "$JAR" "$AUTH_URL" +CB_LOC="$(hdr_location "$H3")" +D_CODE="$(qget "$CB_LOC" code)" +if [ -n "$D_CODE" ]; then ok "授权完成,回调携带授权码"; else bad "未拿到授权码:$CB_LOC"; fi + +# B6. 回调:应用用 code 换 token + 取 userinfo + 建本地会话 +# 必须 -b + -c 同时给:只给 -c 时 curl 不加载既有 jar,会把它整个覆写成空, +# 后续依赖 SSO 会话的断言(C 组)会集体误判为「未登录」。 +CB_CODE="$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR" -c "$JAR" "$CB_LOC")" +D_SESS="$(jar_cookie demo_sess "$JAR")" +if [ "$CB_CODE" = "302" ] && [ -n "$D_SESS" ]; then + ok "回调换发成功并建立 demo-system 本地会话" +else + bad "回调异常(http=$CB_CODE, cookie=${D_SESS})" +fi + +# B7. 应用侧 /api/me +D_ME="$(curl -s -b "$JAR" "$DEMO/api/me")" +SRC="$(tj "$D_ME" source)" +D_USER="$(printf '%s' "$D_ME" | python3 -c " +import sys,json +d=json.loads(sys.stdin.read()) +print((d.get('user') or {}).get('preferred_username','')) +")" +if [ "$SRC" = "oauth2" ] && [ "$D_USER" = "alice" ]; then + ok "demo-system /api/me 返回 OAuth2 会话身份(alice)" +else + bad "demo-system /api/me 异常:$D_ME" +fi + +# B8. 非法 state 应被拒(CSRF 防护) +CB_BAD="$(curl -s -o /dev/null -w '%{http_code}' "$DEMO/oauth2/callback?code=x&state=bogus-$RANDOM")" +if [ "$CB_BAD" = "400" ]; then ok "回调拒绝非法 state(400,防 CSRF)"; else bad "非法 state 未被拒绝(http=${CB_BAD})"; fi + +# =========================================================================== +echo +echo "## C. demo-system 经 IAP 零改造接入(18095)" +# =========================================================================== + +# C1. 无身份 → 302 跳登录(业务系统根本没被访问到) +curl -s -o /dev/null -D "$H1" "$IAPD/" +ILOC="$(hdr_location "$H1")" +case "$ILOC" in + *"/login"*) ok "IAP 无身份拦截并跳登录" ;; + *) bad "IAP 无身份行为异常:$ILOC" ;; +esac + +# C2. 带 SSO 会话经网关 → 网关注入身份头,业务系统读到 +curl -s -o /dev/null -b "$JAR" "$IAPD/" -D "$H2" +IAP_HOME_CODE="$(awk 'NR==1{print $2}' "$H2")" +if [ "$IAP_HOME_CODE" = "200" ]; then ok "IAP 带会话放行(业务系统 200)"; else bad "IAP 放行失败(http=${IAP_HOME_CODE})"; fi + +ECHO_JSON="$(curl -s -b "$JAR" "$IAPD/api/echo")" +INJ_USER="$(printf '%s' "$ECHO_JSON" | python3 -c " +import sys,json +d=json.loads(sys.stdin.read()) +h={k.lower():v for k,v in (d.get('injected_headers') or {}).items()} +print(h.get('x-auth-user','')) +")" +if [ "$INJ_USER" = "alice" ]; then ok "网关注入 X-Auth-User=alice 到业务系统"; else bad "未注入 X-Auth-User:$ECHO_JSON"; fi + +# C4. 业务系统按注入头识身份(不接触令牌) +I_ME="$(curl -s -b "$JAR" "$IAPD/api/me")" +I_SRC="$(tj "$I_ME" source)" +I_USER="$(printf '%s' "$I_ME" | python3 -c " +import sys,json +d=json.loads(sys.stdin.read()) +print((d.get('user') or {}).get('username','')) +")" +if [ "$I_SRC" = "iap" ] && [ "$I_USER" = "alice" ]; then + ok "业务系统零改造识别身份(source=iap, alice)" +else + bad "IAP 身份识别失败:$I_ME" +fi + +# C5. 伪造同名头被网关覆盖(IAP 的关键安全属性) +SPOOF="$(curl -s -b "$JAR" -H 'X-Auth-User: attacker' -H 'X-Auth-Groups: root' "$IAPD/api/echo")" +SP_USER="$(printf '%s' "$SPOOF" | python3 -c " +import sys,json +d=json.loads(sys.stdin.read()) +h={k.lower():v for k,v in (d.get('injected_headers') or {}).items()} +print(h.get('x-auth-user','')) +")" +if [ "$SP_USER" = "alice" ]; then + ok "客户端伪造 X-Auth-User 被网关覆盖(仍为 alice)" +else + bad "伪造头未被覆盖,实得:$SP_USER" +fi + +# =========================================================================== +echo +echo "==========================================" +echo " 通过: $PASS 失败: $FAIL" +echo "==========================================" +rm -f "$JAR" "$H1" "$H2" "$H3" 2>/dev/null || true +[ "$FAIL" = "0" ] || exit 1 +exit 0