Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions doc/webapp-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

---

Expand Down Expand Up @@ -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(路由 + 中间件 + 静态 +
Expand Down
213 changes: 213 additions & 0 deletions src/webapp/uvcpp_web_auth.cpp
Original file line number Diff line number Diff line change
@@ -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 <cctype>
#include <mutex>
#include <random>
#include <sstream>

#include <web/uvcpp_http_common.h>
#include <webapp/uvcpp_session.h>
#include <webapp/uvcpp_web_request.h>
#include <webapp/uvcpp_web_response.h>

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<std::mutex> lk(mu);
char buf[33];
for (int i = 0; i < 32; i += 8) {
const unsigned v = static_cast<unsigned>(rd());
for (int k = 0; k < 8; ++k) {
const unsigned nib = (v >> (k * 4)) & 0xfu;
buf[i + k] = static_cast<char>(nib < 10 ? '0' + nib : 'a' + (nib - 10));
}
}
buf[32] = '\0';
return std::string(buf);
}

std::vector<std::string> split_roles(const std::string& v) {
std::vector<std::string> 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<unsigned char>(a[i]) : 0;
const unsigned char cb = i < b.size() ? static_cast<unsigned char>(b[i]) : 0;
diff |= static_cast<unsigned>(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<std::string>& 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<std::string> 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<std::string>& 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<std::string> held =
req.attribute_as<std::string>("uvcpp.csrf.token");
if (!held || *held != token) {
held = std::make_shared<std::string>(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
122 changes: 122 additions & 0 deletions src/webapp/uvcpp_web_auth.h
Original file line number Diff line number Diff line change
@@ -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 <uvcpp/uvcpp_config.h>
#include <uvcpp/uvcpp_export.h>

#if UVCPP_WEBAPP_ENABLE

#include <string>
#include <vector>

#include <webapp/uvcpp_web_handler.h>

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<std::string> skip_paths;
};

/// 写入角色(覆盖)。空列表 = 清空角色。
UVCPP_API void uvcpp_session_set_roles(
uvcpp_session& s, const std::vector<std::string>& 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<std::string>& 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
Loading
Loading