| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Text; |
| | | 3 | | using Kestrun.Logging; |
| | | 4 | | using Microsoft.AspNetCore.Http.Features; |
| | | 5 | | using Microsoft.AspNetCore.WebUtilities; |
| | | 6 | | using Microsoft.Net.Http.Headers; |
| | | 7 | | using Serilog; |
| | | 8 | | using Serilog.Events; |
| | | 9 | | using Logger = Serilog.ILogger; |
| | | 10 | | |
| | | 11 | | namespace Kestrun.Forms; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Parses incoming form payloads into normalized form payloads. |
| | | 15 | | /// </summary> |
| | | 16 | | public static class KrFormParser |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Parses the incoming request into a normalized form payload. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="context">The HTTP context.</param> |
| | | 22 | | /// <param name="options">The form parsing options.</param> |
| | | 23 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 24 | | /// <returns>The parsed payload.</returns> |
| | | 25 | | public static async Task<IKrFormPayload> ParseAsync(HttpContext context, KrFormOptions options, CancellationToken ca |
| | | 26 | | { |
| | 8 | 27 | | ArgumentNullException.ThrowIfNull(context); |
| | 8 | 28 | | ArgumentNullException.ThrowIfNull(options); |
| | | 29 | | |
| | 8 | 30 | | var logger = ResolveLogger(context, options); |
| | 8 | 31 | | using var _ = logger.BeginTimedOperation("KrFormParser.ParseAsync"); |
| | | 32 | | |
| | 8 | 33 | | var (mediaType, normalizedMediaType) = ValidateAndNormalizeMediaType(context, options, logger); |
| | 6 | 34 | | ApplyRequestBodyLimit(context, options, logger); |
| | | 35 | | |
| | 6 | 36 | | return await ParseByContentTypeAsync(context, mediaType, normalizedMediaType, options, logger, cancellationToken |
| | 6 | 37 | | .ConfigureAwait(false); |
| | 5 | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Resolves the logger to use for form parsing. |
| | | 42 | | /// </summary> |
| | | 43 | | /// <param name="context">The HTTP context.</param> |
| | | 44 | | /// <param name="options">The form parsing options.</param> |
| | | 45 | | /// <returns>The resolved logger.</returns> |
| | | 46 | | private static Logger ResolveLogger(HttpContext context, KrFormOptions options) |
| | | 47 | | { |
| | 8 | 48 | | return options.Logger |
| | 8 | 49 | | ?? context.RequestServices.GetService(typeof(Serilog.ILogger)) as Serilog.ILogger |
| | 8 | 50 | | ?? Log.Logger; |
| | | 51 | | } |
| | | 52 | | |
| | | 53 | | /// <summary> |
| | | 54 | | /// Validates the Content-Type header and returns the parsed and normalized media type. |
| | | 55 | | /// </summary> |
| | | 56 | | /// <param name="context">The HTTP context.</param> |
| | | 57 | | /// <param name="options">The form parsing options.</param> |
| | | 58 | | /// <param name="logger">The logger.</param> |
| | | 59 | | /// <returns>The parsed media type and normalized media type string.</returns> |
| | | 60 | | private static (MediaTypeHeaderValue MediaType, string NormalizedMediaType) ValidateAndNormalizeMediaType( |
| | | 61 | | HttpContext context, |
| | | 62 | | KrFormOptions options, |
| | | 63 | | Logger logger) |
| | | 64 | | { |
| | 8 | 65 | | var contentTypeHeader = context.Request.ContentType; |
| | 8 | 66 | | var contentEncoding = context.Request.Headers[HeaderNames.ContentEncoding].ToString(); |
| | 8 | 67 | | var requestDecompressionEnabled = DetectRequestDecompressionEnabled(context); |
| | 8 | 68 | | if (logger.IsEnabled(LogEventLevel.Debug)) |
| | | 69 | | { |
| | 0 | 70 | | logger.DebugSanitized( |
| | 0 | 71 | | "Form route start: Content-Type={ContentType}, Content-Encoding={ContentEncoding}, RequestDecompressionE |
| | 0 | 72 | | contentTypeHeader, |
| | 0 | 73 | | string.IsNullOrWhiteSpace(contentEncoding) ? "<none>" : contentEncoding, |
| | 0 | 74 | | requestDecompressionEnabled); |
| | | 75 | | } |
| | | 76 | | |
| | 8 | 77 | | if (string.IsNullOrWhiteSpace(contentTypeHeader)) |
| | | 78 | | { |
| | 0 | 79 | | logger.Error("Missing Content-Type header for form parsing."); |
| | 0 | 80 | | throw new KrFormException("Content-Type header is required for form parsing.", StatusCodes.Status415Unsuppor |
| | | 81 | | } |
| | | 82 | | |
| | 8 | 83 | | if (!MediaTypeHeaderValue.TryParse(contentTypeHeader, out var mediaType)) |
| | | 84 | | { |
| | 0 | 85 | | logger.WarningSanitized("Invalid Content-Type header: {ContentType}", contentTypeHeader); |
| | 0 | 86 | | throw new KrFormException("Invalid Content-Type header.", StatusCodes.Status415UnsupportedMediaType); |
| | | 87 | | } |
| | | 88 | | |
| | 8 | 89 | | var normalizedMediaType = mediaType.MediaType.Value ?? string.Empty; |
| | 8 | 90 | | if (!IsAllowedRequestContentType(normalizedMediaType, options.AllowedRequestContentTypes)) |
| | | 91 | | { |
| | 1 | 92 | | if (options.RejectUnknownRequestContentType) |
| | | 93 | | { |
| | 1 | 94 | | logger.Error("Rejected request Content-Type: {ContentType}", normalizedMediaType); |
| | 1 | 95 | | throw new KrFormException("Unsupported Content-Type for form parsing.", StatusCodes.Status415Unsupported |
| | | 96 | | } |
| | | 97 | | |
| | 0 | 98 | | logger.Warning("Unknown Content-Type allowed: {ContentType}", normalizedMediaType); |
| | | 99 | | } |
| | | 100 | | |
| | 7 | 101 | | if (IsMultipartContentType(normalizedMediaType) && !mediaType.Boundary.HasValue) |
| | | 102 | | { |
| | 1 | 103 | | logger.Error("Missing multipart boundary for Content-Type: {ContentType}", normalizedMediaType); |
| | 1 | 104 | | throw new KrFormException("Missing multipart boundary.", StatusCodes.Status400BadRequest); |
| | | 105 | | } |
| | | 106 | | |
| | 6 | 107 | | return (mediaType, normalizedMediaType); |
| | | 108 | | } |
| | | 109 | | |
| | | 110 | | /// <summary> |
| | | 111 | | /// Parses the request body based on the normalized content type. |
| | | 112 | | /// </summary> |
| | | 113 | | /// <param name="context">The HTTP context.</param> |
| | | 114 | | /// <param name="mediaType">The parsed media type.</param> |
| | | 115 | | /// <param name="normalizedMediaType">The normalized media type string.</param> |
| | | 116 | | /// <param name="options">The form parsing options.</param> |
| | | 117 | | /// <param name="logger">The logger.</param> |
| | | 118 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 119 | | /// <returns>The parsed payload.</returns> |
| | | 120 | | private static Task<IKrFormPayload> ParseByContentTypeAsync( |
| | | 121 | | HttpContext context, |
| | | 122 | | MediaTypeHeaderValue mediaType, |
| | | 123 | | string normalizedMediaType, |
| | | 124 | | KrFormOptions options, |
| | | 125 | | Logger logger, |
| | | 126 | | CancellationToken cancellationToken) |
| | | 127 | | { |
| | | 128 | | // application/x-www-form-urlencoded |
| | 6 | 129 | | if (normalizedMediaType.Equals("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) |
| | | 130 | | { |
| | 3 | 131 | | return ParseUrlEncodedAsync(context, options, logger, cancellationToken); |
| | | 132 | | } |
| | | 133 | | // multipart/form-data |
| | 3 | 134 | | if (normalizedMediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase)) |
| | | 135 | | { |
| | 0 | 136 | | return ParseMultipartFormDataAsync(context, mediaType, options, logger, cancellationToken); |
| | | 137 | | } |
| | | 138 | | // ordered multipart types |
| | 3 | 139 | | if (normalizedMediaType.StartsWith("multipart/", StringComparison.OrdinalIgnoreCase)) |
| | | 140 | | { |
| | 3 | 141 | | return ParseMultipartOrderedAsync(context, mediaType, options, logger, 0, cancellationToken); |
| | | 142 | | } |
| | | 143 | | // unsupported content type |
| | 0 | 144 | | throw new KrFormException("Unsupported Content-Type for form parsing.", StatusCodes.Status415UnsupportedMediaTyp |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary> |
| | | 148 | | /// Parses the incoming request into a normalized form payload. Synchronous wrapper. |
| | | 149 | | /// </summary> |
| | | 150 | | /// <param name="context">The HTTP context.</param> |
| | | 151 | | /// <param name="options">The form parsing options.</param> |
| | | 152 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 153 | | /// <returns>The parsed payload.</returns> |
| | | 154 | | public static IKrFormPayload Parse(HttpContext context, KrFormOptions options, CancellationToken cancellationToken) |
| | 0 | 155 | | ParseAsync(context, options, cancellationToken).GetAwaiter().GetResult(); |
| | | 156 | | |
| | | 157 | | /// <summary> |
| | | 158 | | /// Applies the request body size limit based on the provided options. |
| | | 159 | | /// </summary> |
| | | 160 | | /// <param name="context">The HTTP context of the current request.</param> |
| | | 161 | | /// <param name="options">The form parsing options containing limits.</param> |
| | | 162 | | /// <param name="logger">The logger for diagnostic messages.</param> |
| | | 163 | | private static void ApplyRequestBodyLimit(HttpContext context, KrFormOptions options, Logger logger) |
| | | 164 | | { |
| | 6 | 165 | | if (!options.Limits.MaxRequestBodyBytes.HasValue) |
| | | 166 | | { |
| | 0 | 167 | | return; |
| | | 168 | | } |
| | | 169 | | |
| | 6 | 170 | | var feature = context.Features.Get<IHttpMaxRequestBodySizeFeature>(); |
| | 6 | 171 | | if (feature == null || feature.IsReadOnly) |
| | | 172 | | { |
| | 6 | 173 | | logger.Debug("Request body size feature not available or read-only."); |
| | 6 | 174 | | return; |
| | | 175 | | } |
| | | 176 | | |
| | 0 | 177 | | feature.MaxRequestBodySize = options.Limits.MaxRequestBodyBytes; |
| | 0 | 178 | | logger.Debug("Set MaxRequestBodySize to {MaxBytes}", options.Limits.MaxRequestBodyBytes); |
| | 0 | 179 | | } |
| | | 180 | | |
| | | 181 | | private static async Task<IKrFormPayload> ParseUrlEncodedAsync(HttpContext context, KrFormOptions options, Logger lo |
| | | 182 | | { |
| | 3 | 183 | | var payload = new KrFormData(); |
| | 3 | 184 | | var form = await context.Request.ReadFormAsync(cancellationToken).ConfigureAwait(false); |
| | 12 | 185 | | foreach (var key in form.Keys) |
| | | 186 | | { |
| | | 187 | | payload.Fields[key] = [.. form[key].Select(static v => v ?? string.Empty)]; |
| | | 188 | | } |
| | | 189 | | |
| | 3 | 190 | | var rules = CreateRuleMap(options, isRoot: true, scopeName: null); |
| | 3 | 191 | | ValidateRequiredRules(payload, rules, logger); |
| | | 192 | | |
| | 3 | 193 | | logger.Information("Parsed x-www-form-urlencoded payload with {FieldCount} fields.", payload.Fields.Count); |
| | 3 | 194 | | return payload; |
| | 3 | 195 | | } |
| | | 196 | | |
| | | 197 | | /// <summary> |
| | | 198 | | /// Parses a multipart/form-data payload from the request. |
| | | 199 | | /// </summary> |
| | | 200 | | /// <param name="context">The HTTP context.</param> |
| | | 201 | | /// <param name="mediaType">The media type header value.</param> |
| | | 202 | | /// <param name="options">The form parsing options.</param> |
| | | 203 | | /// <param name="logger">The logger for diagnostic messages.</param> |
| | | 204 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 205 | | /// <returns>The parsed payload.</returns> |
| | | 206 | | /// <exception cref="KrFormLimitExceededException">Thrown when the multipart form exceeds configured limits.</except |
| | | 207 | | /// <exception cref="KrFormException">Thrown when a part is rejected by policy or other form errors occur.</exceptio |
| | | 208 | | private static async Task<IKrFormPayload> ParseMultipartFormDataAsync(HttpContext context, MediaTypeHeaderValue medi |
| | | 209 | | { |
| | 0 | 210 | | var boundary = GetBoundary(mediaType); |
| | 0 | 211 | | var reader = new MultipartReader(boundary, context.Request.Body) |
| | 0 | 212 | | { |
| | 0 | 213 | | HeadersLengthLimit = options.Limits.MaxHeaderBytesPerPart |
| | 0 | 214 | | }; |
| | | 215 | | |
| | 0 | 216 | | var payload = new KrFormData(); |
| | 0 | 217 | | var rules = CreateRuleMap(options, isRoot: true, scopeName: null); |
| | 0 | 218 | | var partIndex = 0; |
| | 0 | 219 | | long totalBytes = 0; |
| | 0 | 220 | | var stopwatch = Stopwatch.StartNew(); |
| | | 221 | | |
| | | 222 | | MultipartSection? section; |
| | 0 | 223 | | while ((section = await reader.ReadNextSectionAsync(cancellationToken).ConfigureAwait(false)) != null) |
| | | 224 | | { |
| | 0 | 225 | | partIndex++; |
| | 0 | 226 | | if (partIndex > options.Limits.MaxParts) |
| | | 227 | | { |
| | 0 | 228 | | logger.Error("Multipart form exceeded MaxParts limit ({MaxParts}).", options.Limits.MaxParts); |
| | 0 | 229 | | throw new KrFormLimitExceededException("Too many multipart sections."); |
| | | 230 | | } |
| | 0 | 231 | | var partContext = BuildFormDataPartContext(section, rules, partIndex, logger); |
| | 0 | 232 | | LogFormDataPartDebug(logger, partContext, partIndex - 1); |
| | | 233 | | |
| | 0 | 234 | | var contentEncoding = partContext.ContentEncoding; |
| | 0 | 235 | | if (await HandleFormDataPartActionAsync(section, options, partContext, logger, contentEncoding, cancellation |
| | | 236 | | { |
| | | 237 | | continue; |
| | | 238 | | } |
| | | 239 | | |
| | 0 | 240 | | if (IsFilePart(partContext.FileName)) |
| | | 241 | | { |
| | 0 | 242 | | totalBytes += await ProcessFormDataFilePartAsync( |
| | 0 | 243 | | section, |
| | 0 | 244 | | options, |
| | 0 | 245 | | payload, |
| | 0 | 246 | | partContext, |
| | 0 | 247 | | logger, |
| | 0 | 248 | | cancellationToken).ConfigureAwait(false); |
| | 0 | 249 | | continue; |
| | | 250 | | } |
| | | 251 | | |
| | 0 | 252 | | totalBytes += await ProcessFormDataFieldPartAsync( |
| | 0 | 253 | | section, |
| | 0 | 254 | | options, |
| | 0 | 255 | | payload, |
| | 0 | 256 | | partContext, |
| | 0 | 257 | | logger, |
| | 0 | 258 | | cancellationToken).ConfigureAwait(false); |
| | 0 | 259 | | } |
| | | 260 | | |
| | 0 | 261 | | ValidateRequiredRules(payload, rules, logger); |
| | 0 | 262 | | stopwatch.Stop(); |
| | 0 | 263 | | logger.Information("Parsed multipart/form-data with {Parts} parts, {Files} files, {Bytes} bytes in {ElapsedMs} m |
| | | 264 | | partIndex, payload.Files.Sum(k => k.Value.Length), totalBytes, stopwatch.ElapsedMilliseconds); |
| | | 265 | | |
| | 0 | 266 | | return payload; |
| | 0 | 267 | | } |
| | | 268 | | |
| | | 269 | | /// <summary> |
| | | 270 | | /// Builds the part context for multipart/form-data sections. |
| | | 271 | | /// </summary> |
| | | 272 | | /// <param name="section">The multipart section.</param> |
| | | 273 | | /// <param name="rules">The form part rule map.</param> |
| | | 274 | | /// <param name="partIndex">The current part index (1-based).</param> |
| | | 275 | | /// <param name="logger">The logger instance.</param> |
| | | 276 | | /// <returns>The constructed part context.</returns> |
| | | 277 | | private static KrPartContext BuildFormDataPartContext( |
| | | 278 | | MultipartSection section, |
| | | 279 | | IReadOnlyDictionary<string, KrFormPartRule> rules, |
| | | 280 | | int partIndex, |
| | | 281 | | Logger logger) |
| | | 282 | | { |
| | 0 | 283 | | var headers = ToHeaderDictionary(section.Headers ?? []); |
| | 0 | 284 | | var (name, fileName, _) = GetContentDisposition(section, logger); |
| | 0 | 285 | | var contentType = section.ContentType ?? (string.IsNullOrWhiteSpace(fileName) ? "text/plain" : "application/octe |
| | 0 | 286 | | var contentEncoding = GetHeaderValue(headers, HeaderNames.ContentEncoding); |
| | 0 | 287 | | var declaredLength = GetHeaderLong(headers, HeaderNames.ContentLength); |
| | | 288 | | |
| | 0 | 289 | | var rule = name != null && rules.TryGetValue(name, out var match) ? match : null; |
| | 0 | 290 | | return new KrPartContext |
| | 0 | 291 | | { |
| | 0 | 292 | | Index = partIndex - 1, |
| | 0 | 293 | | Name = name, |
| | 0 | 294 | | FileName = fileName, |
| | 0 | 295 | | ContentType = contentType, |
| | 0 | 296 | | ContentEncoding = contentEncoding, |
| | 0 | 297 | | DeclaredLength = declaredLength, |
| | 0 | 298 | | Headers = headers, |
| | 0 | 299 | | Rule = rule |
| | 0 | 300 | | }; |
| | | 301 | | } |
| | | 302 | | |
| | | 303 | | /// <summary> |
| | | 304 | | /// Logs multipart/form-data part details when debug logging is enabled. |
| | | 305 | | /// </summary> |
| | | 306 | | /// <param name="logger">The logger instance.</param> |
| | | 307 | | /// <param name="partContext">The part context.</param> |
| | | 308 | | /// <param name="index">The 0-based part index.</param> |
| | | 309 | | private static void LogFormDataPartDebug(Logger logger, KrPartContext partContext, int index) |
| | | 310 | | { |
| | 0 | 311 | | if (!logger.IsEnabled(LogEventLevel.Debug)) |
| | | 312 | | { |
| | 0 | 313 | | return; |
| | | 314 | | } |
| | | 315 | | |
| | 0 | 316 | | logger.Debug("Multipart part {Index} name={Name} filename={FileName} contentType={ContentType} contentEncoding={ |
| | 0 | 317 | | index, |
| | 0 | 318 | | partContext.Name, |
| | 0 | 319 | | partContext.FileName, |
| | 0 | 320 | | partContext.ContentType, |
| | 0 | 321 | | string.IsNullOrWhiteSpace(partContext.ContentEncoding) ? "<none>" : partContext.ContentEncoding, |
| | 0 | 322 | | partContext.DeclaredLength); |
| | 0 | 323 | | } |
| | | 324 | | |
| | | 325 | | /// <summary> |
| | | 326 | | /// Handles the OnPart hook for multipart/form-data sections. |
| | | 327 | | /// </summary> |
| | | 328 | | /// <param name="section">The multipart section.</param> |
| | | 329 | | /// <param name="options">The form options.</param> |
| | | 330 | | /// <param name="partContext">The part context.</param> |
| | | 331 | | /// <param name="logger">The logger instance.</param> |
| | | 332 | | /// <param name="contentEncoding">The content encoding.</param> |
| | | 333 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 334 | | /// <returns><c>true</c> when the caller should skip further processing for this section.</returns> |
| | | 335 | | private static async Task<bool> HandleFormDataPartActionAsync( |
| | | 336 | | MultipartSection section, |
| | | 337 | | KrFormOptions options, |
| | | 338 | | KrPartContext partContext, |
| | | 339 | | Logger logger, |
| | | 340 | | string? contentEncoding, |
| | | 341 | | CancellationToken cancellationToken) |
| | | 342 | | { |
| | 0 | 343 | | var action = await InvokeOnPartAsync(options, partContext, logger).ConfigureAwait(false); |
| | 0 | 344 | | if (action == KrPartAction.Reject) |
| | | 345 | | { |
| | 0 | 346 | | logger.Error("Part rejected by hook: {PartIndex}", partContext.Index); |
| | 0 | 347 | | throw new KrFormException("Part rejected by policy.", StatusCodes.Status400BadRequest); |
| | | 348 | | } |
| | | 349 | | |
| | 0 | 350 | | if (action == KrPartAction.Skip) |
| | | 351 | | { |
| | 0 | 352 | | logger.Warning("Part skipped by hook: {PartIndex}", partContext.Index); |
| | 0 | 353 | | await DrainSectionAsync(section.Body, options, contentEncoding, logger, cancellationToken).ConfigureAwait(fa |
| | 0 | 354 | | return true; |
| | | 355 | | } |
| | | 356 | | |
| | 0 | 357 | | return false; |
| | 0 | 358 | | } |
| | | 359 | | |
| | | 360 | | /// <summary> |
| | | 361 | | /// Determines whether a part represents a file based on the file name. |
| | | 362 | | /// </summary> |
| | | 363 | | /// <param name="fileName">The file name from the part.</param> |
| | | 364 | | /// <returns><c>true</c> if the part is a file; otherwise <c>false</c>.</returns> |
| | | 365 | | private static bool IsFilePart(string? fileName) |
| | 0 | 366 | | => !string.IsNullOrWhiteSpace(fileName); |
| | | 367 | | |
| | | 368 | | /// <summary> |
| | | 369 | | /// Processes a file part in multipart/form-data payloads. |
| | | 370 | | /// </summary> |
| | | 371 | | /// <param name="section">The multipart section.</param> |
| | | 372 | | /// <param name="options">The form options.</param> |
| | | 373 | | /// <param name="payload">The form payload to populate.</param> |
| | | 374 | | /// <param name="partContext">The part context.</param> |
| | | 375 | | /// <param name="logger">The logger instance.</param> |
| | | 376 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 377 | | /// <returns>The number of bytes processed.</returns> |
| | | 378 | | private static async Task<long> ProcessFormDataFilePartAsync( |
| | | 379 | | MultipartSection section, |
| | | 380 | | KrFormOptions options, |
| | | 381 | | KrFormData payload, |
| | | 382 | | KrPartContext partContext, |
| | | 383 | | Logger logger, |
| | | 384 | | CancellationToken cancellationToken) |
| | | 385 | | { |
| | 0 | 386 | | ValidateFilePart(partContext.Name, partContext.FileName!, partContext.ContentType, partContext.Rule, payload, lo |
| | 0 | 387 | | var result = await StorePartAsync(section.Body, options, partContext.Rule, partContext.FileName, partContext.Con |
| | 0 | 388 | | .ConfigureAwait(false); |
| | | 389 | | |
| | 0 | 390 | | var filePart = new KrFilePart |
| | 0 | 391 | | { |
| | 0 | 392 | | Name = partContext.Name!, |
| | 0 | 393 | | OriginalFileName = partContext.FileName!, |
| | 0 | 394 | | ContentType = partContext.ContentType, |
| | 0 | 395 | | Length = result.Length, |
| | 0 | 396 | | TempPath = result.TempPath, |
| | 0 | 397 | | Sha256 = result.Sha256, |
| | 0 | 398 | | Headers = partContext.Headers |
| | 0 | 399 | | }; |
| | | 400 | | |
| | 0 | 401 | | AppendFile(payload.Files, filePart, partContext.Rule, logger); |
| | 0 | 402 | | LogStoredFilePart(logger, partContext, result); |
| | 0 | 403 | | return result.Length; |
| | 0 | 404 | | } |
| | | 405 | | |
| | | 406 | | /// <summary> |
| | | 407 | | /// Processes a field part in multipart/form-data payloads. |
| | | 408 | | /// </summary> |
| | | 409 | | /// <param name="section">The multipart section.</param> |
| | | 410 | | /// <param name="options">The form options.</param> |
| | | 411 | | /// <param name="payload">The form payload to populate.</param> |
| | | 412 | | /// <param name="partContext">The part context.</param> |
| | | 413 | | /// <param name="logger">The logger instance.</param> |
| | | 414 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 415 | | /// <returns>The number of bytes processed.</returns> |
| | | 416 | | private static async Task<long> ProcessFormDataFieldPartAsync( |
| | | 417 | | MultipartSection section, |
| | | 418 | | KrFormOptions options, |
| | | 419 | | KrFormData payload, |
| | | 420 | | KrPartContext partContext, |
| | | 421 | | Logger logger, |
| | | 422 | | CancellationToken cancellationToken) |
| | | 423 | | { |
| | 0 | 424 | | if (string.IsNullOrWhiteSpace(partContext.Name)) |
| | | 425 | | { |
| | 0 | 426 | | logger.Error("Field part missing name."); |
| | 0 | 427 | | throw new KrFormException("Field part must include a name.", StatusCodes.Status400BadRequest); |
| | | 428 | | } |
| | | 429 | | |
| | 0 | 430 | | var value = await ReadFieldValueAsync(section.Body, options, partContext.ContentEncoding, logger, cancellationTo |
| | 0 | 431 | | .ConfigureAwait(false); |
| | 0 | 432 | | AppendField(payload.Fields, partContext.Name ?? string.Empty, value); |
| | 0 | 433 | | var bytes = Encoding.UTF8.GetByteCount(value); |
| | 0 | 434 | | logger.Debug("Parsed field part {Index} name={Name} bytes={Bytes}", partContext.Index, partContext.Name, bytes); |
| | 0 | 435 | | return bytes; |
| | 0 | 436 | | } |
| | | 437 | | |
| | | 438 | | /// <summary> |
| | | 439 | | /// Logs file-part storage results for multipart/form-data payloads. |
| | | 440 | | /// </summary> |
| | | 441 | | /// <param name="logger">The logger instance.</param> |
| | | 442 | | /// <param name="partContext">The part context.</param> |
| | | 443 | | /// <param name="result">The stored part result.</param> |
| | | 444 | | private static void LogStoredFilePart(Logger logger, KrPartContext partContext, KrPartWriteResult result) |
| | | 445 | | { |
| | 0 | 446 | | if (string.IsNullOrWhiteSpace(result.TempPath)) |
| | | 447 | | { |
| | 0 | 448 | | logger.Warning("File part {Index} name={Name} was not stored to disk (bytes={Bytes}).", partContext.Index, p |
| | 0 | 449 | | return; |
| | | 450 | | } |
| | | 451 | | |
| | 0 | 452 | | logger.Information("Stored file part {Index} name={Name} filename={FileName} contentType={ContentType} bytes={By |
| | 0 | 453 | | partContext.Index, |
| | 0 | 454 | | partContext.Name, |
| | 0 | 455 | | partContext.FileName, |
| | 0 | 456 | | partContext.ContentType, |
| | 0 | 457 | | result.Length); |
| | 0 | 458 | | } |
| | | 459 | | |
| | | 460 | | /// <summary> |
| | | 461 | | /// Parses an ordered multipart payload from the request. |
| | | 462 | | /// </summary> |
| | | 463 | | /// <param name="context">The current HTTP context.</param> |
| | | 464 | | /// <param name="mediaType">The media type of the request.</param> |
| | | 465 | | /// <param name="options">The form options for parsing.</param> |
| | | 466 | | /// <param name="logger">The logger instance.</param> |
| | | 467 | | /// <param name="nestingDepth">The current nesting depth for multipart parsing.</param> |
| | | 468 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 469 | | /// <returns>Returns the parsed multipart form payload.</returns> |
| | | 470 | | private static async Task<IKrFormPayload> ParseMultipartOrderedAsync(HttpContext context, MediaTypeHeaderValue media |
| | | 471 | | { |
| | 3 | 472 | | var boundary = GetBoundary(mediaType); |
| | 3 | 473 | | return await ParseMultipartFromStreamAsync(context.Request.Body, boundary, options, logger, nestingDepth, isRoot |
| | 2 | 474 | | } |
| | | 475 | | |
| | | 476 | | /// <summary> |
| | | 477 | | /// Parses a multipart payload from the provided stream. |
| | | 478 | | /// </summary> |
| | | 479 | | /// <param name="body">The input stream containing the multipart payload.</param> |
| | | 480 | | /// <param name="boundary">The multipart boundary string.</param> |
| | | 481 | | /// <param name="options">The form options for parsing.</param> |
| | | 482 | | /// <param name="logger">The logger instance.</param> |
| | | 483 | | /// <param name="nestingDepth">The current nesting depth for multipart parsing.</param> |
| | | 484 | | /// <param name="isRoot">Indicates if this is the root multipart payload.</param> |
| | | 485 | | /// <param name="scopeName">The current scope name, or null if root.</param> |
| | | 486 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 487 | | /// <returns>Returns the parsed multipart form payload.</returns> |
| | | 488 | | private static async Task<IKrFormPayload> ParseMultipartFromStreamAsync(Stream body, string boundary, KrFormOptions |
| | | 489 | | { |
| | 4 | 490 | | var reader = new MultipartReader(boundary, body) |
| | 4 | 491 | | { |
| | 4 | 492 | | HeadersLengthLimit = options.Limits.MaxHeaderBytesPerPart |
| | 4 | 493 | | }; |
| | | 494 | | |
| | 4 | 495 | | var payload = new KrMultipart(); |
| | 4 | 496 | | var rules = CreateRuleMap(options, isRoot, scopeName); |
| | 4 | 497 | | var partIndex = 0; |
| | 4 | 498 | | long totalBytes = 0; |
| | | 499 | | |
| | | 500 | | MultipartSection? section; |
| | 8 | 501 | | while ((section = await reader.ReadNextSectionAsync(cancellationToken).ConfigureAwait(false)) != null) |
| | | 502 | | { |
| | 5 | 503 | | partIndex++; |
| | 5 | 504 | | if (partIndex > options.Limits.MaxParts) |
| | | 505 | | { |
| | 0 | 506 | | logger.Error("Multipart payload exceeded MaxParts limit ({MaxParts}).", options.Limits.MaxParts); |
| | 0 | 507 | | throw new KrFormLimitExceededException("Too many multipart sections."); |
| | | 508 | | } |
| | | 509 | | |
| | 5 | 510 | | var partContext = BuildOrderedPartContext(section, rules, partIndex, logger); |
| | 4 | 511 | | LogOrderedPartDebug(logger, partContext, partIndex - 1); |
| | | 512 | | |
| | 4 | 513 | | var contentEncoding = partContext.ContentEncoding; |
| | 4 | 514 | | if (await HandleOrderedPartActionAsync(section, options, partContext, logger, contentEncoding, cancellationT |
| | | 515 | | { |
| | | 516 | | continue; |
| | | 517 | | } |
| | | 518 | | |
| | 4 | 519 | | var result = await StorePartAsync(section.Body, options, partContext.Rule, null, contentEncoding, logger, ca |
| | 4 | 520 | | totalBytes += result.Length; |
| | | 521 | | |
| | 4 | 522 | | var nested = await TryParseNestedPayloadAsync( |
| | 4 | 523 | | partContext, |
| | 4 | 524 | | result, |
| | 4 | 525 | | options, |
| | 4 | 526 | | logger, |
| | 4 | 527 | | nestingDepth, |
| | 4 | 528 | | cancellationToken).ConfigureAwait(false); |
| | | 529 | | |
| | 4 | 530 | | AddOrderedPart(payload, partContext, result, nested); |
| | 4 | 531 | | LogStoredOrderedPart(logger, partContext, partIndex - 1, result); |
| | 4 | 532 | | } |
| | | 533 | | |
| | 3 | 534 | | logger.Information("Parsed multipart ordered payload with {Parts} parts and {Bytes} bytes.", partIndex, totalByt |
| | 3 | 535 | | return payload; |
| | 3 | 536 | | } |
| | | 537 | | |
| | | 538 | | /// <summary> |
| | | 539 | | /// Builds the part context for an ordered multipart section. |
| | | 540 | | /// </summary> |
| | | 541 | | /// <param name="section">The multipart section.</param> |
| | | 542 | | /// <param name="rules">The form part rule map.</param> |
| | | 543 | | /// <param name="partIndex">The current part index (1-based).</param> |
| | | 544 | | /// <param name="logger">The logger instance.</param> |
| | | 545 | | /// <returns>The constructed part context.</returns> |
| | | 546 | | private static KrPartContext BuildOrderedPartContext( |
| | | 547 | | MultipartSection section, |
| | | 548 | | IReadOnlyDictionary<string, KrFormPartRule> rules, |
| | | 549 | | int partIndex, |
| | | 550 | | Logger logger) |
| | | 551 | | { |
| | 5 | 552 | | var headers = ToHeaderDictionary(section.Headers ?? []); |
| | 5 | 553 | | var contentType = section.ContentType ?? "application/octet-stream"; |
| | 5 | 554 | | var allowMissingDisposition = IsMultipartContentType(contentType); |
| | 5 | 555 | | var (name, fileName, _) = GetContentDisposition(section, logger, allowMissing: allowMissingDisposition); |
| | 4 | 556 | | var contentEncoding = GetHeaderValue(headers, HeaderNames.ContentEncoding); |
| | 4 | 557 | | var declaredLength = GetHeaderLong(headers, HeaderNames.ContentLength); |
| | | 558 | | |
| | 4 | 559 | | var rule = name != null && rules.TryGetValue(name, out var match) ? match : null; |
| | 4 | 560 | | return new KrPartContext |
| | 4 | 561 | | { |
| | 4 | 562 | | Index = partIndex - 1, |
| | 4 | 563 | | Name = name, |
| | 4 | 564 | | FileName = fileName, |
| | 4 | 565 | | ContentType = contentType, |
| | 4 | 566 | | ContentEncoding = contentEncoding, |
| | 4 | 567 | | DeclaredLength = declaredLength, |
| | 4 | 568 | | Headers = headers, |
| | 4 | 569 | | Rule = rule |
| | 4 | 570 | | }; |
| | | 571 | | } |
| | | 572 | | |
| | | 573 | | /// <summary> |
| | | 574 | | /// Logs ordered multipart part details when debug logging is enabled. |
| | | 575 | | /// </summary> |
| | | 576 | | /// <param name="logger">The logger instance.</param> |
| | | 577 | | /// <param name="partContext">The part context.</param> |
| | | 578 | | /// <param name="index">The 0-based part index.</param> |
| | | 579 | | private static void LogOrderedPartDebug(Logger logger, KrPartContext partContext, int index) |
| | | 580 | | { |
| | 4 | 581 | | if (!logger.IsEnabled(LogEventLevel.Debug)) |
| | | 582 | | { |
| | 4 | 583 | | return; |
| | | 584 | | } |
| | | 585 | | |
| | 0 | 586 | | logger.Debug("Ordered part {Index} name={Name} filename={FileName} contentType={ContentType} contentEncoding={Co |
| | 0 | 587 | | index, |
| | 0 | 588 | | partContext.Name, |
| | 0 | 589 | | partContext.FileName, |
| | 0 | 590 | | partContext.ContentType, |
| | 0 | 591 | | string.IsNullOrWhiteSpace(partContext.ContentEncoding) ? "<none>" : partContext.ContentEncoding, |
| | 0 | 592 | | partContext.DeclaredLength); |
| | 0 | 593 | | } |
| | | 594 | | |
| | | 595 | | /// <summary> |
| | | 596 | | /// Handles the OnPart hook for ordered multipart sections. |
| | | 597 | | /// </summary> |
| | | 598 | | /// <param name="section">The multipart section.</param> |
| | | 599 | | /// <param name="options">The form options.</param> |
| | | 600 | | /// <param name="partContext">The part context.</param> |
| | | 601 | | /// <param name="logger">The logger instance.</param> |
| | | 602 | | /// <param name="contentEncoding">The content encoding.</param> |
| | | 603 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 604 | | /// <returns><c>true</c> when the caller should skip further processing for this section.</returns> |
| | | 605 | | private static async Task<bool> HandleOrderedPartActionAsync( |
| | | 606 | | MultipartSection section, |
| | | 607 | | KrFormOptions options, |
| | | 608 | | KrPartContext partContext, |
| | | 609 | | Logger logger, |
| | | 610 | | string? contentEncoding, |
| | | 611 | | CancellationToken cancellationToken) |
| | | 612 | | { |
| | 4 | 613 | | var action = await InvokeOnPartAsync(options, partContext, logger).ConfigureAwait(false); |
| | 4 | 614 | | if (action == KrPartAction.Reject) |
| | | 615 | | { |
| | 0 | 616 | | logger.Error("Ordered part rejected by hook: {PartIndex}", partContext.Index); |
| | 0 | 617 | | throw new KrFormException("Part rejected by policy.", StatusCodes.Status400BadRequest); |
| | | 618 | | } |
| | | 619 | | |
| | 4 | 620 | | if (action == KrPartAction.Skip) |
| | | 621 | | { |
| | 0 | 622 | | logger.Warning("Ordered part skipped by hook: {PartIndex}", partContext.Index); |
| | 0 | 623 | | await DrainSectionAsync(section.Body, options, contentEncoding, logger, cancellationToken).ConfigureAwait(fa |
| | 0 | 624 | | return true; |
| | | 625 | | } |
| | | 626 | | |
| | 4 | 627 | | return false; |
| | 4 | 628 | | } |
| | | 629 | | |
| | | 630 | | /// <summary> |
| | | 631 | | /// Attempts to parse a nested multipart payload when the part content type is multipart. |
| | | 632 | | /// </summary> |
| | | 633 | | /// <param name="partContext">The part context.</param> |
| | | 634 | | /// <param name="result">The stored part result.</param> |
| | | 635 | | /// <param name="options">The form options.</param> |
| | | 636 | | /// <param name="logger">The logger instance.</param> |
| | | 637 | | /// <param name="nestingDepth">The current nesting depth.</param> |
| | | 638 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 639 | | /// <returns>The nested payload, or null if none was parsed.</returns> |
| | | 640 | | private static async Task<IKrFormPayload?> TryParseNestedPayloadAsync( |
| | | 641 | | KrPartContext partContext, |
| | | 642 | | KrPartWriteResult result, |
| | | 643 | | KrFormOptions options, |
| | | 644 | | Logger logger, |
| | | 645 | | int nestingDepth, |
| | | 646 | | CancellationToken cancellationToken) |
| | | 647 | | { |
| | 4 | 648 | | if (!IsMultipartContentType(partContext.ContentType)) |
| | | 649 | | { |
| | 3 | 650 | | return null; |
| | | 651 | | } |
| | | 652 | | |
| | 1 | 653 | | if (nestingDepth >= options.Limits.MaxNestingDepth) |
| | | 654 | | { |
| | 0 | 655 | | logger.Error("Nested multipart depth exceeded limit {MaxDepth}.", options.Limits.MaxNestingDepth); |
| | 0 | 656 | | throw new KrFormLimitExceededException("Nested multipart depth exceeded."); |
| | | 657 | | } |
| | | 658 | | |
| | 1 | 659 | | if (!TryGetBoundary(partContext.ContentType, out var nestedBoundary)) |
| | | 660 | | { |
| | 0 | 661 | | logger.Warning("Nested multipart part missing boundary header."); |
| | 0 | 662 | | return null; |
| | | 663 | | } |
| | | 664 | | |
| | 1 | 665 | | if (string.IsNullOrWhiteSpace(result.TempPath)) |
| | | 666 | | { |
| | 0 | 667 | | logger.Warning("Nested multipart part was not stored to disk; skipping nested parse."); |
| | 0 | 668 | | return null; |
| | | 669 | | } |
| | | 670 | | |
| | 1 | 671 | | await using var nestedStream = File.OpenRead(result.TempPath); |
| | 1 | 672 | | return await ParseMultipartFromStreamAsync( |
| | 1 | 673 | | nestedStream, |
| | 1 | 674 | | nestedBoundary, |
| | 1 | 675 | | options, |
| | 1 | 676 | | logger, |
| | 1 | 677 | | nestingDepth + 1, |
| | 1 | 678 | | isRoot: false, |
| | 1 | 679 | | scopeName: partContext.Name, |
| | 1 | 680 | | cancellationToken).ConfigureAwait(false); |
| | 4 | 681 | | } |
| | | 682 | | |
| | | 683 | | /// <summary> |
| | | 684 | | /// Adds a parsed ordered part to the payload. |
| | | 685 | | /// </summary> |
| | | 686 | | /// <param name="payload">The multipart payload.</param> |
| | | 687 | | /// <param name="partContext">The part context.</param> |
| | | 688 | | /// <param name="result">The stored part result.</param> |
| | | 689 | | /// <param name="nested">The nested payload.</param> |
| | | 690 | | private static void AddOrderedPart(KrMultipart payload, KrPartContext partContext, KrPartWriteResult result, IKrForm |
| | | 691 | | { |
| | 4 | 692 | | payload.Parts.Add(new KrRawPart |
| | 4 | 693 | | { |
| | 4 | 694 | | Name = partContext.Name, |
| | 4 | 695 | | ContentType = partContext.ContentType, |
| | 4 | 696 | | Length = result.Length, |
| | 4 | 697 | | TempPath = result.TempPath, |
| | 4 | 698 | | Headers = partContext.Headers, |
| | 4 | 699 | | NestedPayload = nested |
| | 4 | 700 | | }); |
| | 4 | 701 | | } |
| | | 702 | | |
| | | 703 | | /// <summary> |
| | | 704 | | /// Logs ordered multipart part storage results. |
| | | 705 | | /// </summary> |
| | | 706 | | /// <param name="logger">The logger instance.</param> |
| | | 707 | | /// <param name="partContext">The part context.</param> |
| | | 708 | | /// <param name="index">The 0-based part index.</param> |
| | | 709 | | /// <param name="result">The stored part result.</param> |
| | | 710 | | private static void LogStoredOrderedPart(Logger logger, KrPartContext partContext, int index, KrPartWriteResult resu |
| | | 711 | | { |
| | 4 | 712 | | if (string.IsNullOrWhiteSpace(result.TempPath)) |
| | | 713 | | { |
| | 3 | 714 | | logger.Warning("Ordered part {Index} name={Name} was not stored to disk (bytes={Bytes}).", index, partContex |
| | 3 | 715 | | return; |
| | | 716 | | } |
| | | 717 | | |
| | 1 | 718 | | logger.Information("Stored ordered part {Index} name={Name} contentType={ContentType} bytes={Bytes}", index, par |
| | 1 | 719 | | } |
| | | 720 | | |
| | | 721 | | /// <summary> |
| | | 722 | | /// Stores a multipart part to disk or consumes it based on the provided options and rules. |
| | | 723 | | /// </summary> |
| | | 724 | | /// <param name="body">The input stream of the multipart part.</param> |
| | | 725 | | /// <param name="options">The form options for parsing.</param> |
| | | 726 | | /// <param name="rule">The form part rule, if any.</param> |
| | | 727 | | /// <param name="originalFileName">The original file name of the part, if any.</param> |
| | | 728 | | /// <param name="contentEncoding">The content encoding of the part, if any.</param> |
| | | 729 | | /// <param name="logger">The logger instance.</param> |
| | | 730 | | /// <param name="cancellationToken">The cancellation token.</param> |
| | | 731 | | /// <returns>Returns the result of storing the part.</returns> |
| | | 732 | | private static async Task<KrPartWriteResult> StorePartAsync(Stream body, KrFormOptions options, KrFormPartRule? rule |
| | | 733 | | { |
| | 4 | 734 | | var maxBytes = rule?.MaxBytes ?? options.Limits.MaxPartBodyBytes; |
| | 4 | 735 | | var effectiveMax = options.EnablePartDecompression ? Math.Min(maxBytes, options.MaxDecompressedBytesPerPart) : m |
| | | 736 | | |
| | 4 | 737 | | var source = body; |
| | 4 | 738 | | if (options.EnablePartDecompression) |
| | | 739 | | { |
| | 0 | 740 | | var (decoded, normalizedEncoding) = KrPartDecompression.CreateDecodedStream(body, contentEncoding); |
| | 0 | 741 | | if (!IsEncodingAllowed(normalizedEncoding, options.AllowedPartContentEncodings)) |
| | | 742 | | { |
| | 0 | 743 | | var message = $"Unsupported Content-Encoding '{normalizedEncoding}' for multipart part."; |
| | 0 | 744 | | if (options.RejectUnknownContentEncoding) |
| | | 745 | | { |
| | 0 | 746 | | logger.Error(message); |
| | 0 | 747 | | throw new KrFormException(message, StatusCodes.Status415UnsupportedMediaType); |
| | | 748 | | } |
| | 0 | 749 | | logger.Warning(message); |
| | | 750 | | } |
| | | 751 | | else |
| | | 752 | | { |
| | 0 | 753 | | logger.Debug("Part-level decompression enabled for encoding {Encoding}.", normalizedEncoding); |
| | | 754 | | } |
| | 0 | 755 | | source = decoded; |
| | | 756 | | } |
| | 4 | 757 | | else if (!string.IsNullOrWhiteSpace(contentEncoding) && !contentEncoding.Equals("identity", StringComparison.Ord |
| | | 758 | | { |
| | 0 | 759 | | var message = $"Part Content-Encoding '{contentEncoding}' was supplied but part decompression is disabled."; |
| | 0 | 760 | | if (options.RejectUnknownContentEncoding) |
| | | 761 | | { |
| | 0 | 762 | | logger.Error(message); |
| | 0 | 763 | | throw new KrFormException(message, StatusCodes.Status415UnsupportedMediaType); |
| | | 764 | | } |
| | 0 | 765 | | logger.Warning(message); |
| | | 766 | | } |
| | | 767 | | |
| | 4 | 768 | | await using var limited = new LimitedReadStream(source, effectiveMax); |
| | | 769 | | |
| | 4 | 770 | | if (rule?.StoreToDisk == false) |
| | | 771 | | { |
| | 3 | 772 | | var length = await ConsumeStreamAsync(limited, cancellationToken).ConfigureAwait(false); |
| | 3 | 773 | | return new KrPartWriteResult |
| | 3 | 774 | | { |
| | 3 | 775 | | TempPath = string.Empty, |
| | 3 | 776 | | Length = length, |
| | 3 | 777 | | Sha256 = null |
| | 3 | 778 | | }; |
| | | 779 | | } |
| | | 780 | | |
| | 1 | 781 | | var targetPath = rule?.DestinationPath ?? options.DefaultUploadPath; |
| | 1 | 782 | | _ = Directory.CreateDirectory(targetPath); |
| | 1 | 783 | | var sanitizedFileName = string.IsNullOrWhiteSpace(originalFileName) ? null : options.SanitizeFileName(originalFi |
| | 1 | 784 | | var sink = new KrDiskPartSink(targetPath, options.ComputeSha256, sanitizedFileName); |
| | 1 | 785 | | return await sink.WriteAsync(limited, cancellationToken).ConfigureAwait(false); |
| | 4 | 786 | | } |
| | | 787 | | |
| | | 788 | | private static async Task<string> ReadFieldValueAsync(Stream body, KrFormOptions options, string? contentEncoding, L |
| | | 789 | | { |
| | 0 | 790 | | var source = body; |
| | 0 | 791 | | if (options.EnablePartDecompression) |
| | | 792 | | { |
| | 0 | 793 | | var (decoded, normalizedEncoding) = KrPartDecompression.CreateDecodedStream(body, contentEncoding); |
| | 0 | 794 | | if (!IsEncodingAllowed(normalizedEncoding, options.AllowedPartContentEncodings)) |
| | | 795 | | { |
| | 0 | 796 | | var message = $"Unsupported Content-Encoding '{normalizedEncoding}' for multipart field."; |
| | 0 | 797 | | if (options.RejectUnknownContentEncoding) |
| | | 798 | | { |
| | 0 | 799 | | logger.Error(message); |
| | 0 | 800 | | throw new KrFormException(message, StatusCodes.Status415UnsupportedMediaType); |
| | | 801 | | } |
| | 0 | 802 | | logger.Warning(message); |
| | | 803 | | } |
| | | 804 | | else |
| | | 805 | | { |
| | 0 | 806 | | logger.Debug("Field-level decompression enabled for encoding {Encoding}.", normalizedEncoding); |
| | | 807 | | } |
| | 0 | 808 | | source = decoded; |
| | | 809 | | } |
| | | 810 | | |
| | 0 | 811 | | await using var limited = new LimitedReadStream(source, options.Limits.MaxFieldValueBytes); |
| | 0 | 812 | | using var reader = new StreamReader(limited, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: f |
| | 0 | 813 | | var value = await reader.ReadToEndAsync(cancellationToken).ConfigureAwait(false); |
| | 0 | 814 | | return value; |
| | 0 | 815 | | } |
| | | 816 | | |
| | | 817 | | private static async Task DrainSectionAsync(Stream body, KrFormOptions options, string? contentEncoding, Logger logg |
| | | 818 | | { |
| | 0 | 819 | | var source = body; |
| | 0 | 820 | | if (options.EnablePartDecompression) |
| | | 821 | | { |
| | 0 | 822 | | var (decoded, normalizedEncoding) = KrPartDecompression.CreateDecodedStream(body, contentEncoding); |
| | 0 | 823 | | source = decoded; |
| | 0 | 824 | | logger.Debug("Draining part with encoding {Encoding}.", normalizedEncoding); |
| | | 825 | | } |
| | | 826 | | |
| | 0 | 827 | | await using var limited = new LimitedReadStream(source, options.Limits.MaxPartBodyBytes); |
| | 0 | 828 | | await limited.CopyToAsync(Stream.Null, cancellationToken).ConfigureAwait(false); |
| | 0 | 829 | | } |
| | | 830 | | |
| | | 831 | | private static async Task<long> ConsumeStreamAsync(Stream body, CancellationToken cancellationToken) |
| | | 832 | | { |
| | 3 | 833 | | var buffer = new byte[81920]; |
| | 3 | 834 | | long total = 0; |
| | | 835 | | int read; |
| | 6 | 836 | | while ((read = await body.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0) |
| | | 837 | | { |
| | 3 | 838 | | total += read; |
| | | 839 | | } |
| | 3 | 840 | | return total; |
| | 3 | 841 | | } |
| | | 842 | | |
| | | 843 | | private static void ValidateFilePart(string? name, string fileName, string contentType, KrFormPartRule? rule, KrForm |
| | | 844 | | { |
| | 0 | 845 | | if (string.IsNullOrWhiteSpace(name)) |
| | | 846 | | { |
| | 0 | 847 | | logger.Error("File part missing name."); |
| | 0 | 848 | | throw new KrFormException("File part must include a name.", StatusCodes.Status400BadRequest); |
| | | 849 | | } |
| | | 850 | | |
| | 0 | 851 | | if (rule == null) |
| | | 852 | | { |
| | 0 | 853 | | return; |
| | | 854 | | } |
| | | 855 | | |
| | 0 | 856 | | if (!rule.AllowMultiple && payload.Files.ContainsKey(name)) |
| | | 857 | | { |
| | 0 | 858 | | logger.Error("Part rule disallows multiple files for name {Name}.", name); |
| | 0 | 859 | | throw new KrFormException($"Multiple files not allowed for '{name}'.", StatusCodes.Status400BadRequest); |
| | | 860 | | } |
| | | 861 | | |
| | 0 | 862 | | if (rule.AllowedContentTypes.Count > 0 && !IsAllowedRequestContentType(contentType, rule.AllowedContentTypes)) |
| | | 863 | | { |
| | 0 | 864 | | logger.Error("Rejected content type {ContentType} for part {Name}.", contentType, name); |
| | 0 | 865 | | throw new KrFormException("Content type is not allowed for this part.", StatusCodes.Status415UnsupportedMedi |
| | | 866 | | } |
| | | 867 | | |
| | 0 | 868 | | if (rule.AllowedExtensions.Count > 0) |
| | | 869 | | { |
| | 0 | 870 | | var ext = Path.GetExtension(fileName); |
| | 0 | 871 | | if (string.IsNullOrWhiteSpace(ext) || !rule.AllowedExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase |
| | | 872 | | { |
| | 0 | 873 | | logger.Error("Rejected extension {Extension} for part {Name}.", ext, name); |
| | 0 | 874 | | throw new KrFormException("File extension is not allowed for this part.", StatusCodes.Status400BadReques |
| | | 875 | | } |
| | | 876 | | } |
| | | 877 | | |
| | 0 | 878 | | if (rule.MaxBytes.HasValue && rule.MaxBytes.Value <= 0) |
| | | 879 | | { |
| | 0 | 880 | | logger.Warning("Part rule for {Name} has non-positive MaxBytes.", name); |
| | | 881 | | } |
| | 0 | 882 | | } |
| | | 883 | | |
| | | 884 | | private static void AppendFile(Dictionary<string, KrFilePart[]> files, KrFilePart part, KrFormPartRule? rule, Logger |
| | | 885 | | { |
| | 0 | 886 | | files[part.Name] = files.TryGetValue(part.Name, out var existing) |
| | 0 | 887 | | ? [.. existing, part] |
| | 0 | 888 | | : [part]; |
| | | 889 | | |
| | 0 | 890 | | if (rule != null && !rule.AllowMultiple && files[part.Name].Length > 1) |
| | | 891 | | { |
| | 0 | 892 | | logger.Error("Rule disallows multiple files for {Name}.", part.Name); |
| | 0 | 893 | | throw new KrFormException($"Multiple files not allowed for '{part.Name}'.", StatusCodes.Status400BadRequest) |
| | | 894 | | } |
| | 0 | 895 | | } |
| | | 896 | | |
| | | 897 | | private static void AppendField(Dictionary<string, string[]> fields, string name, string value) |
| | | 898 | | { |
| | 0 | 899 | | fields[name] = fields.TryGetValue(name, out var existing) |
| | 0 | 900 | | ? [.. existing, value] |
| | 0 | 901 | | : [value]; |
| | 0 | 902 | | } |
| | | 903 | | |
| | | 904 | | private static void ValidateRequiredRules(KrFormData payload, Dictionary<string, KrFormPartRule> rules, Logger logge |
| | | 905 | | { |
| | 6 | 906 | | foreach (var rule in rules.Values) |
| | | 907 | | { |
| | 0 | 908 | | if (!rule.Required) |
| | | 909 | | { |
| | | 910 | | continue; |
| | | 911 | | } |
| | | 912 | | |
| | 0 | 913 | | var hasField = payload.Fields.ContainsKey(rule.Name); |
| | 0 | 914 | | var hasFile = payload.Files.ContainsKey(rule.Name); |
| | 0 | 915 | | if (!hasField && !hasFile) |
| | | 916 | | { |
| | 0 | 917 | | logger.Error("Required form part missing: {Name}", rule.Name); |
| | 0 | 918 | | throw new KrFormException($"Required form part '{rule.Name}' missing.", StatusCodes.Status400BadRequest) |
| | | 919 | | } |
| | | 920 | | } |
| | 3 | 921 | | } |
| | | 922 | | |
| | | 923 | | private static Dictionary<string, KrFormPartRule> CreateRuleMap(KrFormOptions options, bool isRoot, string? scopeNam |
| | | 924 | | { |
| | 7 | 925 | | var map = new Dictionary<string, KrFormPartRule>(StringComparer.OrdinalIgnoreCase); |
| | 30 | 926 | | foreach (var rule in options.Rules) |
| | | 927 | | { |
| | 8 | 928 | | if (!IsRuleInScope(rule, isRoot, scopeName)) |
| | | 929 | | { |
| | | 930 | | continue; |
| | | 931 | | } |
| | 6 | 932 | | map[rule.Name] = rule; |
| | | 933 | | } |
| | 7 | 934 | | return map; |
| | | 935 | | } |
| | | 936 | | |
| | | 937 | | /// <summary> |
| | | 938 | | /// Determines if a rule applies to the current scope. |
| | | 939 | | /// </summary> |
| | | 940 | | /// <param name="rule">The form part rule.</param> |
| | | 941 | | /// <param name="isRoot">Indicates if the current scope is the root.</param> |
| | | 942 | | /// <param name="scopeName">The current scope name, or null if root.</param> |
| | | 943 | | /// <returns>True if the rule is in scope; otherwise, false.</returns> |
| | | 944 | | private static bool IsRuleInScope(KrFormPartRule rule, bool isRoot, string? scopeName) |
| | | 945 | | { |
| | 8 | 946 | | var ruleScope = string.IsNullOrWhiteSpace(rule.Scope) ? null : rule.Scope; |
| | 8 | 947 | | return isRoot |
| | 8 | 948 | | ? ruleScope is null |
| | 8 | 949 | | : !string.IsNullOrWhiteSpace(scopeName) && string.Equals(ruleScope, scopeName, StringComparison.OrdinalIgnor |
| | | 950 | | } |
| | | 951 | | |
| | | 952 | | private static (string? Name, string? FileName, ContentDispositionHeaderValue? Disposition) GetContentDisposition(Mu |
| | | 953 | | { |
| | 5 | 954 | | if (string.IsNullOrWhiteSpace(section.ContentDisposition)) |
| | | 955 | | { |
| | 1 | 956 | | if (allowMissing) |
| | | 957 | | { |
| | 0 | 958 | | return (null, null, null); |
| | | 959 | | } |
| | | 960 | | |
| | 1 | 961 | | logger.Error("Multipart section missing Content-Disposition header."); |
| | 1 | 962 | | throw new KrFormException("Missing Content-Disposition header.", StatusCodes.Status400BadRequest); |
| | | 963 | | } |
| | | 964 | | |
| | 4 | 965 | | if (!ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var disposition)) |
| | | 966 | | { |
| | 0 | 967 | | logger.Error("Invalid Content-Disposition header: {Header}", section.ContentDisposition); |
| | 0 | 968 | | throw new KrFormException("Invalid Content-Disposition header.", StatusCodes.Status400BadRequest); |
| | | 969 | | } |
| | | 970 | | |
| | 4 | 971 | | var name = disposition.Name.HasValue ? HeaderUtilities.RemoveQuotes(disposition.Name).Value : null; |
| | 4 | 972 | | var fileName = disposition.FileNameStar.HasValue |
| | 4 | 973 | | ? HeaderUtilities.RemoveQuotes(disposition.FileNameStar).Value |
| | 4 | 974 | | : disposition.FileName.HasValue ? HeaderUtilities.RemoveQuotes(disposition.FileName).Value : null; |
| | | 975 | | |
| | 4 | 976 | | return (name, fileName, disposition); |
| | | 977 | | } |
| | | 978 | | |
| | | 979 | | private static string GetBoundary(MediaTypeHeaderValue mediaType) |
| | | 980 | | { |
| | 3 | 981 | | if (!mediaType.Boundary.HasValue) |
| | | 982 | | { |
| | 0 | 983 | | throw new KrFormException("Missing multipart boundary.", StatusCodes.Status400BadRequest); |
| | | 984 | | } |
| | | 985 | | |
| | 3 | 986 | | var boundary = HeaderUtilities.RemoveQuotes(mediaType.Boundary).Value; |
| | 3 | 987 | | return string.IsNullOrWhiteSpace(boundary) |
| | 3 | 988 | | ? throw new KrFormException("Missing multipart boundary.", StatusCodes.Status400BadRequest) |
| | 3 | 989 | | : boundary; |
| | | 990 | | } |
| | | 991 | | |
| | | 992 | | private static bool TryGetBoundary(string contentType, out string boundary) |
| | | 993 | | { |
| | 1 | 994 | | boundary = string.Empty; |
| | 1 | 995 | | if (!MediaTypeHeaderValue.TryParse(contentType, out var mediaType)) |
| | | 996 | | { |
| | 0 | 997 | | return false; |
| | | 998 | | } |
| | | 999 | | |
| | 1 | 1000 | | if (!mediaType.Boundary.HasValue) |
| | | 1001 | | { |
| | 0 | 1002 | | return false; |
| | | 1003 | | } |
| | | 1004 | | |
| | 1 | 1005 | | var parsed = HeaderUtilities.RemoveQuotes(mediaType.Boundary).Value; |
| | 1 | 1006 | | if (string.IsNullOrWhiteSpace(parsed)) |
| | | 1007 | | { |
| | 0 | 1008 | | return false; |
| | | 1009 | | } |
| | | 1010 | | |
| | 1 | 1011 | | boundary = parsed; |
| | 1 | 1012 | | return true; |
| | | 1013 | | } |
| | | 1014 | | |
| | | 1015 | | private static Dictionary<string, string[]> ToHeaderDictionary(IEnumerable<KeyValuePair<string, Microsoft.Extensions |
| | | 1016 | | { |
| | 5 | 1017 | | var dict = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase); |
| | 28 | 1018 | | foreach (var header in headers) |
| | | 1019 | | { |
| | 18 | 1020 | | dict[header.Key] = [.. header.Value.Select(static v => v ?? string.Empty)]; |
| | | 1021 | | } |
| | 5 | 1022 | | return dict; |
| | | 1023 | | } |
| | | 1024 | | |
| | | 1025 | | private static string? GetHeaderValue(IReadOnlyDictionary<string, string[]> headers, string name) |
| | 4 | 1026 | | => headers.TryGetValue(name, out var values) ? values.FirstOrDefault() : null; |
| | | 1027 | | |
| | | 1028 | | private static long? GetHeaderLong(IReadOnlyDictionary<string, string[]> headers, string name) |
| | 4 | 1029 | | => headers.TryGetValue(name, out var values) && long.TryParse(values.FirstOrDefault(), out var result) |
| | 4 | 1030 | | ? result |
| | 4 | 1031 | | : null; |
| | | 1032 | | private static bool IsAllowedRequestContentType(string contentType, IEnumerable<string> allowed) |
| | | 1033 | | { |
| | 39 | 1034 | | foreach (var allowedType in allowed) |
| | | 1035 | | { |
| | 15 | 1036 | | if (string.IsNullOrWhiteSpace(allowedType)) |
| | | 1037 | | { |
| | | 1038 | | continue; |
| | | 1039 | | } |
| | | 1040 | | |
| | 15 | 1041 | | if (allowedType.EndsWith("/*", StringComparison.Ordinal)) |
| | | 1042 | | { |
| | 0 | 1043 | | var prefix = allowedType[..^1]; |
| | 0 | 1044 | | if (contentType.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) |
| | | 1045 | | { |
| | 0 | 1046 | | return true; |
| | | 1047 | | } |
| | | 1048 | | } |
| | 15 | 1049 | | else if (contentType.Equals(allowedType, StringComparison.OrdinalIgnoreCase)) |
| | | 1050 | | { |
| | 7 | 1051 | | return true; |
| | | 1052 | | } |
| | | 1053 | | } |
| | 1 | 1054 | | return false; |
| | 7 | 1055 | | } |
| | | 1056 | | |
| | | 1057 | | private static bool IsMultipartContentType(string contentType) |
| | 16 | 1058 | | => contentType.StartsWith("multipart/", StringComparison.OrdinalIgnoreCase); |
| | | 1059 | | |
| | | 1060 | | private static bool IsEncodingAllowed(string encoding, IEnumerable<string> allowed) |
| | 0 | 1061 | | => allowed.Any(a => string.Equals(a, encoding, StringComparison.OrdinalIgnoreCase)); |
| | | 1062 | | |
| | | 1063 | | private static bool DetectRequestDecompressionEnabled(HttpContext context) |
| | | 1064 | | { |
| | 8 | 1065 | | var type = Type.GetType("Microsoft.AspNetCore.RequestDecompression.IRequestDecompressionProvider, Microsoft.AspN |
| | 8 | 1066 | | return type is not null && context.RequestServices.GetService(type) is not null; |
| | | 1067 | | } |
| | | 1068 | | |
| | | 1069 | | private static async ValueTask<KrPartAction> InvokeOnPartAsync(KrFormOptions options, KrPartContext context, Logger |
| | | 1070 | | { |
| | 4 | 1071 | | if (options.OnPart == null) |
| | | 1072 | | { |
| | 4 | 1073 | | return KrPartAction.Continue; |
| | | 1074 | | } |
| | | 1075 | | |
| | | 1076 | | try |
| | | 1077 | | { |
| | 0 | 1078 | | return await options.OnPart(context).ConfigureAwait(false); |
| | | 1079 | | } |
| | 0 | 1080 | | catch (Exception ex) |
| | | 1081 | | { |
| | 0 | 1082 | | logger.Error(ex, "Part hook failed for part {Index}.", context.Index); |
| | 0 | 1083 | | throw new KrFormException("Part hook failed.", StatusCodes.Status400BadRequest); |
| | | 1084 | | } |
| | 4 | 1085 | | } |
| | | 1086 | | } |
| | | 1087 | | |
| | | 1088 | | internal static class LoggerExtensions |
| | | 1089 | | { |
| | | 1090 | | /// <summary> |
| | | 1091 | | /// Adds a simple timed logging scope. |
| | | 1092 | | /// </summary> |
| | | 1093 | | /// <param name="logger">The logger.</param> |
| | | 1094 | | /// <param name="operation">The operation name.</param> |
| | | 1095 | | /// <returns>The disposable scope.</returns> |
| | | 1096 | | public static IDisposable BeginTimedOperation(this Logger logger, string operation) |
| | | 1097 | | => new TimedOperation(logger, operation); |
| | | 1098 | | |
| | | 1099 | | private sealed class TimedOperation : IDisposable |
| | | 1100 | | { |
| | | 1101 | | private readonly Logger _logger; |
| | | 1102 | | private readonly string _operation; |
| | | 1103 | | private readonly Stopwatch _stopwatch; |
| | | 1104 | | |
| | | 1105 | | public TimedOperation(Logger logger, string operation) |
| | | 1106 | | { |
| | | 1107 | | _logger = logger; |
| | | 1108 | | _operation = operation; |
| | | 1109 | | _stopwatch = Stopwatch.StartNew(); |
| | | 1110 | | if (_logger.IsEnabled(LogEventLevel.Information)) |
| | | 1111 | | { |
| | | 1112 | | _logger.Information("Form parsing started: {Operation}", _operation); |
| | | 1113 | | } |
| | | 1114 | | } |
| | | 1115 | | |
| | | 1116 | | public void Dispose() |
| | | 1117 | | { |
| | | 1118 | | _stopwatch.Stop(); |
| | | 1119 | | if (_logger.IsEnabled(LogEventLevel.Information)) |
| | | 1120 | | { |
| | | 1121 | | _logger.Information("Form parsing completed: {Operation} in {ElapsedMs} ms", _operation, _stopwatch.Elap |
| | | 1122 | | } |
| | | 1123 | | } |
| | | 1124 | | } |
| | | 1125 | | } |