Commit Graph
173 Commits
Author SHA1 Message Date
Arnaud Dartois ed686718d3 fix: remove UseStatusCodePagesWithReExecute — was turning 401 into 400
UseStatusCodePagesWithReExecute('/not-found') intercepts all 4xx
responses and re-executes the pipeline as POST /not-found.
Since /not-found is a Blazor component requiring antiforgery, the
re-executed POST would fail with 400 (no CSRF token).

API controllers now return proper 401/403 for unauthenticated
requests. All 61 integration tests pass.
2026-07-21 07:38:38 +00:00
Arnaud Dartois f7c5f7a80a fix: move UseAntiforgery after UseAuthorization
UseAntiforgery() was before UseAuthentication(), causing all POST
requests to API controllers to get 400 (missing CSRF token) before
auth could return 401. Moving it after authorization ensures:

1. Auth middleware runs first → unauthenticated requests get 401
2. Antiforgery middleware validates tokens only for requests
   that pass auth (Blazor components)
3. API controllers and SignalR hubs work without CSRF tokens
2026-07-21 07:30:14 +00:00
Arnaud Dartois 81b8e6aacf refactor: replace isTesting hacks with appsettings.Testing.json
The entire 'if (isTesting)' pattern is removed. Instead:
- Add appsettings.Testing.json: Database:Provider=InMemory,
  DataProtection:Mode=Ephemeral, Hangfire:Enabled=false,
  Database:MigrateOnStartup=false
- DependencyInjection reads configuration keys instead of
  environment name
- Program.cs uses Hangfire:Enabled and Database:MigrateOnStartup
  config booleans instead of IsEnvironment("Testing") checks
- Test fixture persists (UseEnvironment + UseSetting for
  unique InMemoryDbName per instance)

No functional change — still 54/61 integration tests passing.
The 7 remaining failures are pre-existing 'expected 401 got 400'
auth middleware differences.
2026-07-21 07:23:33 +00:00
Arnaud Dartois 501da8dd0d fix: seed Identity roles in all environments (including Testing)
Roles (Admin, Viewer, etc.) must exist before any user registration
attempts to add a user to a role. The seeding was only in the old
Heimdall.Api/Program.cs — moved to Web/Program.cs and runs in ALL
environments (not skipped in Testing).

Now 54/61 integration tests pass (was 6/61). Remaining 7 failures
are all 'expected 401 got 400' — pre-existing auth middleware
difference.
2026-07-21 06:29:51 +00:00
Arnaud Dartois 1d70455abb fix(web): make integration tests work with Heimdall.Web as entry point
- Add InternalsVisibleTo for Heimdall.Api.Tests and
  Heimdall.IntegrationTests in Web.csproj
- Add partial class Program for WebApplicationFactory<Program>
- Pass builder.Environment.EnvironmentName instead of env var
  so AddInfrastructure correctly detects Testing environment
- Skip DATABASE_URL check, Hangfire setup, migrations, and
  recurring jobs when environment is Testing
- Update test project references from Heimdall.Api to Heimdall.Web
2026-07-20 20:32:32 +00:00
Arnaud Dartois d9a3ea52ba refactor: remove Heimdall.Api, move all routes into Heimdall.Web
Heimdall.Api controllers/hubs/filters were exact duplicates of
files already in Heimdall.Web (same namespace, same content).
The Api project was a leftover from before the single-image merge.

Changes:
- Add missing registrations to Web/Program.cs (JWT Bearer auth,
  rate limiting, controllers with ExceptionFilter, FluentValidation,
  SignalR + broadcast services, OpenAPI/Scalar, CORS, hub mappings)
- Add FluentValidation.AspNetCore, Scalar.AspNetCore,
  Microsoft.AspNetCore.OpenApi NuGet packages to Web.csproj
- Remove Heimdall.Api from solution and delete the project
- All routes continue working at their existing paths
2026-07-20 20:22:30 +00:00
Arnaud Dartois 81da09c110 feat(auth): add structured logging throughout auth module
Add ILogger<AuthService> with log events at every step:
register, login, 2FA, refresh token, password change,
logout, admin registration. All error paths now log
the exact failure reason (validation, Identity errors,
public registration disabled, etc.).

Previously all errors were silently swallowed by the
HeimdallApiClient returning null on non-success responses.
2026-07-20 20:16:58 +00:00
Arnaud Dartois 8ac088de38 fix(web): use port 8080 as default API_BASE_URL for Docker compat
The HeimdallApiClient calls the API via HTTP on localhost.
Inside Docker, the app listens on port 8080 (ASPNETCORE_URLS),
but the default was 5000 (host-mapped port) — causing connection
refused on all API calls from Blazor Server UI.

Fix: change default from localhost:5000 to localhost:8080.
2026-07-20 20:09:24 +00:00
Arnaud Dartois 34037c20bf fix(dp): keep X509Certificate2 alive for DataProtection key ring
- Remove `using var` from dpCert so the cert stays alive for
  ProtectKeysWithCertificate (was disposed, causing
  CryptographicException)
- Add query filter on DiscoveredStreamUrl for model warning #10622
- Simplify migration retry: call Migrate() directly instead of
  GetPendingMigrations()+Migrate() to reduce transient startup noise
2026-07-20 19:58:32 +00:00
Arnaud Dartois 947414cc3f chore: update opencode submodule to 62cd0e6 — add token-cost reduction stack (terse-output, codebase-graph, RTK, ccusage, pxpipe) 2026-07-20 18:23:37 +00:00
Arnaud Dartois 8085df1aa0 fix(ci): update Dockerfile path after worker merge
Dockerfile.central was renamed to Dockerfile. Also update image name
from heimdall/web to heimdall to match the new single-image naming.
2026-07-20 18:15:53 +00:00
Arnaud Dartois 630e7987fe refactor(docker): merge worker and web into single heimdall image
Combine Heimdall.Web and Heimdall.Workers into one process/image.
Hangfire background jobs now run inside the web process.

- Move job classes to Infrastructure/Jobs/ (no Worker SDK dependency)
- Add Hangfire server + recurring jobs to Web/Program.cs
- Add missing AddInfrastructure/AddApplication DI registrations to Web
- Rename image: heimdall (was heimdall-web / heimdall-workers)
- Remove src/Heimdall.Workers project entirely
- Remove tests/Heimdall.Workers.Tests (placeholder)
- Simplify Dockerfile: single build target, no workers publish
- Update docker-compose files: one service heimdall, no workers
- Update Makefile, .env.example
2026-07-20 17:22:56 +00:00
Arnaud Dartois 252724a2fd fix(web): handle login cookie creation failure
- Remove redundant antiforgery check from /_auth/signin and
  /_auth/signout
  (JWT validation is sufficient security; antiforgery tokens
  fail silently because the JS caller never includes one)
- Add ILogger structured logging to both endpoints
- Make AuthHelper.SignInAsync return bool so Blazor pages
  can detect failure
- Show user-friendly error messages in Login.razor and
  Register.razor when cookie creation fails
2026-07-20 17:12:16 +00:00
Arnaud Dartois c8c93e3d87 fix(dp): guard data protection certificate bootstrap with isTesting check
The self-signed certificate auto-bootstrap for DataProtection key
encryption ran unconditionally, causing integration tests to crash
with CryptographicException (m_safeCertContext is an invalid handle)
when Identity token providers tried to use the certificate encryptor.

The test environment has no /var/lib/heimdall/dp-keys/ directory, and
loading a PFX with empty password is fragile on Linux — the X509
certificate handle becomes invalid.

Wrap the certificate + file persistence code in the same if (isTesting)
guard already used for the DbContext setup. Tests now use ephemeral
DataProtection keys without certificate encryption.
2026-07-20 15:44:20 +00:00
Arnaud Dartois 8278c75cf4 fix(dp): auto-bootstrap self-signed certificate for data protection key encryption
Generates a self-signed X.509 certificate on first run and stores it
alongside DP keys in the persistent volume. Uses ProtectKeysWithCertificate
to encrypt data protection keys at rest. Prevents the 'No XML encryptor
configured' startup warning.
2026-07-20 14:07:27 +00:00
Arnaud Dartois 51589dd988 fix(docker): add persistent volume for data protection keys
Mounts heimdall_data volume at /var/lib/heimdall for heimdall-web
and heimdall-workers services. Prevents loss of DP keys on container
destroy, which would permanently break credential decryption.
2026-07-20 14:04:42 +00:00
Arnaud Dartois aa996d764c fix(docker): add krb5 package for Npgsql GSSAPI support
Prevents 'Cannot load library libgssapi_krb5.so.2' error on startup.
Npgsql attempts to load GSSAPI for PostgreSQL authentication; krb5
provides the required shared library on Alpine.
2026-07-20 14:03:59 +00:00
Arnaud Dartois e74995f088 fix(db): add value comparer for KnownFace.Embedding float array
Adds ValueComparer<float[]> with element-by-element comparison and
snapshot copy. Prevents EF Core warning 10620 about collection types
with value converters but no value comparer.
2026-07-20 14:03:40 +00:00
Arnaud Dartois 262d13ee0c fix(db): add matching query filters for required navigations to soft-deletable entities
Adds HasQueryFilter for CameraAssignment (→Agent), CameraDiscoveryResult
(→Site), and CameraEvent (→Camera) to match existing pattern.
Prevents EF Core warning 10622 about required ends with global query
filters.
2026-07-20 14:02:07 +00:00
Arnaud Dartois 886b9f470b fix(validation): restore tzdata detection in timezone validator
The TimeZoneNotFoundException catch was unconditionally accepting all
values, which made timezone validation a no-op on systems WITH tzdata.
Restore the lazy _hasTzData detection: when tzdata is available, reject
invalid IANA timezone ids; when tzdata is missing, accept all values.

Fixes InvalidTimezone_FailsValidation test.
2026-07-20 10:39:27 +00:00
Arnaud Dartois 562aabdfc8 feat(api+web): merge REST API and Blazor UI into single process
Previously the API (heimdall-central) and Blazor UI (heimdall-web) ran as
separate containers with the Blazor Server making internal HTTP calls to
the API. This caused the Blazor circuit to disconnect when the API was
unreachable (network error → "Une erreur réseau est survenue").

Now both serve from the same .NET process on the same port:
- All 16 API controllers, ExceptionFilter, and SignalR hubs integrated
  into Heimdall.Web
- JWT auth, CORS, rate limiting configured in the unified Program.cs
- Dockerfile.central entrypoint runs web/Heimdall.Web.dll
- docker-compose simplified: heimdall-central service removed
- CI publishes heimdall-web image instead of heimdall-central

Also fixes timezone validation on Alpine/tzdata-less environments
and enables FluentValidation auto-validation in the API project.
2026-07-20 10:30:01 +00:00
Arnaud Dartois 892ca88de8 fix(efcore): adopt SaveChangesWithRetryAsync across all infrastructure services 2026-07-20 10:15:39 +00:00
Arnaud Dartois 8dedee5d86 perf(infra): replace .Result with await after Task.WhenAll in camera discovery 2026-07-20 10:13:51 +00:00
Arnaud Dartois b56653ec78 fix(workers): use UtcNow instead of Now in worker log 2026-07-20 10:12:54 +00:00
Arnaud Dartois f1c7c0a1ea fix(workers): replace Thread.Sleep with await Task.Delay in migration retry 2026-07-20 10:12:16 +00:00
Arnaud Dartois b5ff5c6a99 fix(ui): add missing @key directives to all @foreach loops 2026-07-20 10:03:12 +00:00
Arnaud Dartois edc04c836e chore: update opencode submodule to e23bc97
3 improvement fixes: unquoted loops, stale step ref, test detection
2026-07-20 09:57:18 +00:00
Arnaud Dartois 832388c4b3 chore: update opencode submodule to 9620d19
4 anomaly fixes: §3 agent table, benchmark doc + JSON fix,
French→English comments, Forgejo-only prepare-commit-msg
2026-07-20 09:54:33 +00:00
Arnaud Dartois a33a436c26 chore: apply auto-fixes and code improvements
- AuthService: fix public registration logic revert
- JwtService: add ILogger dependency
- SoftDeleteInterceptor removed (merged)
- XML doc comments on all services
- Error boundary + error page in Blazor
- Optimize StatsService queries
- ApiClient error handling improvements
2026-07-20 09:50:43 +00:00
Arnaud Dartois 9917d49601 chore: update opencode submodule to 113b0bc
7 anomaly fixes: step numbering, stale counts, duplicate sections,
B-section cross-ref, chmod +x, dead code, skill placeholder
2026-07-20 09:48:54 +00:00
Arnaud Dartois 756c7a8a2d chore: update opencode submodule to 27e2966
8 critical bug fixes: BusyBox grep -P compat, eval removal,
model: template removal, JSON injection, hardcoded namespace,
broken file paths, unquoted word splitting
2026-07-20 09:33:45 +00:00
Arnaud Dartois ba968a5f23 fix(security): harden Docker, CSRF, EventsHub scoping, secret logging, tests
- Docker: remove default passwords from prod compose (required env vars)
- CSRF: validate antiforgery tokens on /_auth/signin and /_auth/signout
- EventsHub: broadcast to site-scoped Group() instead of Clients.All
- SettingsController: redact secret values in logs
- Create SetAgentSettingValidator + UpdateAppSettingValidator classes
- Replace 3 placeholder test projects with meaningful tests
- Remove FluentValidation auto-validation (incompatible with .NET 10)
2026-07-19 20:53:48 +00:00
Arnaud Dartois 153be535d4 fix(multiple): auth, workers, EF Core, MudTheme fixes
- Auth: AssignmentsController auth bug, ReleaseCamera result, logout endpoint
- Security: open redirect fix
- Workers: AgentState thread-safety, CameraStreamService async, HttpClientFactory
- EF Core: AddCameraDiscoveryFields migration, DI interceptors, retry helper
- UI: MudTheme palette config, aria-labels on icon buttons
2026-07-19 19:58:45 +00:00
Arnaud Dartois 4b83e35df0 fix(infra): persist Data Protection keys for Docker resilience
- Add PersistKeysToFileSystem with SetApplicationName so camera
  credential decryption survives container restarts
- Move connection string resolution inside else block to fix
  integration tests (was evaluating connection string eagerly
  before Testing environment check)
- Remove hardcoded connection string fallback, throw instead
- Add Microsoft.AspNetCore.DataProtection.Extensions dependency
2026-07-19 19:34:58 +00:00
Arnaud Dartois 32025eae67 fix(infra): persist Data Protection keys to filesystem for Docker
- Add PersistKeysToFileSystem to /var/lib/heimdall/dp-keys so camera
  credential decryption survives container restarts
- Remove hardcoded connection string fallback, throw instead
- Add Microsoft.AspNetCore.DataProtection.Extensions dependency
2026-07-19 19:33:10 +00:00
Arnaud Dartois 3f75a20860 fix(infra): copy web wwwroot to /app/wwwroot in Dockerfile
Static files are served from /app/wwwroot but the web publish
output is at /app/web/. Copying wwwroot to the expected location
so StaticFileMiddleware can find CSS, JS, and other static assets.
2026-07-19 19:14:47 +00:00
Arnaud Dartois 41d9ae2bc0 fix(infra): add working_dir /app/web to heimdall-web service
Content root was /app/ but published files are at /app/web/,
causing StaticFileMiddleware to look for wwwroot at /app/wwwroot/
which doesn't exist. Add working_dir to set correct content root.
2026-07-19 19:13:10 +00:00
Arnaud Dartois d2288617f7 fix(web): replace MapStaticAssets with UseStaticFiles 2026-07-19 18:37:52 +00:00
Arnaud Dartois a6f37b8e9d fix(auth): add permission claims to ApiKeyAuthenticationHandler
API keys used by camera agents were missing 'permission' claims,
causing all endpoints with ApiKey + Policy to return 403 Forbidden
(e.g. POST /api/events, POST /api/events/{id}/snapshot).

Add CameraWrite, CameraRead, CameraLive, SiteRead, EventRead
permissions — matching agent operational needs (Supervisor minus
Person permissions).
2026-07-19 16:46:32 +00:00
Arnaud Dartois a50a567f8c feat(auth): improve authentication security rules
- First registered user is auto-assigned Admin role (empty DB)
- Add auth.public-registration.enabled setting to disable public
  registration (only admins can create users via POST /api/users)
- Add DELETE /api/users/{id} endpoint (Admin only) with guards:
  - Cannot delete own account
  - Cannot delete the last administrator
- Guard AssignRolesAsync to prevent removing Admin from last admin
- Add AuthSettings constants class for well-known setting keys
2026-07-19 16:39:35 +00:00
Arnaud Dartois 554fd7ffc3 chore(docker): fix compose files and update README documentation
- Fix docker-compose.prod.yml: agent image ref
  (heimdall-central→heimdall-agent) and env var naming
  (HEIMDALL_* → Agent__*)
- Add missing SENTRY_DSN env vars to central, workers,
  web, and agent services
- Add agent_state volume for agent identity persistence
- Update README with accurate test counts (34→225),
  env var reference table, troubleshooting guide,
  and proper docker documentation
- Update docker-compose.yml header and add
  Agent__StateDirectory/Agent__RegistrationMaxRetries
2026-07-19 16:07:32 +00:00
Arnaud Dartois 363b43f779 fix: prevent orphaned TaskCompletionSource in frame queue
Changed BoundedChannelFullMode from DropOldest to DropWrite.
With DropOldest, the oldest queued job is silently removed when the
channel is full, but its TaskCompletionSource is never completed —
causing the caller to hang indefinitely.

DropWrite rejects new writes when full, returning TryWrite=false,
which triggers the existing graceful fallback (tcs.TrySetResult(null)).
2026-07-19 15:54:46 +00:00
Arnaud Dartois d9f5224e21 fix: resolve review findings — SignalR JWT, enum serialization, TCS leak, thread safety 2026-07-19 15:54:13 +00:00
Arnaud Dartois 926d866749 fix(security): validate returnUrl against open redirect
The returnUrl query parameter is now validated as a local/relative URL
(starts with '/' and does not contain '://') before being used as a
redirect target after login.
2026-07-19 15:54:07 +00:00
Arnaud Dartois 54496cd947 refactor: extract duplicate JS interop signIn to AuthHelper
Both Login and Register pages had identical JsRuntime.InvokeVoidAsync calls
with the same anonymous object shape. Extracted to a shared AuthHelper
static class with SignInAsync(IJSRuntime, object) and CreateSignInPayload(UserInfo).

- New file: Services/AuthHelper.cs
- Login.razor and Register.razor now call AuthHelper.SignInAsync
- Pre-existing fix: Person.cs IAuditableEntity setters made public
2026-07-19 15:53:38 +00:00
Arnaud Dartois b955a98760 refactor(css): use CSS custom properties for auth page theme
Define --auth-* variables on .auth-page for all colors, shadows, and
backgrounds. Dark mode now only overrides variables on .auth-page —
zero selector duplication, single source of truth for theme values.
2026-07-19 15:51:07 +00:00
Arnaud Dartois 0030173c38 refactor: rename mud-button-submit to auth-submit-btn
Avoid potential CSS conflicts with future MudBlazor versions using a
project-specific class name for auth page submit buttons.
2026-07-19 15:50:32 +00:00
Arnaud Dartois b62e48bef7 chore: add justification comment for NU1510 suppression
NU1510 fires because System.Threading.Channels is a transitive dependency
of Microsoft.AspNetCore.SignalR.Client but is already part of the
.NET 10 framework. Safe to suppress.
2026-07-19 15:50:10 +00:00
Arnaud Dartois 70176124cb refactor(css): merge duplicate dark mode media blocks into one
- Single @media (prefers-color-scheme: dark) block containing both
  auth-specific rules and general (body, blazor-error-ui) rules
- Removes duplicate @media query, simplifies maintenance
2026-07-19 15:49:46 +00:00
Arnaud Dartois f0083de97d fix(a11y): add prefers-reduced-motion support for auth page
- Disable auth-card entrance animation when user prefers reduced motion
- Disable auth-footer link color transition
- Respects WCAG accessibility guidelines for vestibular disorders
2026-07-19 15:49:13 +00:00