OdbDesign
OdbDesign ODB++ Parser - C++ library, gRPC/REST server, CLI, tests
 
Loading...
Searching...
No Matches
ETag.h
Go to the documentation of this file.
1#pragma once
2
3// Strong ETag support for the per-design HTTP data endpoints (M1.3).
4//
5// An ETag binds the design name, the design archive file's mtime and size, the
6// per-design cache invalidation generation, and the endpoint path with an
7// FNV-1a 64-bit hash, rendered as a quoted lowercase hex string
8// ("a1b2c3d4e5f60718").
9//
10// Invalidation contract: replacing or re-uploading a design archive changes
11// the on-disk mtime/size, and in-memory replacements (POST /filemodels with
12// save=false, upload-overwrite invalidation) bump the cache invalidation
13// generation — either way the tag changes with no explicit invalidation step,
14// so a client revalidating with the stale tag's If-None-Match no longer
15// matches and receives a fresh 200.
16//
17// Gzip interplay: the tag is the strong validator of the UNCOMPRESSED
18// representation. It is computed before Crow serializes the body, hence also
19// before Crow compresses it for the wire, so it does not vary with the
20// content-coding (a strong variant of the uncompressed representation).
21
22#include <cctype>
23#include <cstdint>
24#include <cstring>
25#include <filesystem>
26#include <string>
27#include <string_view>
28#include <system_error>
29
30namespace Utils
31{
32 constexpr inline std::uint64_t FNV1A64_OFFSET_BASIS = 14695981039346656037ull;
33 constexpr inline std::uint64_t FNV1A64_PRIME = 1099511628211ull;
34
35 // FNV-1a 64-bit over sizeBytes bytes at data, continuing from hash
36 // (defaults to the offset basis, i.e. start of a fresh digest).
37 inline std::uint64_t Fnv1a64(const char* data, std::size_t sizeBytes, std::uint64_t hash = FNV1A64_OFFSET_BASIS)
38 {
39 for (std::size_t i = 0; i < sizeBytes; ++i)
40 {
41 hash ^= static_cast<unsigned char>(data[i]);
42 hash *= FNV1A64_PRIME;
43 }
44 return hash;
45 }
46
47 // Builds the quoted ETag string from the raw hashed fields.
48 // Exposed separately from MakeDesignEtag so tests can pin the digest
49 // behavior (determinism, field sensitivity, formatting) without files.
50 // generation: the design's cache invalidation generation (0 = no
51 // in-memory invalidation has occurred); folded into the digest so
52 // cache-only changes (POST /filemodels with save=false) rotate the tag.
53 inline std::string MakeEtag(const std::string& designName, std::int64_t mtimeTicks, std::uint64_t sizeBytes, const std::string& endpointPath, std::uint64_t generation = 0)
54 {
55 auto hash = Fnv1a64(designName.data(), designName.size());
56 hash = Fnv1a64(reinterpret_cast<const char*>(&mtimeTicks), sizeof(mtimeTicks), hash);
57 hash = Fnv1a64(reinterpret_cast<const char*>(&sizeBytes), sizeof(sizeBytes), hash);
58 hash = Fnv1a64(endpointPath.data(), endpointPath.size(), hash);
59 hash = Fnv1a64(reinterpret_cast<const char*>(&generation), sizeof(generation), hash);
60
61 static constexpr char HEX_DIGITS[] = "0123456789abcdef";
62 std::string tag;
63 tag.reserve(18);
64 tag += '"';
65 for (int shift = 60; shift >= 0; shift -= 4)
66 {
67 tag += HEX_DIGITS[(hash >> shift) & 0xF];
68 }
69 tag += '"';
70 return tag;
71 }
72
73 // Locates the design's archive file exactly the way DesignCache does when
74 // serving (DesignCache::FindArchivePath): the first regular file in the
75 // designs directory whose path stem matches designName (the stem strips
76 // only the LAST extension — "foo.tar.gz" has stem "foo.tar"). Keeping the
77 // two resolvers identical is what makes the validator attest the same
78 // archive that is served; a divergent extension-stripping rule here would
79 // let the tag name a different file than the one behind the body. The
80 // stem comparison is case-sensitive, mirroring DesignCache's lookup.
81 // Returns an empty path when no archive matches or the directory cannot
82 // be read.
83 inline std::filesystem::path FindDesignArchiveFile(const std::string& designsDir, const std::string& designName)
84 {
85 if (designsDir.empty() || designName.empty())
86 {
87 return {};
88 }
89
90 std::error_code ec;
91 std::filesystem::directory_iterator dirIt(designsDir, std::filesystem::directory_options::skip_permission_denied, ec);
92 if (ec)
93 {
94 return {};
95 }
96
97 for (const auto& entry : dirIt)
98 {
99 if (!entry.is_regular_file(ec) || ec)
100 {
101 ec.clear();
102 continue;
103 }
104
105 if (entry.path().stem() == designName)
106 {
107 return entry.path();
108 }
109 }
110
111 return {};
112 }
113
114 // Computes the strong ETag for a per-design data endpoint: locates the
115 // design's archive file under designsDir and hashes (design name, archive
116 // mtime, archive size, endpoint path, cache invalidation generation).
117 // Returns the quoted tag, or an empty string when the archive file cannot
118 // be found or stat'ed — the endpoint will 404 on load in that case, so no
119 // caching headers are emitted.
120 inline std::string MakeDesignEtag(const std::string& designsDir, const std::string& designName, const std::string& endpointPath, std::uint64_t generation = 0)
121 {
122 const auto archivePath = FindDesignArchiveFile(designsDir, designName);
123 if (archivePath.empty())
124 {
125 return "";
126 }
127
128 std::error_code ec;
129 const auto mtime = std::filesystem::last_write_time(archivePath, ec);
130 if (ec)
131 {
132 return "";
133 }
134 const auto sizeBytes = std::filesystem::file_size(archivePath, ec);
135 if (ec)
136 {
137 return "";
138 }
139
140 // file_time_type ticks are stable across server restarts on a given
141 // platform, which is all an ETag requires: it is only ever compared
142 // against itself, never interpreted as a timestamp.
143 const auto mtimeTicks = static_cast<std::int64_t>(mtime.time_since_epoch().count());
144 return MakeEtag(designName, mtimeTicks, sizeBytes, endpointPath, generation);
145 }
146
147 // RFC 7232 If-None-Match evaluation using weak comparison (the spec mandates
148 // weak comparison for If-None-Match even against strong validators like
149 // ours): the header may be "*" (matches any current representation) or a
150 // comma-separated list of entity-tags, each optionally weak-prefixed
151 // (W/"..."); comparison covers the opaque quoted part only.
152 inline bool IfNoneMatchMatches(const std::string& header, const std::string& etag)
153 {
154 if (header.empty() || etag.empty())
155 {
156 return false;
157 }
158
159 constexpr const char* OWS = " \t";
160 std::size_t start = 0;
161 while (start <= header.size())
162 {
163 const auto comma = header.find(',', start);
164 const auto end = (comma == std::string::npos) ? header.size() : comma;
165
166 auto tokenStart = start;
167 auto tokenEnd = end;
168 while (tokenStart < tokenEnd && std::strchr(OWS, header[tokenStart]) != nullptr) ++tokenStart;
169 while (tokenEnd > tokenStart && std::strchr(OWS, header[tokenEnd - 1]) != nullptr) --tokenEnd;
170 auto token = header.substr(tokenStart, tokenEnd - tokenStart);
171
172 if (token.size() >= 2 && (token[0] == 'W' || token[0] == 'w') && token[1] == '/')
173 {
174 token = token.substr(2);
175 }
176
177 if (token == "*" || token == etag)
178 {
179 return true;
180 }
181
182 if (comma == std::string::npos)
183 {
184 break;
185 }
186 start = comma + 1;
187 }
188
189 return false;
190 }
191}
std::uint64_t Fnv1a64(const char *data, std::size_t sizeBytes, std::uint64_t hash=FNV1A64_OFFSET_BASIS)
Definition ETag.h:37
bool IfNoneMatchMatches(const std::string &header, const std::string &etag)
Definition ETag.h:152
std::filesystem::path FindDesignArchiveFile(const std::string &designsDir, const std::string &designName)
Definition ETag.h:83
std::string MakeDesignEtag(const std::string &designsDir, const std::string &designName, const std::string &endpointPath, std::uint64_t generation=0)
Definition ETag.h:120
std::string MakeEtag(const std::string &designName, std::int64_t mtimeTicks, std::uint64_t sizeBytes, const std::string &endpointPath, std::uint64_t generation=0)
Definition ETag.h:53
constexpr std::uint64_t FNV1A64_PRIME
Definition ETag.h:33
constexpr std::uint64_t FNV1A64_OFFSET_BASIS
Definition ETag.h:32