| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using Microsoft.Net.Http.Headers; |
| | | 4 | | |
| | | 5 | | namespace Kestrun.Utilities; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Helper for writing conditional 304 Not Modified responses based on ETag and Last-Modified headers. |
| | | 9 | | /// </summary> |
| | | 10 | | internal static class CacheRevalidation |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Returns true if a 304 Not Modified was written. Otherwise sets validators on the response and returns false. |
| | | 14 | | /// Does NOT write a body on miss; the caller should write the payload/status. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <param name="ctx">The current HTTP context.</param> |
| | | 17 | | /// <param name="payload">The response payload, used to derive an ETag if none is provided. Can be a byte[], ReadOnl |
| | | 18 | | /// <param name="etag">An optional ETag to use. If not provided, an ETag is derived from the payload if possible. Qu |
| | | 19 | | /// <param name="weakETag">If true, the provided or derived ETag is marked as weak (prefixed with W/).</param> |
| | | 20 | | /// <param name="lastModified">An optional Last-Modified timestamp to use.</param> |
| | | 21 | | /// <returns>True if a 304 Not Modified was written; otherwise false.</returns> |
| | | 22 | | public static bool TryWrite304( |
| | | 23 | | HttpContext ctx, |
| | | 24 | | object? payload, |
| | | 25 | | string? etag = null, |
| | | 26 | | bool weakETag = false, |
| | | 27 | | DateTimeOffset? lastModified = null) |
| | | 28 | | { |
| | 16 | 29 | | var req = ctx.Request; |
| | 16 | 30 | | var resp = ctx.Response; |
| | 16 | 31 | | var isSafe = IsSafeMethod(req.Method); |
| | | 32 | | |
| | | 33 | | // 1. Normalize or derive ETag |
| | 16 | 34 | | var normalizedETag = GetOrDeriveETag(etag, payload, req, weakETag); |
| | | 35 | | |
| | | 36 | | // 2. If-None-Match precedence |
| | 16 | 37 | | if (isSafe && ETagMatchesClient(req, normalizedETag)) |
| | | 38 | | { |
| | 1 | 39 | | WriteValidators(resp, normalizedETag, lastModified); |
| | 1 | 40 | | resp.StatusCode = StatusCodes.Status304NotModified; |
| | 1 | 41 | | return true; |
| | | 42 | | } |
| | | 43 | | |
| | | 44 | | // 3. If-Modified-Since fallback |
| | 15 | 45 | | if (isSafe && LastModifiedSatisfied(req, lastModified)) |
| | | 46 | | { |
| | 1 | 47 | | WriteValidators(resp, normalizedETag, lastModified); |
| | 1 | 48 | | resp.StatusCode = StatusCodes.Status304NotModified; |
| | 1 | 49 | | return true; |
| | | 50 | | } |
| | | 51 | | |
| | | 52 | | // 4. Miss - set validators for fresh response |
| | 14 | 53 | | WriteValidators(resp, normalizedETag, lastModified); |
| | 14 | 54 | | return false; |
| | | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <summary>Determines if the HTTP method is cache validator safe (GET/HEAD).</summary> |
| | 16 | 58 | | private static bool IsSafeMethod(string method) => HttpMethods.IsGet(method) || HttpMethods.IsHead(method); |
| | | 59 | | |
| | | 60 | | /// <summary>Returns provided ETag (normalized) or derives one from payload if absent.</summary> |
| | | 61 | | private static string? GetOrDeriveETag(string? etag, object? payload, HttpRequest req, bool weak) |
| | | 62 | | { |
| | 16 | 63 | | var normalized = NormalizeETag(etag); |
| | 16 | 64 | | if (normalized is null && payload is not null) |
| | | 65 | | { |
| | 16 | 66 | | var bytes = ExtractBytesFromPayload(payload, req); |
| | 16 | 67 | | normalized = ComputeETagFromBytes(bytes, weakETag: false); // derive strong first |
| | | 68 | | } |
| | 16 | 69 | | if (weak && normalized is not null && !normalized.StartsWith("W/", StringComparison.Ordinal)) |
| | | 70 | | { |
| | 1 | 71 | | normalized = "W/" + normalized; |
| | | 72 | | } |
| | 16 | 73 | | return normalized; |
| | | 74 | | } |
| | | 75 | | |
| | | 76 | | /// <summary>Extracts a raw byte array from supported payload types or throws.</summary> |
| | | 77 | | private static byte[] ExtractBytesFromPayload(object payload, HttpRequest req) |
| | | 78 | | { |
| | 16 | 79 | | return payload switch |
| | 16 | 80 | | { |
| | 3 | 81 | | byte[] b => b, |
| | 1 | 82 | | ReadOnlyMemory<byte> rom => rom.ToArray(), |
| | 1 | 83 | | Memory<byte> mem => mem.ToArray(), |
| | 1 | 84 | | ArraySegment<byte> seg => seg.Array is null ? [] : seg.Array.AsSpan(seg.Offset, seg.Count).ToArray(), |
| | 9 | 85 | | string text => ChooseEncodingFromAcceptCharset(req.Headers[HeaderNames.AcceptCharset]).GetBytes(text), |
| | 1 | 86 | | Stream s => ReadAllBytesPreservePosition(s), |
| | 0 | 87 | | IFormFile formFile => ReadAllBytesFromFormFile(formFile), |
| | 0 | 88 | | _ => throw new ArgumentException( |
| | 0 | 89 | | $"Cannot derive bytes from payload of type '{payload.GetType().FullName}'. Provide an explicit ETag or p |
| | 16 | 90 | | }; |
| | | 91 | | } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Reads all bytes from an IFormFile, disposing the stream after reading. |
| | | 95 | | /// </summary> |
| | | 96 | | private static byte[] ReadAllBytesFromFormFile(IFormFile formFile) |
| | | 97 | | { |
| | 0 | 98 | | using var stream = formFile.OpenReadStream(); |
| | 0 | 99 | | return ReadAllBytesPreservePosition(stream); |
| | 0 | 100 | | } |
| | | 101 | | /// <summary>Determines whether client's If-None-Match header matches the normalized ETag (or *).</summary> |
| | | 102 | | private static bool ETagMatchesClient(HttpRequest req, string? normalizedETag) |
| | | 103 | | { |
| | 6 | 104 | | return normalizedETag is not null && req.Headers.TryGetValue(HeaderNames.IfNoneMatch, out var inm) && |
| | 7 | 105 | | inm.Any(v => !string.IsNullOrEmpty(v) && |
| | 7 | 106 | | v.Split(',', StringSplitOptions.RemoveEmptyEntries) |
| | 1 | 107 | | .Select(t => t.Trim()) |
| | 8 | 108 | | .Any(tok => tok == normalizedETag || tok == "*")); |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | /// <summary>Checks If-Modified-Since header against lastModified (second precision).</summary> |
| | | 112 | | private static bool LastModifiedSatisfied(HttpRequest req, DateTimeOffset? lastModified) |
| | | 113 | | { |
| | 5 | 114 | | if (!lastModified.HasValue) |
| | | 115 | | { |
| | 4 | 116 | | return false; |
| | | 117 | | } |
| | 1 | 118 | | if (!req.Headers.TryGetValue(HeaderNames.IfModifiedSince, out var imsRaw)) |
| | | 119 | | { |
| | 0 | 120 | | return false; |
| | | 121 | | } |
| | 1 | 122 | | if (!DateTimeOffset.TryParse(imsRaw, out var ims)) |
| | | 123 | | { |
| | 0 | 124 | | return false; |
| | | 125 | | } |
| | 1 | 126 | | var imsTrunc = TruncateToSeconds(ims.ToUniversalTime()); |
| | 1 | 127 | | var lmTrunc = TruncateToSeconds(lastModified.Value.ToUniversalTime()); |
| | 1 | 128 | | return lmTrunc <= imsTrunc; |
| | | 129 | | } |
| | | 130 | | |
| | | 131 | | /// <summary> |
| | | 132 | | /// Computes a strong or weak ETag from the given byte data using SHA-256 hashing. |
| | | 133 | | /// </summary> |
| | | 134 | | /// <param name="data">The byte data to hash.</param> |
| | | 135 | | /// <param name="weakETag">If true, the resulting ETag is marked as weak (prefixed with W/).</param> |
| | | 136 | | /// <returns>The computed ETag string, including quotes.</returns> |
| | | 137 | | private static string ComputeETagFromBytes(ReadOnlySpan<byte> data, bool weakETag) |
| | | 138 | | { |
| | 16 | 139 | | var hash = SHA256.HashData(data.ToArray()); |
| | 16 | 140 | | var tag = $"\"{Convert.ToHexString(hash).ToLowerInvariant()}\""; |
| | 16 | 141 | | return weakETag ? "W/" + tag : tag; |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | // ---- helpers ---- |
| | | 145 | | private static string? NormalizeETag(string? raw) |
| | | 146 | | { |
| | 16 | 147 | | if (string.IsNullOrWhiteSpace(raw)) |
| | | 148 | | { |
| | 16 | 149 | | return null; |
| | | 150 | | } |
| | | 151 | | |
| | 0 | 152 | | var v = raw.Trim(); |
| | 0 | 153 | | return v.StartsWith("W/", StringComparison.Ordinal) |
| | 0 | 154 | | ? v |
| | 0 | 155 | | : v.StartsWith('"') && v.EndsWith('"') ? v : $"\"{v}\""; |
| | | 156 | | } |
| | | 157 | | private static void WriteValidators(HttpResponse resp, string? etag, DateTimeOffset? lastModified) |
| | | 158 | | { |
| | 16 | 159 | | if (etag is not null) |
| | | 160 | | { |
| | 16 | 161 | | resp.Headers[HeaderNames.ETag] = etag; |
| | | 162 | | } |
| | | 163 | | |
| | 16 | 164 | | if (lastModified.HasValue) |
| | | 165 | | { |
| | 2 | 166 | | resp.Headers[HeaderNames.LastModified] = lastModified.Value.ToString("R"); |
| | | 167 | | } |
| | 16 | 168 | | } |
| | | 169 | | |
| | | 170 | | private static DateTimeOffset TruncateToSeconds(DateTimeOffset dto) |
| | 2 | 171 | | => dto.Subtract(TimeSpan.FromTicks(dto.Ticks % TimeSpan.TicksPerSecond)); |
| | | 172 | | private static byte[] ReadAllBytesPreservePosition(Stream s) |
| | | 173 | | { |
| | 1 | 174 | | if (s is MemoryStream ms && ms.TryGetBuffer(out var seg)) |
| | | 175 | | { |
| | 0 | 176 | | return [.. seg]; |
| | | 177 | | } |
| | | 178 | | |
| | 1 | 179 | | long? pos = s.CanSeek ? s.Position : null; |
| | 1 | 180 | | using var buffer = new MemoryStream(); |
| | 1 | 181 | | s.CopyTo(buffer); |
| | 1 | 182 | | var bytes = buffer.ToArray(); |
| | 1 | 183 | | if (pos is not null && s.CanSeek) |
| | | 184 | | { |
| | 1 | 185 | | s.Position = pos.Value; |
| | | 186 | | } |
| | | 187 | | |
| | 1 | 188 | | return bytes; |
| | 1 | 189 | | } |
| | | 190 | | |
| | | 191 | | /// <summary> |
| | | 192 | | /// Chooses an encoding from the Accept-Charset header value. Defaults to UTF-8 if no match found or header missing. |
| | | 193 | | /// Supports a small set of common charsets; extend the Map function as needed. |
| | | 194 | | /// Supports q-values and wildcard. E.g., "utf-8;q=0.9, iso-8859-1;q=0.5, *;q=0.1" |
| | | 195 | | /// </summary> |
| | | 196 | | /// <param name="acceptCharset">The Accept-Charset header value.</param> |
| | | 197 | | /// <returns>The chosen encoding.</returns> |
| | | 198 | | private static Encoding ChooseEncodingFromAcceptCharset(Microsoft.Extensions.Primitives.StringValues acceptCharset) |
| | | 199 | | { |
| | 9 | 200 | | if (acceptCharset.Count == 0) |
| | | 201 | | { |
| | 6 | 202 | | return Encoding.UTF8; // Fast path: header missing |
| | | 203 | | } |
| | | 204 | | |
| | 3 | 205 | | var candidates = ParseAcceptCharsetHeader(acceptCharset); |
| | 7 | 206 | | var (best, _) = SelectBestEncodingCandidate(candidates, static n => MapEncodingName(n)); |
| | 3 | 207 | | return best ?? Encoding.UTF8; |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | /// <summary> |
| | | 211 | | /// Maps a charset token to an <see cref="Encoding"/> instance if it is recognized, otherwise null. |
| | | 212 | | /// </summary> |
| | 4 | 213 | | private static Encoding? MapEncodingName(string name) => name.ToLowerInvariant() switch |
| | 4 | 214 | | { |
| | 1 | 215 | | "utf-8" or "utf8" => Encoding.UTF8, |
| | 1 | 216 | | "utf-16" => Encoding.Unicode, |
| | 0 | 217 | | "utf-16le" => Encoding.Unicode, |
| | 0 | 218 | | "utf-16be" => Encoding.BigEndianUnicode, |
| | 1 | 219 | | "iso-8859-1" => Encoding.GetEncoding("iso-8859-1"), |
| | 0 | 220 | | "us-ascii" or "ascii" => Encoding.ASCII, |
| | 1 | 221 | | _ => null |
| | 4 | 222 | | }; |
| | | 223 | | |
| | | 224 | | /// <summary> |
| | | 225 | | /// Parses an Accept-Charset header (possibly multi-valued) into a sequence of (name,q) tuples. |
| | | 226 | | /// Assumes implicit q=1.0 when missing; ignores empty tokens. |
| | | 227 | | /// </summary> |
| | | 228 | | private static IEnumerable<(string name, double q)> ParseAcceptCharsetHeader(Microsoft.Extensions.Primitives.StringV |
| | | 229 | | { |
| | 3 | 230 | | return values |
| | 3 | 231 | | .SelectMany(static line => line?.Split(',') ?? []) |
| | 3 | 232 | | .Select(static tok => |
| | 3 | 233 | | { |
| | 5 | 234 | | var t = tok.Trim(); |
| | 5 | 235 | | if (string.IsNullOrEmpty(t)) |
| | 3 | 236 | | { |
| | 0 | 237 | | return (name: string.Empty, q: 0.0); |
| | 3 | 238 | | } |
| | 3 | 239 | | |
| | 5 | 240 | | var parts = t.Split(';', 2, StringSplitOptions.TrimEntries); |
| | 5 | 241 | | var name = parts[0].ToLowerInvariant(); |
| | 5 | 242 | | var q = 1.0; |
| | 5 | 243 | | if (parts.Length == 2 && parts[1].StartsWith("q=", StringComparison.OrdinalIgnoreCase) && |
| | 5 | 244 | | double.TryParse(parts[1].AsSpan(2), out var qv)) |
| | 3 | 245 | | { |
| | 5 | 246 | | q = qv; |
| | 3 | 247 | | } |
| | 5 | 248 | | return (name, q); |
| | 3 | 249 | | }) |
| | 8 | 250 | | .Where(static x => x.name.Length > 0); |
| | | 251 | | } |
| | | 252 | | |
| | | 253 | | /// <summary> |
| | | 254 | | /// Selects the highest q-valued encoding candidate from the provided sequence. |
| | | 255 | | /// Wildcard (*) yields UTF-8 at the given q if no prior candidate chosen. |
| | | 256 | | /// </summary> |
| | | 257 | | /// <param name="candidates">Sequence of (name,q) pairs.</param> |
| | | 258 | | /// <param name="resolver">Function mapping charset name to Encoding (may return null).</param> |
| | | 259 | | /// <returns>Tuple of best encoding (or null) and its q value.</returns> |
| | | 260 | | private static (Encoding? best, double q) SelectBestEncodingCandidate( |
| | | 261 | | IEnumerable<(string name, double q)> candidates, |
| | | 262 | | Func<string, Encoding?> resolver) |
| | | 263 | | { |
| | 3 | 264 | | Encoding? best = null; |
| | 3 | 265 | | double bestQ = -1; |
| | 16 | 266 | | foreach (var (name, q) in candidates) |
| | | 267 | | { |
| | 5 | 268 | | if (name == "*") |
| | | 269 | | { |
| | 1 | 270 | | if (best is null) |
| | | 271 | | { |
| | 2 | 272 | | best = Encoding.UTF8; bestQ = q; |
| | | 273 | | } |
| | 1 | 274 | | continue; |
| | | 275 | | } |
| | 4 | 276 | | var enc = resolver(name); |
| | 4 | 277 | | if (enc is not null && q > bestQ) |
| | | 278 | | { |
| | 6 | 279 | | best = enc; bestQ = q; |
| | | 280 | | } |
| | | 281 | | } |
| | 3 | 282 | | return (best, bestQ); |
| | | 283 | | } |
| | | 284 | | } |