Skip to content

Truly independent web browser

LibHTTP: Key the disk cache by full SHA-256 digests

Shannon Boothf2849cf58fb6
diff --git a/Libraries/LibHTTP/Cache/CacheEntry.cpp b/Libraries/LibHTTP/Cache/CacheEntry.cpp
index bb44b6e3f6b..c923d7ba991 100644
--- a/Libraries/LibHTTP/Cache/CacheEntry.cpp
+++ b/Libraries/LibHTTP/Cache/CacheEntry.cpp
@@ -72,7 +72,7 @@ ErrorOr<CacheFooter> CacheFooter::read_from_stream(Stream& stream)
return footer;
}
-CacheEntry::CacheEntry(DiskCache& disk_cache, CacheIndex& index, u64 cache_key, u64 vary_key, String url, Optional<LexicalPath> path, CacheHeader cache_header)
+CacheEntry::CacheEntry(DiskCache& disk_cache, CacheIndex& index, CacheDigest const& cache_key, CacheDigest const& vary_key, String url, Optional<LexicalPath> path, CacheHeader cache_header)
: m_disk_cache(disk_cache)
, m_index(index)
, m_cache_key(cache_key)
@@ -97,18 +97,18 @@ void CacheEntry::close_and_destroy_cache_entry()
m_disk_cache.cache_entry_closed({}, *this);
}
-ErrorOr<NonnullOwnPtr<CacheEntryWriter>> CacheEntryWriter::create(DiskCache& disk_cache, CacheIndex& index, u64 cache_key, String url, UnixDateTime request_time, AK::Duration current_time_offset_for_testing)
+ErrorOr<NonnullOwnPtr<CacheEntryWriter>> CacheEntryWriter::create(DiskCache& disk_cache, CacheIndex& index, CacheDigest const& cache_key, String url, UnixDateTime request_time, AK::Duration current_time_offset_for_testing)
{
CacheHeader cache_header;
- cache_header.key_hash = u64_hash(cache_key);
+ cache_header.key_hash = Traits<CacheDigest>::hash(cache_key);
cache_header.url_size = url.byte_count();
cache_header.url_hash = url.hash();
return adopt_own(*new CacheEntryWriter { disk_cache, index, cache_key, move(url), cache_header, request_time, current_time_offset_for_testing });
}
-CacheEntryWriter::CacheEntryWriter(DiskCache& disk_cache, CacheIndex& index, u64 cache_key, String url, CacheHeader cache_header, UnixDateTime request_time, AK::Duration current_time_offset_for_testing)
- : CacheEntry(disk_cache, index, cache_key, 0, move(url), {}, cache_header)
+CacheEntryWriter::CacheEntryWriter(DiskCache& disk_cache, CacheIndex& index, CacheDigest const& cache_key, String url, CacheHeader cache_header, UnixDateTime request_time, AK::Duration current_time_offset_for_testing)
+ : CacheEntry(disk_cache, index, cache_key, {}, move(url), {}, cache_header)
, m_request_time(request_time)
, m_current_time_offset_for_testing(current_time_offset_for_testing)
{
@@ -297,7 +297,7 @@ void CacheEntryWriter::remove_incomplete_temporary_file()
(void)FileSystem::remove(m_temporary_path->string(), FileSystem::RecursionMode::Disallowed);
}
-ErrorOr<NonnullOwnPtr<CacheEntryReader>> CacheEntryReader::create(DiskCache& disk_cache, CacheIndex& index, u64 cache_key, u64 vary_key, NonnullRefPtr<HeaderList> response_headers, u64 data_size)
+ErrorOr<NonnullOwnPtr<CacheEntryReader>> CacheEntryReader::create(DiskCache& disk_cache, CacheIndex& index, CacheDigest const& cache_key, CacheDigest const& vary_key, String const& expected_url, NonnullRefPtr<HeaderList> response_headers, u64 data_size)
{
auto path = path_for_cache_entry(disk_cache.cache_directory(), cache_key, vary_key);
@@ -319,10 +319,14 @@ ErrorOr<NonnullOwnPtr<CacheEntryReader>> CacheEntryReader::create(DiskCache& dis
if (cache_header.version != CACHE_VERSION)
return Error::from_string_literal("Version mismatch");
- if (cache_header.key_hash != u64_hash(cache_key))
+ if (cache_header.key_hash != Traits<CacheDigest>::hash(cache_key))
return Error::from_string_literal("Key hash mismatch");
+ if (cache_header.url_size != expected_url.byte_count())
+ return Error::from_string_literal("URL mismatch");
url = TRY(String::from_stream(*file, cache_header.url_size));
+ if (url != expected_url)
+ return Error::from_string_literal("URL mismatch");
if (url.hash() != cache_header.url_hash)
return Error::from_string_literal("URL hash mismatch");
@@ -345,7 +349,7 @@ ErrorOr<NonnullOwnPtr<CacheEntryReader>> CacheEntryReader::create(DiskCache& dis
return adopt_own(*new CacheEntryReader { disk_cache, index, cache_key, vary_key, move(url), move(path), move(file), fd, cache_header, move(reason_phrase), move(response_headers), data_offset, data_size });
}
-CacheEntryReader::CacheEntryReader(DiskCache& disk_cache, CacheIndex& index, u64 cache_key, u64 vary_key, String url, LexicalPath path, NonnullOwnPtr<Core::File> file, int fd, CacheHeader cache_header, Optional<String> reason_phrase, NonnullRefPtr<HeaderList> response_headers, u64 data_offset, u64 data_size)
+CacheEntryReader::CacheEntryReader(DiskCache& disk_cache, CacheIndex& index, CacheDigest const& cache_key, CacheDigest const& vary_key, String url, LexicalPath path, NonnullOwnPtr<Core::File> file, int fd, CacheHeader cache_header, Optional<String> reason_phrase, NonnullRefPtr<HeaderList> response_headers, u64 data_offset, u64 data_size)
: CacheEntry(disk_cache, index, cache_key, vary_key, move(url), move(path), cache_header)
, m_file(move(file))
, m_fd(fd)
diff --git a/Libraries/LibHTTP/Cache/CacheEntry.h b/Libraries/LibHTTP/Cache/CacheEntry.h
index 6a1785614ed..ef829118b74 100644
--- a/Libraries/LibHTTP/Cache/CacheEntry.h
+++ b/Libraries/LibHTTP/Cache/CacheEntry.h
@@ -14,6 +14,7 @@
#include <AK/Types.h>
#include <LibCore/File.h>
#include <LibCore/Notifier.h>
+#include <LibHTTP/Cache/CacheKey.h>
#include <LibHTTP/Cache/Version.h>
#include <LibHTTP/Forward.h>
#include <LibHTTP/HeaderList.h>
@@ -66,7 +67,7 @@ public:
virtual ~CacheEntry() = default;
- u64 cache_key() const { return m_cache_key; }
+ CacheDigest const& cache_key() const { return m_cache_key; }
u64 body_size() const { return m_cache_footer.data_size; }
void remove();
@@ -74,15 +75,15 @@ public:
void mark_for_deletion(Badge<DiskCache>) { m_marked_for_deletion = true; }
protected:
- CacheEntry(DiskCache&, CacheIndex&, u64 cache_key, u64 vary_key, String url, Optional<LexicalPath>, CacheHeader);
+ CacheEntry(DiskCache&, CacheIndex&, CacheDigest const& cache_key, CacheDigest const& vary_key, String url, Optional<LexicalPath>, CacheHeader);
void close_and_destroy_cache_entry();
DiskCache& m_disk_cache;
CacheIndex& m_index;
- u64 m_cache_key { 0 };
- u64 m_vary_key { 0 };
+ CacheDigest m_cache_key;
+ CacheDigest m_vary_key;
String m_url;
Optional<LexicalPath> m_path;
@@ -95,7 +96,7 @@ protected:
class CacheEntryWriter final : public CacheEntry {
public:
- static ErrorOr<NonnullOwnPtr<CacheEntryWriter>> create(DiskCache&, CacheIndex&, u64 cache_key, String url, UnixDateTime request_time, AK::Duration current_time_offset_for_testing);
+ static ErrorOr<NonnullOwnPtr<CacheEntryWriter>> create(DiskCache&, CacheIndex&, CacheDigest const& cache_key, String url, UnixDateTime request_time, AK::Duration current_time_offset_for_testing);
virtual ~CacheEntryWriter() override = default;
ErrorOr<void> write_status_and_reason(u32 status_code, Optional<String> reason_phrase, HeaderList const& request_headers, HeaderList const& response_headers);
@@ -105,7 +106,7 @@ public:
void remove_incomplete_entry();
private:
- CacheEntryWriter(DiskCache&, CacheIndex&, u64 cache_key, String url, CacheHeader, UnixDateTime request_time, AK::Duration current_time_offset_for_testing);
+ CacheEntryWriter(DiskCache&, CacheIndex&, CacheDigest const& cache_key, String url, CacheHeader, UnixDateTime request_time, AK::Duration current_time_offset_for_testing);
ErrorOr<void> flush_impl(NonnullRefPtr<HeaderList> request_headers, CacheEntryBodyFile*);
void remove_incomplete_temporary_file();
@@ -123,7 +124,7 @@ private:
class CacheEntryReader final : public CacheEntry {
public:
- static ErrorOr<NonnullOwnPtr<CacheEntryReader>> create(DiskCache&, CacheIndex&, u64 cache_key, u64 vary_key, NonnullRefPtr<HeaderList>, u64 data_size);
+ static ErrorOr<NonnullOwnPtr<CacheEntryReader>> create(DiskCache&, CacheIndex&, CacheDigest const& cache_key, CacheDigest const& vary_key, String const& url, NonnullRefPtr<HeaderList>, u64 data_size);
virtual ~CacheEntryReader() override = default;
enum class RevalidationType {
@@ -149,7 +150,7 @@ public:
HeaderList const& response_headers() const { return m_response_headers; }
private:
- CacheEntryReader(DiskCache&, CacheIndex&, u64 cache_key, u64 vary_key, String url, LexicalPath, NonnullOwnPtr<Core::File>, int fd, CacheHeader, Optional<String> reason_phrase, NonnullRefPtr<HeaderList>, u64 data_offset, u64 data_size);
+ CacheEntryReader(DiskCache&, CacheIndex&, CacheDigest const& cache_key, CacheDigest const& vary_key, String url, LexicalPath, NonnullOwnPtr<Core::File>, int fd, CacheHeader, Optional<String> reason_phrase, NonnullRefPtr<HeaderList>, u64 data_offset, u64 data_size);
void send_without_blocking();
void send_complete();
diff --git a/Libraries/LibHTTP/Cache/CacheIndex.cpp b/Libraries/LibHTTP/Cache/CacheIndex.cpp
index d6af576832b..1b94f96dcf0 100644
--- a/Libraries/LibHTTP/Cache/CacheIndex.cpp
+++ b/Libraries/LibHTTP/Cache/CacheIndex.cpp
@@ -5,7 +5,6 @@
*/
#include <AK/Array.h>
-#include <AK/BitCast.h>
#include <AK/Checked.h>
#include <AK/Debug.h>
#include <AK/NumericLimits.h>
@@ -23,16 +22,16 @@ static constexpr u32 INDEX_SCHEMA_BASELINE_VERSION = 1u;
static constexpr u32 INDEX_SCHEMA_PARTITIONED_CACHE_KEYS_VERSION = 2u;
static constexpr u32 INDEX_SCHEMA_VARY_KEY_VERSION = 3u;
static constexpr u32 INDEX_SCHEMA_RESPONSES_ONLY_VERSION = 4u;
+static constexpr u32 INDEX_SCHEMA_SHA256_KEYS_VERSION = 5u;
-// Persist full-range hashes as signed bit patterns; keys are only compared for equality.
-static i64 encode_cache_key_for_database(u64 key)
+static ReadonlyBytes encode_cache_key_for_database(CacheDigest const& key)
{
- return bit_cast<i64>(key);
+ return key.bytes;
}
-static u64 decode_cache_key_from_database(i64 stored_key)
+static Optional<CacheDigest> decode_cache_key_from_database(ByteBuffer const& stored_key)
{
- return bit_cast<u64>(stored_key);
+ return CacheDigest::from_bytes(stored_key);
}
static ByteString serialize_headers(HeaderList const& headers)
@@ -69,7 +68,7 @@ static NonnullRefPtr<HeaderList> deserialize_headers(StringView serialized_heade
return headers;
}
-static void remove_cache_entry_files(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key)
+static void remove_cache_entry_files(LexicalPath const& cache_directory, CacheDigest const& cache_key, CacheDigest const& vary_key)
{
(void)FileSystem::remove(path_for_cache_entry(cache_directory, cache_key, vary_key).string(), FileSystem::RecursionMode::Disallowed);
}
@@ -126,7 +125,7 @@ static void log_orphaned_disk_cache_entries(Database::Database& database)
// a migration here without invalidating the cache entries on disk. Entry files embed
// CACHE_VERSION in their headers and are validated when read, so an entry format break must
// append a migration that deletes the index rows referencing the now-unreadable entries.
-static_assert(CACHE_VERSION == 8, "Bumping CACHE_VERSION requires appending a CacheIndex migration that deletes the index rows referencing the old entry format");
+static_assert(CACHE_VERSION == 9, "Bumping CACHE_VERSION requires appending a CacheIndex migration that deletes the index rows referencing the old entry format");
ErrorOr<Database::MigrationOutcome> CacheIndex::migrate_schema(Database::Database& database, Database::MigrationMode mode)
{
@@ -185,6 +184,31 @@ ErrorOr<Database::MigrationOutcome> CacheIndex::migrate_schema(Database::Databas
return {};
},
},
+ {
+ // CACHE_VERSION 9 changed cache and vary keys to full SHA-256 digests.
+ .version = INDEX_SCHEMA_SHA256_KEYS_VERSION,
+ .sql = R"#(
+ DROP TABLE CacheIndex;
+ CREATE TABLE CacheIndex (
+ cache_key BLOB,
+ vary_key BLOB,
+ url TEXT,
+ request_headers BLOB,
+ response_headers BLOB,
+ data_size INTEGER,
+ request_time INTEGER,
+ response_time INTEGER,
+ last_access_time INTEGER,
+ PRIMARY KEY(cache_key, vary_key)
+ );
+ )#"sv,
+ .backfill = [](Database::Database& database) -> ErrorOr<void> {
+ for_each_cache_entry_file(database, [](LexicalPath const& cache_entry) {
+ (void)FileSystem::remove(cache_entry.string(), FileSystem::RecursionMode::Disallowed);
+ });
+ return {};
+ },
+ },
});
return database.migrate("CacheIndex"sv, migrations, mode);
@@ -269,7 +293,8 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPath
auto remove_malformed_entries = TRY(database.prepare_statement(R"#(
DELETE FROM CacheIndex
- WHERE typeof(cache_key) != 'integer' OR typeof(vary_key) != 'integer' OR typeof(url) != 'text'
+ WHERE typeof(cache_key) != 'blob' OR typeof(vary_key) != 'blob' OR typeof(url) != 'text'
+ OR OCTET_LENGTH(cache_key) != ?2 OR OCTET_LENGTH(vary_key) != ?2
OR typeof(request_headers) != 'blob' OR typeof(response_headers) != 'blob'
OR typeof(data_size) != 'integer' OR typeof(request_time) != 'integer' OR typeof(response_time) != 'integer' OR typeof(last_access_time) != 'integer'
OR data_size NOT BETWEEN 0 AND ?1
@@ -279,15 +304,15 @@ ErrorOr<CacheIndex> CacheIndex::create(Database::Database& database, LexicalPath
if (auto result = database.try_execute_statement(
remove_malformed_entries,
[&](auto statement_id) -> ErrorOr<void> {
- auto cache_key = database.result_i64_checked(statement_id, 0);
- auto vary_key = database.result_i64_checked(statement_id, 1);
- if (cache_key.is_error() || vary_key.is_error())
+ auto cache_key = decode_cache_key_from_database(database.result_column<ByteBuffer>(statement_id, 0));
+ auto vary_key = decode_cache_key_from_database(database.result_column<ByteBuffer>(statement_id, 1));
+ if (!cache_key.has_value() || !vary_key.has_value())
return {};
- remove_cache_entry_files(cache_directory, decode_cache_key_from_database(cache_key.value()), decode_cache_key_from_database(vary_key.value()));
+ remove_cache_entry_files(cache_directory, *cache_key, *vary_key);
return {};
},
- limits.maximum_disk_cache_size);
+ limits.maximum_disk_cache_size, static_cast<i64>(sizeof(CacheDigest::bytes)));
result.is_error())
dbgln_if(HTTP_DISK_CACHE_DEBUG, "\033[36m[disk]\033[0m \033[31;1mUnable to remove malformed cache entries:\033[0m {}", result.error());
@@ -312,7 +337,7 @@ CacheIndex::CacheIndex(Database::Database& database, Statements statements, Limi
{
}
-ErrorOr<void> CacheIndex::create_entry(u64 cache_key, u64 vary_key, String url, NonnullRefPtr<HeaderList> request_headers, NonnullRefPtr<HeaderList> response_headers, u64 data_size, UnixDateTime request_time, UnixDateTime response_time)
+ErrorOr<void> CacheIndex::create_entry(CacheDigest const& cache_key, CacheDigest const& vary_key, String url, NonnullRefPtr<HeaderList> request_headers, NonnullRefPtr<HeaderList> response_headers, u64 data_size, UnixDateTime request_time, UnixDateTime response_time)
{
auto now = UnixDateTime::now();
@@ -379,7 +404,7 @@ ErrorOr<void> CacheIndex::create_entry(u64 cache_key, u64 vary_key, String url,
return {};
}
-void CacheIndex::remove_entry(u64 cache_key, u64 vary_key)
+void CacheIndex::remove_entry(CacheDigest const& cache_key, CacheDigest const& vary_key)
{
auto result = m_database->try_execute_statement(
m_statements.remove_entry,
@@ -396,7 +421,7 @@ void CacheIndex::remove_entry(u64 cache_key, u64 vary_key)
delete_entry(cache_key, vary_key);
}
-void CacheIndex::remove_entries_exceeding_cache_limit(Function<void(u64 cache_key, u64 vary_key)> on_entry_removed)
+void CacheIndex::remove_entries_exceeding_cache_limit(OnEntryRemoved on_entry_removed)
{
if (m_total_estimated_size <= m_limits.maximum_disk_cache_size)
return;
@@ -404,14 +429,16 @@ void CacheIndex::remove_entries_exceeding_cache_limit(Function<void(u64 cache_ke
auto result = m_database->try_execute_statement(
m_statements.remove_entries_exceeding_cache_limit,
[&](auto statement_id) -> ErrorOr<void> {
- auto cache_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 0));
- auto vary_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 1));
+ auto cache_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 0));
+ auto vary_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 1));
auto removed_size = m_database->result_column<i64>(statement_id, 2);
adjust_total_estimated_size(-removed_size);
- delete_entry(cache_key, vary_key);
+ if (!cache_key.has_value() || !vary_key.has_value())
+ return {};
+ delete_entry(*cache_key, *vary_key);
if (on_entry_removed)
- on_entry_removed(cache_key, vary_key);
+ on_entry_removed(*cache_key, *vary_key);
return {};
},
m_limits.maximum_disk_cache_size);
@@ -420,7 +447,7 @@ void CacheIndex::remove_entries_exceeding_cache_limit(Function<void(u64 cache_ke
dbgln_if(HTTP_DISK_CACHE_DEBUG, "\033[36m[disk]\033[0m \033[31;1mUnable to evict cache entries:\033[0m {}", result.error());
}
-void CacheIndex::remove_variants_exceeding_limit(u64 cache_key, u64 vary_key_to_keep, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed)
+void CacheIndex::remove_variants_exceeding_limit(CacheDigest const& cache_key, CacheDigest const& vary_key_to_keep, OnEntryRemoved on_entry_removed)
{
auto& entries = entries_for_cache_key(cache_key);
@@ -442,20 +469,20 @@ void CacheIndex::remove_variants_exceeding_limit(u64 cache_key, u64 vary_key_to_
}
}
-void CacheIndex::remove_entries_accessed_since(UnixDateTime since, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed)
+void CacheIndex::remove_entries_accessed_since(UnixDateTime since, OnEntryRemoved on_entry_removed)
{
// Removing every entry must not depend on what their rows contain.
if (since == UnixDateTime::earliest()) {
auto result = m_database->try_execute_statement(
m_statements.remove_all_entries,
[&](auto statement_id) -> ErrorOr<void> {
- auto cache_key = m_database->result_i64_checked(statement_id, 0);
- auto vary_key = m_database->result_i64_checked(statement_id, 1);
- if (cache_key.is_error() || vary_key.is_error())
+ auto cache_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 0));
+ auto vary_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 1));
+ if (!cache_key.has_value() || !vary_key.has_value())
return {};
if (on_entry_removed)
- on_entry_removed(decode_cache_key_from_database(cache_key.value()), decode_cache_key_from_database(vary_key.value()));
+ on_entry_removed(*cache_key, *vary_key);
return {};
});
// The entries stay, as their rows do.
@@ -474,14 +501,16 @@ void CacheIndex::remove_entries_accessed_since(UnixDateTime since, Function<void
auto result = m_database->try_execute_statement(
m_statements.remove_entries_accessed_since,
[&](auto statement_id) -> ErrorOr<void> {
- auto cache_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 0));
- auto vary_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 1));
+ auto cache_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 0));
+ auto vary_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 1));
auto removed_size = m_database->result_column<i64>(statement_id, 2);
adjust_total_estimated_size(-removed_size);
- delete_entry(cache_key, vary_key);
+ if (!cache_key.has_value() || !vary_key.has_value())
+ return {};
+ delete_entry(*cache_key, *vary_key);
if (on_entry_removed)
- on_entry_removed(cache_key, vary_key);
+ on_entry_removed(*cache_key, *vary_key);
return {};
},
since);
@@ -489,19 +518,21 @@ void CacheIndex::remove_entries_accessed_since(UnixDateTime since, Function<void
dbgln_if(HTTP_DISK_CACHE_DEBUG, "\033[36m[disk]\033[0m \033[31;1m{}:\033[0m {}", "Unable to remove cache entries"sv, result.error());
}
-void CacheIndex::remove_entries_accessed_before(UnixDateTime before, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed)
+void CacheIndex::remove_entries_accessed_before(UnixDateTime before, OnEntryRemoved on_entry_removed)
{
auto result = m_database->try_execute_statement(
m_statements.remove_entries_accessed_before,
[&](auto statement_id) -> ErrorOr<void> {
- auto cache_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 0));
- auto vary_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, 1));
+ auto cache_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 0));
+ auto vary_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, 1));
auto removed_size = m_database->result_column<i64>(statement_id, 2);
adjust_total_estimated_size(-removed_size);
- delete_entry(cache_key, vary_key);
+ if (!cache_key.has_value() || !vary_key.has_value())
+ return {};
+ delete_entry(*cache_key, *vary_key);
if (on_entry_removed)
- on_entry_removed(cache_key, vary_key);
+ on_entry_removed(*cache_key, *vary_key);
return {};
},
before);
@@ -509,13 +540,13 @@ void CacheIndex::remove_entries_accessed_before(UnixDateTime before, Function<vo
dbgln_if(HTTP_DISK_CACHE_DEBUG, "\033[36m[disk]\033[0m \033[31;1m{}:\033[0m {}", "Unable to remove cache entries"sv, result.error());
}
-void CacheIndex::remove_entries_for_cache_key(u64 cache_key, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed)
+void CacheIndex::remove_entries_for_cache_key(CacheDigest const& cache_key, OnEntryRemoved on_entry_removed)
{
- Vector<u64> vary_keys;
+ Vector<CacheDigest> vary_keys;
for (auto const& entry : entries_for_cache_key(cache_key))
vary_keys.append(entry.vary_key);
- for (auto vary_key : vary_keys) {
+ for (auto const& vary_key : vary_keys) {
remove_entry(cache_key, vary_key);
if (on_entry_removed)
@@ -523,7 +554,7 @@ void CacheIndex::remove_entries_for_cache_key(u64 cache_key, Function<void(u64 c
}
}
-ErrorOr<void> CacheIndex::update_response_headers(u64 cache_key, u64 vary_key, NonnullRefPtr<HeaderList> response_headers, UnixDateTime request_time, UnixDateTime response_time)
+ErrorOr<void> CacheIndex::update_response_headers(CacheDigest const& cache_key, CacheDigest const& vary_key, NonnullRefPtr<HeaderList> response_headers, UnixDateTime request_time, UnixDateTime response_time)
{
auto entry = get_entry(cache_key, vary_key);
if (!entry.has_value())
@@ -553,7 +584,7 @@ ErrorOr<void> CacheIndex::update_response_headers(u64 cache_key, u64 vary_key, N
return {};
}
-void CacheIndex::update_last_access_time(u64 cache_key, u64 vary_key)
+void CacheIndex::update_last_access_time(CacheDigest const& cache_key, CacheDigest const& vary_key)
{
auto entry = get_entry(cache_key, vary_key);
if (!entry.has_value())
@@ -568,7 +599,7 @@ void CacheIndex::update_last_access_time(u64 cache_key, u64 vary_key)
entry->last_access_time = now;
}
-Optional<CacheIndex::Entry const&> CacheIndex::find_entry(u64 cache_key, HeaderList const& request_headers)
+Optional<CacheIndex::Entry const&> CacheIndex::find_entry(CacheDigest const& cache_key, HeaderList const& request_headers)
{
auto& entries = entries_for_cache_key(cache_key);
Optional<Entry const&> selected_entry;
@@ -590,7 +621,7 @@ Optional<CacheIndex::Entry const&> CacheIndex::find_entry(u64 cache_key, HeaderL
return selected_entry;
}
-Vector<CacheIndex::Entry>& CacheIndex::entries_for_cache_key(u64 cache_key)
+Vector<CacheIndex::Entry>& CacheIndex::entries_for_cache_key(CacheDigest const& cache_key)
{
return m_entries.ensure(cache_key, [&]() {
Vector<Entry> entries;
@@ -600,7 +631,7 @@ Vector<CacheIndex::Entry>& CacheIndex::entries_for_cache_key(u64 cache_key)
[&](auto statement_id) -> ErrorOr<void> {
int column = 0;
- auto vary_key = decode_cache_key_from_database(m_database->result_column<i64>(statement_id, column++));
+ auto vary_key = decode_cache_key_from_database(m_database->result_column<ByteBuffer>(statement_id, column++));
auto url = m_database->result_column<String>(statement_id, column++);
auto request_headers = m_database->result_column<ByteString>(statement_id, column++);
auto response_headers = m_database->result_column<ByteString>(statement_id, column++);
@@ -609,10 +640,10 @@ Vector<CacheIndex::Entry>& CacheIndex::entries_for_cache_key(u64 cache_key)
auto response_time = m_database->result_column<UnixDateTime>(statement_id, column++);
auto last_access_time = m_database->result_column<UnixDateTime>(statement_id, column++);
- if (data_size < 0)
+ if (!vary_key.has_value() || data_size < 0)
return {};
- entries.empend(vary_key, move(url), deserialize_headers(request_headers), deserialize_headers(response_headers), static_cast<u64>(data_size), request_headers.length(), response_headers.length(), request_time, response_time, last_access_time);
+ entries.empend(vary_key.release_value(), move(url), deserialize_headers(request_headers), deserialize_headers(response_headers), static_cast<u64>(data_size), request_headers.length(), response_headers.length(), request_time, response_time, last_access_time);
return {};
},
encode_cache_key_for_database(cache_key));
@@ -626,12 +657,12 @@ Vector<CacheIndex::Entry>& CacheIndex::entries_for_cache_key(u64 cache_key)
});
}
-bool CacheIndex::has_entry(u64 cache_key, u64 vary_key)
+bool CacheIndex::has_entry(CacheDigest const& cache_key, CacheDigest const& vary_key)
{
return get_entry(cache_key, vary_key).has_value();
}
-Optional<CacheIndex::Entry&> CacheIndex::get_entry(u64 cache_key, u64 vary_key)
+Optional<CacheIndex::Entry&> CacheIndex::get_entry(CacheDigest const& cache_key, CacheDigest const& vary_key)
{
auto& entries = entries_for_cache_key(cache_key);
return find_value(entries, [&](auto const& entry) { return entry.vary_key == vary_key; });
@@ -650,7 +681,7 @@ void CacheIndex::adjust_total_estimated_size(i64 delta)
on_total_estimated_size_change();
}
-void CacheIndex::delete_entry(u64 cache_key, u64 vary_key)
+void CacheIndex::delete_entry(CacheDigest const& cache_key, CacheDigest const& vary_key)
{
auto entries = m_entries.get(cache_key);
if (!entries.has_value())
diff --git a/Libraries/LibHTTP/Cache/CacheIndex.h b/Libraries/LibHTTP/Cache/CacheIndex.h
index 3a18ceea6ca..a9468ede897 100644
--- a/Libraries/LibHTTP/Cache/CacheIndex.h
+++ b/Libraries/LibHTTP/Cache/CacheIndex.h
@@ -12,6 +12,7 @@
#include <AK/Time.h>
#include <AK/Types.h>
#include <LibDatabase/Database.h>
+#include <LibHTTP/Cache/CacheKey.h>
#include <LibHTTP/HeaderList.h>
#include <LibRequests/CacheSizes.h>
@@ -21,7 +22,7 @@ namespace HTTP {
// the entire cache entry has been successfully written to disk.
class CacheIndex {
struct Entry {
- u64 vary_key { 0 };
+ CacheDigest vary_key;
String url;
NonnullRefPtr<HeaderList> request_headers;
@@ -45,19 +46,21 @@ public:
static ErrorOr<CacheIndex> create(Database::Database&, LexicalPath const& cache_directory);
- ErrorOr<void> create_entry(u64 cache_key, u64 vary_key, String url, NonnullRefPtr<HeaderList> request_headers, NonnullRefPtr<HeaderList> response_headers, u64 data_size, UnixDateTime request_time, UnixDateTime response_time);
- void remove_entry(u64 cache_key, u64 vary_key);
- void remove_entries_exceeding_cache_limit(Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);
- void remove_variants_exceeding_limit(u64 cache_key, u64 vary_key_to_keep, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);
- void remove_entries_accessed_since(UnixDateTime, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);
- void remove_entries_accessed_before(UnixDateTime, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);
- void remove_entries_for_cache_key(u64 cache_key, Function<void(u64 cache_key, u64 vary_key)> on_entry_removed);
+ using OnEntryRemoved = Function<void(CacheDigest const& cache_key, CacheDigest const& vary_key)>;
- Optional<Entry const&> find_entry(u64 cache_key, HeaderList const& request_headers);
- bool has_entry(u64 cache_key, u64 vary_key);
+ ErrorOr<void> create_entry(CacheDigest const& cache_key, CacheDigest const& vary_key, String url, NonnullRefPtr<HeaderList> request_headers, NonnullRefPtr<HeaderList> response_headers, u64 data_size, UnixDateTime request_time, UnixDateTime response_time);
+ void remove_entry(CacheDigest const& cache_key, CacheDigest const& vary_key);
+ void remove_entries_exceeding_cache_limit(OnEntryRemoved on_entry_removed);
+ void remove_variants_exceeding_limit(CacheDigest const& cache_key, CacheDigest const& vary_key_to_keep, OnEntryRemoved on_entry_removed);
+ void remove_entries_accessed_since(UnixDateTime, OnEntryRemoved on_entry_removed);
+ void remove_entries_accessed_before(UnixDateTime, OnEntryRemoved on_entry_removed);
+ void remove_entries_for_cache_key(CacheDigest const& cache_key, OnEntryRemoved on_entry_removed);
- ErrorOr<void> update_response_headers(u64 cache_key, u64 vary_key, NonnullRefPtr<HeaderList>, UnixDateTime request_time, UnixDateTime response_time);
- void update_last_access_time(u64 cache_key, u64 vary_key);
+ Optional<Entry const&> find_entry(CacheDigest const& cache_key, HeaderList const& request_headers);
+ bool has_entry(CacheDigest const& cache_key, CacheDigest const& vary_key);
+
+ ErrorOr<void> update_response_headers(CacheDigest const& cache_key, CacheDigest const& vary_key, NonnullRefPtr<HeaderList>, UnixDateTime request_time, UnixDateTime response_time);
+ void update_last_access_time(CacheDigest const& cache_key, CacheDigest const& vary_key);
Requests::CacheSizes estimate_cache_size_accessed_since(UnixDateTime since);
Vector<Requests::CacheAccessBucket> access_profile(AK::Duration granularity);
@@ -92,15 +95,15 @@ private:
CacheIndex(Database::Database&, Statements, Limits, i64 total_estimated_size);
- Vector<Entry>& entries_for_cache_key(u64 cache_key);
- Optional<Entry&> get_entry(u64 cache_key, u64 vary_key);
- void delete_entry(u64 cache_key, u64 vary_key);
+ Vector<Entry>& entries_for_cache_key(CacheDigest const& cache_key);
+ Optional<Entry&> get_entry(CacheDigest const& cache_key, CacheDigest const& vary_key);
+ void delete_entry(CacheDigest const& cache_key, CacheDigest const& vary_key);
void adjust_total_estimated_size(i64 delta);
NonnullRawPtr<Database::Database> m_database;
Statements m_statements;
- HashMap<u64, Vector<Entry>, IdentityHashTraits<u64>> m_entries;
+ HashMap<CacheDigest, Vector<Entry>> m_entries;
Limits m_limits;
i64 m_total_estimated_size { 0 };
diff --git a/Libraries/LibHTTP/Cache/CacheKey.h b/Libraries/LibHTTP/Cache/CacheKey.h
index 0baaeccb647..f0bfb23a5b8 100644
--- a/Libraries/LibHTTP/Cache/CacheKey.h
+++ b/Libraries/LibHTTP/Cache/CacheKey.h
@@ -6,7 +6,10 @@
#pragma once
+#include <AK/Array.h>
+#include <AK/ByteReader.h>
#include <AK/HashFunctions.h>
+#include <AK/Optional.h>
#include <AK/String.h>
#include <AK/Traits.h>
@@ -20,6 +23,22 @@ struct CacheKey {
bool operator==(CacheKey const&) const = default;
};
+// A SHA-256 digest. It is not truncated, so that pages cannot construct colliding requests.
+struct CacheDigest {
+ static Optional<CacheDigest> from_bytes(ReadonlyBytes bytes)
+ {
+ CacheDigest digest;
+ if (bytes.size() != digest.bytes.size())
+ return {};
+ bytes.copy_to(digest.bytes);
+ return digest;
+ }
+
+ Array<u8, 32> bytes {};
+
+ bool operator==(CacheDigest const&) const = default;
+};
+
}
namespace AK {
@@ -29,4 +48,9 @@ struct Traits<HTTP::CacheKey> : DefaultTraits<HTTP::CacheKey> {
static unsigned hash(HTTP::CacheKey const& key) { return pair_int_hash(key.url.hash(), key.method.hash()); }
};
+template<>
+struct Traits<HTTP::CacheDigest> : DefaultTraits<HTTP::CacheDigest> {
+ static unsigned hash(HTTP::CacheDigest const& digest) { return ByteReader::load32(digest.bytes.data()); }
+};
+
}
diff --git a/Libraries/LibHTTP/Cache/DiskCache.cpp b/Libraries/LibHTTP/Cache/DiskCache.cpp
index ed83567ea2a..b5e5abe3d60 100644
--- a/Libraries/LibHTTP/Cache/DiskCache.cpp
+++ b/Libraries/LibHTTP/Cache/DiskCache.cpp
@@ -129,7 +129,7 @@ Variant<Optional<CacheEntryReader&>, DiskCache::CacheHasOpenEntry> DiskCache::op
return Optional<CacheEntryReader&> {};
}
- auto cache_entry = CacheEntryReader::create(*this, m_index, cache_key, index_entry->vary_key, index_entry->response_headers, index_entry->data_size);
+ auto cache_entry = CacheEntryReader::create(*this, m_index, cache_key, index_entry->vary_key, serialized_url, index_entry->response_headers, index_entry->data_size);
if (cache_entry.is_error()) {
dbgln_if(HTTP_DISK_CACHE_DEBUG, "\033[36m[disk]\033[0m \033[31;1mUnable to open cache entry for\033[0m {}: {}", url, cache_entry.error());
@@ -220,7 +220,7 @@ Variant<Optional<CacheEntryReader&>, DiskCache::CacheHasOpenEntry> DiskCache::op
return Optional<CacheEntryReader&> { *cache_entry_pointer };
}
-bool DiskCache::check_if_cache_has_open_entry(CacheRequest& request, u64 cache_key, URL::URL const& url, CheckReaderEntries check_reader_entries)
+bool DiskCache::check_if_cache_has_open_entry(CacheRequest& request, CacheDigest const& cache_key, URL::URL const& url, CheckReaderEntries check_reader_entries)
{
// FIXME: We purposefully do not use the vary key here, as we do not yet have it when creating a CacheEntryWriter
// (we can only compute it once we receive the response headers). We could come up with a more sophisticated
@@ -276,14 +276,14 @@ Optional<MonotonicTime> DiskCache::last_activity_time_of_open_entries(Utf16Strin
void DiskCache::remove_entries_exceeding_cache_limit()
{
- m_index.remove_entries_exceeding_cache_limit([&](auto cache_key, auto vary_key) {
+ m_index.remove_entries_exceeding_cache_limit([&](auto const& cache_key, auto const& vary_key) {
delete_entry(cache_key, vary_key);
});
}
-void DiskCache::remove_variants_exceeding_limit(Badge<CacheEntryWriter>, u64 cache_key, u64 vary_key_to_keep)
+void DiskCache::remove_variants_exceeding_limit(Badge<CacheEntryWriter>, CacheDigest const& cache_key, CacheDigest const& vary_key_to_keep)
{
- m_index.remove_variants_exceeding_limit(cache_key, vary_key_to_keep, [&](auto cache_key, auto vary_key) {
+ m_index.remove_variants_exceeding_limit(cache_key, vary_key_to_keep, [&](auto const& cache_key, auto const& vary_key) {
delete_entry(cache_key, vary_key);
});
}
@@ -308,14 +308,14 @@ void DiskCache::remove_entries_accessed_since(UnixDateTime since)
}
}
- m_index.remove_entries_accessed_since(since, [&](auto cache_key, auto vary_key) {
+ m_index.remove_entries_accessed_since(since, [&](auto const& cache_key, auto const& vary_key) {
delete_entry(cache_key, vary_key);
});
}
void DiskCache::remove_entries_accessed_before(UnixDateTime before)
{
- m_index.remove_entries_accessed_before(before, [&](auto cache_key, auto vary_key) {
+ m_index.remove_entries_accessed_before(before, [&](auto const& cache_key, auto const& vary_key) {
delete_entry(cache_key, vary_key);
});
}
@@ -336,7 +336,7 @@ void DiskCache::invalidate(Utf16String const& partition, URL::URL const& url)
open_entry->mark_for_deletion({});
}
- m_index.remove_entries_for_cache_key(cache_key, [&](auto cache_key, auto vary_key) {
+ m_index.remove_entries_for_cache_key(cache_key, [&](auto const& cache_key, auto const& vary_key) {
delete_entry(cache_key, vary_key);
});
}
@@ -392,7 +392,7 @@ void DiskCache::close_entry(CacheEntry const& cache_entry)
}
}
-void DiskCache::delete_entry(u64 cache_key, u64 vary_key)
+void DiskCache::delete_entry(CacheDigest const& cache_key, CacheDigest const& vary_key)
{
if (auto open_entries = m_open_cache_entries.get(cache_key); open_entries.has_value()) {
for (auto const& [open_entry, _] : *open_entries)
@@ -402,7 +402,7 @@ void DiskCache::delete_entry(u64 cache_key, u64 vary_key)
remove_entry_files(cache_key, vary_key);
}
-void DiskCache::remove_entry_files(u64 cache_key, u64 vary_key)
+void DiskCache::remove_entry_files(CacheDigest const& cache_key, CacheDigest const& vary_key)
{
auto cache_path = path_for_cache_entry(m_cache_directory, cache_key, vary_key);
(void)FileSystem::remove(cache_path.string(), FileSystem::RecursionMode::Disallowed);
diff --git a/Libraries/LibHTTP/Cache/DiskCache.h b/Libraries/LibHTTP/Cache/DiskCache.h
index 7f493e39cfc..5d02296b508 100644
--- a/Libraries/LibHTTP/Cache/DiskCache.h
+++ b/Libraries/LibHTTP/Cache/DiskCache.h
@@ -53,7 +53,7 @@ public:
Variant<Optional<CacheEntryReader&>, CacheHasOpenEntry> open_entry(CacheRequest&, Utf16String const& partition, URL::URL const&, StringView method, HeaderList const& request_headers, CacheMode, OpenMode);
void remove_entries_exceeding_cache_limit();
- void remove_variants_exceeding_limit(Badge<CacheEntryWriter>, u64 cache_key, u64 vary_key_to_keep);
+ void remove_variants_exceeding_limit(Badge<CacheEntryWriter>, CacheDigest const& cache_key, CacheDigest const& vary_key_to_keep);
void set_maximum_disk_cache_size(u64 maximum_disk_cache_size);
Requests::CacheSizes estimate_cache_size_accessed_since(UnixDateTime since);
@@ -85,11 +85,11 @@ private:
No,
Yes,
};
- bool check_if_cache_has_open_entry(CacheRequest&, u64 cache_key, URL::URL const&, CheckReaderEntries);
+ bool check_if_cache_has_open_entry(CacheRequest&, CacheDigest const& cache_key, URL::URL const&, CheckReaderEntries);
void close_entry(CacheEntry const&);
- void delete_entry(u64 cache_key, u64 vary_key);
- void remove_entry_files(u64 cache_key, u64 vary_key);
+ void delete_entry(CacheDigest const& cache_key, CacheDigest const& vary_key);
+ void remove_entry_files(CacheDigest const& cache_key, CacheDigest const& vary_key);
Mode m_mode;
NonnullRefPtr<Database::Database> m_database;
@@ -98,8 +98,8 @@ private:
NonnullOwnPtr<CacheEntry> entry;
WeakPtr<CacheRequest> request;
};
- HashMap<u64, Vector<OpenCacheEntry, 1>, IdentityHashTraits<u64>> m_open_cache_entries;
- HashMap<u64, Vector<WeakPtr<CacheRequest>, 1>, IdentityHashTraits<u64>> m_requests_waiting_completion;
+ HashMap<CacheDigest, Vector<OpenCacheEntry, 1>> m_open_cache_entries;
+ HashMap<CacheDigest, Vector<WeakPtr<CacheRequest>, 1>> m_requests_waiting_completion;
LexicalPath m_cache_directory;
CacheIndex m_index;
diff --git a/Libraries/LibHTTP/Cache/MemoryCache.cpp b/Libraries/LibHTTP/Cache/MemoryCache.cpp
index 2637baa271a..051599013ca 100644
--- a/Libraries/LibHTTP/Cache/MemoryCache.cpp
+++ b/Libraries/LibHTTP/Cache/MemoryCache.cpp
@@ -241,7 +241,7 @@ void MemoryCache::abandon_entry(URL::URL const& url, StringView method, HeaderLi
remove_complete_entries(cache_key, [&](auto const& entry) { return entry_matches_request(request_headers, entry); });
}
-Optional<MemoryCache::Entry> MemoryCache::take_pending_entry(CacheKey const& cache_key, Optional<u64> vary_key)
+Optional<MemoryCache::Entry> MemoryCache::take_pending_entry(CacheKey const& cache_key, Optional<CacheDigest> const& vary_key)
{
auto cache_entries = m_pending_entries.get(cache_key);
if (!cache_entries.has_value())
@@ -304,7 +304,7 @@ Vector<MemoryCache::EntryUse> MemoryCache::complete_entry_uses() const
return uses;
}
-void MemoryCache::evict_complete_entry(CacheKey const& cache_key, u64 vary_key)
+void MemoryCache::evict_complete_entry(CacheKey const& cache_key, CacheDigest const& vary_key)
{
dbgln_if(HTTP_MEMORY_CACHE_DEBUG, "\033[37m[memory]\033[0m \033[33;1mEvicted cache entry\033[0m {}", cache_key.url);
remove_complete_entries(cache_key, [&](auto const& entry) { return entry.vary_key == vary_key; });
diff --git a/Libraries/LibHTTP/Cache/MemoryCache.h b/Libraries/LibHTTP/Cache/MemoryCache.h
index 8ff66afa1a2..bd8c7633c4c 100644
--- a/Libraries/LibHTTP/Cache/MemoryCache.h
+++ b/Libraries/LibHTTP/Cache/MemoryCache.h
@@ -32,7 +32,7 @@ struct MemoryCacheUsage : public RefCounted<MemoryCacheUsage> {
class MemoryCache : public RefCounted<MemoryCache> {
public:
struct Entry {
- u64 vary_key { 0 };
+ CacheDigest vary_key;
u32 status_code { 0 };
ByteString reason_phrase;
@@ -69,19 +69,19 @@ public:
struct EntryUse {
CacheKey cache_key;
- u64 vary_key { 0 };
+ CacheDigest vary_key;
bool body_is_mapped { false };
u64 last_use { 0 };
};
Vector<EntryUse> complete_entry_uses() const;
- void evict_complete_entry(CacheKey const& cache_key, u64 vary_key);
+ void evict_complete_entry(CacheKey const& cache_key, CacheDigest const& vary_key);
private:
explicit MemoryCache(NonnullRefPtr<MemoryCacheUsage>);
void add_to_usage(Entry const&);
void remove_from_usage(Entry const&);
- Optional<Entry> take_pending_entry(CacheKey const& cache_key, Optional<u64> vary_key);
+ Optional<Entry> take_pending_entry(CacheKey const& cache_key, Optional<CacheDigest> const& vary_key);
void remove_complete_entries(CacheKey const& cache_key, Function<bool(Entry const&)> const& predicate);
HashMap<CacheKey, Vector<Entry>> m_pending_entries;
diff --git a/Libraries/LibHTTP/Cache/Utilities.cpp b/Libraries/LibHTTP/Cache/Utilities.cpp
index 0cf51552280..8b59743b885 100644
--- a/Libraries/LibHTTP/Cache/Utilities.cpp
+++ b/Libraries/LibHTTP/Cache/Utilities.cpp
@@ -8,6 +8,7 @@
#include <AK/Array.h>
#include <AK/CharacterTypes.h>
#include <AK/GenericLexer.h>
+#include <AK/Hex.h>
#include <AK/NumericLimits.h>
#include <AK/QuickSort.h>
#include <AK/StringBuilder.h>
@@ -81,27 +82,26 @@ String serialize_url_for_cache_storage(URL::URL const& url)
return url.serialize(URL::ExcludeFragment::Yes);
}
-static u64 serialize_hash(Crypto::Hash::Hasher& hasher)
+static CacheDigest serialize_hash(Crypto::Hash::Hasher& hasher)
{
auto digest = hasher.finish();
- auto bytes = digest.bytes();
-
- u64 result = 0;
- result |= static_cast<u64>(bytes[0]) << 56;
- result |= static_cast<u64>(bytes[1]) << 48;
- result |= static_cast<u64>(bytes[2]) << 40;
- result |= static_cast<u64>(bytes[3]) << 32;
- result |= static_cast<u64>(bytes[4]) << 24;
- result |= static_cast<u64>(bytes[5]) << 16;
- result |= static_cast<u64>(bytes[6]) << 8;
- result |= static_cast<u64>(bytes[7]);
+ return CacheDigest::from_bytes(digest.bytes()).release_value();
+}
- return result;
+// Length prefixes prevent distinct fields from hashing the same byte sequence.
+static void update_with_length(Crypto::Hash::Hasher& hasher, StringView bytes)
+{
+ u64 length = bytes.length();
+ hasher.update(ReadonlyBytes { &length, sizeof(length) });
+ hasher.update(bytes);
}
-u64 create_cache_key(Utf16View const& partition, StringView url, StringView method)
+CacheDigest create_cache_key(Utf16View const& partition, StringView url, StringView method)
{
- Crypto::Hash::Hasher hasher { Crypto::Hash::HashKind::SHA1 };
+ Crypto::Hash::Hasher hasher { Crypto::Hash::HashKind::SHA256 };
+
+ u64 partition_length = partition.length_in_code_units();
+ hasher.update(ReadonlyBytes { &partition_length, sizeof(partition_length) });
// NB: Hash the code units rather than the string's storage, so the same text always gives the same key.
Array<u8, 256> buffer;
@@ -116,9 +116,8 @@ u64 create_cache_key(Utf16View const& partition, StringView url, StringView meth
buffer[buffer_size++] = static_cast<u8>(code_unit >> 8);
}
hasher.update(buffer.span().trim(buffer_size));
- hasher.update("\n"sv);
- hasher.update(url);
- hasher.update(method);
+ update_with_length(hasher, url);
+ update_with_length(hasher, method);
return serialize_hash(hasher);
}
@@ -173,25 +172,18 @@ Optional<Vector<ByteString>> vary_field_names(HeaderList const& response_headers
return field_names;
}
-Optional<u64> create_vary_key(HeaderList const& request_headers, HeaderList const& response_headers)
+Optional<CacheDigest> create_vary_key(HeaderList const& request_headers, HeaderList const& response_headers)
{
auto field_names = vary_field_names(response_headers);
if (!field_names.has_value())
return {};
if (field_names->is_empty())
- return 0;
-
- Crypto::Hash::Hasher hasher { Crypto::Hash::HashKind::SHA1 };
+ return CacheDigest {};
- // Length prefixes prevent distinct field sets from hashing the same byte sequence.
- auto update_with_length = [&](StringView bytes) {
- u64 length = bytes.length();
- hasher.update(ReadonlyBytes { &length, sizeof(length) });
- hasher.update(bytes);
- };
+ Crypto::Hash::Hasher hasher { Crypto::Hash::HashKind::SHA256 };
for (auto const& field_name : *field_names) {
- update_with_length(field_name);
+ update_with_length(hasher, field_name);
// If (after any normalization that might take place) a header field is absent from a request, it can only
// match another request if it is also absent there.
@@ -203,22 +195,30 @@ Optional<u64> create_vary_key(HeaderList const& request_headers, HeaderList cons
if (values.has_value()) {
for (auto const& value : *values)
- update_with_length(value);
+ update_with_length(hasher, value);
}
}
return serialize_hash(hasher);
}
-LexicalPath path_for_cache_entry(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key)
+LexicalPath path_for_cache_entry(LexicalPath const& cache_directory, CacheDigest const& cache_key, CacheDigest const& vary_key)
{
- auto file = vary_key == 0
- ? ByteString::formatted("{:016x}", cache_key)
- : ByteString::formatted("{:016x}_{:016x}", cache_key, vary_key);
+ auto file = vary_key == CacheDigest {}
+ ? encode_hex(cache_key.bytes)
+ : ByteString::formatted("{}_{}", encode_hex(cache_key.bytes), encode_hex(vary_key.bytes));
return cache_directory.append(file);
}
+static Optional<CacheDigest> parse_digest(StringView hex)
+{
+ auto bytes = decode_hex(hex);
+ if (bytes.is_error())
+ return {};
+ return CacheDigest::from_bytes(bytes.value());
+}
+
Optional<CacheEntryData> cache_entry_data_for_file(LexicalPath const& cache_file)
{
CacheEntryData result;
@@ -228,15 +228,15 @@ Optional<CacheEntryData> cache_entry_data_for_file(LexicalPath const& cache_file
if (parts.size() != 2)
return {};
- auto cache_key = AK::parse_number<u64>(parts[0], TrimWhitespace::No, 16);
- auto vary_key = AK::parse_number<u64>(parts[1], TrimWhitespace::No, 16);
+ auto cache_key = parse_digest(parts[0]);
+ auto vary_key = parse_digest(parts[1]);
if (!cache_key.has_value() || !vary_key.has_value())
return {};
result.cache_key = *cache_key;
result.vary_key = *vary_key;
} else {
- auto cache_key = AK::parse_number<u64>(file_name, TrimWhitespace::No, 16);
+ auto cache_key = parse_digest(file_name);
if (!cache_key.has_value())
return {};
diff --git a/Libraries/LibHTTP/Cache/Utilities.h b/Libraries/LibHTTP/Cache/Utilities.h
index 01a5e32c505..1bcc6401558 100644
--- a/Libraries/LibHTTP/Cache/Utilities.h
+++ b/Libraries/LibHTTP/Cache/Utilities.h
@@ -31,15 +31,15 @@ i64 compute_maximum_disk_cache_size(u64 free_bytes, u64 limit_maximum_disk_cache
i64 compute_maximum_disk_cache_entry_size(i64 maximum_disk_cache_size);
String serialize_url_for_cache_storage(URL::URL const&);
-u64 create_cache_key(Utf16View const& partition, StringView url, StringView method);
+CacheDigest create_cache_key(Utf16View const& partition, StringView url, StringView method);
CacheKey create_cache_key(StringView url, StringView method);
Optional<Vector<ByteString>> vary_field_names(HeaderList const& response_headers);
-Optional<u64> create_vary_key(HeaderList const& request_headers, HeaderList const& response_headers);
-LexicalPath path_for_cache_entry(LexicalPath const& cache_directory, u64 cache_key, u64 vary_key);
+Optional<CacheDigest> create_vary_key(HeaderList const& request_headers, HeaderList const& response_headers);
+LexicalPath path_for_cache_entry(LexicalPath const& cache_directory, CacheDigest const& cache_key, CacheDigest const& vary_key);
struct CacheEntryData {
- u64 cache_key { 0 };
- u64 vary_key { 0 };
+ CacheDigest cache_key;
+ CacheDigest vary_key;
};
Optional<CacheEntryData> cache_entry_data_for_file(LexicalPath const&);
diff --git a/Libraries/LibHTTP/Cache/Version.h b/Libraries/LibHTTP/Cache/Version.h
index a29b1d074a8..bbec50e6164 100644
--- a/Libraries/LibHTTP/Cache/Version.h
+++ b/Libraries/LibHTTP/Cache/Version.h
@@ -12,6 +12,6 @@ namespace HTTP {
// Increment this version when a breaking change is made to the cache entry file format.
// Index-only schema changes are handled by the CacheIndex schema migrations instead.
-static constexpr inline u32 CACHE_VERSION = 8u;
+static constexpr inline u32 CACHE_VERSION = 9u;
}
diff --git a/Tests/LibHTTP/TestCacheIndex.cpp b/Tests/LibHTTP/TestCacheIndex.cpp
index 9827f037673..e98f0a303eb 100644
--- a/Tests/LibHTTP/TestCacheIndex.cpp
+++ b/Tests/LibHTTP/TestCacheIndex.cpp
@@ -4,8 +4,8 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
+#include <AK/Hex.h>
#include <AK/LexicalPath.h>
-#include <AK/NumericLimits.h>
#include <AK/QuickSort.h>
#include <LibCore/Directory.h>
#include <LibCore/File.h>
@@ -37,6 +37,18 @@ static CacheIndexTestState create_cache_index()
return { move(database), move(index) };
}
+static HTTP::CacheDigest key(u8 value)
+{
+ HTTP::CacheDigest digest;
+ digest.bytes.last() = value;
+ return digest;
+}
+
+static ByteString key_literal(u8 value)
+{
+ return ByteString::formatted("x'{}'", encode_hex(key(value).bytes));
+}
+
TEST_CASE(create_entry_replaces_loaded_entry)
{
auto state = create_cache_index();
@@ -51,7 +63,7 @@ TEST_CASE(create_entry_replaces_loaded_entry)
{ "ETag"sv, "v2"sv },
});
- auto cache_key = 1u;
+ auto cache_key = key(1);
auto vary_key = HTTP::create_vary_key(*request_headers, *response_headers_v1).value();
auto now = UnixDateTime::now();
@@ -81,12 +93,12 @@ TEST_CASE(remove_entries_exceeding_cache_limit_is_noop_when_under_limit)
state.index.set_maximum_disk_cache_size(80);
- for (u64 cache_key = 1; cache_key <= 5; ++cache_key)
- TRY_OR_FAIL(state.index.create_entry(cache_key, vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ for (u8 cache_key = 1; cache_key <= 5; ++cache_key)
+ TRY_OR_FAIL(state.index.create_entry(key(cache_key), vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
Vector<u64> removed_entries;
- state.index.remove_entries_exceeding_cache_limit([&](auto removed_cache_key, auto) {
- removed_entries.append(removed_cache_key);
+ state.index.remove_entries_exceeding_cache_limit([&](auto const& removed_cache_key, auto const&) {
+ removed_entries.append(removed_cache_key.bytes.last());
});
EXPECT_EQ(removed_entries.size(), 0u);
@@ -104,15 +116,15 @@ TEST_CASE(remove_entries_exceeding_cache_limit_tolerates_replaced_unloaded_entri
state.index.set_maximum_disk_cache_size(80);
- for (u64 cache_key = 1; cache_key <= 8; ++cache_key)
- TRY_OR_FAIL(state.index.create_entry(cache_key, vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ for (u8 cache_key = 1; cache_key <= 8; ++cache_key)
+ TRY_OR_FAIL(state.index.create_entry(key(cache_key), vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
- TRY_OR_FAIL(reloaded_index.create_entry(1, vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(reloaded_index.create_entry(key(1), vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
Vector<u64> removed_entries;
- reloaded_index.remove_entries_exceeding_cache_limit([&](auto removed_cache_key, auto) {
- removed_entries.append(removed_cache_key);
+ reloaded_index.remove_entries_exceeding_cache_limit([&](auto const& removed_cache_key, auto const&) {
+ removed_entries.append(removed_cache_key.bytes.last());
});
EXPECT_EQ(removed_entries.size(), 0u);
@@ -142,11 +154,11 @@ TEST_CASE(entries_with_previous_vary_keys_are_dropped_on_migration)
EXPECT_EQ(TRY_OR_FAIL(HTTP::CacheIndex::migrate_schema(*database)), Database::MigrationOutcome::Success);
auto index = MUST(HTTP::CacheIndex::create(*database, cache_directory()));
- EXPECT(!index.find_entry(1, *HTTP::HeaderList::create()).has_value());
+ EXPECT(!index.find_entry(key(1), *HTTP::HeaderList::create()).has_value());
EXPECT_EQ(index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 0u);
}
-TEST_CASE(stored_responses_outlive_the_files_beside_them_on_migration)
+TEST_CASE(legacy_response_and_bytecode_files_are_dropped_on_migration)
{
Test::TemporaryDirectory const directory { "TestCacheIndex"sv };
auto database = TRY_OR_FAIL(Database::Database::create(directory.path().string(), "INDEX"sv));
@@ -164,16 +176,16 @@ TEST_CASE(stored_responses_outlive_the_files_beside_them_on_migration)
EXPECT_EQ(TRY_OR_FAIL(HTTP::CacheIndex::migrate_schema(*database)), Database::MigrationOutcome::Success);
- EXPECT(FileSystem::exists(entry_file.string()));
+ EXPECT(!FileSystem::exists(entry_file.string()));
EXPECT(!FileSystem::exists(bytecode_file.string()));
EXPECT(!FileSystem::exists(partial_bytecode_file.string()));
auto index = MUST(HTTP::CacheIndex::create(*database, directory.path()));
- EXPECT(index.has_entry(1, 0));
- EXPECT_EQ(index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 10u);
+ EXPECT(!index.has_entry(key(1), {}));
+ EXPECT_EQ(index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 0u);
}
-TEST_CASE(full_range_cache_keys_round_trip)
+TEST_CASE(negative_stored_sizes_are_skipped_as_corrupt)
{
auto state = create_cache_index();
@@ -182,31 +194,27 @@ TEST_CASE(full_range_cache_keys_round_trip)
auto vary_key = HTTP::create_vary_key(*request_headers, *response_headers).value();
auto now = UnixDateTime::now();
- for (u64 cache_key : { static_cast<u64>(NumericLimits<i64>::max()) + 1, NumericLimits<u64>::max() }) {
- TRY_OR_FAIL(state.index.create_entry(cache_key, vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET data_size = -5;"sv));
- auto entry = state.index.find_entry(cache_key, *request_headers);
- EXPECT(entry.has_value());
- EXPECT_EQ(entry->vary_key, vary_key);
- EXPECT(state.index.has_entry(cache_key, vary_key));
- }
+ auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
+ auto entry = reloaded_index.find_entry(key(1), *request_headers);
+ EXPECT(!entry.has_value());
}
-TEST_CASE(negative_stored_sizes_are_skipped_as_corrupt)
+TEST_CASE(keys_of_the_wrong_length_are_skipped_after_startup)
{
auto state = create_cache_index();
- auto request_headers = HTTP::HeaderList::create();
- auto response_headers = HTTP::HeaderList::create({ { "Cache-Control"sv, "max-age=60"sv } });
- auto vary_key = HTTP::create_vary_key(*request_headers, *response_headers).value();
- auto now = UnixDateTime::now();
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("INSERT INTO CacheIndex VALUES ({}, x'00', 'https://example.com', x'', x'', 10, 0, 0, 0);", key_literal(1))));
+ TRY_OR_FAIL(state.database->execute_raw("INSERT INTO CacheIndex VALUES (x'01', x'00', 'https://example.com', x'', x'', 10, 0, 0, 0);"sv));
- TRY_OR_FAIL(state.index.create_entry(1, vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET data_size = -5;"sv));
+ EXPECT(!state.index.find_entry(key(1), *HTTP::HeaderList::create()).has_value());
- auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
- auto entry = reloaded_index.find_entry(1, *request_headers);
- EXPECT(!entry.has_value());
+ size_t removed_count = 0;
+ state.index.remove_entries_accessed_before(UnixDateTime::from_milliseconds_since_epoch(1), [&](auto const&, auto const&) { ++removed_count; });
+ EXPECT_EQ(removed_count, 0u);
+ EXPECT_EQ(state.index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 0u);
}
// SQLite stores the root page of each b-tree in sqlite_schema. CacheIndex's table and primary-key index use separate
@@ -243,24 +251,24 @@ TEST_CASE(failed_statements_after_creation_do_not_abort)
auto vary_key = HTTP::create_vary_key(*request_headers, *response_headers).value();
auto now = UnixDateTime::now();
- TRY_OR_FAIL(state.index.create_entry(1, vary_key, "https://example.com/1"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), vary_key, "https://example.com/1"_string, request_headers, response_headers, 10, now, now));
TRY_OR_FAIL(corrupt_cache_index_table(*state.database));
// Writes report that they failed.
- EXPECT(state.index.create_entry(2, vary_key, "https://example.com/2"_string, request_headers, response_headers, 10, now, now).is_error());
- EXPECT(state.index.update_response_headers(1, vary_key, response_headers, UnixDateTime::now(), UnixDateTime::now()).is_error());
- state.index.update_last_access_time(1, vary_key);
+ EXPECT(state.index.create_entry(key(2), vary_key, "https://example.com/2"_string, request_headers, response_headers, 10, now, now).is_error());
+ EXPECT(state.index.update_response_headers(key(1), vary_key, response_headers, UnixDateTime::now(), UnixDateTime::now()).is_error());
+ state.index.update_last_access_time(key(1), vary_key);
// Entries that can't be read are missed.
- EXPECT(!state.index.find_entry(3, *request_headers).has_value());
+ EXPECT(!state.index.find_entry(key(3), *request_headers).has_value());
// Entries that can't be removed stay, as their rows do.
state.index.remove_entries_accessed_before(UnixDateTime::now(), {});
state.index.remove_entries_accessed_since(UnixDateTime::earliest(), {});
- EXPECT(state.index.find_entry(1, *request_headers).has_value());
+ EXPECT(state.index.find_entry(key(1), *request_headers).has_value());
- state.index.remove_entry(1, vary_key);
- EXPECT(!state.index.find_entry(1, *request_headers).has_value());
+ state.index.remove_entry(key(1), vary_key);
+ EXPECT(!state.index.find_entry(key(1), *request_headers).has_value());
}
TEST_CASE(variants_per_cache_key_are_limited)
@@ -281,7 +289,7 @@ TEST_CASE(variants_per_cache_key_are_limited)
for (size_t variant = 0; variant < variant_count; ++variant) {
auto request_headers = request_headers_for_variant(variant);
auto vary_key = HTTP::create_vary_key(*request_headers, *response_headers).value();
- TRY_OR_FAIL(state.index.create_entry(1, vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), vary_key, "https://example.com"_string, request_headers, response_headers, 10, now, now));
}
// Variants persisted by an earlier index count too.
@@ -289,17 +297,17 @@ TEST_CASE(variants_per_cache_key_are_limited)
auto newest_request_headers = request_headers_for_variant(variant_count);
auto newest_vary_key = HTTP::create_vary_key(*newest_request_headers, *response_headers).value();
- TRY_OR_FAIL(reloaded_index.create_entry(1, newest_vary_key, "https://example.com"_string, newest_request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(reloaded_index.create_entry(key(1), newest_vary_key, "https://example.com"_string, newest_request_headers, response_headers, 10, now, now));
size_t removed_count = 0;
- reloaded_index.remove_variants_exceeding_limit(1, newest_vary_key, [&](auto, auto) { ++removed_count; });
+ reloaded_index.remove_variants_exceeding_limit(key(1), newest_vary_key, [&](auto, auto) { ++removed_count; });
EXPECT_EQ(removed_count, variant_count + 1 - HTTP::MAXIMUM_CACHE_ENTRY_VARIANT_COUNT);
- EXPECT(reloaded_index.find_entry(1, *newest_request_headers).has_value());
+ EXPECT(reloaded_index.find_entry(key(1), *newest_request_headers).has_value());
size_t remaining_count = 0;
for (size_t variant = 0; variant <= variant_count; ++variant) {
- if (reloaded_index.find_entry(1, *request_headers_for_variant(variant)).has_value())
+ if (reloaded_index.find_entry(key(1), *request_headers_for_variant(variant)).has_value())
++remaining_count;
}
EXPECT_EQ(remaining_count, HTTP::MAXIMUM_CACHE_ENTRY_VARIANT_COUNT);
@@ -322,10 +330,10 @@ TEST_CASE(most_recent_matching_variant_is_selected)
});
auto now = UnixDateTime::now();
- TRY_OR_FAIL(state.index.create_entry(1, HTTP::create_vary_key(*request_headers, *older_response_headers).value(), "https://example.com"_string, request_headers, older_response_headers, 10, now - AK::Duration::from_seconds(10), now - AK::Duration::from_seconds(10)));
- TRY_OR_FAIL(state.index.create_entry(1, HTTP::create_vary_key(*request_headers, *newer_response_headers).value(), "https://example.com"_string, request_headers, newer_response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), HTTP::create_vary_key(*request_headers, *older_response_headers).value(), "https://example.com"_string, request_headers, older_response_headers, 10, now - AK::Duration::from_seconds(10), now - AK::Duration::from_seconds(10)));
+ TRY_OR_FAIL(state.index.create_entry(key(1), HTTP::create_vary_key(*request_headers, *newer_response_headers).value(), "https://example.com"_string, request_headers, newer_response_headers, 10, now, now));
- auto entry = state.index.find_entry(1, *request_headers);
+ auto entry = state.index.find_entry(key(1), *request_headers);
VERIFY(entry.has_value());
EXPECT_EQ(entry->response_headers->get("ETag"sv), Optional<ByteString> { ByteString { "newer"sv } });
}
@@ -339,15 +347,15 @@ TEST_CASE(updated_response_headers_respect_entry_size_limit)
auto now = UnixDateTime::now();
state.index.set_maximum_disk_cache_size(800);
- TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
auto small_response_headers = HTTP::HeaderList::create({ { "ETag"sv, "v1"sv }, { "X-Small"sv, "x"sv } });
- TRY_OR_FAIL(state.index.update_response_headers(1, 0, small_response_headers, UnixDateTime::now(), UnixDateTime::now()));
+ TRY_OR_FAIL(state.index.update_response_headers(key(1), {}, small_response_headers, UnixDateTime::now(), UnixDateTime::now()));
auto large_response_headers = HTTP::HeaderList::create({ { "ETag"sv, "v1"sv }, { "X-Large"sv, ByteString::repeated('x', 200) } });
- EXPECT(state.index.update_response_headers(1, 0, large_response_headers, UnixDateTime::now(), UnixDateTime::now()).is_error());
+ EXPECT(state.index.update_response_headers(key(1), {}, large_response_headers, UnixDateTime::now(), UnixDateTime::now()).is_error());
- auto entry = state.index.find_entry(1, *request_headers);
+ auto entry = state.index.find_entry(key(1), *request_headers);
VERIFY(entry.has_value());
EXPECT(!entry->response_headers->contains("X-Large"sv));
}
@@ -361,16 +369,16 @@ TEST_CASE(updated_response_headers_record_the_times_of_the_revalidation)
auto stored_at = UnixDateTime::from_seconds_since_epoch(1000);
auto revalidated_at = UnixDateTime::from_seconds_since_epoch(2000);
- TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com"_string, request_headers, response_headers, 10, stored_at, stored_at));
- TRY_OR_FAIL(state.index.update_response_headers(1, 0, response_headers, revalidated_at, revalidated_at + AK::Duration::from_seconds(1)));
+ TRY_OR_FAIL(state.index.create_entry(key(1), {}, "https://example.com"_string, request_headers, response_headers, 10, stored_at, stored_at));
+ TRY_OR_FAIL(state.index.update_response_headers(key(1), {}, response_headers, revalidated_at, revalidated_at + AK::Duration::from_seconds(1)));
- auto entry = state.index.find_entry(1, *request_headers);
+ auto entry = state.index.find_entry(key(1), *request_headers);
VERIFY(entry.has_value());
EXPECT_EQ(entry->request_time, revalidated_at);
EXPECT_EQ(entry->response_time, revalidated_at + AK::Duration::from_seconds(1));
auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
- auto reloaded_entry = reloaded_index.find_entry(1, *request_headers);
+ auto reloaded_entry = reloaded_index.find_entry(key(1), *request_headers);
VERIFY(reloaded_entry.has_value());
EXPECT_EQ(reloaded_entry->request_time, revalidated_at);
EXPECT_EQ(reloaded_entry->response_time, revalidated_at + AK::Duration::from_seconds(1));
@@ -384,10 +392,10 @@ TEST_CASE(persisted_entries_are_found_before_they_are_looked_up)
auto response_headers = HTTP::HeaderList::create({ { "Cache-Control"sv, "max-age=60"sv } });
auto now = UnixDateTime::now();
- TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
- EXPECT(reloaded_index.has_entry(1, 0));
+ EXPECT(reloaded_index.has_entry(key(1), {}));
EXPECT_EQ(reloaded_index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 10u + 25u);
}
@@ -400,22 +408,22 @@ TEST_CASE(malformed_rows_are_dropped_when_the_index_is_opened)
auto response_headers = HTTP::HeaderList::create({ { "Cache-Control"sv, "max-age=60"sv } });
auto now = UnixDateTime::now();
- for (u64 cache_key = 1; cache_key <= 5; ++cache_key)
- TRY_OR_FAIL(state.index.create_entry(cache_key, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ for (u8 cache_key = 1; cache_key <= 5; ++cache_key)
+ TRY_OR_FAIL(state.index.create_entry(key(cache_key), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET request_headers = NULL WHERE cache_key = 1;"sv));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = NULL WHERE cache_key = 2;"sv));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET data_size = 9223372036854775807 WHERE cache_key = 3;"sv));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET response_time = 'late' WHERE cache_key = 4;"sv));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET request_headers = NULL WHERE cache_key = {};", key_literal(1))));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET last_access_time = NULL WHERE cache_key = {};", key_literal(2))));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET data_size = 9223372036854775807 WHERE cache_key = {};", key_literal(3))));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET response_time = 'late' WHERE cache_key = {};", key_literal(4))));
auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
- for (u64 cache_key = 1; cache_key <= 4; ++cache_key)
- EXPECT(!reloaded_index.find_entry(cache_key, *request_headers).has_value());
- EXPECT(reloaded_index.find_entry(5, *request_headers).has_value());
+ for (u8 cache_key = 1; cache_key <= 4; ++cache_key)
+ EXPECT(!reloaded_index.find_entry(key(cache_key), *request_headers).has_value());
+ EXPECT(reloaded_index.find_entry(key(5), *request_headers).has_value());
EXPECT_EQ(reloaded_index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total, 10u + 25u);
- TRY_OR_FAIL(reloaded_index.create_entry(6, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(reloaded_index.create_entry(key(6), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
reloaded_index.set_maximum_disk_cache_size(40);
reloaded_index.remove_entries_exceeding_cache_limit({});
EXPECT(reloaded_index.estimate_cache_size_accessed_since(UnixDateTime::earliest()).total <= 40u);
@@ -429,19 +437,19 @@ TEST_CASE(clearing_every_entry_does_not_depend_on_row_contents)
auto response_headers = HTTP::HeaderList::create({ { "Cache-Control"sv, "max-age=60"sv } });
auto now = UnixDateTime::now();
- TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
- TRY_OR_FAIL(state.index.create_entry(2, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = NULL WHERE cache_key = 1;"sv));
+ TRY_OR_FAIL(state.index.create_entry(key(1), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(2), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET last_access_time = NULL WHERE cache_key = {};", key_literal(1))));
Vector<u64> removed_entries;
- state.index.remove_entries_accessed_since(UnixDateTime::earliest(), [&](auto cache_key, auto) { removed_entries.append(cache_key); });
+ state.index.remove_entries_accessed_since(UnixDateTime::earliest(), [&](auto const& cache_key, auto const&) { removed_entries.append(cache_key.bytes.last()); });
EXPECT_EQ(removed_entries.size(), 2u);
- EXPECT(!state.index.find_entry(1, *request_headers).has_value());
- EXPECT(!state.index.find_entry(2, *request_headers).has_value());
+ EXPECT(!state.index.find_entry(key(1), *request_headers).has_value());
+ EXPECT(!state.index.find_entry(key(2), *request_headers).has_value());
auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
- EXPECT(!reloaded_index.find_entry(1, *request_headers).has_value());
+ EXPECT(!reloaded_index.find_entry(key(1), *request_headers).has_value());
}
TEST_CASE(overflowing_cache_size_sums_do_not_abort)
@@ -452,10 +460,10 @@ TEST_CASE(overflowing_cache_size_sums_do_not_abort)
auto response_headers = HTTP::HeaderList::create({ { "Cache-Control"sv, "max-age=60"sv } });
auto now = UnixDateTime::now();
- TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET data_size = 9223372036854775807, request_headers = x'', response_headers = x'' WHERE cache_key = 1;"sv));
+ TRY_OR_FAIL(state.index.create_entry(key(1), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET data_size = 9223372036854775807, request_headers = x'', response_headers = x'' WHERE cache_key = {};", key_literal(1))));
- TRY_OR_FAIL(state.index.create_entry(2, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(2), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
state.index.set_maximum_disk_cache_size(40);
state.index.remove_entries_exceeding_cache_limit({});
(void)state.index.estimate_cache_size_accessed_since(UnixDateTime::earliest());
@@ -472,10 +480,10 @@ TEST_CASE(stored_vary_wildcard_does_not_match)
});
auto now = UnixDateTime::now();
- TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), {}, "https://example.com"_string, request_headers, response_headers, 10, now, now));
auto reloaded_index = MUST(HTTP::CacheIndex::create(*state.database, cache_directory()));
- EXPECT(!reloaded_index.find_entry(1, *request_headers).has_value());
+ EXPECT(!reloaded_index.find_entry(key(1), *request_headers).has_value());
}
TEST_CASE(access_profile_and_eviction_by_last_access_time)
@@ -489,15 +497,15 @@ TEST_CASE(access_profile_and_eviction_by_last_access_time)
auto response_headers = HTTP::HeaderList::create();
auto now = UnixDateTime::now();
- TRY_OR_FAIL(state.index.create_entry(1, 0, "https://example.com/1"_string, request_headers, response_headers, 10, now, now));
- TRY_OR_FAIL(state.index.create_entry(2, 0, "https://example.com/2"_string, request_headers, response_headers, 20, now, now));
- TRY_OR_FAIL(state.index.create_entry(3, 0, "https://example.com/3"_string, request_headers, response_headers, 40, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(1), {}, "https://example.com/1"_string, request_headers, response_headers, 10, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(2), {}, "https://example.com/2"_string, request_headers, response_headers, 20, now, now));
+ TRY_OR_FAIL(state.index.create_entry(key(3), {}, "https://example.com/3"_string, request_headers, response_headers, 40, now, now));
EXPECT_EQ(size_changes, 3u);
// Entries 1 and 2 were last used in the same minute, entry 3 five minutes later.
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = 60000 WHERE cache_key = 1;"sv));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = 119999 WHERE cache_key = 2;"sv));
- TRY_OR_FAIL(state.database->execute_raw("UPDATE CacheIndex SET last_access_time = 360000 WHERE cache_key = 3;"sv));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET last_access_time = 60000 WHERE cache_key = {};", key_literal(1))));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET last_access_time = 119999 WHERE cache_key = {};", key_literal(2))));
+ TRY_OR_FAIL(state.database->execute_raw(ByteString::formatted("UPDATE CacheIndex SET last_access_time = 360000 WHERE cache_key = {};", key_literal(3))));
auto buckets = state.index.access_profile(AK::Duration::from_seconds(60));
EXPECT_EQ(buckets.size(), 2u);
@@ -507,11 +515,11 @@ TEST_CASE(access_profile_and_eviction_by_last_access_time)
EXPECT_EQ(buckets[1].size, 30u);
Vector<u64> removed_entries;
- state.index.remove_entries_accessed_before(UnixDateTime::from_milliseconds_since_epoch(360000), [&](auto cache_key, auto) { removed_entries.append(cache_key); });
+ state.index.remove_entries_accessed_before(UnixDateTime::from_milliseconds_since_epoch(360000), [&](auto const& cache_key, auto const&) { removed_entries.append(cache_key.bytes.last()); });
quick_sort(removed_entries);
EXPECT_EQ(removed_entries, (Vector<u64> { 1, 2 }));
EXPECT_EQ(state.index.total_estimated_size(), 40u);
EXPECT(size_changes >= 5u);
- EXPECT(state.index.find_entry(3, *request_headers).has_value());
- EXPECT(!state.index.find_entry(1, *request_headers).has_value());
+ EXPECT(state.index.find_entry(key(3), *request_headers).has_value());
+ EXPECT(!state.index.find_entry(key(1), *request_headers).has_value());
}
diff --git a/Tests/LibHTTP/TestCacheUtilities.cpp b/Tests/LibHTTP/TestCacheUtilities.cpp
index 212c66eafb8..704fbef0772 100644
--- a/Tests/LibHTTP/TestCacheUtilities.cpp
+++ b/Tests/LibHTTP/TestCacheUtilities.cpp
@@ -118,7 +118,7 @@ TEST_CASE(vary_wildcard_never_produces_a_vary_key)
EXPECT(!HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "Accept, *" } })).has_value());
EXPECT(!HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "," }, { "Vary", "*" } })).has_value());
- EXPECT_EQ(HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create()), Optional<u64> { 0 });
+ EXPECT(HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create()) == Optional<HTTP::CacheDigest> { HTTP::CacheDigest {} });
}
TEST_CASE(vary_key_does_not_depend_on_order_or_case_of_nominated_fields)
@@ -126,8 +126,8 @@ TEST_CASE(vary_key_does_not_depend_on_order_or_case_of_nominated_fields)
auto request_headers = HTTP::HeaderList::create({ { "Accept", "text/html" }, { "X-Variant", "a" } });
auto vary_key = HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "Accept, X-Variant" } }));
- EXPECT_EQ(HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "x-variant, ACCEPT" } })), vary_key);
- EXPECT_EQ(HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "X-Variant" }, { "Vary", "Accept, X-Variant, accept" } })), vary_key);
+ EXPECT(HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "x-variant, ACCEPT" } })) == vary_key);
+ EXPECT(HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "X-Variant" }, { "Vary", "Accept, X-Variant, accept" } })) == vary_key);
}
TEST_CASE(vary_nominating_too_many_fields_is_not_cacheable)
@@ -155,7 +155,7 @@ TEST_CASE(vary_nominating_too_many_fields_is_not_cacheable)
auto repeated_response_headers = HTTP::HeaderList::create({ { "Cache-Control", "max-age=60" }, { "Vary", repeated_vary.to_byte_string() } });
EXPECT(HTTP::is_cacheable(200, *repeated_response_headers));
- EXPECT_EQ(HTTP::create_vary_key(*request_headers, *repeated_response_headers), HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "X-Fill" } })));
+ EXPECT(HTTP::create_vary_key(*request_headers, *repeated_response_headers) == HTTP::create_vary_key(*request_headers, HTTP::HeaderList::create({ { "Vary", "X-Fill" } })));
}
TEST_CASE(not_modified_response_must_not_change_vary)
@@ -235,10 +235,10 @@ TEST_CASE(vary_key_frames_each_nominated_field)
auto first_request_headers = HTTP::HeaderList::create({ { "Accept", "x" }, { "Accept-Language", "b" }, { "Authorization", "A" } });
auto second_request_headers = HTTP::HeaderList::create({ { "Accept", "x" }, { "Accept-Language", "" }, { "Authorization", "bA" } });
- EXPECT_NE(HTTP::create_vary_key(*first_request_headers, *response_headers), HTTP::create_vary_key(*second_request_headers, *response_headers));
+ EXPECT(HTTP::create_vary_key(*first_request_headers, *response_headers) != HTTP::create_vary_key(*second_request_headers, *response_headers));
auto absent_request_headers = HTTP::HeaderList::create({ { "Accept", "x" }, { "Authorization", "bA" } });
- EXPECT_NE(HTTP::create_vary_key(*second_request_headers, *response_headers), HTTP::create_vary_key(*absent_request_headers, *response_headers));
+ EXPECT(HTTP::create_vary_key(*second_request_headers, *response_headers) != HTTP::create_vary_key(*absent_request_headers, *response_headers));
}
TEST_CASE(vary_key_normalizes_list_based_fields)
@@ -246,8 +246,8 @@ TEST_CASE(vary_key_normalizes_list_based_fields)
auto response_headers = HTTP::HeaderList::create({ { "Vary", "Accept" } });
auto vary_key = HTTP::create_vary_key(*HTTP::HeaderList::create({ { "Accept", "text/html, application/json;q=0.5" } }), *response_headers);
- EXPECT_EQ(HTTP::create_vary_key(*HTTP::HeaderList::create({ { "Accept", "Application/JSON;q=0.5,text/html" } }), *response_headers), vary_key);
- EXPECT_EQ(HTTP::create_vary_key(*HTTP::HeaderList::create({ { "Accept", "application/json;q=0.5" }, { "Accept", "text/html" } }), *response_headers), vary_key);
+ EXPECT(HTTP::create_vary_key(*HTTP::HeaderList::create({ { "Accept", "Application/JSON;q=0.5,text/html" } }), *response_headers) == vary_key);
+ EXPECT(HTTP::create_vary_key(*HTTP::HeaderList::create({ { "Accept", "application/json;q=0.5" }, { "Accept", "text/html" } }), *response_headers) == vary_key);
}
TEST_CASE(vary_key_keeps_quoted_strings_intact)
@@ -257,11 +257,11 @@ TEST_CASE(vary_key_keeps_quoted_strings_intact)
// Comma splitting loses the association between parameters and media types.
auto first_request_headers = HTTP::HeaderList::create({ { "Accept", "text/a;p=\"x,y\", text/b;p=\"z,w\"" } });
auto second_request_headers = HTTP::HeaderList::create({ { "Accept", "text/a;p=\"x,w\", text/b;p=\"z,y\"" } });
- EXPECT_NE(HTTP::create_vary_key(*first_request_headers, *response_headers), HTTP::create_vary_key(*second_request_headers, *response_headers));
+ EXPECT(HTTP::create_vary_key(*first_request_headers, *response_headers) != HTTP::create_vary_key(*second_request_headers, *response_headers));
auto lowercase_request_headers = HTTP::HeaderList::create({ { "Accept", "text/html;p=\"value\"" } });
auto uppercase_request_headers = HTTP::HeaderList::create({ { "Accept", "TEXT/HTML;p=\"VALUE\"" } });
- EXPECT_NE(HTTP::create_vary_key(*lowercase_request_headers, *response_headers), HTTP::create_vary_key(*uppercase_request_headers, *response_headers));
+ EXPECT(HTTP::create_vary_key(*lowercase_request_headers, *response_headers) != HTTP::create_vary_key(*uppercase_request_headers, *response_headers));
}
TEST_CASE(invalid_max_age_does_not_cache_temporary_redirect)
diff --git a/Tests/LibHTTP/TestDiskCache.cpp b/Tests/LibHTTP/TestDiskCache.cpp
index 3f315daa810..68ee4f5c187 100644
--- a/Tests/LibHTTP/TestDiskCache.cpp
+++ b/Tests/LibHTTP/TestDiskCache.cpp
@@ -5,6 +5,7 @@
*/
#include <AK/ByteBuffer.h>
+#include <LibCore/EventLoop.h>
#include <LibCore/File.h>
#include <LibCore/ImmutableBytes.h>
#include <LibCore/System.h>
@@ -20,7 +21,11 @@
struct TestCacheRequest final : public HTTP::CacheRequest {
virtual bool is_revalidation_request() const override { return false; }
- virtual void notify_request_unblocked(Badge<HTTP::DiskCache>) override { }
+ virtual void notify_request_unblocked(Badge<HTTP::DiskCache>) override { ++unblocked_count; }
+ virtual Optional<MonotonicTime> last_activity_time() const override { return activity; }
+
+ size_t unblocked_count { 0 };
+ Optional<MonotonicTime> activity;
};
static URL::URL parse_url(StringView url)
@@ -241,7 +246,7 @@ TEST_CASE(unreadable_entry_is_removed)
store_cache_entry(disk_cache, request, url, *request_headers, create_cacheable_response_headers(), "console.log('hello');"sv);
auto cache_key = HTTP::create_cache_key(test_partition(), HTTP::serialize_url_for_cache_storage(url), "GET"sv);
- auto path = HTTP::path_for_cache_entry(disk_cache.cache_directory(), cache_key, 0);
+ auto path = HTTP::path_for_cache_entry(disk_cache.cache_directory(), cache_key, {});
{
auto file = TRY_OR_FAIL(Core::File::open(path.string(), Core::File::OpenMode::Write | Core::File::OpenMode::Truncate));
TRY_OR_FAIL(file->write_until_depleted("garbage"sv.bytes()));
@@ -436,3 +441,109 @@ TEST_CASE(force_cache_reuses_stale_must_revalidate_entries)
VERIFY(reader.has_value());
EXPECT_EQ(reader->revalidation_type(), HTTP::CacheEntryReader::RevalidationType::None);
}
+
+// Legacy disk SHA-1 prefix: cc4122efe2277ef8, with test_partition() and GET.
+TEST_CASE(legacy_disk_hash_collision_does_not_alias_responses)
+{
+ auto disk_cache = MUST(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();
+ TestCacheRequest request;
+ auto a = parse_url("https://b.example/a15233b41c58b0cc"sv);
+ auto b = parse_url("https://a.example/3a0fafd1c5bfae49"sv);
+ auto headers = create_cacheable_request_headers();
+ auto response_a = create_cacheable_response_headers();
+ response_a->append({ "X-Identity"sv, "A"sv });
+ auto response_b = create_cacheable_response_headers();
+ response_b->append({ "X-Identity"sv, "B"sv });
+ store_cache_entry(disk_cache, request, a, *headers, response_a, "response A"sv);
+ auto unexpected = open_cache_entry(disk_cache, request, b, *headers);
+ EXPECT(!unexpected.has_value());
+ if (unexpected.has_value())
+ disk_cache.close_entries_read_by(request);
+ store_cache_entry(disk_cache, request, b, *headers, response_b, "response B"sv);
+ for (auto which : { 0, 1 }) {
+ auto const& url = which == 0 ? a : b;
+ auto expected = which == 0 ? "response A"sv : "response B"sv;
+ auto reader = open_cache_entry(disk_cache, request, url, *headers);
+ VERIFY(reader.has_value());
+ EXPECT_EQ(reader->response_headers().get("X-Identity"sv), Optional<ByteString> { which == 0 ? "A" : "B" });
+ auto file = TRY_OR_FAIL(reader->take_body_file());
+ auto body = TRY_OR_FAIL(Core::ImmutableBytes::map_from_fd_range_and_close(file.fd, "collision body"sv, file.offset, file.size));
+ EXPECT_EQ(body.bytes(), expected.bytes());
+ }
+ disk_cache.invalidate(test_partition(), a);
+ EXPECT(!open_cache_entry(disk_cache, request, a, *headers).has_value());
+ EXPECT(open_cache_entry(disk_cache, request, b, *headers).has_value());
+}
+
+TEST_CASE(different_resources_do_not_share_writer_activity_or_locks)
+{
+ auto disk_cache = TRY_OR_FAIL(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();
+ TestCacheRequest request_a;
+ TestCacheRequest request_b;
+ auto a = parse_url("https://b.example/a15233b41c58b0cc"sv);
+ auto b = parse_url("https://a.example/3a0fafd1c5bfae49"sv);
+ auto headers = create_cacheable_request_headers();
+ request_a.activity = MonotonicTime::now();
+ auto& writer_a = create_cache_entry(disk_cache, request_a, a, *headers);
+ EXPECT(disk_cache.last_activity_time_of_open_entries(test_partition(), a, "GET"sv) == request_a.activity);
+ EXPECT(!disk_cache.last_activity_time_of_open_entries(test_partition(), b, "GET"sv).has_value());
+ // This helper fails if B is queued behind A, as happens with the legacy collision.
+ auto& writer_b = create_cache_entry(disk_cache, request_b, b, *headers);
+ TRY_OR_FAIL(writer_a.write_status_and_reason(200, "OK"_string, *headers, *create_cacheable_response_headers()));
+ TRY_OR_FAIL(writer_b.write_status_and_reason(200, "OK"_string, *headers, *create_cacheable_response_headers()));
+ disk_cache.invalidate(test_partition(), a);
+ EXPECT(writer_a.write_data("A"sv.bytes()).is_error());
+ TRY_OR_FAIL(writer_b.write_data("B"sv.bytes()));
+ TRY_OR_FAIL(writer_b.flush(create_cacheable_request_headers()));
+ EXPECT(open_cache_entry(disk_cache, request_b, b, *headers).has_value());
+}
+
+TEST_CASE(waiters_are_resumed_only_when_their_exact_resource_closes)
+{
+ Core::EventLoop event_loop;
+ auto disk_cache = TRY_OR_FAIL(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();
+ TestCacheRequest holder_a;
+ TestCacheRequest holder_b;
+ TestCacheRequest waiter_a;
+ TestCacheRequest waiter_b;
+ auto a = parse_url("https://b.example/a15233b41c58b0cc"sv);
+ auto b = parse_url("https://a.example/3a0fafd1c5bfae49"sv);
+ auto headers = create_cacheable_request_headers();
+ auto& writer_a = create_cache_entry(disk_cache, holder_a, a, *headers);
+ auto& writer_b = create_cache_entry(disk_cache, holder_b, b, *headers);
+ for (auto which : { 0, 1 }) {
+ auto& waiter = which == 0 ? waiter_a : waiter_b;
+ auto const& url = which == 0 ? a : b;
+ auto result = disk_cache.create_entry(waiter, test_partition(), url, "GET"sv, *headers, UnixDateTime::now());
+ EXPECT(result.has<HTTP::DiskCache::CacheHasOpenEntry>());
+ }
+ writer_a.remove_incomplete_entry();
+ event_loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT_EQ(waiter_a.unblocked_count, 1u);
+ EXPECT_EQ(waiter_b.unblocked_count, 0u);
+ writer_b.remove_incomplete_entry();
+ event_loop.pump(Core::EventLoop::WaitMode::PollForEvents);
+ EXPECT_EQ(waiter_b.unblocked_count, 1u);
+}
+
+TEST_CASE(cache_file_for_another_url_is_not_served)
+{
+ auto disk_cache = TRY_OR_FAIL(HTTP::DiskCache::create(HTTP::DiskCache::Mode::Testing, test_cache_root())).release_value();
+ auto url = parse_url("https://example.com/a"sv);
+ auto other_url = "https://example.com/b"_string;
+ auto headers = create_cacheable_request_headers();
+ TestCacheRequest request;
+ store_cache_entry(disk_cache, request, url, *headers, create_cacheable_response_headers(), "body"sv);
+ auto cache_key = HTTP::create_cache_key(test_partition(), HTTP::serialize_url_for_cache_storage(url), "GET"sv);
+ auto path = HTTP::path_for_cache_entry(disk_cache.cache_directory(), cache_key, {});
+ {
+ auto file = TRY_OR_FAIL(Core::File::open(path.string(), Core::File::OpenMode::ReadWrite));
+ auto header = TRY_OR_FAIL(file->read_value<HTTP::CacheHeader>());
+ header.url_hash = other_url.hash();
+ (void)TRY_OR_FAIL(file->seek(0, SeekMode::SetPosition));
+ TRY_OR_FAIL(file->write_value(header));
+ TRY_OR_FAIL(file->write_until_depleted(other_url));
+ }
+ EXPECT(!open_cache_entry(disk_cache, request, url, *headers).has_value());
+ EXPECT(!FileSystem::exists(path.string()));
+}