Crow  1.1
A C++ microframework for the web
Loading...
Searching...
No Matches
session.h
1#pragma once
2
3#include "crow/http_request.h"
4#include "crow/http_response.h"
5#include "crow/json.h"
6#include "crow/utility.h"
7#include "crow/middlewares/cookie_parser.h"
8
9#include <unordered_map>
10#include <unordered_set>
11#include <set>
12#include <queue>
13
14#include <memory>
15#include <string>
16#include <cstdio>
17#include <mutex>
18
19#include <fstream>
20#include <sstream>
21
22#include <type_traits>
23#include <functional>
24#include <chrono>
25
26#include <variant>
27
28namespace
29{
30 // convert all integer values to int64_t
31 template<typename T>
32 using wrap_integral_t = typename std::conditional<
33 std::is_integral<T>::value && !std::is_same<bool, T>::value
34 // except for uint64_t because that could lead to overflow on conversion
35 && !std::is_same<uint64_t, T>::value,
36 int64_t, T>::type;
37
38 // convert char[]/char* to std::string
39 template<typename T>
40 using wrap_char_t = typename std::conditional<
41 std::is_same<typename std::decay<T>::type, char*>::value,
42 std::string, T>::type;
43
44 // Upgrade to correct type for multi_variant use
45 template<typename T>
46 using wrap_mv_t = wrap_char_t<wrap_integral_t<T>>;
47} // namespace
48
49namespace crow
50{
51 namespace session
52 {
53
54 using multi_value_types = black_magic::S<bool, int64_t, double, std::string>;
55
56 /// A multi_value is a safe variant wrapper with json conversion support
58 {
59 json::wvalue json() const
60 {
61 // clang-format off
62 return std::visit([](auto arg) {
63 return json::wvalue(arg);
64 }, v_);
65 // clang-format on
66 }
67
68 static multi_value from_json(const json::rvalue&);
69
70 std::string string() const
71 {
72 // clang-format off
73 return std::visit([](auto arg) {
74 if constexpr (std::is_same_v<decltype(arg), std::string>)
75 return arg;
76 else
77 return std::to_string(arg);
78 }, v_);
79 // clang-format on
80 }
81
82 template<typename T, typename RT = wrap_mv_t<T>>
83 RT get(const T& fallback)
84 {
85 if (const RT* val = std::get_if<RT>(&v_)) return *val;
86 return fallback;
87 }
88
89 template<typename T, typename RT = wrap_mv_t<T>>
90 void set(T val)
91 {
92 v_ = RT(std::move(val));
93 }
94
95 typename multi_value_types::rebind<std::variant> v_;
96 };
97
98 inline multi_value multi_value::from_json(const json::rvalue& rv)
99 {
100 using namespace json;
101 switch (rv.t())
102 {
103 case type::Number:
104 {
105 if (rv.nt() == num_type::Floating_point || rv.nt() == num_type::Double_precision_floating_point)
106 return multi_value{rv.d()};
107 else if (rv.nt() == num_type::Unsigned_integer)
108 return multi_value{int64_t(rv.u())};
109 else
110 return multi_value{rv.i()};
111 }
112 case type::False: return multi_value{false};
113 case type::True: return multi_value{true};
114 case type::String: return multi_value{std::string(rv)};
115 default: return multi_value{false};
116 }
117 }
118
119 /// Expiration tracker keeps track of soonest-to-expire keys
121 {
122 using DataPair = std::pair<uint64_t /*time*/, std::string /*key*/>;
123
124 /// Add key with time to tracker.
125 /// If the key is already present, it will be updated
126 void add(std::string key, uint64_t time)
127 {
128 auto it = times_.find(key);
129 if (it != times_.end()) remove(key);
130 times_[key] = time;
131 queue_.insert({time, std::move(key)});
132 }
133
134 void remove(const std::string& key)
135 {
136 auto it = times_.find(key);
137 if (it != times_.end())
138 {
139 queue_.erase({it->second, key});
140 times_.erase(it);
141 }
142 }
143
144 /// Get expiration time of soonest-to-expire entry
145 uint64_t peek_first() const
146 {
147 if (queue_.empty()) return std::numeric_limits<uint64_t>::max();
148 return queue_.begin()->first;
149 }
150
151 /// Get expiration time of key, or the maximum value if it is not tracked
152 uint64_t get(const std::string& key) const
153 {
154 auto it = times_.find(key);
155 if (it == times_.end()) return std::numeric_limits<uint64_t>::max();
156 return it->second;
157 }
158
159 std::string pop_first()
160 {
161 auto it = times_.find(queue_.begin()->second);
162 auto key = it->first;
163 times_.erase(it);
164 queue_.erase(queue_.begin());
165 return key;
166 }
167
168 using iterator = typename std::set<DataPair>::const_iterator;
169
170 iterator begin() const { return queue_.cbegin(); }
171
172 iterator end() const { return queue_.cend(); }
173
174 private:
175 std::set<DataPair> queue_;
176 std::unordered_map<std::string, uint64_t> times_;
177 };
178
179 /// CachedSessions are shared across requests
181 {
182 std::string session_id;
183 std::string requested_session_id; // session hasn't been created yet, but a key was requested
184
185 std::unordered_map<std::string, multi_value> entries;
186 std::unordered_set<std::string> dirty; // values that were changed after last load
187
188 void* store_data;
189 bool requested_refresh;
190
191 // number of references held - used for correctly destroying the cache.
192 // No need to be atomic, all SessionMiddleware accesses are synchronized
193 int referrers;
194 std::recursive_mutex mutex;
195 };
196 } // namespace session
197
198 // SessionMiddleware allows storing securely and easily small snippets of user information
199 template<typename Store>
200 struct SessionMiddleware
201 {
202 using lock = std::scoped_lock<std::mutex>;
203 using rc_lock = std::scoped_lock<std::recursive_mutex>;
204
205 struct context
206 {
207 // Get a mutex for locking this session
208 std::recursive_mutex& mutex()
209 {
210 check_node();
211 return node->mutex;
212 }
213
214 // Check whether this session is already present
215 bool exists() { return bool(node); }
216
217 // Get a value by key or fallback if it doesn't exist or is of another type
218 template<typename F>
219 auto get(const std::string& key, const F& fallback = F())
220 // This trick lets the multi_value deduce the return type from the fallback
221 // which allows both:
222 // context.get<std::string>("key")
223 // context.get("key", "") -> char[] is transformed into string by multivalue
224 // to return a string
225 -> decltype(std::declval<session::multi_value>().get<F>(std::declval<F>()))
226 {
227 if (!node) return fallback;
228 rc_lock l(node->mutex);
229
230 auto it = node->entries.find(key);
231 if (it != node->entries.end()) return it->second.get<F>(fallback);
232 return fallback;
233 }
234
235 // Set a value by key
236 template<typename T>
237 void set(const std::string& key, T value)
238 {
239 check_node();
240 rc_lock l(node->mutex);
241
242 node->dirty.insert(key);
243 node->entries[key].set(std::move(value));
244 }
245
246 bool contains(const std::string& key)
247 {
248 if (!node) return false;
249 rc_lock l(node->mutex);
250
251 return node->entries.find(key) != node->entries.end();
252 }
253
254 // Atomically mutate a value with a function
255 template<typename Func>
256 void apply(const std::string& key, const Func& f)
257 {
258 using traits = utility::function_traits<Func>;
259 using arg = typename std::decay<typename traits::template arg<0>>::type;
260 using retv = typename std::decay<typename traits::result_type>::type;
261 check_node();
262 rc_lock l(node->mutex);
263 node->dirty.insert(key);
264 node->entries[key].set<retv>(f(node->entries[key].get(arg{})));
265 }
266
267 // Remove a value from the session
268 void remove(const std::string& key)
269 {
270 if (!node) return;
271 rc_lock l(node->mutex);
272 node->dirty.insert(key);
273 node->entries.erase(key);
274 }
275
276 // Format value by key as a string
277 std::string string(const std::string& key)
278 {
279 if (!node) return "";
280 rc_lock l(node->mutex);
281
282 auto it = node->entries.find(key);
283 if (it != node->entries.end()) return it->second.string();
284 return "";
285 }
286
287 // Get a list of keys present in session
288 std::vector<std::string> keys()
289 {
290 if (!node) return {};
291 rc_lock l(node->mutex);
292
293 std::vector<std::string> out;
294 for (const auto& p : node->entries)
295 out.push_back(p.first);
296 return out;
297 }
298
299 // Delay expiration by issuing another cookie with an updated expiration time
300 // and notifying the store
301 void refresh_expiration()
302 {
303 if (!node) return;
304 node->requested_refresh = true;
305 }
306
307 private:
308 friend struct SessionMiddleware;
309
310 void check_node()
311 {
312 if (!node) node = std::make_shared<session::CachedSession>();
313 }
314
315 std::shared_ptr<session::CachedSession> node;
316 };
317
318 template<typename... Ts>
319 SessionMiddleware(
321 int id_length,
322 Ts... ts):
323 id_length_(id_length),
324 cookie_(cookie),
325 store_(std::forward<Ts>(ts)...), mutex_(new std::mutex{})
326 {}
327
328 template<typename... Ts>
329 SessionMiddleware(Ts... ts):
331 CookieParser::Cookie("session")
332 .path("/")
333 .max_age(/*month*/ 30 * 24 * 60 * 60)
334 .httponly()
335 .same_site(CookieParser::Cookie::SameSitePolicy::Lax),
336 /*id_length */ 20, // around 10^34 possible combinations, but small enough to fit into SSO
337 std::forward<Ts>(ts)...)
338 {}
339
340 template<typename AllContext>
341 void before_handle(request& /*req*/, response& /*res*/, context& ctx, AllContext& all_ctx)
342 {
343 lock l(*mutex_);
344
345 auto& cookies = all_ctx.template get<CookieParser>();
346 auto session_id = load_id(cookies);
347 if (session_id == "") return;
348
349 // search entry in cache
350 auto it = cache_.find(session_id);
351 if (it != cache_.end())
352 {
353 it->second->referrers++;
354 ctx.node = it->second;
355 return;
356 }
357
358 // check this is a valid entry before loading
359 if (!store_.contains(session_id)) return;
360
361 auto node = std::make_shared<session::CachedSession>();
362 node->session_id = session_id;
363 node->referrers = 1;
364
365 try
366 {
367 store_.load(*node);
368 }
369 catch (...)
370 {
371 CROW_LOG_ERROR << "Exception occurred during session load";
372 return;
373 }
374
375 ctx.node = node;
376 cache_[session_id] = node;
377 }
378
379 template<typename AllContext>
380 void after_handle(request& /*req*/, response& /*res*/, context& ctx, AllContext& all_ctx)
381 {
382 lock l(*mutex_);
383 if (!ctx.node || --ctx.node->referrers > 0) return;
384 ctx.node->requested_refresh |= ctx.node->session_id == "";
385
386 // generate new id
387 if (ctx.node->session_id == "")
388 {
389 // check for requested id
390 ctx.node->session_id = std::move(ctx.node->requested_session_id);
391 if (ctx.node->session_id == "")
392 {
393 ctx.node->session_id = utility::random_alphanum(id_length_);
394 }
395 }
396 else
397 {
398 cache_.erase(ctx.node->session_id);
399 }
400
401 if (ctx.node->requested_refresh)
402 {
403 auto& cookies = all_ctx.template get<CookieParser>();
404 store_id(cookies, ctx.node->session_id);
405 }
406
407 try
408 {
409 store_.save(*ctx.node);
410 }
411 catch (...)
412 {
413 CROW_LOG_ERROR << "Exception occurred during session save";
414 return;
415 }
416 }
417
418 private:
419 std::string next_id()
420 {
421 std::string id;
422 do
423 {
424 id = utility::random_alphanum(id_length_);
425 } while (store_.contains(id));
426 return id;
427 }
428
429 std::string load_id(const CookieParser::context& cookies)
430 {
431 return cookies.get_cookie(cookie_.name());
432 }
433
434 void store_id(CookieParser::context& cookies, const std::string& session_id)
435 {
436 cookie_.value(session_id);
437 cookies.set_cookie(cookie_);
438 }
439
440 private:
441 int id_length_;
442
443 // prototype for cookie
444 CookieParser::Cookie cookie_;
445
446 Store store_;
447
448 // mutexes are immovable
449 std::unique_ptr<std::mutex> mutex_;
450 std::unordered_map<std::string, std::shared_ptr<session::CachedSession>> cache_;
451 };
452
453 /// InMemoryStore stores all entries in memory
455 {
456 // Load a value into the session cache.
457 // A load is always followed by a save, no loads happen consecutively
458 void load(session::CachedSession& cn)
459 {
460 // load & stores happen sequentially, so moving is safe
461 cn.entries = std::move(entries[cn.session_id]);
462 }
463
464 // Persist session data
465 void save(session::CachedSession& cn)
466 {
467 entries[cn.session_id] = std::move(cn.entries);
468 // cn.dirty is a list of changed keys since the last load
469 }
470
471 bool contains(const std::string& key)
472 {
473 return entries.count(key) > 0;
474 }
475
476 std::unordered_map<std::string, std::unordered_map<std::string, session::multi_value>> entries;
477 };
478
479 // FileStore stores all data as json files in a folder.
480 // Files are deleted after expiration. Expiration refreshes are automatically picked up.
481 struct FileStore
482 {
483 FileStore(const std::string& folder, uint64_t expiration_seconds = /*month*/ 30 * 24 * 60 * 60):
484 path_(folder), expiration_seconds_(expiration_seconds)
485 {
486 std::ifstream ifs(get_filename(".expirations", false));
487
488 auto current_ts = chrono_time();
489 std::string key;
490 uint64_t time;
491 while (ifs >> key >> time)
492 {
493 if (current_ts > time)
494 {
495 evict(key);
496 }
497 else if (contains(key))
498 {
499 expirations_.add(key, time);
500 }
501 }
502 }
503
504 ~FileStore()
505 {
506 std::ofstream ofs(get_filename(".expirations", false), std::ios::trunc);
507 for (const auto& p : expirations_)
508 ofs << p.second << " " << p.first << "\n";
509 }
510
511 // Delete expired entries
512 // At most 3 to prevent freezes
513 void handle_expired()
514 {
515 int deleted = 0;
516 auto current_ts = chrono_time();
517 while (current_ts > expirations_.peek_first() && deleted < 3)
518 {
519 evict(expirations_.pop_first());
520 deleted++;
521 }
522 }
523
524 void load(session::CachedSession& cn)
525 {
526 handle_expired();
527
528 std::ifstream file(get_filename(cn.session_id));
529
530 std::stringstream buffer;
531 buffer << file.rdbuf() << std::endl;
532
533 for (const auto& p : json::load(buffer.str()))
534 cn.entries[p.key()] = session::multi_value::from_json(p);
535 }
536
537 void save(session::CachedSession& cn)
538 {
539 if (cn.requested_refresh)
540 expirations_.add(cn.session_id, chrono_time() + expiration_seconds_);
541 if (cn.dirty.empty()) return;
542
543 std::ofstream file(get_filename(cn.session_id));
544 json::wvalue jw;
545 for (const auto& p : cn.entries)
546 jw[p.first] = p.second.json();
547 file << jw.dump() << std::flush;
548 }
549
550 std::string get_filename(const std::string& key, bool suffix = true)
551 {
552 std::string filename{key};
553 // we have to sanitize here to prevent file traversal by ".." or similar
554 utility::sanitize_filename(filename);
555 if (suffix)
556 {
557 filename.append(".json");
558 }
559 return (path_/filename).string();
560 }
561
562 bool contains(const std::string& key)
563 {
564 // handle_expired() only evicts a few entries per load, so check this key explicitly
565 if (chrono_time() > expirations_.get(key))
566 {
567 expirations_.remove(key);
568 evict(key);
569 return false;
570 }
571
572 std::ifstream file(get_filename(key));
573 return file.good();
574 }
575
576 void evict(const std::string& key)
577 {
578 std::remove(get_filename(key).c_str());
579 }
580
581 // expirations are persisted across restarts, so they need a clock with a fixed epoch
582 uint64_t chrono_time() const
583 {
584 return std::chrono::duration_cast<std::chrono::seconds>(
585 std::chrono::system_clock::now().time_since_epoch())
586 .count();
587 }
588
589 std::filesystem::path path_;
590 uint64_t expiration_seconds_;
591 session::ExpirationTracker expirations_;
592 };
593
594} // namespace crow
JSON read value.
Definition json.h:322
int64_t i() const
The integer value.
Definition json.h:444
double d() const
The double precision floating-point number value.
Definition json.h:478
uint64_t u() const
The unsigned integer value.
Definition json.h:462
num_type nt() const
The number type of the JSON value.
Definition json.h:432
type t() const
The type of the JSON value.
Definition json.h:420
JSON write value.
Definition json.h:1378
The main namespace of the library. In this namespace is defined the most important classes and functi...
InMemoryStore stores all entries in memory.
Definition session.h:455
Definition session.h:206
Definition session.h:201
CachedSessions are shared across requests.
Definition session.h:181
Expiration tracker keeps track of soonest-to-expire keys.
Definition session.h:121
uint64_t peek_first() const
Get expiration time of soonest-to-expire entry.
Definition session.h:145
uint64_t get(const std::string &key) const
Get expiration time of key, or the maximum value if it is not tracked.
Definition session.h:152
void add(std::string key, uint64_t time)
Definition session.h:126
A multi_value is a safe variant wrapper with json conversion support.
Definition session.h:58