diff --git a/doc/webapp-guide.md b/doc/webapp-guide.md index 36694073..707cb9ce 100644 --- a/doc/webapp-guide.md +++ b/doc/webapp-guide.md @@ -43,6 +43,7 @@ 20. [可观测性:`/health` / `/ready` / `/metrics`](#20-可观测性health--ready--metrics) 21. [WebSocket 房间与广播](#21-websocket-房间与广播) 22. [会话与安全 Cookie](#22-会话与安全-cookie) +23. [RBAC 与 CSRF](#23-rbac-与-csrf) --- @@ -1637,6 +1638,35 @@ app.post("/login", [](uvcpp::uvcpp_web_request& req, uvcpp::uvcpp_web_response& --- +## 23. RBAC 与 CSRF + +`uvcpp_web_auth.h`(#70 第二批;密码哈希/限流/审计仍留后续): + +```cpp +// doc-snippet: fragment — 装配摘录,不是完整翻译单元。 +app.use(uvcpp_session_middleware(store, session_opts)); +app.use(uvcpp_csrf_protect()); +uvcpp::uvcpp_roles_options ropts; +ropts.skip_paths = {"/login", "/me"}; +app.use(uvcpp_require_roles({"admin"}, ropts)); + +app.post("/login", [](uvcpp::uvcpp_web_request& req, ...) { + uvcpp::uvcpp_session* s = uvcpp::uvcpp_session_of(req); + if (s) uvcpp::uvcpp_session_set_roles(*s, {"admin"}); +}); +``` + +- **RBAC**:角色存在会话数据里(`roles`,逗号分隔);`require_roles` 是**任一 + 命中**;无会话 / 会话里没有角色键 → **401**,有角色但不匹配 → **403**; + `skip_paths` 精确匹配放行(登录、健康检查)。 +- **CSRF**:每会话随机 token,存会话 + 发**非 HttpOnly** Cookie(SameSite=Strict); + 不安全方法(非 GET/HEAD/OPTIONS)必须带 `X-CSRF-Token` 或表单 `_csrf`, + 与会话 token 逐字节相同,否则 403;`uvcpp_csrf_protect()` 必须在会话中间件之后。 +- 没装会话中间件时 `csrf_protect()` 返回 500(配置错误不静默放行)。 +- 用例:`web_app_auth_func.cpp`。 + +--- + ## 可运行示例 `examples/webapp_demo.cpp` —— 默认**自校验**:起一个 app(路由 + 中间件 + 静态 + diff --git a/src/webapp/uvcpp_web_auth.cpp b/src/webapp/uvcpp_web_auth.cpp new file mode 100644 index 00000000..c44feb07 --- /dev/null +++ b/src/webapp/uvcpp_web_auth.cpp @@ -0,0 +1,213 @@ +/** + * @file src/webapp/uvcpp_web_auth.cpp + * @brief RBAC 与 CSRF 中间件的实现。 + * @author zhuweiye + * @version 1.0.0 + */ + +#include "webapp/uvcpp_web_auth.h" + +#if UVCPP_WEBAPP_ENABLE + +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace uvcpp { + +uvcpp_roles_options::uvcpp_roles_options() : session_key("roles") {} + +uvcpp_csrf_options::uvcpp_csrf_options() + : token_key("csrf"), + cookie_name("csrf"), + header_name("x-csrf-token"), + form_field("_csrf"), + same_site("Strict"), + cookie_secure(false) {} + +namespace { + +std::string random_token() { + static std::mutex mu; + static std::random_device rd; + std::lock_guard lk(mu); + char buf[33]; + for (int i = 0; i < 32; i += 8) { + const unsigned v = static_cast(rd()); + for (int k = 0; k < 8; ++k) { + const unsigned nib = (v >> (k * 4)) & 0xfu; + buf[i + k] = static_cast(nib < 10 ? '0' + nib : 'a' + (nib - 10)); + } + } + buf[32] = '\0'; + return std::string(buf); +} + +std::vector split_roles(const std::string& v) { + std::vector out; + std::string cur; + for (size_t i = 0; i < v.size(); ++i) { + if (v[i] == ',') { + if (!cur.empty()) out.push_back(cur); + cur.clear(); + } else if (v[i] != ' ' && v[i] != '\t') { + cur += v[i]; + } + } + if (!cur.empty()) out.push_back(cur); + return out; +} + +bool secure_eq(const std::string& a, const std::string& b) { + // 长度不等也走完整循环,尽量不把"差在哪一位"泄漏给计时侧信道。 + const size_t n = a.size() > b.size() ? a.size() : b.size(); + unsigned diff = a.size() == b.size() ? 0u : 1u; + for (size_t i = 0; i < n; ++i) { + const unsigned char ca = i < a.size() ? static_cast(a[i]) : 0; + const unsigned char cb = i < b.size() ? static_cast(b[i]) : 0; + diff |= static_cast(ca ^ cb); + } + return diff == 0; +} + +bool is_safe_method(http_method m) { + return m == http_method::HTTP_GET || m == http_method::HTTP_HEAD || + m == http_method::HTTP_OPTIONS; +} + +} // namespace + +// --------------------------------------------------------------------------- +// RBAC +// --------------------------------------------------------------------------- + +void uvcpp_session_set_roles(uvcpp_session& s, + const std::vector& roles, + const uvcpp_roles_options& opts) { + std::string v; + for (size_t i = 0; i < roles.size(); ++i) { + if (i != 0) v += ','; + v += roles[i]; + } + if (v.empty()) { + s.erase(opts.session_key); + } else { + s.set(opts.session_key, v); + } +} + +bool uvcpp_session_has_role(const uvcpp_session& s, const std::string& role, + const uvcpp_roles_options& opts) { + if (role.empty() || !s.has(opts.session_key)) return false; + const std::vector have = split_roles(s.get(opts.session_key)); + for (size_t i = 0; i < have.size(); ++i) { + if (have[i] == role) return true; + } + return false; +} + +uvcpp_web_middleware uvcpp_require_roles( + const std::vector& roles, const uvcpp_roles_options& opts) { + return [roles, opts](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next next) { + for (size_t i = 0; i < opts.skip_paths.size(); ++i) { + if (req.path() == opts.skip_paths[i]) { + next(); + return; + } + } + uvcpp_session* s = uvcpp_session_of(req); + // 没有会话、或会话里**根本没有角色键** = 未认证 → 401; + // 有角色键但一个都不匹配 = 已认证但没权限 → 403。 + if (s == nullptr || s->empty() || !s->has(opts.session_key)) { + resp.status(http_status::UNAUTHORIZED); + resp.text(std::string("unauthorized")); + resp.end(); + return; // 不调 next:链到此为止 + } + for (size_t i = 0; i < roles.size(); ++i) { + if (uvcpp_session_has_role(*s, roles[i], opts)) { + next(); + return; + } + } + resp.status(http_status::FORBIDDEN); + resp.text(std::string("forbidden")); + resp.end(); + }; +} + +// --------------------------------------------------------------------------- +// CSRF +// --------------------------------------------------------------------------- + +const std::string* uvcpp_csrf_token(uvcpp_web_request& req, + const uvcpp_csrf_options& opts) { + uvcpp_session* s = uvcpp_session_of(req); + if (s == nullptr || s->empty() || !s->has(opts.token_key)) return nullptr; + // session 的 get 按值返回;用请求级属性缓存一份,保证返回指针活到请求结束。 + const std::string token = s->get(opts.token_key); + std::shared_ptr held = + req.attribute_as("uvcpp.csrf.token"); + if (!held || *held != token) { + held = std::make_shared(token); + req.set_attribute("uvcpp.csrf.token", held); + } + return held.get(); +} + +uvcpp_web_middleware uvcpp_csrf_protect(const uvcpp_csrf_options& opts) { + return [opts](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next next) { + uvcpp_session* s = uvcpp_session_of(req); + if (s == nullptr) { + // 没装会话中间件是配置错误:**拒绝**而不是静默放行,否则 CSRF 形同虚设。 + resp.status(http_status::INTERNAL_SERVER_ERROR); + resp.text(std::string("csrf: session middleware missing")); + resp.end(); + return; + } + std::string token = s->get(opts.token_key); + if (token.empty()) { + token = random_token(); + s->set(opts.token_key, token); + // 新 token:立刻刷新双提交 Cookie。非 HttpOnly —— 前端 JS 要读它。 + resp.set_cookie(opts.cookie_name, token, "/", -1, /*http_only=*/false, + opts.cookie_secure, opts.same_site); + } else { + const std::string* ck = req.cookie(opts.cookie_name); + if (ck == nullptr || *ck != token) { + resp.set_cookie(opts.cookie_name, token, "/", -1, /*http_only=*/false, + opts.cookie_secure, opts.same_site); + } + } + + if (is_safe_method(req.method())) { + next(); + return; + } + + std::string supplied = req.header(opts.header_name); + if (supplied.empty()) { + const std::string* f = req.form(opts.form_field); + if (f != nullptr) supplied = *f; + } + if (!secure_eq(supplied, token)) { + resp.status(http_status::FORBIDDEN); + resp.text(std::string("csrf token mismatch")); + resp.end(); + return; + } + next(); + }; +} + +} // namespace uvcpp + +#endif // UVCPP_WEBAPP_ENABLE diff --git a/src/webapp/uvcpp_web_auth.h b/src/webapp/uvcpp_web_auth.h new file mode 100644 index 00000000..ffe2d061 --- /dev/null +++ b/src/webapp/uvcpp_web_auth.h @@ -0,0 +1,122 @@ +/** + * @file src/webapp/uvcpp_web_auth.h + * @brief 会话之上的 RBAC 与 CSRF(issue #70 第二批)。 + * @author zhuweiye + * @version 1.0.0 + * + * ```cpp + * app.use(uvcpp_session_middleware(store, session_opts)); + * app.use(uvcpp_csrf_protect()); // 先保证有会话 + * app.use(uvcpp_require_roles({"admin"}, opts)); // opts.skip_paths = {"/login"} + * + * app.post("/login", [](uvcpp_web_request& req, uvcpp_web_response& resp, + * uvcpp_web_next) { + * uvcpp_session* s = uvcpp_session_of(req); + * if (s) uvcpp_session_set_roles(*s, {"admin"}); // 业务校验之后 + * resp.end(); + * }); + * ``` + * + * ## RBAC 语义 + * + * - 角色存在会话的数据里(键名可配,默认 `roles`,逗号分隔),由业务在登录 + * 成功时通过 `uvcpp_session_set_roles()` 写入; + * - `uvcpp_require_roles(list)` 是**任一命中**(OR)语义:会话里有 list 中 + * 任意一个即可;全部都要请传单个角色或用多条中间件; + * - 没有会话 / 会话里没有角色 → **401**;有角色但不匹配 → **403**; + * - `skip_paths` 按**归一化后的路径精确匹配**(登录、健康检查这类要放行)。 + * + * ## CSRF 语义(双提交 + 会话绑定) + * + * - 每个会话生成一个随机 token,存在会话里并写一条**非 HttpOnly** Cookie + * (前端 JS 需要读它放请求头);`SameSite` 默认 `Strict`; + * - 不安全方法(非 GET/HEAD/OPTIONS)必须带 `X-CSRF-Token` 头或表单字段 + * `_csrf`,且与会话里的 token **逐字节相同**,否则 403; + * - token 是按会话的,注销/换会话后旧 token 失效; + * - 安全方法只负责"确保 token 存在并下发 Cookie"。 + * + * ## 不做 + * + * - 密码哈希、登录失败限流、审计事件:需要选型/业务模型,留 #70 后续; + * - 不做基于路径前缀的通配豁免(`skip_paths` 是精确匹配,避免 `/admin` + * 豁免时把 `/admin/../secret` 这类归一化绕过也放进来)。 + */ + +#pragma once +#ifndef SRC_WEBAPP_UVCPP_WEB_AUTH_H +#define SRC_WEBAPP_UVCPP_WEB_AUTH_H + +#include +#include + +#if UVCPP_WEBAPP_ENABLE + +#include +#include + +#include + +namespace uvcpp { + +class uvcpp_session; +class uvcpp_web_request; +class uvcpp_web_response; + +// --------------------------------------------------------------------------- +// RBAC +// --------------------------------------------------------------------------- + +/// 会话里角色列表的键名(默认 `roles`)。 +struct UVCPP_API uvcpp_roles_options { + uvcpp_roles_options(); + std::string session_key; + std::vector skip_paths; +}; + +/// 写入角色(覆盖)。空列表 = 清空角色。 +UVCPP_API void uvcpp_session_set_roles( + uvcpp_session& s, const std::vector& roles, + const uvcpp_roles_options& opts = uvcpp_roles_options()); + +/// 会话里是否有该角色。 +UVCPP_API bool uvcpp_session_has_role( + const uvcpp_session& s, const std::string& role, + const uvcpp_roles_options& opts = uvcpp_roles_options()); + +/** + * @brief 任一角色命中才放行。见文件头。 + * + * 必须在会话中间件**之后**注册。 + */ +UVCPP_API uvcpp_web_middleware uvcpp_require_roles( + const std::vector& roles, + const uvcpp_roles_options& opts = uvcpp_roles_options()); + +// --------------------------------------------------------------------------- +// CSRF +// --------------------------------------------------------------------------- + +struct UVCPP_API uvcpp_csrf_options { + uvcpp_csrf_options(); + std::string token_key; ///< 会话里的键(默认 `csrf`) + std::string cookie_name; ///< 默认 `csrf`(**非** HttpOnly) + std::string header_name; ///< 默认 `x-csrf-token` + std::string form_field; ///< 默认 `_csrf` + std::string same_site; ///< 默认 `Strict` + bool cookie_secure; ///< HTTPS 部署置 true +}; + +/** + * @brief 防 CSRF 中间件。必须在会话中间件之后。 + */ +UVCPP_API uvcpp_web_middleware uvcpp_csrf_protect( + const uvcpp_csrf_options& opts = uvcpp_csrf_options()); + +/// 本请求会话的 CSRF token;没有会话/未生成时返回 nullptr。 +UVCPP_API const std::string* uvcpp_csrf_token( + uvcpp_web_request& req, const uvcpp_csrf_options& opts = uvcpp_csrf_options()); + +} // namespace uvcpp + +#endif // UVCPP_WEBAPP_ENABLE +#endif // SRC_WEBAPP_UVCPP_WEB_AUTH_H diff --git a/tests/functional/web_app_auth_func.cpp b/tests/functional/web_app_auth_func.cpp new file mode 100644 index 00000000..88e9bfcf --- /dev/null +++ b/tests/functional/web_app_auth_func.cpp @@ -0,0 +1,266 @@ +/** + * @file tests/functional/web_app_auth_func.cpp + * @brief RBAC + CSRF(issue #70 第二批)。 + * + * 判据: + * 1. 无角色访问受保护路由 → 401;有角色但不匹配 → 403; + * 2. 登录(handler 写角色)后放行; + * 3. CSRF:不安全方法缺 token → 403;`X-CSRF-Token` 或表单 `_csrf` 正确 → 放行; + * 4. CSRF Cookie **非 HttpOnly**(前端可读)、与会话 token 一致; + * 5. 同一 token 换会话(注销后)不再有效(隐式由会话绑定保证)。 + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#if UVCPP_WEBAPP_ENABLE + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace uvcpp; + +namespace { + +int g_fail = 0; + +void check(bool ok, const std::string& what) { + if (ok) { + std::cout << " [ ok ] " << what << std::endl; + } else { + ++g_fail; + std::cerr << " [FAIL] " << what << std::endl; + } +} + +struct reply { + int status = 0; + std::string body; + std::vector cookies; + + std::string cookie(const std::string& name) const { + const std::string key = name + "="; + for (size_t i = 0; i < cookies.size(); ++i) { + if (cookies[i].compare(0, key.size(), key) == 0) { + const size_t b = key.size(); + size_t e = cookies[i].find(';', b); + if (e == std::string::npos) e = cookies[i].size(); + return cookies[i].substr(b, e - b); + } + } + return std::string(); + } + bool cookie_has(const std::string& name, const std::string& needle) const { + for (size_t i = 0; i < cookies.size(); ++i) { + if (cookies[i].compare(0, name.size() + 1, name + "=") == 0 && + cookies[i].find(needle) != std::string::npos) { + return true; + } + } + return false; + } +}; + +reply call(int port, const std::string& path, bool post, + const std::string& sid = std::string(), + const std::string& csrf = std::string(), + const std::string& form_body = std::string()) { + uvcpp_http_client c; + reply out; + if (c.connect_wait("127.0.0.1", port, 3000) != 0) return out; + uvcpp_http_request req = + post ? uvcpp_http_request::make_post( + path, form_body.data(), form_body.size(), + "application/x-www-form-urlencoded") + : uvcpp_http_request::make_get(path); + std::string cookie; + if (!sid.empty()) cookie += "sid=" + sid; + if (!cookie.empty()) req.set_header("cookie", cookie); + if (!csrf.empty()) req.set_header("x-csrf-token", csrf); + uvcpp_http_response resp; + if (c.send_wait(req, resp, 3000) != 0) return out; + out.status = static_cast(resp.status_code); + out.body = resp.body.to_string(); + for (size_t i = 0; i < resp.headers.size(); ++i) { + std::string k = resp.headers[i].name; + for (size_t j = 0; j < k.size(); ++j) { + k[j] = static_cast(std::tolower(static_cast(k[j]))); + } + if (k == "set-cookie") out.cookies.push_back(resp.headers[i].value); + } + return out; +} + +struct TestApp { + std::shared_ptr store = + std::make_shared(); + uvcpp_session_options session_opts; + uvcpp_roles_options roles_opts; + uvcpp_web_app app; + + explicit TestApp(const std::vector& required = + std::vector{"admin"}) { + roles_opts.skip_paths.push_back("/login"); + roles_opts.skip_paths.push_back("/me"); + + app.set_host("127.0.0.1") + .set_port(0) + .set_access_log(false) + .set_log_level(log_level::WARN); + app.use(uvcpp_session_middleware(store, session_opts)); + app.use(uvcpp_csrf_protect()); + app.use(uvcpp_require_roles(required, roles_opts)); + + app.get("/me", [](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next) { + uvcpp_session* s = uvcpp_session_of(req); + resp.text("roles=" + (s ? s->get(roles_string()) : std::string())); + resp.end(); + }); + // 小工具:避免在 lambda 里构造 options 的副本。 + app.post("/login", + [](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next) { + uvcpp_session* s = uvcpp_session_of(req); + if (s != nullptr) { + uvcpp_session_set_roles(*s, std::vector{"admin"}); + } + resp.text(std::string("ok")); + resp.end(); + }); + app.get("/admin", [](uvcpp_web_request&, uvcpp_web_response& resp, + uvcpp_web_next) { + resp.text(std::string("admin")); + resp.end(); + }); + app.post("/admin", [](uvcpp_web_request&, uvcpp_web_response& resp, + uvcpp_web_next) { + resp.text(std::string("admin-post")); + resp.end(); + }); + app.get("/user", [](uvcpp_web_request&, uvcpp_web_response& resp, + uvcpp_web_next) { + resp.text(std::string("user")); + resp.end(); + }); + } + + static std::string roles_string() { return std::string("roles"); } + + int start() { + if (app.start_background() != 0) return -1; + return app.bound_port(); + } + void shutdown() { + app.stop(); + app.join(); + } +}; + +void test_roles_and_csrf() { + std::cout << "-- RBAC / CSRF --" << std::endl; + TestApp t; + // /user 需要 user 角色:单独注册一条只要求 user 的中间件会污染全链, + // 这里用相同的全局 admin 规则验证"不匹配 → 403"(admin 用户访问 /user 也 403)。 + const int port = t.start(); + check(port > 0, "app 起来了"); + if (port <= 0) { + t.shutdown(); + return; + } + + const reply first = call(port, "/me", false); + check(first.status == 200, "GET /me 200(roles 中间件放行)"); + const std::string sid = first.cookie("sid"); + const std::string csrf = first.cookie("csrf"); + check(!sid.empty(), "拿到 sid"); + check(!csrf.empty(), "拿到 csrf token"); + check(first.cookie_has("csrf", "HttpOnly") == false, + "CSRF Cookie 不是 HttpOnly(JS 要读)"); + check(first.cookie_has("csrf", "SameSite=Strict"), "CSRF Cookie SameSite=Strict"); + + check(call(port, "/admin", false, sid).status == 401, + "无角色访问 /admin → 401"); + + check(call(port, "/login", true, sid, "").status == 403, + "POST /login 缺 CSRF token → 403"); + check(call(port, "/login", true, sid, csrf).status == 200, + "带 X-CSRF-Token 登录成功"); + check(call(port, "/admin", false, sid).status == 200 && + call(port, "/admin", false, sid).body == "admin", + "admin 角色访问 /admin 200"); + check(call(port, "/user", false, sid).status == 200, + "admin 命中本中间件 → /user 也放行(OR 语义)"); + + // 表单字段路径 + const std::string form = "_csrf=" + csrf; + check(call(port, "/login", true, sid, "", form).status == 200, + "表单 _csrf 字段同样通过"); + + // 不安全的 POST /admin 也必须带 token + check(call(port, "/admin", true, sid, "").status == 403, + "POST /admin 缺 token → 403"); + check(call(port, "/admin", true, sid, csrf).status == 200 && + call(port, "/admin", true, sid, csrf).body == "admin-post", + "POST /admin 带 token → 200"); + + t.shutdown(); +} + +void test_role_mismatch() { + std::cout << "-- 角色不匹配 → 403 --" << std::endl; + TestApp t(std::vector{"user"}); + const int port = t.start(); + if (port <= 0) { + check(false, "app 起来了"); + t.shutdown(); + return; + } + const reply first = call(port, "/me", false); + const std::string sid = first.cookie("sid"); + const std::string csrf = first.cookie("csrf"); + check(call(port, "/login", true, sid, csrf).status == 200, + "登录(只拿到 admin 角色)"); + check(call(port, "/admin", false, sid).status == 403, + "只有 admin、要求 user → 403"); + t.shutdown(); +} + +} // namespace + +int main() { + std::cout << "[web_app_auth] start" << std::endl; + test_roles_and_csrf(); + test_role_mismatch(); + if (g_fail == 0) { + std::cout << "[web_app_auth] ALL PASS" << std::endl; + return 0; + } + std::cerr << "[web_app_auth] " << g_fail << " check(s) failed" << std::endl; + return 1; +} + +#else // !WEBAPP + +int main() { + std::cout << "SKIP: webapp disabled" << std::endl; + return 0; +} + +#endif