// The pairings table + the pairing rate limiter. #include #include "check.hpp" #include "rpc/pairing.hpp" #include "store/migrations.hpp" #include "store/pairings.hpp" #include "store/sqlite.hpp" using namespace velox::daemon; void run() { // --- store: create -> find-by-token -> revoke --------------------------------- { auto db = store::Db::open(":memory:"); CHECK(db.has_value()); if (!db) return; CHECK(store::migrate_to_head(*db).has_value()); store::Pairings p(*db); auto created = p.create("moz-extension://abc", "Velox for Firefox", "2026-09-10T00:00:00Z"); CHECK(created.has_value()); if (!created) return; CHECK(created->token.size() >= 40); // 32 bytes base64url, unpadded CHECK(!created->pairing_id.empty()); // The plaintext token is not in the DB — only its hash. auto st = db->prepare("SELECT count(*) FROM pairings WHERE token_sha256 = ?1"); CHECK(st.has_value()); CHECK(st->bind(1, std::string_view(created->token)).has_value()); auto row = st->step(); CHECK(row.has_value() && *row); CHECK_EQ(st->column_int(0), 0); // token itself never stored auto found = p.find_active_by_token(created->token); CHECK(found.has_value()); CHECK(found->has_value()); if (found && *found) CHECK_EQ((*found)->origin, std::string("moz-extension://abc")); auto missing = p.find_active_by_token("not-the-token"); CHECK(missing.has_value() && !missing->has_value()); auto revoked = p.revoke(created->pairing_id, "2026-09-10T01:00:00Z"); CHECK(revoked.has_value() && *revoked == true); auto after = p.find_active_by_token(created->token); CHECK(after.has_value() && !after->has_value()); // revoked -> not active auto revoke_again = p.revoke(created->pairing_id, "2026-09-10T02:00:00Z"); CHECK(revoke_again.has_value() && *revoke_again == false); } // --- rate limiter: 5 failures, then a lockout with retryAfter ----------------- { rpc::PairingRateLimiter rl; using Clock = rpc::PairingRateLimiter::Clock; const auto t0 = Clock::now(); for (int i = 0; i < 5; ++i) { CHECK(rl.check("origin-a", t0).allowed); rl.record_failure("origin-a", t0); } const auto d = rl.check("origin-a", t0); CHECK(!d.allowed); CHECK(d.retry_after_sec > 0 && d.retry_after_sec <= 61); // A different origin is unaffected — the lockout is per-origin. CHECK(rl.check("origin-b", t0).allowed); // Still locked 30 s later; clear after the lockout elapses. CHECK(!rl.check("origin-a", t0 + std::chrono::seconds(30)).allowed); CHECK(rl.check("origin-a", t0 + std::chrono::seconds(121)).allowed); // A success wipes the origin's history. rl.record_failure("origin-c", t0); rl.record_failure("origin-c", t0); rl.record_success("origin-c"); for (int i = 0; i < 4; ++i) { CHECK(rl.check("origin-c", t0).allowed); rl.record_failure("origin-c", t0); } CHECK(rl.check("origin-c", t0).allowed); // only 4 since the reset } } TEST_MAIN()