This commit is contained in:
Paul Schneider 2026-09-26 00:35:43 +01:00
commit 8c8ab70d38
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
82 changed files with 113 additions and 94 deletions

View file

@ -0,0 +1,309 @@
using System.Net;
using IdentityServer8.EntityFramework.Entities;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Models;
using Yavsc.Tests.Shared;
using Xunit;
namespace Yavsc.Org.Tests.Controllers;
/// <summary>
/// Integration tests for the per-collection edit pages of the OAuth2
/// client editor. Hits the real ASP.NET pipeline against
/// <see cref="WebServerFixture"/>: the WebApplication is built once per
/// collection and shared, so these tests must be defensive about row
/// IDs (they pick their own dedicated client to mutate).
///
/// Admin auth is satisfied by sending an <c>X-Test-Role: Administrator</c>
/// header. The <see cref="TestAuthPolicyProvider"/> short-circuits the
/// production policy to honour that header, sidestepping the login flow
/// (which is itself not exercised by these tests).
/// </summary>
[Collection("Yavsc Server")]
public class ClientControllerCollectionTests : IClassFixture<TestWebApplicationFactory>
{
private const string TargetClientId = "collection-tests-target";
private readonly TestWebApplicationFactory _factory;
public ClientControllerCollectionTests(TestWebApplicationFactory factory)
{
_factory = factory;
EnsureTargetClient();
}
private void EnsureTargetClient()
{
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (db.Clients.Any(c => c.ClientId == TargetClientId)) return;
db.Clients.Add(new Client
{
ClientId = TargetClientId,
ClientName = "Collection-edit tests target",
Enabled = true,
RequireClientSecret = false,
RequirePkce = true,
ProtocolType = "oidc",
AllowedGrantTypes = new List<ClientGrantType>
{
new() { GrantType = "authorization_code" },
},
AllowedScopes = new List<ClientScope>
{
new() { Scope = "openid" },
},
RedirectUris = new List<ClientRedirectUri>
{
new() { RedirectUri = "https://app.example.com/cb" },
},
});
db.SaveChanges();
}
private int TargetClientDbId()
{
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
return db.Clients.Single(c => c.ClientId == TargetClientId).Id;
}
private HttpClient CreateAdminClient()
{
// WebApplicationFactory.CreateClient() returns an HttpClient wired
// directly to the in-memory test server — no Kestrel socket, no
// self-signed cert, no IServerAddressesFeature lookup. Keep
// cookies enabled so the antiforgery cookie set on the GET that
// fetches the form is replayed on the POST that submits it.
var http = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
HandleCookies = true,
});
http.DefaultRequestHeaders.Add(TestAuthPolicyProvider.HeaderName, TestAuthPolicyProvider.AdminRole);
return http;
}
[Fact]
public async Task Edit_GET_returns_200_for_admin()
{
var http = CreateAdminClient();
var id = TargetClientDbId();
var resp = await http.GetAsync($"/Client/Edit/{id}", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
var body = await resp.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Contains(TargetClientId, body);
}
[Fact]
public async Task EditRedirectUris_GET_returns_200_and_lists_seeded_uri()
{
var http = CreateAdminClient();
var id = TargetClientDbId();
var resp = await http.GetAsync($"/Client/EditRedirectUris/{id}", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
var body = await resp.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Contains("https://app.example.com/cb", body);
}
// Repro: GET /Client/EditRedirectUris/{id} après qu'une seconde
// RedirectUri a été ajoutée via POST. LoadClientAsync(id) réhydrate
// le Client avec 9 Includes (RedirectUris, AllowedScopes, ClientSecrets,
// etc.) via l'InMemory provider. Sur l'Id=2 seedé, la matérialisation
// des nav properties sur les entités IdentityServer8 lève
// IndexOutOfRangeException — l'action renvoie un 500 et la page
// d'erreur masque le diagnostic.
//
// Ce test reproduit le chemin qui plante : GET initial (lit l'AF
// token) → POST AddRedirectUri → GET final qui exerce LoadClientAsync
// avec une collection RedirectUris non triviale (2 entrées).
// Il doit ÉCHOUER tant que le bug n'est pas traité.
[Fact]
public async Task EditRedirectUris_GET_after_add_lists_both_uris()
{
var http = CreateAdminClient();
var id = TargetClientDbId();
const string newUri = "https://app.example.com/cb-repro";
// Premier GET pour récupérer l'antiforgery token du form Add.
var pageResp = await http.GetAsync(
$"/Client/EditRedirectUris/{id}", TestContext.Current.CancellationToken);
pageResp.EnsureSuccessStatusCode();
var token = ExtractAntiforgeryToken(
await pageResp.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
Assert.False(string.IsNullOrEmpty(token));
// Ajout d'une seconde RedirectUri — c'est l'état non-trivial
// qui déclenche la matérialisation problématique côté
// InMemory provider.
var form = new MultipartFormDataContent
{
{ new StringContent(newUri), "redirectUri" },
{ new StringContent(token!), "__RequestVerificationToken" },
};
var addResp = await http.PostAsync(
$"/Client/AddRedirectUri/{id}", form, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, addResp.StatusCode);
try
{
// GET final : exerce LoadClientAsync(id) sur le client
// avec 2 RedirectUris, 1 AllowedScope, 1 GrantType, etc.
// Si la matérialisation échoue (IndexOutOfRange), ce GET
// renvoie 500 et EnsureSuccessStatusCode fait échouer le test.
var finalResp = await http.GetAsync(
$"/Client/EditRedirectUris/{id}", TestContext.Current.CancellationToken);
finalResp.EnsureSuccessStatusCode();
var finalBody = await finalResp.Content.ReadAsStringAsync(
TestContext.Current.CancellationToken);
// La page doit lister les DEUX URIs.
Assert.Contains("https://app.example.com/cb", finalBody);
Assert.Contains(newUri, finalBody);
}
finally
{
// Cleanup idempotent : on retire l'URI ajoutée pour ne
// pas polluer les autres tests de la collection.
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var row = db.ClientRedirectUris
.FirstOrDefault(r => r.RedirectUri == newUri);
if (row is not null)
{
db.ClientRedirectUris.Remove(row);
db.SaveChanges();
}
}
}
[Fact]
public async Task AddRedirectUri_POST_appends_to_database()
{
var http = CreateAdminClient();
var id = TargetClientDbId();
const string newUri = "https://app.example.com/cb2";
// Read the GET page first to grab the antiforgery token attached
// to the Add form on EditRedirectUris.
var pageResp = await http.GetAsync($"/Client/EditRedirectUris/{id}", TestContext.Current.CancellationToken);
pageResp.EnsureSuccessStatusCode();
var pageHtml = await pageResp.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
var token = ExtractAntiforgeryToken(pageHtml);
Assert.False(string.IsNullOrEmpty(token));
var form = new MultipartFormDataContent
{
{ new StringContent(newUri), "redirectUri" },
{ new StringContent(token!), "__RequestVerificationToken" },
};
var postResp = await http.PostAsync($"/Client/AddRedirectUri/{id}", form, TestContext.Current.CancellationToken);
var postBody = await postResp.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(postResp.StatusCode == HttpStatusCode.OK,
$"Expected 200, got {(int)postResp.StatusCode}. Body[0..500]: {postBody.Substring(0, Math.Min(500, postBody.Length))}");
Assert.Equal(HttpStatusCode.OK, postResp.StatusCode);
// Verify in DB.
using var scope = _factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var client = db.Clients
.Include(c => c.RedirectUris)
.Single(c => c.ClientId == TargetClientId);
Assert.Contains(client.RedirectUris, r => r.RedirectUri == newUri);
// Cleanup so the test is idempotent across runs.
var toRemove = client.RedirectUris.First(r => r.RedirectUri == newUri);
db.ClientRedirectUris.Remove(toRemove);
db.SaveChanges();
}
[Fact]
public async Task RemoveRedirectUri_POST_with_foreign_rowId_returns_NotFound()
{
// SECURITY: a Remove call for a row that belongs to a different
// client must be rejected. The test creates a second client,
// gets a real rowId from it, then calls Remove on the target
// client with that foreign rowId. Expected: 404, target
// client unchanged.
using (var scope = _factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (!db.Clients.Any(c => c.ClientId == "collection-tests-other"))
{
db.Clients.Add(new Client
{
ClientId = "collection-tests-other",
ClientName = "Other target",
Enabled = true,
ProtocolType = "oidc",
RequireClientSecret = false,
RequirePkce = true,
});
db.SaveChanges();
}
}
int otherRowId;
using (var scope = _factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var other = db.Clients.Include(c => c.RedirectUris)
.Single(c => c.ClientId == "collection-tests-other");
if (!other.RedirectUris.Any())
{
other.RedirectUris.Add(new ClientRedirectUri { RedirectUri = "https://other.example/cb" });
db.SaveChanges();
}
otherRowId = other.RedirectUris.First().Id;
}
var http = CreateAdminClient();
var targetId = TargetClientDbId();
var pageResp = await http.GetAsync($"/Client/EditRedirectUris/{targetId}", TestContext.Current.CancellationToken);
var token = ExtractAntiforgeryToken(await pageResp.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
var form = new MultipartFormDataContent
{
{ new StringContent(targetId.ToString()), "id" },
{ new StringContent(otherRowId.ToString()), "rowId" },
{ new StringContent(token!), "__RequestVerificationToken" },
};
var resp = await http.PostAsync($"/Client/RemoveRedirectUri", form,
TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, resp.StatusCode);
}
// ---------- Bisection de l'Include qui plante ----------
//
// LoadClientAsync charge le Client avec 9 Includes :
// RedirectUris, PostLogoutRedirectUris, AllowedScopes,
// AllowedGrantTypes, AllowedCorsOrigins,
// IdentityProviderRestrictions, Claims, Properties, ClientSecrets.
//
// Le test EditRedirectUris_GET_after_add_lists_both_uris échoue
// avec IndexOutOfRangeException au shaper de l'InMemory provider,
// sans préciser lequel des Includes pose problème. La stack
// indique IncludeCollection (donc un Include de collection, pas
// de référence).
//
// 2026-07-11 fix/issue-3-splitquery: tests retirés car leur hypothèse
// ("bug de provider InMemory sur ces 3 entités") n'est pas la cause
// racine — c'est une redondance de mapping HasOne dans
// ApplicationDbContext.OnModelCreating. Le test gardien
// EditRedirectUris_GET_after_add_lists_both_uris reste en place
// comme sentinelle de régression sur le fix.
private static string? ExtractAntiforgeryToken(string html)
{
const string marker = "name=\"__RequestVerificationToken\"";
var idx = html.IndexOf(marker, StringComparison.Ordinal);
if (idx < 0) return null;
var valueStart = html.IndexOf("value=\"", idx, StringComparison.Ordinal);
if (valueStart < 0) return null;
valueStart += "value=\"".Length;
var valueEnd = html.IndexOf('"', valueStart);
return valueEnd < 0 ? null : html[valueStart..valueEnd];
}
}

View file

@ -0,0 +1,37 @@
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Yavsc.Tests.Shared;
using Xunit;
namespace Yavsc.Org.Tests.Controllers;
public class CommandFormsControllerTests : IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;
public CommandFormsControllerTests(TestWebApplicationFactory factory)
{
_factory = factory;
}
private HttpClient CreateAdminClient()
{
var http = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
HandleCookies = true,
});
http.DefaultRequestHeaders.Add(TestAuthPolicyProvider.HeaderName, TestAuthPolicyProvider.AdminRole);
return http;
}
[Fact]
public async Task Create_GET_returns_200_for_admin()
{
var http = CreateAdminClient();
var response = await http.GetAsync("/CommandForms/Create", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.Contains("Create", body);
}
}

View file

@ -0,0 +1,93 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Yavsc.Models;
using Yavsc.Models.Blog;
using Yavsc.Tests.Shared;
using Xunit;
namespace Yavsc.Org.Tests.Controllers;
public class CommentsApiIntegrationTests : IClassFixture<TestWebApplicationFactory>
{
private readonly TestWebApplicationFactory _factory;
public CommentsApiIntegrationTests(TestWebApplicationFactory factory)
{
_factory = factory;
}
[Fact]
public async Task Post_blogcomments_json_returns_201_and_persists_comment()
{
long postId;
using (var scope = _factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
if (!db.Users.Any(u => u.Id == TestUserMiddleware.UserId))
{
db.Users.Add(new ApplicationUser
{
Id = TestUserMiddleware.UserId,
UserName = "test-user",
NormalizedUserName = "TEST-USER",
Email = "test-user@example.com",
NormalizedEmail = "TEST-USER@EXAMPLE.COM",
EmailConfirmed = true,
SecurityStamp = Guid.NewGuid().ToString("N"),
ConcurrencyStamp = Guid.NewGuid().ToString("N")
});
}
var post = new BlogPost
{
Title = "Post for comment API test",
AuthorId = TestUserMiddleware.UserId,
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow
};
db.BlogSpot.Add(post);
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
postId = post.Id;
}
var http = _factory.CreateClient(new WebApplicationFactoryClientOptions
{
HandleCookies = true,
AllowAutoRedirect = false
});
http.DefaultRequestHeaders.Add(TestAuthPolicyProvider.HeaderName, TestAuthPolicyProvider.AdminRole);
var response = await http.PostAsJsonAsync(
"/api/v1/blogcomments",
new
{
Article = "Comment API integration test",
ReceiverId = postId
},
TestContext.Current.CancellationToken);
var responseBody = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken);
Assert.True(
response.StatusCode != HttpStatusCode.InternalServerError,
$"Unexpected 500 on POST /api/v1/blogcomments. Body: {responseBody}");
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
Assert.Contains("\"id\"", responseBody, StringComparison.OrdinalIgnoreCase);
Assert.Contains("\"dateCreated\"", responseBody, StringComparison.OrdinalIgnoreCase);
using var verifyScope = _factory.Services.CreateScope();
var verifyDb = verifyScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var stored = await verifyDb.Comment
.OrderByDescending(c => c.Id)
.FirstOrDefaultAsync(c => c.ReceiverId == postId, TestContext.Current.CancellationToken);
Assert.NotNull(stored);
Assert.Equal("Comment API integration test", stored!.Article);
Assert.Equal(TestUserMiddleware.UserId, stored.AuthorId);
}
}

View file

@ -0,0 +1,64 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Yavsc.Controllers;
using Yavsc.Models;
using Yavsc.Models.Blog;
using Xunit;
namespace Yavsc.Org.Tests.Controllers;
public class CommentsControllerTests
{
[Fact]
public async Task Create_sets_author_and_persists_comment()
{
var dbName = $"comments-controller-{Guid.NewGuid():N}";
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(dbName)
.Options;
await using var db = new ApplicationDbContext(options);
var post = new BlogPost
{
Title = "Post de test",
AuthorId = "post-author",
DateCreated = DateTime.UtcNow,
DateModified = DateTime.UtcNow
};
db.BlogSpot.Add(post);
await db.SaveChangesAsync(TestContext.Current.CancellationToken);
var controller = new CommentsController(db)
{
ControllerContext = new ControllerContext
{
HttpContext = new DefaultHttpContext
{
User = new ClaimsPrincipal(new ClaimsIdentity(
[
new Claim(ClaimTypes.NameIdentifier, "comment-author")
], "TestAuth"))
}
}
};
var comment = new Comment
{
ReceiverId = post.Id,
Article = "Commentaire de test",
Visible = true
};
var result = await controller.Create(comment);
var redirect = Assert.IsType<RedirectToActionResult>(result);
Assert.Equal("Index", redirect.ActionName);
var stored = await db.Comment.SingleAsync(TestContext.Current.CancellationToken);
Assert.Equal("comment-author", stored.AuthorId);
Assert.Equal(post.Id, stored.ReceiverId);
Assert.Equal("Commentaire de test", stored.Article);
}
}

View file

@ -0,0 +1,68 @@
using IdentityServer8.EntityFramework.DbContexts;
using IdentityServer8.EntityFramework.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Yavsc.Org.Tests.Controllers;
/// <summary>
/// Regression sentinel: two <see cref="TestWebApplicationFactory"/>
/// instances must not see each other's clients.
///
/// EF Core's <c>UseInMemoryDatabase(name)</c> returns the same
/// backing store to every <c>DbContext</c> that asks for it under
/// the same name, in the same process. Before the per-fixture GUID
/// fix, both <see cref="TestWebApplicationFactory"/> and
/// <see cref="WebServerFixture"/> used the bare <c>"InMemory"</c>
/// connection string, so every fixture shared one store and tests
/// were silently order-dependent.
///
/// We assert against <see cref="ConfigurationDbContext"/> directly
/// rather than via <c>IClientStore</c>: the validating wrapper around
/// <c>IClientStore</c> raises events through <c>IEventService</c>,
/// which is not registered in the test host and crashes with a
/// <c>NullReferenceException</c> before it can return a result. Going
/// straight to the DbContext is the same code path the production
/// code uses, so it is the right surface to assert against.
/// </summary>
public class TestWebApplicationFactoryIsolationTests
{
[Fact]
public async Task Second_factory_does_not_see_clients_seeded_into_first()
{
var marker = $"marker-A-{Guid.NewGuid():N}";
// First factory: seed a distinctive client.
using (var first = new TestWebApplicationFactory())
{
await using var scope = first.Services.CreateAsyncScope();
var configDb = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
var firstCs = scope.ServiceProvider.GetRequiredService<IConfiguration>()
.GetConnectionString("YavscConnection");
configDb.Clients.Add(new Client { ClientId = marker, ClientName = "marker-A" });
await configDb.SaveChangesAsync(TestContext.Current.CancellationToken);
// Sanity: the first factory can see its own seed.
var seenByFirst = await configDb.Clients
.AsNoTracking()
.AnyAsync(c => c.ClientId == marker, TestContext.Current.CancellationToken);
Assert.True(seenByFirst);
}
// Second factory: must start from a clean slate. If the
// in-memory store leaked from the first factory, this
// assertion fails.
using var second = new TestWebApplicationFactory();
await using var secondScope = second.Services.CreateAsyncScope();
var secondCs = secondScope.ServiceProvider.GetRequiredService<IConfiguration>()
.GetConnectionString("YavscConnection");
Assert.StartsWith("InMemory-", secondCs);
var secondDb = secondScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
var seenBySecond = await secondDb.Clients
.AsNoTracking()
.AnyAsync(c => c.ClientId == marker, TestContext.Current.CancellationToken);
Assert.False(seenBySecond);
}
}