Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -351,4 +351,5 @@ MigrationBackup/
# Intell-J Rider etc.
.idea/*

.vscode/*
.vscode/*
**/.DS_Store
23 changes: 17 additions & 6 deletions src/Auth0.AuthenticationApi/AuthenticationApiClient.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -41,7 +42,7 @@
/// <code>var client = new AuthenticationApiClient(baseUri, new HttpClientAuthenticationConnection(myHttpClient));</code> or
/// <code>var client = new AuthenticationApiClient(baseUri, new HttpClientAuthenticationConnection(myHttpMessageHandler));</code> or
/// </remarks>
public AuthenticationApiClient(Uri baseUri, IAuthenticationConnection connection = null)

Check warning on line 45 in src/Auth0.AuthenticationApi/AuthenticationApiClient.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
{
BaseUri = baseUri;
if (connection == null)
Expand Down Expand Up @@ -71,7 +72,7 @@
/// <code>var client = new AuthenticationApiClient(domain, new HttpClientAuthenticationConnection(myHttpClient));</code> or
/// <code>var client = new AuthenticationApiClient(domain, new HttpClientAuthenticationConnection(myHttpMessageHandler));</code> or
/// </remarks>
public AuthenticationApiClient(string domain, IAuthenticationConnection connection = null)

Check warning on line 75 in src/Auth0.AuthenticationApi/AuthenticationApiClient.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
: this(new Uri($"https://{domain}"), connection)
{
}
Expand Down Expand Up @@ -240,8 +241,7 @@
body.AddIfNotEmpty("realm", request.Realm);
body.Add("grant_type", String.IsNullOrEmpty(request.Realm) ? "password" : "http://auth0.com/oauth/grant-type/password-realm");

var headers = String.IsNullOrEmpty(request.ForwardedForIp) ? null
: new Dictionary<string, string> { { "auth0-forwarded-for", request.ForwardedForIp } };
var headers = BuildForwardedForHeaders(request.ForwardedForIp);

var response = await connection.SendAsync<AccessTokenResponse>(
HttpMethod.Post,
Expand Down Expand Up @@ -300,8 +300,7 @@

ApplyClientAuthentication(request, body);

var headers = String.IsNullOrEmpty(request.ForwardedForIp) ? null
: new Dictionary<string, string> { { "auth0-forwarded-for", request.ForwardedForIp } };
var headers = BuildForwardedForHeaders(request.ForwardedForIp);

var response = await connection.SendAsync<AccessTokenResponse>(
HttpMethod.Post,
Expand Down Expand Up @@ -421,8 +420,7 @@
phone_number = request.PhoneNumber
};

var headers = String.IsNullOrEmpty(request.ForwardedForIp) ? null
: new Dictionary<string, string> { { "auth0-forwarded-for", request.ForwardedForIp } };
var headers = BuildForwardedForHeaders(request.ForwardedForIp);

return connection.SendAsync<PasswordlessSmsResponse>(
HttpMethod.Post,
Expand Down Expand Up @@ -702,7 +700,7 @@
GC.SuppressFinalize(this);
}

private async Task AssertIdTokenValidIfExisting(string idToken, string audience, JwtSignatureAlgorithm algorithm, string clientSecret, string organization = null)

Check warning on line 703 in src/Auth0.AuthenticationApi/AuthenticationApiClient.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
{
if (!string.IsNullOrEmpty(idToken))
{
Expand All @@ -710,7 +708,7 @@
}
}

private Task AssertIdTokenValid(string idToken, string audience, JwtSignatureAlgorithm algorithm, string clientSecret, string organization = null)

Check warning on line 711 in src/Auth0.AuthenticationApi/AuthenticationApiClient.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
{
var requirements = new IdTokenRequirements(algorithm, BaseUri.AbsoluteUri, audience, idTokenValidationLeeway, null, organization);
return idTokenValidator.Assert(requirements, idToken, clientSecret);
Expand All @@ -726,6 +724,19 @@
return new Dictionary<string, string> { { "Authorization", "Bearer " + accessToken } };
}

internal static IDictionary<string, string>? BuildForwardedForHeaders(string? forwardedForIp)
{
if (String.IsNullOrEmpty(forwardedForIp))
return null;

if (!IPAddress.TryParse(forwardedForIp, out _))
throw new ArgumentException(
$"ForwardedForIp must be a valid IPv4 or IPv6 address, got: '{forwardedForIp}'.",
nameof(forwardedForIp));

return new Dictionary<string, string> { { "auth0-forwarded-for", forwardedForIp! } };
}

private void ApplyClientAuthentication(IClientAuthentication request, Dictionary<string, string> body, bool requireSecret = false)
{
if (requireSecret)
Expand Down
46 changes: 37 additions & 9 deletions src/Auth0.Core/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,16 +92,44 @@ public static class Extensions
if (string.IsNullOrEmpty(headerValue))
return null;

var kvp = headerValue
.Split(';')
.Select(x => x.Split('='))
.ToDictionary(keyValue => keyValue[0], keyValue => keyValue[1]);
bucket = kvp["b"];
var kvp = new Dictionary<string, string>();
foreach (var segment in headerValue.Split(';'))
{
var parts = segment.Split(['='], 2);
if (parts.Length != 2 || parts[0].Length == 0 || parts[1].Length == 0)
return null;

var key = parts[0];
var value = parts[1];

// Duplicate keys indicate a malformed header
if (kvp.ContainsKey(key))
return null;

kvp[key] = value;
}

if (!kvp.TryGetValue("b", out var bucketValue)
|| !kvp.TryGetValue("q", out var quota)
|| !kvp.TryGetValue("r", out var remaining)
|| !kvp.TryGetValue("t", out var resetAfter))
{
return null;
}

if (!int.TryParse(quota, out var quotaInt)
|| !int.TryParse(remaining, out var remainingInt)
|| !int.TryParse(resetAfter, out var resetAfterInt))
{
return null;
}

bucket = bucketValue;
return new QuotaLimit
{
Quota = int.Parse(kvp["q"]),
Remaining = int.Parse(kvp["r"]),
ResetAfter = int.Parse(kvp["t"])
Quota = quotaInt,
Remaining = remainingInt,
ResetAfter = resetAfterInt
};
}
}
}
6 changes: 3 additions & 3 deletions src/Auth0.Core/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ internal static byte[] Base64UrlDecode(string input)
internal static string Base64UrlEncode(byte[] input)
{
var output = Convert.ToBase64String(input);
output = output.Replace('-', '+');
output = output.Replace('_', '/');
output = output.PadRight(output.Length + (4 - output.Length % 4) % 4, '=');
output = output.Replace('+', '-');
output = output.Replace('/', '_');
output = output.TrimEnd('=');

return output;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Auth0.Tests.Shared;
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Net.Http;
Expand Down Expand Up @@ -46,4 +47,60 @@ public Task<T> SendAsync<T>(HttpMethod method, Uri uri, object body, IDictionary
return Task.FromResult(default(T));
}
}

[Fact]
public void BuildForwardedForHeaders_WithNull_ReturnsNull()
{
var result = AuthenticationApiClient.BuildForwardedForHeaders(null);
result.Should().BeNull();
}

[Fact]
public void BuildForwardedForHeaders_WithEmptyString_ReturnsNull()
{
var result = AuthenticationApiClient.BuildForwardedForHeaders(string.Empty);
result.Should().BeNull();
}

[Fact]
public void BuildForwardedForHeaders_WithValidIPv4_ReturnsHeader()
{
var result = AuthenticationApiClient.BuildForwardedForHeaders("192.168.1.1");
result.Should().NotBeNull();
result.Should().ContainKey("auth0-forwarded-for");
result["auth0-forwarded-for"].Should().Be("192.168.1.1");
}

[Fact]
public void BuildForwardedForHeaders_WithValidIPv6_ReturnsHeader()
{
var result = AuthenticationApiClient.BuildForwardedForHeaders("2001:db8::1");
result.Should().NotBeNull();
result.Should().ContainKey("auth0-forwarded-for");
result["auth0-forwarded-for"].Should().Be("2001:db8::1");
}

[Fact]
public void BuildForwardedForHeaders_ValidIPv4_HeaderValueMatchesInput()
{
var ip = "10.0.0.255";
var result = AuthenticationApiClient.BuildForwardedForHeaders(ip);
result["auth0-forwarded-for"].Should().Be(ip);
}

[Fact]
public void BuildForwardedForHeaders_WithHostname_ThrowsArgumentException()
{
Action act = () => AuthenticationApiClient.BuildForwardedForHeaders("example.com");
act.Should().Throw<ArgumentException>()
.And.ParamName.Should().Be("forwardedForIp");
}

[Fact]
public void BuildForwardedForHeaders_WithArbitraryString_ThrowsArgumentException()
{
Action act = () => AuthenticationApiClient.BuildForwardedForHeaders("not-an-ip");
act.Should().Throw<ArgumentException>()
.And.ParamName.Should().Be("forwardedForIp");
}
}
Loading
Loading