Commit Graph

36 Commits

Author SHA1 Message Date
Oliver Kieselbach f795fbcb4e feat(auth): dual app-reg parallel operation - legacy gktatooine app alongside new C4A8 app
True parallel operation, no forced re-consent: existing tenants keep signing
in via the legacy app (1a400946), new tenants land on the C4A8 app (886ab5e2).

Model "default legacy, funnel primary, learn in the background":
- Web: am_auth_app flag -> NEXT_PUBLIC_ENTRA_DEFAULT_APP -> primary; get-started
  CTA hands over with ?authapp=primary; auth/me homedApp updates the flag so an
  operator tenant flip takes effect on each user's NEXT login; AADSTS90094/65001
  one-shot cross-app retry, AADSTS65004 -> failed screen with previous-app link;
  am_login_attempt pins redirect returns to the app that started them.
- Backend: TenantConfiguration.HomedAppClientId (null = legacy, GA-only flip via
  PUT config) + LastAuthClientId/Since observability; EntraAppRegistry resolves
  the acting app per tenant (no-op until the legacy config pair is set); Graph
  client-credentials, admin-consent URLs and the surfaced client id follow the
  homed app (app-scoped cache keys); JwtBearer [Authorize] pipeline now shares
  the middleware audience builders (was single-audience - would 401 legacy
  tokens after the swap); middleware trusts EntraId:LegacyClientId implicitly.
- well-known association file now lists both app ids (publisher domain);
  deploy-web passes NEXT_PUBLIC_ENTRA_LEGACY_CLIENT_ID / _DEFAULT_APP;
  mcp-server.bicep default client id -> C4A8 app.

Backend xUnit 3730/3730, vitest 625/625 (13 new), tsc/ESLint clean, next build ok.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-31 18:12:25 +02:00
Oliver Kieselbach e0ad51b965 refactor(urls): one guard-enforced URL registry per component, agent downloads move to the alias
Every well-known host -- own subdomains, both blob accounts, the API origin,
Graph, Entra login -- now lives in exactly one registry per component:
Constants.cs (*BaseUrl) for C#, utils/config.ts for the web app, src/config.ts
for the MCP server. lib/hostRouting.ts derives its hostnames from the registry
and middleware.ts imports from it, retiring what turned out to be a fourth
independent copy of the www/portal host pair.

Three new guard tests (backend xUnit, web vitest, MCP vitest) scan non-test
source and fail on any enforced host outside its registry. This is the lesson
of the EU cutover: the registry existed then too, but LatestVersionsService
(feeds the portal's version badge) and ValidateBootstrapCodeFunction carried
their own literal copies of the legacy blob host and were missed -- kept
working only by the fail-soft legacy mirror in build-agent.yml, whose silent
failure would have pinned badge and self-update to stale bits with a green
release. Both guards proved themselves on their first run, flagging the
middleware host copy and a literal in an MCP tool description. Test files stay
exempt on purpose: literals there are independent oracles, and
ValidateBootstrapCodeResponseShapeTests now pins the full alias URL against
the Constants-built one so registry changes must be acknowledged consciously.

The two legacy readers plus the agent SelfUpdater now use
Constants.AgentDownloadBaseUrl (download.autopilotmonitor.com/agent); the
alias was verified live for version.json, version-v2.json and both ZIPs
before the switch. The portal's bootstrap allow-list accepts the alias AND
the legacy host (AGENT_DOWNLOAD_HOSTNAMES) for already-deployed customer
scripts, which imposes a deploy order: web before or with backend. The
legacy keepalive probes and the release mirror stay untouched -- they exist
for exactly this transition. Also: the bootstrap short-link now targets www
directly instead of riding the registrar's apex 301, and the welcome-mail
docs button points at docs. instead of bouncing through www./docs.

Suites: backend 3194, agent core 1925, DecisionCore 474, web 582, MCP 449 --
all green; next build verified (it, not tsc, proves the next.config.ts
registry import). Docs: docs/url-registry.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 08:37:42 +02:00
Oliver Kieselbach 757427ffea chore(build): clear the compiler and xUnit analyzer warnings CI annotates
The CI test job surfaced 10 annotations, but GitHub caps them at 10 per job —
a full rebuild showed 31 nullable warnings plus 26 xUnit analyzer warnings.

Production code:
- CertificateValidator: X509Certificate2(byte[]) is obsolete (SYSLIB0057) ->
  X509CertificateLoader.LoadCertificate.
- AuthenticationMiddleware: IsValidTenantId now carries [NotNullWhen(true)], so
  the guard above BuildTenantAuthority is visible to flow analysis.
- AgentEndpointMigrationRules: the out params are genuinely nullable on the
  false path; netstandard2.0 has no usable [NotNullWhen], so the contract is
  documented instead.
- Constants.ClassifyEspAppsFailure: errorCode is optional by design (the
  "no HRESULT" branch is the timeout fallback) - signature says so now.

Tests: nullable annotations on helper signatures, Assert.Single/DoesNotContain
overloads instead of pre-filtering with Where, and [InlineData(null)] theories
declare nullable parameters. GatherRule helpers now seed Parameters with the
model default (empty) rather than null, matching a deserialized rule.

No behaviour change. 5616 tests pass; solution builds warning-free apart from
the two pre-existing NU1510 pruning notices on the pinned security packages.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 11:09:11 +02:00
Oliver Kieselbach fa640ebe61 fix(security): resolve CodeQL log-forging findings and suppress by-design queries
Bucket B (real fixes) + Bucket A (config) of the CodeQL alert triage.

Log-forging (cs/log-forging, 8 sinks): add Helpers/LogSanitizer that strips
CR/LF and other control characters, and apply it to the logged copy of every
user-controlled value in AuthenticationMiddleware, PolicyEnforcementMiddleware
(Invoke + DecideAsync), McpQuotaEnforcementMiddleware and TableUserUsageRepository.
Only the logged value is sanitized — routing, authorization and storage keys are
untouched, so tracing fidelity for legitimate values (paths, UPNs, GUIDs) is
preserved. Structured logging already isolated the fields; this closes the CRLF
vector as defense-in-depth and clears the query.

Three genuine JS/TS fixes:
- guardValidation.ts: replace the no-op `.replace(/%/g, "%")` with a real
  escapeRegExp() — the author intended to escape; this also closes the latent
  metacharacter gap (js/identity-replacement).
- access-guard.ts: use a `%s` format argument instead of interpolating the UPN
  into the console.error format string (js/tainted-format-string).
- docs-corpus.ts: strip HTML tags with a loop-until-stable stripHtmlTags() so the
  sanitizer is robust and recognized as complete (js/incomplete-multi-char-sanitization).

CodeQL config: filter the two queries that fire structurally on this codebase,
where the flagged behavior is the feature — cs/exposure-of-sensitive-information
(audit/notification logs legitimately record the actor UPN / recipient email) and
cs/cleartext-storage-of-sensitive-information (rate limiters key on the trusted
client IP). Default suites stay active; genuine one-off false positives from other
queries are dismissed individually so those queries stay sharp.

Tests: Backend xUnit 3110 (+9 LogSanitizer), MCP vitest 19 (+1 tag-strip),
Web vitest 49, all tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 01:38:47 +02:00
Oliver Kieselbach 3a4d80cd7f hardening(auth): validate + audit EntraId:AdditionalClientIds trust-set expansion
Expanding the token audience trust set via EntraId:AdditionalClientIds was
completely silent: no format validation, no operator-visible logging. During
the tenant-move window a typo'd GUID would be indistinguishable from "the new
app registration doesn't work" (daily-review follow-up, 2026-07-14).

- ResolveConfiguredClientIds: additional entries must parse as GUIDs; malformed
  entries are dropped (fail-closed - they could never match a token aud) and
  reported via out param. Accepted entries are normalized to the canonical
  lowercase dashed GUID form so brace/uppercase paste variants still match the
  ordinal audience comparison. Primary ClientId handling stays verbatim.
- AuditClientIdTrustSet: one Warning per distinct config value per instance for
  (a) dropped malformed entries (truncated - never log a full pasted value in
  case it is a secret) and (b) trust-set expansion with the accepted ID list.
  Warning level because nothing below Warning reaches App Insights.
- Tests: existing ResolveConfiguredClientIds tests moved to GUID values
  (signature change, no compat alias) + rejection, primary-verbatim,
  normalization and TruncateForLog coverage.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 14:01:43 +02:00
Oliver Kieselbach bffbf35875 feat(auth): config-driven audience set — trust a second app registration
Make JWT audience validation accept the primary EntraId:ClientId PLUS an
optional comma/semicolon/space-separated EntraId:AdditionalClientIds. Each
client ID expands to {id} and api://{id}; the set is trimmed, empties dropped,
and de-duplicated case-insensitively (fail-closed on empty input).

This is the seam that lets the API trust a second/rotated app registration
during a future Entra app-reg tenant move: adding a client ID to
EntraId__AdditionalClientIds is the only backend step needed. When the setting
is unset the accepted audiences are exactly the primary id — today's behaviour,
zero change for production.

BuildTokenValidationParameters now takes params string?[] clientIds (backward
compatible), with two pure, unit-tested helpers ResolveConfiguredClientIds and
BuildValidAudiences. +12 tests (multi-audience accept, primary still valid,
foreign audience rejected, parsing/dedupe/fail-closed). 64/64 auth tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-13 16:44:53 +02:00
Oliver Kieselbach 5aa68553d2 test: extract pure seams for MDM cert selection + JWT validation, then cover them
Two security-critical paths had zero unit coverage because the logic was inlined
behind infrastructure (a real X509Store / a live OIDC ConfigurationManager +
HttpContext). Extract the decision logic into pure, testable seams — no
behavioural change — and pin it.

CertificateHelper (Agent):
- Extract SelectMdmCertificate(IEnumerable<X509Certificate2>): the issuer
  discrimination (CN=Microsoft Intune MDM Device CA only, never the MMP-C CA),
  ClientAuth-EKU filter and NotAfter tiebreaker. FindMdmCertificate now calls it.
- 13 tests incl. the dual-stack regression (issuer filter beats the NotAfter
  tiebreaker so a longer-lived MMP-C cert can't win over a genuine MDM cert).

AuthenticationMiddleware (Backend):
- Extract BuildTokenValidationParameters(signingKeys, clientId), IsValidTenantId(tid)
  and BuildTenantAuthority(issuer, tid). Invoke() now composes them.
- 16 tests validating locally-minted tokens against a test key: alg:none and HS256
  rejected (algorithm-confusion defence), expired / wrong-audience / foreign-issuer
  / unknown-signing-key rejected, valid RS256 + api:// audience + v1 issuer accepted,
  plus the tid GUID gate and v1/v2 authority mapping.

Backend 2746/2746 and Agent 1615/1615 green; full solution builds clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 15:45:05 +02:00
Oliver Kieselbach dfa0fe27c1 fix(entitlements): address Codex review findings
- High: TenantConfigurationService.SaveConfigurationAsync now THROWS when the repository reports a failed persist (it swallows storage exceptions and returns false) - plan/trial/config writes can no longer be audited and returned as 200 without being persisted. Cache is invalidated on every attempted save (finally), covering in-place mutations of the cached instance; the now-redundant invalidate-on-failure wrapper in PlanManagementFunction is removed. AuthFunction login side-effect saves (first-login domain write, auto-re-enable) are wrapped best-effort so a storage blip cannot 500 auth/me - they self-gate and retry on next login.
- Medium: MCP usage increment moved from AuthenticationMiddleware (fire-and-forget BEFORE the quota decision) into McpQuotaEnforcementMiddleware: strictly check-then-increment and only for requests actually served (GA tracked but quota-exempt; denied 403/429 requests no longer inflate counters; the exact-limit request is now deterministic - 1..limit pass, limit+1 blocks).
- Low: fixed both new nullable warnings (PlanTierDefinitionParser guarded json, McpQuotaEnforcementMiddleware principal null-flow).

Tests: +3 save-semantics regression tests (throw on false, cache invalidation on failed/successful save). Backend 2656/2656 green, build clean.
2026-07-07 13:38:00 +02:00
Oliver Kieselbach 6e78291100 fix(backend): reject non-GUID tid before OIDC metadata fetch in auth middleware
Codex review #7 (MEDIUM): AuthenticationMiddleware read the unvalidated
`tid` claim and built a tenant-specific OIDC authority before signature
validation. A garbage tid would drive an outbound metadata fetch to a bogus
authority - a DoS/cost surface on malformed-token floods (not an auth bypass;
signature/audience/issuer are still validated afterward).

- Guard `tid` with Guid.TryParse before constructing the authority; missing/
  non-GUID throws SecurityTokenValidationException -> 401, no fetch. Loss-free:
  every legitimate Entra token (incl. consumer MSA 9188040d-...) has a GUID tid.
- Drop the now-unreachable null -> common/v2.0 fallback.
- Pass context.CancellationToken into GetConfigurationAsync (was None).

Negative cache for invalid/unreachable authorities deferred (LRU already
bounds memory; revisit only if floods observed).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 10:33:16 +02:00
Oliver Kieselbach 5cd268e88c fix(backend): derive AuthenticationMiddleware JWT-exempt set from policy catalog
The ticket-gated diagnostics/download route (PublicAnonymous, MCP session_debug)
401'd on the deployed backend: AuthenticationMiddleware kept its OWN hardcoded
_anonymousRoutes allowlist, parallel to EndpointAccessPolicyCatalog, and the new
route was added only to the catalog. Since AuthenticationMiddleware runs before
PolicyEnforcementMiddleware, the missing entry rejected the request with a JWT
401 before the PublicAnonymous policy was ever honored. Classic hand-synced
parallel-catalog drift.

Delete _anonymousRoutes / _anonymousPrefixes and derive the JWT-exempt decision
from the catalog: a route skips JWT iff its policy is PublicAnonymous or
DeviceOrBootstrapAuth (authenticated in-function via cert/bootstrap token, not
JWT). Now method-aware and fail-closed on unregistered routes. Behavior-
preserving: the old 14 routes + 1 prefix equal exactly the catalog's
PublicAnonymous u DeviceOrBootstrapAuth set.

Add drift guard in EndpointPolicyCatalogCompletenessTests:
AnonymousAndDeviceRoutes_AreJwtExemptInAuthMiddleware loops every such catalog
entry and asserts the middleware exempts it (would have caught this bug);
SkipsJwtValidation_MatchesPolicyTier locks the positive/negative tiers incl. the
diagnostics/download vs diagnostics/download-url contrast. Full suite 2393 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 23:40:18 +02:00
Oliver Kieselbach 781cf0fb9b updated allowlist for anonymous requests 2026-06-22 23:27:05 +02:00
Oliver Kieselbach e6792aee95 added entra upcoming valid algorithm 2026-05-20 20:09:10 +02:00
Oliver Kieselbach 2ecbefce73 backend route fix and v2 agent version check fix 2026-04-22 17:51:12 +02:00
Oliver Kieselbach fee6909ec6 feat(mcp): add tool-call telemetry for production observability
Track MCP tool invocations in App Insights and UserUsageLog:
- Add ClientSource + McpToolName custom dimensions to RequestTelemetry
- Propagate tool name via X-MCP-Tool-Name header from MCP server
- Wrap all 26 tool handlers with withToolTelemetry for context propagation
- Add MCP_TOOL_LOGGING env var (default false) for optional stderr logging
- Add toolLoggingEnabled param to Bicep template for persistence

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 10:30:41 +02:00
Oliver Kieselbach 734061031b better OIDC config cache scaling 2026-04-01 12:52:15 +02:00
Oliver Kieselbach d9c4ea2657 agent emergency channel established 2026-03-31 03:07:52 +02:00
Oliver Kieselbach 66cc6af20f added user requests rate limiter, mcp tools bugfix, optimized request pipeline, mcp usage data retention, mcp plantier management 2026-03-29 16:12:15 +02:00
Oliver Kieselbach e88749e794 tracking only for mcp 2026-03-29 14:57:13 +02:00
Oliver Kieselbach 762bcfde34 better debug logging 2026-03-29 14:33:52 +02:00
Oliver Kieselbach 9e278db162 added logging for debug 2026-03-29 14:24:18 +02:00
Oliver Kieselbach f6d685392a request telemetry, fixed usage logging bug 2026-03-29 14:06:43 +02:00
Oliver Kieselbach dbb8c20a45 fixed usage log, fixed mcp tools, fixed version comparer vul report 2026-03-29 13:28:00 +02:00
Oliver Kieselbach 49a14c0a00 added CORS middleware 2026-03-28 09:26:44 +01:00
Oliver Kieselbach cefdc5e8fb CORS fix 2026-03-28 09:16:27 +01:00
Oliver Kieselbach 219f5c686a oauth for mcp server 2026-03-28 06:15:12 +01:00
Oliver Kieselbach 0126ce3c93 Added Policy Catalog and Audit for verification (first phase) 2026-03-08 14:23:25 +01:00
Oliver Kieselbach a2de05fe33 refactor: reorganize metrics/stats API routes and fix session-reports 404 handling
- Rename app-metrics → metrics/app (tenant + galactic)
- Rename usage-metrics → metrics/usage (tenant)
- Rename platform/usage-metrics → galactic/metrics/usage
- Rename platform-stats → stats/platform (anon whitelist updated)
- SessionReportService: gracefully handle missing table (404) with empty list
- SessionReportsSection: treat 404 as no reports yet (suppress error)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 16:47:55 +01:00
Oliver Kieselbach 81c4806083 Hardening: re-architecture to use mTLS for complete agent communication (agent endpoints consolidated) 2026-02-26 23:02:50 +01:00
Oliver Kieselbach c1c19c4f7a fix diagnostics upload 401 and enrich upload event data
- Add /api/diagnostics/upload-url to anonymous routes in AuthenticationMiddleware so the
  new device-cert-authenticated endpoint is not blocked by the JWT middleware
- Add DiagnosticsUploadResult value object to DiagnosticsPackageService carrying BlobName,
  SasUrlPrefix (truncated, safe to log), and ErrorCode
- Change CreateAndUploadAsync return type to DiagnosticsUploadResult for richer error context
- Add BuildSasUrlPrefix helper to produce a safe truncated URL for event data
- Change UploadToBlobStorageAsync to return (bool success, string errorCode) tuple
- Update MonitoringService to populate sasUrl and errorCode in diagnostics_upload_failed
  event data dict for visible timeline diagnostics

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-24 22:18:21 +01:00
Oliver Kieselbach 1f1b2cf2b4 usage of EntraId ClientId harmonised 2026-02-16 18:18:42 +01:00
Oliver Kieselbach a7e12b3588 Middleware security fix 2026-02-07 21:56:13 +01:00
Oliver Kieselbach 89fb50368e ConfigManagerCache fix 2026-02-07 21:41:25 +01:00
Oliver Kieselbach 064319334d Signing fix 2026-02-05 22:02:12 +01:00
Oliver Kieselbach 557dd22c53 Authentication & Galactic Admin: Implement JWT-based multi-tenant access control with cross-tenant support
Backend Changes:
- Fix user identification to use UPN (User Principal Name) claim as primary identifier instead of display name
- Add JWT authentication validation to all API endpoints with Authorization header support
- Implement Galactic Admin role with cross-tenant access permissions for sessions, events, and SignalR groups
- Add cross-tenant validation in GetSessionEventsFunction, SignalRAddToGroupFunction, and SignalRRemoveFromGroupFunction
- Enhance AuthenticationMiddleware to log actual user identifier (UPN) instead of display name

Admin Configuration:
- Add GetAdminConfigurationFunction and UpdateAdminConfigurationFunction for global settings
- Create AdminConfigurationService for managing platform-wide configuration
- Add AdminConfiguration model with global rate limiting and maintenance settings
- Restrict admin configuration access to Galactic Admins only

SignalR Real-time Updates:
- Implement "galactic-admins" SignalR group for cross-tenant session visibility
- RegisterSessionFunction now sends "newSession" events to both tenant-specific and galactic-admins groups
- IngestEventsFunction sends "newevents" only to tenant-specific groups (prevents flooding)
- Frontend listens to both "newSession" and "newevents" for real-time updates
- Galactic Admins see new sessions from all tenants without being flooded with event updates

Frontend Changes:
- Add Authorization headers with JWT tokens to all API fetch calls (sessions, events, metrics, configuration)
- Implement automatic joining/leaving of "galactic-admins" SignalR group based on Galactic Admin mode
- Handle both "newSession" and "newevents" SignalR events for complete session list updates
- Add authentication error handling with user notifications for token failures

Security Improvements:
- Validate tenant access for all cross-tenant operations
- Ensure users can only access their own tenant data unless they're Galactic Admins
- Log all cross-tenant access attempts with user identifiers for audit trail
2026-02-05 20:49:36 +01:00
Oliver Kieselbach a20ff48ae6 Backend:
- Add JWT-based authentication to all API endpoints
- Implement tenant isolation and access control validation
- Add Galactic Admin role validation for cross-tenant endpoints
- Enhance certificate validation with full X.509 chain checking
- Add certificate validation cache (5-min TTL) and self-signed cert protection
- Implement NDJSON payload size limit protection (configurable per tenant)
- Replace placeholder audit user identifiers with actual JWT user principals
- Add TenantHelper utility for consistent tenant/user extraction from tokens
- Disable PII logging in production (ShowPII = false)

Agent:
- Add automatic tenant ID detection from Windows Registry (AAD Join enrollment)
- Implement tenant ID precedence: CLI argument > Registry > Fallback

SignalR:
- Add authentication checks to all SignalR functions
- Implement tenant-based group access control
- Add user identifier logging for SignalR operations

Frontend:
- Change MSAL cache from localStorage to sessionStorage (XSS protection)
- Add warning status support to health check page
- Add Admin Configuration link in navbar (Galactic Admin only)
- Move maintenance trigger from Settings to Admin Configuration page
- Update tenant context logging for clarity

Configuration:
- Add MaxNdjsonPayloadSizeMB setting to TenantConfiguration model
- Update configuration service to persist new retention/timeout settings
2026-02-05 16:38:16 +01:00
Oliver Kieselbach 5690620058 Initial commit 2026-02-05 06:14:41 +01:00