Public Access
Authorization Code with PKCE on a loopback redirect, per RFC 6749, RFC 7636 and RFC 8252. Zero package references: the flow is fully specified, and the one thing a library would own for us -- nonce generation and validation -- is exactly what the key binding needs to control. Duende's OidcClient generates and validates its own nonce as an internal detail, and the binding requires the nonce be a specific value: the hash of the key statement being enrolled. Fighting that is worse than owning the flow. AuthorizeKeyBindingAsync is the client half of the primary trust anchor. It runs a second authorization with nonce set to the statement hash and prompt=login, so the ID token that returns is the provider's signature over exactly those public keys, attesting to a user present now rather than to a session opened at some unknown earlier time. It requests only openid -- a second refresh token would be one more long-lived credential for no benefit -- and rejects a token whose nonce is not the one it asked for, because enrolling that would store evidence verifying against keys we are not publishing. The nonce is read without validating the ID token's signature. Sanctioned by OIDC Core 3.1.3.7: for a token received by direct communication with the token endpoint, TLS server authentication may stand in for signature checking. That reasoning does not extend to another user's binding, which arrives via the DodoSSH server and must be verified against JWKS fetched directly -- the directory work in M3. Raw TcpListener rather than HttpListener for the redirect: an ephemeral port can be bound and read atomically instead of picking one and hoping it is still free, there is no HTTP.SYS URL-ACL question on Windows, and the whole surface is one request line. It answers 404 on other paths and keeps waiting, because a browser asks for /favicon.ico first and treating that as the callback would abort every sign-in. 127.0.0.1 rather than localhost: RFC 8252 permits either, but the name resolves through the hosts file. 20 tests, driving the real listener over TCP with a fake browser that actually fetches the redirect -- injecting a fabricated callback would skip the parsing, path filtering and response writing that can break. Mostly negative, because the loopback port is reachable by every local process: a response with the wrong state is rejected *and* never reaches the token endpoint, metadata declaring an issuer other than its own authority is rejected (RFC 8414 3.3, without which a mix-up attack works), a provider offering only 'plain' is fatal rather than a silent downgrade, and the verifier sent is checked against the challenge advertised so PKCE is not theatre that only fails in production. Two bugs caught by writing the tests: the authorize URL builder dropped client_id entirely after a refactor, and CancellationTokenSource.CancelAfter has no TimeProvider overload -- so the browser timeout is now constructed with the clock and a test can advance it instead of waiting five minutes.
176 lines
5.9 KiB
C#
176 lines
5.9 KiB
C#
using System.Buffers.Text;
|
|
using System.Text;
|
|
using System.Text.Json.Nodes;
|
|
using WireMock.RequestBuilders;
|
|
using WireMock.ResponseBuilders;
|
|
using WireMock.Server;
|
|
|
|
namespace DodoSSH.Client.Auth.Tests;
|
|
|
|
/// <summary>An identity provider stub: discovery and a token endpoint.</summary>
|
|
internal sealed class StubProvider : IDisposable
|
|
{
|
|
private readonly WireMockServer server;
|
|
|
|
internal StubProvider(
|
|
bool advertiseS256 = true,
|
|
string? issuerOverride = null)
|
|
{
|
|
server = WireMockServer.Start();
|
|
Authority = new Uri(server.Url!.TrimEnd('/'), UriKind.Absolute);
|
|
|
|
StubDiscovery(advertiseS256, issuerOverride);
|
|
}
|
|
|
|
/// <summary>The provider's base URL, which is also its issuer.</summary>
|
|
internal Uri Authority { get; }
|
|
|
|
/// <summary>Requests the stub received, so tests can assert on what was sent.</summary>
|
|
internal IReadOnlyList<WireMock.Logging.ILogEntry> Requests => server.LogEntries.ToList();
|
|
|
|
/// <summary>Stubs a successful token response.</summary>
|
|
internal void StubTokenResponse(
|
|
string accessToken = "access-token",
|
|
string? refreshToken = "refresh-token",
|
|
string? idTokenNonce = null,
|
|
bool includeIdToken = false,
|
|
int? expiresInSeconds = 3600)
|
|
{
|
|
var body = new JsonObject
|
|
{
|
|
["access_token"] = accessToken,
|
|
["token_type"] = "Bearer",
|
|
};
|
|
|
|
if (expiresInSeconds is { } seconds)
|
|
{
|
|
body["expires_in"] = seconds;
|
|
}
|
|
|
|
if (refreshToken is not null)
|
|
{
|
|
body["refresh_token"] = refreshToken;
|
|
}
|
|
|
|
if (includeIdToken)
|
|
{
|
|
body["id_token"] = BuildIdToken(idTokenNonce);
|
|
}
|
|
|
|
server
|
|
.Given(Request.Create().WithPath("/connect/token").UsingPost())
|
|
.RespondWith(Response.Create()
|
|
.WithStatusCode(200)
|
|
.WithHeader("Content-Type", "application/json")
|
|
.WithBody(body.ToJsonString()));
|
|
}
|
|
|
|
/// <summary>Stubs an error from the token endpoint.</summary>
|
|
internal void StubTokenError(int statusCode, string error, string description)
|
|
{
|
|
var body = new JsonObject
|
|
{
|
|
["error"] = error,
|
|
["error_description"] = description,
|
|
};
|
|
|
|
server
|
|
.Given(Request.Create().WithPath("/connect/token").UsingPost())
|
|
.RespondWith(Response.Create()
|
|
.WithStatusCode(statusCode)
|
|
.WithHeader("Content-Type", "application/json")
|
|
.WithBody(body.ToJsonString()));
|
|
}
|
|
|
|
/// <summary>The form body the token endpoint last received, parsed.</summary>
|
|
internal IReadOnlyDictionary<string, string> LastTokenRequestForm()
|
|
{
|
|
var entries = server.LogEntries
|
|
.Where(e => e.RequestMessage?.Path?
|
|
.EndsWith("/connect/token", StringComparison.Ordinal) == true)
|
|
.ToList();
|
|
|
|
if (entries.Count == 0)
|
|
{
|
|
throw new InvalidOperationException("The token endpoint was never called.");
|
|
}
|
|
|
|
var body = entries[^1].RequestMessage?.Body ?? string.Empty;
|
|
var form = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
|
|
foreach (var pair in body.Split('&', StringSplitOptions.RemoveEmptyEntries))
|
|
{
|
|
var separator = pair.IndexOf('=', StringComparison.Ordinal);
|
|
if (separator < 0)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
form[Uri.UnescapeDataString(pair[..separator])] =
|
|
Uri.UnescapeDataString(pair[(separator + 1)..].Replace('+', ' '));
|
|
}
|
|
|
|
return form;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public void Dispose()
|
|
{
|
|
server.Stop();
|
|
server.Dispose();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Builds a JWT-shaped ID token with an unverifiable signature.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Unsigned on purpose. The client reads the nonce without validating the signature, which OIDC
|
|
/// Core §3.1.3.7 permits for a token received directly from the token endpoint over TLS — so a
|
|
/// real signature here would test nothing the client does.
|
|
/// </remarks>
|
|
private static string BuildIdToken(string? nonce)
|
|
{
|
|
var header = new JsonObject { ["alg"] = "RS256", ["typ"] = "JWT" };
|
|
var payload = new JsonObject { ["sub"] = "alice", ["iss"] = "https://idp.example" };
|
|
|
|
if (nonce is not null)
|
|
{
|
|
payload["nonce"] = nonce;
|
|
}
|
|
|
|
return string.Join('.',
|
|
Base64Url.EncodeToString(Encoding.UTF8.GetBytes(header.ToJsonString())),
|
|
Base64Url.EncodeToString(Encoding.UTF8.GetBytes(payload.ToJsonString())),
|
|
Base64Url.EncodeToString("not-a-real-signature"u8));
|
|
}
|
|
|
|
private void StubDiscovery(bool advertiseS256, string? issuerOverride)
|
|
{
|
|
var document = new JsonObject
|
|
{
|
|
["issuer"] = issuerOverride ?? Authority.AbsoluteUri.TrimEnd('/'),
|
|
["authorization_endpoint"] = $"{Authority.AbsoluteUri.TrimEnd('/')}/connect/authorize",
|
|
["token_endpoint"] = $"{Authority.AbsoluteUri.TrimEnd('/')}/connect/token",
|
|
["jwks_uri"] = $"{Authority.AbsoluteUri.TrimEnd('/')}/.well-known/jwks.json",
|
|
["response_types_supported"] = new JsonArray("code"),
|
|
["id_token_signing_alg_values_supported"] = new JsonArray("RS256"),
|
|
};
|
|
|
|
if (advertiseS256)
|
|
{
|
|
document["code_challenge_methods_supported"] = new JsonArray("S256");
|
|
}
|
|
else
|
|
{
|
|
document["code_challenge_methods_supported"] = new JsonArray("plain");
|
|
}
|
|
|
|
server
|
|
.Given(Request.Create().WithPath("/.well-known/openid-configuration").UsingGet())
|
|
.RespondWith(Response.Create()
|
|
.WithStatusCode(200)
|
|
.WithHeader("Content-Type", "application/json")
|
|
.WithBody(document.ToJsonString()));
|
|
}
|
|
}
|