# Authorize product capabilities

Compose current actor/resource authorization and explicitly gated diagnostic timing.

Status: supplied in Foundation **0.14.0**. Version 0.13.0 does not contain these
APIs. Consumers upgrade and bind current product authorization explicitly;
publication does not grant permissions or change a deployed product.

## Ownership

`Fabricators.Kernel.Security.Authorization` supplies immutable capability
definitions, an exact-match catalog, actor/resource contracts, a current
authorization port and a checker. This layer has no ASP.NET, DI, EF or identity
provider reference. Use it from HTTP hosts, workers or application services.

`Fabricators.Kernel.AspNetCore` adds policies and endpoint requirements.
`Fabricators.Observability.AspNetCore` contributes the first protected feature:
response diagnostic timing. No additional production dependency is needed;
Observability's HTTP adapter now references Kernel.AspNetCore.

Foundation owns `foundation.diagnostics.read`. The catalog describes the
operation; it grants nobody access. Products own roles, persisted assignments,
tenant/company membership, licensing, delegation, audit and any operator UI/CLI.
There is no universal Admin/Owner role, wildcard grant or assignment writer.
Session/credential management capabilities are not invented here: their exact
resource and ownership semantics need a separate design.

Identifiers are stable, lowercase dotted segments with lowercase letters,
digits and hyphens, with a letter first in each segment. Matching is ordinal.
Definitions include an explicit owner and description. The immutable registry
rejects duplicate IDs, including conflicting owners. The trusted host approves
definitions; an owner label is not publisher verification or a security proof.

## Product adapters

Register one approved catalog per host:

```csharp
services.AddFoundationAuthorization(
    new PermissionDefinition(
        "acme.helpdesk.ticket.read",
        "acme.helpdesk",
        "Read an admitted ticket."));
services.AddScoped<IPermissionRequestBinder, ProductPermissionBinder>();
services.AddScoped<IPermissionAuthorizer, ProductPermissionAuthorizer>();
```

Implement both adapters against current, trusted product state:

- `IPermissionRequestBinder.BindAsync` receives the authenticated principal and
  ASP.NET resource (`HttpContext` for HTTP policies). Resolve authority, stable
  subject ID, human/workload kind and resource scope on the server. Reject
  revoked users/sessions, ambiguous identities, inadmissible recovery/setup
  sessions and mismatched authorities. Return null to deny. Never bind an actor
  from an arbitrary owner ID, query parameter or unverified forwarding header.
- `IPermissionAuthorizer.IsGrantedAsync` receives the exact catalog definition,
  actor and optional resource. Read current grants and enforce resource
  ownership, tenancy, license and product constraints. Never treat token roles,
  OAuth scopes or the fact that a definition exists as an implicit grant.

There is no permission decision cache. Scoped adapters are resolved for each
request; the same session observes revocation on its next authorization check.
Missing adapters, unknown IDs, wildcards, invalid bindings and explicit denial
deny. Cancellation propagates. A failing authorization store cannot become an
allow decision; normal product exception handling applies. The checker does not
turn a failed store into an anonymous identity or cache a last-known allow.

For endpoints, keep authentication/authorization middleware and compose other
requirements normally:

```csharp
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/tickets/{id}", ReadTicket)
    .RequireFoundationPermission("acme.helpdesk.ticket.read")
    .RequireAuthorization("RecentMfa");
```

A permission does not establish MFA assurance, recent authentication or resource
ownership. The additional policy and product checks still have to succeed.
Consumers may enforce assurance in their adapters or independent ASP.NET
requirements. Machine scope ceilings are additional restrictions, not aliases
for user grants. Explicit scheme selection remains the host's responsibility.

Workers can construct `PermissionCatalog` and `PermissionChecker` directly and
pass a server-verified `PermissionActor`, exact ID and `PermissionResource`.
The checker validates bounded keys but cannot establish their provenance.
Resource `Kind`, `Id` and optional `Scope` are opaque product keys, not an ERP
tenant model. A product must not silently ignore resource scope or actor kind.

## Gate diagnostic timing

```csharp
services.AddFoundationAuthorization();
services.AddScoped<IPermissionRequestBinder, ProductPermissionBinder>();
services.AddScoped<IPermissionAuthorizer, ProductPermissionAuthorizer>();
services.AddFabricatorsHttpDiagnostics();
services.AddFoundationDiagnosticDisclosure(options =>
{
    options.Enabled = true;
    options.AllowedEnvironments = [Environments.Development];
});

// Place before authentication/authorization to measure their work.
app.UseFoundationRequestDiagnostics(options =>
    options.JsonHeaderName = "X-Product-Timing");
app.UseAuthentication();
app.UseAuthorization();
```

Import Kernel.AspNetCore, Kernel.Security.Authorization and
Observability.AspNetCore. Enable disclosure deliberately: defaults are disabled
with an empty environment allowlist. Environment names match exactly. Both an
allowed environment and current `foundation.diagnostics.read` are required;
Development, a BFF connector, Owner or token scope alone is insufficient.
Configuration is snapshotted at host composition; live user grants remain
product-owned. Authentication must actually run on the measured route.

In published 0.14.0/0.15.0, the public middleware selects this policy and disables the low-level
Development bypass, even if its customization callback attempts to replace
them. JSON/header customization remains available. Denial emits no timing,
trace ID or optional timing JSON and does not invoke the JSON payload factory.
Allowed timing responses have `Cache-Control: no-store`. Products must preserve
this at their BFF/proxy and avoid caching/replaying authorized timing headers.
Internal metrics continue regardless of response disclosure. Totals/phases use
one monotonic snapshot before asynchronous authorization checks.

Starting in **0.16.0**, a quiet policy predicate controls optional response
enrichment. It preserves the frozen environment gate, named policy requirements,
registered handlers/evaluator and current product binder/checker, but avoids
calling ASP.NET's denial-logging service on every ordinary response. Additional
assurance requirements on the named policy continue to apply; actual protected
endpoints retain the ordinary authorization service. Put product restrictions
in policy requirements/handlers or the live permission adapters, rather than
only in a replacement IAuthorizationService decorator.
The high-level middleware still prevents customization callbacks from bypassing
its gate. False yields no headers and no authorization-failure event; actual
endpoint denials retain normal authorization logging. Explicit caching and
validators suppress diagnostic disclosure without changing the cache policy;
see [observability](/foundation/0.19.0/guides/observability/).

The older `UseFabricatorsRequestDiagnostics` remains a low-level compatibility
API for existing product-owned policies. Its default Development exposure is
**off starting in 0.14.0**. Explicit `ExposeInDevelopment = true` retains the old local bypass;
it must not be used as the public permission gate. A custom `DisclosurePolicy`
must itself enforce the product's environment and authorization restrictions.
This change hides default Development timings until a host opts in.

Hiding diagnostic headers does not remove observable network response times or
prove password verification constant-time. Credential verification, enumeration
controls and rate limits remain independent authentication requirements.

## Existing ERP permission binding

ERP already persists `platform.diagnostics.read`. Do not rename it in place or
invalidate sessions. Its adapter can explicitly map Foundation's operation
`foundation.diagnostics.read` to that existing product grant while preserving
the current environment, session assurance and identity checks. This is a
consumer binding, not a Foundation legacy fallback. The ERP deployment CLI,
catalog and audit remain product-owned; adoption is a separate increment.

## Acceptance

Tests exercise exact/duplicate/invalid catalogs, independent worker contracts,
current authorization without caching, invalid actors/resources, cancellation
and store failure. Real ASP.NET TestServer requests cover absent adapters,
anonymous/role/scope-only denial, third-party definitions, unknown operations,
environment gates, disabled defaults, same-session revocation and independent
assurance policies. Independent NuGet consumers compile the public contracts
and reject missing authorization. No database tables or migrations are added.

Local acceptance on 2026-11-16: **559 SDK-only tests plus all 14 real PostgreSQL
tests passed (573 distinct tests)**. Locked restore, unused imports, style,
analyzers, formatting/layout and Release build pass with zero warnings/errors.
All 30 local NuGet archives pass independent consumers and installed-tool checks;
the headless documentation export is validated. The release workflow separately
requires successful CI on the exact tagged source; downstream adoption remains
an explicit consumer operation.
