# CareLedger tenant isolation: operational reference

Companion to [Cancel appointment 100 in the right organization](https://dotnetguides.com/guides/multi-tenancy-tutorial). The sample is fictional and exercises SQLite and loopback HTTP only.

## Production planning index · 22 use cases

“Sample” identifies implemented mechanisms; “Pattern” is unimplemented guidance. The final column distinguishes tested fixture checks from checks still to run on real infrastructure.

Ownership rules and negative acceptance checks

| Use case | Status | Rule | Negative check |
| --- | --- | --- | --- |
| Tenant resolution | Sample + pattern | Active route selector and membership lookup; no default tenant. For host selectors, register domains and trust forwarded hosts only through configured proxies. [Host policy](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/host-filtering?view=aspnetcore-10.0). | Tested: Unknown or unjoined tenant is denied. |
| Authentication | Pattern | Replace fixture headers with verified principals; identity-provider tenant IDs require application mapping. | Plan: Forged issuer, audience or signature fails before data access. |
| Membership and switching | Sample | Fresh permission snapshot per operation; stricter in-flight revocation needs a stated policy. | Tested: North writer switching to South cannot write there. |
| Operation and facility permissions | Sample | Endpoint authorization and authorized row loads; grants belong to one organization. | Tested: Blair cannot read or change North inpatient slots. |
| Shared / dedicated / hybrid storage | Sample + pattern | Shared SQLite is implemented. SQL Server placement choices follow recovery, region and principal requirements. | Plan: Wrong catalog mapping must fail before opening tenant storage. |
| EF reads and writes | Sample | Filters, tenant-composite keys/relationships, DTOs and both save paths; internal context access remains privileged. | Tested: Foreign victim stays unchanged after HTTP and detached attacks. |
| Bypasses | Sample + pattern | IgnoreQueryFilters is demonstrated. Bulk/direct SQL/RLS need separate protections below. | Plan: Every permitted bypass has its own negative integration test. |
| Jobs and retries | Sample + pattern | In-memory registered job IDs and execution scopes are implemented. Production needs protected stored requests, trusted producer/broker and placement validation. Idempotency uses (TenantId, Operation, Key), payload hash and scope; business changes/outbox commit together, consumers deduplicate and saved results are reauthorized. | Plan: Revocation denies execution; durable retry duplicates no effect and changed input is rejected. |
| Cache and output caching | Sample + pattern | Authorize before lookup. Keys include tenant, resource, version and permission dimensions; permission-specific results need grant version or user scope. Invalidate writes and permission changes. Default output caching excludes authenticated requests; custom policies need explicit variation. [Output caching](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/output?view=aspnetcore-10.0). | Tested: A cache warmed by Alex cannot reveal Blair’s forbidden facility. |
| Files and signed URLs | Sample + pattern | Authorize metadata, then owned bytes. Uploads use bounded staging, scan/size checks and expiry. Signed URLs are object/operation-limited bearer capabilities; immediate revocation needs a proxy or supported mechanism. Never log their secrets. [Signed access](https://learn.microsoft.com/en-us/azure/storage/blobs/sas-service-create-dotnet). | Plan: Guessed foreign object keys return no bytes or capability. |
| Search | Pattern | Build tenant/permission constraints server-side for documents, counts, facets, suggestions and autocomplete. Tenant-bind index upserts/deletes; update stale permission fields and validate rebuild counts. [Security filters](https://learn.microsoft.com/en-us/azure/search/search-security-trimming-for-azure-search). | Plan: No foreign counts or suggestions; stale indexing cannot restore revoked visibility. |
| Realtime | Pattern | Authorize joins and commands; leave old groups on switches, revalidate reconnects and remove/terminate revoked connections. Broadcast producers carry tenant context. Group names are routing, not security. [SignalR groups](https://learn.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-10.0). | Plan: A guessed group name or reconnect cannot regain access. |
| Integrations and webhooks | Pattern | Verify provider-signed bytes, timing and replay policy; map verified account to one integration/tenant. Deduplicate (TenantId, IntegrationId, Provider, EventId). For outgoing delivery, validate scheme, DNS/address and every retry; disable redirects or validate each hop before forwarding secrets. [Integrations](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/approaches/integration); [redirects](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.allowautoredirect?view=net-10.0). | Plan: Forged tenant JSON is ignored; duplicate events and DNS/redirect changes cannot widen scope. |
| Exports | Sample + pattern | Count executor is implemented. Persist request scope, purpose, format, state and expiry; authorize status/download again. Bound rows, bytes, concurrency and retention; clean partial output and define CSV formula safety. | Plan: Membership removal denies a new download; another tenant cannot read status or bytes. |
| Audit and observability | Pattern | Record real actor, tenant, operation, resource, time and outcome. Commit durable audit intent with sensitive changes; failure to commit audit intent blocks the mutation; sink outages retry delivery of committed intent. Operational logs omit patient data, bodies, tokens and URLs; keep EF sensitive-data logging off and metric labels bounded. [EF logging](https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/simple-logging). | Plan: A failed audit sink produces retryable intent, not a silent gap or secret-bearing trace. |
| Quotas and noisy neighbors | Pattern | Use validated-tenant partitions for API, jobs, storage, exports and expensive queries. Instance-local rate limits do not enforce global quotas across replicas; coordinate contracted totals. Bound shared compute and measure contention. [Rate limits](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-10.0); [capacity](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/approaches/compute). | Plan: North’s export burst leaves South within its agreed latency/error budget. |
| Provisioning, migrations and moves | Pattern | Activate only after storage/schema/grants are ready. Track versions per placement; run reviewed migration cohorts with a separate deployment identity. After interruption inspect physical schema and history. Cutover pauses/drains writers or enforces placement generation in the write protocol. [Catalog](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/approaches/control-planes); [migrations](https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying). | Plan: Partial provisioning denies traffic; an old worker cannot write after cutover. |
| Backup and restore | Pattern | Dedicated databases have separate restore units. Shared recovery restores to an isolated environment, extracts one tenant and reconciles files, audit, memberships, integrations and queued work. Agree lost-work/recovery-time targets and control replay. [SQL Server restore](https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/restore-a-database-backup-using-ssms?view=sql-server-ver17). | Plan: Recover North without reverting South or replaying duplicate external effects. |
| Support access | Pattern | Separate administrative path: named operator, explicit tenant, purpose, allowed operations, expiry and approval policy. Audit actual operator and effective tenant; default to operational metadata. | Plan: Grant expiry and tenant limits hold; support never masquerades as an ordinary user. |
| Cross-tenant reporting | Pattern | Separate curated extraction pipeline and reporting principal with approved fields and explicit platform permission. Tenant-facing reports remain scoped; aggregation alone does not establish anonymization. | Plan: Tenant users cannot invoke platform reports; removals propagate to derived datasets. |
| Offboarding | Sample + pattern | Suspension is implemented. Revoke grants/credentials, quarantine jobs and expire exports; purge derived copies under retention policy. Keep external tombstones so old backups cannot reactivate tenants. IDs are never recycled. [Lifecycle](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/considerations/tenant-life-cycle). | Plan: Delayed jobs/index retries and restored backups cannot recreate active tenant data. |
| Patient processing and clinical compliance | Excluded | Synthetic appointment slots only. No patient records, EHR connectivity, clinical authorization or HIPAA-compliance claim. | Plan: Requires separate domain, legal and infrastructure work. |

## EF Core bypasses and tracked-write guard

Access paths that need separate protections

| Path | Required protection |
| --- | --- |
| IgnoreQueryFilters / soft deletion | Disabling every filter removes tenant isolation. EF Core 10 named filters allow selective soft-delete bypass; retain the tenant filter. [Filters](https://learn.microsoft.com/en-us/ef/core/querying/filters). |
| Find and required navigations | Find can return a tracked entity without querying. Reauthorize the resource. Filtered required joins can change Includes, projections and counts; test their exact provider behavior. [Find](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.find?view=efcore-10.0). |
| ExecuteUpdate / ExecuteDelete | Query filters can still apply, but SaveChanges guards do not run. Require tenant/facility predicates, permitted columns, affected-row checks and transactions; prohibit TenantId changes. Tracked state may become stale. [Bulk operations](https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete). |
| FromSql and direct SQL | Composable entity FromSql can retain EF filters. ExecuteSql, Dapper, scalar SqlQuery, procedures and administrative commands need their own authorized tenant scope. Parameterization addresses injection, not permission. [SQL composition](https://learn.microsoft.com/en-us/ef/core/querying/sql-queries). |
| Pooling and cached options | A pool reuses instances; prove tenant-state reset before reuse. A singleton factory must not cache tenant-dependent options across switches. [Pooling guidance](https://learn.microsoft.com/en-us/ef/core/performance/advanced-performance-topics). |

**Data.cs · common sync/async tracked-write guard**

```csharp
private void ValidateWrites()
	{
		ChangeTracker.DetectChanges();
		foreach (var entry in ChangeTracker.Entries<ITenantEntity>()
			.Where(e => e.State is EntityState.Added or EntityState.Modified or EntityState.Deleted))
		{
			access.RequireWrite();
			if (entry.Entity.TenantId != _tenantId) throw new TenantDeniedException();
			access.RequireFacility(entry.Entity.FacilityId);
			if (entry.State != EntityState.Added)
			{
				if (entry.Property(nameof(ITenantEntity.TenantId)).OriginalValue as string != _tenantId)
					throw new TenantDeniedException();
				access.RequireFacility((string)entry.Property(nameof(ITenantEntity.FacilityId)).OriginalValue!);
			}
		}
	}
```

## SQL Server RLS illustration

Illustrative DDL only: it was not executed or syntax-validated against SQL Server. Filter predicates restrict visibility; block predicates reject disallowed writes. [RLS documentation](https://learn.microsoft.com/en-us/sql/relational-databases/security/row-level-security?view=sql-server-ver17).

**T-SQL · illustrative**

```sql
-- Illustrative SQL Server DDL. Not executed by the SQLite sample.
-- Prerequisites: dbo.Appointments(TenantId nvarchar(32), ...) and
-- a deployment principal authorized to create the security schema/policy.
CREATE SCHEMA Security;
GO
CREATE FUNCTION Security.TenantPredicate(@TenantId nvarchar(32))
RETURNS TABLE WITH SCHEMABINDING AS
RETURN SELECT 1 AS Allowed
WHERE @TenantId = CONVERT(nvarchar(32), SESSION_CONTEXT(N'tenant_id'));
GO
CREATE SECURITY POLICY Security.AppointmentTenantPolicy
	ADD FILTER PREDICATE Security.TenantPredicate(TenantId)
		ON dbo.Appointments,
	ADD BLOCK PREDICATE Security.TenantPredicate(TenantId)
		ON dbo.Appointments AFTER INSERT,
	ADD BLOCK PREDICATE Security.TenantPredicate(TenantId)
		ON dbo.Appointments AFTER UPDATE
	WITH (STATE = ON);
GO
-- Trusted connection setup, before any tenant data command:
EXEC sys.sp_set_session_context @key = N'tenant_id', @value = N'north';
```

Apply policies to all relevant tables. Trusted connection setup must set validated session context before commands and prevent stale pooled values. Runtime principals cannot alter the policy; broad SQL access may still set another tenant value. RLS supplements application authorization.

## Evidence, startup cleanup and remaining limits

The 49 isolation and 13 lifetime assertions are retained, with 17 added boundary checks. The separate consumer project verifies public onboarding compilation. Raw output and startup regression are in the ZIP.

Create owns the built app until initialization succeeds; failed seeding disposes it before rethrowing. Removing that cleanup makes the regression assertion fail. Caller-owned contexts use using/await using; request contexts belong to DI.

SQLite does not establish SQL Server locking, collation, RLS, pooling, migrations or recovery. EnsureCreated is used only for fresh scratch files. Concurrent duplicate creation, competing business edits and distributed cache invalidation require separate evidence.

The cache still authorizes through a database read, and files are synthetic in-memory bytes. TenantAccess is internal immutable facts; it is not a security boundary against malicious same-process code. Patient processing, clinical authorization and HIPAA compliance are excluded.

## Sources

- [Storage tradeoffs](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/approaches/storage-data)

- [Middleware activation](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/extensibility?view=aspnetcore-10.0)

- [Context lifetime](https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/)

- [JWT validation](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/configure-jwt-bearer-authentication?view=aspnetcore-10.0)

- [Composite relationships](https://learn.microsoft.com/en-us/ef/core/modeling/relationships/foreign-and-principal-keys)

- [Filters](https://learn.microsoft.com/en-us/ef/core/querying/filters)

- [EF factory contract](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.idbcontextfactory-1.createdbcontextasync?view=efcore-10.0)

- [Background-service scopes](https://learn.microsoft.com/en-us/dotnet/core/extensions/scoped-service)

- [EF cancellation guidance](https://learn.microsoft.com/en-us/ef/core/miscellaneous/async)

- [Provider testing strategy](https://learn.microsoft.com/en-us/ef/core/testing/choosing-a-testing-strategy)

- [Host policy](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/host-filtering?view=aspnetcore-10.0)

- [Output caching](https://learn.microsoft.com/en-us/aspnet/core/performance/caching/output?view=aspnetcore-10.0)

- [Signed access](https://learn.microsoft.com/en-us/azure/storage/blobs/sas-service-create-dotnet)

- [Security filters](https://learn.microsoft.com/en-us/azure/search/search-security-trimming-for-azure-search)

- [SignalR groups](https://learn.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-10.0)

- [Integrations](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/approaches/integration)

- [redirects](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.allowautoredirect?view=net-10.0)

- [EF logging](https://learn.microsoft.com/en-us/ef/core/logging-events-diagnostics/simple-logging)

- [Rate limits](https://learn.microsoft.com/en-us/aspnet/core/performance/rate-limit?view=aspnetcore-10.0)

- [capacity](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/approaches/compute)

- [Catalog](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/approaches/control-planes)

- [migrations](https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying)

- [SQL Server restore](https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/restore-a-database-backup-using-ssms?view=sql-server-ver17)

- [Lifecycle](https://learn.microsoft.com/en-us/azure/architecture/guide/multitenant/considerations/tenant-life-cycle)

- [Find](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.find?view=efcore-10.0)

- [Bulk operations](https://learn.microsoft.com/en-us/ef/core/saving/execute-insert-update-delete)

- [SQL composition](https://learn.microsoft.com/en-us/ef/core/querying/sql-queries)

- [Pooling guidance](https://learn.microsoft.com/en-us/ef/core/performance/advanced-performance-topics)

- [RLS documentation](https://learn.microsoft.com/en-us/sql/relational-databases/security/row-level-security?view=sql-server-ver17)

Written with AI and not reviewed by a human. It may contain mistakes.
