MdpApiPullEgress.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System.Net;
  2. using System.Net.Sockets;
  3. using Microsoft.Extensions.Configuration;
  4. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. public sealed record MdpApiPullTarget(string Host, int Port, string[] Addresses, bool AllowHttp = false)
  6. {
  7. public bool AllowsAddress(IPAddress value)
  8. {
  9. var address = Normalize(value);
  10. return IsUsable(address) && Addresses.Any(text => IPAddress.TryParse(text, out var approved)
  11. && Normalize(approved).Equals(address));
  12. }
  13. private static IPAddress Normalize(IPAddress value) => value.IsIPv4MappedToIPv6 ? value.MapToIPv4() : value;
  14. private static bool IsUsable(IPAddress address)
  15. {
  16. if (IPAddress.IsLoopback(address)) return false;
  17. var bytes = address.GetAddressBytes();
  18. if (address.AddressFamily == AddressFamily.InterNetwork)
  19. {
  20. // Never delegate link-local, node-local cloud endpoints, or special network ranges to configuration.
  21. return bytes[0] is > 0 and < 224 and not 127
  22. && !(bytes[0] == 169 && bytes[1] == 254)
  23. && !(bytes[0] == 168 && bytes[1] == 63 && bytes[2] == 129 && bytes[3] == 16)
  24. && !(bytes[0] == 100 && bytes[1] is >= 64 and <= 127);
  25. }
  26. // IPv6 endpoints are limited to direct global unicast and explicitly pinned unique local addresses.
  27. return address.ScopeId == 0 && (bytes[0] is 0xfc or 0xfd
  28. || (bytes[0] & 0xe0) == 0x20 && !(bytes[0] == 0x20 && bytes[1] == 0x02)
  29. && !(bytes[0] == 0x20 && bytes[1] == 0x01 && bytes[2] == 0x00 && bytes[3] == 0x00));
  30. }
  31. }
  32. public sealed class MdpApiPullEgress(IConfiguration configuration)
  33. {
  34. internal HttpClient Open(long tenant, long source, Uri uri, bool requireHttps = true)
  35. {
  36. var target = Target(tenant, source, uri, requireHttps);
  37. var handler = new SocketsHttpHandler
  38. {
  39. AllowAutoRedirect = false,
  40. UseCookies = false,
  41. UseProxy = false,
  42. AutomaticDecompression = DecompressionMethods.None,
  43. PooledConnectionLifetime = TimeSpan.Zero,
  44. ConnectTimeout = TimeSpan.FromSeconds(8),
  45. ConnectCallback = async (context, token) =>
  46. {
  47. var host = uri.IdnHost.Trim('[', ']');
  48. if (!string.Equals(context.DnsEndPoint.Host.Trim('[', ']'), host, StringComparison.OrdinalIgnoreCase)
  49. || context.DnsEndPoint.Port != uri.Port)
  50. throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
  51. var addresses = IPAddress.TryParse(host, out var exact) ? [exact] : await Dns.GetHostAddressesAsync(host, token);
  52. if (addresses.Length == 0 || addresses.Any(address => !target.AllowsAddress(address)))
  53. throw new MdpApiPullException("PULL_ADDRESS_FORBIDDEN");
  54. foreach (var address in addresses)
  55. {
  56. var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
  57. try
  58. {
  59. await socket.ConnectAsync(address, context.DnsEndPoint.Port, token);
  60. return new NetworkStream(socket, ownsSocket: true);
  61. }
  62. catch (SocketException)
  63. {
  64. socket.Dispose();
  65. }
  66. catch
  67. {
  68. socket.Dispose();
  69. throw;
  70. }
  71. }
  72. throw new HttpRequestException("Approved API destination was unreachable.");
  73. }
  74. };
  75. return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(25) };
  76. }
  77. internal MdpApiPullTarget Target(long tenant, long source, Uri uri, bool requireHttps = true)
  78. {
  79. if (!uri.IsAbsoluteUri || uri.UserInfo.Length != 0 || uri.Fragment.Length != 0
  80. || uri.Scheme != "https" && (requireHttps || uri.Scheme != "http"))
  81. throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
  82. var host = uri.IdnHost.Trim('[', ']').TrimEnd('.');
  83. if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host.EndsWith(".localhost", StringComparison.OrdinalIgnoreCase))
  84. throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
  85. var section = configuration.GetSection($"MdpApiPull:Targets:{tenant}:{source}");
  86. var target = section.GetChildren().Select(rule =>
  87. new MdpApiPullTarget(rule["Host"] ?? "", rule.GetValue<int>("Port"),
  88. rule.GetSection("Addresses").Get<string[]>() ?? [], rule.GetValue<bool>("AllowHttp")))
  89. .SingleOrDefault(rule => string.Equals(rule.Host.TrimEnd('.'), host, StringComparison.OrdinalIgnoreCase)
  90. && rule.Port == uri.Port && (uri.Scheme == "https" || rule.AllowHttp));
  91. if (target is null || target.Addresses.Length == 0 || IPAddress.TryParse(host, out var ip) && !target.AllowsAddress(ip))
  92. throw new MdpApiPullException("PULL_TARGET_FORBIDDEN");
  93. return target;
  94. }
  95. internal static bool SameOrigin(Uri first, Uri second) =>
  96. first.Scheme == second.Scheme && first.Port == second.Port &&
  97. string.Equals(first.IdnHost, second.IdnHost, StringComparison.OrdinalIgnoreCase);
  98. }
  99. internal sealed class MdpApiPullException(string code, TimeSpan? retry = null) : Exception(code)
  100. {
  101. internal string Code { get; } = code;
  102. internal TimeSpan? Retry { get; } = retry;
  103. }