diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..3bc90e6 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,27 @@ +name: Test + +on: + push: + branches: [master] + pull_request: + +permissions: + contents: read + +jobs: + test: + name: ${{ matrix.os }} / .NET ${{ matrix.dotnet }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + dotnet: ['8.0', '9.0', '10.0'] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 + with: + dotnet-version: ${{ matrix.dotnet }}.x + - run: dotnet restore IPGeolocation.sln -p:TestTargetFramework=net${{ matrix.dotnet }} -p:NuGetAudit=true -p:NuGetAuditMode=all '-warnaserror:NU1900,NU1901,NU1902,NU1903,NU1904' + - run: dotnet test IPGeolocation.sln --no-restore -c Release -p:TestTargetFramework=net${{ matrix.dotnet }} + - run: dotnet pack src/IPGeolocation/IPGeolocation.csproj --no-build -c Release -o artifacts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ac2ffd..1a4cb7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 3.0.1 + +- Hide API keys in error messages and details. +- Handle incomplete or invalid error responses. +- Fix request handling for very short or very long timeouts. +- Add Arabic (`ar`) for single and bulk lookups. + +Existing public methods and .NET Standard 2.1 support remain unchanged. + ## 3.0.0 - 2026-04-08 - Replaced the old generated multi-API SDK with the new .NET SDK for the IPGeolocation.io IP Location API. diff --git a/README.md b/README.md index 8acce79..c0363e3 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Install-Package IPGeoLocation.IPGeolocation ``` ```xml - + ``` - NuGet package: `IPGeoLocation.IPGeolocation` @@ -144,10 +144,10 @@ Paid plans still need `include` for optional modules. `fields` and `excludes` on | `apiKey` | `string?` | unset | Required for bulk lookup. Optional for single lookup if `requestOrigin` is set. | | `requestOrigin` | `string?` | unset | Must be an absolute `http` or `https` origin. | | `baseUrl` | `string` | `https://api.ipgeolocation.io` | Override the API base URL. | -| `connectTimeout` | `TimeSpan` | `10` seconds | Time to open the connection. | -| `readTimeout` | `TimeSpan` | `30` seconds | Time to wait while reading the response body. | +| `connectTimeout` | `TimeSpan` | `10` seconds | Time to connect and receive response headers. | +| `readTimeout` | `TimeSpan` | `30` seconds | Time to wait for the next part of the response. | -The client constructor accepts an `IpGeolocationClientConfig`. Timeouts are validated before the request is sent. +The client constructor accepts an `IpGeolocationClientConfig`. Both timeouts must be greater than zero. ## Available Methods @@ -168,7 +168,7 @@ The client constructor accepts an `IpGeolocationClientConfig`. Timeouts are vali |-------|------------|-------| | `ip` | Single lookup | IPv4, IPv6, or domain. Omit it for caller IP lookup. | | `ips` | Bulk lookup | Collection of 1 to 50,000 IPs or domains. | -| `lang` | Single and bulk | One of `en`, `de`, `ru`, `ja`, `fr`, `cn`, `es`, `cs`, `it`, `ko`, `fa`, `pt`. | +| `lang` | Single and bulk | One of `en`, `de`, `ru`, `ja`, `fr`, `cn`, `es`, `cs`, `it`, `ko`, `fa`, `pt`, `ar`. | | `include` | Single and bulk | Collection of module names such as `security`, `abuse`, `user_agent`, `hostname`, `liveHostname`, `hostnameFallbackLive`, `geo_accuracy`, `dma_code`, or `*`. | | `fields` | Single and bulk | Collection of field paths to keep, for example `location.country_name` or `security.threat_score`. | | `excludes` | Single and bulk | Collection of field paths to remove from the response. | @@ -327,7 +327,7 @@ Console.WriteLine(response.Metadata.FirstHeaderValue("content-type")); ## Errors -The SDK throws typed exceptions instead of returning error objects for failed HTTP responses. +The SDK throws typed exceptions instead of returning error objects for failed HTTP responses. SDK error messages replace your configured API key with `[REDACTED]`. SDK error types and HTTP status codes stay the same. Some technical error details may be shortened to keep the key hidden. | Exception | When it happens | |-----------|-----------------| diff --git a/src/IPGeolocation.Test/IPGeolocation.Test.csproj b/src/IPGeolocation.Test/IPGeolocation.Test.csproj index 380aacf..d42caaa 100644 --- a/src/IPGeolocation.Test/IPGeolocation.Test.csproj +++ b/src/IPGeolocation.Test/IPGeolocation.Test.csproj @@ -3,7 +3,8 @@ IPGeolocation.Test IPGeolocation.Test - net8.0 + net8.0 + $(TestTargetFramework) false enable disable diff --git a/src/IPGeolocation.Test/IpLocation/ErrorHandlingTests.cs b/src/IPGeolocation.Test/IpLocation/ErrorHandlingTests.cs new file mode 100644 index 0000000..2201e34 --- /dev/null +++ b/src/IPGeolocation.Test/IpLocation/ErrorHandlingTests.cs @@ -0,0 +1,321 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using IPGeolocation.Internal; +using IPGeolocation.Test.IpLocation.Support; +using Xunit; + +namespace IPGeolocation.Test.IpLocation; + +public sealed class ErrorHandlingTests +{ + private const string ApiKey = "test-secret+/value"; + + public static IEnumerable ApiFailures() + { + var statuses = new (int Status, Type Type)[] + { + (400, typeof(BadRequestException)), (401, typeof(UnauthorizedException)), + (403, typeof(ForbiddenException)), (404, typeof(NotFoundException)), + (405, typeof(MethodNotAllowedException)), (413, typeof(ContentTooLargeException)), + (415, typeof(UnsupportedMediaTypeException)), (423, typeof(LockedException)), + (429, typeof(TooManyRequestsException)), (499, typeof(CustomStatus499Exception)), + (500, typeof(InternalServerErrorException)), (502, typeof(ApiException)) + }; + for (var method = 0; method < 4; method++) + { + foreach (var status in statuses) yield return new object[] { method, status.Status, status.Type }; + } + } + + [Theory] + [MemberData(nameof(ApiFailures))] + public async Task ApiErrorsHideKeysAndPreserveStatus(int method, int status, Type expectedType) + { + var transport = Response(status, JsonSerializer.Serialize(new { message = "Invalid API key: " + ApiKey })); + using var client = Client(transport); + + var error = await Assert.ThrowsAnyAsync(() => Invoke(client, method)); + + Assert.Equal(expectedType, error.GetType()); + Assert.Equal((HttpStatusCode)status, error.StatusCode); + Assert.Equal("Invalid API key: [REDACTED]", error.Message); + AssertHidden(error); + Assert.Contains("apiKey=" + Uri.EscapeDataString(ApiKey), transport.LastRequest!.Url); + } + + [Theory] + [InlineData("plain")] + [InlineData("encoded")] + [InlineData("encoded-lower")] + [InlineData("nested")] + public async Task RedactsDifferentErrorBodies(string form) + { + var encoded = Uri.EscapeDataString(ApiKey); + var body = form switch + { + "plain" => "Invalid key " + ApiKey + "", + "encoded" => "Request failed: ?apiKey=" + encoded, + "encoded-lower" => "Request failed: ?apiKey=" + encoded.Replace("%2B", "%2b").Replace("%2F", "%2f"), + "nested" => JsonSerializer.Serialize(new { error = new { message = ApiKey } }), + _ => JsonSerializer.Serialize(new { details = ApiKey }) + }; + using var client = Client(Response(503, body)); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationRawAsync()); + + AssertHidden(error); + Assert.DoesNotContain(encoded, error.ToString(), StringComparison.OrdinalIgnoreCase); + Assert.Contains("[REDACTED]", error.Message); + } + + [Theory] + [InlineData("{\"details\":\"test\\u002Dsecret+/value\"}")] + [InlineData("[\"test\\u002Dsecret+/value\"]")] + [InlineData("{\"error\":{\"details\":\"test\\u002Dsecret+/value\"}}")] + [InlineData("{\"message\":\"test\\u002Dsecret+/value\"")] + [InlineData("\" \"")] + public async Task UnknownStructuredErrorsUseTheStatusMessage(string body) + { + using var client = Client(Response(401, body)); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationAsync()); + + Assert.Equal("Unauthorized", error.Message); + AssertHidden(error); + } + + [Fact] + public async Task OverlyNestedJsonErrorsUseTheStatusMessage() + { + var body = new string('[', 70) + "\"test\\u002Dsecret+/value\"" + new string(']', 70); + using var client = Client(Response(401, body)); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationAsync()); + + Assert.Equal("Unauthorized", error.Message); + } + + [Theory] + [InlineData("{\"message\":\"test\\u002Dsecret+/value\"}")] + [InlineData("{\"error\":{\"message\":\"test\\u002Dsecret+/value\"}}")] + [InlineData("\"test\\u002Dsecret+/value\"")] + public async Task JsonEscapesAreDecodedBeforeRedaction(string body) + { + using var client = Client(Response(401, body)); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationAsync()); + + Assert.Equal("[REDACTED]", error.Message); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public async Task TransportErrorsDoNotRetainOriginalDetails(int method) + { + var detail = new SecretException(ApiKey); + var original = new TransportException("Network error " + ApiKey, new AggregateException(detail)); + original.Data["key"] = ApiKey; + original.HelpLink = "https://example.invalid/" + ApiKey; + var transport = new FakeTransport(); + transport.QueueException(original); + using var client = Client(transport); + + var error = await Assert.ThrowsAsync(() => Invoke(client, method)); + + AssertHidden(error); + Assert.NotSame(original, error); + for (Exception? current = error; current is not null; current = current.InnerException) + { + Assert.NotSame(original, current); + Assert.NotSame(detail, current); + Assert.Empty(current.Data); + Assert.Null(current.HelpLink); + Assert.IsNotType(current); + Assert.IsNotType(current); + } + } + + [Fact] + public async Task DeepErrorDetailsAreBounded() + { + Exception detail = new SecretException(ApiKey); + for (var i = 0; i < 100; i++) detail = new Exception("Nested " + ApiKey, detail); + var transport = new FakeTransport(); + transport.QueueException(new RequestTimeoutException("Timeout " + ApiKey, detail)); + using var client = Client(transport); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationAsync()); + + AssertHidden(error); + var depth = 0; + for (Exception? current = error; current is not null; current = current.InnerException) depth++; + Assert.InRange(depth, 1, 12); + } + + [Fact] + public async Task CallerCancellationRemainsCancellation() + { + using var source = new CancellationTokenSource(); + source.Cancel(); + var transport = new FakeTransport(); + transport.QueueException(new OperationCanceledException("Cancelled " + ApiKey, new SecretException(ApiKey), source.Token)); + using var client = Client(transport); + + var task = client.LookupIpGeolocationAsync(cancellationToken: source.Token); + var error = await Assert.ThrowsAnyAsync(() => task); + + Assert.True(task.IsCanceled); + Assert.Equal(source.Token, error.CancellationToken); + AssertHidden(error); + } + + [Fact] + public async Task OriginOnlyRequestsKeepTheirOriginalErrorDetails() + { + var original = new TransportException("Unchanged details", new HttpRequestException("Original cause")); + var transport = new FakeTransport(); + transport.QueueException(original); + using var client = new IpGeolocationClient(new IpGeolocationClientConfig(requestOrigin: "https://example.com"), transport); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationAsync()); + + Assert.Same(original, error); + } + + [Fact] + public async Task TypedBulkRedactsOnlyErrorMessages() + { + var body = JsonSerializer.Serialize(new object[] { new { ip = ApiKey }, new { error = new { message = ApiKey } } }); + using var client = Client(Response(200, body)); + + var result = await client.BulkLookupIpGeolocationAsync(new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8" })); + + Assert.Equal(ApiKey, Assert.IsType(result.Data[0]).Data.Ip); + Assert.Equal("[REDACTED]", Assert.IsType(result.Data[1]).Error.Message); + } + + [Theory] + [InlineData(false, ResponseFormat.Json)] + [InlineData(false, ResponseFormat.Xml)] + [InlineData(true, ResponseFormat.Json)] + [InlineData(true, ResponseFormat.Xml)] + public async Task SuccessfulRawBodiesStayUnchanged(bool bulk, ResponseFormat output) + { + var body = output == ResponseFormat.Json ? JsonSerializer.Serialize(new { message = ApiKey }) : "" + ApiKey + ""; + using var client = Client(Response(200, body)); + + var result = bulk + ? await client.BulkLookupIpGeolocationRawAsync(new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8" }, output: output)) + : await client.LookupIpGeolocationRawAsync(new LookupIpGeolocationRequest(output: output)); + + Assert.Equal(body, result.Data); + } + + [Fact] + public async Task JsonParseErrorsDoNotExposeKeysInTheirDetails() + { + using var client = Client(Response(200, "{\"" + ApiKey + "\": invalid}")); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationAsync()); + + AssertHidden(error); + } + + [Theory] + [InlineData("test-key")] + [InlineData("test+key/with spaces")] + [InlineData("test-مفتاح-🔑")] + [InlineData("test-\"quoted\"-key")] + [InlineData("test.*(key)[1]")] + public async Task EncodedKeysAreHiddenWithoutChangingAuthentication(string key) + { + var json = JsonSerializer.Serialize(key); + var forms = new[] { key, Uri.EscapeDataString(key), json.Substring(1, json.Length - 2) }; + foreach (var form in forms) + { + var transport = Response(401, "Rejected: " + form); + using var client = new IpGeolocationClient(new IpGeolocationClientConfig(apiKey: key), transport); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationRawAsync()); + + Assert.Equal("Rejected: [REDACTED]", error.Message); + Assert.Contains("apiKey=" + Uri.EscapeDataString(key), transport.LastRequest!.Url); + } + } + + [Fact] + public async Task UnreadableErrorMessagesDoNotReplaceTheSdkError() + { + var transport = new FakeTransport(); + transport.QueueException(new TransportException("Failure", new UnreadableException())); + using var client = Client(transport); + + var error = await Assert.ThrowsAsync(() => client.LookupIpGeolocationAsync()); + + Assert.Equal("Failure", error.Message); + Assert.Contains("Error details unavailable.", error.InnerException!.Message); + AssertHidden(error); + } + + [Fact] + public async Task TaskCancellationKeepsItsTypeAndToken() + { + using var source = new CancellationTokenSource(); + source.Cancel(); + var transport = new FakeTransport(); + transport.QueueException(new TaskCanceledException(ApiKey, null, source.Token)); + using var client = Client(transport); + + var task = client.LookupIpGeolocationAsync(cancellationToken: source.Token); + var error = await Assert.ThrowsAsync(() => task); + + Assert.True(task.IsCanceled); + Assert.Equal(source.Token, error.CancellationToken); + Assert.Equal("[REDACTED]", error.Message); + } + + private static FakeTransport Response(int status, string body) + { + var transport = new FakeTransport(); + transport.QueueResponse(new HttpResponseData(status, body, new Dictionary>())); + return transport; + } + + private static IpGeolocationClient Client(FakeTransport transport) => new(new IpGeolocationClientConfig(apiKey: ApiKey), transport); + + private static Task Invoke(IpGeolocationClient client, int method) => method switch + { + 0 => client.LookupIpGeolocationAsync(), + 1 => client.LookupIpGeolocationRawAsync(), + 2 => client.BulkLookupIpGeolocationAsync(new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8" })), + _ => client.BulkLookupIpGeolocationRawAsync(new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8" })) + }; + + private static void AssertHidden(Exception error) => Assert.DoesNotContain(ApiKey, error.ToString(), StringComparison.Ordinal); + + private sealed class SecretException : Exception + { + public SecretException(string key) : base("Underlying error " + key) + { + Secret = key; + Data["key"] = key; + } + + public string Secret { get; } + public override string ToString() => Secret; + } + + private sealed class UnreadableException : Exception + { + public override string Message => throw new InvalidOperationException(ApiKey); + } +} diff --git a/src/IPGeolocation.Test/IpLocation/HttpClientTransportTests.cs b/src/IPGeolocation.Test/IpLocation/HttpClientTransportTests.cs index 757af0c..0d40b54 100644 --- a/src/IPGeolocation.Test/IpLocation/HttpClientTransportTests.cs +++ b/src/IPGeolocation.Test/IpLocation/HttpClientTransportTests.cs @@ -13,6 +13,55 @@ namespace IPGeolocation.Test.IpLocation; public sealed class HttpClientTransportTests { + [Theory] + [InlineData(1L)] + [InlineData(9999L)] + [InlineData(10000L)] + [InlineData(21474836470000L)] + [InlineData(25920000000000L)] + [InlineData(42949672940000L)] + [InlineData(long.MaxValue)] + public void PositiveTimeoutsCanBeScheduled(long ticks) + { + using var source = new CancellationTokenSource(); + HttpClientTransport.SetTimeout(source, TimeSpan.FromTicks(ticks)); + source.Cancel(); + Assert.True(source.IsCancellationRequested); + } + + [Theory] + [InlineData(long.MaxValue)] + [InlineData(21474836480000L)] + public async Task LargeTimeoutsDoNotFailBeforeSending(long ticks) + { + var calls = 0; + using var client = new HttpClient(new StubHandler(_ => + { + calls++; + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("ok") }; + })); + using var transport = new HttpClientTransport(client); + + var response = await transport.SendAsync(CreateRequest(TimeSpan.FromTicks(ticks), TimeSpan.FromTicks(ticks)), CancellationToken.None); + + Assert.Equal(1, calls); + Assert.Equal("ok", response.Body); + } + + [Fact] + public async Task PreCancelledRequestsRemainCancelled() + { + using var source = new CancellationTokenSource(); + source.Cancel(); + using var client = new HttpClient(new StubHandler(_ => new HttpResponseMessage(HttpStatusCode.OK))); + using var transport = new HttpClientTransport(client); + + var task = transport.SendAsync(CreateRequest(), source.Token); + + await Assert.ThrowsAnyAsync(() => task); + Assert.True(task.IsCanceled); + } + [Fact] public async Task ReturnsResponseDataAndHeaders() { diff --git a/src/IPGeolocation.Test/IpLocation/IpGeolocationClientConfigTests.cs b/src/IPGeolocation.Test/IpLocation/IpGeolocationClientConfigTests.cs index a06a102..2517e85 100644 --- a/src/IPGeolocation.Test/IpLocation/IpGeolocationClientConfigTests.cs +++ b/src/IPGeolocation.Test/IpLocation/IpGeolocationClientConfigTests.cs @@ -6,6 +6,31 @@ namespace IPGeolocation.Test.IpLocation; public sealed class IpGeolocationClientConfigTests { + [Theory] + [InlineData(1L)] + [InlineData(9999L)] + [InlineData(10000L)] + [InlineData(21474836470000L)] + [InlineData(long.MaxValue)] + public void KeepsConfiguredPositiveTimeoutValues(long ticks) + { + var value = TimeSpan.FromTicks(ticks); + var config = new IpGeolocationClientConfig(connectTimeout: value, readTimeout: value); + Assert.Equal(value, config.ConnectTimeout); + Assert.Equal(value, config.ReadTimeout); + } + + [Theory] + [InlineData(0L)] + [InlineData(-1L)] + [InlineData(-10000L)] + [InlineData(long.MinValue)] + public void RejectsNonPositiveTimeouts(long ticks) + { + Assert.Throws(() => new IpGeolocationClientConfig(connectTimeout: TimeSpan.FromTicks(ticks))); + Assert.Throws(() => new IpGeolocationClientConfig(readTimeout: TimeSpan.FromTicks(ticks))); + } + [Fact] public void NormalizesRequestOriginAndBaseUrl() { diff --git a/src/IPGeolocation.Test/IpLocation/IpGeolocationClientTests.cs b/src/IPGeolocation.Test/IpLocation/IpGeolocationClientTests.cs index 4a5eff2..3a33ef7 100644 --- a/src/IPGeolocation.Test/IpLocation/IpGeolocationClientTests.cs +++ b/src/IPGeolocation.Test/IpLocation/IpGeolocationClientTests.cs @@ -8,6 +8,33 @@ namespace IPGeolocation.Test.IpLocation; public sealed class IpGeolocationClientTests { + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(2)] + [InlineData(3)] + public async Task ArabicIsForwardedByEveryLookupMethod(int method) + { + var transport = new FakeTransport(); + transport.QueueResponse(new HttpResponseData(200, + method < 2 ? "{\"ip\":\"8.8.8.8\"}" : "[{\"ip\":\"8.8.8.8\"}]", + new Dictionary>())); + using var client = new IpGeolocationClient(new IpGeolocationClientConfig(apiKey: "test-key"), transport); + var single = new LookupIpGeolocationRequest(ip: "8.8.8.8", lang: " AR "); + var bulk = new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8" }, lang: " AR "); + + switch (method) + { + case 0: await client.LookupIpGeolocationAsync(single); break; + case 1: await client.LookupIpGeolocationRawAsync(single); break; + case 2: await client.BulkLookupIpGeolocationAsync(bulk); break; + default: await client.BulkLookupIpGeolocationRawAsync(bulk); break; + } + + Assert.Contains("lang=ar", transport.LastRequest!.Url); + Assert.Contains("apiKey=test-key", transport.LastRequest.Url); + } + [Fact] public async Task LookupBuildsRequestWithExpectedHeaders() { diff --git a/src/IPGeolocation.Test/IpLocation/LiveIntegrationTests.cs b/src/IPGeolocation.Test/IpLocation/LiveIntegrationTests.cs index 6229e2a..695cf28 100644 --- a/src/IPGeolocation.Test/IpLocation/LiveIntegrationTests.cs +++ b/src/IPGeolocation.Test/IpLocation/LiveIntegrationTests.cs @@ -7,6 +7,19 @@ namespace IPGeolocation.Test.IpLocation; public sealed class LiveIntegrationTests { + [SkippableFact] + public async Task ArabicLookupsLive() + { + var apiKey = LiveTestGuard.RequirePaidKeyForLive(); + using var client = new IpGeolocationClient(new IpGeolocationClientConfig(apiKey: apiKey)); + + var single = await client.LookupIpGeolocationAsync(new LookupIpGeolocationRequest(ip: "8.8.8.8", lang: "ar")); + var bulk = await client.BulkLookupIpGeolocationAsync(new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8" }, lang: "ar")); + + Assert.Matches(@"[\u0600-\u06ff]", single.Data.Location?.CountryName ?? string.Empty); + Assert.Matches(@"[\u0600-\u06ff]", Assert.IsType(Assert.Single(bulk.Data)).Data.Location?.CountryName ?? string.Empty); + } + [SkippableFact] public async Task SingleLookupLive() { diff --git a/src/IPGeolocation.Test/IpLocation/RequestModelTests.cs b/src/IPGeolocation.Test/IpLocation/RequestModelTests.cs index 8a20aae..f94a354 100644 --- a/src/IPGeolocation.Test/IpLocation/RequestModelTests.cs +++ b/src/IPGeolocation.Test/IpLocation/RequestModelTests.cs @@ -5,6 +5,16 @@ namespace IPGeolocation.Test.IpLocation; public sealed class RequestModelTests { + [Theory] + [InlineData("ar")] + [InlineData("AR")] + [InlineData(" ar ")] + public void AcceptsArabicForSingleAndBulk(string language) + { + Assert.Equal("ar", new LookupIpGeolocationRequest(lang: language).Lang); + Assert.Equal("ar", new BulkLookupIpGeolocationRequest(new[] { "8.8.8.8" }, lang: language).Lang); + } + [Fact] public void LookupRequestNormalizesListsAndHeaders() { diff --git a/src/IPGeolocation.Test/IpLocation/SerDeTests.cs b/src/IPGeolocation.Test/IpLocation/SerDeTests.cs index 8c8912b..6bc0f89 100644 --- a/src/IPGeolocation.Test/IpLocation/SerDeTests.cs +++ b/src/IPGeolocation.Test/IpLocation/SerDeTests.cs @@ -6,6 +6,69 @@ namespace IPGeolocation.Test.IpLocation; public sealed class SerDeTests { + [Theory] + [InlineData("null")] + [InlineData("[]")] + [InlineData("1")] + [InlineData("\"text\"")] + [InlineData("")] + [InlineData("{")] + public void InvalidSingleRootsUseSerializationException(string body) + { + Assert.Throws(() => SerDe.ParseSingleLookup(body)); + } + + [Theory] + [InlineData("[null]")] + [InlineData("[1]")] + [InlineData("[true]")] + [InlineData("[\"text\"]")] + [InlineData("[[]]")] + [InlineData("{}")] + [InlineData("null")] + [InlineData("[")] + public void InvalidBulkShapesUseSerializationException(string body) + { + Assert.Throws(() => SerDe.ParseBulkLookup(body)); + } + + [Theory] + [InlineData("{\"error\":null}")] + [InlineData("{\"error\":true}")] + [InlineData("{\"error\":1}")] + [InlineData("{\"error\":[]}")] + [InlineData("{\"error\":\"failure\"}")] + [InlineData("{\"message\":\" \"}")] + [InlineData("{\"error\":{\"message\":\"\"}}")] + public void UnusualErrorBodiesPreserveHttpStatus(string body) + { + var error = SerDe.ToApiException(401, body); + Assert.IsType(error); + Assert.False(string.IsNullOrWhiteSpace(error.Message)); + } + + [Theory] + [InlineData("[{\"error\":null}]")] + [InlineData("[{\"error\":true}]")] + [InlineData("[{\"error\":\"failure\"}]")] + [InlineData("[{\"message\":\" \"}]")] + [InlineData("[{\"error\":{\"message\":\"\"}}]")] + public void UnusualBulkErrorsHaveUsableMessages(string body) + { + var result = SerDe.ParseBulkLookup(body); + var error = Assert.IsType(Assert.Single(result)); + Assert.False(string.IsNullOrWhiteSpace(error.Error.Message)); + } + + [Fact] + public void InvalidOptionalObjectsRemainIgnored() + { + var result = SerDe.ParseSingleLookup("{\"ip\":\"8.8.8.8\",\"location\":123,\"security\":[]}"); + Assert.Equal("8.8.8.8", result.Ip); + Assert.Null(result.Location); + Assert.Null(result.Security); + } + [Fact] public void ParsesMixedBulkSuccessAndError() { diff --git a/src/IPGeolocation/IPGeolocation.csproj b/src/IPGeolocation/IPGeolocation.csproj index b0a98d0..5099738 100644 --- a/src/IPGeolocation/IPGeolocation.csproj +++ b/src/IPGeolocation/IPGeolocation.csproj @@ -13,12 +13,17 @@ IPGeolocation IPGeolocation IPGeoLocation.IPGeolocation - 3.0.0 + 3.0.1 IPGeolocation.io IPGeolocation.io IPGeolocation .NET SDK Official .NET SDK for the IPGeolocation.io IP Location API with single and bulk lookup, typed responses, and raw JSON or XML support. - Replaced the old generated multi-API SDK with the new .NET SDK for the IPGeolocation.io IP Location API. + - Hide API keys in error messages and details. +- Handle incomplete or invalid error responses. +- Fix request handling for very short or very long timeouts. +- Add Arabic (`ar`) for single and bulk lookups. + +Existing public methods and .NET Standard 2.1 support remain unchanged. MIT https://ipgeolocation.io README.md diff --git a/src/IPGeolocation/Internal/ErrorSanitizer.cs b/src/IPGeolocation/Internal/ErrorSanitizer.cs new file mode 100644 index 0000000..a4d1842 --- /dev/null +++ b/src/IPGeolocation/Internal/ErrorSanitizer.cs @@ -0,0 +1,71 @@ +using System; +using System.Linq; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace IPGeolocation.Internal; + +internal static class ErrorSanitizer +{ + internal static string Redact(string value, string? apiKey) + { + if (apiKey is null) return value; + + try + { + var json = JsonSerializer.Serialize(apiKey); + var forms = new[] { apiKey, Uri.EscapeDataString(apiKey), json.Substring(1, json.Length - 2) }; + var pattern = string.Join("|", forms.Distinct(StringComparer.OrdinalIgnoreCase) + .OrderByDescending(form => form.Length).Select(Regex.Escape)); + return new Regex(pattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)) + .Replace(value, "[REDACTED]"); + } + catch (Exception) + { + return "Error details omitted."; + } + } + + internal static Exception Sanitize(Exception error, string apiKey) + { + var message = Redact(ReadMessage(error), apiKey); + var inner = CopyDetails(error.InnerException, apiKey, 0); + + return error switch + { + ApiException api when api.GetType() == typeof(ApiException) => new ApiException(api.StatusCode, message), + ApiException api => SerDe.CreateApiException((int)api.StatusCode, message), + ValidationException _ => new ValidationException(message), + RequestTimeoutException _ => new RequestTimeoutException(message, inner), + TransportException _ => new TransportException(message, inner), + SerializationException _ => new SerializationException(message, inner), + IpGeolocationException _ => new IpGeolocationException(message, inner), + TaskCanceledException canceled => new TaskCanceledException(message, inner, canceled.CancellationToken), + OperationCanceledException canceled => new OperationCanceledException(message, inner, canceled.CancellationToken), + _ => new TransportException(message, CopyDetails(error, apiKey, 0)) + }; + } + + private static Exception? CopyDetails(Exception? error, string apiKey, int depth) + { + if (error is null) return null; + if (depth == 8) return new Exception("Additional error details omitted."); + + return new Exception( + Redact(error.GetType().Name + ": " + ReadMessage(error), apiKey), + CopyDetails(error.InnerException, apiKey, depth + 1)); + } + + private static string ReadMessage(Exception error) + { + try + { + return error.Message; + } + catch (Exception) + { + return "Error details unavailable."; + } + } +} diff --git a/src/IPGeolocation/Internal/HttpClientTransport.cs b/src/IPGeolocation/Internal/HttpClientTransport.cs index eee15b9..e459549 100644 --- a/src/IPGeolocation/Internal/HttpClientTransport.cs +++ b/src/IPGeolocation/Internal/HttpClientTransport.cs @@ -65,7 +65,7 @@ public async Task SendAsync(HttpRequestData request, Cancellat HttpResponseMessage response; using (var connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { - connectCts.CancelAfter(request.ConnectTimeout); + SetTimeout(connectCts, request.ConnectTimeout); try { @@ -125,7 +125,7 @@ private async Task ReadBodyAsync(HttpResponseMessage response, TimeSpan int bytesRead; using (var readCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { - readCts.CancelAfter(readTimeout); + SetTimeout(readCts, readTimeout); try { @@ -160,4 +160,16 @@ private async Task ReadBodyAsync(HttpResponseMessage response, TimeSpan return Encoding.UTF8.GetString(buffer.ToArray()); } + + internal static void SetTimeout(CancellationTokenSource source, TimeSpan timeout) + { + try + { + source.CancelAfter(timeout < TimeSpan.FromMilliseconds(1) ? TimeSpan.FromMilliseconds(1) : timeout); + } + catch (ArgumentOutOfRangeException) + { + source.CancelAfter(int.MaxValue); + } + } } diff --git a/src/IPGeolocation/Internal/RequestNormalizer.cs b/src/IPGeolocation/Internal/RequestNormalizer.cs index 88fb9e4..ba5b878 100644 --- a/src/IPGeolocation/Internal/RequestNormalizer.cs +++ b/src/IPGeolocation/Internal/RequestNormalizer.cs @@ -7,7 +7,7 @@ internal static class RequestNormalizer { private static readonly HashSet AllowedLanguages = new(StringComparer.OrdinalIgnoreCase) { - "en", "de", "ru", "ja", "fr", "cn", "es", "cs", "it", "ko", "fa", "pt" + "en", "de", "ru", "ja", "fr", "cn", "es", "cs", "it", "ko", "fa", "pt", "ar" }; internal static string? NormalizeLookupIp(string? value) @@ -67,7 +67,7 @@ internal static IReadOnlyList NormalizeIpList(IEnumerable values if (!AllowedLanguages.Contains(normalized)) { - throw new ValidationException("lang must be one of: en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt"); + throw new ValidationException("lang must be one of: en, de, ru, ja, fr, cn, es, cs, it, ko, fa, pt, ar"); } return normalized.ToLowerInvariant(); diff --git a/src/IPGeolocation/Internal/SerDe.cs b/src/IPGeolocation/Internal/SerDe.cs index bcc77ee..7cfdef1 100644 --- a/src/IPGeolocation/Internal/SerDe.cs +++ b/src/IPGeolocation/Internal/SerDe.cs @@ -59,7 +59,11 @@ internal static ApiResponseMetadata ToMetadata(int statusCode, int durationMs, I internal static ApiException ToApiException(int statusCode, string body) { var message = ExtractApiMessage(body) ?? DefaultApiMessage(statusCode); + return CreateApiException(statusCode, message); + } + internal static ApiException CreateApiException(int statusCode, string message) + { return statusCode switch { 400 => new BadRequestException(message), @@ -95,7 +99,7 @@ internal static IpGeolocationResponse ParseSingleLookup(string body) } } - internal static IReadOnlyList ParseBulkLookup(string body) + internal static IReadOnlyList ParseBulkLookup(string body, string? apiKey = null) { try { @@ -108,9 +112,15 @@ internal static IReadOnlyList ParseBulkLookup(string body) var result = new List(); foreach (var item in document.RootElement.EnumerateArray()) { + if (item.ValueKind != JsonValueKind.Object) + { + throw new SerializationException("Expected a JSON object for each bulk lookup response item"); + } + if (IsBulkError(item)) { - result.Add(new BulkLookupError(new BulkLookupErrorDetails(ReadBulkErrorMessage(item)))); + var message = ReadErrorMessage(item) ?? "Bulk lookup item failed"; + result.Add(new BulkLookupError(new BulkLookupErrorDetails(ErrorSanitizer.Redact(message, apiKey)))); } else { @@ -132,11 +142,19 @@ private static bool IsBulkError(JsonElement item) && (item.TryGetProperty("error", out _) || (item.TryGetProperty("message", out _) && !item.TryGetProperty("ip", out _))); } - private static string ReadBulkErrorMessage(JsonElement item) + private static string? ReadErrorMessage(JsonElement item) { - return ReadString(item, "message") - ?? (item.TryGetProperty("error", out var errorObject) ? ReadString(errorObject, "message") : null) - ?? "Bulk lookup item failed"; + var message = ReadString(item, "message"); + if (!string.IsNullOrWhiteSpace(message)) return message; + if (!item.TryGetProperty("error", out var error)) return null; + + message = error.ValueKind switch + { + JsonValueKind.Object => ReadString(error, "message"), + JsonValueKind.String => error.GetString(), + _ => null + }; + return string.IsNullOrWhiteSpace(message) ? null : message; } private static IpGeolocationResponse ParseResponse(JsonElement root) @@ -305,16 +323,16 @@ private static IpGeolocationResponse ParseResponse(JsonElement root) using var document = JsonDocument.Parse(body); if (document.RootElement.ValueKind != JsonValueKind.Object) { - return body.Trim(); + var message = document.RootElement.ValueKind == JsonValueKind.String ? document.RootElement.GetString() : null; + return string.IsNullOrWhiteSpace(message) ? null : message; } - return ReadString(document.RootElement, "message") - ?? (document.RootElement.TryGetProperty("error", out var errorObject) ? ReadString(errorObject, "message") : null) - ?? body.Trim(); + return ReadErrorMessage(document.RootElement); } catch (JsonException) { - return body.Trim(); + var trimmed = body.Trim(); + return trimmed[0] is '{' or '[' or '"' ? null : trimmed; } } diff --git a/src/IPGeolocation/IpGeolocationClient.cs b/src/IPGeolocation/IpGeolocationClient.cs index 8883145..8806a01 100644 --- a/src/IPGeolocation/IpGeolocationClient.cs +++ b/src/IPGeolocation/IpGeolocationClient.cs @@ -60,16 +60,7 @@ public async Task> LookupIpGeolocationAsync( ValidateLookupRequestBase(); SerDe.ValidateJsonOutput(typedRequest.Output); - var (response, durationMs) = await ExecuteWithMetricsAsync(BuildLookupHttpRequest(typedRequest), cancellationToken).ConfigureAwait(false); - if (!IsSuccessStatus(response.StatusCode)) - { - throw SerDe.ToApiException(response.StatusCode, response.Body); - } - - return new ApiResponse( - SerDe.ParseSingleLookup(response.Body), - SerDe.ToMetadata(response.StatusCode, durationMs, response.Headers) - ); + return await ExecuteAsync(() => BuildLookupHttpRequest(typedRequest), SerDe.ParseSingleLookup, cancellationToken).ConfigureAwait(false); } public async Task> LookupIpGeolocationRawAsync( @@ -80,16 +71,7 @@ public async Task> LookupIpGeolocationRawAsync( var typedRequest = request ?? new LookupIpGeolocationRequest(); ValidateLookupRequestBase(); - var (response, durationMs) = await ExecuteWithMetricsAsync(BuildLookupHttpRequest(typedRequest), cancellationToken).ConfigureAwait(false); - if (!IsSuccessStatus(response.StatusCode)) - { - throw SerDe.ToApiException(response.StatusCode, response.Body); - } - - return new ApiResponse( - response.Body, - SerDe.ToMetadata(response.StatusCode, durationMs, response.Headers) - ); + return await ExecuteAsync(() => BuildLookupHttpRequest(typedRequest), body => body, cancellationToken).ConfigureAwait(false); } public async Task>> BulkLookupIpGeolocationAsync( @@ -104,16 +86,7 @@ public async Task>> BulkLookupIpGeol ValidateBulkRequestBase(); SerDe.ValidateJsonOutput(request.Output); - var (response, durationMs) = await ExecuteWithMetricsAsync(BuildBulkHttpRequest(request), cancellationToken).ConfigureAwait(false); - if (!IsSuccessStatus(response.StatusCode)) - { - throw SerDe.ToApiException(response.StatusCode, response.Body); - } - - return new ApiResponse>( - SerDe.ParseBulkLookup(response.Body), - SerDe.ToMetadata(response.StatusCode, durationMs, response.Headers) - ); + return await ExecuteAsync(() => BuildBulkHttpRequest(request), body => SerDe.ParseBulkLookup(body, _config.ApiKey), cancellationToken).ConfigureAwait(false); } public async Task> BulkLookupIpGeolocationRawAsync( @@ -127,16 +100,7 @@ public async Task> BulkLookupIpGeolocationRawAsync( } ValidateBulkRequestBase(); - var (response, durationMs) = await ExecuteWithMetricsAsync(BuildBulkHttpRequest(request), cancellationToken).ConfigureAwait(false); - if (!IsSuccessStatus(response.StatusCode)) - { - throw SerDe.ToApiException(response.StatusCode, response.Body); - } - - return new ApiResponse( - response.Body, - SerDe.ToMetadata(response.StatusCode, durationMs, response.Headers) - ); + return await ExecuteAsync(() => BuildBulkHttpRequest(request), body => body, cancellationToken).ConfigureAwait(false); } private void EnsureNotDisposed() @@ -247,12 +211,26 @@ private Dictionary BuildHeaders( return headers; } - private async Task<(HttpResponseData Response, int DurationMs)> ExecuteWithMetricsAsync(HttpRequestData request, CancellationToken cancellationToken) + private async Task> ExecuteAsync(Func buildRequest, Func parse, CancellationToken cancellationToken) { - var stopwatch = Stopwatch.StartNew(); - var response = await _transport.SendAsync(request, cancellationToken).ConfigureAwait(false); - stopwatch.Stop(); - return (response, (int)stopwatch.ElapsedMilliseconds); + try + { + var request = buildRequest(); + var stopwatch = Stopwatch.StartNew(); + var response = await _transport.SendAsync(request, cancellationToken).ConfigureAwait(false); + stopwatch.Stop(); + if (!IsSuccessStatus(response.StatusCode)) + { + throw SerDe.ToApiException(response.StatusCode, response.Body); + } + + return new ApiResponse(parse(response.Body), + SerDe.ToMetadata(response.StatusCode, (int)Math.Min(stopwatch.ElapsedMilliseconds, int.MaxValue), response.Headers)); + } + catch (Exception error) when (_config.ApiKey is not null) + { + throw ErrorSanitizer.Sanitize(error, _config.ApiKey); + } } private static bool IsSuccessStatus(int statusCode) diff --git a/src/IPGeolocation/SdkVersion.cs b/src/IPGeolocation/SdkVersion.cs index 40b5831..0828706 100644 --- a/src/IPGeolocation/SdkVersion.cs +++ b/src/IPGeolocation/SdkVersion.cs @@ -2,5 +2,5 @@ namespace IPGeolocation; public static class SdkVersion { - public const string Value = "3.0.0"; + public const string Value = "3.0.1"; }