@cratis/pi 7.3.3 → 7.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: cratis-arc-authentication-authorization-and-identity
3
- description: Wire authentication, authorization and identity in a Cratis Arc application — IProvideIdentityDetails and the /.cratis/me endpoint, the [Authorize]/[Roles]/[AllowAnonymous] attributes Arc actually evaluates, IAuthenticationHandler, the Microsoft Identity Platform header contract, tenant resolution, and the React identity hooks. Use for Arc identity providers, endpoint protection, roles, or frontend identity integration. Do not use for isolated command validation, and do not use for Chronicle tenant namespaces alone.
3
+ description: Wire authentication, authorization and identity in a Cratis Arc application — IProvideIdentityDetails and the /.cratis/me endpoint, Arc's [Authorize]/[Roles]/[AllowAnonymous] attributes and named policies, fallback baselines, observable-query emission guards, IAuthenticationHandler, the Microsoft Identity Platform header contract and its ingress requirements, discovery and introspection exposure, tenant resolution, and the React identity hooks. Use for Arc identity providers, endpoint protection, roles, policies, or frontend identity integration. Do not use for isolated command validation, and do not use for Chronicle tenant namespaces alone.
4
4
  license: MIT
5
5
  ---
6
6
 
@@ -15,12 +15,12 @@ told about them. Each has its own extension point.
15
15
 
16
16
  | Package | Version | Purpose |
17
17
  | --- | --- | --- |
18
- | `Cratis.Arc.Core` | `22.16.0` | `Cratis.Arc.Identity`, `Cratis.Arc.Authorization`, `Cratis.Arc.Authentication`, `Cratis.Arc.Tenancy` |
19
- | `Cratis.Arc` | `22.16.0` | ASP.NET Core hosting, `AddMicrosoftIdentityPlatformIdentityAuthentication` |
20
- | `@cratis/arc` | `22.16.0` | `IdentityProvider`, `IIdentity` |
21
- | `@cratis/arc.react` | `22.16.0` | `IdentityProvider` component, `useIdentity`, `RequireRole` |
18
+ | `Cratis.Arc.Core` | `22.41.1` | `Cratis.Arc.Identity`, `Cratis.Arc.Authorization`, `Cratis.Arc.Authentication`, `Cratis.Arc.Tenancy` |
19
+ | `Cratis.Arc` | `22.41.1` | ASP.NET Core hosting, `AddMicrosoftIdentityPlatformIdentityAuthentication` |
20
+ | `@cratis/arc` | `22.41.1` | `IdentityProvider`, `IIdentity` |
21
+ | `@cratis/arc.react` | `22.41.1` | `IdentityProvider` component, `useIdentity`, `RequireRole` |
22
22
 
23
- > Re-verified at the versions above by **symbol and signature**: every type, attribute and member this skill names exists at that tag, and the public surface it describes is unchanged since the previous verification (Chronicle 16.45.x / Arc 22.10.4 — the Chronicle 16→18 client diff is converters, options and doc comments; no type was removed or renamed). Behavior claims were verified at the earlier tag unless a section says otherwise.
23
+ > Re-verified at `22.41.1` (the latest release when written) against that tag's source and Arc's documentation: the types, attributes and members this skill names exist, and the authorization, introspection, identity and emission-guard behavior it describes matches them. **Authorization behavior changed materially after `22.16.0`**, the version this skill used to pin: named policies, schemes, fallback baselines, guest policies and Microsoft-attribute enforcement all arrived later. [authorization](references/authorization.md) has a version table; check it if you run an older version.
24
24
 
25
25
  Reverify before claiming support for another version.
26
26
 
@@ -35,12 +35,23 @@ That is not a defect — it is the EasyAuth/reverse-proxy model, where the ingre
35
35
  is the trust boundary. But it means:
36
36
 
37
37
  - the application must be unreachable except through the ingress that sets those
38
- headers;
38
+ headers, and that ingress must **authenticate callers, strip any
39
+ caller-supplied identity headers, write its own trusted replacements, and block
40
+ direct access to the backend**;
39
41
  - nothing Arc gives you makes the forwarded values authentic;
40
42
  - Arc ships **no** OpenID Connect and **no** JWT bearer integration. If you need
41
43
  the application itself to validate a token, that is ordinary ASP.NET Core
42
44
  authentication you configure yourself.
43
45
 
46
+ Today the default is that a plain `builder.AddCratis()` host registers the
47
+ unsigned-header scheme as its **default** authentication scheme, so any caller who
48
+ can reach it can forge a principal for every authorized command and query (open
49
+ Arc#2946). Run it only behind that ingress; otherwise use `AddCratisArc()` and
50
+ configure a credential-validating scheme. Arc itself refuses the unsigned headers
51
+ in one place — protected introspection — until
52
+ `Cratis:Arc:Introspection:TrustForwardedIdentityHeaders` is set; see
53
+ [authentication](references/authentication.md).
54
+
44
55
  ## Identity details — what the frontend is told
45
56
 
46
57
  Implement `IProvideIdentityDetails` to shape what `/.cratis/me` returns:
@@ -75,13 +86,31 @@ public class <Name>IdentityDetailsProvider : IProvideIdentityDetails<<Details>>
75
86
  | Route | What it does |
76
87
  | --- | --- |
77
88
  | `GET /.cratis/me` | The current identity. 401 when not authenticated, 403 when the provider says not authorized, otherwise the result plus the identity cookie |
78
- | `GET /.cratis/identity-details/schema` | The JSON schema of the details type |
89
+ | `GET /.cratis/identity-details/schema` | The JSON schema of the details type (`{}` without a details provider) |
79
90
  | `GET /.cratis/users` | Development tooling — aggregates every `ICanProvideUsers` |
80
91
  | `GET /.cratis/tenants` | Development tooling — aggregates every `ICanProvideTenants` |
92
+ | `GET /.cratis/commands`, `GET /.cratis/queries` | Introspection catalogs of operation names, types and routes (`MapIntrospectionEndpoints()`) |
93
+
94
+ Normal `UseCratisArc()` activation maps all of these `AllowAnonymous` by default,
95
+ **including in Production**, unless an endpoint of the same name already exists; `/.cratis/me`
96
+ does its own 401/403. There is no public constant for the identity routes — they
97
+ are string literals in the endpoint mapper.
98
+
99
+ ⚠️ **A fallback policy does not protect an endpoint that is explicitly anonymous**,
100
+ and the word "development" is not an environment check. Today the default is that
101
+ these routes are public and expose your command, query, user and tenant surface;
102
+ the exposure is tracked in open Arc#2834. To change it:
81
103
 
82
- All four are mapped `AllowAnonymous`; `/.cratis/me` does its own 401/403. There
83
- is no public constant for these routes — they are string literals in the endpoint
84
- mapper.
104
+ - the two catalogs: configure `Cratis:Arc:Introspection` (`Enabled: false` unmaps
105
+ them; `RequireAuthentication`/`Roles` protect them; the
106
+ `TrustForwardedIdentityHeaders` opt-in is for the header handler only behind a
107
+ trusted ingress) — options table in [authentication](references/authentication.md);
108
+ - `/.cratis/identity-details/schema`, `/.cratis/users` and `/.cratis/tenants` are
109
+ **not** affected by those options. Return fixtures only from the user and tenant
110
+ providers, and restrict all three at the trusted ingress.
111
+
112
+ Test the discovery endpoints under Production settings, with your fallback policy
113
+ enabled.
85
114
 
86
115
  `/.cratis/me` writes the result as JSON **and** as a base64 cookie named
87
116
  `.cratis-identity`, deliberately **not `HttpOnly`** so the frontend can read it
@@ -90,46 +119,105 @@ is `Lax`, `Path` is `/`.
90
119
 
91
120
  ⚠️ A non-`HttpOnly` cookie the browser can read is a cookie the user can edit.
92
121
  Treat everything in it as a **display** input. Never let it decide anything the
93
- server has not already decided.
122
+ server has not already decided. Today the default is that `/.cratis/me` returns
123
+ whatever a presented `.cratis-identity` cookie decodes to *before* it looks at the
124
+ authenticated principal, so a client can make it report any identity or roles
125
+ (open Arc#2939). Commands and queries authorize on the request principal and are
126
+ not affected; a frontend that shows or branches on `/.cratis/me` can be misled.
94
127
 
95
- ## Authorization — what Arc actually evaluates
128
+ ## Authorization — what Arc evaluates
96
129
 
97
- Arc ships exactly three attributes, all in `Cratis.Arc.Authorization`:
130
+ Arc's attributes live in `Cratis.Arc.Authorization`:
98
131
 
99
132
  | Attribute | Targets | Notes |
100
133
  | --- | --- | --- |
101
134
  | `[AllowAnonymous]` | class, method | No arguments |
102
- | `[Authorize]` | class, method, repeatable | Settable `Policy`, `Roles` (comma-delimited), `AuthenticationSchemes` |
135
+ | `[Authorize]` | class, method, repeatable | `Policy`, `Roles` (comma-delimited), `AuthenticationSchemes` |
103
136
  | `[Roles(params string[] roles)]` | class, method | Derives from `[Authorize]`, joins the roles with commas |
104
137
 
105
138
  There is **no** `[Policy]`, `[Scopes]` or `[Claims]` attribute anywhere in Arc.
106
-
107
- ⚠️ **`AuthorizeAttribute.Policy` and `AuthenticationSchemes` are declared but
108
- never read by Arc's evaluator.** Writing `[Authorize(Policy = "…")]` compiles and
109
- enforces nothing. Only `Roles` is evaluated.
110
-
111
- Evaluation, in order:
112
-
113
- 1. every `IAnonymousEvaluator` is consulted; the first non-null answer decides
114
- anonymous access;
115
- 2. every `IAuthorizationAttributeEvaluator` is consulted for `[Authorize]` and
116
- its `Roles`;
117
- 3. no `[Authorize]` at all means **authorized**; with `[Authorize]`, a null or
118
- unauthenticated principal fails, and a non-empty role list passes when the
119
- user is in **any** of them (comma-split and trimmed — OR, not AND);
120
- 4. a method with no `[Authorize]` falls back to its declaring type's verdict.
121
-
122
- Both `[Authorize]` and `[AllowAnonymous]` on the same member throws
123
- `AmbiguousAuthorizationLevel`.
139
+ Arc's attributes are the portable choice: they are enforced on every Arc host.
140
+
141
+ ⚠️ **Which version you run decides what is enforced.** Through `22.20.0` (this
142
+ skill's old pin was `22.16.0`) only `Roles` is evaluated: `[Authorize(Policy = "…")]`
143
+ and `AuthenticationSchemes` enforce nothing, and Microsoft's `[Authorize]` is **not**
144
+ honored on model-bound commands and read models, so a command protected only by it
145
+ is open. From `22.21.0` Microsoft's `[Authorize]`/`[AllowAnonymous]` are enforced on
146
+ the ASP.NET Core host (never on the standalone Core host), and from `22.23.0` named
147
+ policies and schemes are evaluated. The rest of this section is `22.41.1` behavior;
148
+ see [authorization](references/authorization.md) for the version table.
149
+
150
+ At `22.41.1`:
151
+
152
+ - **Named policies work.** `[Authorize(Policy = "…")]` requires the policy to
153
+ succeed asynchronously. Implement
154
+ `IAuthorizationPolicy.IsAuthorized(AuthorizationPolicyContext, CancellationToken)`
155
+ and register it with `AddArcAuthorizationPolicy<T>(name)` before `Build()`.
156
+ Unknown or duplicate names fail startup; an unresolved policy never grants access.
157
+ The context carries `Principal`, `Target`, `Resource` and `ReceivedAt`.
158
+ The old synchronous `IAuthorizationEvaluator.IsAuthorized` rejects policy-bearing
159
+ declarations.
160
+ - **Schemes.** `AuthenticationSchemes` is honored on the ASP.NET Core host and
161
+ rejected at startup on the standalone Core host.
162
+ - **Composition.** Stacked attributes **AND**; only a role list is OR. A method's
163
+ declaration **replaces** its type's — a method-level `[AllowAnonymous]` or
164
+ guest policy removes a type-level `[Roles]` for that method. `[Authorize]` plus
165
+ `[AllowAnonymous]` on one member throws `AmbiguousAuthorizationLevel`.
166
+ - **Guests.** A policy requires an authenticated principal by default. Unauthenticated
167
+ callers are evaluated only for policies registered with
168
+ `AddArcAuthorizationPolicy<T>(name, evaluatesAnonymous: true)`, or ASP.NET policies
169
+ opted in with `AddArcAnonymousAspNetAuthorizationPolicy(name)` (exact, case-sensitive
170
+ name; no authenticated-user requirement, no schemes). Roles and schemes always
171
+ require authentication.
172
+ - **Order.** Policies are awaited **before** `Provide()`, `Handle()` or the query
173
+ method; context-value providers and scope `Begin` run before the verdict;
174
+ identity and declaration continuity is rechecked around each policy and before
175
+ the handler. A change denies. Policy checks gate **admission**; they do not revoke.
176
+ - **Baselines.** `IFallbackAuthorizationEvaluator` supplies a baseline for commands
177
+ and queries with no explicit declaration, on both hosts, and ASP.NET's
178
+ `FallbackPolicy` covers HTTP endpoints and MVC actions. They are separate:
179
+ neither covers what the other does, and neither protects an explicitly anonymous
180
+ endpoint.
181
+ - **Direct calls bypass authorization.** Calling `Handle()` or a query method
182
+ directly skips authorization, validation and filters; only the pipeline and
183
+ mapped endpoints enforce them. Server-side callers still need a principal
184
+ (`ICurrentPrincipalAccessor`, `ISystemExecution`).
185
+ - **Results.** A denied command returns `CommandResult.Unauthorized(context.CorrelationId)`,
186
+ a query `QueryResult.Unauthorized(...)`; mapped Arc denials are 403, middleware may
187
+ answer 401 or another shape.
124
188
 
125
189
  `ARC0011` warns when a `[Roles]` argument is a string literal: use
126
190
  `nameof(<RoleEnum>.<Member>)` so a rename is a compile error rather than a silent
127
- authorization failure — a desynchronized literal either locks the endpoint or
128
- matches a stale role.
129
-
130
- Read [authorization](references/authorization.md) for the default-access
131
- question, which is genuinely different between Arc's two hosting models, and for
132
- the filter and system-execution extension points.
191
+ authorization failure. `ARC0019` flags `[AllowAnonymous]` with `[Authorize]`/`[Roles]`,
192
+ `ARC0020` flags an ASP.NET Core attribute that is not enforced without Arc's ASP.NET
193
+ Core integration, and `ARC0021` flags `AuthenticationSchemes` on the Core host.
194
+
195
+ ### Observable queries and revocation
196
+
197
+ Authorization runs when a subscription is established. Nothing ends a running
198
+ stream when a token expires, a session is signed out or a role changes. Implement
199
+ `IGuardObservableQueryEmission` (discovered by convention, no registration) to
200
+ re-check access on **every emission on every transport** (hub, WebSocket, SSE):
201
+ the verdict is `Allow`, `Suppress` (withheld, delta baseline unmoved) or
202
+ `DenyAndTerminate` (that subscription only; the client stops reconnecting). The most
203
+ restrictive verdict wins, and a guard that throws, or cannot be constructed, fails
204
+ closed — the latter denies every observable query in the process. The principal comes
205
+ from `ObservableQueryEmissionContext.Principal`, never from ambient accessors or
206
+ `IHttpContextAccessor`; the guard is constructed per emission, so keep it cheap and
207
+ cache in a singleton. Guards do not protect the HTTP snapshot path. Read
208
+ [observable emission guards](references/observable-emission-guards.md).
209
+
210
+ ### Validators are not an authorization boundary
211
+
212
+ A `[ProtectedDecision]` command runs only certified, parameterless validators and
213
+ refuses validators with constructor dependencies. A permission or ownership rule
214
+ that depends on state does not belong in a validator (or in an `[Unprotected]`
215
+ one): put it in `Provide()`/`Handle()` with `DecisionRead<T>` or `IDecisionReads`,
216
+ and see the command-validation and Chronicle guidance.
217
+
218
+ Read [authorization](references/authorization.md) for the guest rules, evaluation
219
+ order, the two baselines, default access under Arc's two hosting models, the
220
+ filters, and system-execution.
133
221
 
134
222
  ## Authentication — the extension point
135
223
 
@@ -208,7 +296,8 @@ implements as `ICanProvideUsers` and `ICanProvideTenants`.
208
296
  To run locally with an identity, supply the forwarded headers yourself — see
209
297
  [local development](references/local-development.md).
210
298
 
211
- ⚠️ Those two endpoints are `AllowAnonymous` and mapped unconditionally. If your
299
+ ⚠️ Those two endpoints are `AllowAnonymous` and mapped unconditionally, in
300
+ Production too, and a fallback policy does not protect them. If your
212
301
  `ICanProvideUsers` implementation returns real users, that list is public. Return
213
302
  development fixtures only, and gate the implementation on a development
214
303
  environment check.
@@ -217,9 +306,30 @@ environment check.
217
306
 
218
307
  - Exactly one non-default `IProvideIdentityDetails` implementation exists, and it
219
308
  also implements `IProvideIdentityDetails<TDetails>`.
220
- - No authorization decision depends on `[Authorize(Policy = …)]`.
309
+ - The Arc version in use enforces what the code declares: policies and Microsoft's
310
+ attributes are not enforced before `22.23.0` and `22.21.0` respectively.
311
+ - Every named policy is registered exactly once; a policy meant for guests has the
312
+ explicit opt-in, and no declaration mixes a guest policy with roles or schemes.
313
+ - A method-level `[AllowAnonymous]` or guest policy is intended to replace its
314
+ type's `[Roles]`.
221
315
  - `[Roles]` arguments use `nameof`, so `ARC0011` is silent.
222
316
  - No member carries both `[Authorize]` and `[AllowAnonymous]`.
317
+ - A baseline exists on purpose: an `IFallbackAuthorizationEvaluator` for the Arc
318
+ pipeline and, on ASP.NET Core, a `FallbackPolicy` for HTTP endpoints and MVC
319
+ actions.
320
+ - Authorization-sensitive logic is never reached by calling `Handle()` or a query
321
+ method directly.
322
+ - Observable queries that serve private or revocable data have an emission guard
323
+ backed by current session and membership state.
324
+ - Permission and ownership rules in `[ProtectedDecision]` commands live in
325
+ `Provide()`/`Handle()`, not in validators.
326
+ - Discovery endpoints (`/.cratis/commands`, `/.cratis/queries`,
327
+ `/.cratis/identity-details/schema`, `/.cratis/users`, `/.cratis/tenants`) are
328
+ tested under Production settings; introspection is restricted or disabled where it
329
+ must not be public, and the rest are restricted at the ingress.
330
+ - `TrustForwardedIdentityHeaders` is set only behind an ingress that authenticates
331
+ callers, strips caller-supplied identity headers, writes trusted ones and blocks
332
+ direct backend access; custom handlers honor it.
223
333
  - Every rule the frontend enforces also exists on the server.
224
334
  - Nothing trusts the identity cookie or the forwarded headers beyond what the
225
335
  ingress guarantees.
@@ -229,7 +339,8 @@ environment check.
229
339
 
230
340
  ## Route near misses
231
341
 
232
- - Rejecting a command's input or state: `cratis-arc-command-validation` scope.
342
+ - Rejecting a command's input or state: `cratis-arc-command-validation` scope
343
+ (validators are not the place for state-dependent permission rules).
233
344
  - Chronicle tenant namespaces and per-tenant event stores: the Chronicle
234
345
  multi-tenancy guidance.
235
346
  - Building the React page that consumes identity: the Arc React guidance.
@@ -1,6 +1,6 @@
1
1
  # Authentication
2
2
 
3
- Verified against `Cratis.Arc.Core` and `Cratis.Arc` `22.16.0`. Types are in
3
+ Verified against `Cratis.Arc.Core` and `Cratis.Arc` `22.41.1`. Types are in
4
4
  `Cratis.Arc.Authentication` and `Cratis.Arc.Identity`.
5
5
 
6
6
  ## The contract
@@ -120,8 +120,62 @@ services.AddMicrosoftIdentityPlatformIdentityAuthentication(scheme?);
120
120
 
121
121
  registers the standard ASP.NET Core scheme backed by
122
122
  `MicrosoftIDentityPlatformAuthHandler` (note the capital `D` in the type name),
123
- whose `SchemeName` is `"MicrosoftIdentityPlatform"`. `builder.AddCratis()` calls
124
- this for you.
123
+ whose `SchemeName` is `"MicrosoftIdentityPlatform"`. `builder.AddCratis()` (the
124
+ `Cratis` package) calls this for you and makes it the **default** authentication
125
+ scheme; `AddCratisArc()` from `Cratis.Arc` does not register it.
126
+
127
+ ⚠️ Today the default is that a plain `builder.AddCratis()` host trusts the unsigned
128
+ `x-ms-client-principal*` headers from **any caller that can reach it** — it is safe
129
+ only behind the ingress described below (tracked as open Arc#2946). If the host is
130
+ not behind such an ingress, do not use this scheme: configure a credential-validating
131
+ ASP.NET Core scheme yourself.
132
+
133
+ ## Forwarded headers, ingress requirements and protected introspection
134
+
135
+ The headers are only safe behind an ingress that **authenticates callers, strips
136
+ any caller-supplied identity headers, writes its own trusted replacements, and
137
+ prevents direct access to the backend**. The same applies to any custom header
138
+ such as `X-User-ID`. Adding a bearer validator does not make a separately accepted
139
+ forwarded-header mechanism safe.
140
+
141
+ Arc applies that rule to one place itself: the protected introspection catalogs
142
+ (`/.cratis/commands`, `/.cratis/queries`). By default those are enabled and
143
+ **anonymous**. Configure `Cratis:Arc:Introspection`:
144
+
145
+ | Option | Default | Effect |
146
+ | --- | --- | --- |
147
+ | `Enabled` | `true` | `false` leaves both catalog routes unmapped |
148
+ | `RequireAuthentication` | `false` | `true` requires an authenticated caller, regardless of the host's default authorization policy |
149
+ | `Roles` | `null` | Comma-separated, any one grants access; needs `RequireAuthentication: true` and no empty entries |
150
+ | `TrustForwardedIdentityHeaders` | `false` | Accepts identity from the unsigned forwarded headers for the protected catalog; needs `Enabled` and `RequireAuthentication` |
151
+
152
+ Today the default is that the catalogs are public, and with
153
+ `RequireAuthentication: true` the forwarded headers are **ignored** for them until
154
+ you set `TrustForwardedIdentityHeaders: true`: the built-in
155
+ `MicrosoftIdentityPlatformAuthenticationHandler` returns
156
+ `AuthenticationResult.Anonymous` for a protected catalog endpoint, so the request
157
+ gets 401. **Only set the opt-in behind the trusted ingress above.**
158
+
159
+ - Startup fails closed for unsafe combinations: `Roles` or the trust option
160
+ without the requirements above; on Arc.Core, `RequireAuthentication` with no
161
+ handler, or with only the built-in header handler and no trust opt-in; on
162
+ ASP.NET Core, a header-trusting scheme reachable from the default scheme or the
163
+ catalog's policy schemes without the opt-in, and a reachable scheme with
164
+ `ForwardDefaultSelector` when a header handler is registered.
165
+ - **Custom handlers.** Arc cannot tell whether your own `IAuthenticationHandler`
166
+ reads forwarded headers, and startup accepts any custom handler as
167
+ credential-validating. If yours builds an identity from ingress headers, read
168
+ `IOptions<ArcOptions>` and return `AuthenticationResult.Anonymous` when
169
+ `TrustForwardedIdentityHeaders` is `false` and
170
+ `context.GetEndpointMetadata()?.RequireAuthentication == true`. A subclass of the
171
+ ASP.NET Core header handler that overrides `HandleAuthenticateAsync` without
172
+ calling the base is your own handler and carries the same obligation.
173
+ - These options do **not** change `/.cratis/identity-details/schema`, command and
174
+ query invocation, or the user and tenant discovery endpoints. Restrict those at
175
+ the ingress. On ASP.NET Core a protected catalog's 401/403 is the configured
176
+ scheme's challenge, which a cookie scheme may turn into a redirect.
177
+
178
+ Discovery exposure as a whole is tracked in open Arc#2834.
125
179
 
126
180
  ## What is not here
127
181
 
@@ -1,94 +1,279 @@
1
1
  # Authorization
2
2
 
3
- Verified against `Cratis.Arc.Core` and `Cratis.Arc` `22.16.0`. Everything below
4
- is in `Cratis.Arc.Authorization` unless stated.
3
+ Verified against `Cratis.Arc.Core` and `Cratis.Arc` `22.41.1`. Everything below
4
+ describes that version and is in `Cratis.Arc.Authorization` unless stated.
5
5
 
6
- ## Default access differs by hosting model
6
+ ## Versions differ — check the one you run
7
7
 
8
- There is **no option anywhere in Arc** that sets a default authentication or
9
- authorization requirement. `ArcOptions` has no such switch. What you get depends
10
- on which pipeline is running.
8
+ Authorization changed a lot between the version this skill used to pin
9
+ (`22.16.0`) and `22.41.1`. Advice that is right for one range is wrong for
10
+ another.
11
11
 
12
- ### Self-hosted `ArcApplication` (Arc.Core)
12
+ | Version | Behavior |
13
+ | --- | --- |
14
+ | through `22.20.0` (includes `22.16.0`) | Only Arc's own attributes count, and only `Roles` is evaluated: `Policy` and `AuthenticationSchemes` are read by nothing, so `[Authorize(Policy = "…")]` enforces nothing. Microsoft's `[Authorize]`/`[AllowAnonymous]` are **not** enforced on model-bound commands and read models (Arc's ASP.NET evaluators bind to Arc's same-named attributes), so a command protected only with Microsoft's attribute is open to every caller. Only the first attribute or evaluator that answers is used. |
15
+ | `22.21.0` | Microsoft's `[Authorize]`/`[AllowAnonymous]` are enforced on the ASP.NET Core host. Every stacked requirement applies (AND). Anonymous plus restricted on one member is rejected as ambiguous. Roles are still the only requirement evaluated. |
16
+ | `22.23.0` | Named policies and `AuthenticationSchemes` are evaluated (`IAuthorizationPolicy`, `AddArcAuthorizationPolicy<T>`, ASP.NET Core policies). |
17
+ | `22.26.0` | `Cratis:Arc:Introspection` options. |
18
+ | `22.30.0` | `IFallbackAuthorizationEvaluator` and `AuthorizationPolicyContext.ReceivedAt`. |
19
+ | `22.31.0` | Opt-in policy evaluation for unauthenticated callers. |
20
+ | `22.39.0` | Protected decisions arrive; the validator boundary at the end of this page is verified at `22.41.1`. |
13
21
 
14
- `AuthenticationMiddleware` runs per request:
22
+ If you are on a version before `22.21.0`, either upgrade, or use only Arc's
23
+ attributes with roles and treat everything else as unenforced. Do not write a
24
+ policy-protected endpoint on a version before `22.23.0`. The rest of this page
25
+ is `22.41.1` behavior.
15
26
 
16
- - **No `IAuthenticationHandler` registered at all → every endpoint is anonymous.**
17
- The middleware returns immediately.
18
- - With at least one handler registered, an endpoint marked `AllowAnonymous`
19
- passes and everything else requires an authenticated principal — otherwise the
20
- response is **401** with a body of `Unauthorized`.
27
+ ## Attributes
21
28
 
22
- `AllowsAnonymousAccess` defaults to **false**: `IsAnonymousAllowed()` on a
23
- top-level type with no attributes has no declaring type to fall back to and
24
- returns false. So under this pipeline commands and queries are
25
- authenticated-by-default *once any handler exists*.
29
+ | Attribute | Notes |
30
+ | --- | --- |
31
+ | `[AllowAnonymous]` | Arc's: class or method, no arguments |
32
+ | `[Authorize]` | Arc's: class or method, repeatable; settable `Policy`, `Roles` (comma-delimited, OR), `AuthenticationSchemes` |
33
+ | `[Roles(params string[] roles)]` | Arc's: derives from Arc's `[Authorize]` and joins the roles with commas |
26
34
 
27
- ### ASP.NET Core hosting (the `Arc` package)
35
+ There is **no** `[Policy]`, `[Scopes]` or `[Claims]` attribute in Arc.
36
+
37
+ With `Cratis.Arc` (ASP.NET Core host), Arc's pipeline **also enforces Microsoft's**
38
+ `[Authorize]` and `[AllowAnonymous]` on model-bound commands and read models,
39
+ including their policies and schemes, over mapped HTTP and hub subscriptions
40
+ (`22.21.0` and later). The two families can be mixed. Arc's own attributes are
41
+ the portable choice: they are enforced on every Arc host, whereas on the
42
+ standalone Core host nothing reads Microsoft's. `RolesAttribute` derives from
43
+ **Arc's** `AuthorizeAttribute`, never Microsoft's.
44
+
45
+ Analyzers: `ARC0011` (use `nameof` in `[Roles]`), `ARC0019` (`[AllowAnonymous]`
46
+ conflicts with `[Authorize]`/`[Roles]` on one declaration), `ARC0020` (an ASP.NET
47
+ Core attribute is not enforced without Arc's ASP.NET Core integration), `ARC0021`
48
+ (`AuthenticationSchemes` needs the ASP.NET Core host). Not every older NuGet
49
+ version contains every rule.
50
+
51
+ ## Composition and precedence
28
52
 
29
- The endpoint mapper only ever calls `AllowAnonymous()`. It **never** calls
30
- `RequireAuthorization()`, and nothing else in Arc does either. Endpoints are
31
- therefore **anonymous by default** unless the application configures its own
32
- fallback policy in ASP.NET Core.
53
+ - **Stacked requirements AND.** Every attribute on a declaration applies. A role
54
+ list is the only OR: the caller needs **any one** role of a single list.
55
+ Policies and roles are never OR'd with each other.
56
+ - **A method replaces its type.** A method's declaration replaces its type's
57
+ declaration; it does not combine with it, whichever attribute family each
58
+ comes from. A method-level `[AllowAnonymous]`, or a guest-allowed policy on a
59
+ method, removes a type-level `[Roles("Admin")]` protection from that method.
60
+ - **Anonymous plus restricted is ambiguous.** `[AllowAnonymous]` with `[Authorize]`
61
+ or `[Roles]` on one member throws `AmbiguousAuthorizationLevel`, in either
62
+ attribute family (Microsoft's is read with `inherit: true`).
63
+ - **No attribute at all** means no authentication or role requirement, unless a
64
+ fallback evaluator supplies a baseline (below).
33
65
 
34
- Decide this deliberately for your host. Do not assume "Arc protects it".
66
+ ## Named policies
35
67
 
36
- ## Role evaluation
68
+ ```csharp
69
+ public class ActiveSubscription : IAuthorizationPolicy
70
+ {
71
+ public ValueTask<bool> IsAuthorized(AuthorizationPolicyContext context, CancellationToken cancellationToken) =>
72
+ ValueTask.FromResult(context.Principal.HasClaim("subscription", "active"));
73
+ }
74
+
75
+ builder.Services.AddArcAuthorizationPolicy<ActiveSubscription>("ActiveSubscription"); // before Build()
76
+ ```
37
77
 
38
- `AuthorizationEvaluator`:
78
+ ```csharp
79
+ [Authorize(Policy = "ActiveSubscription")]
80
+ [Command]
81
+ public record <Name>(...)
82
+ ```
39
83
 
40
- 1. every `IAnonymousEvaluator` is asked; the first non-null answer wins — `true`
41
- authorizes immediately, `false` stops asking and moves on;
42
- 2. every `IAuthorizationAttributeEvaluator` is asked for `[Authorize]` and its
43
- `Roles`; the first that reports one wins;
44
- 3. no `[Authorize]` → **authorized**;
45
- 4. `[Authorize]` with a null or unauthenticated principal → denied;
46
- 5. `[Authorize]` with roles → authorized when the user is in **any** of them.
47
- The string is comma-split and trimmed. It is OR, never AND;
48
- 6. a `MethodInfo` with no `[Authorize]` falls back to its declaring type.
84
+ - `IAuthorizationPolicy.IsAuthorized(AuthorizationPolicyContext, CancellationToken)`
85
+ returns `ValueTask<bool>`. The policy is registered **scoped** and resolves
86
+ from the command's or query's executing scope, so it may depend on scoped
87
+ services.
88
+ - `AuthorizationPolicyContext` is `(ClaimsPrincipal Principal, MemberInfo Target, object Resource)`
89
+ plus `ReceivedAt`. `Target` is the command type or query method; `Resource` is
90
+ the executing `CommandContext` or `QueryContext`.
91
+ - `ReceivedAt` is **Arc receipt time**, captured once at transport dispatch (or
92
+ direct pipeline entry, or per hub subscribe operation) and fixed across
93
+ delayed or repeated evaluation. Use it for time-based admission instead of
94
+ reading the clock after an asynchronous lookup. It is not network arrival
95
+ time. A default value means no receipt: deny.
96
+ - Register every policy before the host starts. An unknown or duplicate name
97
+ fails startup, and an unresolved policy at runtime never grants access. Register
98
+ a name natively **or** in ASP.NET Core, not both.
99
+ - On the ASP.NET Core host, Arc also evaluates policies registered with
100
+ ASP.NET Core (`AddAuthorizationBuilder().AddPolicy(...)`), referenced by either
101
+ attribute family. The handlers receive Arc's `CommandContext`/`QueryContext`
102
+ as the resource, not an MVC resource.
103
+ - The old synchronous `IAuthorizationEvaluator.IsAuthorized(Type|MethodInfo)`
104
+ **rejects policy-bearing declarations** (`AsynchronousAuthorizationRequired`).
105
+ Use the command or query pipeline.
106
+ - The standalone Core host fails startup on `AuthenticationSchemes`. The ASP.NET
107
+ Core host authenticates each named scheme, combines the identities of the ones
108
+ that succeed, and denies when none does; a request that selects schemes runs
109
+ in a fresh execution scope. `ICurrentPrincipalAccessor` then exposes the
110
+ selected identity.
49
111
 
50
- `[Authorize]` and `[AllowAnonymous]` on the same member throws
51
- `AmbiguousAuthorizationLevel` from `AnonymousEvaluator` and from
52
- `AllowAnonymousExtensions.IsAnonymousAllowed`.
112
+ ## Guests and anonymous policies
53
113
 
54
- ⚠️ The ASP.NET Core-flavoured evaluators (`AspNetAnonymousEvaluator`,
55
- `AspNetAuthorizationAttributeEvaluator`) are declared inside
56
- `namespace Cratis.Arc.Authorization` and do not import
57
- `Microsoft.AspNetCore.Authorization`, so the attribute names in them bind to
58
- **Arc's own** attributes. Do not rely on ASP.NET Core's `[Authorize]` being
59
- honoured by them. `AspNetAnonymousEvaluator` also does not throw on the
60
- both-attributes case; it prefers `AllowAnonymous`.
114
+ By default **a policy requires an authenticated principal**, even when the policy
115
+ body would allow an anonymous caller. A guest is evaluated only after an explicit
116
+ opt-in:
61
117
 
62
- ## The filters
118
+ - Arc policy: `AddArcAuthorizationPolicy<T>(name, evaluatesAnonymous: true)`. The
119
+ policy receives an empty unauthenticated `ClaimsPrincipal` and decides itself.
120
+ - ASP.NET Core policy: register it as usual **and** call
121
+ `AddArcAnonymousAspNetAuthorizationPolicy(name)`. The policy must not call
122
+ `RequireAuthenticatedUser()` and must not select authentication schemes. The
123
+ opt-in name must equal the declaration's name exactly, **case-sensitive**.
124
+ The standalone Core host cannot use this opt-in.
125
+ - Startup rejects a missing, ambiguous, native, authentication-required or
126
+ scheme-selected opt-in.
127
+ - Only a declaration made **entirely** of opted-in policies, with no roles and no
128
+ schemes, can evaluate guests. Roles and schemes always require authentication.
129
+
130
+ ⚠️ The opt-in governs Arc's pipeline verdict only. Today the HTTP layer can reject
131
+ a guest before the policy runs: a Core host with any authentication handler, or an
132
+ ASP.NET Core `FallbackPolicy` that requires authentication, returns 401 first
133
+ (tracked in Cratis/Arc#2948). Test guest endpoints through the real HTTP host.
134
+
135
+ ⚠️ Because a method replaces its type, a method-level guest policy on a read model
136
+ with a type-level `[Roles("Admin")]` is reachable by guests when the policy
137
+ allows them. The type-level role no longer protects that method.
138
+
139
+ ## Evaluation order
140
+
141
+ 1. Anonymous evaluators and attribute evaluators resolve the declaration: method
142
+ first, then its type, then the fallback baseline. Conflicts throw
143
+ `AmbiguousAuthorizationLevel`.
144
+ 2. On the ASP.NET Core host, named schemes are authenticated and the selected
145
+ identity chosen.
146
+ 3. Command context-value providers and the execution-scope `Begin` hooks run
147
+ next, **before the policy verdict**, so they can run for a caller the policy
148
+ later denies. They must not perform irreversible effects.
149
+ 4. Authentication and roles are checked, and every policy is **awaited**, one at a
150
+ time, **before** `Provide()`, `Handle()` or the query method runs.
151
+ 5. Identity and declaration continuity is rechecked before and after each policy
152
+ and again immediately before the handler or query method; a change denies.
153
+ 6. Only then does `Provide()`/`Handle()`/the query method run.
154
+
155
+ ⚠️ Policy checks gate **admission**. They do not revoke: a running observable
156
+ stream or a deferred enumeration is not rechecked, and a change in an external
157
+ permission store after admission is not detected. See
158
+ [observable emission guards](observable-emission-guards.md).
159
+
160
+ ## Baselines: two separate mechanisms
161
+
162
+ **`IFallbackAuthorizationEvaluator`** supplies baseline requirements for commands
163
+ and queries that have **no explicit declaration**, on both hosts. Implement it on
164
+ a public class; it is discovered by convention, do not register it.
165
+
166
+ ```csharp
167
+ public class MembersByDefault : IFallbackAuthorizationEvaluator
168
+ {
169
+ public IEnumerable<AuthorizationRequirement> GetAuthorizationRequirements(Type type) =>
170
+ [AuthorizationRequirement.FromRoles("Member")];
171
+
172
+ public IEnumerable<AuthorizationRequirement> GetAuthorizationRequirements(MethodInfo method) => [];
173
+ }
174
+ ```
175
+
176
+ - Commands and type-targeted queries consult only the `Type` overload; the
177
+ `MethodInfo` overload applies only to query methods. Put a baseline for all
178
+ commands in the `Type` overload.
179
+ - A query method's explicit declaration, or its type's, replaces the baseline.
180
+ With neither, the method and type baselines **all** apply, across evaluators.
181
+ - `[AllowAnonymous]` still wins; a method or type `[Authorize]` replaces the
182
+ baseline. It returns requirements, not verdicts: use a policy or a filter for
183
+ resource-dependent rules.
184
+ - `IAuthorizationAttributeEvaluator` reports only **explicit** declarations from
185
+ another attribute family; it never becomes a baseline.
186
+
187
+ **ASP.NET Core `FallbackPolicy`** covers HTTP endpoints and MVC actions without
188
+ authorization metadata. It does **not** supply Arc's pipeline baseline, and
189
+ `IFallbackAuthorizationEvaluator` does not cover direct HTTP GET and WebSocket
190
+ requests to **controller-based** queries or controller-based commands (those are
191
+ MVC actions). Configure both: the evaluator for the Arc pipeline, `FallbackPolicy`
192
+ for MVC. Neither protects an endpoint that is mapped explicitly anonymous (see the
193
+ discovery endpoints in the skill).
194
+
195
+ ## Default access by hosting model
196
+
197
+ There is no `ArcOptions` switch for a default requirement. What you get depends
198
+ on the pipeline.
199
+
200
+ ### Self-hosted `ArcApplication` (Arc.Core)
201
+
202
+ The authentication middleware runs per request:
203
+
204
+ - **No `IAuthenticationHandler` registered → the middleware lets the request
205
+ through** (every endpoint is effectively anonymous), except an endpoint whose
206
+ metadata sets `RequireAuthentication`, which throws
207
+ `AuthenticationRequiredWithoutHandlers` instead.
208
+ - With at least one handler, an endpoint marked `AllowAnonymous` passes and every
209
+ other endpoint requires an authenticated principal, or the response is **401**
210
+ with body `Unauthorized` (**403** when a metadata role is missing). Command and
211
+ query endpoints are marked anonymous only through Arc's `[AllowAnonymous]`
212
+ (`IsAnonymousAllowed`, falling back to the declaring type).
213
+
214
+ Pipeline authorization (roles, policies, fallback baseline) is a second,
215
+ separate check.
216
+
217
+ ### ASP.NET Core hosting (the `Arc` package)
218
+
219
+ Arc's endpoint mapper marks endpoints anonymous with `AllowAnonymous()`, and it
220
+ **does** call `RequireAuthorization(...)` when an endpoint's metadata requires
221
+ authentication or roles (for example the protected introspection catalog).
222
+ Command and query endpoints are otherwise not protected by the mapper, so
223
+ **without a `FallbackPolicy`, ASP.NET Core endpoints are anonymous**, and what
224
+ remains is Arc's pipeline authorization on the declared attributes and any
225
+ `IFallbackAuthorizationEvaluator`. Decide this deliberately; do not assume "Arc
226
+ protects it".
227
+
228
+ ## The filters and results
63
229
 
64
230
  | Interface | Namespace | Shape |
65
231
  | --- | --- | --- |
66
232
  | `IAuthorizationCommandFilter` | `Cratis.Arc.Commands` | Empty marker over `ICommandFilter` (`Task<CommandResult> OnExecution(CommandContext)`) |
67
233
  | `IAuthorizationQueryFilter` | `Cratis.Arc.Queries` | Empty marker over `IQueryFilter` (`Task<QueryResult> OnPerform(QueryContext)`) |
68
234
 
69
- Both are found by discovery — implement one on a public class and it is picked
70
- up. The marker is what guarantees ordering: the filter chains sort
71
- authorization filters first with a stable sort, so a validation failure can never
72
- short-circuit the chain before the authorization verdict is recorded.
235
+ Both are found by discovery. The marker guarantees ordering: authorization filters
236
+ sort first (stable), so a validation failure never short-circuits before the
237
+ authorization verdict.
238
+
239
+ The built-in filters run roles, policies, schemes and the fallback baseline in the
240
+ same pipeline. The command filter returns `CommandResult.Unauthorized(context.CorrelationId)`;
241
+ the query filter returns `QueryResult.Unauthorized(context.CorrelationId)`, and
242
+ returns **success** when no performer is found for the name. A custom filter that
243
+ denies uses the same results — not `CommandResult.Error(...)`, which describes an
244
+ exception.
245
+
246
+ Mapped Arc denials set `IsAuthorized = false` and return **403**. Middleware may
247
+ reject earlier with **401**, and ASP.NET Core's own challenge/forbid can return a
248
+ different shape (a cookie scheme may redirect). Do not infer which layer ran from
249
+ the status alone.
250
+
251
+ ⚠️ `AuthorizationResult` — `record (bool IsAuthorized, string? FailureReason)` with
252
+ `Success` and `Failure(reason)` — is **not** what either filter returns and not
253
+ what `IAuthorizationEvaluator` produces. It is a standalone type, usable as a
254
+ command `Provide()` short-circuit value. A handler returning
255
+ `ValidationResult.Error(...)` is **validation**, not authorization.
73
256
 
74
- Built-in implementations: the command `AuthorizationFilter` returns
75
- `CommandResult.Unauthorized(...)` from `IAuthorizationEvaluator`; the query
76
- `AuthorizationFilter` asks the query performer, and returns **success** when no
77
- performer is found for the name.
257
+ ## Direct calls bypass authorization
78
258
 
79
- ⚠️ `AuthorizationResult` — `record (bool IsAuthorized, string? FailureReason)`
80
- with `Success` and `Failure(reason)` — is **not** what either filter returns and
81
- not what `IAuthorizationEvaluator` produces (that returns a plain `bool`). It is
82
- a standalone type, usable as a command `Provide()` short-circuit value. Do not
83
- describe it as the filter contract.
259
+ Attributes do not intercept ordinary C# calls. `new <Command>(...).Handle()` and a
260
+ static query method called directly skip authorization, validation, filters and
261
+ result handling. Use a mapped endpoint or the command/query pipeline when those
262
+ guarantees matter. Server-side callers must still establish a principal (below);
263
+ being in-process does not prove permission.
84
264
 
85
- ## Executing as a system actor
265
+ ## The principal and system actors
86
266
 
87
- Command authorization reads the principal from the current HTTP request. A
88
- reactor, hosted service, or one command orchestrating another has no request, so
89
- any command carrying `[Authorize]` or `[Roles]` is **denied**.
267
+ `ICurrentPrincipalAccessor.Current` is a nullable `ClaimsPrincipal`, independent
268
+ of transport. During HTTP it is the request principal; outside HTTP it can be the
269
+ principal established by a server-side scope. Read claims from it, not from the
270
+ identity cookie, and not through `IHttpContextAccessor` in code that must also run
271
+ on hub emissions.
90
272
 
91
- `ISystemExecution` is the way out:
273
+ Command authorization reads the principal from the current request. A reactor,
274
+ hosted service, or one command orchestrating another has no request, so any
275
+ command carrying `[Authorize]` or `[Roles]` is **denied**. `ISystemExecution` is
276
+ the way out:
92
277
 
93
278
  ```csharp
94
279
  using var scope = systemExecution.AsSystem(nameof(<RoleEnum>.<Member>));
@@ -101,12 +286,19 @@ await pipeline.Execute(new <CommandName>(<args>));
101
286
  - Disposing restores the previous context.
102
287
 
103
288
  `SystemPrincipal.AuthenticationType` is `"System"` and `SystemPrincipal.Subject`
104
- is `"[System]"`, which is what appears in audit trails.
289
+ is `"[System]"`, which is what appears in audit trails. The established principal
290
+ is consulted **only** when there is no HTTP request context, so it can never
291
+ influence an HTTP-origin command. Keep the scope as narrow as the work: a broad
292
+ `AsSystem` around a whole hosted service makes every command it touches
293
+ privileged.
105
294
 
106
- The established principal is consulted **only** when there is no HTTP request
107
- context, so it can never influence the authorization of an HTTP-origin command.
108
- `CurrentPrincipalAccessor` implements that: a request principal always wins over
109
- the ambient override.
295
+ ## Protected decisions and validators
110
296
 
111
- Keep the scope as narrow as the work. A broad `AsSystem` around a whole hosted
112
- service turns every command it touches into a privileged one.
297
+ A `[ProtectedDecision]` command (`Cratis.Arc.Chronicle.ReadModels`) runs only
298
+ certified, parameterless validators and **refuses** a validator whose constructor
299
+ takes dependencies (a read model, `DecisionRead<T>`, `IDecisionReads`, any
300
+ service). So an authorization or ownership rule put in such a validator — or in an
301
+ `[Unprotected]` command's validator — is **not decision-safe**. Put
302
+ state-dependent permission and ownership rules in `Provide()` or `Handle()` using
303
+ `DecisionRead<T>` or `IDecisionReads`, and route to the validation and Chronicle
304
+ guidance. Validators that read decision state are tracked in Arc#2831.
@@ -1,6 +1,6 @@
1
1
  # Frontend identity
2
2
 
3
- Verified against `@cratis/arc` and `@cratis/arc.react` `22.16.0`.
3
+ Verified against `@cratis/arc` and `@cratis/arc.react` `22.41.1`.
4
4
 
5
5
  ## `@cratis/arc/identity`
6
6
 
@@ -51,6 +51,11 @@ interface IIdentityContext<TDetails = object> extends IIdentity<TDetails> {
51
51
  It seeds `isLoading: true` and fetches on mount. The root `<Arc>` component takes
52
52
  the same `detailsType` prop and renders this provider for you.
53
53
 
54
+ When a refresh finds that an identity which was set is now unset (the server-side
55
+ session ended), the React `IdentityProvider` reloads the page with a full
56
+ top-level navigation rather than leaving the tab signed out and stuck. Do not rely
57
+ on a signed-out render surviving a refresh.
58
+
54
59
  `useIdentity` has two overloads:
55
60
 
56
61
  ```ts
@@ -1,6 +1,6 @@
1
1
  # Running with an identity locally
2
2
 
3
- Verified against `Cratis.Arc.Core` and `Cratis.Arc` `22.16.0`.
3
+ Verified against `Cratis.Arc.Core` and `Cratis.Arc` `22.41.1`.
4
4
 
5
5
  ## What Arc does not give you
6
6
 
@@ -29,8 +29,11 @@ public interface ICanProvideUsers { Task<IEnumerable<User>> Provide(); }
29
29
  ```
30
30
 
31
31
  ⚠️ Both are mapped `AllowAnonymous` and **unconditionally** — there is no
32
- environment check in the mapper. Whatever your implementations return is public
33
- to anyone who can reach the application. Register them only for a development
32
+ environment check in the mapper, so they are anonymous in Production too, and an
33
+ ASP.NET `FallbackPolicy` does not protect them. Without providers they return
34
+ empty arrays. Whatever your implementations return is public to anyone who can
35
+ reach the application. The `Cratis:Arc:Introspection` options do not affect them;
36
+ restrict them at the ingress (see the discovery note in the skill). Register them only for a development
34
37
  environment, and return fixtures rather than production users or tenants.
35
38
 
36
39
  ## Supplying an identity locally
@@ -0,0 +1,104 @@
1
+ # Observable query emission guards
2
+
3
+ Verified against `Cratis.Arc.Core` `22.41.1` (`Cratis.Arc.Queries`).
4
+
5
+ Authorization for an observable query runs **once, when the subscription is
6
+ established**. It decides whether the caller may obtain the live stream. It does
7
+ **not** end the stream when a token expires, a session is signed out, or a role or
8
+ membership changes; keep-alive pings keep the connection open and the client
9
+ reconnects on its own. An **emission guard** closes that gap.
10
+
11
+ ## The opt-in
12
+
13
+ Implement `IGuardObservableQueryEmission`. Guards are discovered by convention:
14
+ no registration, no configuration. With no guard installed, emissions take their
15
+ existing path.
16
+
17
+ ```csharp
18
+ public class SessionMustStillBeActive(ISessions sessions) : IGuardObservableQueryEmission
19
+ {
20
+ public async Task<ObservableQueryEmissionVerdict> Guard(ObservableQueryEmissionContext context)
21
+ {
22
+ var sessionId = context.Principal?.FindFirst("sid")?.Value;
23
+ if (sessionId is null) return ObservableQueryEmissionVerdict.DenyAndTerminate;
24
+
25
+ return await sessions.IsActive(sessionId)
26
+ ? ObservableQueryEmissionVerdict.Allow
27
+ : ObservableQueryEmissionVerdict.DenyAndTerminate;
28
+ }
29
+ }
30
+ ```
31
+
32
+ `ISessions` is the application's own store of authoritative session state — not an
33
+ Arc API, and never an always-true stub.
34
+
35
+ It runs on **every emission** of **every subscription**, on **every transport**:
36
+ the multiplexed hub, WebSocket and SSE.
37
+
38
+ ## Verdicts
39
+
40
+ | Verdict | Effect |
41
+ | --- | --- |
42
+ | `Allow` | The emission is written unchanged. |
43
+ | `Suppress` | This emission is withheld; the subscription stays live. It does **not** move the delta baseline, so the next `ChangeSet` is computed against what the client last actually received. |
44
+ | `DenyAndTerminate` | Nothing is written and **that subscription only** is torn down (siblings on the same connection keep streaming). The client gets `Unauthorized`, latches the denial and stops reconnecting. |
45
+
46
+ Several guards: every guard is asked, the **most restrictive** verdict wins
47
+ (`DenyAndTerminate` over `Suppress` over `Allow`), and the first
48
+ `DenyAndTerminate` short-circuits the rest.
49
+
50
+ ## The context
51
+
52
+ `ObservableQueryEmissionContext` carries `QueryName`, `Arguments`,
53
+ `SubscriptionScope`, `Principal`, `CorrelationId`, `IsFirstEmission`,
54
+ `CancellationToken` and the `ServiceProvider` to resolve from. Each guard gets its
55
+ own copy of the scope and arguments.
56
+
57
+ - The principal is passed **explicitly** in `Principal`. Emissions arrive on the
58
+ producer's thread where the request's ambient context does not flow, so do not
59
+ use ambient accessors, and on **hub** emissions do not use `IHttpContextAccessor`:
60
+ there is no native `HttpContext` after admission.
61
+ - On a **WebSocket** the identity is frozen at the handshake and never refreshes.
62
+ The guard must look it up against your source of truth (session store, revocation
63
+ list, token introspection), not re-read it.
64
+ - `QueryContext.SubscriptionScope` lets a **query filter** record what it decided
65
+ (for example the organization). Arc captures it after the filters succeed and
66
+ **before** the query executes, and hands each emission a fresh copy; a guard can
67
+ compare it to current membership. It must serialize with Arc's
68
+ `JsonSerializerOptions` (small, primitive values; no live services or caches),
69
+ or the query fails as `InvalidSubscriptionScope`. Setting it does not filter the
70
+ data: the query must select its data with the same value. **Controller-based**
71
+ observable queries do not run `IQueryFilters`, so their guards always receive
72
+ `null`.
73
+
74
+ ## Fail closed, and its blast radius
75
+
76
+ A guard that **throws** is treated as `DenyAndTerminate` and logged at `Error`.
77
+ The aggregator is a process-wide singleton over every discovered guard type, so a
78
+ guard that **cannot be constructed** (an open generic, or a constructor the
79
+ subscription scope cannot resolve) denies **every** observable query in the
80
+ process on every transport, with only an `Error` log as the symptom. Cover a new
81
+ guard with a spec that runs its real constructor. A cancellation of the
82
+ subscription's own token while a guard runs ends the subscription without logging
83
+ a failure.
84
+
85
+ ## Cost
86
+
87
+ - The guard is **constructed per emission** and never disposed, because Arc's
88
+ `IFoo → Foo` convention does not match a guard named for what it decides. Keep
89
+ the constructor trivial and put caches in an injected **singleton**, not in a
90
+ field on the guard.
91
+ - Prefer cached state, a local revocation list or a short-TTL lookup to a network
92
+ round trip per emission.
93
+ - Constructor dependencies come from the subscription's own scope, so a scoped
94
+ session store is safe to inject.
95
+
96
+ ## What a guard does not protect
97
+
98
+ - The HTTP **snapshot** path (`ObservableQueryHttp`, including
99
+ `waitForFirstResult=true`) is not an emission guard path. Apply subscription-time
100
+ authorization and safe data selection to every query.
101
+ - A guard is not a substitute for the subscription-time declaration: the
102
+ `[Authorize]`/`[Roles]`/policy on the read model still decides who may subscribe.
103
+ - Interceptor masking is not an access control; the producer must never yield
104
+ rows or fields the caller may not receive.
@@ -1,6 +1,6 @@
1
1
  # Tenancy
2
2
 
3
- Verified against `Cratis.Arc.Core` `22.16.0`. Types are in `Cratis.Arc.Tenancy`.
3
+ Verified against `Cratis.Arc.Core` `22.41.1`. Types are in `Cratis.Arc.Tenancy`.
4
4
 
5
5
  Arc tenancy is **request-scoped tenant resolution**. It answers "which tenant is
6
6
  this request for". It is not Chronicle's tenant namespace isolation, and it does
@@ -72,12 +72,19 @@ be refused.
72
72
  `string.IsNullOrEmpty(tenantId)` never fires for an unresolved tenant. Compare
73
73
  against `TenantId.NotSet`.
74
74
 
75
+ `ITenantScope.Begin(TenantId)` selects a tenant explicitly for the current
76
+ asynchronous flow until the returned scope is disposed, and takes precedence over
77
+ the configured resolver. It rejects a null or blank tenant, and it does **not**
78
+ authorize access to that tenant. Resolve tenant-scoped services in a DI scope
79
+ created after beginning it.
80
+
75
81
  ## Development listing
76
82
 
77
83
  `ICanProvideTenants` (`Task<IEnumerable<Tenant>> Provide()`) feeds
78
84
  `GET /.cratis/tenants`, where `Tenant` is `record (TenantId Id, TenantName Name)`.
79
- The endpoint is `AllowAnonymous` and mapped unconditionally, so an implementation
80
- that returns real tenants publishes them. Return development fixtures only.
85
+ The endpoint is `AllowAnonymous` and mapped unconditionally — also in Production,
86
+ and an ASP.NET fallback policy does not protect it — so an implementation that
87
+ returns real tenants publishes them. Return development fixtures only.
81
88
 
82
89
  ## Where the boundary is
83
90
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.3.3",
3
+ "version": "7.3.4",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [