using System.Globalization; using System.Net; using System.Security.Cryptography; using System.Text; using Admin.NET.Plugin.AiDOP.DataPlatform.Core.Edge; using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress; namespace Admin.NET.DataPlatform.Edge; internal static class EdgePush { internal static void Map(WebApplication app, EdgeEngine engine, EdgeQueue queue, IConfiguration config) { string access = config["Edge:PushAccessKey"] ?? throw new EdgeContractException("EDGE_PUSH_ACCESS_KEY_REQUIRED"); var peerStrings = config.GetSection("Edge:PushPeers").Get() ?? []; if (peerStrings.Length == 0 || peerStrings.Any(value => !IPAddress.TryParse(value, out _))) throw new EdgeContractException("EDGE_PUSH_PEERS_REQUIRED"); var peers = peerStrings.Select(IPAddress.Parse).Select(Normalize).ToHashSet(); var secret = Convert.FromBase64String(EdgeEngine.LocalCredential("MDP_EDGE_SECRET_PUSH") ?? ""); if (secret.Length != 32 || access.Length is < 12 or > 96) throw new EdgeContractException("EDGE_PUSH_KEY_INVALID"); var limiter = new Queue(); var rate = Math.Clamp(config.GetValue("Edge:PushRequestsPerMinute", 60), 1, 1000); var endpoint = app.MapPost("/api/v1/edge/push/{datasetKey}", async (HttpContext context, string datasetKey) => { context.Response.Headers.CacheControl = "no-store"; if (!AllowedPeer(context, peers)) return Failure(403, "EDGE_PUSH_FORBIDDEN"); var task = engine.Current; if (task is not { Mode: EdgeProtocol.ApiPush, State: "READY" } || task.LeaseUntil <= DateTimeOffset.UtcNow || !string.Equals(task.DatasetKey, datasetKey, StringComparison.Ordinal)) return Failure(503, "EDGE_PUSH_UNAVAILABLE"); var request = context.Request; var media = request.ContentType?.Split(';', 2)[0].ToLowerInvariant(); if (media is not ("application/json" or "application/x-ndjson") || request.Headers.ContainsKey("Content-Encoding")) return Failure(415, "EDGE_PUSH_MEDIA_INVALID"); var key = Header(request, "X-Idempotency-Key", 128); var nonce = Header(request, "X-Nonce", 128); var timestamp = Header(request, "X-Timestamp", 20); var suppliedAccess = Header(request, "X-Access-Key", 96); var signature = Header(request, "X-Signature", 64); var digest = Header(request, "X-Content-SHA256", 64); if (key is null || nonce is null || suppliedAccess != access || digest is null || !InTime(timestamp) || signature is null) return Failure(403, "EDGE_PUSH_FORBIDDEN"); // Validate signed headers before reading the bounded request. var canonical = MdpIngestProtocol.CanonicalSignature("POST", request.Path, access, timestamp!, nonce, digest, key, true, media, task.FactoryId.ToString(CultureInfo.InvariantCulture), task.SchemaVersion); var expected = HMACSHA256.HashData(secret, Encoding.UTF8.GetBytes(canonical)); var provided = new byte[32]; if (!Convert.TryFromBase64String(signature, provided, out var count) || count != expected.Length || !CryptographicOperations.FixedTimeEquals(expected, provided)) return Failure(403, "EDGE_PUSH_FORBIDDEN"); lock (limiter) { var now = DateTimeOffset.UtcNow; while (limiter.TryPeek(out var oldest) && oldest.AddMinutes(1) <= now) limiter.Dequeue(); if (limiter.Count >= rate) return Failure(429, "EDGE_PUSH_RATE_LIMITED"); limiter.Enqueue(now); } using var body = new MemoryStream(); var bytes = new byte[8192]; while (true) { var read = await request.Body.ReadAsync(bytes, context.RequestAborted); if (read == 0) break; if (body.Length + read > EdgeProtocol.MaxBodyBytes) return Failure(413, "EDGE_PUSH_TOO_LARGE"); body.Write(bytes, 0, read); } var batch = EdgeBatch.Create(task.Stream, key, null, null, body.ToArray()) with { Ndjson = media == "application/x-ndjson" }; if (batch.Digest != digest || batch.Body.Length == 0) return Failure(400, "EDGE_PUSH_DIGEST_INVALID"); try { var nonceHash = EdgeProtocol.Digest(Encoding.UTF8.GetBytes(task.SourceId.ToString(CultureInfo.InvariantCulture) + ":" + nonce)); var receipt = queue.Buffer(batch, nonceHash); return Results.Json(receipt, EdgeProtocol.Json, statusCode: receipt.Status == EdgeProtocol.Buffered ? 202 : 200); } catch (EdgeContractException error) { return Failure(error.Code == "EDGE_STORAGE_LIMIT" ? 429 : 409, error.Code); } catch (Microsoft.Data.Sqlite.SqliteException) { return Failure(503, "EDGE_STORAGE_UNAVAILABLE"); } }); endpoint.WithMetadata(new Microsoft.AspNetCore.Mvc.RequestSizeLimitAttribute(EdgeProtocol.MaxBodyBytes)); app.MapGet("/api/v1/edge/push/{datasetKey}/receipts/{key}", (HttpContext context, string datasetKey, string key) => { context.Response.Headers.CacheControl = "no-store"; if (!AllowedPeer(context, peers) || engine.Current is not { Mode: EdgeProtocol.ApiPush } task || task.DatasetKey != datasetKey) return Failure(403, "EDGE_PUSH_FORBIDDEN"); var request = context.Request; var timestamp = Header(request, "X-Timestamp", 20); var signature = Header(request, "X-Signature", 64); if (!InTime(timestamp) || Header(request, "X-Access-Key", 96) != access || signature is null) return Failure(403, "EDGE_PUSH_FORBIDDEN"); var canonical = string.Join('&', "GET", request.Path.Value, access, timestamp, key); var expected = HMACSHA256.HashData(secret, Encoding.UTF8.GetBytes(canonical)); var provided = new byte[32]; if (!Convert.TryFromBase64String(signature, provided, out var count) || count != 32 || !CryptographicOperations.FixedTimeEquals(expected, provided)) return Failure(403, "EDGE_PUSH_FORBIDDEN"); if (key.Length is < 1 or > 128 || !key.All(ch => ch is >= '!' and <= '~')) return Failure(400, "EDGE_PUSH_KEY_INVALID"); var receipt = queue.Lookup(EdgeBatch.Create(task.Stream, key, null, null, []).BatchId); return receipt is null ? Results.NotFound() : Results.Json(receipt, EdgeProtocol.Json); }); } private static IResult Failure(int status, string code) => Results.Json(new { code }, statusCode: status); private static string? Header(HttpRequest request, string name, int max) => request.Headers[name] is { Count: 1 } values && values[0] is { Length: > 0 } value && value.Length <= max && value.All(ch => ch is >= '!' and <= '~') ? value : null; private static bool InTime(string? timestamp) { var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); return long.TryParse(timestamp, NumberStyles.None, CultureInfo.InvariantCulture, out var signed) && signed >= now - 300 && signed <= now + 300; } private static IPAddress Normalize(IPAddress value) => value.IsIPv4MappedToIPv6 ? value.MapToIPv4() : value; private static bool AllowedPeer(HttpContext context, HashSet peers) => context.Request.IsHttps && context.Connection.RemoteIpAddress is { } peer && peers.Contains(Normalize(peer)); }