Files
DodoSSH/tests/DodoSSH.Api.Tests/StubIdentityProvider.cs
T
jaap-jan 98d29bff37
ci / build and test (ubuntu) (push) Has been cancelled
ci / build (windows) (push) Has been cancelled
Add HTTP integration harness and the sync authorization matrix (M1)
27 end-to-end tests over the real HTTP pipeline, against a PostgreSQL container and a
stubbed identity provider. This closes the gap the previous commit flagged.

Authentication is genuinely exercised, not bypassed. StubIdentityProvider serves real OIDC
discovery and JWKS via WireMock and signs tokens with a real RSA key, so the application's
own JwtBearer pipeline validates issuer, audience, signature, lifetime and claims. A
TestAuthHandler that short-circuits authentication would hide exactly the claim-mapping
mistakes that cause real authorization holes. Proven by rejecting: no token, a foreign
signing key, the wrong audience, the wrong issuer, and an expired token.

Authorization denials — the tests that matter most:
- Another user's vault is 404, not 403, for both pull and push. A distinct
  "exists but forbidden" answer is an existence oracle for other tenants' vault ids.
- A denied push writes nothing: no host row and no change-log entry. A denial that still
  mutated state would be worse than no check at all.
- A team vault is denied until M3 rather than falling through to a permissive default.

Behaviour covered: push/pull round trip, cursor advance (and that an empty pull does not
rewind the cursor, which would replay history), tampered cursor rejection, stale-version
conflict returning server state without overwriting, operation-id replay reported Duplicate
and applied once, a mixed batch applying the good and reporting the bad, relay field
enforcement both ways, delete clearing the relay address, tombstones carrying no payload,
and JIT provisioning happening exactly once.

Two configuration problems found by running it:
- appsettings.json carried empty-string placeholders for the connection string and OIDC
  authority. Under minimal hosting those beat anything a test registers via
  ConfigureAppConfiguration, because Program.cs adds its own sources after that callback
  runs. Removed them outright — an empty placeholder turns "not configured" into
  "configured as empty", which defeats failing fast. Tests now use DODOSSH_ environment
  variables, which Program.cs adds last.
- My first fix for minting an expired test token derived notBefore from the expiry, which
  put nbf fourteen minutes in the future for normal tokens and made every valid token 401.
  It needs the earlier of now-1min and exp-1min.

Verified: 0 warnings on a clean rebuild, 173 tests pass (up from 146), format clean.
2026-07-28 15:11:43 +02:00

172 lines
6.0 KiB
C#

using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.IdentityModel.Tokens;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
namespace DodoSSH.Api.Tests;
/// <summary>
/// A stand-in identity provider: OIDC discovery, JWKS, and token minting.
/// </summary>
/// <remarks>
/// Deliberately not a <c>TestAuthHandler</c> that short-circuits authentication. Tokens are signed
/// with a real RSA key and validated by the application's own JwtBearer pipeline, so issuer,
/// audience, signature, lifetime and claim handling are all genuinely exercised. Bypassing that
/// would hide precisely the claim-mapping mistakes that cause real authorization holes.
/// </remarks>
public sealed class StubIdentityProvider : IDisposable
{
private const string KeyId = "dodossh-test-key";
private readonly WireMockServer server;
private readonly RsaSecurityKey signingKey;
public StubIdentityProvider()
{
var rsa = RSA.Create(2048);
signingKey = new RsaSecurityKey(rsa) { KeyId = KeyId };
server = WireMockServer.Start();
Authority = server.Url!.TrimEnd('/');
StubDiscovery();
StubJwks();
}
/// <summary>Issuer URL, matching what the tokens claim.</summary>
public string Authority { get; }
/// <summary>Audience the API is configured to expect.</summary>
public static string Audience => "dodossh-api";
/// <summary>
/// Mints a signed access token.
/// </summary>
/// <param name="subject">The <c>sub</c> claim — the stable user identifier.</param>
/// <param name="email">Optional email claim.</param>
/// <param name="name">Optional display name claim.</param>
/// <param name="audience">Override the audience, to test rejection.</param>
/// <param name="issuer">Override the issuer, to test rejection.</param>
/// <param name="expires">Override expiry, to test rejection.</param>
public string MintToken(
string subject,
string? email = null,
string? name = null,
string? audience = null,
string? issuer = null,
DateTime? expires = null)
{
var now = TimeProvider.System.GetUtcNow().UtcDateTime;
var claims = new List<System.Security.Claims.Claim>
{
new("sub", subject),
};
if (email is not null)
{
claims.Add(new System.Security.Claims.Claim("email", email));
}
if (name is not null)
{
claims.Add(new System.Security.Claims.Claim("name", name));
}
var expiry = expires ?? now.AddMinutes(15);
// The earlier of now-1min and exp-1min. A fixed now-1min would sit after the expiry of a
// deliberately-expired test token (rejected at construction), while exp-1min alone would
// put nbf in the future for a normal token and make every valid token unauthorized.
var notBefore = expiry < now ? expiry.AddMinutes(-1) : now.AddMinutes(-1);
var token = new JwtSecurityToken(
issuer: issuer ?? Authority,
audience: audience ?? Audience,
claims: claims,
notBefore: notBefore,
expires: expiry,
signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
/// <summary>Mints a token signed by a different key, which must be rejected.</summary>
public string MintTokenWithForeignKey(string subject)
{
var foreign = new RsaSecurityKey(RSA.Create(2048)) { KeyId = KeyId };
var now = TimeProvider.System.GetUtcNow().UtcDateTime;
var token = new JwtSecurityToken(
issuer: Authority,
audience: Audience,
claims: [new System.Security.Claims.Claim("sub", subject)],
notBefore: now.AddMinutes(-1),
expires: now.AddMinutes(15),
signingCredentials: new SigningCredentials(foreign, SecurityAlgorithms.RsaSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
private void StubDiscovery()
{
var document = new Dictionary<string, object>(StringComparer.Ordinal)
{
["issuer"] = Authority,
["jwks_uri"] = $"{Authority}/.well-known/jwks.json",
["authorization_endpoint"] = $"{Authority}/connect/authorize",
["token_endpoint"] = $"{Authority}/connect/token",
["response_types_supported"] = new[] { "code" },
["subject_types_supported"] = new[] { "public" },
["id_token_signing_alg_values_supported"] = new[] { "RS256" },
["code_challenge_methods_supported"] = new[] { "S256" },
};
server
.Given(Request.Create().WithPath("/.well-known/openid-configuration").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(document)));
}
private void StubJwks()
{
var parameters = signingKey.Rsa.ExportParameters(includePrivateParameters: false);
var jwks = new
{
keys = new[]
{
new
{
kty = "RSA",
use = "sig",
kid = KeyId,
alg = "RS256",
n = Base64UrlEncoder.Encode(parameters.Modulus),
e = Base64UrlEncoder.Encode(parameters.Exponent),
},
},
};
server
.Given(Request.Create().WithPath("/.well-known/jwks.json").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(JsonSerializer.Serialize(jwks)));
}
/// <inheritdoc />
public void Dispose()
{
server.Stop();
server.Dispose();
signingKey.Rsa.Dispose();
}
}