feat(admin): runtime feature flags (catalog-in-code, admin toggle, FE+backend)

Catalog declared in code (Domain/Features/FeatureFlags.cs, build-validated), on/off state
persisted in SQLite (FeatureFlagStore + migration). GET /flags (drives FE gating) + admin
PUT /admin/flags/{key} (new flags:manage capability + FlagsAdmin gate). Enforced end-to-end:
the `inschrijving-open` flag hides the Inschrijven nav item + dashboard action (FE) AND makes
POST /applications for a registratie 403 when off (backend). FE FeatureFlagStore mirrors
AccessStore (enabled() deny-by-default); admin toggle page at /beheer/functies in ADMIN_LINKS.
+4 backend tests, /me cap-list updated, client regenerated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
eho
2026-07-23 22:29:48 +02:00
co-authored by Claude Opus 4.8
parent ed264be714
commit 67802c68b4
28 changed files with 1154 additions and 52 deletions
@@ -83,6 +83,10 @@ public sealed record ChangeRequestRequest(string Telefoon);
public sealed record AuthzAuditDto(
string At, string Action, string Resource, string Decision, string Role, string CorrelationId);
// Feature flags (WP-47): the resolved flag set + the admin toggle body.
public sealed record FeatureFlagDto(string Key, string Description, bool Enabled);
public sealed record SetFeatureFlagRequest(bool Enabled);
public sealed record ReferentieResponse(string Referentie);
// --- Applications (aanvragen): the system of record for the dashboard. ---
@@ -20,6 +20,7 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbCon
public DbSet<StoredDocument> Documents => Set<StoredDocument>();
public DbSet<AuditEntry> AuditEntries => Set<AuditEntry>();
public DbSet<AuthzAuditEntry> AuthzAudit => Set<AuthzAuditEntry>();
public DbSet<FeatureFlagEntity> FeatureFlags => Set<FeatureFlagEntity>();
public DbSet<Aanvraag> Applications => Set<Aanvraag>();
public DbSet<BriefEntity> Briefs => Set<BriefEntity>();
public DbSet<OrgTemplateEntity> OrgTemplates => Set<OrgTemplateEntity>();
@@ -40,6 +41,8 @@ public sealed class AppDbContext(DbContextOptions<AppDbContext> options) : DbCon
e.Property(a => a.Id).ValueGeneratedOnAdd();
});
modelBuilder.Entity<FeatureFlagEntity>().HasKey(f => f.Key);
modelBuilder.Entity<Aanvraag>(e =>
{
e.HasKey(a => a.Id);
@@ -0,0 +1,67 @@
using BigRegister.Domain.Features;
namespace BigRegister.Api.Data;
/// One persisted runtime override for a feature flag (only stored once toggled; otherwise the
/// catalog default applies). Key = the flag key from the code catalog (FeatureFlags.Catalog).
public sealed class FeatureFlagEntity
{
public required string Key { get; init; }
public bool Enabled { get; set; }
}
/// A flag resolved for a consumer: catalog default overlaid with any stored override.
public sealed record ResolvedFlag(string Key, string Description, bool Enabled);
/// <summary>
/// Runtime feature-flag state (WP-47). SQLite-backed like <see cref="OrgTemplateStore"/>, same
/// single-gate idiom. The CATALOG (which flags exist + their defaults) is code
/// (<see cref="FeatureFlags"/>); this store only holds the admin's on/off overrides. An unknown
/// key is never writable/enabled — the code catalog is the authority.
/// </summary>
public static class FeatureFlagStore
{
private static readonly object _gate = new();
/// Catalog defaults overlaid with stored overrides — the whole flag set for the admin UI + FE.
public static IReadOnlyList<ResolvedFlag> All()
{
Dictionary<string, bool> overrides;
lock (_gate)
{
using var db = Db.Create();
overrides = db.FeatureFlags.ToDictionary(f => f.Key, f => f.Enabled);
}
return FeatureFlags.Catalog
.Select(d => new ResolvedFlag(d.Key, d.Description,
overrides.TryGetValue(d.Key, out var e) ? e : d.DefaultEnabled))
.ToList();
}
/// Server-side enforcement helper. Unknown key → false (fail closed).
public static bool IsEnabled(string key)
{
var def = FeatureFlags.Catalog.FirstOrDefault(d => d.Key == key);
if (def is null) return false;
lock (_gate)
{
using var db = Db.Create();
return db.FeatureFlags.Find(key)?.Enabled ?? def.DefaultEnabled;
}
}
/// Set an override for a KNOWN flag; returns false for an unknown key (caller → 404).
public static bool Set(string key, bool enabled)
{
if (!FeatureFlags.Catalog.Any(d => d.Key == key)) return false;
lock (_gate)
{
using var db = Db.Create();
var row = db.FeatureFlags.Find(key);
if (row is null) db.FeatureFlags.Add(new FeatureFlagEntity { Key = key, Enabled = enabled });
else row.Enabled = enabled;
db.SaveChanges();
}
return true;
}
}
@@ -0,0 +1,273 @@
// <auto-generated />
using System;
using BigRegister.Api.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BigRegister.Api.Data.Migrations
{
[DbContext(typeof(AppDbContext))]
[Migration("20260723202131_FeatureFlags")]
partial class FeatureFlags
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.9");
modelBuilder.Entity("BigRegister.Api.Data.Aanvraag", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<bool>("AutoApprovable")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("DocumentIds")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Draft")
.HasColumnType("TEXT");
b.Property<string>("Owner")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Reden")
.HasColumnType("TEXT");
b.Property<string>("Referentie")
.HasColumnType("TEXT");
b.Property<int>("StepCount")
.HasColumnType("INTEGER");
b.Property<int>("StepIndex")
.HasColumnType("INTEGER");
b.Property<bool>("Submitted")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("SubmittedAt")
.HasColumnType("TEXT");
b.Property<string>("Type")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Applications");
});
modelBuilder.Entity("BigRegister.Api.Data.AuditEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Action")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Actor")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("At")
.HasColumnType("TEXT");
b.Property<string>("CategoryId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("DocumentId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("AuditEntries");
});
modelBuilder.Entity("BigRegister.Api.Data.AuthzAuditEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Action")
.IsRequired()
.HasColumnType("TEXT");
b.Property<DateTimeOffset>("At")
.HasColumnType("TEXT");
b.Property<string>("CorrelationId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Decision")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Resource")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("AuthzAudit");
});
modelBuilder.Entity("BigRegister.Api.Data.BriefEntity", b =>
{
b.Property<string>("BriefId")
.HasColumnType("TEXT");
b.Property<string>("ArchivedHtml")
.HasColumnType("TEXT");
b.Property<string>("Beroep")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("DrafterId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Owner")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Placeholders")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Sections")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int?>("SentOrgTemplateVersion")
.HasColumnType("INTEGER");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("SubOrgId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("TemplateId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("BriefId");
b.HasIndex("Owner")
.IsUnique();
b.ToTable("Briefs");
});
modelBuilder.Entity("BigRegister.Api.Data.FeatureFlagEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.HasKey("Key");
b.ToTable("FeatureFlags");
});
modelBuilder.Entity("BigRegister.Api.Data.OrgTemplateEntity", b =>
{
b.Property<string>("SubOrgId")
.HasColumnType("TEXT");
b.Property<string>("Draft")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("History")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("PublishedVersion")
.HasColumnType("INTEGER");
b.HasKey("SubOrgId");
b.ToTable("OrgTemplates");
});
modelBuilder.Entity("BigRegister.Api.Data.StoredDocument", b =>
{
b.Property<string>("DocumentId")
.HasColumnType("TEXT");
b.Property<string>("CategoryId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<byte[]>("Content")
.IsRequired()
.HasColumnType("BLOB");
b.Property<string>("ContentType")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("FileName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("Linked")
.HasColumnType("INTEGER");
b.Property<string>("LocalId")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Owner")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("SizeBytes")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset>("UploadedAt")
.HasColumnType("TEXT");
b.Property<string>("WizardId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("DocumentId");
b.ToTable("Documents");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,33 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BigRegister.Api.Data.Migrations
{
/// <inheritdoc />
public partial class FeatureFlags : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "FeatureFlags",
columns: table => new
{
Key = table.Column<string>(type: "TEXT", nullable: false),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_FeatureFlags", x => x.Key);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "FeatureFlags");
}
}
}
@@ -184,6 +184,19 @@ namespace BigRegister.Api.Data.Migrations
b.ToTable("Briefs");
});
modelBuilder.Entity("BigRegister.Api.Data.FeatureFlagEntity", b =>
{
b.Property<string>("Key")
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.HasKey("Key");
b.ToTable("FeatureFlags");
});
modelBuilder.Entity("BigRegister.Api.Data.OrgTemplateEntity", b =>
{
b.Property<string>("SubOrgId")
@@ -43,7 +43,7 @@ public static class Authz
public static IReadOnlyList<string> RoleCapabilities(Principal principal) => principal.Role switch
{
PrincipalRole.Approver => new[] { "brief:approve", "brief:reject", "brief:send" },
PrincipalRole.Admin => new[] { "orgtemplate:edit", "stamdata:edit", "cases:manage" },
PrincipalRole.Admin => new[] { "orgtemplate:edit", "stamdata:edit", "cases:manage", "flags:manage" },
_ => Array.Empty<string>(),
};
@@ -74,6 +74,9 @@ public static class Authz
/// list + admin delete.
public static bool CanManageCases(Principal principal) => principal.Role == PrincipalRole.Admin;
/// Feature-flag management (WP-47): admin-only, resource-independent — role IS the decision.
public static bool CanManageFeatureFlags(Principal principal) => principal.Role == PrincipalRole.Admin;
/// Field-level PII (PRD-0002 §5c, phase P2): the case screen's BIG-nummer ships
/// masked by default; only the behandelaar (Drafter) composing the case — the actor
/// whose behandel-scherm shows the field — may reveal it. Role-based in the POC; a
@@ -0,0 +1,22 @@
namespace BigRegister.Domain.Features;
/// A known feature flag — DECLARED in code (this catalog, build-validated), TOGGLED at runtime
/// (on/off state persisted in SQLite by FeatureFlagStore). Same split as stamdata (catalog is
/// config-as-code) × org-templates (runtime state in the DB): what flags exist is code; whether
/// they're on is operational config an admin flips.
public sealed record FeatureFlagDef(string Key, string Description, bool DefaultEnabled);
public static class FeatureFlags
{
/// Whether self-service registration (inschrijving) is open. When off, the FE hides the
/// "Inschrijven" action and POST /applications for a `registratie` is refused (server-enforced).
public const string InschrijvingOpen = "inschrijving-open";
public static readonly IReadOnlyList<FeatureFlagDef> Catalog = new[]
{
new FeatureFlagDef(
InschrijvingOpen,
"Zelf-inschrijving in het BIG-register is opengesteld.",
DefaultEnabled: true),
};
}
+26
View File
@@ -5,6 +5,7 @@ using BigRegister.Api.Data;
using BigRegister.Domain.Authorization;
using BigRegister.Domain.Diplomas;
using BigRegister.Domain.Documents;
using BigRegister.Domain.Features;
using BigRegister.Domain.Intake;
using BigRegister.Domain.Letters;
using BigRegister.Domain.Registrations;
@@ -244,6 +245,9 @@ api.MapGet("/applications/{id}", (string id) =>
api.MapPost("/applications", (CreateApplicationRequest req) =>
{
// Feature flag (WP-47): self-service registration can be closed by an admin.
if (req.Type == "registratie" && !FeatureFlagStore.IsEnabled(FeatureFlags.InschrijvingOpen))
return Results.Problem(detail: "Inschrijving is momenteel gesloten.", statusCode: StatusCodes.Status403Forbidden);
var a = ApplicationStore.CreateConcept(req.Type, DocumentStore.DemoOwner);
if (a is null)
return Results.Problem(
@@ -344,6 +348,18 @@ api.MapGet("/admin/audit", (HttpContext ctx) => CasesAdmin(ctx, () =>
api.MapGet("/me", (HttpContext ctx) => new MeDto(Authz.RoleCapabilities(Authz.ResolvePrincipal(ctx))))
.Produces<MeDto>();
// Feature flags (WP-47). GET is readable by any principal (it drives FE gating); the toggle is
// admin-only. Catalog is code; state is the runtime override in SQLite.
api.MapGet("/flags", () =>
Results.Ok(FeatureFlagStore.All().Select(f => new FeatureFlagDto(f.Key, f.Description, f.Enabled)).ToList()))
.Produces<List<FeatureFlagDto>>();
api.MapPut("/admin/flags/{key}", (string key, SetFeatureFlagRequest req, HttpContext ctx) => FlagsAdmin(ctx, () =>
FeatureFlagStore.Set(key, req.Enabled) ? Results.NoContent() : Results.NotFound()))
.Produces(StatusCodes.Status204NoContent)
.Produces(StatusCodes.Status404NotFound)
.ProducesProblem(StatusCodes.Status403Forbidden);
// --- Brief (letter composition). One demo brief per owner; the server owns the
// status machine + authorization (Authz, PRD-0002 phase P1). Principal is a
// dev-only stand-in via X-Role (mirrors the X-Admin seam and the FE ?role=
@@ -556,6 +572,16 @@ IResult CasesAdmin(HttpContext ctx, Func<IResult> action)
statusCode: StatusCodes.Status403Forbidden);
}
// One gate for the feature-flag toggle — the enforce twin of `flags:manage` (WP-47).
IResult FlagsAdmin(HttpContext ctx, Func<IResult> action)
{
var principal = Authz.ResolvePrincipal(ctx);
if (Authz.CanManageFeatureFlags(principal)) return action();
AuditAuthz(ctx, "flags:manage", "feature-flags", false, principal);
return Results.Problem(detail: "Alleen een beheerder mag functievlaggen beheren.",
statusCode: StatusCodes.Status403Forbidden);
}
static StamdataColumnDto ToColumnDto(StamdataColumn c) => new(c.Name, c.Type, c.IsKey, c.Options);
// Authorization audit (PRD-0002 §8): access-relevant decisions recorded with NO PII —
+93
View File
@@ -852,6 +852,73 @@
}
}
},
"/api/v1/flags": {
"get": {
"tags": [
"BigRegister.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/FeatureFlagDto"
}
}
}
}
}
}
}
},
"/api/v1/admin/flags/{key}": {
"put": {
"tags": [
"BigRegister.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
],
"parameters": [
{
"name": "key",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SetFeatureFlagRequest"
}
}
},
"required": true
},
"responses": {
"204": {
"description": "No Content"
},
"404": {
"description": "Not Found"
},
"403": {
"description": "Forbidden",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
}
}
}
},
"/api/v1/brief": {
"get": {
"tags": [
@@ -1830,6 +1897,23 @@
},
"additionalProperties": false
},
"FeatureFlagDto": {
"type": "object",
"properties": {
"key": {
"type": "string",
"nullable": true
},
"description": {
"type": "string",
"nullable": true
},
"enabled": {
"type": "boolean"
}
},
"additionalProperties": false
},
"HerregistratieDecisionsDto": {
"type": "object",
"properties": {
@@ -2396,6 +2480,15 @@
},
"additionalProperties": false
},
"SetFeatureFlagRequest": {
"type": "object",
"properties": {
"enabled": {
"type": "boolean"
}
},
"additionalProperties": false
},
"StamdataColumnDto": {
"type": "object",
"properties": {
@@ -0,0 +1,72 @@
using System.Net;
using System.Net.Http.Json;
using BigRegister.Api.Contracts;
using BigRegister.Domain.Features;
using Microsoft.AspNetCore.Mvc.Testing;
namespace BigRegister.Tests;
/// WP-47: runtime feature flags — catalog in code, admin-toggled, server-enforced.
public class FeatureFlagTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
{
private readonly HttpClient _client = factory.CreateClient();
private HttpRequestMessage Admin(HttpMethod method, string path, object? body = null)
{
var req = new HttpRequestMessage(method, path) { Headers = { { "X-Role", "admin" } } };
if (body is not null) req.Content = JsonContent.Create(body);
return req;
}
[Fact]
public void The_catalog_has_unique_keys()
{
var keys = FeatureFlags.Catalog.Select(f => f.Key).ToList();
Assert.Equal(keys.Count, keys.Distinct().Count());
Assert.All(FeatureFlags.Catalog, f => Assert.False(string.IsNullOrWhiteSpace(f.Key)));
}
[Fact]
public async Task Get_flags_returns_the_catalog()
{
var flags = await _client.GetFromJsonAsync<List<FeatureFlagDto>>("/api/v1/flags");
Assert.Contains(flags!, f => f.Key == FeatureFlags.InschrijvingOpen);
}
[Fact]
public async Task Toggling_is_admin_only_and_an_unknown_key_is_404()
{
// Non-admin (no X-Role → drafter) may not toggle.
var denied = await _client.PutAsJsonAsync(
$"/api/v1/admin/flags/{FeatureFlags.InschrijvingOpen}", new { enabled = false });
Assert.Equal(HttpStatusCode.Forbidden, denied.StatusCode);
// Admin, unknown flag → 404.
var unknown = await _client.SendAsync(Admin(HttpMethod.Put, "/api/v1/admin/flags/does-not-exist", new { enabled = true }));
Assert.Equal(HttpStatusCode.NotFound, unknown.StatusCode);
}
[Fact]
public async Task Closing_inschrijving_blocks_a_registratie_then_reopening_allows_it()
{
try
{
// Off → POST /applications for a registratie is refused.
(await _client.SendAsync(Admin(HttpMethod.Put, $"/api/v1/admin/flags/{FeatureFlags.InschrijvingOpen}", new { enabled = false })))
.EnsureSuccessStatusCode();
var blocked = await _client.PostAsJsonAsync("/api/v1/applications", new { type = "registratie" });
Assert.Equal(HttpStatusCode.Forbidden, blocked.StatusCode);
// On → allowed again.
(await _client.SendAsync(Admin(HttpMethod.Put, $"/api/v1/admin/flags/{FeatureFlags.InschrijvingOpen}", new { enabled = true })))
.EnsureSuccessStatusCode();
var ok = await _client.PostAsJsonAsync("/api/v1/applications", new { type = "registratie" });
Assert.Equal(HttpStatusCode.Created, ok.StatusCode);
}
finally
{
// Leave the flag on (shared DB across this class).
await _client.SendAsync(Admin(HttpMethod.Put, $"/api/v1/admin/flags/{FeatureFlags.InschrijvingOpen}", new { enabled = true }));
}
}
}
@@ -201,7 +201,9 @@ public class OrgTemplateEndpointTests(TestWebApplicationFactory factory) : IClas
{
var res = await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/me", role: "admin"));
var me = await res.Content.ReadFromJsonAsync<MeDto>();
Assert.Equal(new[] { "orgtemplate:edit", "stamdata:edit", "cases:manage" }, me!.Capabilities);
Assert.Equal(
new[] { "orgtemplate:edit", "stamdata:edit", "cases:manage", "flags:manage" },
me!.Capabilities);
}
[Fact]