Skip to content

Commit 0c7394c

Browse files
authored
Merge pull request #44 from HodeTech/development
feat(web): revoke native sessions on provider logout
2 parents 8435300 + dd9721f commit 0c7394c

91 files changed

Lines changed: 7414 additions & 228 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.claude/skills/local-dev-setup/SKILL.md‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,16 @@ contents out of tool output, command arguments and committed files.
101101

102102
### Step 3: Bring up the stack
103103

104+
Optional native back-channel logout follows the
105+
[realm setup recipe](../../../infra/keycloak/README.md#native-back-channel-logout).
106+
It is explicitly disabled by default. Before enabling it, the operator runs
107+
`make backchannel-tls`, supplies the existing native certificate's public root
108+
through `LEARNSTACK_BFF_BACKCHANNEL_NATIVE_CA`, and adds every agreed callback
109+
setting without replacing private values. `make dev` prepares the public-only
110+
Keycloak trust directory before Compose; seed/demo share the same read-only
111+
preflight. Follow that recipe for TLS/conflict failures, saturation and actual
112+
managed-family restart; never evict fences or reclaim by PID/lock age.
113+
104114
```bash
105115
make dev # the daily loop: 7 services, the ones the backend can call
106116
make dev-gated # all 14, including Valkey, Kafka, kafka-ui, Vault, APISIX and Dapr
@@ -223,13 +233,14 @@ scripts do not re-run, `make dev` reports healthy, and `make migrate` fails with
223233
What `make dev` expands to:
224234

225235
```bash
226-
# One file holds the whole stack. --env-file is not optional: Compose resolves
227-
# its default env file from the project directory (infra/compose/), not the cwd,
228-
# so without the flag the repo-root .env is ignored and every ${VAR:-default}
229-
# silently falls back.
230-
docker compose --env-file .env -f infra/compose/dev.yml up -d
236+
node scripts/compose.mjs selected up -d
231237
```
232238

239+
The wrapper selects the explicit environment/project, prepares the public-only
240+
Keycloak trust directory and injects its computed trust digest for `up`.
241+
Running Docker Compose directly bypasses that preparation and cannot replace
242+
`make dev` when native back-channel logout is enabled.
243+
233244
The canonical service inventory — image, local endpoint and default credentials
234245
for every service in the stack — lives in
235246
[`infra/compose/README.md`](../../../infra/compose/README.md), grouped by the

‎.claude/skills/run-tests-locally/SKILL.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,20 @@ Common failure shapes:
189189

190190
### Step 6: Run frontend tests
191191

192+
For native back-channel setup/provider changes, run the focused Docker-free
193+
controls before full qualification:
194+
195+
```bash
196+
node --test scripts/development-backchannel.test.mjs scripts/development-realm-backchannel.test.mjs
197+
```
198+
199+
These cover owned TLS setup, source/trust refusals and separate fresh/warm exact
200+
readback/zero-write reconciliation. They do not establish actual Docker provider
201+
delivery. Use the [normal setup recipe](../../../infra/keycloak/README.md#native-back-channel-logout)
202+
for real TLS reachability and managed-family recovery; follow
203+
[Security 11](../../../docs/standards/11-security.md#native-back-channel-logout)
204+
for admission, saturation and retained ownership policy.
205+
192206
```bash
193207
cd frontend
194208
pnpm test # all discovered test packages; nonempty, zero skips/todos

‎.claude/skills/seed-tenant/SKILL.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ to a BYPASSRLS/superuser role on every physical connection.
5656

5757
### 1. Check the environment and migrations
5858

59+
If native back-channel logout is explicitly enabled, complete the
60+
[operator setup](../../../infra/keycloak/README.md#native-back-channel-logout)
61+
first. Shared preflight qualifies private-source agreement, owned callback
62+
leaf/key/public CA and the separate public root for the existing native leaf
63+
before stack or realm mutations. Normal seed convergence verifies the actual
64+
running Keycloak trust route and exact web callback fields, then performs an
65+
independent readback and zero-write rerun. A foreign retained callback requires
66+
explicit operator correction. Default-disabled seed remains usable without
67+
callback certificates; never read private settings into a transcript.
68+
5969
Prepare the selected private source before `make dev` or `make seed`: it must
6070
include `KEYCLOAK_WEB_CLIENT_SECRET`, retain an existing confidential secret,
6171
and be a current-user-owned regular, nonsymlink, single-link file without

‎.env.example‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,18 @@ IdentityEvents__ClientSecret=learnstack-event-reader-dev-secret
9999
# All present root/web/process values must agree. Private source files are 0600.
100100
LEARNSTACK_BFF_ENABLED=false
101101
# LEARNSTACK_BFF_ISSUER=http://localhost:8080/realms/learnstack
102+
# Optional callback-only TLS listener in the SAME managed native runtime child.
103+
# Explicit true requires BFF=true and every callback setting below. Configure
104+
# existing native TLS first, then `make backchannel-tls`; no trust/hosts/env edits.
105+
# infra/keycloak/README.md#native-back-channel-logout owns setup and recovery.
106+
LEARNSTACK_BFF_BACKCHANNEL_ENABLED=false
107+
# LEARNSTACK_BFF_BACKCHANNEL_URL=https://host.docker.internal:3443/api/auth/backchannel/keycloak
108+
# LEARNSTACK_BFF_BACKCHANNEL_BIND_ADDRESS=0.0.0.0
109+
# LEARNSTACK_BFF_BACKCHANNEL_TLS_CERT=.data/tls/backchannel/leaf.pem
110+
# LEARNSTACK_BFF_BACKCHANNEL_TLS_KEY=.data/tls/backchannel/leaf-key.pem
111+
# LEARNSTACK_BFF_BACKCHANNEL_CA=.data/tls/backchannel/ca.pem
112+
# PUBLIC root verifying the EXISTING native localhost leaf (never rootCA-key.pem).
113+
# LEARNSTACK_BFF_BACKCHANNEL_NATIVE_CA=<absolute mkcert CAROOT>/rootCA.pem
102114
# Enabled native BFF/API scope admission also requires a SEPARATE 32-random-byte
103115
# canonical base64url secret (43 characters), matching in both server owners.
104116
# It must differ from LEARNSTACK_PUBLIC_HOP_SECRET; never expose it to a browser.

‎Makefile‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,10 @@ help: ## Show this help, listing every target and its one-line description.
5353
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_.-]+:.*?## / {printf " $(CYAN)%-18s$(RESET) %s\n", $$1, $$2}' $(MAKEFILE_LIST)
5454

5555
# ─── Dev infrastructure ───────────────────────────────────────────────────
56-
.PHONY: public-env public-api public-web
56+
.PHONY: public-env public-api public-web backchannel-tls
57+
backchannel-tls: ## Create missing owned local callback TLS material (no trust or env edits).
58+
node scripts/setup-development-backchannel.mjs
59+
5760
public-env: .env ## Generate the private local renderer secret (no hosts/trust edits).
5861
(cd frontend && pnpm --filter @learnstack/web build:ingress)
5962
node scripts/public-local.mjs prepare

‎backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.Admission.cs‎

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
using System.Diagnostics;
12
using System.Net;
23
using System.Text.Json.Nodes;
34
using System.Threading.RateLimiting;
@@ -13,6 +14,7 @@
1314
using Microsoft.Extensions.DependencyInjection;
1415
using Microsoft.Extensions.DependencyInjection.Extensions;
1516
using OpenTelemetry.Metrics;
17+
using OpenTelemetry.Trace;
1618
using Serilog.Core;
1719
using Xunit;
1820

@@ -21,6 +23,7 @@ namespace LearnStack.Tests.Integration;
2123
public sealed partial class AuthenticatedRateLimitTests
2224
{
2325
private static readonly TimeSpan AdmissionDeadline = TimeSpan.FromSeconds(15);
26+
private const string AdmissionTraceSource = "test.admission.host-lifetime";
2427
private const string UnknownAdmissionPath = "/api/v1/admission-unknown";
2528

2629
[Theory]
@@ -134,10 +137,10 @@ public async Task Signed_admission_exports_quota_capacity_and_sticky_fault_witho
134137
TenantAuthenticationIssuer.Actor.ToString("D"), SeedData.English.TenantId.Value.ToString("D") })
135138
collector.Metrics.Should().NotContain(canary);
136139
await AssertFaultedShutdown(scenario);
137-
DisposeFaultedClient(client, scenario);
140+
await DisposeAdmissionClientAsync(client);
138141
client = null;
139142
}
140-
finally { DisposeFaultedClient(client, scenario); }
143+
finally { await DisposeAdmissionClientAsync(client); }
141144
}
142145

143146
[Fact]
@@ -149,12 +152,17 @@ public async Task Blocked_acquisition_cleanup_holds_its_signed_request_until_fau
149152
AssertNoStoreHeaderControls();
150153
var observed = new SubjectQuotaObservation();
151154
var memberships = new AdmissionMembershipObservation();
155+
using var traceProbe = new ActivitySource(AdmissionTraceSource);
156+
traceProbe.HasListeners().Should().BeFalse(
157+
"no previous admission-test host may retain this explicitly observed source");
152158
HttpClient? client = AdmissionClient(issuer, scenario, observed, memberships);
153159
using var release = new ManualResetEventSlim();
154160
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
155161
Task<HttpResponseMessage>? pending = null;
156162
try
157163
{
164+
traceProbe.HasListeners().Should().BeTrue(
165+
"the actual API host must make the cleanup control observable");
158166
using (var first = await AdmissionSend(client, issuer, "blocked-retiring-subject"))
159167
first.StatusCode.Should().Be(HttpStatusCode.OK);
160168
using (var existing = await AdmissionSend(client, issuer, "blocked-retained-subject"))
@@ -190,8 +198,10 @@ public async Task Blocked_acquisition_cleanup_holds_its_signed_request_until_fau
190198
(await fixture.AuditCountAsync(SeedData.English)).Should().Be(audits);
191199
scenario.Budgets.Should().HaveCount(3, "the failed owner cannot allocate after its disposal returns");
192200
await AssertFaultedShutdown(scenario);
193-
DisposeFaultedClient(client, scenario);
201+
await DisposeAdmissionClientAsync(client);
194202
client = null;
203+
traceProbe.HasListeners().Should().BeFalse(
204+
"host disposal must reach telemetry after the scenario joins its deliberately faulted owner");
195205
}
196206
finally
197207
{
@@ -200,7 +210,7 @@ public async Task Blocked_acquisition_cleanup_holds_its_signed_request_until_fau
200210
{
201211
if (pending is not null) (await pending.WaitAsync(AdmissionDeadline)).Dispose();
202212
}
203-
finally { DisposeFaultedClient(client, scenario); }
213+
finally { await DisposeAdmissionClientAsync(client); }
204214
}
205215
}
206216

@@ -210,7 +220,10 @@ private HttpClient AdmissionClient(TenantAuthenticationIssuer issuer, AdmissionS
210220
{
211221
AddQuotaBindings(services, issuer);
212222
services.RemoveAll<TenantSubjectRateLimiter>();
213-
services.AddSingleton(_ => scenario.Owner);
223+
// The scenario creates and joins this deliberately faulting owner.
224+
// Giving DI a second disposal claim would interrupt host cleanup.
225+
services.AddSingleton(scenario.Owner);
226+
services.AddOpenTelemetry().WithTracing(tracing => tracing.AddSource(AdmissionTraceSource));
214227
services.AddScoped<AuditingTenantAssertionRecorder>();
215228
services.AddScoped<ITenantAssertionRecorder>(provider => new ObservedQuotaRecorder(
216229
provider.GetRequiredService<AuditingTenantAssertionRecorder>(), observed));
@@ -281,15 +294,16 @@ private static async Task AssertFaultedShutdown(AdmissionScenario scenario)
281294
"shutdown drains the retained partitions without retrying the failed retirement");
282295
}
283296

284-
private static void DisposeFaultedClient(HttpClient? client, AdmissionScenario scenario)
297+
private static async Task DisposeAdmissionClientAsync(HttpClient? client)
285298
{
286299
if (client is null) return;
287-
try { client.Dispose(); }
288-
catch (Exception error) when (IsKnownFailureTree(error, scenario.Failure))
289-
{
290-
// Preserve a primary assertion failure while joining the known
291-
// faulted owner. Successful paths assert the failure above.
292-
}
300+
client.Dispose();
301+
// The entry point can still be finishing asynchronous host disposal.
302+
// Observe this host's real subscription retirement; time alone is no credit.
303+
using var source = new ActivitySource(AdmissionTraceSource);
304+
using var deadline = new CancellationTokenSource(AdmissionDeadline);
305+
while (source.HasListeners())
306+
await Task.Delay(TimeSpan.FromMilliseconds(10), deadline.Token);
293307
}
294308

295309
private static bool IsKnownFailureTree(Exception error, Exception expected) => ReferenceEquals(error, expected)

0 commit comments

Comments
 (0)