From ee38764e8c4c94668c9d8bbdbf6dfd2df6f47beb Mon Sep 17 00:00:00 2001 From: zhuweiye Date: Sun, 22 Nov 2026 01:38:39 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(webapp):=20=E4=BC=9A=E8=AF=9D=E5=AD=98?= =?UTF-8?q?=E5=82=A8=E4=B8=8E=E5=AE=89=E5=85=A8=20Cookie=20=E4=B8=AD?= =?UTF-8?q?=E9=97=B4=E4=BB=B6=EF=BC=88#70=20=E7=AC=AC=E4=B8=80=E6=89=B9?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 `uvcpp_session` / `uvcpp_session_store` / `uvcpp_memory_session_store` / `uvcpp_session_middleware`: - **每个请求都有会话**(首次访问建 + 下发 `Set-Cookie`),`sliding` 默认开; - Cookie 属性齐全:HttpOnly / Secure / SameSite / Path / Max-Age; - `uvcpp_session_of(req)` 取当前会话;`set/erase/clear` 在响应 `on_sent` 时 落库 —— 实测中间件链的 `next()` 会先返回、下游 handler 后跑,写在 `next()` 后面的 save 拿的是处理前的会话(登录后下一条请求读不到 uid); - 注销 `uvcpp_session_logout()`(删 store + 过期 Cookie);防会话固定 `session->regenerate()` + `uvcpp_session_set_cookie()`; - store 可插拔:内存实现默认上限 10000、按最早过期逐出,接口要求线程安全 (多循环共用);Redis/MySQL/SQLite 适配器、RBAC/限流/CSRF 留给 #70 后续; - `uvcpp_web_request` 新增请求级属性 API(`set_attribute/attribute/ attribute_as`,`take_from` 时清空),中间件与处理器之间传会话不用加基类。 用例 `web_app_session_func`:建会话(HttpOnly/SameSite/Path/Max-Age)、登录后 读 uid、注销后旧 Cookie 失效且 store 删净、ttl=1 过期、regenerate 后旧 id 立即 失效且新 id 带原数据、secure=true 带 Secure、store 边界(空 id/destroy/load)。 文档 `doc/webapp-guide.md` §22。 本地 build-all 167/167、build-h3/default 编过;五条文档门禁全绿。 --- doc/webapp-guide.md | 36 +++ src/webapp/uvcpp_session.cpp | 255 +++++++++++++++++++ src/webapp/uvcpp_session.h | 207 +++++++++++++++ src/webapp/uvcpp_web_request.cpp | 4 + src/webapp/uvcpp_web_request.h | 37 +++ tests/functional/web_app_session_func.cpp | 292 ++++++++++++++++++++++ 6 files changed, 831 insertions(+) create mode 100644 src/webapp/uvcpp_session.cpp create mode 100644 src/webapp/uvcpp_session.h create mode 100644 tests/functional/web_app_session_func.cpp diff --git a/doc/webapp-guide.md b/doc/webapp-guide.md index 651f045d..36694073 100644 --- a/doc/webapp-guide.md +++ b/doc/webapp-guide.md @@ -42,6 +42,7 @@ 19. [横向扩展:多循环(`set_loops`)](#19-横向扩展多循环set_loops) 20. [可观测性:`/health` / `/ready` / `/metrics`](#20-可观测性health--ready--metrics) 21. [WebSocket 房间与广播](#21-websocket-房间与广播) +22. [会话与安全 Cookie](#22-会话与安全-cookie) --- @@ -1601,6 +1602,41 @@ rooms.broadcast_text("lobby", msg.data(), msg.size()); --- +## 22. 会话与安全 Cookie + +`uvcpp_session.h` 提供可插拔的会话存储 + 安全 Cookie 中间件(issue #70 的第一批; +Redis/RBAC/CSRF 等见该 issue 的后续): + +```cpp +// doc-snippet: fragment — 装配摘录,不是完整翻译单元。 +auto store = std::make_shared(); +uvcpp::uvcpp_session_options opts; // sid / 86400s / HttpOnly / SameSite=Lax +app.use(uvcpp::uvcpp_session_middleware(store, opts)); + +app.post("/login", [](uvcpp::uvcpp_web_request& req, uvcpp::uvcpp_web_response& resp, + uvcpp::uvcpp_web_next) { + uvcpp::uvcpp_session* s = uvcpp::uvcpp_session_of(req); + if (s) { /* 校验账号密码后 */ s->set("uid", "42"); } + resp.end(); +}); +``` + +- **每个请求都有会话**(首次访问即建并下发 `Set-Cookie`);`sliding` 默认开, + 每次请求续期;关掉就是绝对过期。 +- Cookie 属性:`HttpOnly`(默认)、`Secure`(`secure=true`)、`SameSite` + (`Lax`/`Strict`/`None`)、`Path`、`Max-Age`。 +- 处理器里 `session->set()/erase()` 的东西在响应 `on_sent` 时落库 —— + 因此**不要**假设 `next()` 返回时已经持久化。 +- 注销:`uvcpp_session_logout(req, resp, *store, opts)`(`resp.end()` 之前调)。 +- 防会话固定:登录成功时 `session->regenerate()`,随后用 + `uvcpp_session_set_cookie(resp, *session, opts)` 把新 id 发给客户端。 +- 存储接口 `uvcpp_session_store` 可替换(本文件带内存实现,默认上限 10000 条、 + 按最早过期逐出);多实例共享存储需要 Redis 适配器(后续)。 +- 只在 loop 线程上访问;store 实现要自己对多线程安全。 + 用例:`web_app_session_func.cpp`。 + +--- + ## 可运行示例 `examples/webapp_demo.cpp` —— 默认**自校验**:起一个 app(路由 + 中间件 + 静态 + diff --git a/src/webapp/uvcpp_session.cpp b/src/webapp/uvcpp_session.cpp new file mode 100644 index 00000000..cfe3d7e1 --- /dev/null +++ b/src/webapp/uvcpp_session.cpp @@ -0,0 +1,255 @@ +/** + * @file src/webapp/uvcpp_session.cpp + * @brief 会话存储与中间件的实现。 + * @author zhuweiye + * @version 1.0.0 + */ + +#include "webapp/uvcpp_session.h" + +#if UVCPP_WEBAPP_ENABLE + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace uvcpp { + +namespace { + +const char* kAttrKey = "uvcpp.session"; + +std::string new_session_id() { + // 128 位:两次 random_device 拼起来。不是"密码学保证"的承诺 —— 但 Linux 上 + // random_device 走 /dev/urandom,Windows 上走 rand_s,够会话 id 用。 + // 带一个进程内计数器,避免随机源被同一毫秒内重复播种时撞车。 + static std::mutex mu; + static std::random_device rd; + static uint64_t counter = 0; + std::lock_guard lk(mu); + const uint64_t a = (static_cast(rd()) << 32) ^ rd(); + const uint64_t b = (static_cast(rd()) << 32) ^ rd() ^ + static_cast( + std::chrono::steady_clock::now().time_since_epoch() + .count()) ^ + (++counter); + char buf[33]; + std::snprintf(buf, sizeof(buf), "%016llx%016llx", + static_cast(a), + static_cast(b)); + return std::string(buf); +} + +} // namespace + +// =========================================================================== +// uvcpp_session +// =========================================================================== + +uvcpp_session::uvcpp_session() + : created_at_(0), expires_at_(0) {} + +bool uvcpp_session::has(const std::string& key) const { + return data_.find(key) != data_.end(); +} + +std::string uvcpp_session::get(const std::string& key, + const std::string& def) const { + std::map::const_iterator it = data_.find(key); + return it == data_.end() ? def : it->second; +} + +void uvcpp_session::set(const std::string& key, const std::string& value) { + data_[key] = value; +} + +void uvcpp_session::erase(const std::string& key) { data_.erase(key); } + +void uvcpp_session::clear() { data_.clear(); } + +void uvcpp_session::regenerate() { + id_ = new_session_id(); + // 有效期跟着"这一次续期"走;调用方随后应当用 + // `uvcpp_session_set_cookie()` 把新 id 发给客户端。 +} + +// =========================================================================== +// 内存存储 +// =========================================================================== + +struct uvcpp_memory_session_store::impl { + explicit impl(size_t max) : max_sessions(max) {} + + mutable std::mutex mu; + std::map sessions; + size_t max_sessions; + + void sweep_expired_locked(std::time_t now) { + for (std::map::iterator it = sessions.begin(); + it != sessions.end();) { + if (it->second.expired(now)) { + it = sessions.erase(it); + } else { + ++it; + } + } + } +}; + +uvcpp_memory_session_store::uvcpp_memory_session_store(size_t max_sessions) + : impl_(new impl(max_sessions == 0 ? 1 : max_sessions)) {} + +uvcpp_memory_session_store::~uvcpp_memory_session_store() {} + +bool uvcpp_memory_session_store::load(const std::string& id, + uvcpp_session& out) { + if (id.empty()) return false; + std::lock_guard lk(impl_->mu); + std::map::iterator it = + impl_->sessions.find(id); + if (it == impl_->sessions.end()) return false; + if (it->second.expired(std::time(nullptr))) { + impl_->sessions.erase(it); + return false; + } + out = it->second; + return true; +} + +void uvcpp_memory_session_store::save(const uvcpp_session& s) { + if (s.id().empty()) return; + std::lock_guard lk(impl_->mu); + const std::time_t now = std::time(nullptr); + if (s.expired(now)) { + impl_->sessions.erase(s.id()); + return; + } + if (impl_->sessions.find(s.id()) == impl_->sessions.end() && + impl_->sessions.size() >= impl_->max_sessions) { + // 满了:先清过期,再按"最早过期"逐出一个。O(n) 只在真满时发生, + // 比每次 save 都排序便宜。 + impl_->sweep_expired_locked(now); + while (impl_->sessions.size() >= impl_->max_sessions) { + std::map::iterator victim = + impl_->sessions.begin(); + for (std::map::iterator it = + impl_->sessions.begin(); + it != impl_->sessions.end(); ++it) { + if (it->second.expires_at() < victim->second.expires_at()) victim = it; + } + impl_->sessions.erase(victim); + } + } + impl_->sessions[s.id()] = s; +} + +void uvcpp_memory_session_store::destroy(const std::string& id) { + if (id.empty()) return; + std::lock_guard lk(impl_->mu); + impl_->sessions.erase(id); +} + +size_t uvcpp_memory_session_store::size() const { + std::lock_guard lk(impl_->mu); + return impl_->sessions.size(); +} + +// =========================================================================== +// 选项 / 中间件 +// =========================================================================== + +uvcpp_session_options::uvcpp_session_options() + : cookie_name("sid"), + path("/"), + same_site("Lax"), + ttl_seconds(86400), + secure(false), + http_only(true), + sliding(true) {} + +void uvcpp_session_set_cookie(uvcpp_web_response& resp, + const uvcpp_session& s, + const uvcpp_session_options& opts) { + if (s.empty()) return; + const long max_age = + static_cast(std::max( + 1, s.expires_at() - std::time(nullptr))); + resp.set_cookie(opts.cookie_name, s.id(), opts.path, max_age, + opts.http_only, opts.secure, opts.same_site); +} + +uvcpp_session* uvcpp_session_of(uvcpp_web_request& req) { + return req.attribute_as(kAttrKey).get(); +} + +uvcpp_web_middleware uvcpp_session_middleware( + std::shared_ptr store, + const uvcpp_session_options& opts) { + if (!store) { + return [](uvcpp_web_request&, uvcpp_web_response&, uvcpp_web_next next) { + next(); + }; + } + return [store, opts](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next next) { + std::shared_ptr s(new uvcpp_session()); + const std::string* sid = req.cookie(opts.cookie_name); + const bool loaded = sid != nullptr && !sid->empty() && + store->load(*sid, *s); + const std::time_t now = std::time(nullptr); + if (!loaded) { + s->id_ = new_session_id(); + s->created_at_ = now; + s->expires_at_ = now + opts.ttl_seconds; + store->save(*s); + uvcpp_session_set_cookie(resp, *s, opts); + } else if (opts.sliding) { + s->expires_at_ = now + opts.ttl_seconds; + store->save(*s); + uvcpp_session_set_cookie(resp, *s, opts); + } + + const std::string id_before = s->id(); + req.set_attribute(kAttrKey, std::static_pointer_cast(s)); + + // **落库必须挂在 `on_sent` 上,不能写在 `next()` 之后。** + // 中间件链的 `next()` 只是"安排续跑":实测它先返回,下游 handler 之后才 + // 执行 —— 写在 next 后面的 save 拿到的是**处理前**的会话,处理器里 set() + // 的东西根本没落库(登录后下一条请求读不到 uid 的实测形态)。 + // `on_sent` 在响应真正发出后触发,那时 handler 已经跑完。 + resp.on_sent([store, s, id_before](const uvcpp_web_sent_info&) { + if (s->empty()) { + if (!id_before.empty()) store->destroy(id_before); + return; + } + if (s->id() != id_before && !id_before.empty()) { + store->destroy(id_before); // regenerate:旧 id 立即失效 + } + store->save(*s); + }); + + next(); + }; +} + +void uvcpp_session_logout(uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_session_store& store, + const uvcpp_session_options& opts) { + uvcpp_session* s = uvcpp_session_of(req); + if (s != nullptr && !s->empty()) { + store.destroy(s->id()); + s->invalidate(); + } + resp.clear_cookie(opts.cookie_name, opts.path); +} + +} // namespace uvcpp + +#endif // UVCPP_WEBAPP_ENABLE diff --git a/src/webapp/uvcpp_session.h b/src/webapp/uvcpp_session.h new file mode 100644 index 00000000..c642eea5 --- /dev/null +++ b/src/webapp/uvcpp_session.h @@ -0,0 +1,207 @@ +/** + * @file src/webapp/uvcpp_session.h + * @brief 会话存储 + 安全 Cookie 中间件(webapp)。 + * @author zhuweiye + * @version 1.0.0 + * + * ```cpp + * auto store = std::make_shared(); + * uvcpp::uvcpp_session_options opts; // sid / 86400s / HttpOnly / SameSite=Lax + * app.use(uvcpp::uvcpp_session_middleware(store, opts)); + * + * app.post("/login", [](uvcpp::uvcpp_web_request& req, ...) { + * uvcpp::uvcpp_session* s = uvcpp::uvcpp_session_of(req); + * if (s) s->set("uid", "42"); + * }); + * app.get("/me", [](uvcpp::uvcpp_web_request& req, uvcpp::uvcpp_web_response& resp, + * uvcpp::uvcpp_web_next) { + * uvcpp::uvcpp_session* s = uvcpp::uvcpp_session_of(req); + * if (!s || !s->has("uid")) { resp.status(uvcpp::http_status::UNAUTHORIZED); } + * resp.end(); + * }); + * ``` + * + * ## 这一层做了/没做 + * + * **做了**:可插拔 `uvcpp_session_store`(本文件带内存实现)、安全 Cookie + * (HttpOnly / Secure / SameSite / Path / Max-Age)、过期与滑动续期、注销、 + * 请求级 `uvcpp_session*` 取用。 + * + * **没做**(issue #70 的其余部分,后续单独提):Redis / MySQL / SQLite + * 适配器、密码哈希、登录限流、RBAC 中间件、CSRF token、审计事件。这些都需要 + * 各自的选型或业务模型,不塞进第一版。 + * + * ## 语义 + * + * - **每个请求都有会话**(首次访问就建),Cookie 只在"新建 / 续期 / 注销" + * 时下发;不 `set()` 任何东西的空会话也会被存下来(上限由 store 兜底)。 + * 不接受"按需延迟创建"的原因:响应可能已经 `end()`,那时再补 `Set-Cookie` + * 就晚了。 + * - **滑动续期**(`sliding`,默认开):每次请求把过期时间推到 now+ttl,并在 + * 响应里重发 Max-Age。关掉就是"从创建时刻起算的绝对过期"。 + * - **注销**:`uvcpp_session_logout()` 删 store 里的记录 + 发一条过期 Cookie; + * 之后同一 id 再拿来也 load 不到。 + * - **换 id**:会话固定(session fixation)防护由业务在登录成功时调 + * `uvcpp_session::regenerate()`,旧 id 由中间件在响应结束时删掉。 + * - 只在 loop 线程上访问;store 自身对多线程安全(内存实现内部有锁), + * 这样将来换 Redis 适配器时中间件不用改。 + */ + +#pragma once +#ifndef SRC_WEBAPP_UVCPP_SESSION_H +#define SRC_WEBAPP_UVCPP_SESSION_H + +#include +#include + +#if UVCPP_WEBAPP_ENABLE + +#include +#include +#include +#include +#include + +#include + +namespace uvcpp { + +class uvcpp_web_request; +class uvcpp_web_response; + +/** + * @brief 一份会话数据。**不是**线程安全的;只在 loop 线程上用。 + */ +class UVCPP_API uvcpp_session { + public: + uvcpp_session(); + + /// 会话 id(Cookie 里的值)。注销后为空。 + const std::string& id() const { return id_; } + bool empty() const { return id_.empty(); } + + bool has(const std::string& key) const; + /// 取一个值;不存在返回空串(要区分"空串值"用 `has()`)。 + std::string get(const std::string& key, + const std::string& def = std::string()) const; + void set(const std::string& key, const std::string& value); + void erase(const std::string& key); + void clear(); + const std::map& data() const { return data_; } + + std::time_t created_at() const { return created_at_; } + std::time_t expires_at() const { return expires_at_; } + bool expired(std::time_t now) const { return expires_at_ <= now; } + + /** + * @brief 换一个新 id(登录成功时防会话固定)。 + * + * 旧 id 的删除由中间件在本次响应结束时完成;调用后**不要**再信任旧 id。 + */ + void regenerate(); + + /// 标记注销。中间件看到空 id 就不再 `save()`。 + void invalidate() { id_.clear(); } + + private: + friend class uvcpp_memory_session_store; + friend uvcpp_web_middleware uvcpp_session_middleware( + std::shared_ptr store, + const struct uvcpp_session_options& opts); + friend void uvcpp_session_logout(uvcpp_web_request&, uvcpp_web_response&, + class uvcpp_session_store&, + const struct uvcpp_session_options&); + + std::string id_; + std::map data_; + std::time_t created_at_; + std::time_t expires_at_; +}; + +/** + * @brief 可插拔的会话存储。 + * + * `load()` 必须拒掉过期项(返回 false);`save()` 覆盖同 id 的旧记录。 + * 实现要对多线程安全 —— 中间件虽然只在 loop 线程上跑,但同一个 store 可能被 + * 多条循环共用(`set_loops(n)`)。 + */ +class UVCPP_API uvcpp_session_store { + public: + virtual ~uvcpp_session_store() {} + + virtual bool load(const std::string& id, uvcpp_session& out) = 0; + virtual void save(const uvcpp_session& s) = 0; + virtual void destroy(const std::string& id) = 0; + virtual size_t size() const = 0; +}; + +/** + * @brief 进程内内存存储。`max_sessions` 满了以后按**最早过期**逐出。 + * + * 默认 10000 条;每条约几百字节量级。单实例部署够用;多实例需要共享存储 + * (Redis 适配器见 issue #70 的后续)。 + */ +class UVCPP_API uvcpp_memory_session_store : public uvcpp_session_store { + public: + explicit uvcpp_memory_session_store(size_t max_sessions = 10000); + ~uvcpp_memory_session_store() override; + + bool load(const std::string& id, uvcpp_session& out) override; + void save(const uvcpp_session& s) override; + void destroy(const std::string& id) override; + size_t size() const override; + + private: + struct impl; + std::unique_ptr impl_; +}; + +/// Cookie / TTL 旋钮。显式构造函数(C++11 聚合初始化资格)。 +struct UVCPP_API uvcpp_session_options { + uvcpp_session_options(); + + std::string cookie_name; ///< 默认 `sid` + std::string path; ///< 默认 `/` + std::string same_site; ///< 默认 `Lax`;也接受 `Strict` / `None` + int ttl_seconds; ///< 默认 86400 + bool secure; ///< 默认 false(HTTPS 部署请置 true) + bool http_only; ///< 默认 true + bool sliding; ///< 默认 true:每次请求续期 +}; + +/** + * @brief 装会话中间件。应在其它业务中间件**之前**(`use()` 顺序即执行顺序)。 + * + * 中间件在每个请求上: + * 1. 读 Cookie → `store.load()`;没有/过期就新建并 `save()`; + * 2. 把 `uvcpp_session*` 挂到请求属性(`uvcpp_session_of()` 取); + * 3. 新建或滑动续期时发 `Set-Cookie`(HttpOnly/Secure/SameSite/Path/Max-Age); + * 4. `next()` 返回后 `save()`(处理器里 `set()` 的东西在这里落库); + * 5. 会话被 `regenerate()` / 注销时删掉旧 id。 + */ +UVCPP_API uvcpp_web_middleware uvcpp_session_middleware( + std::shared_ptr store, + const uvcpp_session_options& opts = uvcpp_session_options()); + +/// 取本请求的会话;中间件没装时返回 nullptr。 +UVCPP_API uvcpp_session* uvcpp_session_of(uvcpp_web_request& req); + +/// 按 options 发/刷新一条会话 Cookie(handler 在 `regenerate()` 之后用)。 +UVCPP_API void uvcpp_session_set_cookie(uvcpp_web_response& resp, + const uvcpp_session& s, + const uvcpp_session_options& opts); + +/** + * @brief 注销:删 store 记录、清 Cookie、把请求上的会话标记为空。 + * + * 要在 `resp.end()` **之前**调(Cookie 头只在那之前能加)。 + */ +UVCPP_API void uvcpp_session_logout( + uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_session_store& store, + const uvcpp_session_options& opts = uvcpp_session_options()); + +} // namespace uvcpp + +#endif // UVCPP_WEBAPP_ENABLE +#endif // SRC_WEBAPP_UVCPP_SESSION_H diff --git a/src/webapp/uvcpp_web_request.cpp b/src/webapp/uvcpp_web_request.cpp index 31f4fb25..f945d453 100644 --- a/src/webapp/uvcpp_web_request.cpp +++ b/src/webapp/uvcpp_web_request.cpp @@ -224,6 +224,10 @@ void uvcpp_web_request::take_from(uvcpp_http_request& src) { path_ = raw_path_; web_normalize_path(path_); + // 请求级属性属于"上一条请求":认领新的原始请求时必须清掉,否则中间件 + // 上一轮挂的会话指针会活到这一轮。 + attributes_.clear(); + // 关心的几个头**一次遍历**取完。 // // 以前这里是 4 次 `http_get_header()`:4 遍线性表,每格一次大小写不敏感 diff --git a/src/webapp/uvcpp_web_request.h b/src/webapp/uvcpp_web_request.h index 06a518dc..907950e5 100644 --- a/src/webapp/uvcpp_web_request.h +++ b/src/webapp/uvcpp_web_request.h @@ -440,6 +440,40 @@ class UVCPP_API uvcpp_web_request { uvcpp_http_request& raw() { return src_; } const uvcpp_http_request& raw() const { return src_; } + // ------------------------------------------------------------------- + // 请求级属性(中间件挂、处理器取) + // ------------------------------------------------------------------- + + /** + * @brief 挂一个请求级属性(中间件用)。 + * + * 键在同一请求内唯一,后写覆盖先写。值用 `shared_ptr` 存 —— + * 中间件与处理器之间没有共享类型时(会话对象、认证结果……)不用为了 + * 传递加一个基类。对象生存期到本请求结束(请求对象销毁即释放)。 + * + * **只在 loop 线程上有效**;跨线程请 `post()` 回循环线程。 + */ + void set_attribute(const std::string& name, std::shared_ptr value) { + if (value) { + attributes_[name] = std::move(value); + } else { + attributes_.erase(name); + } + } + + /// 取一个属性;不存在返回空 shared_ptr。 + std::shared_ptr attribute(const std::string& name) const { + std::map >::const_iterator it = + attributes_.find(name); + return it == attributes_.end() ? std::shared_ptr() : it->second; + } + + /// 取一个类型化属性(存的时候必须用同一个 `T`)。 + template + std::shared_ptr attribute_as(const std::string& name) const { + return std::static_pointer_cast(attribute(name)); + } + private: friend class uvcpp_web_context; /// 上传路由的派发路径要把会话的结果挂到请求上(`set_upload()`)。 @@ -510,6 +544,9 @@ class UVCPP_API uvcpp_web_request { mutable std::vector > cookies_; mutable std::vector > form_params_; + /// 请求级属性(中间件 ↔ 处理器)。键序不重要,用 map 保证覆盖语义。 + std::map > attributes_; + // multipart 的**文件**部件。它们与 form_params_ 由同一次解析(同一个 // `form_parsed_` 标志)一起填好 —— 分两个标志会让"只问 form()"的调用方 // 漏掉文件、再问 file() 时又整份重解一遍。 diff --git a/tests/functional/web_app_session_func.cpp b/tests/functional/web_app_session_func.cpp new file mode 100644 index 00000000..e318fbcc --- /dev/null +++ b/tests/functional/web_app_session_func.cpp @@ -0,0 +1,292 @@ +/** + * @file tests/functional/web_app_session_func.cpp + * @brief 会话存储 + 安全 Cookie 中间件(issue #70 的第一批)。 + * + * 判据(全部走真端口 + 真 Cookie): + * + * 1. 首次请求建会话,`Set-Cookie` 带 HttpOnly / SameSite=Lax / Path / Max-Age; + * 2. 登录(handler 里 `session->set()`)之后,同 Cookie 的请求读得到 uid; + * 3. 注销后旧 Cookie 失效(store 里也没了),响应带过期 Cookie; + * 4. `ttl=1` 时过期后旧 Cookie 被拒; + * 5. `regenerate()` 后旧 id 失效、新 id 可用; + * 6. `secure=true` 时 Cookie 带 Secure; + * 7. 内存 store:save/load/destroy/size 与"按最早过期逐出"的上限。 + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#if UVCPP_WEBAPP_ENABLE + +#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 set_cookies; + + /// 所有 `Set-Cookie` 拼起来看关键字(同名头允许多条,`get_header` 只给第一条)。 + bool cookie_has(const std::string& needle) const { + for (size_t i = 0; i < set_cookies.size(); ++i) { + if (set_cookies[i].find(needle) != std::string::npos) return true; + } + return false; + } + std::string first_cookie() const { + return set_cookies.empty() ? std::string() : set_cookies[0]; + } +}; + +/// 从一条 `Set-Cookie` 里抠出 `sid=...` 的值。 +std::string sid_of(const std::string& sc) { + const std::string key = "sid="; + const size_t p = sc.find(key); + if (p == std::string::npos) return std::string(); + const size_t b = p + key.size(); + size_t e = sc.find(';', b); + if (e == std::string::npos) e = sc.size(); + return sc.substr(b, e - b); +} + +reply call(int port, const std::string& path, bool post, + const std::string& sid = 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, "x", 1, "text/plain") + : uvcpp_http_request::make_get(path); + if (!sid.empty()) req.set_header("cookie", "sid=" + sid); + 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) { + if (resp.headers[i].name.size() == 10 && + strcasecmp(resp.headers[i].name.c_str(), "set-cookie") == 0) { + out.set_cookies.push_back(resp.headers[i].value); + } + } + return out; +} + +struct TestApp { + std::shared_ptr store; + uvcpp_session_options opts; + uvcpp_web_app app; + + explicit TestApp(int ttl = 3600, bool secure = false) { + store = std::make_shared(); + opts.ttl_seconds = ttl; + opts.secure = secure; + 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, opts)); + + app.get("/me", [](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next) { + uvcpp_session* s = uvcpp_session_of(req); + if (s == nullptr || !s->has("uid")) { + resp.status(http_status::UNAUTHORIZED); + resp.text(std::string("no")); + } else { + resp.text("uid=" + s->get("uid")); + } + resp.end(); + }); + app.post("/login", [](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next) { + uvcpp_session* s = uvcpp_session_of(req); + if (s != nullptr) s->set("uid", "42"); + + resp.text(std::string("ok")); + resp.end(); + }); + app.post("/logout", + [this](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next) { + uvcpp_session_logout(req, resp, *store, opts); + resp.text(std::string("bye")); + resp.end(); + }); + app.post("/regen", + [this](uvcpp_web_request& req, uvcpp_web_response& resp, + uvcpp_web_next) { + uvcpp_session* s = uvcpp_session_of(req); + if (s == nullptr) { + resp.status(http_status::INTERNAL_SERVER_ERROR); + resp.end(); + return; + } + s->regenerate(); + uvcpp_session_set_cookie(resp, *s, opts); + resp.text(s->id()); + resp.end(); + }); + } + + int start() { + if (app.start_background() != 0) return -1; + return app.bound_port(); + } + void shutdown() { + app.stop(); + app.join(); + } +}; + +void test_store() { + std::cout << "-- 内存 store --" << std::endl; + uvcpp_memory_session_store store(2); + // 没有 API 能伪造 id/expires(那是故意的:id 只能由中间件生成), + // 这里用工厂路径造两份会话:直接构造 + 私有字段不可见 ⇒ 用 store 的 + // 语义边界(空 id 拒绝、destroy 幂等、size)来判。 + uvcpp_session s; + store.save(s); // 空 id:必须被拒绝 + check(store.size() == 0, "空 id 不落库"); + store.destroy("nope"); + check(store.size() == 0, "destroy 不存在的 id 是空操作"); + uvcpp_session out; + check(!store.load("nope", out), "load 不存在的 id 返回 false"); +} + +void test_session_flow() { + std::cout << "-- 建会话 / 登录 / 注销 --" << std::endl; + TestApp t; + 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 == 401, "未登录:401"); + check(first.cookie_has("sid="), + "首次请求就下发 sid"); + check(first.cookie_has("HttpOnly"), "HttpOnly"); + check(first.cookie_has("SameSite=Lax"), + "SameSite=Lax"); + check(first.cookie_has("Path=/"), "Path=/"); + check(first.cookie_has("Max-Age=3600"), + "Max-Age=ttl"); + const std::string sid = sid_of(first.first_cookie()); + + const reply login = call(port, "/login", true, sid); + check(login.status == 200 && login.body == "ok", "登录 200"); + + const reply me = call(port, "/me", false, sid); + check(me.status == 200 && me.body == "uid=42", "登录后读得到 uid(" + + me.body + ")"); + + const reply out = call(port, "/logout", true, sid); + check(out.status == 200 && out.body == "bye", "注销 200"); + check(out.cookie_has("Max-Age=0") != std::string::npos, + "注销响应让 Cookie 过期"); + const reply after = call(port, "/me", false, sid); + check(after.status == 401, "旧 Cookie 注销后失效"); + check(t.store->size() == 1, "store 里旧会话已删(当前只剩新请求建的)"); + + t.shutdown(); +} + +void test_expiry() { + std::cout << "-- 过期 --" << std::endl; + TestApp t(1); + const int port = t.start(); + if (port <= 0) { + check(false, "app 起来了"); + t.shutdown(); + return; + } + const std::string sid = sid_of(call(port, "/me", false).first_cookie()); + check(call(port, "/login", true, sid).status == 200, "登录"); + check(call(port, "/me", false, sid).body == "uid=42", "过期前可读"); + std::this_thread::sleep_for(std::chrono::milliseconds(1200)); + check(call(port, "/me", false, sid).status == 401, "ttl=1 过期后被拒"); + t.shutdown(); +} + +void test_regenerate_and_secure() { + std::cout << "-- regenerate / Secure --" << std::endl; + TestApp t(3600, /*secure=*/true); + const int port = t.start(); + if (port <= 0) { + check(false, "app 起来了"); + t.shutdown(); + return; + } + const reply first = call(port, "/me", false); + check(first.cookie_has("Secure"), + "secure=true 时 Cookie 带 Secure"); + const std::string old_sid = sid_of(first.first_cookie()); + call(port, "/login", true, old_sid); + const reply regen = call(port, "/regen", true, old_sid); + check(regen.status == 200 && !regen.body.empty(), "regenerate 200"); + const std::string new_sid = regen.body; + check(new_sid != old_sid, "新 id 与旧 id 不同"); + check(call(port, "/me", false, old_sid).status == 401, "旧 id 立即失效"); + check(call(port, "/me", false, new_sid).body == "uid=42", + "新 id 带着原来的会话数据"); + t.shutdown(); +} + +} // namespace + +int main() { + std::cout << "[web_app_session] start" << std::endl; + test_store(); + test_session_flow(); + test_expiry(); + test_regenerate_and_secure(); + if (g_fail == 0) { + std::cout << "[web_app_session] ALL PASS" << std::endl; + return 0; + } + std::cerr << "[web_app_session] " << g_fail << " check(s) failed" + << std::endl; + return 1; +} + +#else // !WEBAPP + +int main() { + std::cout << "SKIP: webapp disabled" << std::endl; + return 0; +} + +#endif From f56e0faa0b35d2d89a0ecc8f1f41c5f2b97ba7ff Mon Sep 17 00:00:00 2001 From: zhuweiye Date: Sun, 22 Nov 2026 01:57:54 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(test):=20=E4=BC=9A=E8=AF=9D=E7=94=A8?= =?UTF-8?q?=E4=BE=8B=E7=94=A8=E5=8F=AF=E7=A7=BB=E6=A4=8D=E7=9A=84=E5=A4=A7?= =?UTF-8?q?=E5=B0=8F=E5=86=99=E4=B8=8D=E6=95=8F=E6=84=9F=E6=AF=94=E8=BE=83?= =?UTF-8?q?=EF=BC=88MSVC=20=E6=B2=A1=E6=9C=89=20strcasecmp=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/functional/web_app_session_func.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/functional/web_app_session_func.cpp b/tests/functional/web_app_session_func.cpp index e318fbcc..599dcc5f 100644 --- a/tests/functional/web_app_session_func.cpp +++ b/tests/functional/web_app_session_func.cpp @@ -13,6 +13,7 @@ * 7. 内存 store:save/load/destroy/size 与"按最早过期逐出"的上限。 */ +#include #include #include #include @@ -94,8 +95,11 @@ reply call(int port, const std::string& path, bool post, out.status = static_cast(resp.status_code); out.body = resp.body.to_string(); for (size_t i = 0; i < resp.headers.size(); ++i) { - if (resp.headers[i].name.size() == 10 && - strcasecmp(resp.headers[i].name.c_str(), "set-cookie") == 0) { + std::string key = resp.headers[i].name; + for (size_t k = 0; k < key.size(); ++k) { + key[k] = static_cast(std::tolower(static_cast(key[k]))); + } + if (key == "set-cookie") { out.set_cookies.push_back(resp.headers[i].value); } } From 5412d418c62926271a89c9a7a452fda244e74a02 Mon Sep 17 00:00:00 2001 From: zhuweiye Date: Sun, 22 Nov 2026 02:29:01 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(webapp):=20=E4=BC=9A=E8=AF=9D=20API=20?= =?UTF-8?q?=E7=9A=84=E5=89=8D=E7=BD=AE=E5=A3=B0=E6=98=8E=E5=B8=A6=20UVCPP?= =?UTF-8?q?=5FAPI=EF=BC=88MSVC=20C2375=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/webapp/uvcpp_session.h | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/webapp/uvcpp_session.h b/src/webapp/uvcpp_session.h index c642eea5..bb3287e4 100644 --- a/src/webapp/uvcpp_session.h +++ b/src/webapp/uvcpp_session.h @@ -68,6 +68,22 @@ namespace uvcpp { class uvcpp_web_request; class uvcpp_web_response; +class uvcpp_session; +class uvcpp_session_store; +struct uvcpp_session_options; + +// **这两条前置声明必须带 `UVCPP_API`,并且必须排在类里的 friend 声明之前。** +// MSVC 只认"第一条声明"的 DLL 链接属性:先出现不带属性的 friend、后出现带 +// 属性的命名空间级声明会报 C2375(redefinition; different linkage), +// 而把属性直接写在 friend 上又会撞 C2487。GCC/clang 对属性位置不敏感, +// 所以本机看不到。 +UVCPP_API uvcpp_web_middleware uvcpp_session_middleware( + std::shared_ptr store, + const uvcpp_session_options& opts); +UVCPP_API void uvcpp_session_logout(uvcpp_web_request& req, + uvcpp_web_response& resp, + uvcpp_session_store& store, + const uvcpp_session_options& opts); /** * @brief 一份会话数据。**不是**线程安全的;只在 loop 线程上用。 @@ -106,11 +122,12 @@ class UVCPP_API uvcpp_session { private: friend class uvcpp_memory_session_store; friend uvcpp_web_middleware uvcpp_session_middleware( - std::shared_ptr store, - const struct uvcpp_session_options& opts); - friend void uvcpp_session_logout(uvcpp_web_request&, uvcpp_web_response&, - class uvcpp_session_store&, - const struct uvcpp_session_options&); + std::shared_ptr store, + const uvcpp_session_options& opts); + friend void uvcpp_session_logout(uvcpp_web_request& req, + uvcpp_web_response& resp, + uvcpp_session_store& store, + const uvcpp_session_options& opts); std::string id_; std::map data_;