| 496 | } |
| 497 | |
| 498 | bool HttpServer::isAuthorized(const httplib::Request& req) { |
| 499 | if (!_authRequired) { |
| 500 | return true; |
| 501 | } |
| 502 | if (_authToken.empty()) { |
| 503 | return false; |
| 504 | } |
| 505 | if (_authTokenHasExpiry && std::chrono::steady_clock::now() > _authTokenExpiry) { |
| 506 | _authToken.clear(); |
| 507 | _authSessionId.clear(); |
| 508 | _authSessionSecret.clear(); |
| 509 | _authTokenHasExpiry = false; |
| 510 | return false; |
| 511 | } |
| 512 | if (!_authSessionId.empty()) { |
| 513 | auto sessionIt = req.headers.find("X-Dora-Session"s); |
| 514 | auto timestampIt = req.headers.find("X-Dora-Timestamp"s); |
| 515 | auto nonceIt = req.headers.find("X-Dora-Nonce"s); |
| 516 | auto signatureIt = req.headers.find("X-Dora-Signature"s); |
| 517 | if (sessionIt == req.headers.end() || timestampIt == req.headers.end() || nonceIt == req.headers.end() || signatureIt == req.headers.end()) { |
| 518 | return false; |
| 519 | } |
| 520 | const auto& sessionId = sessionIt->second; |
| 521 | if (sessionId != _authSessionId) { |
| 522 | return false; |
| 523 | } |
| 524 | long long timestamp = 0; |
| 525 | try { |
| 526 | timestamp = std::stoll(timestampIt->second); |
| 527 | } catch (...) { |
| 528 | return false; |
| 529 | } |
| 530 | auto now = std::chrono::system_clock::now(); |
| 531 | auto nowSeconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count(); |
| 532 | if (std::llabs(nowSeconds - timestamp) > AuthSignatureTTLSeconds) { |
| 533 | return false; |
| 534 | } |
| 535 | const auto& nonce = nonceIt->second; |
| 536 | auto path = canonicalize_path(req.path, req.params); |
| 537 | auto bodyHash = sha256_hex(req.body); |
| 538 | auto payload = fmt::format("{}\n{}\n{}\n{}\n{}\n{}", sessionId, req.method, path, timestampIt->second, nonce, bodyHash); |
| 539 | auto expected = hmac_sha256_hex(_authSessionSecret, payload); |
| 540 | if (expected != signatureIt->second) { |
| 541 | return false; |
| 542 | } |
| 543 | { |
| 544 | std::lock_guard<std::mutex> lock(_authNonceMutex); |
| 545 | auto cutoff = std::chrono::steady_clock::now() - std::chrono::seconds(AuthSignatureTTLSeconds); |
| 546 | for (auto it = _authNonces.begin(); it != _authNonces.end();) { |
| 547 | if (it->second < cutoff) { |
| 548 | it = _authNonces.erase(it); |
| 549 | } else { |
| 550 | ++it; |
| 551 | } |
| 552 | } |
| 553 | if (_authNonces.find(nonce) != _authNonces.end()) { |
| 554 | return false; |
| 555 | } |
nothing calls this directly
no test coverage detected