Compare commits
449
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ba35f6d12 | ||
|
|
a8ce828c01 | ||
|
|
c5a250586b | ||
|
|
c8a428555a | ||
|
|
ec80e31e33 | ||
|
|
511fbfce7b | ||
|
|
78ff15799e | ||
|
|
aef04552a8 | ||
|
|
7c0c8ecf46 | ||
|
|
dc8a313deb | ||
|
|
9fd9c75f94 | ||
|
|
fcc719d627 | ||
|
|
bc7ddccfe3 | ||
|
|
6e7f593cb3 | ||
|
|
622abb4454 | ||
|
|
9162e374f0 | ||
|
|
02783dd718 | ||
|
|
24a2400610 | ||
|
|
374b7f267f | ||
|
|
ace7746695 | ||
|
|
5b1255ad80 | ||
|
|
1d60f04691 | ||
|
|
e042b832d8 | ||
|
|
adf8d73476 | ||
|
|
b3d5ea5add | ||
|
|
2d28771945 | ||
|
|
4c790e0489 | ||
|
|
43e6752a31 | ||
|
|
38647d3623 | ||
|
|
5bcd4968a8 | ||
|
|
86d77dc462 | ||
|
|
188a9ad2d4 | ||
|
|
cae09e3698 | ||
|
|
1b512ab040 | ||
|
|
7869800ea5 | ||
|
|
62261f914e | ||
|
|
4498e39d34 | ||
|
|
938adbf3a8 | ||
|
|
af67a1757a | ||
|
|
d12e16c6e5 | ||
|
|
dc0b01a7aa | ||
|
|
636154572b | ||
|
|
6e61d38ca8 | ||
|
|
c6da6195c9 | ||
|
|
c200f27461 | ||
|
|
89c4c43922 | ||
|
|
ea5f0b7589 | ||
|
|
8a70d2ee1f | ||
|
|
546115e2ea | ||
|
|
8195ee4ab8 | ||
|
|
416b171117 | ||
|
|
6d9eefa3bb | ||
|
|
0f897b25ab | ||
|
|
189d80253b | ||
|
|
ea30cbf02f | ||
|
|
342626ac90 | ||
|
|
4d875143d1 | ||
|
|
d0de2ac308 | ||
|
|
1b3f9e0032 | ||
|
|
affcda5912 | ||
|
|
3f46bde5f1 | ||
|
|
68db815e38 | ||
|
|
098c562113 | ||
|
|
79ee36360b | ||
|
|
64df46b145 | ||
|
|
a10d3d5fb1 | ||
|
|
5db3d627f7 | ||
|
|
e7c2c3adff | ||
|
|
d129bf2350 | ||
|
|
afde95fe03 | ||
|
|
9c80c1e245 | ||
|
|
9785cbd3c3 | ||
|
|
f94cfb028d | ||
|
|
b568956772 | ||
|
|
5fc85d4655 | ||
|
|
237d5a789a | ||
|
|
07c44b5c1c | ||
|
|
8aa02c5630 | ||
|
|
5a7b7c1931 | ||
|
|
9d01ca33c0 | ||
|
|
1f878f5049 | ||
|
|
428a730938 | ||
|
|
e1b900c915 | ||
|
|
39d15ac62e | ||
|
|
edf750e36d | ||
|
|
79ad576186 | ||
|
|
5588d655ea | ||
|
|
3e10c550c5 | ||
|
|
126e7665fe | ||
|
|
60c3ddc9a6 | ||
|
|
264ce157cf | ||
|
|
8d35518d1a | ||
|
|
13b6ee7979 | ||
|
|
70cef93289 | ||
|
|
124cf1c740 | ||
|
|
0386d06d8d | ||
|
|
d1f3f1a746 | ||
|
|
cedeba08d3 | ||
|
|
adabd5952a | ||
|
|
9b9ac28697 | ||
|
|
9e0eeb8558 | ||
|
|
f832d2fb62 | ||
|
|
7c4cff90d8 | ||
|
|
e034d81a34 | ||
|
|
84ddf83da4 | ||
|
|
7f7c1d50a9 | ||
|
|
d774d28f2a | ||
|
|
68e540133c | ||
|
|
8f25952c04 | ||
|
|
026222ed2c | ||
|
|
25dc4869d2 | ||
|
|
bd97bbf6d2 | ||
|
|
7d99a4029a | ||
|
|
e09cb4003d | ||
|
|
1b7aab7964 | ||
|
|
0fcb7ec3d6 | ||
|
|
92b473de8a | ||
|
|
8fa43ac1b6 | ||
|
|
1371eefb70 | ||
|
|
fb74c58a88 | ||
|
|
0f5956634f | ||
|
|
1d5f995af4 | ||
|
|
435f8c4a05 | ||
|
|
6b2a37823b | ||
|
|
561b18f072 | ||
|
|
cfb8f3832d | ||
|
|
a9f26ddebb | ||
|
|
7f481b383b | ||
|
|
ff7e896a69 | ||
|
|
783b03cef4 | ||
|
|
8de2b69d1e | ||
|
|
f4c62a6b8c | ||
|
|
864bf026f9 | ||
|
|
5a8dfedaa8 | ||
|
|
76ee6a91ea | ||
|
|
db3496e57d | ||
|
|
0d3907640f | ||
|
|
53084ce4db | ||
|
|
6530304887 | ||
|
|
14afaee0d1 | ||
|
|
7b6f887b2e | ||
|
|
5f6df6146c | ||
|
|
71fff7c84c | ||
|
|
724dd3760d | ||
|
|
db406e8be5 | ||
|
|
1e63eac471 | ||
|
|
0c1eea244a | ||
|
|
59bce4755a | ||
|
|
fe7774f28a | ||
|
|
fa86185b00 | ||
|
|
1143b0dfa4 | ||
|
|
fea873ee97 | ||
|
|
3b64021d90 | ||
|
|
f0c8a08a6c | ||
|
|
81d8edcb10 | ||
|
|
c400f77289 | ||
|
|
3ebead5445 | ||
|
|
3c4fa9e91b | ||
|
|
c384c1ea3f | ||
|
|
4661837110 | ||
|
|
7e1e018557 | ||
|
|
16f5f4fa5a | ||
|
|
1a98594d27 | ||
|
|
7b9c7bcc97 | ||
|
|
ecfd94f7ca | ||
|
|
66e51c5381 | ||
|
|
6ce6e2e9ae | ||
|
|
6ba31db8fe | ||
|
|
b387980b03 | ||
|
|
f4dba338cb | ||
|
|
135ebe75d1 | ||
|
|
b759db78a6 | ||
|
|
db49a07440 | ||
|
|
e8652b6797 | ||
|
|
56bfa19390 | ||
|
|
55d779e839 | ||
|
|
a3dbc8cf47 | ||
|
|
849e1d3807 | ||
|
|
23571da9c3 | ||
|
|
a76a6d2a17 | ||
|
|
2e45c37925 | ||
|
|
4ac8c705a5 | ||
|
|
93a6f1fa03 | ||
|
|
3c28b0e27c | ||
|
|
0adc204f65 | ||
|
|
c321c057da | ||
|
|
96af711eac | ||
|
|
199a9c24d9 | ||
|
|
9b3fb86f80 | ||
|
|
c78614f790 | ||
|
|
81722ac815 | ||
|
|
6d3e20fe6f | ||
|
|
e9872c56f1 | ||
|
|
e46f45180a | ||
|
|
a1459994bb | ||
|
|
fddea09928 | ||
|
|
e9c61e6431 | ||
|
|
e91706e05b | ||
|
|
d890e0c0d5 | ||
|
|
9de10f3c53 | ||
|
|
e21a1eba8f | ||
|
|
f310fe0ebf | ||
|
|
b41d8d3910 | ||
|
|
a816222d93 | ||
|
|
d3aa74496b | ||
|
|
d24322704f | ||
|
|
3d871b72ac | ||
|
|
4731471015 | ||
|
|
2cf53300d5 | ||
|
|
2bf60263b3 | ||
|
|
6abde35475 | ||
|
|
d543eced8d | ||
|
|
aea3b46f68 | ||
|
|
8d5447f826 | ||
|
|
83ee648c2d | ||
|
|
e86c0e159a | ||
|
|
97d35858d9 | ||
|
|
5edaba16ca | ||
|
|
3218ef8941 | ||
|
|
c8c84f0e2c | ||
|
|
9cf995383f | ||
|
|
69fdf757cb | ||
|
|
2cb530c54f | ||
|
|
89146e2c39 | ||
|
|
7b3e1489b6 | ||
|
|
998040b827 | ||
|
|
72e63c5699 | ||
|
|
293f3a817d | ||
|
|
a2f75a00a7 | ||
|
|
8d116bd3cc | ||
|
|
010e2139c8 | ||
|
|
4f35e907b7 | ||
|
|
b9f7ba6fda | ||
|
|
d24a288684 | ||
|
|
7c15cea8cd | ||
|
|
117f01142d | ||
|
|
d59b546b09 | ||
|
|
59f0782094 | ||
|
|
f93b245911 | ||
|
|
71e869a011 | ||
|
|
f3b181b9de | ||
|
|
59ba41fe41 | ||
|
|
0cbcae5502 | ||
|
|
045b27b651 | ||
|
|
c009dbeeb4 | ||
|
|
2d2e5bc211 | ||
|
|
cc6cbeccf5 | ||
|
|
cd1d95faa4 | ||
|
|
eb49f8e925 | ||
|
|
873a6e6e7d | ||
|
|
454b05c31f | ||
|
|
5f0f970f65 | ||
|
|
66c873b4f7 | ||
|
|
d4cbae324a | ||
|
|
18a814f7c1 | ||
|
|
e4dc00cab3 | ||
|
|
397b970949 | ||
|
|
7e9a2e4137 | ||
|
|
da97044586 | ||
|
|
18cacd8980 | ||
|
|
bbc481678c | ||
|
|
6ec40cdf84 | ||
|
|
1c5ae82f6c | ||
|
|
7dd4ba2c23 | ||
|
|
4e9a826edf | ||
|
|
63197dba97 | ||
|
|
636d990cc7 | ||
|
|
0dc1763e7e | ||
|
|
08ffe25da7 | ||
|
|
612b11b4ae | ||
|
|
7d5f8260b0 | ||
|
|
e1cb8fae86 | ||
|
|
9bdf0f67a8 | ||
|
|
5cf508950f | ||
|
|
7fa35e7fad | ||
|
|
0fd2c37ef6 | ||
|
|
3d0264bc27 | ||
|
|
978f578801 | ||
|
|
9f4f7925f1 | ||
|
|
2bd01a219f | ||
|
|
6fc8efc438 | ||
|
|
6af7fceb03 | ||
|
|
e2b2f5f312 | ||
|
|
9663b4f00b | ||
|
|
78c3b2bdbe | ||
|
|
8e67b177e3 | ||
|
|
a731107c5d | ||
|
|
24ba6b8a73 | ||
|
|
196370656b | ||
|
|
a1d6160320 | ||
|
|
0f8cb4be46 | ||
|
|
1144b7fb83 | ||
|
|
1e5c7ae7ff | ||
|
|
6503a17545 | ||
|
|
e6afed76b1 | ||
|
|
0cc950967e | ||
|
|
21084bf00e | ||
|
|
d93eaca043 | ||
|
|
07b29b1e8e | ||
|
|
8f00f69a5f | ||
|
|
f4a8f4a668 | ||
|
|
b793bae739 | ||
|
|
9e27e89af5 | ||
|
|
3d9ec99291 | ||
|
|
8c09d210c9 | ||
|
|
64aa425f54 | ||
|
|
6ee7b93421 | ||
|
|
88da58723f | ||
|
|
e3e80f82ac | ||
|
|
964fc80fe3 | ||
|
|
0d7c8777b2 | ||
|
|
dc3742da77 | ||
|
|
564eb58925 | ||
|
|
8a0c4c7f33 | ||
|
|
890cac91f9 | ||
|
|
52243f2218 | ||
|
|
d24a20b497 | ||
|
|
2a67061700 | ||
|
|
7278f3280e | ||
|
|
2b41ab4ea3 | ||
|
|
d572ad575b | ||
|
|
0655feab30 | ||
|
|
afb58c51c7 | ||
|
|
ac70685616 | ||
|
|
91c5efed5f | ||
|
|
d78da50c93 | ||
|
|
573e6c37cc | ||
|
|
8fafbdfaec | ||
|
|
21842bdf09 | ||
|
|
183e1b37f7 | ||
|
|
53c9a3e90b | ||
|
|
3c4b8c95f5 | ||
|
|
49de4fb4e1 | ||
|
|
e757c2f846 | ||
|
|
1129cc9157 | ||
|
|
de829ed80b | ||
|
|
be45515fa5 | ||
|
|
ab970d07f2 | ||
|
|
18813106a5 | ||
|
|
79988a9033 | ||
|
|
7262c6dc55 | ||
|
|
633397821b | ||
|
|
efde3f23b5 | ||
|
|
0a87760db5 | ||
|
|
86963af538 | ||
|
|
3d07ea4b37 | ||
|
|
e74d48812b | ||
|
|
1f7b895646 | ||
|
|
8ebb231c17 | ||
|
|
e82dbf9a0a | ||
|
|
8ebcdb81a6 | ||
|
|
75a09aaf9a | ||
|
|
1fbbeb3b7e | ||
|
|
48f0b46d99 | ||
|
|
56a617744a | ||
|
|
249c4ef0de | ||
|
|
f22c7f47f8 | ||
|
|
542a0ec5a2 | ||
|
|
a02ce34be1 | ||
|
|
9b2bf4d555 | ||
|
|
75ad090d04 | ||
|
|
1aa2448dbc | ||
|
|
04a1f24536 | ||
|
|
f0cf011c30 | ||
|
|
d70ce54e65 | ||
|
|
83d3ac5d3b | ||
|
|
f173673998 | ||
|
|
dc277c0b24 | ||
|
|
b34cc6cefd | ||
|
|
a954a57d9f | ||
|
|
1c8cd508bd | ||
|
|
cbf4708d41 | ||
|
|
2cc39e9d09 | ||
|
|
0d8ec23154 | ||
|
|
b2c03ad24d | ||
|
|
4c180827d6 | ||
|
|
38ab3146e1 | ||
|
|
9e34975cd7 | ||
|
|
c99fd9ae25 | ||
|
|
7f3bc15810 | ||
|
|
33f154b192 | ||
|
|
96e01da641 | ||
|
|
d0eb1e32b2 | ||
|
|
96e8a794f0 | ||
|
|
750086adb7 | ||
|
|
f0afc9afb8 | ||
|
|
5ab568af83 | ||
|
|
858756642a | ||
|
|
785093d1c6 | ||
|
|
b29ea0b9e4 | ||
|
|
8a12277589 | ||
|
|
83d11c25eb | ||
|
|
f897bd8936 | ||
|
|
1e25343dc4 | ||
|
|
d2e291c4b1 | ||
|
|
f893738b86 | ||
|
|
1107aa6170 | ||
|
|
02082e504d | ||
|
|
33ab9c7122 | ||
|
|
9acab869bd | ||
|
|
0bde7266f8 | ||
|
|
0c6ebbf134 | ||
|
|
1d661e0ac0 | ||
|
|
330d626f6c | ||
|
|
f5538d42a0 | ||
|
|
39394d4df2 | ||
|
|
ed3dcb88dc | ||
|
|
65cef84b85 | ||
|
|
d95d762299 | ||
|
|
fd0b245d94 | ||
|
|
66492af971 | ||
|
|
65229a8645 | ||
|
|
b4b306b1e4 | ||
|
|
abc28f1a93 | ||
|
|
463e09f530 | ||
|
|
fff563b878 | ||
|
|
2fc15a079c | ||
|
|
8d26ff74e4 | ||
|
|
316d26924e | ||
|
|
d82cf4b4f3 | ||
|
|
6fc6aa1ff2 | ||
|
|
cb1a4dd2ad | ||
|
|
dac178930b | ||
|
|
99aa8d4b28 | ||
|
|
00451084e8 | ||
|
|
de7efca59e | ||
|
|
93b9257e47 | ||
|
|
7aeeb7552a | ||
|
|
63216de07e | ||
|
|
b3a705bc87 | ||
|
|
5c533a8167 | ||
|
|
6b887d5fbf | ||
|
|
a717653dc9 | ||
|
|
85606a58d9 | ||
|
|
a0401280be | ||
|
|
c0467ad820 | ||
|
|
0042bf6abc | ||
|
|
112fd1a7b5 | ||
|
|
cab8a789fc | ||
|
|
50cd3f3210 | ||
|
|
8cdbe6c7fa | ||
|
|
7ecf4ad247 | ||
|
|
26321bb81c | ||
|
|
a37b899b4a | ||
|
|
4885d47592 | ||
|
|
9371270b99 | ||
|
|
b6701fe30e | ||
|
|
087161db76 | ||
|
|
ad2a582b63 |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
---
|
||||
name: secure-env-secrets
|
||||
description: Store or retrieve a user-provided secret as a local environment variable outside repositories, without exposing its value in commands or output. Does not configure CI or remote services.
|
||||
---
|
||||
|
||||
# Secure local environment secrets
|
||||
|
||||
Use this skill only for secrets the user supplied or explicitly authorized you to retrieve. Keep values outside repositories and never repeat them in commentary, tool output, logs, diffs, or a final response.
|
||||
|
||||
## Choose scope and storage
|
||||
|
||||
- Prefer the operating system credential store or an existing secret manager, and expose a value only to the process that needs it.
|
||||
- A secret in an environment variable is available to same-user processes and is not a secure store. Do not add secrets to global shell startup files by default.
|
||||
- If the user needs persistence and no credential store is available, use a user-owned directory outside every repository, with directory permissions `0700` and file permissions `0600`. Explain that permissions restrict other accounts but do not encrypt the file. Avoid synced/shared locations unless requested.
|
||||
- Keep a persistent file inert data (for example, base64-encoded values keyed by validated variable names); do not source a file containing arbitrary shell code. Load a requested value only in the shell/process that needs it, without printing it.
|
||||
|
||||
## Read or write safely
|
||||
|
||||
1. Establish the variable name, intended scope (one command, one shell, or persistent local use), and destination. Ask only for details that change the safe implementation.
|
||||
2. Before writing, check for an existing value without displaying it. Preserve it unless the user explicitly requests replacement; do not silently delete credentials.
|
||||
3. Accept the secret through a masked prompt or credential-store protected input. Never place it in a command string, here-document, argument, URL, exported helper variable, or ordinary prompt. If the interface would expose input through tool history/output, ask the user to enter it locally and continue with metadata-only checks.
|
||||
4. Resolve and verify the destination is outside all involved repositories. Create owner-only directories and set owner-only file permissions before writing.
|
||||
5. Disable shell tracing and avoid commands that dump environment or variable values. Expose the variable only for the requested operation.
|
||||
6. Verify presence and permissions without printing or deriving information from the value. Report only the variable name, storage scope/path, and set/unset state.
|
||||
|
||||
Never use `env`, `printenv`, `set`, `echo "$SECRET"`, shell tracing, or a diff to inspect secret values. Do not place secrets in project `.env` files, Compose definitions, source code, CI workflows, or test fixtures. This skill does not configure remote CI, cloud, registry, or account secrets.
|
||||
|
||||
If a value appears in output or is committed, stop using it and tell the user it should be rotated. Do not rotate credentials in an external service unless separately authorized.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "Secure Environment Secrets"
|
||||
short_description: "Keep user secrets outside repositories"
|
||||
default_prompt: "Safely read or store the user-provided secret as a local environment variable outside the repository."
|
||||
@@ -36,3 +36,9 @@ Thumbs.db
|
||||
.env
|
||||
.env.local
|
||||
*.env
|
||||
|
||||
# Build outputs at every depth; never copy host restore state into images.
|
||||
**/bin/**
|
||||
**/obj/**
|
||||
artifacts/
|
||||
**/secrets/**
|
||||
+23
-29
@@ -1,17 +1,19 @@
|
||||
# ─── Heimdall — Environment Variables ──────────────────────────────
|
||||
# Copy this file to .env and adjust for your deployment
|
||||
# Development examples only. Copy to docker/.env for a local deployment.
|
||||
# Never commit real values; docker/.env and docker/secrets/ are ignored by Git.
|
||||
#
|
||||
# The heimdall service serves the Blazor UI, REST API, SignalR hubs,
|
||||
# and Hangfire background jobs in a single process on port 5000.
|
||||
#
|
||||
# PRODUCTION: Use Docker secrets (docker/secrets/) for sensitive values.
|
||||
# See docker-compose.prod.yml header for instructions.
|
||||
# Production core is PostgreSQL + Central. Use docker/secrets/db_password for
|
||||
# the database and set JWT keys only in the host environment or ignored env file.
|
||||
# Install Agents from the digest-pinned Compose supplied by Central's UI.
|
||||
|
||||
# Development example only: replace all credentials before exposure.
|
||||
# Database
|
||||
POSTGRES_PASSWORD=heimdall
|
||||
RABBITMQ_PASSWORD=heimdall-development-only
|
||||
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall
|
||||
# Production uses eltruncho/heimdall:latest from Docker Hub.
|
||||
|
||||
# JWT (change in production!)
|
||||
# JWT__Key is used for access tokens, JWT__RefreshKey for refresh tokens.
|
||||
@@ -21,48 +23,40 @@ JWT__REFRESHKEY=ChangeMeToAtLeast32BytesRefreshKeyInProd!
|
||||
JWT__ISSUER=heimdall
|
||||
JWT__AUDIENCE=heimdall-api
|
||||
|
||||
# Optional manual license-plate crop OCR (disabled by default).
|
||||
PLATE_OCR_ENABLED=false
|
||||
|
||||
# ASP.NET
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
ASPNETCORE_ENVIRONMENT=Development
|
||||
ASPNETCORE_URLS=http://+:8080
|
||||
|
||||
# CORS (default: allow all origins — restrict in production)
|
||||
Cors__AllowedOrigins=*
|
||||
|
||||
# Alarik (S3-compatible object storage)
|
||||
ALARIK_API_PORT=9000
|
||||
ALARIK_CONSOLE_PORT=9001
|
||||
ALARIK_ADMIN_USERNAME=heimdall
|
||||
ALARIK_ADMIN_PASSWORD=heimdall123
|
||||
ALARIK_JWT=ChangeMeAtLeast32BytesLongKeyInProd!
|
||||
# RustFS (S3-compatible object storage)
|
||||
RUSTFS_API_PORT=9000
|
||||
RUSTFS_CONSOLE_PORT=9001
|
||||
RUSTFS_ACCESS_KEY=heimdall
|
||||
RUSTFS_SECRET_KEY=ChangeMeAtLeast32BytesLongKeyInProd!
|
||||
RUSTFS_ENDPOINT=http://rustfs:9000
|
||||
RUSTFS_BUCKET=heimdall
|
||||
|
||||
# Sentry / GlitchTip (error tracking, performance, structured logs)
|
||||
# Primary: Sentry__Dsn (ASP.NET Core config convention)
|
||||
# Fallback: SENTRY_DSN (legacy, for backward compatibility)
|
||||
# When unset/empty, the Sentry SDK is not initialized (graceful no-op).
|
||||
Sentry__Dsn=https://db94b9...dc73@glitchtip.tordais.cc/6
|
||||
Sentry__TracesSampleRate=0.05
|
||||
Sentry__Release=heimdall@1.0.0
|
||||
SENTRY_DSN=
|
||||
SENTRY_TRACES_SAMPLE_RATE=0.05
|
||||
SENTRY_RELEASE=heimdall@1.0.0
|
||||
|
||||
# Agent (set per agent instance)
|
||||
# Agent (for local development only; production Compose is supplied by Central)
|
||||
HEIMDALL_CENTRAL_URL=http://localhost:5000
|
||||
HEIMDALL_PUBLIC_IP_RESOLVER_URL=
|
||||
HEIMDALL_SITE_TOKEN=replace-with-actual-token
|
||||
HEIMDALL_AGENT_NAME=agent-01
|
||||
HEIMDALL_HEARTBEAT_INTERVAL=30
|
||||
HEIMDALL_REGISTRATION_RETRIES=5
|
||||
|
||||
# Email (SMTP) — notifications
|
||||
EMAIL__SMTP_HOST=smtp.example.com
|
||||
EMAIL__SMTP_PORT=587
|
||||
EMAIL__USERNAME=
|
||||
EMAIL__PASSWORD=
|
||||
EMAIL__FROM_ADDRESS=noreply@heimdall.local
|
||||
EMAIL__FROM_NAME=Heimdall
|
||||
EMAIL__USE_SSL=true
|
||||
|
||||
# ntfy push notifications
|
||||
NTFY__BASE_URL=http://ntfy:80
|
||||
NTFY__TOKEN=
|
||||
|
||||
# Coturn (TURN relay for WebRTC)
|
||||
COTURN_SECRET=ChangeMeAtLeast32BytesLongCoturnSecret!
|
||||
COTURN_REALM=heimdall.local
|
||||
@@ -72,4 +66,4 @@ OLLAMA_PORT=11434
|
||||
|
||||
# Redis (SignalR backplane, optional — scaling)
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=
|
||||
REDIS_PASSWORD=replace-with-a-long-unique-password
|
||||
@@ -1,47 +1,25 @@
|
||||
## Contexte
|
||||
## Problème et résultat
|
||||
|
||||
<!-- Pourquoi cette PR ? Quel problème résout-elle ? (obligatoire) -->
|
||||
<!-- Décrire le déclencheur, le comportement corrigé et le périmètre. -->
|
||||
|
||||
## Changements
|
||||
Refs #
|
||||
|
||||
- [ ] ...
|
||||
## Vérification
|
||||
|
||||
## Tickets liés (obligatoire)
|
||||
<!-- Issue Gitea liée, liens des runs Gitea, suites exécutées et résultats observés. -->
|
||||
|
||||
> Une PR DOIT être liée à un ticket ou un groupe de tickets du même thème (préfixe `Fixes #N` / `Refs #N` dans la description ou les commits).
|
||||
- [ ] Build and tests : compilation, PostgreSQL, Chromium, archives et images
|
||||
- [ ] Contrôles NuGet et images sans HIGH/CRITICAL
|
||||
- [ ] Limites et tests non exécutés explicitement documentés
|
||||
- [ ] Aucun secret dans les logs/artefacts
|
||||
|
||||
- Fixes #N
|
||||
- Refs #N
|
||||
## Livraison
|
||||
|
||||
## Résultats des tests (obligatoire)
|
||||
<!-- Voir docs/gitea-builds.md. Pas de merge/déploiement implicite. -->
|
||||
|
||||
> Le **rapport QA détaillé** (plan, exécution, résultats, coverage, verdict) est posté en commentaire sur cette PR par **the-qa**, selon le **modèle immutable** du repo `templates` : [.forgejo/templates/rapport-qa.md](https://forgejo.tordais.cc/nonobis/templates/src/branch/main/.forgejo/templates/rapport-qa.md)
|
||||
- [ ] Traçabilité commit → résultats → SHA256 des archives → digests images
|
||||
- [ ] Revue des changements de contrats/migrations/configuration
|
||||
- [ ] Si la PR change un graphe d’image : seules les images affectées ont été construites/scannées; publication Docker Hub vérifiée après merge
|
||||
- [ ] Si elle change la livraison : le workflow de tag versionné et la release Gitea versionnée sont documentés et acceptés
|
||||
|
||||
- [ ] Rapport QA de the-qa : ✅ VALIDÉ / ❌ REFUSÉ / ⚠️ réserves (voir commentaire)
|
||||
- [ ] Tous les tests passent (voir commentaire CI + rapport QA)
|
||||
- [ ] Coverage : **X %** (ou lien vers le rapport)
|
||||
|
||||
## Retours SonarQube (obligatoire)
|
||||
|
||||
> La qualité gate SonarQube est **bloquante** en CI : la PR ne peut pas être mergée si elle est rouge. Traiter TOUS les retours avant de demander la relecture.
|
||||
|
||||
- [ ] Quality gate SonarQube **OK** (voir run CI)
|
||||
- [ ] Bugs / vulnérabilités : **0 non résolu** — sinon détailler ici pourquoi :
|
||||
- `rule:key` — justifié (hors scope / faux positif / ticket de dette technique créé)
|
||||
|
||||
## CVE (obligatoire)
|
||||
|
||||
> Trivy + OWASP Dependency-Check sont **bloquants** (HIGH/CRITICAL). Toute CVE signalée doit être corrigée. Si une correction est **impossible**, l'expliquer en commentaire sur la PR (pas de merge sans justification).
|
||||
|
||||
- [ ] Aucune CVE HIGH/CRITICAL nouvelle sur cette PR (voir commentaire CI)
|
||||
- [ ] CVE non corrigeables documentées en commentaire (si applicable)
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Commits atomiques au format conventionnel (`feat(scope): ...`, `fix(scope): ...`)
|
||||
- [ ] Branche issue de `main`, à jour (`git rebase main` si besoin)
|
||||
- [ ] Pas de secret en clair (tokens, mots de passe)
|
||||
- [ ] Build local : `dotnet build -c Release`
|
||||
- [ ] Tests locaux : `dotnet test` (ou `make test`)
|
||||
- [ ] CI verte : build, tests, Trivy, Dependency-Check, SonarQube (politiques bloquantes)
|
||||
- [ ] Release notes / versioning impacté (GitVersion)
|
||||
SonarQube, matériel et autres contrôles externes ne sont considérés validés que si une preuve réelle est jointe. Une protection de branche doit exiger le contexte Gitea constaté sur le run avant de compter sur le blocage d’un merge.
|
||||
@@ -0,0 +1,361 @@
|
||||
name: Heimdall Gitea
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['*.*.*']
|
||||
permissions:
|
||||
contents: read
|
||||
concurrency:
|
||||
group: heimdall-${{ gitea.ref }}
|
||||
cancel-in-progress: false
|
||||
env:
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
jobs:
|
||||
changes:
|
||||
name: Detect CI scope
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
outputs:
|
||||
run_validation: ${{ steps.filter.outputs.run_validation }}
|
||||
build_server: ${{ steps.filter.outputs.build_server }}
|
||||
build_agent: ${{ steps.filter.outputs.build_agent }}
|
||||
build_agent_gpu: ${{ steps.filter.outputs.build_agent_gpu }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Detect changed projects and images
|
||||
id: filter
|
||||
env:
|
||||
PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
|
||||
PUSH_BEFORE_SHA: ${{ gitea.event.before }}
|
||||
CURRENT_SHA: ${{ gitea.sha }}
|
||||
EVENT_NAME: ${{ gitea.event_name }}
|
||||
REF: ${{ gitea.ref }}
|
||||
run: python3 scripts/ci/change_scope.py
|
||||
policy:
|
||||
name: CI policy
|
||||
if: always()
|
||||
needs: [changes, verify, server_image, agent_image, agent_gpu_image, publish]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
steps:
|
||||
- name: Require all applicable validation jobs to pass
|
||||
env:
|
||||
CHANGE_RESULT: ${{ needs.changes.result }}
|
||||
RUN_VALIDATION: ${{ needs.changes.outputs.run_validation }}
|
||||
VERIFY_RESULT: ${{ needs.verify.result }}
|
||||
SERVER_IMAGE_RESULT: ${{ needs.server_image.result }}
|
||||
AGENT_IMAGE_RESULT: ${{ needs.agent_image.result }}
|
||||
AGENT_GPU_IMAGE_RESULT: ${{ needs.agent_gpu_image.result }}
|
||||
RELEASE_RESULT: ${{ needs.publish.result }}
|
||||
EVENT_NAME: ${{ gitea.event_name }}
|
||||
REF: ${{ gitea.ref }}
|
||||
run: |
|
||||
set -eu
|
||||
test "$CHANGE_RESULT" = success
|
||||
|
||||
if [ "$RUN_VALIDATION" != true ]; then
|
||||
echo 'No source, test, build, or deployment inputs changed.'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
test "$VERIFY_RESULT" = success
|
||||
if [ "${{ needs.changes.outputs.build_server }}" = true ]; then test "$SERVER_IMAGE_RESULT" = success; fi
|
||||
if [ "${{ needs.changes.outputs.build_agent }}" = true ]; then test "$AGENT_IMAGE_RESULT" = success; fi
|
||||
if [ "${{ needs.changes.outputs.build_agent_gpu }}" = true ]; then test "$AGENT_GPU_IMAGE_RESULT" = success; fi
|
||||
case "$EVENT_NAME:$REF" in
|
||||
push:refs/tags/*) test "$RELEASE_RESULT" = success ;;
|
||||
esac
|
||||
verify:
|
||||
name: Build and tests
|
||||
if: needs.changes.outputs.run_validation == 'true'
|
||||
needs: [changes]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine@sha256:b0f9560a2de083e2cc7382e75f808c7381a32852a7ec49117deedb300e552b24
|
||||
env:
|
||||
POSTGRES_DB: postgres
|
||||
POSTGRES_USER: heimdall_ci
|
||||
POSTGRES_PASSWORD: ephemeral-ci-only
|
||||
options: --health-cmd 'pg_isready -U heimdall_ci -d postgres' --health-interval 5s --health-timeout 5s --health-retries 20
|
||||
env:
|
||||
DATABASE_URL: Host=postgres;Port=5432;Database=postgres;Username=heimdall_ci;Password=ephemeral-ci-only
|
||||
PGHOST: postgres
|
||||
PGUSER: heimdall_ci
|
||||
PGPASSWORD: ephemeral-ci-only
|
||||
PGDATABASE: postgres
|
||||
DOTNET_CLI_TELEMETRY_OPTOUT: '1'
|
||||
DOTNET_NOLOGO: '1'
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
BUILD_RUN_ID: ${{ gitea.run_id }}
|
||||
GITEA_EVENT_NAME: ${{ gitea.event_name }}
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
|
||||
test "$(uname -m)" = x86_64
|
||||
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
|
||||
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
|
||||
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
|
||||
ln -sf /usr/local/bin/node /usr/bin/node
|
||||
rm /tmp/node.tar.xz
|
||||
node --version
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Runner prerequisites
|
||||
run: bash scripts/ci/bootstrap.sh
|
||||
- name: Reclaim old Heimdall build storage
|
||||
run: bash scripts/ci/cleanup-docker.sh before
|
||||
- name: CI script contracts
|
||||
run: |
|
||||
python3 -m unittest discover -s scripts/ci -p 'test_*.py'
|
||||
python3 scripts/ci/check-efcore-usage.py
|
||||
- name: Validate Compose and restore .NET solution
|
||||
run: |
|
||||
mkdir -p artifacts/tests artifacts/security
|
||||
dotnet --info > artifacts/dotnet-info.txt
|
||||
bash scripts/ci/validate-compose.sh
|
||||
dotnet restore Heimdall.slnx --locked-mode
|
||||
- name: Plan affected test suites
|
||||
run: python3 scripts/ci/test-plan.py
|
||||
- name: Build affected projects
|
||||
run: python3 scripts/ci/build-plan.py
|
||||
- name: Agent tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.Agent.Tests
|
||||
- name: API tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.Api.Tests
|
||||
- name: Application tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.Application.Tests
|
||||
- name: Domain tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.Domain.Tests
|
||||
- name: Infrastructure tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.Infrastructure.Tests
|
||||
- name: Integration tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.IntegrationTests
|
||||
- name: Web tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.Web.Tests
|
||||
- name: Camera access coverage gate
|
||||
run: python3 scripts/ci/check-camera-access-coverage.py artifacts/tests artifacts/tests/plan.json
|
||||
- name: Browser tests
|
||||
run: bash scripts/ci/test-suite.sh Heimdall.E2E.Tests
|
||||
- name: NuGet dependency security gate
|
||||
run: bash scripts/ci/security.sh dependencies --no-restore
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
|
||||
bash scripts/ci/cleanup-docker.sh after
|
||||
fi
|
||||
server_image:
|
||||
name: Build and scan server image
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_server == 'true'
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
|
||||
test "$(uname -m)" = x86_64
|
||||
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
|
||||
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
|
||||
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
|
||||
ln -sf /usr/local/bin/node /usr/bin/node
|
||||
rm /tmp/node.tar.xz
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Runner prerequisites
|
||||
run: bash scripts/ci/bootstrap.sh
|
||||
- name: Reclaim old build storage
|
||||
run: bash scripts/ci/cleanup-docker.sh before
|
||||
- name: Build server image
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/images.sh server
|
||||
- name: Scan server image
|
||||
run: bash scripts/ci/security.sh server
|
||||
- name: Push immutable server image to Docker Hub
|
||||
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/push-images.sh server
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
|
||||
bash scripts/ci/cleanup-docker.sh after
|
||||
fi
|
||||
agent_image:
|
||||
name: Build and scan agent image
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent == 'true'
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
|
||||
test "$(uname -m)" = x86_64
|
||||
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
|
||||
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
|
||||
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
|
||||
ln -sf /usr/local/bin/node /usr/bin/node
|
||||
rm /tmp/node.tar.xz
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Runner prerequisites
|
||||
run: bash scripts/ci/bootstrap.sh
|
||||
- name: Reclaim old build storage
|
||||
run: bash scripts/ci/cleanup-docker.sh before
|
||||
- name: Build agent image
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/images.sh agent
|
||||
- name: Scan agent image
|
||||
run: bash scripts/ci/security.sh agent
|
||||
- name: Push immutable agent image to Docker Hub
|
||||
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/push-images.sh agent
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
|
||||
bash scripts/ci/cleanup-docker.sh after
|
||||
fi
|
||||
agent_gpu_image:
|
||||
name: Build and scan NVIDIA Agent image
|
||||
if: needs.changes.outputs.run_validation == 'true' && needs.changes.outputs.build_agent_gpu == 'true'
|
||||
needs: [changes, verify]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
|
||||
test "$(uname -m)" = x86_64
|
||||
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
|
||||
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
|
||||
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
|
||||
ln -sf /usr/local/bin/node /usr/bin/node
|
||||
rm /tmp/node.tar.xz
|
||||
- name: Checkout
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Runner prerequisites
|
||||
run: bash scripts/ci/bootstrap.sh
|
||||
- name: Reclaim old build storage
|
||||
run: bash scripts/ci/cleanup-docker.sh before
|
||||
- name: Build NVIDIA Agent image
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/images.sh agent-gpu
|
||||
- name: Scan NVIDIA Agent image
|
||||
run: bash scripts/ci/security.sh agent-gpu
|
||||
- name: Push immutable NVIDIA Agent image to Docker Hub
|
||||
if: gitea.event_name == 'push' && (gitea.ref == 'refs/heads/main' || startsWith(gitea.ref, 'refs/tags/'))
|
||||
env:
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
run: bash scripts/ci/push-images.sh agent-gpu
|
||||
- name: Reclaim build storage after job
|
||||
if: always()
|
||||
run: |
|
||||
if test -f scripts/ci/cleanup-docker.sh && command -v docker >/dev/null 2>&1; then
|
||||
bash scripts/ci/cleanup-docker.sh after
|
||||
fi
|
||||
publish:
|
||||
name: Publish versioned installer release
|
||||
if: needs.changes.outputs.run_validation == 'true' && startsWith(gitea.ref, 'refs/tags/')
|
||||
needs: [changes, verify, server_image, agent_image, agent_gpu_image]
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: read
|
||||
actions: read
|
||||
steps:
|
||||
- name: Prepare action runtime before checkout
|
||||
run: |
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends curl git ca-certificates xz-utils
|
||||
test "$(uname -m)" = x86_64
|
||||
curl --fail --silent --show-error --location https://nodejs.org/dist/v22.23.3/node-v22.23.3-linux-x64.tar.xz -o /tmp/node.tar.xz
|
||||
echo 'df450af89261115ef9f9e3830c3eeb2cc9213b63c720b1af623cb5dcbe2e02de /tmp/node.tar.xz' | sha256sum --check
|
||||
tar -xJf /tmp/node.tar.xz -C /usr/local --strip-components=1
|
||||
ln -sf /usr/local/bin/node /usr/bin/node
|
||||
rm /tmp/node.tar.xz
|
||||
node --version
|
||||
- uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- run: bash scripts/ci/bootstrap.sh
|
||||
- name: Build versioned installer and Agent archives
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
BUILD_RUN_ID: ${{ gitea.run_id }}
|
||||
run: bash scripts/ci/package.sh
|
||||
- name: Generate changes since the previous version tag
|
||||
run: |
|
||||
current_tag="${GITEA_REF#refs/tags/}"
|
||||
previous_tag="$(git tag --merged "$CURRENT_SHA" --sort=-version:refname | sed -n '/^[0-9][0-9]*\.[0-9]/p' | grep -Fvx "$current_tag" | head -n 1 || true)"
|
||||
if [ -n "$previous_tag" ]; then
|
||||
BEFORE_SHA="$(git rev-list -n 1 "$previous_tag")"
|
||||
else
|
||||
BEFORE_SHA="$(git rev-list --max-parents=0 "$CURRENT_SHA" | tail -n 1)"
|
||||
fi
|
||||
export BEFORE_SHA CURRENT_SHA GITEA_TOKEN BUILD_SERVER_URL BUILD_REPOSITORY
|
||||
python3 scripts/ci/release-notes.py
|
||||
env:
|
||||
GITEA_REF: ${{ gitea.ref }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
CURRENT_SHA: ${{ gitea.sha }}
|
||||
- name: Publish signed release assets
|
||||
env:
|
||||
BUILD_REF: ${{ gitea.ref }}
|
||||
BUILD_REPOSITORY: ${{ gitea.repository }}
|
||||
BUILD_SERVER_URL: ${{ gitea.server_url }}
|
||||
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
RELEASE_SIGNING_KEY_B64: ${{ secrets.RELEASE_SIGNING_KEY_B64 }}
|
||||
EXPECTED_BUILD_SERVER_URL: ${{ vars.RELEASE_SERVER_URL }}
|
||||
RELEASE_NOTES_FILE: artifacts/release-notes.md
|
||||
RELEASE_TAG: ${{ gitea.ref_name }}
|
||||
run: bash scripts/ci/publish.sh
|
||||
- name: Reclaim build storage after release
|
||||
if: always()
|
||||
run: bash scripts/ci/cleanup-docker.sh after
|
||||
@@ -0,0 +1,30 @@
|
||||
name: Renovate dependencies
|
||||
on:
|
||||
schedule:
|
||||
- cron: '17 3 * * 1'
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
renovate:
|
||||
runs-on: [ubuntu-latest, build-agent]
|
||||
container:
|
||||
image: renovate/renovate:44.133.0
|
||||
env:
|
||||
RENOVATE_PLATFORM: gitea
|
||||
RENOVATE_ENDPOINT: ${{ vars.FORGEJO_API_ENDPOINT }}
|
||||
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
|
||||
RENOVATE_ONBOARDING: 'false'
|
||||
steps:
|
||||
- name: Checkout Renovate preflight
|
||||
uses: https://github.com/actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
persist-credentials: false
|
||||
- name: Check Renovate credentials against Gitea
|
||||
run: |
|
||||
node --test scripts/ci/renovate-preflight.test.mjs
|
||||
node scripts/ci/renovate-preflight.mjs
|
||||
- name: Create dependency pull requests
|
||||
run: |
|
||||
renovate arnaud.dartois/Heimdall
|
||||
@@ -92,3 +92,6 @@ docker/.env
|
||||
# Python bytecode (CI scripts)
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
# Gitea build outputs
|
||||
artifacts/
|
||||
@@ -0,0 +1,18 @@
|
||||
# Heimdall contributor rules
|
||||
|
||||
- For every feature, fix, operational change, or meaningful documentation change, create or update a focused skill under `skills/` in the same PR. The skill must capture the project-specific implementation and acceptance workflow, not restate generic guidance.
|
||||
- Every behavior or deployment change must pass an acceptance recipe in a disposable Docker Compose project built from the changed source. Use isolated generated credentials, ports, volumes, project names, and unique tags for locally built acceptance images; never reuse production configuration/data. Tear down only that project and confirm its containers/volumes/networks are gone, then remove and verify absence of only the exact image tags built by that recipe. Keep shared upstream/base images. Never use broad image pruning. Do not skip this recipe silently when Docker is unavailable.
|
||||
- Use Gitea project issues as the sole backlog and work-status source. Before changing code, find or create the focused issue, keep its acceptance evidence current, and link the issue from the PR (`Closes #N` only when all criteria are complete; otherwise `Refs #N`). Follow [skills/gitea-ticket-workflow/SKILL.md](skills/gitea-ticket-workflow/SKILL.md). Do not create or maintain a `todo.md` backlog.
|
||||
- Keep `Domain` independent of infrastructure. Put use cases and interfaces in `Application`, adapters and EF Core persistence in `Infrastructure`, HTTP/UI composition in `Web`, and camera/runtime behavior in `Agent`.
|
||||
- Target the SDK pinned by `global.json` and .NET 10 or newer. Use nullable reference types, cancellation tokens for I/O, and explicit options validation. Do not weaken locked restore or suppress a new warning without a reason.
|
||||
- Use EF Core for production database reads and writes. Do not use direct ADO.NET or provider commands in production code; provider-specific EF SQL is allowed only for capabilities LINQ cannot express, with a nearby rationale and a test. The CI persistence policy enforces this boundary. Preserve PostgreSQL behavior, add migrations for schema changes, and verify translation, concurrency, and deletion semantics with relational tests. Never reuse a `DbContext` across concurrent operations.
|
||||
- Keep tenant/site and camera authorization checks at API and application boundaries. Do not log credentials, RTSP URLs, embeddings, or raw tokens.
|
||||
- CI jobs run only on `[ubuntu-latest, build-agent]`. Keep `runner-aaja` outside that label. Never use release credentials in pull request jobs.
|
||||
- A PR touching deployment or publication must document required secrets and prove the relevant script locally. Do not claim a runner, registry, camera, or object store was validated without a real run.
|
||||
|
||||
See [skills/heimdall-dotnet/SKILL.md](skills/heimdall-dotnet/SKILL.md) for project-specific implementation guidance.
|
||||
For Penpot design work, follow [skills/penpot-design-sync/SKILL.md](skills/penpot-design-sync/SKILL.md): always open Penpot and establish the authenticated session through the Orca browser, and keep the connected design synchronized with relevant shipped UI changes.
|
||||
When work can be split safely, follow [skills/parallel-development/SKILL.md](skills/parallel-development/SKILL.md) to dispatch independent investigations and implementation through Orca, then integrate and validate the combined change once.
|
||||
For database access, also follow [skills/ef-core-persistence/SKILL.md](skills/ef-core-persistence/SKILL.md); the CI persistence policy checks production source for direct database commands and requires documented provider-specific exceptions.
|
||||
For behavior changes, use [skills/compose-disposable-recipe/SKILL.md](skills/compose-disposable-recipe/SKILL.md); account bootstrap changes also use [skills/first-admin-bootstrap/SKILL.md](skills/first-admin-bootstrap/SKILL.md).
|
||||
For Central installer, Compose, or server image update changes, also use [skills/central-auto-updates/SKILL.md](skills/central-auto-updates/SKILL.md).
|
||||
@@ -0,0 +1,5 @@
|
||||
<Project>
|
||||
<PropertyGroup>
|
||||
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,6 +1,6 @@
|
||||
# ─── Heimdall — Development & Deployment ──────────────────────────
|
||||
.DEFAULT_GOAL := help
|
||||
.PHONY: help build test docker-up docker-down docker-build clean dev backup backup-alarik restore backup-test
|
||||
.PHONY: help build test test-watch clean docker-up docker-down docker-build docker-logs docker-ps docker-reset docker-agent-up docker-agent-down deploy version version-tag version-tag-agent migration-add migration-remove dev-api dev-web backup backup-rustfs restore restore-file backup-test backup-up backup-down backup-logs
|
||||
|
||||
help: ## Show this help
|
||||
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | \
|
||||
@@ -20,23 +20,29 @@ clean: ## Clean build artifacts
|
||||
|
||||
# ─── Docker ──────────────────────────────────────────────────────
|
||||
|
||||
docker-up: ## Start all services (dev)
|
||||
docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.yml up -d
|
||||
docker-up: ## Start Central and PostgreSQL (dev)
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d
|
||||
|
||||
docker-down: ## Stop all services
|
||||
docker compose -f docker/docker-compose.yml down -v
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml down
|
||||
|
||||
docker-build: ## Rebuild images without cache
|
||||
docker compose -f docker/docker-compose.yml build --no-cache
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml build --no-cache
|
||||
|
||||
docker-logs: ## Tail logs
|
||||
docker compose -f docker/docker-compose.yml logs -f
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml logs -f
|
||||
|
||||
docker-ps: ## List running services
|
||||
docker compose -f docker/docker-compose.yml ps
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml ps
|
||||
|
||||
docker-reset: ## Stop and remove everything
|
||||
docker compose -f docker/docker-compose.yml down -v --rmi all
|
||||
docker-reset: ## Stop Central and PostgreSQL and remove their volumes
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml down -v --rmi all
|
||||
|
||||
docker-agent-up: ## Build and start a local Agent (set HEIMDALL_SITE_TOKEN)
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.agent.dev.yml up -d --build
|
||||
|
||||
docker-agent-down: ## Stop the local Agent
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.agent.dev.yml down
|
||||
|
||||
# ─── Deployment ──────────────────────────────────────────────────
|
||||
|
||||
@@ -71,11 +77,7 @@ migration-remove: ## Remove last migration
|
||||
# ─── Dev helpers ─────────────────────────────────────────────────
|
||||
|
||||
dev-api: ## Run combined API+Web in development mode (API and Blazor UI in one process)
|
||||
DATABASE_URL="Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall" \
|
||||
JWT__Key="ThisIsADevKeyThatIsAtLeast32BytesLong!!" \
|
||||
ASPNETCORE_ENVIRONMENT=Development \
|
||||
Cors__AllowedOrigins="*" \
|
||||
dotnet run --project src/Heimdall.Web
|
||||
$(MAKE) dev-web
|
||||
|
||||
dev-web: ## Run combined API+Web+Jobs in development mode (single process)
|
||||
DATABASE_URL="Host=localhost;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall" \
|
||||
@@ -86,15 +88,15 @@ dev-web: ## Run combined API+Web+Jobs in development mode (single process)
|
||||
|
||||
# ─── Backup & Restore ──────────────────────────────────────────
|
||||
|
||||
backup: ## Run PostgreSQL backup (daily — pg_dump + upload to Alarik/S3)
|
||||
backup: ## Run PostgreSQL backup (daily — pg_dump + upload to RustFS/S3)
|
||||
chmod +x docker/scripts/backup.sh
|
||||
POSTGRES_HOST=localhost POSTGRES_PORT=5432 \
|
||||
POSTGRES_DB=heimdall POSTGRES_USER=heimdall POSTGRES_PASSWORD=heimdall \
|
||||
./docker/scripts/backup.sh
|
||||
|
||||
backup-alarik: ## Run Alarik/S3 mirror backup (weekly — snapshots + recordings)
|
||||
chmod +x docker/scripts/backup-alarik.sh
|
||||
./docker/scripts/backup-alarik.sh
|
||||
backup-rustfs: ## Run RustFS/S3 mirror backup (weekly — snapshots + recordings)
|
||||
chmod +x docker/scripts/backup-rustfs.sh
|
||||
./docker/scripts/backup-rustfs.sh
|
||||
|
||||
restore: ## Restore PostgreSQL from latest backup (⚠️ drops current DB)
|
||||
chmod +x docker/scripts/restore.sh
|
||||
@@ -113,11 +115,11 @@ backup-test: ## Run backup/restore E2E test (isolated PostgreSQL)
|
||||
chmod +x docker/scripts/test-backup-restore.sh
|
||||
./docker/scripts/test-backup-restore.sh
|
||||
|
||||
backup-up: ## Start backup cron service (daily PG + weekly Alarik mirror)
|
||||
docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml up -d backup
|
||||
backup-up: ## Start backup cron service (daily PG + weekly RustFS mirror)
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml up -d
|
||||
|
||||
backup-down: ## Stop backup cron service
|
||||
docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml down backup
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml down
|
||||
|
||||
backup-logs: ## Tail backup service logs
|
||||
docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml logs -f backup
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml logs -f backup
|
||||
@@ -0,0 +1,127 @@
|
||||
groups:
|
||||
- name: heimdall
|
||||
rules:
|
||||
- alert: HeimdallAgentSnapshotDrops
|
||||
expr: increase(heimdall_ai_queue_dropped_total{job="heimdall-agent"}[5m]) > 0
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Agent is dropping camera snapshots
|
||||
description: "{{ $labels.instance }} rejected snapshots during the last five minutes. Check camera load and Agent capacity."
|
||||
|
||||
- alert: HeimdallAgentInferenceDrops
|
||||
expr: increase(heimdall_ai_inference_queue_rejected_total{job="heimdall-agent"}[5m]) > 0
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Agent is dropping inference frames
|
||||
description: "{{ $labels.instance }} rejected inference frames during the last five minutes. Check model performance and Agent capacity."
|
||||
|
||||
# 90% is an example; tune it for the host's reserved disk capacity.
|
||||
- alert: HeimdallAgentDiskUsageHigh
|
||||
expr: heimdall_agent_disk_usage_percent{job="heimdall-agent"} > 90
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Agent disk usage is high
|
||||
description: "{{ $labels.instance }} has reported disk usage above the example 90% threshold for ten minutes."
|
||||
|
||||
# This signals sustained work waiting, not necessarily a stuck queue.
|
||||
# Tune the 10m duration for the camera count and expected processing latency.
|
||||
- alert: HeimdallAgentSnapshotBacklog
|
||||
expr: min_over_time(heimdall_ai_queue_depth{job="heimdall-agent"}[10m]) > 0
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Agent snapshot queue has a persistent backlog
|
||||
description: "{{ $labels.instance }} had pending snapshots throughout the last ten minutes."
|
||||
|
||||
- alert: HeimdallAgentInferenceBacklog
|
||||
expr: min_over_time(heimdall_ai_inference_queue_depth{job="heimdall-agent"}[10m]) > 0
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Agent inference queue has a persistent backlog
|
||||
description: "{{ $labels.instance }} had pending inference frames throughout the last ten minutes."
|
||||
|
||||
- alert: HeimdallHangfireEnqueuedJobsStale
|
||||
expr: heimdall_hangfire_jobs_oldest_enqueued_age{job="heimdall-central"} > 900
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Central has long-waiting background jobs
|
||||
description: "The oldest observed enqueued job has waited over 15 minutes. Tune this example threshold for your workload."
|
||||
|
||||
- alert: HeimdallHangfireProcessingJobLongRunning
|
||||
expr: heimdall_hangfire_jobs_oldest_processing_age{job="heimdall-central"} > 1800
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Central has a long-running background job
|
||||
description: "The oldest observed processing job has run over 30 minutes. Tune this example threshold for your workload."
|
||||
|
||||
- alert: HeimdallHangfireFailedJobs
|
||||
expr: heimdall_hangfire_jobs_failed{job="heimdall-central"} > 0
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Central has failed background jobs
|
||||
description: "Hangfire reports failed jobs for more than ten minutes. Review the protected Hangfire dashboard."
|
||||
|
||||
- alert: HeimdallHangfireMonitoringUnavailable
|
||||
expr: heimdall_hangfire_monitoring_available{job="heimdall-central"} == 0
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall cannot read Hangfire monitoring data
|
||||
description: "The latest Hangfire monitoring polls have failed. Check Central and its database connectivity."
|
||||
|
||||
- alert: HeimdallNotificationDeliveryFailed
|
||||
expr: heimdall_notifications_outbox_failed{job="heimdall-central"} > 0
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall has terminal notification delivery failures
|
||||
description: "The notification outbox has deliveries in terminal Failed state. Review Central logs without exposing recipient details."
|
||||
|
||||
- alert: HeimdallNotificationDeliveryOverdue
|
||||
expr: heimdall_notifications_outbox_oldest_pending_due_age{job="heimdall-central"} > 300
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall has notification deliveries waiting too long
|
||||
description: "A due notification delivery has been pending for over five minutes. Scheduled retries are excluded until their next attempt is due."
|
||||
|
||||
- alert: HeimdallNotificationDeliveryLeaseExpired
|
||||
expr: heimdall_notifications_outbox_expired_leases{job="heimdall-central"} > 0
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall has notification deliveries with expired leases
|
||||
description: "Some deliveries remain Processing after their lease expired and should be recovered by the dispatcher."
|
||||
|
||||
- alert: HeimdallNotificationOutboxMonitoringUnavailable
|
||||
expr: heimdall_notifications_outbox_monitoring_available{job="heimdall-central"} == 0
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall cannot read notification outbox metrics
|
||||
description: "The latest outbox metrics poll failed. Check Central and database connectivity."
|
||||
|
||||
- alert: HeimdallAgentHasNotReceivedCentralConfiguration
|
||||
expr: heimdall_agent_central_configuration_received{job="heimdall-agent", central_config_expected="true"} == 0
|
||||
for: 10m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Heimdall Agent has not received Central camera configuration
|
||||
description: "This Agent has not accepted a valid Central snapshot since startup. Enable this rule only for Agents expected to be assigned to Central sites."
|
||||
+17
-41
@@ -1,47 +1,23 @@
|
||||
# ─── Heimdall — Single image (Web API + Blazor UI + Background Jobs) ──
|
||||
# This image runs the combined Heimdall.Web process which serves:
|
||||
# - Blazor UI (interactive Server)
|
||||
# - REST API controllers
|
||||
# - Hangfire background jobs (heartbeat monitor, agent failover)
|
||||
# - SignalR hubs (config, events)
|
||||
#
|
||||
# Build: docker build -f docker/Dockerfile -t heimdall .
|
||||
# Run: docker compose -f docker/docker-compose.yml up -d
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build
|
||||
# Server/PWA: restore the complete project graph from locked dependencies.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Version injectée par la CI (GitVersion) — ex. docker build --build-arg VERSION=1.0.0
|
||||
ARG VERSION=0.0.0-local
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
COPY src/ ./src/
|
||||
COPY install/ ./install/
|
||||
RUN dotnet restore src/Heimdall.Web/Heimdall.Web.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
# Copy solution and project files
|
||||
COPY *.slnx .
|
||||
COPY Directory.Build.props .
|
||||
COPY src/Heimdall.Domain.Primitives/*.csproj src/Heimdall.Domain.Primitives/
|
||||
COPY src/Heimdall.Domain/*.csproj src/Heimdall.Domain/
|
||||
COPY src/Heimdall.Application/*.csproj src/Heimdall.Application/
|
||||
COPY src/Heimdall.Infrastructure/*.csproj src/Heimdall.Infrastructure/
|
||||
COPY src/Heimdall.Web/*.csproj src/Heimdall.Web/
|
||||
|
||||
RUN dotnet restore src/Heimdall.Web/Heimdall.Web.csproj
|
||||
|
||||
# Copy all source
|
||||
COPY src/ src/
|
||||
|
||||
# Build and publish — the Web project now includes Web UI, REST API, and background jobs
|
||||
RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release -o /app -p:Version=$VERSION
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e
|
||||
WORKDIR /app
|
||||
|
||||
RUN apk add --no-cache icu-libs libstdc++ tzdata krb5
|
||||
|
||||
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \
|
||||
ASPNETCORE_URLS=http://+:8080
|
||||
|
||||
COPY --from=build /app .
|
||||
COPY --from=build /app/wwwroot ./wwwroot
|
||||
|
||||
RUN apt-get update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
|
||||
&& apt_version="$(dpkg-query -W -f='${Version}' apt)" \
|
||||
&& dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends wget tzdata tesseract-ocr tesseract-ocr-eng \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
ENV ASPNETCORE_URLS=http://+:8080
|
||||
COPY --from=build /out/ ./
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s CMD wget -q -O /dev/null http://localhost:8080/healthz || exit 1
|
||||
ENTRYPOINT ["dotnet", "Heimdall.Web.dll"]
|
||||
+30
-58
@@ -1,63 +1,35 @@
|
||||
# Build stage
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build
|
||||
# CPU agent: use glibc for ONNX native dependencies. GPU variants need a
|
||||
# separately validated .NET/native-library runtime and are not published here.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Version injectée par la CI (GitVersion.Agent.yml) — ex. docker build --build-arg VERSION=1.0.0
|
||||
ARG VERSION=0.0.0-local
|
||||
|
||||
COPY *.slnx .
|
||||
COPY Directory.Build.props .
|
||||
COPY src/Heimdall.Domain.Primitives/*.csproj src/Heimdall.Domain.Primitives/
|
||||
COPY src/Heimdall.Domain/*.csproj src/Heimdall.Domain/
|
||||
COPY src/Heimdall.Application/*.csproj src/Heimdall.Application/
|
||||
COPY src/Heimdall.Infrastructure/*.csproj src/Heimdall.Infrastructure/
|
||||
COPY src/Heimdall.Agent/*.csproj src/Heimdall.Agent/
|
||||
|
||||
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj
|
||||
|
||||
COPY src/ src/
|
||||
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release -o /app -p:Version=$VERSION
|
||||
|
||||
# Modèle YOLOv8n pré-converti en ONNX et committé dans le repo (voir models/)
|
||||
# (ultralytics ne distribue plus d'.onnx prêt ; torch/OpenCV s'installent mal en
|
||||
# CI — trop lent + deps libGL/libxcb absentes. On committe le .onnx une fois.)
|
||||
|
||||
# --- GPU Runtime variants (multi-arch, GPU-aware) ---
|
||||
# NVIDIA CUDA runtime (GPU acceleration for ONNX Runtime)
|
||||
FROM nvidia/cuda:12.6-runtime-ubuntu22.04 AS runtime-nvidia
|
||||
WORKDIR /app
|
||||
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/local/cuda/compat:$LD_LIBRARY_PATH
|
||||
|
||||
# AMD ROCm runtime (GPU acceleration for ONNX Runtime)
|
||||
FROM rocm/rocm-runtime:6.3.3-ubuntu22.04 AS runtime-amd
|
||||
WORKDIR /app
|
||||
ENV HSA_OVERRIDE_GFX_VERSION=10.3.0
|
||||
|
||||
# Intel VAAPI / iGPU runtime (GPU acceleration for ONNX Runtime via DirectML/OpenVINO)
|
||||
FROM intel/intel-extension-for-pytorch:2.3.0-ubuntu22.04 AS runtime-intel
|
||||
WORKDIR /app
|
||||
ENV LIBVA_DRIVER_NAME=iHD
|
||||
ENV LIBVA_DRIVERS_PATH=/usr/lib/x86_64-linux-gnu/dri
|
||||
|
||||
# CPU-only fallback (original alpine image)
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime-cpu
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache icu-libs libstdc++ ffmpeg krb5 wget
|
||||
|
||||
# Select runtime based on build argument (default: cpu)
|
||||
ARG TARGET_RUNTIME=cpu
|
||||
FROM runtime-${TARGET_RUNTIME} AS runtime
|
||||
RUN test "$TARGET_RUNTIME" = cpu
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
COPY src/ ./src/
|
||||
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e
|
||||
WORKDIR /app
|
||||
|
||||
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
|
||||
ENV ASPNETCORE_URLS=http://+:8080
|
||||
|
||||
COPY --from=build /app .
|
||||
# Modèle YOLOv8n ONNX committé dans le repo (contexte de build = racine repo)
|
||||
COPY models/yolov8n.onnx models/yolov8n.onnx
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
||||
CMD wget --no-verbose --tries=1 --spider http://localhost:8080/healthz || exit 1
|
||||
|
||||
ARG DOCKER_CLI_VERSION=29.9.3
|
||||
ARG DOCKER_CLI_SHA256=3fb5d1f13014c18cc54945bc177c58a9056a482dada031e17d12cf2e6922c973
|
||||
RUN apt-get update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
|
||||
&& apt_version="$(dpkg-query -W -f='${Version}' apt)" \
|
||||
&& dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends ca-certificates curl ffmpeg wget libgomp1 tzdata \
|
||||
&& curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
|
||||
"https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_CLI_VERSION}.tgz" -o /tmp/docker-cli.tgz \
|
||||
&& echo "${DOCKER_CLI_SHA256} /tmp/docker-cli.tgz" | sha256sum --check \
|
||||
&& tar -xzf /tmp/docker-cli.tgz -C /tmp docker/docker \
|
||||
&& install -m 0755 /tmp/docker/docker /usr/local/bin/docker \
|
||||
&& rm -rf /tmp/docker /tmp/docker-cli.tgz /var/lib/apt/lists/*
|
||||
RUN install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
|
||||
ENV ASPNETCORE_URLS=http://127.0.0.1:8080
|
||||
COPY --from=build /out/ ./
|
||||
COPY models/yolov8n.onnx ./models/yolov8n.onnx
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
|
||||
USER 1654:1654
|
||||
ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"]
|
||||
@@ -0,0 +1,43 @@
|
||||
# Optional NVIDIA Agent image. ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9.
|
||||
# NVIDIA amd64 runtime image digest is pinned; it includes CUDA 12.8.1/cuDNN 9.8.0.87.
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0-noble@sha256:fe0fd4e93bd2fbb47c883b7a6369e5c8d3db8bf01cdc5981f6ee35fbdf3ff4fb AS build
|
||||
WORKDIR /src
|
||||
ARG VERSION=0.0.0-local
|
||||
COPY global.json Directory.Build.props Directory.Build.targets ./
|
||||
COPY src/ ./src/
|
||||
RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj -p:HeimdallOnnxRuntime=GPU --locked-mode
|
||||
RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release --no-restore -o /out \
|
||||
-p:HeimdallOnnxRuntime=GPU -p:Version=$VERSION -p:ContinuousIntegrationBuild=true
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble@sha256:bfd912c83295ce66d4b706ebb8541b9f14259b0e76fbb88b2751f58ce2399d2e AS dotnet-runtime
|
||||
|
||||
FROM nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9 AS runtime
|
||||
WORKDIR /app
|
||||
ARG DOCKER_CLI_VERSION=29.9.3
|
||||
ARG DOCKER_CLI_SHA256=3fb5d1f13014c18cc54945bc177c58a9056a482dada031e17d12cf2e6922c973
|
||||
ENV DOTNET_ROOT=/usr/share/dotnet \
|
||||
PATH=/usr/share/dotnet:$PATH \
|
||||
LD_LIBRARY_PATH=/usr/local/cuda/lib64:/usr/lib/x86_64-linux-gnu \
|
||||
ASPNETCORE_URLS=http://127.0.0.1:8080 \
|
||||
Agent__InferenceExecutionProvider=CUDA
|
||||
RUN apt-get update -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -qq \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends --only-upgrade apt libapt-pkg6.0t64 \
|
||||
&& apt_version="$(dpkg-query -W -f='${Version}' apt)" \
|
||||
&& dpkg --compare-versions "$apt_version" ge 2.8.4ubuntu0.1 \
|
||||
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl ffmpeg libgomp1 libicu74 libssl3t64 tzdata wget zlib1g \
|
||||
&& curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
|
||||
"https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_CLI_VERSION}.tgz" -o /tmp/docker-cli.tgz \
|
||||
&& echo "${DOCKER_CLI_SHA256} /tmp/docker-cli.tgz" | sha256sum --check \
|
||||
&& tar -xzf /tmp/docker-cli.tgz -C /tmp docker/docker \
|
||||
&& install -m 0755 /tmp/docker/docker /usr/local/bin/docker \
|
||||
&& rm -rf /tmp/docker /tmp/docker-cli.tgz /var/lib/apt/lists/* \
|
||||
&& install -d -m 0700 -o 1654 -g 1654 /var/lib/heimdall
|
||||
COPY --from=dotnet-runtime /usr/share/dotnet/ /usr/share/dotnet/
|
||||
COPY --from=build /out/ ./
|
||||
COPY models/yolov8n.onnx ./models/yolov8n.onnx
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
|
||||
USER 1654:1654
|
||||
ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"]
|
||||
+178
-55
@@ -1,35 +1,38 @@
|
||||
# Heimdall — Backup & Restore
|
||||
|
||||
Sauvegarde automatisée de PostgreSQL (quotidien) et Alarik/S3 (hebdomadaire) avec test de restauration.
|
||||
Sauvegarde automatisée de PostgreSQL (quotidien) et RustFS/S3 (hebdomadaire) avec test de restauration.
|
||||
|
||||
## Vue d'ensemble
|
||||
|
||||
| Composant | Fréquence | Script | Rétention |
|
||||
|---|---|---|---|
|
||||
| PostgreSQL `pg_dump` | Quotidien 02:00 UTC | `docker/scripts/backup.sh` | 30 jours (local) + 30 jours (S3) |
|
||||
| Alarik `mc mirror` | Hebdo dimanche 03:00 UTC | `docker/scripts/backup-alarik.sh` | 12 semaines |
|
||||
| RustFS `mc mirror` | Hebdo dimanche 03:00 UTC | `docker/scripts/backup-rustfs.sh` | 12 semaines |
|
||||
| Volume Central (objets locaux + clés Data Protection) | Quotidien 02:15 UTC | `docker/scripts/backup-protected-data.sh` | 30 jours (local); cycle S3 selon la politique de bucket |
|
||||
| Test de restauration | Manuel / CI | `docker/scripts/test-backup-restore.sh` | — |
|
||||
|
||||
## Activation
|
||||
|
||||
### Option 1 — Overlay docker-compose (recommandé)
|
||||
### Compose facultatif séparé
|
||||
|
||||
```bash
|
||||
cd docker/
|
||||
docker compose -f docker-compose.yml -f docker-compose.backup.yml up -d
|
||||
docker compose --env-file .env -f docker-compose.backup.yml up -d
|
||||
```
|
||||
|
||||
Le service `backup` tourne dans un conteneur PostgreSQL 17-alpine avec crontab interne.
|
||||
Les dumps sont stockés dans le volume `backup_data` et uploadés vers Alarik/S3 si configuré.
|
||||
|
||||
### Option 2 — Profil dans docker-compose.prod.yml
|
||||
|
||||
```bash
|
||||
cd docker/
|
||||
docker compose --profile backup -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
Le service backup est activé via le profil Docker Compose `backup`.
|
||||
Le Central et PostgreSQL doivent d'abord être démarrés. Le service `backup`
|
||||
rejoint le réseau partagé et tourne dans un conteneur PostgreSQL 17-alpine
|
||||
avec crontab interne, AWS CLI et GNU coreutils (pour le calcul portable des seuils
|
||||
de rétention Alpine). Les dumps sont stockés dans `backup_data`; l'upload
|
||||
RustFS/S3 est facultatif.
|
||||
Le service monte aussi le volume `heimdall_data` du Compose Central : les
|
||||
objets stockés localement et les clés Data Protection sont archivés ensemble.
|
||||
Le nom par défaut est `docker_heimdall_data`, pour le projet Compose du dépôt.
|
||||
Si Central utilise un autre nom de projet ou un nom explicite, définir
|
||||
`HEIMDALL_DATA_VOLUME` avec le nom Docker exact dans l'environnement du Compose
|
||||
backup. Le volume est externe pour éviter de créer silencieusement une copie vide.
|
||||
La sauvegarde S3 de ce volume est activée seulement si les identifiants S3 sont
|
||||
configurés. Garder l’application Central arrêtée pendant une restauration.
|
||||
|
||||
## Variables d'environnement
|
||||
|
||||
@@ -39,13 +42,13 @@ Le service backup est activé via le profil Docker Compose `backup`.
|
||||
| `POSTGRES_PORT` | `5432` | Port PostgreSQL |
|
||||
| `POSTGRES_DB` | `heimdall` | Nom de la base |
|
||||
| `POSTGRES_USER` | `heimdall` | Utilisateur PostgreSQL |
|
||||
| `POSTGRES_PASSWORD` | `heimdall` | Mot de passe PostgreSQL |
|
||||
| `ALARIK_ENDPOINT` | — | Endpoint S3/Alarik (ex: `http://alarik:9000`) |
|
||||
| `ALARIK_ACCESS_KEY` | — | Clé d'accès S3 |
|
||||
| `ALARIK_SECRET_KEY` | — | Clé secrète S3 |
|
||||
| `ALARIK_BUCKET` | `heimdall` | Bucket S3 |
|
||||
| `docker/secrets/db_password` | fichier hôte requis | Mot de passe PostgreSQL partagé avec le Compose Central |
|
||||
| `RUSTFS_ENDPOINT` | `http://rustfs:9000` (Compose) | Endpoint S3/RustFS |
|
||||
| `RUSTFS_ACCESS_KEY` | — | Clé d'accès S3 |
|
||||
| `RUSTFS_SECRET_KEY` | — | Clé secrète S3 |
|
||||
| `RUSTFS_BUCKET` | `heimdall` | Bucket S3 |
|
||||
| `BACKUP_RETENTION_DAYS` | `30` | Rétention jours (PostgreSQL) |
|
||||
| `BACKUP_RETENTION_WEEKS` | `12` | Rétention semaines (Alarik) |
|
||||
| `BACKUP_RETENTION_WEEKS` | `12` | Rétention semaines (RustFS) |
|
||||
| `BACKUP_LOCAL_DIR` | `/backups` | Répertoire local dans le conteneur |
|
||||
|
||||
## Structure des backups
|
||||
@@ -62,10 +65,10 @@ s3://heimdall/backup/postgresql/
|
||||
└── ...
|
||||
```
|
||||
|
||||
### Alarik (S3 mirror)
|
||||
### RustFS (S3 mirror)
|
||||
|
||||
```
|
||||
s3://heimdall/backup/alarik/
|
||||
s3://heimdall/backup/rustfs/
|
||||
├── 2026-W35/
|
||||
│ ├── MANIFEST.txt
|
||||
│ ├── snapshots/...
|
||||
@@ -80,45 +83,141 @@ s3://heimdall/backup/alarik/
|
||||
### Lancer un backup PostgreSQL
|
||||
|
||||
```bash
|
||||
# Depuis l'hôte (avec accès docker)
|
||||
docker exec heimdall-backup /scripts/backup.sh
|
||||
# Depuis la racine du dépôt
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup /scripts/backup.sh
|
||||
|
||||
# Dry-run
|
||||
docker exec heimdall-backup /scripts/backup.sh --dry-run
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup /scripts/backup.sh --dry-run
|
||||
```
|
||||
|
||||
### Lancer un mirror Alarik
|
||||
### Lancer un mirror RustFS
|
||||
|
||||
```bash
|
||||
docker exec heimdall-backup /scripts/backup-alarik.sh
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup /scripts/backup-rustfs.sh
|
||||
|
||||
# Archiver le volume des objets locaux et des clés Data Protection
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup /scripts/backup-protected-data.sh
|
||||
```
|
||||
|
||||
### Restaurer PostgreSQL
|
||||
|
||||
```bash
|
||||
# Depuis un fichier local
|
||||
docker exec heimdall-backup /scripts/restore.sh --file /backups/postgresql/latest.sql.gz --yes
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup /scripts/restore.sh --file /backups/postgresql/latest.sql.gz --yes
|
||||
|
||||
# Depuis S3
|
||||
docker exec heimdall-backup /scripts/restore.sh --latest --yes
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup /scripts/restore.sh --latest --yes
|
||||
|
||||
# Dry-run
|
||||
docker exec heimdall-backup /scripts/restore.sh --latest --dry-run
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup /scripts/restore.sh --latest --dry-run
|
||||
```
|
||||
|
||||
### Restaurer les objets locaux et les clés Data Protection
|
||||
|
||||
```bash
|
||||
# Depuis le dossier d'installation généré par install/install-server.sh
|
||||
INSTALL_DIR="$HOME/heimdall"
|
||||
CORE=(docker compose --env-file "$INSTALL_DIR/.env" -f "$INSTALL_DIR/docker-compose.yml")
|
||||
BACKUP=(docker compose --project-name heimdall-backup --env-file "$INSTALL_DIR/.env" -f "$INSTALL_DIR/optional/docker-compose.backup.yml")
|
||||
|
||||
# Arrêter Central avant de modifier son volume partagé
|
||||
"${CORE[@]}" stop heimdall
|
||||
|
||||
# Restaurer un archive locale ou téléchargée depuis backup/protected-data/
|
||||
"${BACKUP[@]}" exec backup \
|
||||
/scripts/restore-protected-data.sh \
|
||||
--file /backups/protected-data/heimdall-data-TIMESTAMP.tar.gz
|
||||
|
||||
"${CORE[@]}" start heimdall
|
||||
```
|
||||
|
||||
L'installateur copie les scripts et le Compose backup dans `optional/` et crée
|
||||
le secret PostgreSQL dans `optional/secrets/`. Ces chemins relatifs sont résolus
|
||||
par rapport au Compose backup. Il fixe le projet Central à `heimdall` et configure
|
||||
le volume partagé dans `.env`; utilisez donc ce fichier `.env` et ces fichiers
|
||||
Compose générés pour les opérations. N'effacez pas un volume Docker pour lancer
|
||||
une restauration : `restore.sh` recrée la base dans le volume existant.
|
||||
|
||||
Pour une reprise complète, restaurer PostgreSQL et le volume protégé depuis les
|
||||
sauvegardes les plus proches, puis démarrer Central. Ces sauvegardes sont prises
|
||||
séparément : l'application ne fournit pas de snapshot atomique entre PostgreSQL
|
||||
et les fichiers. Vérifier les événements récents et les références d'objets après
|
||||
reprise, et conserver les archives précédentes jusqu'à cette vérification.
|
||||
|
||||
Le script valide l’archive, refuse les chemins et liens dangereux, puis restaure
|
||||
les fichiers en superposition; les fichiers présents uniquement dans le volume
|
||||
ne sont pas supprimés. L’archive contient le répertoire `dp-keys`, dont
|
||||
`dp-cert.pfx` protège les clés Data Protection. Protéger les sauvegardes locales
|
||||
et S3 comme des données sensibles.
|
||||
|
||||
### Conservation et rotation des clés Data Protection
|
||||
|
||||
Le volume Central contient le trousseau XML Data Protection et `dp-cert.pfx`,
|
||||
qui protège ces clés au repos. L’archive de données protégées doit conserver
|
||||
l’ensemble de `dp-keys`; restaurer PostgreSQL sans ce répertoire peut laisser
|
||||
les identifiants et autres charges utiles protégées impossibles à relire.
|
||||
|
||||
- Arrêter Central avant la restauration et restaurer l’archive protégée complète
|
||||
dans le volume correspondant. Ne remplacer ni supprimer `dp-cert.pfx` ou des
|
||||
fichiers de clés indépendamment.
|
||||
- Garder les archives comme des secrets : `dp-cert.pfx` contient la clé privée
|
||||
qui déchiffre le trousseau. Le script crée l’archive locale avec le mode
|
||||
`0600`; contrôler aussi les permissions et l’accès du bucket S3.
|
||||
- Le framework fait évoluer automatiquement le trousseau selon sa politique de
|
||||
durée de vie. Les clés expirées restent nécessaires pour lire les données
|
||||
protégées avec ces clés; ne pas purger les anciennes clés au seul motif
|
||||
qu’elles ont expiré.
|
||||
- Le certificat de protection `dp-cert.pfx` n’a pas de procédure de rotation
|
||||
manuelle validée dans Heimdall. Ne pas le remplacer lors d’une restauration.
|
||||
Toute rotation planifiée doit faire l’objet d’une procédure séparée et d’un
|
||||
essai sur copie isolée, avec vérification de lecture des anciennes et nouvelles
|
||||
charges utiles avant suppression de la clé précédente.
|
||||
|
||||
Voir [la gestion des clés Data Protection dans ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/implementation/key-management)
|
||||
pour le cycle des clés; supprimer une clé qui protège encore des données rend
|
||||
ces données définitivement illisibles.
|
||||
|
||||
### Mesure RPO/RTO
|
||||
|
||||
Les horaires configurés ne constituent pas une mesure de RPO. Les sauvegardes
|
||||
PostgreSQL et du volume protégé sont prises séparément, et le miroir RustFS suit
|
||||
un autre intervalle; Heimdall ne fournit pas de point de restauration atomique.
|
||||
Le responsable d’exploitation doit définir les objectifs visés et le scénario
|
||||
avant un exercice réel.
|
||||
|
||||
Pour chaque exercice autorisé, consigner sans données personnelles :
|
||||
|
||||
1. La date UTC du changement connu le plus récent dans chaque stockage, la date
|
||||
de la panne simulée, et la date du changement le plus récent réellement
|
||||
restauré. Calculer le RPO séparément pour PostgreSQL, objets locaux/S3 et
|
||||
clés protégées; retenir le pire résultat pour le service.
|
||||
2. L’heure de début de la restauration, ses jalons (base, objets, démarrage de
|
||||
Central) et l’heure où les vérifications post-restauration réussissent. Cette
|
||||
durée est le RTO mesuré pour cet essai, pas un engagement universel.
|
||||
3. Versions des scripts/images, tailles et nombres d’objets, hôte/CPU/mémoire,
|
||||
stockage et réseau utilisés, étapes manuelles, erreurs et résultat final.
|
||||
Répéter l’exercice complet au moins deux fois avant de fixer une cible.
|
||||
|
||||
La recette synthétique de `test-backup-restore.sh` ne comprend pas le démarrage
|
||||
de Central, une connexion utilisateur ni un backend S3; son temps d’exécution
|
||||
ne doit jamais être présenté comme un RTO de production.
|
||||
|
||||
## Test de restauration (runbook)
|
||||
|
||||
### Prérequis
|
||||
|
||||
- Docker
|
||||
- Le stack Heimdall est à jour (`docker compose up -d`)
|
||||
- Docker avec le daemon démarré
|
||||
- `bash`, `gzip` et `tar` (disponibles sur Linux)
|
||||
|
||||
Le test crée son propre conteneur PostgreSQL isolé et un répertoire temporaire.
|
||||
Il ne nécessite ni serveur Heimdall démarré, ni accès au réseau applicatif.
|
||||
|
||||
### Procédure
|
||||
|
||||
```bash
|
||||
cd docker/scripts/
|
||||
|
||||
# 1. Lancer le test (crée un PG isolé, seed, dump, drop, restore, vérifie)
|
||||
# 1. Lancer le test (crée un PG isolé et un volume de fichiers temporaire)
|
||||
./test-backup-restore.sh
|
||||
|
||||
# Résultat attendu : All tests PASSED ✅
|
||||
@@ -128,51 +227,75 @@ Le script teste :
|
||||
|
||||
1. **Création d'un dump** — pg_dump --format=custom --compress=9
|
||||
2. **Drop + recreate** de la base de test
|
||||
3. **Restauration** via pg_restore
|
||||
4. **Vérification** :
|
||||
3. **Restauration** via pg_restore (toute erreur fait échouer le test)
|
||||
4. **Archive et restauration du volume protégé** dans un répertoire isolé, avec objet local et clé Data Protection de test
|
||||
5. **Vérification** :
|
||||
- Nombre de sites identique
|
||||
- Nombre de caméras identique
|
||||
- Nombre d'événements identique
|
||||
- Noms et URLs préservés (intégrité des données)
|
||||
- Absence de violations de clés étrangères
|
||||
- Objet local et clé Data Protection restaurés avec leurs permissions
|
||||
|
||||
### Mode sans cleanup
|
||||
|
||||
```bash
|
||||
./test-backup-restore.sh --no-cleanup
|
||||
# Le conteneur de test reste actif sur le port 15432
|
||||
# Utile pour inspection manuelle
|
||||
# Le conteneur, le réseau et le répertoire temporaire restent disponibles
|
||||
# Les noms exacts sont imprimés pour inspection manuelle
|
||||
```
|
||||
|
||||
### Restauration complète (runbook DR)
|
||||
|
||||
En cas de disaster recovery :
|
||||
En cas de reprise après sinistre sur une installation créée par
|
||||
`install/install-server.sh`, renseigner le chemin réel de l'installation. Le
|
||||
fichier `.env` généré garde le nom du volume des objets et des clés Data
|
||||
Protection; le nom du volume PostgreSQL est `heimdall_pgdata` avec le Compose
|
||||
généré (le nom peut différer sur les installations personnalisées).
|
||||
|
||||
```bash
|
||||
# 1. Arrêter le stack
|
||||
cd docker/
|
||||
docker compose down
|
||||
INSTALL_DIR="$HOME/heimdall"
|
||||
CORE=(docker compose --env-file "$INSTALL_DIR/.env" -f "$INSTALL_DIR/docker-compose.yml")
|
||||
BACKUP=(docker compose --project-name heimdall-backup --env-file "$INSTALL_DIR/.env" -f "$INSTALL_DIR/optional/docker-compose.backup.yml")
|
||||
|
||||
# 2. Supprimer les données corrompues
|
||||
docker volume rm docker_pgdata
|
||||
# 1. Arrêter l'application pendant la restauration
|
||||
"${CORE[@]}" stop heimdall
|
||||
|
||||
# 3. Redémarrer PostgreSQL seul
|
||||
docker compose up -d postgresql
|
||||
sleep 10
|
||||
# 2. Démarrer PostgreSQL puis le service de backup sur le réseau partagé
|
||||
"${CORE[@]}" up -d postgresql
|
||||
"${BACKUP[@]}" up -d backup
|
||||
|
||||
# 4. Restaurer depuis S3 (latest)
|
||||
docker compose run --rm backup /scripts/restore.sh --latest --yes
|
||||
# 3. Restaurer la base depuis le dernier backup
|
||||
"${BACKUP[@]}" exec backup /scripts/restore.sh --latest --yes
|
||||
|
||||
# 5. Redémarrer tout le stack
|
||||
docker compose up -d
|
||||
# 4. Restaurer séparément les fichiers protégés si nécessaire
|
||||
# Pour une archive S3, la télécharger d'abord sur l'hôte avec l'outil S3
|
||||
# configuré, puis la copier dans le volume local des sauvegardes.
|
||||
ARCHIVE="$HOME/restore/heimdall-data-TIMESTAMP.tar.gz"
|
||||
BACKUP_CONTAINER="$("${BACKUP[@]}" ps -q backup)"
|
||||
docker exec "$BACKUP_CONTAINER" mkdir -p /backups/protected-data
|
||||
docker cp "$ARCHIVE" "$BACKUP_CONTAINER:/backups/protected-data/"
|
||||
"${BACKUP[@]}" exec backup /scripts/restore-protected-data.sh \
|
||||
--file /backups/protected-data/heimdall-data-TIMESTAMP.tar.gz --yes
|
||||
|
||||
# 5. Redémarrer Central
|
||||
"${CORE[@]}" up -d heimdall
|
||||
|
||||
# 6. Vérifier
|
||||
# - Sites accessibles via l'UI
|
||||
# - Agents connectés (heartbeat)
|
||||
# - Événements présents
|
||||
# - Snapshots accessibles dans Alarik
|
||||
# - Snapshots accessibles dans RustFS
|
||||
```
|
||||
|
||||
Ne supprimez pas `heimdall_pgdata` avant la restauration : le script supprime et
|
||||
recrée uniquement la base cible dans PostgreSQL. Si une réinitialisation du
|
||||
volume est réellement nécessaire, identifier le nom exact avec
|
||||
`docker volume ls` et vérifier deux fois qu'une sauvegarde exploitable existe.
|
||||
Pour une installation dont l'installateur ou le Compose a été déplacé ou
|
||||
personnalisé, adapter `INSTALL_DIR`, les fichiers Compose et le nom de volume à
|
||||
la configuration effective; ne pas supposer le préfixe `docker_`.
|
||||
|
||||
### Vérification post-restauration
|
||||
|
||||
| Check | Commande |
|
||||
@@ -180,7 +303,7 @@ docker compose up -d
|
||||
| Sites | `curl -s http://localhost:5000/api/sites -H "Authorization: Bearer $TOKEN" \| jq '.[].name'` |
|
||||
| Agents | `curl -s http://localhost:5000/api/agents -H "Authorization: Bearer $TOKEN" \| jq '.[].name'` |
|
||||
| Événements | `curl -s "http://localhost:5000/api/cameras/{id}/events" -H "Authorization: Bearer $TOKEN" \| jq 'length'` |
|
||||
| Alarik | Ouvrir `http://localhost:9001` — vérifier les snapshots |
|
||||
| RustFS | Ouvrir `http://localhost:9001` — vérifier les snapshots |
|
||||
|
||||
## Logs
|
||||
|
||||
@@ -188,10 +311,10 @@ Les logs backup sont disponibles dans le conteneur :
|
||||
|
||||
```bash
|
||||
# Dernière exécution
|
||||
docker exec heimdall-backup cat /var/log/backup.log
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup cat /var/log/backup.log
|
||||
|
||||
# Historique (rotation hebdomadaire)
|
||||
docker exec heimdall-backup ls -la /var/log/backup.log*
|
||||
docker compose -f docker/docker-compose.backup.yml exec backup ls -la /var/log/backup.log*
|
||||
```
|
||||
|
||||
## Pièges
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Optional development overlay. The default dev Compose remains CPU-only.
|
||||
services:
|
||||
heimdall-agent:
|
||||
platform: linux/amd64
|
||||
profiles:
|
||||
- gpu-nvidia
|
||||
image: heimdall-agent:gpu-local
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent.gpu
|
||||
environment:
|
||||
Agent__InferenceExecutionProvider: CUDA
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
|
||||
agent-state-init:
|
||||
image: heimdall-agent:gpu-local
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent.gpu
|
||||
@@ -0,0 +1,47 @@
|
||||
# Local standalone Agent for development. The Central must be running first.
|
||||
services:
|
||||
heimdall-agent:
|
||||
image: heimdall-agent:local
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
restart: unless-stopped
|
||||
user: "1654:1654"
|
||||
group_add:
|
||||
- "${DOCKER_GID:-0}"
|
||||
network_mode: host
|
||||
environment:
|
||||
ASPNETCORE_URLS: http://127.0.0.1:8081
|
||||
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://localhost:5000}
|
||||
Agent__PublicIpResolverUrl: ${HEIMDALL_PUBLIC_IP_RESOLVER_URL:-}
|
||||
Agent__AllowInsecureHttp: "true"
|
||||
Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required}
|
||||
Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-dev}
|
||||
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
depends_on:
|
||||
agent-state-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
agent-state-init:
|
||||
image: heimdall-agent:local
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
user: "0:0"
|
||||
entrypoint: ["chown", "-R", "1654:1654", "/state"]
|
||||
volumes:
|
||||
- agent_state:/state
|
||||
restart: "no"
|
||||
|
||||
volumes:
|
||||
agent_state:
|
||||
@@ -1,70 +1,55 @@
|
||||
# ─── Heimdall — Backup Cron Service ──────────────────────────────
|
||||
# Overlay for docker-compose.yml: adds a cron container that runs
|
||||
# PostgreSQL backups daily and Alarik mirrors weekly.
|
||||
#
|
||||
# Usage:
|
||||
# docker compose -f docker/docker-compose.yml -f docker/docker-compose.backup.yml up -d
|
||||
#
|
||||
# The cron service mounts the scripts directory and a backup volume.
|
||||
# PostgreSQL dumps are uploaded to Alarik/S3 when configured.
|
||||
#
|
||||
# Requires: .env with DATABASE_URL, S3 credentials (optional for local-only backups)
|
||||
# ──────────────────────────────────────────────────────────────────
|
||||
# Optional scheduled backup container. Requires the core PostgreSQL service
|
||||
# and its shared heimdall-net to be running first.
|
||||
services:
|
||||
backup:
|
||||
image: postgres:17-alpine
|
||||
container_name: heimdall-backup
|
||||
pull_policy: always
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
# Pass through all env vars needed by backup scripts
|
||||
POSTGRES_HOST: postgresql
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DB: ${POSTGRES_DB:-heimdall}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-heimdall}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required}
|
||||
# S3/Alarik config (optional — backup works local-only without these)
|
||||
ALARIK_ENDPOINT: ${ALARIK_ENDPOINT:-}
|
||||
ALARIK_ACCESS_KEY: ${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}
|
||||
ALARIK_SECRET_KEY: ${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}
|
||||
ALARIK_BUCKET: ${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}
|
||||
# Backup config
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||
RUSTFS_ENDPOINT: ${RUSTFS_ENDPOINT:-http://rustfs:9000}
|
||||
RUSTFS_ACCESS_KEY: ${RUSTFS_ACCESS_KEY:-}
|
||||
RUSTFS_SECRET_KEY: ${RUSTFS_SECRET_KEY:-}
|
||||
RUSTFS_BUCKET: ${RUSTFS_BUCKET:-heimdall}
|
||||
BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-30}
|
||||
BACKUP_RETENTION_WEEKS: ${BACKUP_RETENTION_WEEKS:-12}
|
||||
BACKUP_LOCAL_DIR: /backups
|
||||
# Timezone
|
||||
TZ: Europe/Paris
|
||||
TZ: ${TZ:-Europe/Paris}
|
||||
secrets:
|
||||
- db_password
|
||||
volumes:
|
||||
- ./scripts:/scripts:ro
|
||||
- backup_data:/backups
|
||||
depends_on:
|
||||
postgresql:
|
||||
condition: service_healthy
|
||||
- heimdall_data:/source/heimdall_data
|
||||
networks:
|
||||
- heimdall-net
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
# Install mc (MinIO client) for S3 uploads
|
||||
apk add --no-cache curl bash > /dev/null 2>&1 || true
|
||||
curl -sSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc 2>/dev/null || true
|
||||
chmod +x /usr/local/bin/mc 2>/dev/null || true
|
||||
chmod +x /scripts/*.sh
|
||||
|
||||
# Create crontab
|
||||
echo "# Daily PostgreSQL backup at 02:00 UTC" > /tmp/crontab.txt
|
||||
echo "0 2 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1" >> /tmp/crontab.txt
|
||||
echo "# Weekly Alarik mirror on Sundays at 03:00 UTC" >> /tmp/crontab.txt
|
||||
echo "0 3 * * 0 /scripts/backup-alarik.sh >> /var/log/backup-alarik.log 2>&1" >> /tmp/crontab.txt
|
||||
echo "# Log rotation weekly" >> /tmp/crontab.txt
|
||||
echo "0 4 * * 0 if [ -f /var/log/backup.log ]; then mv /var/log/backup.log /var/log/backup.log.\$$(date +\%Y\%W); fi" >> /tmp/crontab.txt
|
||||
|
||||
set -e
|
||||
export POSTGRES_PASSWORD="$$(cat /run/secrets/db_password)"
|
||||
apk add --no-cache aws-cli bash coreutils
|
||||
echo '0 2 * * * bash /scripts/backup.sh >> /var/log/backup.log 2>&1' > /tmp/crontab.txt
|
||||
echo '15 2 * * * bash /scripts/backup-protected-data.sh >> /var/log/backup-protected-data.log 2>&1' >> /tmp/crontab.txt
|
||||
echo '0 3 * * 0 bash /scripts/backup-rustfs.sh >> /var/log/backup-rustfs.log 2>&1' >> /tmp/crontab.txt
|
||||
crontab /tmp/crontab.txt
|
||||
echo "Crontab installed:"
|
||||
crontab -l
|
||||
|
||||
# Run crond in foreground
|
||||
exec crond -f -l 2
|
||||
|
||||
volumes:
|
||||
backup_data:
|
||||
driver: local
|
||||
heimdall_data:
|
||||
external: true
|
||||
name: ${HEIMDALL_DATA_VOLUME:-docker_heimdall_data}
|
||||
|
||||
secrets:
|
||||
db_password:
|
||||
file: ./secrets/db_password
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
external: true
|
||||
@@ -0,0 +1,43 @@
|
||||
# Optional TURN relay, used only by a future/externally integrated WebRTC setup.
|
||||
services:
|
||||
coturn:
|
||||
image: coturn/coturn:4.6
|
||||
pull_policy: always
|
||||
# Local Compose secrets are read-only bind mounts and preserve the
|
||||
# installer's 0600 owner-only permissions. Read the mounted file as a
|
||||
# short-lived root initializer, write a private config into tmpfs, then
|
||||
# run turnserver as nobody. The upstream binary does not exec with a
|
||||
# reduced capability set; no-new-privileges still prevents elevation.
|
||||
user: "0:0"
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /run/coturn:rw,noexec,nosuid,nodev,size=1m,mode=0700
|
||||
ports:
|
||||
- "${COTURN_PORT:-3478}:3478/tcp"
|
||||
- "${COTURN_PORT:-3478}:3478/udp"
|
||||
- "${COTURN_RELAY_PORT_MIN:-49160}-${COTURN_RELAY_PORT_MAX:-49200}:${COTURN_RELAY_PORT_MIN:-49160}-${COTURN_RELAY_PORT_MAX:-49200}/udp"
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
set -eu;
|
||||
umask 077;
|
||||
printf 'use-auth-secret\nstatic-auth-secret=%s\nrealm=%s\nfingerprint\nno-tlsv1\nno-tlsv1_1\nlog-file=stdout\nno-cli\nlistening-port=3478\nmin-port=%s\nmax-port=%s\n'
|
||||
"$$(cat /run/secrets/coturn_secret)" "${COTURN_REALM:-heimdall.local}"
|
||||
"${COTURN_RELAY_PORT_MIN:-49160}" "${COTURN_RELAY_PORT_MAX:-49200}"
|
||||
> /run/coturn/turnserver.conf;
|
||||
printf 'pidfile=/run/coturn/turnserver.pid\n' >> /run/coturn/turnserver.conf;
|
||||
if [ -n "$$COTURN_EXTERNAL_IP" ]; then
|
||||
printf 'external-ip=%s\n' "$$COTURN_EXTERNAL_IP" >> /run/coturn/turnserver.conf;
|
||||
fi;
|
||||
chown 65534:65534 /run/coturn /run/coturn/turnserver.conf;
|
||||
exec su -s /bin/sh -c 'exec /usr/bin/turnserver -c /run/coturn/turnserver.conf' nobody
|
||||
environment:
|
||||
COTURN_EXTERNAL_IP: ${COTURN_EXTERNAL_IP:-}
|
||||
secrets:
|
||||
- coturn_secret
|
||||
restart: unless-stopped
|
||||
|
||||
secrets:
|
||||
coturn_secret:
|
||||
file: ./optional/secrets/coturn_secret
|
||||
@@ -0,0 +1,12 @@
|
||||
# Optional AMD device passthrough for Agent GPU inventory.
|
||||
# The current Agent image still runs ONNX inference on CPU.
|
||||
services:
|
||||
heimdall-agent:
|
||||
profiles:
|
||||
- gpu-amd-inventory
|
||||
devices:
|
||||
- /dev/kfd:/dev/kfd
|
||||
- /dev/dri:/dev/dri
|
||||
group_add:
|
||||
- "${VIDEO_GID:-44}"
|
||||
- "${RENDER_GID:-109}"
|
||||
@@ -0,0 +1,11 @@
|
||||
# Optional Intel render-device passthrough for Agent GPU inventory.
|
||||
# The current Agent image still runs ONNX inference on CPU.
|
||||
services:
|
||||
heimdall-agent:
|
||||
profiles:
|
||||
- gpu-intel-inventory
|
||||
devices:
|
||||
- /dev/dri:/dev/dri
|
||||
group_add:
|
||||
- "${VIDEO_GID:-44}"
|
||||
- "${RENDER_GID:-109}"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Optional NVIDIA device passthrough for Agent GPU inventory on the published
|
||||
# CPU image. Use docker-compose.agent.dev.gpu-nvidia.yml for the CUDA image.
|
||||
services:
|
||||
heimdall-agent:
|
||||
profiles:
|
||||
- gpu-nvidia-inventory
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
@@ -1,16 +0,0 @@
|
||||
# ─── Heimdall — Override: use locally-built image with current fixes ───
|
||||
# The Docker Hub image (eltruncho/heimdall:latest) is published by CI on
|
||||
# main pushes; until the fixes are pushed, deploy the local image instead.
|
||||
# Usage: docker compose --env-file docker/.env -f docker/docker-compose.prod.yml -f docker/docker-compose.local.yml up -d
|
||||
services:
|
||||
heimdall:
|
||||
image: heimdall:local
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
|
||||
heimdall-agent:
|
||||
image: heimdall-agent:local
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
@@ -0,0 +1,24 @@
|
||||
# Optional self-hosted ntfy service. Central's default URL is http://ntfy:80.
|
||||
services:
|
||||
ntfy:
|
||||
image: binwiederhier/ntfy:latest
|
||||
pull_policy: always
|
||||
restart: unless-stopped
|
||||
command: ["serve"]
|
||||
environment:
|
||||
TZ: ${TZ:-Europe/Paris}
|
||||
NTFY_AUTH_FILE: /var/lib/ntfy/auth
|
||||
ports:
|
||||
- "${NTFY_PORT:-8080}:80"
|
||||
volumes:
|
||||
- ntfy_data:/var/lib/ntfy
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
volumes:
|
||||
ntfy_data:
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
external: true
|
||||
@@ -0,0 +1,26 @@
|
||||
# Optional local Ollama backend. Configure http://ollama:11434 in Central settings.
|
||||
services:
|
||||
ollama:
|
||||
image: ollama/ollama:latest
|
||||
pull_policy: always
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${OLLAMA_PORT:-11434}:11434"
|
||||
volumes:
|
||||
- ollama_data:/root/.ollama
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:11434/api/tags"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
volumes:
|
||||
ollama_data:
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
external: true
|
||||
+28
-336
@@ -1,35 +1,17 @@
|
||||
# ─── Heimdall — Production Docker Compose ─────────────────────────
|
||||
# Pulls pre-built images from Docker Hub instead of building locally.
|
||||
# Usage: docker compose -f docker/docker-compose.prod.yml up -d
|
||||
# Prerequisite: cp .env.example .env && edit secrets
|
||||
#
|
||||
# Secrets are stored in docker/secrets/ (gitignored). Create them with:
|
||||
# mkdir -p docker/secrets
|
||||
# openssl rand -base64 32 > docker/secrets/jwt_signing_key
|
||||
# openssl rand -base64 32 > docker/secrets/jwt_refresh_key
|
||||
# openssl rand -base64 32 > docker/secrets/coturn_secret
|
||||
# echo -n "your-db-password" > docker/secrets/db_password
|
||||
# echo -n "your-alarik-admin-password" > docker/secrets/alarik_admin_password
|
||||
# echo -n "your-alarik-jwt" > docker/secrets/alarik_jwt
|
||||
# echo -n "your-smtp-password" > docker/secrets/smtp_password
|
||||
#
|
||||
# Images are published by the CI pipeline on main branch pushes:
|
||||
# eltruncho/heimdall:latest
|
||||
# eltruncho/heimdall-agent:latest
|
||||
#
|
||||
# The heimdall service serves the Blazor UI, REST API, SignalR hubs,
|
||||
# and Hangfire background jobs (heartbeat monitor, agent failover)
|
||||
# in a single process.
|
||||
# Production core: PostgreSQL and Heimdall Central only.
|
||||
# Usage: docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d
|
||||
# Optional software has its own Compose file; see docs/docker-compose.md.
|
||||
|
||||
x-logging: &default-logging
|
||||
driver: "json-file"
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
|
||||
services:
|
||||
postgresql:
|
||||
image: postgres:17-alpine
|
||||
pull_policy: always
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-heimdall}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-heimdall}
|
||||
@@ -51,88 +33,42 @@ services:
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
alarik:
|
||||
image: ghcr.io/achtungsoftware/alarik:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${ALARIK_API_PORT:-9000}:8080"
|
||||
environment:
|
||||
API_BASE_URL: ${ALARIK_API_BASE_URL:-http://localhost:9000}
|
||||
CONSOLE_BASE_URL: ${ALARIK_CONSOLE_BASE_URL:-http://localhost:9001}
|
||||
ADMIN_USERNAME: ${ALARIK_ADMIN_USERNAME:-heimdall}
|
||||
ADMIN_PASSWORD_FILE: /run/secrets/alarik_admin_password
|
||||
JWT_FILE: /run/secrets/alarik_jwt
|
||||
ALLOW_ACCOUNT_CREATION: false
|
||||
secrets:
|
||||
- alarik_admin_password
|
||||
- alarik_jwt
|
||||
volumes:
|
||||
- alarik_storage:/app/Storage
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
alarik-console:
|
||||
image: ghcr.io/achtungsoftware/alarik-console:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${ALARIK_CONSOLE_PORT:-9001}:3000"
|
||||
environment:
|
||||
NUXT_PUBLIC_API_BASE_URL: ${ALARIK_API_BASE_URL:-http://localhost:9000}
|
||||
NUXT_PUBLIC_CONSOLE_BASE_URL: ${ALARIK_CONSOLE_BASE_URL:-http://localhost:9001}
|
||||
NUXT_PUBLIC_ALLOW_ACCOUNT_CREATION: false
|
||||
depends_on:
|
||||
- alarik
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
heimdall:
|
||||
image: eltruncho/heimdall:latest
|
||||
pull_policy: always
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: "true"
|
||||
environment:
|
||||
# MassTransit / RabbitMQ
|
||||
RABBITMQ__HOST: rabbitmq
|
||||
RABBITMQ__PORT: "5672"
|
||||
RABBITMQ__USER: ${RABBITMQ_USER:-heimdall}
|
||||
RABBITMQ__PASSWORD_FILE: /run/secrets/rabbitmq_password
|
||||
# Database (password from secret, rest from env)
|
||||
DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required}
|
||||
# JWT (keys from secrets)
|
||||
JWT__Issuer: ${JWT__ISSUER:-heimdall}
|
||||
JWT__Audience: ${JWT__AUDIENCE:-heimdall-api}
|
||||
# ASP.NET
|
||||
JWT__KEY: ${JWT__KEY:?JWT__KEY is required}
|
||||
JWT__REFRESHKEY: ${JWT__REFRESHKEY:?JWT__REFRESHKEY is required}
|
||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production}
|
||||
ASPNETCORE_URLS: http://+:8080
|
||||
# CORS (for external agents and API clients)
|
||||
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
|
||||
# Monolith: internal HTTP calls (circuit-triggered) must target the
|
||||
# container's own listener, NOT the host-mapped origin the browser sees.
|
||||
API_BASE_URL: ${API_BASE_URL:-http://localhost:8080}
|
||||
# Ollama (optional — daily summaries)
|
||||
Ollama__Endpoint: http://ollama:11434
|
||||
# Coturn (WebRTC relay)
|
||||
Coturn__Url: turns:coturn:3478
|
||||
# Redis (SignalR backplane, optional — scaling)
|
||||
ConnectionStrings__Redis: redis:6379
|
||||
# Sentry / GlitchTip (error tracking)
|
||||
LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-}
|
||||
LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-}
|
||||
LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false}
|
||||
LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-}
|
||||
LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-}
|
||||
LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-}
|
||||
Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776}
|
||||
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
|
||||
Sentry__Dsn: ${SENTRY_DSN:-}
|
||||
Sentry__TracesSampleRate: ${SENTRY_TRACES_SAMPLE_RATE:-0.05}
|
||||
Sentry__Release: ${SENTRY_RELEASE:-}
|
||||
secrets:
|
||||
- jwt_signing_key
|
||||
- jwt_refresh_key
|
||||
ports:
|
||||
- "${WEB_PORT:-5000}:8080"
|
||||
volumes:
|
||||
- heimdall_data:/var/lib/heimdall
|
||||
- dataprotection_keys:/root/.aspnet/DataProtection-Keys
|
||||
# Local storage defaults to ./data/storage under /app; persist it in the same volume.
|
||||
- heimdall_data:/app/data
|
||||
depends_on:
|
||||
postgresql:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://127.0.0.1:8080/healthz"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
@@ -142,225 +78,12 @@ services:
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
ntfy:
|
||||
image: binwiederhier/ntfy:latest
|
||||
container_name: heimdall-ntfy
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- "serve"
|
||||
environment:
|
||||
- TZ=Europe/Paris
|
||||
- NTFY_AUTH_FILE=/var/lib/ntfy/auth
|
||||
watchtower:
|
||||
image: nickfedor/watchtower:1.23.2
|
||||
pull_policy: always
|
||||
command: ["--cleanup", "--label-enable", "--interval", "86400"]
|
||||
volumes:
|
||||
- ntfy_data:/var/lib/ntfy
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
heimdall-agent:
|
||||
# Versioned tag via AGENT_IMAGE_TAG env var (ticket #97)
|
||||
image: eltruncho/heimdall-agent:${AGENT_IMAGE_TAG:-latest}
|
||||
# Host network: the agent must see the real camera LAN to run discovery.
|
||||
# On a bridge network it only sees 172.x → the scanner skips (no local subnet).
|
||||
network_mode: host
|
||||
environment:
|
||||
# 8080 is taken by ntfy on the host → listen on 8081
|
||||
ASPNETCORE_URLS: http://+:8081
|
||||
# Host network: Docker DNS names don't resolve → point HEIMDALL_CENTRAL_URL
|
||||
# to the Central's public URL (e.g. https://heimdall.tordais.cc)
|
||||
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:?HEIMDALL_CENTRAL_URL is required (public URL of the Central, e.g. https://heimdall.tordais.cc)}
|
||||
Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required}
|
||||
Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01}
|
||||
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
# MassTransit / RabbitMQ — host network can't resolve Docker DNS
|
||||
RABBITMQ__HOST: ${RABBITMQ_HOST:-localhost}
|
||||
RABBITMQ__PORT: ${RABBITMQ_PORT:-5672}
|
||||
RABBITMQ__USER: ${RABBITMQ_USER:-heimdall}
|
||||
RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required}
|
||||
# ONNX Runtime GPU provider selection
|
||||
ORT_PROVIDER: ${AGENT_ORT_PROVIDER:-CUDA}
|
||||
ORT_CUDA_DEVICE_ID: ${AGENT_CUDA_DEVICE_ID:-0}
|
||||
# GPU device exposure (NVIDIA CUDA, AMD ROCm, Intel VAAPI/iGPU)
|
||||
# Override in docker-compose.local.yml for specific GPU hardware:
|
||||
# deploy:
|
||||
# resources:
|
||||
# reservations:
|
||||
# devices:
|
||||
# - driver: nvidia
|
||||
# count: 1
|
||||
# capabilities: [gpu]
|
||||
# Or for AMD ROCm:
|
||||
# devices:
|
||||
# - /dev/kfd:/dev/kfd
|
||||
# - /dev/dri:/dev/dri
|
||||
# Or for Intel iGPU/VAAPI:
|
||||
# devices:
|
||||
# - /dev/dri:/dev/dri
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities: [gpu]
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8081/healthz"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
depends_on:
|
||||
- heimdall
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
# no networks: host networking
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:3-management
|
||||
hostname: rabbitmq
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-heimdall}
|
||||
RABBITMQ_DEFAULT_PASS_FILE: /run/secrets/rabbitmq_password
|
||||
secrets:
|
||||
- rabbitmq_password
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
# ── Backup service (opt-in via --profile backup) ───────────────
|
||||
|
||||
backup:
|
||||
image: postgres:17-alpine
|
||||
container_name: heimdall-backup
|
||||
profiles:
|
||||
- backup
|
||||
environment:
|
||||
POSTGRES_HOST: postgresql
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DB: ${POSTGRES_DB:-heimdall}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-heimdall}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||
# S3/Alarik config (optional — backup works local-only without these)
|
||||
ALARIK_ENDPOINT: ${ALARIK_ENDPOINT:-}
|
||||
ALARIK_ACCESS_KEY: ${ALARIK_ACCESS_KEY:-}
|
||||
ALARIK_SECRET_KEY: ${ALARIK_SECRET_KEY:-}
|
||||
ALARIK_BUCKET: ${ALARIK_BUCKET:-heimdall}
|
||||
# Backup config
|
||||
BACKUP_RETENTION_DAYS: ${BACKUP_RETENTION_DAYS:-30}
|
||||
BACKUP_RETENTION_WEEKS: ${BACKUP_RETENTION_WEEKS:-12}
|
||||
BACKUP_LOCAL_DIR: /backups
|
||||
TZ: Europe/Paris
|
||||
secrets:
|
||||
- db_password
|
||||
volumes:
|
||||
- ./scripts:/scripts:ro
|
||||
- backup_data:/backups
|
||||
depends_on:
|
||||
postgresql:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- heimdall-net
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
# Read password from Docker secret file
|
||||
if [ -f /run/secrets/db_password ]; then
|
||||
export POSTGRES_PASSWORD="$(cat /run/secrets/db_password)"
|
||||
fi
|
||||
|
||||
apk add --no-cache curl bash > /dev/null 2>&1 || true
|
||||
curl -sSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc 2>/dev/null || true
|
||||
chmod +x /usr/local/bin/mc 2>/dev/null || true
|
||||
chmod +x /scripts/*.sh
|
||||
|
||||
# Create crontab
|
||||
echo "# Daily PostgreSQL backup at 02:00 UTC" > /tmp/crontab.txt
|
||||
echo "0 2 * * * /scripts/backup.sh >> /var/log/backup.log 2>&1" >> /tmp/crontab.txt
|
||||
echo "# Weekly Alarik mirror on Sundays at 03:00 UTC" >> /tmp/crontab.txt
|
||||
echo "0 3 * * 0 /scripts/backup-alarik.sh >> /var/log/backup-alarik.log 2>&1" >> /tmp/crontab.txt
|
||||
echo "# Log rotation weekly" >> /tmp/crontab.txt
|
||||
echo "0 4 * * 0 if [ -f /var/log/backup.log ]; then mv /var/log/backup.log /var/log/backup.log.\$$(date +\%Y\%W); fi" >> /tmp/crontab.txt
|
||||
|
||||
crontab /tmp/crontab.txt
|
||||
echo "Crontab installed:"
|
||||
crontab -l
|
||||
|
||||
# Run crond in foreground
|
||||
exec crond -f -l 2
|
||||
|
||||
# ── Optional services ──────────────────────────────────────────
|
||||
|
||||
coturn:
|
||||
image: coturn/coturn:4.6
|
||||
# TURN relay for WebRTC — network_mode host required for UDP ports.
|
||||
command: >
|
||||
-n --use-auth-secret
|
||||
--static-auth-secret-file=/run/secrets/coturn_secret
|
||||
--realm=${COTURN_REALM:-heimdall.local}
|
||||
--fingerprint
|
||||
--no-tlsv1
|
||||
--no-tlsv1_1
|
||||
--log-file=stdout
|
||||
network_mode: host
|
||||
secrets:
|
||||
- coturn_secret
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
ollama:
|
||||
image: ollama/ollama:latest
|
||||
# Local LLM for daily summaries and event analysis.
|
||||
# GPU passthrough: add --gpus all or mount /dev/dri for Intel/AMD.
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${OLLAMA_PORT:-11434}:11434"
|
||||
volumes:
|
||||
- ollama_data:/root/.ollama
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:11434/api/tags"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
# Uncomment for GPU passthrough:
|
||||
# deploy:
|
||||
# resources:
|
||||
# reservations:
|
||||
# devices:
|
||||
# - driver: nvidia
|
||||
# count: all
|
||||
# capabilities: [gpu]
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
# SignalR backplane (scaling) + cache.
|
||||
command: redis-server --requirepass ${REDIS_PASSWORD:-} --appendonly yes
|
||||
ports:
|
||||
- "${REDIS_PORT:-6379}:6379"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
networks:
|
||||
@@ -368,44 +91,13 @@ services:
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
driver: local
|
||||
alarik_storage:
|
||||
driver: local
|
||||
agent_state:
|
||||
driver: local
|
||||
heimdall_data:
|
||||
driver: local
|
||||
ntfy_data:
|
||||
driver: local
|
||||
dataprotection_keys:
|
||||
driver: local
|
||||
ollama_data:
|
||||
driver: local
|
||||
redis_data:
|
||||
driver: local
|
||||
rabbitmq_data:
|
||||
driver: local
|
||||
backup_data:
|
||||
driver: local
|
||||
|
||||
secrets:
|
||||
db_password:
|
||||
file: ./secrets/db_password
|
||||
jwt_signing_key:
|
||||
file: ./secrets/jwt_signing_key
|
||||
jwt_refresh_key:
|
||||
file: ./secrets/jwt_refresh_key
|
||||
coturn_secret:
|
||||
file: ./secrets/coturn_secret
|
||||
alarik_admin_password:
|
||||
file: ./secrets/alarik_admin_password
|
||||
alarik_jwt:
|
||||
file: ./secrets/alarik_jwt
|
||||
smtp_password:
|
||||
file: ./secrets/smtp_password
|
||||
rabbitmq_password:
|
||||
file: ./secrets/rabbitmq_password
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: ${HEIMDALL_NETWORK_NAME:-heimdall-net}
|
||||
driver: bridge
|
||||
@@ -0,0 +1,27 @@
|
||||
# Optional standalone Redis service. Heimdall currently does not require it.
|
||||
services:
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
pull_policy: always
|
||||
command: ["redis-server", "--appendonly", "yes", "--requirepass", "${REDIS_PASSWORD:?Set REDIS_PASSWORD}"]
|
||||
environment:
|
||||
REDISCLI_AUTH: ${REDIS_PASSWORD:?Set REDIS_PASSWORD}
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
volumes:
|
||||
redis_data:
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
external: true
|
||||
@@ -0,0 +1,68 @@
|
||||
# Optional S3-compatible object store. Start the core Compose first so the
|
||||
# shared heimdall-net exists, then configure storage in Central to use rustfs.
|
||||
services:
|
||||
rustfs:
|
||||
image: rustfs/rustfs:latest
|
||||
pull_policy: always
|
||||
restart: unless-stopped
|
||||
# Compose file secrets are read-only bind mounts locally. The installer
|
||||
# deliberately creates them mode 0600, owned by root; RustFS runs as UID
|
||||
# 10001 and cannot read that source directly. A small root init copies the
|
||||
# files into tmpfs, then drops privileges before starting the server.
|
||||
user: "0:0"
|
||||
read_only: true
|
||||
cap_drop:
|
||||
- ALL
|
||||
cap_add:
|
||||
- CHOWN
|
||||
- DAC_OVERRIDE
|
||||
- SETGID
|
||||
- SETUID
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
tmpfs:
|
||||
- /run/rustfs-secrets:rw,noexec,nosuid,nodev,size=1m,mode=0700
|
||||
- /logs:rw,noexec,nosuid,nodev,size=16m,mode=1777
|
||||
- /tmp:rw,noexec,nosuid,nodev,size=16m,mode=1777
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- >-
|
||||
set -eu;
|
||||
umask 077;
|
||||
cp /run/secrets/rustfs_access_key /run/rustfs-secrets/access_key;
|
||||
cp /run/secrets/rustfs_secret_key /run/rustfs-secrets/secret_key;
|
||||
chown 10001:10001 /run/rustfs-secrets /run/rustfs-secrets/access_key /run/rustfs-secrets/secret_key;
|
||||
exec su -s /bin/sh -c 'exec /etc/rustfs/entrypoint.sh rustfs' rustfs
|
||||
ports:
|
||||
- "${RUSTFS_API_PORT:-9000}:9000"
|
||||
- "${RUSTFS_CONSOLE_PORT:-9001}:9001"
|
||||
environment:
|
||||
RUSTFS_VOLUMES: /data
|
||||
RUSTFS_ADDRESS: 0.0.0.0:9000
|
||||
RUSTFS_CONSOLE_ADDRESS: 0.0.0.0:9001
|
||||
RUSTFS_CONSOLE_ENABLE: "true"
|
||||
RUSTFS_ACCESS_KEY_FILE: /run/rustfs-secrets/access_key
|
||||
RUSTFS_SECRET_KEY_FILE: /run/rustfs-secrets/secret_key
|
||||
secrets:
|
||||
- rustfs_access_key
|
||||
- rustfs_secret_key
|
||||
volumes:
|
||||
- rustfs_data:/data
|
||||
networks:
|
||||
heimdall-net:
|
||||
aliases:
|
||||
- rustfs
|
||||
|
||||
volumes:
|
||||
rustfs_data:
|
||||
|
||||
secrets:
|
||||
rustfs_access_key:
|
||||
file: ./optional/secrets/rustfs_access_key
|
||||
rustfs_secret_key:
|
||||
file: ./optional/secrets/rustfs_secret_key
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
external: true
|
||||
@@ -0,0 +1,62 @@
|
||||
# Loopback-only media services for disposable acceptance, never production.
|
||||
services:
|
||||
mediamtx:
|
||||
image: bluenviron/mediamtx:1.21.3
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin}
|
||||
MTX_AUTHMETHOD: http
|
||||
MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central callback URL}
|
||||
MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the local Central origin}
|
||||
# The browser receives this ICE port in SDP; keep the published host port
|
||||
# identical so Docker NAT does not advertise an unreachable container port.
|
||||
MTX_WEBRTCLOCALUDPADDRESS: :${HEIMDALL_TEST_ICE_PORT:-18189}
|
||||
ports:
|
||||
- "127.0.0.1:${HEIMDALL_TEST_PUBLISH_PORT:-18555}:8554/tcp"
|
||||
- "127.0.0.1:${HEIMDALL_TEST_WHEP_PORT:-18889}:8889/tcp"
|
||||
- "127.0.0.1:${HEIMDALL_TEST_ICE_PORT:-18189}:${HEIMDALL_TEST_ICE_PORT:-18189}/udp"
|
||||
volumes:
|
||||
- ./mediamtx.local-test.yml:/mediamtx.yml:ro
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
heimdall-agent:
|
||||
image: heimdall-agent:webrtc-test
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
user: "1654:1654"
|
||||
environment:
|
||||
ASPNETCORE_URLS: http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081}
|
||||
Agent__CentralUrl: http://127.0.0.1:${WEB_PORT:-5000}
|
||||
Agent__AllowInsecureHttp: "true"
|
||||
Agent__SiteToken: ${HEIMDALL_TEST_SITE_TOKEN:-}
|
||||
Agent__AgentName: webrtc-synthetic-agent
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
volumes:
|
||||
- heimdall_agent_state:/var/lib/heimdall
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://127.0.0.1:${HEIMDALL_TEST_AGENT_PORT:-18081}/healthz"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 20s
|
||||
depends_on:
|
||||
agent-state-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
agent-state-init:
|
||||
image: heimdall-agent:webrtc-test
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
user: "0:0"
|
||||
entrypoint: ["chown", "-R", "1654:1654", "/state"]
|
||||
volumes:
|
||||
- heimdall_agent_state:/state
|
||||
restart: "no"
|
||||
|
||||
volumes:
|
||||
heimdall_agent_state:
|
||||
@@ -0,0 +1,22 @@
|
||||
# Test-only synthetic camera source. Exposes one local RTSP port so an Agent
|
||||
# can be configured through Central to pull this generated H.264 stream.
|
||||
services:
|
||||
synthetic-camera:
|
||||
image: bluenviron/mediamtx:1.21.3
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:${HEIMDALL_SYNTHETIC_RTSP_PORT:-18554}:8554/tcp"
|
||||
volumes:
|
||||
- ./mediamtx.synthetic-source.yml:/mediamtx.yml:ro
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
synthetic-camera-publisher:
|
||||
image: jrottenberg/ffmpeg:7.1-alpine
|
||||
restart: unless-stopped
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command: ["while true; do ffmpeg -nostdin -hide_banner -loglevel error -re -f lavfi -i testsrc2=size=640x360:rate=25 -an -vf format=yuv420p -c:v libx264 -profile:v baseline -tune zerolatency -bf 0 -g 25 -f rtsp -rtsp_transport tcp rtsp://synthetic-camera:8554/synthetic; sleep 2; done"]
|
||||
depends_on:
|
||||
- synthetic-camera
|
||||
networks:
|
||||
- heimdall-net
|
||||
@@ -0,0 +1,27 @@
|
||||
# Optional MediaMTX for live camera video. Start after the core stack has
|
||||
# created heimdall-net. Public DNS and certificates are deployment supplied.
|
||||
services:
|
||||
mediamtx:
|
||||
image: bluenviron/mediamtx:1.21.3
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
HEIMDALL_WEBRTC_PUBLIC_HOST: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname}
|
||||
HEIMDALL_WEBRTC_ALLOWED_ORIGIN: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin}
|
||||
MTX_AUTHMETHOD: http
|
||||
MTX_AUTHHTTPADDRESS: ${HEIMDALL_MEDIAMTX_AUTH_URL:?Set the Central MediaMTX callback URL}
|
||||
MTX_WEBRTCALLOWORIGINS: ${HEIMDALL_WEBRTC_ALLOWED_ORIGIN:?Set the Central browser origin}
|
||||
MTX_WEBRTCADDITIONALHOSTS: ${HEIMDALL_WEBRTC_PUBLIC_HOST:?Set the public WebRTC hostname}
|
||||
ports:
|
||||
- "${HEIMDALL_RTSPS_PORT:-8322}:8322/tcp"
|
||||
- "${HEIMDALL_WHEP_PORT:-8889}:8889/tcp"
|
||||
- "${HEIMDALL_WEBRTC_UDP_PORT:-8189}:8189/udp"
|
||||
volumes:
|
||||
- ./mediamtx.yml:/mediamtx.yml:ro
|
||||
- ${HEIMDALL_LIVE_MEDIA_CERT_DIR:?Set directory containing server.crt and server.key}:/certs:ro
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
external: true
|
||||
name: ${HEIMDALL_NETWORK_NAME:-heimdall-net}
|
||||
+23
-243
@@ -1,18 +1,5 @@
|
||||
# ─── Heimdall — Development Docker Compose ─────────────────────────
|
||||
# Builds image from local source. For production with pre-built images,
|
||||
# use: docker compose -f docker/docker-compose.prod.yml up -d
|
||||
# For development with hot-reload:
|
||||
# docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.yml up -d
|
||||
#
|
||||
# The heimdall service serves the Blazor UI, REST API, SignalR hubs,
|
||||
# and Hangfire background jobs (heartbeat monitor, agent failover)
|
||||
# in a single process.
|
||||
|
||||
x-logging: &default-logging
|
||||
driver: "json-file"
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
# Local development core: PostgreSQL and Heimdall Central only.
|
||||
# The Agent and optional software have separate Compose files.
|
||||
|
||||
services:
|
||||
postgresql:
|
||||
@@ -32,40 +19,6 @@ services:
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
alarik:
|
||||
image: ghcr.io/achtungsoftware/alarik:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${ALARIK_API_PORT:-9000}:8080"
|
||||
environment:
|
||||
API_BASE_URL: ${ALARIK_API_BASE_URL:-http://localhost:9000}
|
||||
CONSOLE_BASE_URL: ${ALARIK_CONSOLE_BASE_URL:-http://localhost:9001}
|
||||
ADMIN_USERNAME: ${ALARIK_ADMIN_USERNAME:-heimdall}
|
||||
ADMIN_PASSWORD: ${ALARIK_ADMIN_PASSWORD:?ALARIK_ADMIN_PASSWORD is required}
|
||||
JWT: ${ALARIK_JWT:?ALARIK_JWT is required}
|
||||
ALLOW_ACCOUNT_CREATION: false
|
||||
volumes:
|
||||
- alarik_storage:/app/Storage
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
alarik-console:
|
||||
image: ghcr.io/achtungsoftware/alarik-console:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${ALARIK_CONSOLE_PORT:-9001}:3000"
|
||||
environment:
|
||||
NUXT_PUBLIC_API_BASE_URL: ${ALARIK_API_BASE_URL:-http://localhost:9000}
|
||||
NUXT_PUBLIC_CONSOLE_BASE_URL: ${ALARIK_CONSOLE_BASE_URL:-http://localhost:9001}
|
||||
NUXT_PUBLIC_ALLOW_ACCOUNT_CREATION: false
|
||||
depends_on:
|
||||
- alarik
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
@@ -73,222 +26,49 @@ services:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
image: heimdall:latest
|
||||
image: heimdall:local
|
||||
environment:
|
||||
# MassTransit / RabbitMQ
|
||||
RABBITMQ__HOST: rabbitmq
|
||||
RABBITMQ__PORT: "5672"
|
||||
RABBITMQ__USER: ${RABBITMQ_USER:-heimdall}
|
||||
RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required}
|
||||
# Database
|
||||
DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required}
|
||||
# JWT
|
||||
JWT__Key: ${JWT__KEY:?JWT__KEY is required}
|
||||
JWT__RefreshKey: ${JWT__REFRESHKEY:?JWT__REFRESHKEY is required}
|
||||
JWT__Issuer: ${JWT__ISSUER:-heimdall}
|
||||
JWT__Audience: ${JWT__AUDIENCE:-heimdall-api}
|
||||
# ASP.NET
|
||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production}
|
||||
JWT__KEY: ${JWT__KEY:?JWT__KEY is required}
|
||||
JWT__REFRESHKEY: ${JWT__REFRESHKEY:?JWT__REFRESHKEY is required}
|
||||
JWT__ISSUER: ${JWT__ISSUER:-heimdall}
|
||||
JWT__AUDIENCE: ${JWT__AUDIENCE:-heimdall-api}
|
||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Development}
|
||||
ASPNETCORE_URLS: http://+:8080
|
||||
# CORS (for external agents and API clients)
|
||||
Cors__AllowedOrigins: ${Cors__AllowedOrigins:-*}
|
||||
# Ollama (optional — daily summaries)
|
||||
Ollama__Endpoint: http://ollama:11434
|
||||
# Coturn (WebRTC relay)
|
||||
Coturn__Url: turns:coturn:3478
|
||||
# Redis (SignalR backplane, optional — scaling)
|
||||
ConnectionStrings__Redis: redis:6379
|
||||
# Error tracking
|
||||
LiveMedia__WhepUrl: ${HEIMDALL_WHEP_URL:-}
|
||||
LiveMedia__PublishRtspUrl: ${HEIMDALL_PUBLISH_RTSPS_URL:-}
|
||||
LiveMedia__AllowInsecureRtsp: ${HEIMDALL_ALLOW_INSECURE_RTSP:-false}
|
||||
LiveMedia__AllowInsecureHttp: ${HEIMDALL_ALLOW_INSECURE_HTTP:-false}
|
||||
LiveMedia__IceServers__0__Urls__0: ${HEIMDALL_STUN_URL:-}
|
||||
LiveMedia__Turn__Urls__0: ${HEIMDALL_TURN_URL:-}
|
||||
LiveMedia__Turn__SharedSecret: ${HEIMDALL_TURN_SHARED_SECRET:-}
|
||||
Recordings__StorageQuota__MaxBytes: ${RECORDING_STORAGE_QUOTA_MAX_BYTES:-1099511627776}
|
||||
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
|
||||
ports:
|
||||
- "${WEB_PORT:-5000}:8080"
|
||||
volumes:
|
||||
- heimdall_data:/var/lib/heimdall
|
||||
# Persist the default ./data/storage path as well as /var/lib/heimdall.
|
||||
- heimdall_data:/app/data
|
||||
depends_on:
|
||||
postgresql:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- heimdall_data:/var/lib/heimdall
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/healthz"]
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://localhost:8080/healthz"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
ntfy:
|
||||
image: binwiederhier/ntfy
|
||||
container_name: heimdall-ntfy
|
||||
restart: unless-stopped
|
||||
command:
|
||||
- "serve"
|
||||
environment:
|
||||
- TZ=Europe/Paris
|
||||
volumes:
|
||||
- ntfy_data:/var/lib/ntfy
|
||||
ports:
|
||||
- "8080:80"
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
heimdall-agent:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
args:
|
||||
# Select GPU runtime: nvidia | amd | intel | cpu (default)
|
||||
TARGET_RUNTIME: ${AGENT_RUNTIME:-cpu}
|
||||
# Host network: the agent must see the real camera LAN to run discovery.
|
||||
# On a bridge network it only sees 172.x → the scanner skips (no local subnet).
|
||||
network_mode: host
|
||||
environment:
|
||||
# 8080 is taken by ntfy on the host → listen on 8081
|
||||
ASPNETCORE_URLS: http://+:8081
|
||||
# Host network: Docker DNS names don't resolve → reach the Central via
|
||||
# a host-reachable URL (same machine: http://localhost:5010)
|
||||
Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://localhost:5010}
|
||||
Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required}
|
||||
Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01}
|
||||
Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30}
|
||||
Agent__StateDirectory: /var/lib/heimdall
|
||||
Agent__RegistrationMaxRetries: ${HEIMDALL_REGISTRATION_RETRIES:-5}
|
||||
# MassTransit / RabbitMQ — host network can't resolve Docker DNS
|
||||
RABBITMQ__HOST: ${RABBITMQ_HOST:-localhost}
|
||||
RABBITMQ__PORT: ${RABBITMQ_PORT:-5672}
|
||||
RABBITMQ__USER: ${RABBITMQ_USER:-heimdall}
|
||||
RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required}
|
||||
# ONNX Runtime GPU provider selection
|
||||
ORT_PROVIDER: ${AGENT_ORT_PROVIDER:-CUDA}
|
||||
ORT_CUDA_DEVICE_ID: ${AGENT_CUDA_DEVICE_ID:-0}
|
||||
volumes:
|
||||
- agent_state:/var/lib/heimdall
|
||||
# GPU device exposure (NVIDIA CUDA, AMD ROCm, Intel VAAPI/iGPU)
|
||||
# Override in docker-compose.local.yml for specific GPU hardware:
|
||||
# deploy:
|
||||
# resources:
|
||||
# reservations:
|
||||
# devices:
|
||||
# - driver: nvidia
|
||||
# count: 1
|
||||
# capabilities: [gpu]
|
||||
# Or for AMD ROCm:
|
||||
# devices:
|
||||
# - /dev/kfd:/dev/kfd
|
||||
# - /dev/dri:/dev/dri
|
||||
# Or for Intel iGPU/VAAPI:
|
||||
# devices:
|
||||
# - /dev/dri:/dev/dri
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: 1
|
||||
capabilities: [gpu]
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8081/healthz"]
|
||||
interval: 30s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
depends_on:
|
||||
- heimdall
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
# no networks: host networking
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:3-management
|
||||
hostname: rabbitmq
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-heimdall}
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required}
|
||||
ports:
|
||||
- "${RABBITMQ_PORT:-5672}:5672"
|
||||
- "${RABBITMQ_MGMT_PORT:-15672}:15672"
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
# ── Optional services (dev) ────────────────────────────────────
|
||||
|
||||
coturn:
|
||||
image: coturn/coturn:4.6
|
||||
command: >
|
||||
-n --use-auth-secret
|
||||
--static-auth-secret=${COTURN_SECRET:?COTURN_SECRET is required}
|
||||
--realm=${COTURN_REALM:-heimdall.local}
|
||||
--fingerprint
|
||||
--no-tlsv1
|
||||
--no-tlsv1_1
|
||||
--log-file=stdout
|
||||
network_mode: host
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
|
||||
ollama:
|
||||
image: ollama/ollama:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "${OLLAMA_PORT:-11434}:11434"
|
||||
volumes:
|
||||
- ollama_data:/root/.ollama
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:11434/api/tags"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 30s
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
command: redis-server --appendonly yes
|
||||
ports:
|
||||
- "${REDIS_PORT:-6379}:6379"
|
||||
volumes:
|
||||
- redis_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
logging: *default-logging
|
||||
networks:
|
||||
- heimdall-net
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
driver: local
|
||||
alarik_storage:
|
||||
driver: local
|
||||
agent_state:
|
||||
driver: local
|
||||
heimdall_data:
|
||||
driver: local
|
||||
ntfy_data:
|
||||
driver: local
|
||||
ollama_data:
|
||||
driver: local
|
||||
redis_data:
|
||||
driver: local
|
||||
rabbitmq_data:
|
||||
driver: local
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: ${HEIMDALL_NETWORK_NAME:-heimdall-net}
|
||||
driver: bridge
|
||||
@@ -0,0 +1,17 @@
|
||||
# Loopback-only insecure listeners for disposable workstation acceptance only.
|
||||
logLevel: warn
|
||||
rtsp: true
|
||||
rtspTransports: [tcp]
|
||||
rtspEncryption: "no"
|
||||
rtspAddress: :8554
|
||||
webrtc: true
|
||||
webrtcAddress: :8889
|
||||
webrtcEncryption: false
|
||||
webrtcAllowOrigins: ['${HEIMDALL_WEBRTC_ALLOWED_ORIGIN}']
|
||||
webrtcLocalUDPAddress: :8189
|
||||
webrtcAdditionalHosts: ['127.0.0.1']
|
||||
pathDefaults:
|
||||
source: publisher
|
||||
record: false
|
||||
paths:
|
||||
all_others:
|
||||
@@ -0,0 +1,15 @@
|
||||
logLevel: warn
|
||||
rtsp: true
|
||||
rtspTransports: [tcp]
|
||||
rtspEncryption: "no"
|
||||
rtspAddress: :8554
|
||||
authMethod: internal
|
||||
authInternalUsers:
|
||||
- user: any
|
||||
pass:
|
||||
ips: []
|
||||
permissions:
|
||||
- action: publish
|
||||
- action: read
|
||||
paths:
|
||||
all_others:
|
||||
@@ -0,0 +1,23 @@
|
||||
logLevel: warn
|
||||
rtsp: true
|
||||
rtspTransports: [tcp]
|
||||
rtspEncryption: strict
|
||||
rtspsAddress: :8322
|
||||
rtspServerCert: /certs/server.crt
|
||||
rtspServerKey: /certs/server.key
|
||||
|
||||
webrtc: true
|
||||
webrtcAddress: :8889
|
||||
webrtcEncryption: true
|
||||
webrtcServerCert: /certs/server.crt
|
||||
webrtcServerKey: /certs/server.key
|
||||
webrtcAllowOrigins: []
|
||||
webrtcLocalUDPAddress: :8189
|
||||
webrtcAdditionalHosts: []
|
||||
|
||||
pathDefaults:
|
||||
source: publisher
|
||||
record: false
|
||||
|
||||
paths:
|
||||
all_others:
|
||||
Executable
+49
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env bash
|
||||
# Archive the shared Central data volume, including local objects and the
|
||||
# encrypted ASP.NET Data Protection key ring.
|
||||
set -euo pipefail
|
||||
|
||||
SOURCE_DIR="${HEIMDALL_DATA_SOURCE:-/source/heimdall_data}"
|
||||
BACKUP_DIR="${BACKUP_LOCAL_DIR:-/backups}"
|
||||
RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-30}"
|
||||
S3_ENDPOINT="${RUSTFS_ENDPOINT:-${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}}"
|
||||
S3_ACCESS_KEY="${RUSTFS_ACCESS_KEY:-${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}}"
|
||||
S3_SECRET_KEY="${RUSTFS_SECRET_KEY:-${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}}"
|
||||
S3_BUCKET="${RUSTFS_BUCKET:-${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}}"
|
||||
SKIP_S3_UPLOAD="${BACKUP_SKIP_S3_UPLOAD:-0}"
|
||||
TIMESTAMP="$(date -u +%Y-%m-%dT%H-%M-%SZ)"
|
||||
ARCHIVE_DIR="${BACKUP_DIR}/protected-data"
|
||||
ARCHIVE="${ARCHIVE_DIR}/heimdall-data-${TIMESTAMP}.tar.gz"
|
||||
|
||||
log() { echo "[protected-data-backup] $(date -u +%H:%M:%S) $*"; }
|
||||
die() { log "FATAL: $*" >&2; exit 1; }
|
||||
|
||||
[[ -d "$SOURCE_DIR/dp-keys" ]] || die "Data Protection key directory is missing: $SOURCE_DIR/dp-keys"
|
||||
[[ "$RETENTION_DAYS" =~ ^[0-9]+$ ]] || die "BACKUP_RETENTION_DAYS must be a non-negative integer"
|
||||
|
||||
mkdir -p "$ARCHIVE_DIR"
|
||||
TEMP_ARCHIVE="${ARCHIVE}.tmp"
|
||||
trap 'rm -f "$TEMP_ARCHIVE"' EXIT
|
||||
tar -czf "$TEMP_ARCHIVE" -C "$SOURCE_DIR" .
|
||||
chmod 0600 "$TEMP_ARCHIVE"
|
||||
mv "$TEMP_ARCHIVE" "$ARCHIVE"
|
||||
log "Created protected data archive: $ARCHIVE"
|
||||
|
||||
find "$ARCHIVE_DIR" -type f -name 'heimdall-data-*.tar.gz' -mtime "+$RETENTION_DAYS" -delete
|
||||
|
||||
# Store an off-site copy when S3-compatible credentials are configured.
|
||||
if [[ "$SKIP_S3_UPLOAD" == "1" ]]; then
|
||||
log "S3 upload disabled by BACKUP_SKIP_S3_UPLOAD"
|
||||
elif [[ -n "$S3_ENDPOINT" && -n "$S3_ACCESS_KEY" && -n "$S3_SECRET_KEY" ]]; then
|
||||
if command -v mc >/dev/null 2>&1; then
|
||||
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 >/dev/null
|
||||
mc cp "$ARCHIVE" "heimdall-backup/${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")"
|
||||
elif command -v aws >/dev/null 2>&1; then
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$ARCHIVE" "s3://${S3_BUCKET}/backup/protected-data/$(basename "$ARCHIVE")"
|
||||
else
|
||||
die "Neither mc nor aws CLI is available to upload protected data backups"
|
||||
fi
|
||||
log "Uploaded protected data archive to the configured object store"
|
||||
else
|
||||
log "S3 credentials are not configured; the archive remains in the local backup volume"
|
||||
fi
|
||||
@@ -1,16 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# ─── Heimdall — Alarik/S3 Mirror Backup (weekly) ────────────────
|
||||
# ─── Heimdall — RustFS/S3 Mirror Backup (weekly) ────────────────
|
||||
# Mirrors the heimdall bucket to a backup prefix with versioning.
|
||||
# This captures snapshots, recordings, and other S3-stored data.
|
||||
#
|
||||
# Usage:
|
||||
# ./backup-alarik.sh # defaults from env / .env
|
||||
# ./backup-alarik.sh --dry-run # show what would be done
|
||||
# BACKUP_RETENTION_WEEKS=8 ./backup-alarik.sh
|
||||
# ./backup-rustfs.sh # defaults from env / .env
|
||||
# ./backup-rustfs.sh --dry-run # show what would be done
|
||||
# BACKUP_RETENTION_WEEKS=8 ./backup-rustfs.sh
|
||||
#
|
||||
# Required env vars:
|
||||
# ALARIK_ENDPOINT (or S3_ENDPOINT), ALARIK_ACCESS_KEY (or S3_ACCESS_KEY),
|
||||
# ALARIK_SECRET_KEY (or S3_SECRET_KEY), ALARIK_BUCKET (default: heimdall)
|
||||
# RUSTFS_ENDPOINT, RUSTFS_ACCESS_KEY, RUSTFS_SECRET_KEY,
|
||||
# RUSTFS_BUCKET (default: heimdall; S3_* and legacy ALARIK_* aliases accepted)
|
||||
#
|
||||
# Optional:
|
||||
# BACKUP_RETENTION_WEEKS (default: 12)
|
||||
@@ -31,23 +31,23 @@ if [[ -f "$ENV_FILE" ]]; then
|
||||
fi
|
||||
|
||||
# ── Configuration ───────────────────────────────────────────────
|
||||
S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}"
|
||||
S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}"
|
||||
S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}"
|
||||
S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}"
|
||||
BACKUP_PREFIX="backup/alarik"
|
||||
S3_ENDPOINT="${RUSTFS_ENDPOINT:-${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}}"
|
||||
S3_ACCESS_KEY="${RUSTFS_ACCESS_KEY:-${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}}"
|
||||
S3_SECRET_KEY="${RUSTFS_SECRET_KEY:-${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}}"
|
||||
S3_BUCKET="${RUSTFS_BUCKET:-${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}}"
|
||||
BACKUP_PREFIX="backup/rustfs"
|
||||
RETENTION_WEEKS="${BACKUP_RETENTION_WEEKS:-12}"
|
||||
TIMESTAMP="$(date -u +%Y-%m-%dT%H-%M-%SZ)"
|
||||
WEEK_TAG="$(date -u +%Y-W%V)"
|
||||
IS_DRY_RUN="${DRY_RUN:-0}"
|
||||
|
||||
# ── Helpers ─────────────────────────────────────────────────────
|
||||
log() { echo "[alarik-backup] $(date -u +%H:%M:%S) $*"; }
|
||||
log() { echo "[rustfs-backup] $(date -u +%H:%M:%S) $*"; }
|
||||
warn() { log "WARN: $*"; }
|
||||
die() { log "FATAL: $*"; exit 1; }
|
||||
|
||||
# ── Preflight ───────────────────────────────────────────────────
|
||||
[[ -z "$S3_ENDPOINT" ]] && die "S3_ENDPOINT not set — cannot mirror Alarik"
|
||||
[[ -z "$S3_ENDPOINT" ]] && die "S3_ENDPOINT not set — cannot mirror RustFS"
|
||||
|
||||
if command -v mc >/dev/null 2>&1; then
|
||||
CLIENT="mc"
|
||||
@@ -76,7 +76,7 @@ else
|
||||
2>&1 | tail -10
|
||||
else
|
||||
# AWS CLI: sync with exclusion
|
||||
aws --endpoint-url "$S3_ENDPOINT" s3 sync \
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 sync \
|
||||
"s3://${S3_BUCKET}" \
|
||||
"s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}" \
|
||||
--exclude "backup/*" \
|
||||
@@ -102,6 +102,14 @@ if [[ -n "$CUTOFF_WEEK" ]]; then
|
||||
mc rm --recursive --force "heimdall-backup/${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
else
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${BACKUP_PREFIX}/" 2>/dev/null | awk '$1 == "PRE" {print $2}' | while read -r week; do
|
||||
week="${week%/}"
|
||||
if [[ "$week" < "$CUTOFF_WEEK" ]]; then
|
||||
log " Deleting: ${BACKUP_PREFIX}/${week}/"
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm --recursive "s3://${S3_BUCKET}/${BACKUP_PREFIX}/${week}/" >/dev/null
|
||||
fi
|
||||
done
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
@@ -119,7 +127,7 @@ if [[ "$IS_DRY_RUN" != "1" ]]; then
|
||||
TOTAL_SIZE=$(echo "$STATS" | grep -oP 'Size: \K\d+' || echo "0")
|
||||
fi
|
||||
|
||||
MANIFEST="Heimdall Alarik Backup Manifest
|
||||
MANIFEST="Heimdall RustFS Backup Manifest
|
||||
================================
|
||||
Week: ${WEEK_TAG}
|
||||
Created: ${TIMESTAMP}
|
||||
@@ -131,10 +139,10 @@ Total: ${TOTAL_SIZE} bytes
|
||||
if [[ "$CLIENT" == "mc" ]]; then
|
||||
echo "$MANIFEST" | mc pipe "heimdall-backup/${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
|
||||
else
|
||||
echo "$MANIFEST" | aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
|
||||
echo "$MANIFEST" | AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp - "s3://${S3_BUCKET}/${MANIFEST_KEY}" 2>/dev/null
|
||||
fi
|
||||
log "Manifest written: ${MANIFEST_KEY}"
|
||||
fi
|
||||
|
||||
log "Alarik backup complete ✓"
|
||||
log "RustFS backup complete ✓"
|
||||
log " Location: s3://${S3_BUCKET}/${BACKUP_PREFIX}/${WEEK_TAG}/"
|
||||
+29
-12
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# ─── Heimdall — PostgreSQL Daily Backup ──────────────────────────
|
||||
# Runs pg_dump inside the PostgreSQL container, compresses, uploads
|
||||
# to Alarik/S3 under backup/postgresql/YYYY-MM-DD/, and prunes
|
||||
# to RustFS/S3 under backup/postgresql/YYYY-MM-DD/, and prunes
|
||||
# backups older than RETENTION_DAYS.
|
||||
#
|
||||
# Usage:
|
||||
@@ -11,8 +11,9 @@
|
||||
#
|
||||
# Required env vars (set in .env or export):
|
||||
# POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD
|
||||
# ALARIK_ENDPOINT (or S3_ENDPOINT), ALARIK_ACCESS_KEY (or S3_ACCESS_KEY),
|
||||
# ALARIK_SECRET_KEY (or S3_SECRET_KEY), ALARIK_BUCKET (default: heimdall)
|
||||
# or POSTGRES_PASSWORD_FILE (for Docker secrets)
|
||||
# RUSTFS_ENDPOINT, RUSTFS_ACCESS_KEY, RUSTFS_SECRET_KEY,
|
||||
# RUSTFS_BUCKET (default: heimdall; S3_* and legacy ALARIK_* aliases accepted)
|
||||
#
|
||||
# Optional:
|
||||
# BACKUP_RETENTION_DAYS (default: 30)
|
||||
@@ -38,12 +39,19 @@ PG_HOST="${POSTGRES_HOST:-localhost}"
|
||||
PG_PORT="${POSTGRES_PORT:-5432}"
|
||||
PG_DB="${POSTGRES_DB:-heimdall}"
|
||||
PG_USER="${POSTGRES_USER:-heimdall}"
|
||||
PG_PASSWORD="${POSTGRES_PASSWORD:-heimdall}"
|
||||
if [[ -n "${POSTGRES_PASSWORD:-}" ]]; then
|
||||
PG_PASSWORD="$POSTGRES_PASSWORD"
|
||||
elif [[ -n "${POSTGRES_PASSWORD_FILE:-}" ]]; then
|
||||
[[ -r "$POSTGRES_PASSWORD_FILE" ]] || { echo "[backup] FATAL: POSTGRES_PASSWORD_FILE is not readable" >&2; exit 1; }
|
||||
PG_PASSWORD="$(<"$POSTGRES_PASSWORD_FILE")"
|
||||
else
|
||||
PG_PASSWORD="heimdall"
|
||||
fi
|
||||
|
||||
S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}"
|
||||
S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}"
|
||||
S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}"
|
||||
S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}"
|
||||
S3_ENDPOINT="${RUSTFS_ENDPOINT:-${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}}"
|
||||
S3_ACCESS_KEY="${RUSTFS_ACCESS_KEY:-${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}}"
|
||||
S3_SECRET_KEY="${RUSTFS_SECRET_KEY:-${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}}"
|
||||
S3_BUCKET="${RUSTFS_BUCKET:-${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}}"
|
||||
S3_PREFIX="backup/postgresql"
|
||||
|
||||
RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-30}"
|
||||
@@ -86,7 +94,7 @@ else
|
||||
log "Dump created: $(du -h "$DUMP_FILE" | cut -f1) → $DUMP_FILE"
|
||||
fi
|
||||
|
||||
# ── Step 2: Upload to Alarik/S3 ────────────────────────────────
|
||||
# ── Step 2: Upload to RustFS/S3 ────────────────────────────────
|
||||
S3_KEY="${S3_PREFIX}/${DATE_TAG}/heimdall-${TIMESTAMP}.sql.gz"
|
||||
S3_LATEST_KEY="${S3_PREFIX}/latest.sql.gz"
|
||||
|
||||
@@ -101,8 +109,8 @@ if [[ -n "$S3_ENDPOINT" ]]; then
|
||||
mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
|
||||
mc cp "$DUMP_FILE" "heimdall-backup/${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
|
||||
else
|
||||
aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
|
||||
aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_KEY}" 2>&1 | tail -3
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "$DUMP_FILE" "s3://${S3_BUCKET}/${S3_LATEST_KEY}" 2>&1 | tail -3
|
||||
fi
|
||||
log "Upload complete"
|
||||
fi
|
||||
@@ -133,10 +141,19 @@ if [[ -n "$S3_ENDPOINT" && "$IS_DRY_RUN" != "1" ]]; then
|
||||
mc rm "heimdall-backup/${S3_BUCKET}/${key}" 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
elif command -v aws >/dev/null 2>&1; then
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 ls "s3://${S3_BUCKET}/${S3_PREFIX}/" --recursive 2>/dev/null | awk '{print $4}' | while read -r key; do
|
||||
if [[ "$key" =~ ([0-9]{4}-[0-9]{2}-[0-9]{2})/ ]] && [[ "${BASH_REMATCH[1]}" < "$CUTOFF_DATE" ]]; then
|
||||
log " Deleting: $key"
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 rm "s3://${S3_BUCKET}/${key}" >/dev/null
|
||||
fi
|
||||
done
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
log "Backup complete ✓"
|
||||
log " Local: ${DUMP_FILE}"
|
||||
[[ -n "$S3_ENDPOINT" ]] && log " S3: s3://${S3_BUCKET}/${S3_KEY}"
|
||||
if [[ -n "$S3_ENDPOINT" ]]; then
|
||||
log " S3: s3://${S3_BUCKET}/${S3_KEY}"
|
||||
fi
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
# Restore a protected-data archive into the mounted Heimdall data volume.
|
||||
set -euo pipefail
|
||||
|
||||
SOURCE_DIR="${HEIMDALL_DATA_SOURCE:-/source/heimdall_data}"
|
||||
RESTORE_DIR=""
|
||||
FILE=""
|
||||
AUTO_YES=0
|
||||
|
||||
log() { echo "[protected-data-restore] $(date -u +%H:%M:%S) $*"; }
|
||||
die() { log "FATAL: $*" >&2; exit 1; }
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--file) [[ $# -ge 2 ]] || die "--file requires a path"; FILE="$2"; shift 2 ;;
|
||||
--yes) AUTO_YES=1; shift ;;
|
||||
-h|--help)
|
||||
echo "Usage: $(basename "$0") --file ARCHIVE [--yes]"
|
||||
exit 0
|
||||
;;
|
||||
*) die "Unknown option: $1" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
[[ -n "$FILE" ]] || die "Specify --file ARCHIVE"
|
||||
[[ -f "$FILE" ]] || die "Archive not found: $FILE"
|
||||
[[ -d "$SOURCE_DIR" ]] || die "Mounted Heimdall data volume is missing: $SOURCE_DIR"
|
||||
tar -tzf "$FILE" >/dev/null || die "Archive is invalid or truncated"
|
||||
|
||||
while IFS= read -r member; do
|
||||
normalized="${member#./}"
|
||||
case "$normalized" in
|
||||
/*|..|../*|*/../*) die "Archive contains an unsafe path" ;;
|
||||
esac
|
||||
done < <(tar -tzf "$FILE")
|
||||
|
||||
MEMBERS="$(tar -tzf "$FILE")"
|
||||
NORMALIZED_MEMBERS="$(sed 's#^\./##' <<<"$MEMBERS")"
|
||||
grep -q '^dp-keys/' <<<"$NORMALIZED_MEMBERS" \
|
||||
|| die "Archive does not contain the Data Protection key ring"
|
||||
if tar -tvzf "$FILE" | awk 'substr($0, 1, 1) == "l" || substr($0, 1, 1) == "h" { found = 1 } END { exit !found }'; then
|
||||
die "Archive contains a symbolic or hard link"
|
||||
fi
|
||||
|
||||
if [[ "$AUTO_YES" != "1" ]]; then
|
||||
echo "This overlays local objects and the Data Protection key ring in: $SOURCE_DIR"
|
||||
echo "Stop Heimdall Central before restoring to avoid concurrent writes."
|
||||
read -rp "Type RESTORE to continue: " confirmation
|
||||
[[ "$confirmation" == "RESTORE" ]] || { log "Aborted"; exit 1; }
|
||||
fi
|
||||
|
||||
RESTORE_DIR="$(mktemp -d /tmp/heimdall-protected-restore.XXXXXX)"
|
||||
trap 'rm -rf "$RESTORE_DIR"' EXIT
|
||||
tar -xzf "$FILE" -C "$RESTORE_DIR" --no-same-owner
|
||||
[[ -d "$RESTORE_DIR/dp-keys" ]] || die "Restored Data Protection key ring is missing"
|
||||
cp -a "$RESTORE_DIR/." "$SOURCE_DIR/"
|
||||
log "Protected data restored from $FILE"
|
||||
log "Existing target files not present in the archive were left unchanged"
|
||||
+35
-16
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# ─── Heimdall — PostgreSQL Restore from Backup ───────────────────
|
||||
# Downloads a backup from Alarik/S3 (or uses a local file) and
|
||||
# Downloads a backup from RustFS/S3 (or uses a local file) and
|
||||
# restores it to the PostgreSQL database.
|
||||
#
|
||||
# Usage:
|
||||
@@ -13,6 +13,7 @@
|
||||
#
|
||||
# Required env vars (set in .env or export):
|
||||
# POSTGRES_HOST, POSTGRES_PORT, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD
|
||||
# or POSTGRES_PASSWORD_FILE (for Docker secrets)
|
||||
# (S3 vars only needed for --s3-key or --latest)
|
||||
# ──────────────────────────────────────────────────────────────────
|
||||
set -euo pipefail
|
||||
@@ -34,12 +35,19 @@ PG_HOST="${POSTGRES_HOST:-localhost}"
|
||||
PG_PORT="${POSTGRES_PORT:-5432}"
|
||||
PG_DB="${POSTGRES_DB:-heimdall}"
|
||||
PG_USER="${POSTGRES_USER:-heimdall}"
|
||||
PG_PASSWORD="${POSTGRES_PASSWORD:-heimdall}"
|
||||
if [[ -n "${POSTGRES_PASSWORD:-}" ]]; then
|
||||
PG_PASSWORD="$POSTGRES_PASSWORD"
|
||||
elif [[ -n "${POSTGRES_PASSWORD_FILE:-}" ]]; then
|
||||
[[ -r "$POSTGRES_PASSWORD_FILE" ]] || { echo "[restore] FATAL: POSTGRES_PASSWORD_FILE is not readable" >&2; exit 1; }
|
||||
PG_PASSWORD="$(<"$POSTGRES_PASSWORD_FILE")"
|
||||
else
|
||||
PG_PASSWORD="heimdall"
|
||||
fi
|
||||
|
||||
S3_ENDPOINT="${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}"
|
||||
S3_ACCESS_KEY="${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}"
|
||||
S3_SECRET_KEY="${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}"
|
||||
S3_BUCKET="${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}"
|
||||
S3_ENDPOINT="${RUSTFS_ENDPOINT:-${ALARIK_ENDPOINT:-${S3_ENDPOINT:-}}}"
|
||||
S3_ACCESS_KEY="${RUSTFS_ACCESS_KEY:-${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}}}"
|
||||
S3_SECRET_KEY="${RUSTFS_SECRET_KEY:-${ALARIK_SECRET_KEY:-${S3_SECRET_KEY:-}}}"
|
||||
S3_BUCKET="${RUSTFS_BUCKET:-${ALARIK_BUCKET:-${S3_BUCKET:-heimdall}}}"
|
||||
|
||||
LOCAL_DIR="${BACKUP_LOCAL_DIR:-/var/lib/heimdall/backups}"
|
||||
RESTORE_TMP="${LOCAL_DIR}/.restore-tmp"
|
||||
@@ -116,13 +124,24 @@ if [[ -n "$S3_KEY" ]]; then
|
||||
mc alias set heimdall-backup "$S3_ENDPOINT" "$S3_ACCESS_KEY" "$S3_SECRET_KEY" --api S3v4 2>/dev/null
|
||||
mc cp "heimdall-backup/${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
|
||||
else
|
||||
aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
|
||||
AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY" AWS_SECRET_ACCESS_KEY="$S3_SECRET_KEY" AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-us-east-1}" aws --endpoint-url "$S3_ENDPOINT" s3 cp "s3://${S3_BUCKET}/${S3_KEY}" "$FILE" 2>&1 | tail -3
|
||||
fi
|
||||
log "Downloaded: $(du -h "$FILE" | cut -f1)"
|
||||
fi
|
||||
|
||||
[[ ! -f "$FILE" ]] && die "Backup file not found: $FILE"
|
||||
|
||||
# Validate the backup before confirming or changing the target database.
|
||||
if pg_restore --list "$FILE" >/dev/null 2>&1; then
|
||||
RESTORE_FORMAT="custom"
|
||||
else
|
||||
gzip -t "$FILE" >/dev/null 2>&1 || die "Backup is not a valid PostgreSQL custom dump or gzip-compressed SQL file"
|
||||
SQL_HEADER="$(gunzip -c "$FILE" | sed -n '1,5p')"
|
||||
grep -qE '^(-- PostgreSQL|SET |CREATE |SELECT )' <<<"$SQL_HEADER" \
|
||||
|| die "Backup is not a valid PostgreSQL custom dump or gzip-compressed SQL file"
|
||||
RESTORE_FORMAT="plain"
|
||||
fi
|
||||
|
||||
# ── Step 2: Confirm ─────────────────────────────────────────────
|
||||
if [[ "$AUTO_YES" != "1" && "$IS_DRY_RUN" != "1" ]]; then
|
||||
echo ""
|
||||
@@ -135,11 +154,13 @@ if [[ "$AUTO_YES" != "1" && "$IS_DRY_RUN" != "1" ]]; then
|
||||
fi
|
||||
|
||||
# ── Step 3: Terminate existing connections ───────────────────────
|
||||
log "Terminating existing connections to ${PG_DB}..."
|
||||
PGPASSWORD="$PG_PASSWORD" psql \
|
||||
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres \
|
||||
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${PG_DB}' AND pid <> pg_backend_pid();" \
|
||||
2>/dev/null || warn "Could not terminate connections (may be first restore)"
|
||||
if [[ "$IS_DRY_RUN" != "1" ]]; then
|
||||
log "Terminating existing connections to ${PG_DB}..."
|
||||
PGPASSWORD="$PG_PASSWORD" psql \
|
||||
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d postgres \
|
||||
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${PG_DB}' AND pid <> pg_backend_pid();" \
|
||||
2>/dev/null || warn "Could not terminate connections (may be first restore)"
|
||||
fi
|
||||
|
||||
# ── Step 4: Drop and recreate database ──────────────────────────
|
||||
log "Dropping and recreating database ${PG_DB}..."
|
||||
@@ -154,17 +175,15 @@ fi
|
||||
# ── Step 5: Restore ─────────────────────────────────────────────
|
||||
log "Restoring from backup..."
|
||||
if [[ "$IS_DRY_RUN" != "1" ]]; then
|
||||
# Try pg_restore first (for custom format dumps)
|
||||
if pg_restore --version 2>/dev/null | grep -q "."; then
|
||||
if [[ "$RESTORE_FORMAT" == "custom" ]]; then
|
||||
PGPASSWORD="$PG_PASSWORD" pg_restore \
|
||||
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" \
|
||||
-d "$PG_DB" \
|
||||
--no-owner \
|
||||
--no-privileges \
|
||||
--verbose \
|
||||
"$FILE" 2>&1 | tail -10 || true
|
||||
"$FILE" 2>&1 | tail -10
|
||||
else
|
||||
# Fallback: psql for plain SQL dumps
|
||||
gunzip -c "$FILE" | PGPASSWORD="$PG_PASSWORD" psql \
|
||||
-h "$PG_HOST" -p "$PG_PORT" -U "$PG_USER" -d "$PG_DB" \
|
||||
--quiet 2>&1 | tail -10
|
||||
|
||||
@@ -17,10 +17,15 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
TEST_DB="heimdall_backup_test"
|
||||
TEST_PORT=15432
|
||||
TEST_USER="testbackup"
|
||||
TEST_PASS="testbackup123"
|
||||
CONTAINER_NAME="heimdall-pg-backup-test"
|
||||
TEST_SUFFIX="$$-${RANDOM}"
|
||||
CONTAINER_NAME="heimdall-pg-backup-test-${TEST_SUFFIX}"
|
||||
NETWORK_NAME="heimdall-backup-test-net-${TEST_SUFFIX}"
|
||||
TEST_BACKUP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/heimdall-test-backup.XXXXXX")"
|
||||
POSTGRES_PASSWORD_FILE="${TEST_BACKUP_DIR}/postgres-password"
|
||||
printf '%s' "$TEST_PASS" > "$POSTGRES_PASSWORD_FILE"
|
||||
chmod 0644 "$POSTGRES_PASSWORD_FILE"
|
||||
CLEANUP=1
|
||||
|
||||
# ── Helpers ─────────────────────────────────────────────────────
|
||||
@@ -44,20 +49,6 @@ run_sql_raw() {
|
||||
rm -f "$sql_file"
|
||||
}
|
||||
|
||||
# Drop DB helper — connects to 'postgres' to avoid dangling session
|
||||
drop_and_recreate_db() {
|
||||
local sql_file
|
||||
sql_file=$(mktemp /tmp/heimdall-test-XXXXXX.sql)
|
||||
cat > "$sql_file" <<SQLEOF
|
||||
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '${TEST_DB}' AND pid <> pg_backend_pid();
|
||||
DROP DATABASE IF EXISTS ${TEST_DB};
|
||||
CREATE DATABASE ${TEST_DB} OWNER ${TEST_USER};
|
||||
SQLEOF
|
||||
docker cp "$sql_file" "${CONTAINER_NAME}:/tmp/drop-recreate.sql"
|
||||
docker exec "$CONTAINER_NAME" psql -U "$TEST_USER" -d postgres -f /tmp/drop-recreate.sql >/dev/null 2>&1
|
||||
rm -f "$sql_file"
|
||||
}
|
||||
|
||||
FAILURES=0
|
||||
TESTS=0
|
||||
|
||||
@@ -85,8 +76,10 @@ cleanup() {
|
||||
if [[ "$CLEANUP" == "1" ]]; then
|
||||
log "Cleaning up test environment..."
|
||||
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
|
||||
docker network rm heimdall-backup-test-net 2>/dev/null || true
|
||||
rm -rf "${SCRIPT_DIR}/.test-backup-tmp" 2>/dev/null
|
||||
docker network rm "$NETWORK_NAME" 2>/dev/null || true
|
||||
rm -rf "$TEST_BACKUP_DIR" 2>/dev/null
|
||||
else
|
||||
log "Keeping test container $CONTAINER_NAME, network $NETWORK_NAME, and files under $TEST_BACKUP_DIR"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
@@ -94,17 +87,18 @@ trap cleanup EXIT
|
||||
# ── Setup: Start isolated PostgreSQL ─────────────────────────────
|
||||
log "Setting up isolated PostgreSQL for backup test..."
|
||||
|
||||
docker network create heimdall-backup-test-net 2>/dev/null || true
|
||||
docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
|
||||
docker network create "$NETWORK_NAME" >/dev/null
|
||||
|
||||
docker run -d \
|
||||
--name "$CONTAINER_NAME" \
|
||||
--network heimdall-backup-test-net \
|
||||
--network "$NETWORK_NAME" \
|
||||
--tmpfs /var/lib/postgresql/data \
|
||||
-e POSTGRES_DB="$TEST_DB" \
|
||||
-e POSTGRES_USER="$TEST_USER" \
|
||||
-e POSTGRES_PASSWORD="$TEST_PASS" \
|
||||
-p "${TEST_PORT}:5432" \
|
||||
-e POSTGRES_PASSWORD_FILE=/tmp/test-db-password \
|
||||
-v "$POSTGRES_PASSWORD_FILE:/tmp/test-db-password:ro" \
|
||||
postgres:17-alpine
|
||||
log "Test container: $CONTAINER_NAME"
|
||||
|
||||
log "Waiting for PostgreSQL to be ready..."
|
||||
for i in $(seq 1 30); do
|
||||
@@ -159,42 +153,44 @@ PRE_CAMERAS=$(run_sql "SELECT COUNT(*) FROM cameras;")
|
||||
PRE_EVENTS=$(run_sql "SELECT COUNT(*) FROM camera_events;")
|
||||
log "Pre-backup: ${PRE_SITES} sites, ${PRE_CAMERAS} cameras, ${PRE_EVENTS} events"
|
||||
|
||||
# ── Step 2: Create backup using pg_dump ─────────────────────────
|
||||
TEST_BACKUP_DIR="${SCRIPT_DIR}/.test-backup-tmp"
|
||||
# ── Step 2: Create backup using the production backup script ────
|
||||
mkdir -p "$TEST_BACKUP_DIR"
|
||||
DUMP_FILE="${TEST_BACKUP_DIR}/test-backup.sql.gz"
|
||||
|
||||
log "Creating backup with pg_dump..."
|
||||
docker exec "$CONTAINER_NAME" pg_dump \
|
||||
-U "$TEST_USER" -d "$TEST_DB" \
|
||||
--format=custom --compress=9 \
|
||||
-f "/tmp/test-backup.sql.gz"
|
||||
log "Creating backup through backup.sh with POSTGRES_PASSWORD_FILE..."
|
||||
printf '%s\n' '#!/bin/sh' 'exit 0' > "$TEST_BACKUP_DIR/mc"
|
||||
chmod 0755 "$TEST_BACKUP_DIR/mc"
|
||||
docker exec "$CONTAINER_NAME" mkdir -p /tmp/test-bin
|
||||
docker cp "$TEST_BACKUP_DIR/mc" "$CONTAINER_NAME:/tmp/test-bin/mc"
|
||||
docker cp "$SCRIPT_DIR/backup.sh" "$CONTAINER_NAME:/tmp/backup.sh"
|
||||
docker exec "$CONTAINER_NAME" env \
|
||||
PATH=/tmp/test-bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
|
||||
POSTGRES_HOST=localhost POSTGRES_PORT=5432 \
|
||||
POSTGRES_DB="$TEST_DB" POSTGRES_USER="$TEST_USER" POSTGRES_PASSWORD_FILE=/tmp/test-db-password \
|
||||
BACKUP_LOCAL_DIR=/tmp/backup-test \
|
||||
bash /tmp/backup.sh
|
||||
|
||||
docker cp "${CONTAINER_NAME}:/tmp/test-backup.sql.gz" "$DUMP_FILE"
|
||||
docker exec "$CONTAINER_NAME" rm -f /tmp/test-backup.sql.gz
|
||||
DUMP_CONTAINER_PATH="$(docker exec "$CONTAINER_NAME" sh -c 'find /tmp/backup-test/postgresql -type f -name "*.sql.gz" -print -quit')"
|
||||
[[ -n "$DUMP_CONTAINER_PATH" ]] || die "backup.sh did not create a dump"
|
||||
docker cp "${CONTAINER_NAME}:${DUMP_CONTAINER_PATH}" "$DUMP_FILE"
|
||||
docker exec "$CONTAINER_NAME" rm -rf /tmp/backup-test /tmp/backup.sh /tmp/test-bin
|
||||
|
||||
[[ -f "$DUMP_FILE" ]] || die "Backup file not created"
|
||||
DUMP_SIZE=$(du -h "$DUMP_FILE" | cut -f1)
|
||||
log "Backup created: ${DUMP_SIZE}"
|
||||
|
||||
run_test "Backup file exists and is non-empty" test -s "$DUMP_FILE"
|
||||
run_test "backup.sh creates a non-empty dump using POSTGRES_PASSWORD_FILE" test -s "$DUMP_FILE"
|
||||
|
||||
# ── Step 3: Drop and recreate database ──────────────────────────
|
||||
log "Dropping and recreating test database..."
|
||||
drop_and_recreate_db
|
||||
|
||||
# Verify empty
|
||||
EMPTY_TABLES=$(run_sql "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';")
|
||||
run_test "Database is empty after drop" test "$EMPTY_TABLES" -eq 0
|
||||
|
||||
# ── Step 4: Restore from backup ─────────────────────────────────
|
||||
log "Restoring from backup..."
|
||||
# ── Step 3: Restore using the production restore script ──────────
|
||||
log "Restoring through restore.sh..."
|
||||
docker cp "$DUMP_FILE" "${CONTAINER_NAME}:/tmp/restore-dump.sql.gz"
|
||||
docker exec "$CONTAINER_NAME" pg_restore \
|
||||
-U "$TEST_USER" -d "$TEST_DB" \
|
||||
--no-owner --no-privileges \
|
||||
/tmp/restore-dump.sql.gz 2>&1 | tail -5 || true
|
||||
docker exec "$CONTAINER_NAME" rm -f /tmp/restore-dump.sql.gz
|
||||
docker cp "$SCRIPT_DIR/restore.sh" "${CONTAINER_NAME}:/tmp/restore.sh"
|
||||
docker exec "$CONTAINER_NAME" env \
|
||||
POSTGRES_HOST=localhost POSTGRES_PORT=5432 \
|
||||
POSTGRES_DB="$TEST_DB" POSTGRES_USER="$TEST_USER" POSTGRES_PASSWORD_FILE=/tmp/test-db-password \
|
||||
BACKUP_LOCAL_DIR=/tmp/backup-test bash /tmp/restore.sh \
|
||||
--file /tmp/restore-dump.sql.gz --yes
|
||||
docker exec "$CONTAINER_NAME" rm -f /tmp/restore-dump.sql.gz /tmp/restore.sh
|
||||
|
||||
# ── Step 5: Verify restored data ────────────────────────────────
|
||||
POST_SITES=$(run_sql "SELECT COUNT(*) FROM sites;")
|
||||
@@ -220,6 +216,33 @@ FK_VIOLATIONS=$(run_sql "
|
||||
")
|
||||
run_test "No FK violations in restored data" test "$FK_VIOLATIONS" -eq 0
|
||||
|
||||
# ── Step 7: Verify local object and Data Protection volume restore ──
|
||||
VOLUME_SOURCE_DIR="${TEST_BACKUP_DIR}/heimdall-volume"
|
||||
VOLUME_BACKUP_DIR="${TEST_BACKUP_DIR}/volume-backups"
|
||||
OBJECT_FILE="${VOLUME_SOURCE_DIR}/storage/snapshots/test-snapshot.bin"
|
||||
DP_KEY_FILE="${VOLUME_SOURCE_DIR}/dp-keys/dp-cert.pfx"
|
||||
mkdir -p "${VOLUME_SOURCE_DIR}/storage/snapshots" "${VOLUME_SOURCE_DIR}/dp-keys"
|
||||
printf 'snapshot fixture for restore verification\n' > "$OBJECT_FILE"
|
||||
printf 'private data-protection-key fixture for restore verification\n' > "$DP_KEY_FILE"
|
||||
chmod 0600 "$DP_KEY_FILE"
|
||||
OBJECT_DIGEST_BEFORE=$(sha256sum "$OBJECT_FILE" | cut -d' ' -f1)
|
||||
DP_KEY_DIGEST_BEFORE=$(sha256sum "$DP_KEY_FILE" | cut -d' ' -f1)
|
||||
|
||||
HEIMDALL_DATA_SOURCE="$VOLUME_SOURCE_DIR" BACKUP_LOCAL_DIR="$VOLUME_BACKUP_DIR" BACKUP_SKIP_S3_UPLOAD=1 \
|
||||
"$SCRIPT_DIR/backup-protected-data.sh"
|
||||
VOLUME_ARCHIVE=$(find "$VOLUME_BACKUP_DIR/protected-data" -maxdepth 1 -type f -name 'heimdall-data-*.tar.gz' -print -quit)
|
||||
run_test "Protected volume archive exists and is non-empty" test -s "$VOLUME_ARCHIVE"
|
||||
|
||||
rm -rf "${VOLUME_SOURCE_DIR}/storage" "${VOLUME_SOURCE_DIR}/dp-keys"
|
||||
HEIMDALL_DATA_SOURCE="$VOLUME_SOURCE_DIR" \
|
||||
"$SCRIPT_DIR/restore-protected-data.sh" --file "$VOLUME_ARCHIVE" --yes
|
||||
OBJECT_DIGEST_AFTER=$(sha256sum "$OBJECT_FILE" | cut -d' ' -f1)
|
||||
DP_KEY_DIGEST_AFTER=$(sha256sum "$DP_KEY_FILE" | cut -d' ' -f1)
|
||||
run_test "Local object preserved by volume restore" test "$OBJECT_DIGEST_AFTER" = "$OBJECT_DIGEST_BEFORE"
|
||||
run_test "Data Protection key preserved by volume restore" test "$DP_KEY_DIGEST_AFTER" = "$DP_KEY_DIGEST_BEFORE"
|
||||
DP_KEY_PERMISSIONS="$(ls -l "$DP_KEY_FILE" | awk '{print $1}')"
|
||||
run_test "Data Protection key permissions preserved" test "$DP_KEY_PERMISSIONS" = "-rw-------"
|
||||
|
||||
# ── Summary ─────────────────────────────────────────────────────
|
||||
echo ""
|
||||
log "═══════════════════════════════════════════"
|
||||
|
||||
+43
-139
@@ -41,7 +41,7 @@ Le client natif est retiré. L’application Blazor devient la cible mobile inst
|
||||
| **Docker uniquement** | FFmpeg, SIPSorcery, YOLOv8 (ONNX Runtime) ont des dépendances natives complexes |
|
||||
| Installation manuelle rejetée | Gestion des versions, dépendances système, mise à jour = cauchemar sans conteneurisation |
|
||||
|
||||
**Conséquence** : L'Agent est distribué exclusivement via `heimdall/agent:latest` (Docker Hub / registry privée).
|
||||
**Conséquence** : L'Agent est distribué exclusivement via `eltruncho/heimdall-agent` sur Docker Hub.
|
||||
Pas de binaire standalone, pas de .deb, pas d'installation manuelle. La mise à jour se fait par `docker pull` + redémarrage.
|
||||
|
||||
### D6 — SFU (MediaMTX) différé à v2
|
||||
@@ -101,7 +101,7 @@ Heimdall est une plateforme de vidéosurveillance IA locale, auto-hébergée, mu
|
||||
│ │ │ │ └────────────┘ │
|
||||
│ └──────────────────┴─────────────────┘ │
|
||||
│ │ PostgreSQL / Hangfire (schema séparé) │
|
||||
│ │ Alarik / S3 │
|
||||
│ │ RustFS / S3 │
|
||||
└──────────────────────────────┼────────────────────────────────────────┘
|
||||
│
|
||||
HTTPS REST + SignalR (events + signaling)
|
||||
@@ -131,7 +131,7 @@ services:
|
||||
heimdall-central: # Api + Web + Workers fusionnés (1 conteneur)
|
||||
heimdall-agent: # SIPSorcery + FFmpeg + YOLOv8 + Hangfire InMemory
|
||||
postgresql: # Base de données (app + hangfire)
|
||||
alarik: # Stockage S3 (enregistrements)
|
||||
rustfs: # Stockage S3 (enregistrements)
|
||||
# L'IA lourde (détection, visages, LPR) tourne sur les agents GPU (ONNX Runtime) — pas de service central
|
||||
ollama: # LLM local (résumés quotidiens)
|
||||
coturn: # TURN relay (OBLIGATOIRE, pas optionnel)
|
||||
@@ -497,7 +497,7 @@ public class CameraDetectionProfile
|
||||
| CORS | Domaines connus uniquement (pas `AllowAnyOrigin`) | P0 |
|
||||
| API Keys HMACSHA256 | Avec salt par clé, préfixe 8 chars pour identification | P0 |
|
||||
| IDataProtector | Purposes isolées par type : `CameraCredentials`, `NotificationCredentials`, `SmtpConfig` | P0 |
|
||||
| Key ring partagé | Volume Docker monté : `/root/.aspnet/DataProtection-Keys` | P0 |
|
||||
| Key ring partagé | `DataProtection` persiste les clés sous `/var/lib/heimdall/dp-keys` dans `heimdall_data`; le Compose de sauvegarde archive ce volume | P0 |
|
||||
| Audit logging | Table `AuditLog` append-only (login, admin actions, permissions) | P0 |
|
||||
| HTTPS partout | Y compris AMQP TLS vers le broker (certificat CA auto) | P1 |
|
||||
| Docker secrets | `/run/secrets/` en production, env vars en dev | P1 |
|
||||
@@ -751,7 +751,7 @@ class HeimdallLiveView {
|
||||
|
||||
## PARTIE 7 : Stockage et Hangfire
|
||||
|
||||
### 7.1 Stockage Alarik/S3
|
||||
### 7.1 Stockage RustFS/S3
|
||||
|
||||
| File Type | Path Pattern | Rétention |
|
||||
|---|---|---|
|
||||
@@ -851,7 +851,7 @@ builder.Services.AddHangfireServer(options =>
|
||||
| Job | Schedule | Queue | Description |
|
||||
|---|---|---|---|
|
||||
| `RetentionCheckJob` | Quotidien 3h | default | Purge enregistrements + S3 batch delete |
|
||||
| `S3CleanupJob` | Quotidien 4h | default | Nettoie fichiers orphelins Alarik (pagination) |
|
||||
| `S3CleanupJob` | Quotidien 4h | default | Nettoie fichiers orphelins RustFS (pagination) |
|
||||
| `CleanupUnknownFacesJob` | Dimanche 5h | default | Supprime visages inconnus > 30j |
|
||||
| `CleanupLicensePlatesJob` | Dimanche 6h | default | Plaques non associées > 30j |
|
||||
| `DatabaseMaintenanceJob` | Hebdomadaire dimanche 7h | default | VACUUM events + REINDEX (VACUUM FULL mensuel) |
|
||||
@@ -973,24 +973,24 @@ Phase 1 — Solution .NET 10 + Clean Architecture
|
||||
│ Infrastructure, Api, Web, Workers, Agent, Contracts)
|
||||
├── Project references (flux inward)
|
||||
├── NuGet packages (EF Core, Npgsql, Hangfire, SIPSorcery, Serilog...)
|
||||
├── Docker Compose de dev (PostgreSQL + Alarik + Redis)
|
||||
├── Docker Compose de dev (PostgreSQL + RustFS + Redis)
|
||||
├── Verify: dotnet build → 0 errors
|
||||
│
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│ • dotnet build sur TOUS les projets : 0 erreur
|
||||
│ • docker compose up central + postgresql + alarik : démarre
|
||||
│ • docker compose up central + postgresql + rustfs : démarre
|
||||
│ • Solution navigable dans Rider/VS
|
||||
|
||||
Phase 2 — Test Framework & Tooling
|
||||
├── xUnit + Shouldly + NSubstitute + FluentAssertions
|
||||
├── Testcontainers (PostgreSQL + Alarik réels)
|
||||
├── Testcontainers (PostgreSQL + RustFS réels)
|
||||
├── bUnit (Blazor UI), Playwright (E2E)
|
||||
├── .editorconfig + analyzers + StyleCop
|
||||
├── Verify: dotnet test → green (skeleton pass)
|
||||
│
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│ • dotnet test sur chaque projet : squelette vert
|
||||
│ • Testcontainers lance PostgreSQL + Alarik pour les tests
|
||||
│ • Testcontainers lance PostgreSQL + RustFS pour les tests
|
||||
│ • .editorconfig analysers appliqués
|
||||
|
||||
Phase 3 — CI/CD
|
||||
@@ -1002,7 +1002,7 @@ Phase 3 — CI/CD
|
||||
│
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│ • git push → pipeline CI déclenché
|
||||
│ • docker images publiées sur Docker Hub / registry
|
||||
│ • images `eltruncho/heimdall` et `eltruncho/heimdall-agent` publiées sur Docker Hub
|
||||
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
@@ -1102,20 +1102,20 @@ Phase 7 — Infrastructure EF Core
|
||||
│ • CreatedAt/UpdatedAt auto-set sur toutes les entités
|
||||
│ • Tests intégration : Testcontainers PostgreSQL, vrai DB
|
||||
|
||||
Phase 8 — Storage Alarik/S3
|
||||
├── AlarikStorageProvider (IStorageProvider)
|
||||
Phase 8 — Storage RustFS/S3
|
||||
├── RustFSStorageProvider (IStorageProvider)
|
||||
├── Staging prefix pour uploads atomiques
|
||||
├── Batch delete (RemoveObjectsAsync, 1000/appel)
|
||||
├── Health check → /health
|
||||
├── Verify: dotnet test → Testcontainers Alarik green
|
||||
├── Verify: dotnet test → Testcontainers RustFS green
|
||||
│
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
│ • UploadAsync → fichier dans Alarik (bucket recordings/)
|
||||
│ • DownloadAsync → fichier depuis Alarik
|
||||
│ • UploadAsync → fichier dans RustFS (bucket recordings/)
|
||||
│ • DownloadAsync → fichier depuis RustFS
|
||||
│ • DeleteBatchAsync → 1000 fichiers supprimés en 1 appel
|
||||
│ • Upload atomique : staging/ → move → recordings/
|
||||
│ • Si crash pendant upload : staging nettoyé, pas de fichiers orphelins
|
||||
│ • Tests intégration : Testcontainers Alarik, vrai S3
|
||||
│ • Tests intégration : Testcontainers RustFS, vrai S3
|
||||
|
||||
|
||||
┌──────────────────────────────────────────────────────────────────┐
|
||||
@@ -1238,18 +1238,15 @@ Phase 11 — Hangfire Foundation + Jobs Multi-Site
|
||||
│ → C'EST L'OBJECTIF DE L'ÉTAPE 1 │
|
||||
└──────────────────────────────────────────────────────────────────┘
|
||||
|
||||
Phase 12 — Agent Foundation (Docker-only)
|
||||
├── Docker-only : heimdall/agent:latest
|
||||
Phase 12 — Agent Foundation (multi-format installation)
|
||||
├── Image Agent `eltruncho/heimdall-agent` (Docker Hub)
|
||||
├── Installation Linux native via install/install-agent.sh et systemd
|
||||
├── Compose Docker généré dans l'IHM depuis le manifeste signé Central
|
||||
├── AgentRegistrationService (register via API au premier démarrage)
|
||||
├── HeartbeatSenderJob (Hangfire InMemory Central, 30s)
|
||||
├── Agent → Central : API Key auth (X-Api-Key header)
|
||||
├── Central → Agent : heartbeat OK renouvelle le statut Online
|
||||
├── docker-compose.yml minimal pour l'Agent :
|
||||
│ docker run -e HEIMDALL_CENTRAL_URL=https://central.example.com \
|
||||
│ -e HEIMDALL_SITE_TOKEN=abc123def456 \
|
||||
│ -e HEIMDALL_API_KEY=heimdall_sk_abc123def456 \
|
||||
│ -e HEIMDALL_AGENT_NAME=agent-paris-01 \
|
||||
│ heimdall/agent:latest
|
||||
├── L'Agent Docker utilise le réseau hôte pour accéder au LAN des caméras
|
||||
├── Verify: Agent démarre → register → heartbeat 30s
|
||||
│
|
||||
✅ Fonctionnel à la fin de cette phase :
|
||||
@@ -1801,14 +1798,14 @@ Phase 19 — Jobs Métier (retention, cleanup)
|
||||
│ │ → ExecuteDelete : DELETE FROM recordings WHERE │
|
||||
│ │ timestamp < NOW() - retention_days │
|
||||
│ │ → Batch S3 : RemoveObjectsAsync (1000 clés par appel) │
|
||||
│ │ → Enregistrements supprimés = place libérée dans Alarik │
|
||||
│ │ → Enregistrements supprimés = place libérée dans RustFS │
|
||||
│ │ │
|
||||
│ │ Résultat : 5 lignes SQL, pas de boucle, pas de OOM │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ ┌─ S3 CLEANUP ──────────────────────────────────────────────────┐
|
||||
│ │ 4h du matin : S3CleanupJob s'exécute │
|
||||
│ │ → Liste les fichiers dans Alarik prefix "recordings/" │
|
||||
│ │ → Liste les fichiers dans RustFS prefix "recordings/" │
|
||||
│ │ → Pagination : 1000 fichiers par page (continuation token) │
|
||||
│ │ → Pour chaque page : vérifie StoragePath dans DB │
|
||||
│ │ → Supprime ceux qui n'existent pas en DB │
|
||||
@@ -2023,7 +2020,7 @@ Phase 24 — Production Hardening
|
||||
├── Docker secrets (/run/secrets/) pour :
|
||||
│ ├── DB_PASSWORD, JWT_SIGNING_KEY
|
||||
│ ├── COTURN_SECRET, BROKER_AMQP_PASSWORD, SMTP_PASSWORD
|
||||
│ └── ALARIK_ADMIN_USERNAME, ALARIK_ADMIN_PASSWORD, ALARIK_JWT
|
||||
│ └── RUSTFS_ACCESS_KEY, RUSTFS_SECRET_KEY
|
||||
├── Serilog + Sentry/GlitchTip (PII stripping activé)
|
||||
│ ├── Sanitize : password, token, secret, snapshotUrl, ApiKey
|
||||
│ └── SendDefaultPii = false
|
||||
@@ -2033,11 +2030,11 @@ Phase 24 — Production Hardening
|
||||
│ └── heimdall.signalr.connections, heimdall.streaming.viewers
|
||||
├── Health checks :
|
||||
│ ├── GET /health (basique : API répond)
|
||||
│ ├── GET /health/ready (DB, Alarik, broker, Redis OK)
|
||||
│ ├── GET /health/ready (DB, RustFS, broker, Redis OK)
|
||||
│ └── GET /health/live (ready + pas de degradation active)
|
||||
├── Backup automatisé (cron) :
|
||||
│ ├── PostgreSQL : pg_dump quotidien → Alarik backup/
|
||||
│ └── Alarik : alarik mirror hebdomadaire → backup/ (versionné)
|
||||
│ ├── PostgreSQL : pg_dump quotidien → RustFS backup/
|
||||
│ └── RustFS : rustfs mirror hebdomadaire → backup/ (versionné)
|
||||
├── k6 load tests :
|
||||
│ ├── 10 agents, 50 caméras, 20 viewers simultanés
|
||||
│ ├── Latence API < 200ms p95
|
||||
@@ -2067,13 +2064,13 @@ Phase 24 — Production Hardening
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
│ ┌─ BACKUP ─────────────────────────────────────────────────────┐
|
||||
│ │ Quotidien 2h : pg_dump → Alarik backup/heimdall_YYYY-MM-DD.sql.gz │
|
||||
│ │ Quotidien 2h : pg_dump → RustFS backup/heimdall_YYYY-MM-DD.sql.gz │
|
||||
│ │ Hebdomadaire dimanche 3h : mc mirror → backup/ (versionné) │
|
||||
│ │ │
|
||||
│ │ Test de restauration : │
|
||||
│ │ 1. docker compose down │
|
||||
│ │ 2. Restaurer PostgreSQL depuis le dump │
|
||||
│ │ 3. Restaurer Alarik depuis le mirror │
|
||||
│ │ 3. Restaurer RustFS depuis le mirror │
|
||||
│ │ 4. docker compose up │
|
||||
│ │ 5. Vérifier les sites, agents, events toujours présents │
|
||||
│ └──────────────────────────────────────────────────────────────┘
|
||||
@@ -2115,114 +2112,22 @@ Plan détaillé : docs/pwa.md
|
||||
|
||||
## PARTIE 11 : Déploiement Docker
|
||||
|
||||
### 11.1 docker-compose.yml (production)
|
||||
### 11.1 Compose de déploiement
|
||||
|
||||
> **L'Agent est distribué EXCLUSIVEMENT via Docker.** Pas de binaire standalone,
|
||||
> pas d'installation manuelle. La commande Docker est générée par l'UI Admin
|
||||
> avec le token et l'API Key pré-remplis : `docker run -e HEIMDALL_SITE_TOKEN=... -e HEIMDALL_API_KEY=... heimdall/agent:latest`.
|
||||
|
||||
```yaml
|
||||
services:
|
||||
heimdall-central:
|
||||
image: heimdall/central:latest
|
||||
ports:
|
||||
- "5000:5000" # HTTPS
|
||||
environment:
|
||||
- ConnectionStrings__PostgreSQL=Server=postgresql;Database=heimdall;...
|
||||
- ConnectionStrings__Hangfire=Server=postgresql;Database=heimdall_hangfire;...
|
||||
- ConnectionStrings__Redis=redis:6379
|
||||
- Alarik__Endpoint=http://alarik:8080
|
||||
# L'IA est exécutée par les agents (ONNX Runtime) — plus de service central
|
||||
- Ollama__Endpoint=http://ollama:11434
|
||||
- Coturn__Url=turns:coturn:3478
|
||||
- Coturn__Secret=${COTURN_SECRET}
|
||||
volumes:
|
||||
- dataprotection_keys:/root/.aspnet/DataProtection-Keys
|
||||
secrets:
|
||||
- jwt_signing_key
|
||||
- coturn_secret
|
||||
- smtp_password
|
||||
|
||||
heimdall-agent:
|
||||
image: heimdall/agent:latest
|
||||
environment:
|
||||
- HEIMDALL_CENTRAL_URL=https://heimdall-central:5000
|
||||
- HEIMDALL_SITE_TOKEN=${HEIMDALL_SITE_TOKEN}
|
||||
- HEIMDALL_API_KEY=${HEIMDALL_API_KEY}
|
||||
- HEIMDALL_AGENT_NAME=${HEIMDALL_AGENT_NAME}
|
||||
volumes:
|
||||
- /dev/dri:/dev/dri # GPU Intel/AMD (optionnel)
|
||||
- /tmp/heimdall:/tmp/heimdall # Cache snapshots local
|
||||
deploy:
|
||||
resources:
|
||||
reservations:
|
||||
devices:
|
||||
- driver: nvidia
|
||||
count: all
|
||||
capabilities: [gpu]
|
||||
depends_on:
|
||||
postgresql:
|
||||
condition: service_healthy
|
||||
alarik:
|
||||
condition: service_started
|
||||
|
||||
postgresql:
|
||||
image: postgres:17
|
||||
environment:
|
||||
POSTGRES_USER: heimdall
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||
POSTGRES_DB: heimdall
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U heimdall"]
|
||||
ports:
|
||||
- "5432:5432"
|
||||
|
||||
alarik:
|
||||
image: ghcr.io/achtungsoftware/alarik:latest
|
||||
ports:
|
||||
- "9000:8080" # S3 API
|
||||
environment:
|
||||
API_BASE_URL: http://localhost:9000
|
||||
CONSOLE_BASE_URL: http://localhost:9001
|
||||
ADMIN_USERNAME: ${ALARIK_ADMIN_USERNAME}
|
||||
ADMIN_PASSWORD: ${ALARIK_ADMIN_PASSWORD}
|
||||
JWT: ${ALARIK_JWT}
|
||||
ALLOW_ACCOUNT_CREATION: false
|
||||
volumes:
|
||||
- alarik_storage:/app/Storage
|
||||
|
||||
alarik-console:
|
||||
image: ghcr.io/achtungsoftware/alarik-console:latest
|
||||
ports:
|
||||
- "9001:3000" # Console
|
||||
environment:
|
||||
NUXT_PUBLIC_API_BASE_URL: http://localhost:9000
|
||||
NUXT_PUBLIC_CONSOLE_BASE_URL: http://localhost:9001
|
||||
NUXT_PUBLIC_ALLOW_ACCOUNT_CREATION: false
|
||||
depends_on:
|
||||
- alarik
|
||||
|
||||
coturn:
|
||||
image: coturn/coturn:4.6
|
||||
command: >
|
||||
-n --use-auth-secret
|
||||
--static-auth-secret=${COTURN_SECRET}
|
||||
--realm=heimdall.local
|
||||
--fingerprint
|
||||
--no-tlsv1
|
||||
--no-tlsv1_1
|
||||
network_mode: host # nécessaire pour TURN (ports UDP)
|
||||
```
|
||||
La configuration déployable est maintenue dans `docker/` et décrite dans
|
||||
[docker-compose.md](docker-compose.md). Le noyau obligatoire contient
|
||||
uniquement Central et PostgreSQL (`docker-compose.prod.yml`). Pour chaque site,
|
||||
l’IHM génère le Compose Agent épinglé au digest du manifeste signé Central. Le
|
||||
dépôt ne garde qu’un Compose Agent de développement local.
|
||||
RustFS, ntfy, Ollama, Coturn, Redis et les sauvegardes disposent chacun d'un
|
||||
Compose facultatif. Les overlays GPU ciblent uniquement les Agents et
|
||||
n'activent pas l'inférence ONNX GPU dans l'image publiée.
|
||||
|
||||
### 11.2 GPU Passthrough
|
||||
|
||||
| Conteneur | GPU | Docker Compose |
|
||||
|---|---|---|
|
||||
| agent GPU | NVIDIA/AMD/Intel | profiles compose GPU (nvidia/rocm/vaapi) — cf. docker |
|
||||
| `heimdall-agent` | NVIDIA/Intel/AMD | `--gpus all` ou `/dev/dri:/dev/dri` |
|
||||
| `ollama` | NVIDIA (optionnel) | `--gpus all` |
|
||||
Les fichiers `docker-compose.gpu-*.yml` exposent le matériel au Compose Agent
|
||||
pour l'inventaire seulement. L'image Agent publiée embarque le fournisseur ONNX
|
||||
CPU; l'inférence GPU nécessite encore une image et un runtime dédiés.
|
||||
|
||||
---
|
||||
|
||||
@@ -2299,8 +2204,7 @@ AnalysisWorker: concurrent requests from multiple cameras
|
||||
|---|---|---|
|
||||
| API | `/health` | 30s |
|
||||
| PostgreSQL | Ping DB | 30s |
|
||||
| Alarik | GET /health | 30s |
|
||||
| Broker IA (RabbitMQ) | AMQP / healthcheck | 30s |
|
||||
| RustFS | GET /health | 30s |
|
||||
| Ollama | `/api/tags` | 60s |
|
||||
| Agent | POST /api/agents/{id}/heartbeat | 30s |
|
||||
|
||||
|
||||
+23
-16
@@ -10,9 +10,11 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
|
||||
| Si vous cherchez... | Allez voir |
|
||||
|---|---|
|
||||
| **Vue d'ensemble** du projet | `docs/specs.md` (Vision, Architecture, Stack) |
|
||||
| **Plan d'implémentation** (23 phases) | `docs/implementation.md` |
|
||||
| **État réel et travaux restants** | [Issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues) |
|
||||
| **Plan d'implémentation historique** (MVP juillet 2026) | `docs/implementation.md` |
|
||||
| **Maquettes UI Blazor** détaillées | `docs/ui-pages.md` |
|
||||
| **Application web installable (PWA)** | [Audit et plan PWA](pwa.md) |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) |
|
||||
|
||||
## 🏗️ Domaines fonctionnels
|
||||
|
||||
@@ -20,8 +22,8 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
|
||||
|---|---|---|
|
||||
| **Sites & Agents** | `docs/specs.md` (§11-12) | Sites, tokens, registration, heartbeat, bootstrap |
|
||||
| **Caméras & IA** | `docs/specs.md` (§14-19) | ONVIF, Imou, FFmpeg, GPU, AI Pipeline, détection |
|
||||
| **Streaming live** | `docs/specs.md` (§13) + `docs/signalr-usage.md` | WebRTC, SIPSorcery, SFU, signaling, JS Interop |
|
||||
| **Enregistrements** | `docs/specs.md` (§20-21) + `docs/hangfire-usage.md` | Alarik/S3, rétention, stockage local |
|
||||
| **Streaming live** | `docs/specs.md` (§13) + `docs/signalr-usage.md` | Architecture cible; consulter l'audit pour l'état livré |
|
||||
| **Enregistrements** | `docs/specs.md` (§20-21) + `docs/hangfire-usage.md` | Stockage cible; le pipeline d'enregistrement vidéo reste à raccorder |
|
||||
| **Événements** | `docs/specs.md` (§16-19) | Personnes, véhicules, plaques, notifications |
|
||||
| **Notifications** | `docs/notifications.md` | Email SMTP, Gotify, templates Markdown i18n |
|
||||
|
||||
@@ -30,10 +32,13 @@ vidéosurveillance IA locale, multi-site, auto-hébergée.
|
||||
| Domaine | Document | Contenu |
|
||||
|---|---|---|
|
||||
| **Auth & Rôles** | `docs/auth-roles.md` | Identity, JWT, permissions, UI par rôle, site-scope |
|
||||
| **IA (ONNX)** | `docs/specs.md` | détection, face, ALPR — ONNX Runtime sur agents GPU |
|
||||
| **Hangfire (jobs)** | `docs/hangfire-usage.md` | Central PostgreSQL, Agent InMemory, tous les jobs |
|
||||
| **SignalR (temps réel)** | `docs/signalr-usage.md` | 5 hubs, events, streaming, monitoring, notifications |
|
||||
| **IA (ONNX)** | `docs/specs.md` | Architecture cible; consulter l'audit pour distinguer les capacités livrées |
|
||||
| **Hangfire (jobs)** | `docs/hangfire-usage.md` | Configuration actuelle et jobs présents; vérifier l'état des parcours dans l'audit |
|
||||
| **Métriques et alertes** | [Métriques Prometheus](metrics.md) | Endpoints Web/Agent et signaux de santé exportés |
|
||||
| **SignalR (temps réel)** | `docs/signalr-usage.md` | Hubs et contrats documentés; état du streaming live dans l'audit |
|
||||
| **Déploiement Docker** | `docs/specs.md` (§30) | Containers, GPU passthrough, docker-compose |
|
||||
| **Docker Compose** | [Déploiement séparé](docker-compose.md) | Central + PostgreSQL requis; Agent et logiciels optionnels séparés |
|
||||
| **GPU Agent** | [Accès matériel et état de l'inférence](gpu-runtime.md) | Profils facultatifs; l'inférence ONNX publiée reste CPU |
|
||||
|
||||
## 📐 Structure du projet
|
||||
|
||||
@@ -45,10 +50,8 @@ Heimdall/
|
||||
│ ├── Heimdall.Contracts # DTOs partagés, constantes
|
||||
│ ├── Heimdall.Application # CQRS (Command/Query/Handler)
|
||||
│ ├── Heimdall.Infrastructure # EF Core, PostgreSQL, S3, Identity
|
||||
│ ├── Heimdall.Api # API REST + SignalR Hubs
|
||||
│ ├── Heimdall.Web # Blazor Web App (MudBlazor)
|
||||
│ ├── Heimdall.Agent # Worker + SIPSorcery + FFmpeg
|
||||
│ └── Heimdall.Workers # Hangfire jobs
|
||||
│ ├── Heimdall.Web # Blazor Server + API REST + SignalR + jobs
|
||||
│ └── Heimdall.Agent # Service agent, capture FFmpeg et analyse
|
||||
├── tests/ # xUnit + Shouldly + NSubstitute
|
||||
├── docker/ # Docker Compose + Dockerfiles
|
||||
└── docs/ # Documentation (ce dossier)
|
||||
@@ -59,19 +62,23 @@ Heimdall/
|
||||
| Fichier | Description |
|
||||
|---|---|
|
||||
| `specs.md` | Spécification complète : vision, architecture, features, déploiement |
|
||||
| `implementation.md` | Plan d'implémentation en 23 phases ordonnées |
|
||||
| `implementation.md` | Plan historique du MVP (juillet 2026); statuts non représentatifs de l'état actuel |
|
||||
| `docker-compose.md` | Déploiement Central, Agents autonomes et logiciels facultatifs |
|
||||
| `ui-pages.md` | Pages Blazor (MudBlazor) : maquettes ASCII, composants, états |
|
||||
| `pwa.md` | Audit PWA du serveur Blazor, architecture cible et plan de réalisation |
|
||||
| `auth-roles.md` | Auth : 2 user types, permissions, site-scope, UI visibility |
|
||||
| `notifications.md` | Email (SMTP), Gotify, templates Markdown i18n, hangfile queue |
|
||||
| `hangfire-usage.md` | Jobs Central (PostgreSQL) + Agent (InMemory) complets |
|
||||
| `signalr-usage.md` | 5 hubs SignalR : events, streaming, monitoring, notifications, admin |
|
||||
| `hangfire-usage.md` | Description des jobs Hangfire présents au Central et à l’Agent |
|
||||
| `metrics.md` | Métriques exportées par Central et les Agents, avec leur portée et limites |
|
||||
| `signalr-usage.md` | Hubs SignalR et contrats documentés; voir l’audit pour les capacités effectivement livrées |
|
||||
|
||||
L'audit est la source de vérité pour les constats actuels, leur statut et les travaux
|
||||
restants. Les documents de spécification décrivent parfois la cible initiale; leurs
|
||||
mentions de fonctionnalités ne prouvent pas leur livraison.
|
||||
|
||||
**Total : ~5 600 lignes de documentation**
|
||||
|
||||
## Audit du 20 octobre 2026
|
||||
|
||||
- [Rapport fonctionnel et technique](audits/2026-10-20-audit-complet.md)
|
||||
- [Plan d’implémentation priorisé](audits/2026-10-20-plan-implementation.md)
|
||||
- [Résultats de validation](audits/2026-10-20-validation.md)
|
||||
- [Issues et preuves courantes](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues)
|
||||
- [Audit et plan PWA](pwa.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
# Signatures des mises à jour Agent
|
||||
|
||||
Les mises à jour natives et Docker sont acceptées uniquement si le manifeste de release est signé par la clé de publication. La release publie aussi la clé publique ECDSA P-256. Pour le premier déploiement, l’installateur la récupère via Central sur HTTPS; l’Agent la conserve ensuite localement (Linux) ou dans la configuration générée par l’IHM (Docker/Windows). Central ne peut donc pas remplacer silencieusement la clé déjà épinglée par un Agent existant.
|
||||
|
||||
## Préparer les clés
|
||||
|
||||
Créer une paire ECDSA P-256 hors du dépôt et conserver la clé privée dans le coffre de secrets CI :
|
||||
|
||||
```sh
|
||||
openssl ecparam -name prime256v1 -genkey -noout -out agent-release-private.pem
|
||||
openssl pkey -in agent-release-private.pem -pubout -out agent-release-public.pem
|
||||
base64 -w0 agent-release-private.pem
|
||||
```
|
||||
|
||||
La dernière sortie est la valeur du secret Gitea Actions du dépôt `RELEASE_SIGNING_KEY_B64` (Settings → Actions → Secrets). Ne pas ajouter la clé privée au dépôt ni aux images. Le job de publication dérive la clé publique depuis ce secret et l’attache à chaque release. La publication d’une release échoue si le secret de signature manque. Au premier bootstrap, lorsqu’aucun Agent ni manifeste signé n’a encore été distribué, cette paire devient la racine de confiance de la première release; conserver une copie de sauvegarde privée dans un coffre sécurisé. Le jeton Gitea de publication est éphémère et limité au job déclenché par un tag SemVer; aucun PAT `RELEASE_TOKEN` n’est nécessaire.
|
||||
|
||||
Configurer également la variable Gitea Actions `RELEASE_SERVER_URL` avec l’origine HTTPS de la forge attendue (par exemple `https://sources.tordais.cc`, sans chemin). La publication compare cette valeur à `BUILD_SERVER_URL`, fourni par Gitea, avant toute publication. Les images serveur et Agent sont publiées sur Docker Hub sous `eltruncho/heimdall` et `eltruncho/heimdall-agent`; configurer les secrets Actions `DOCKERHUB_USERNAME` et `DOCKERHUB_TOKEN`. Central transmet à l’Agent le dépôt et le digest signés dans la release.
|
||||
|
||||
La publication génère `agent-update-manifest.json`, qui lie la version, les SHA-256 des archives Agent, l’image CPU et son digest, ainsi que l’image NVIDIA CUDA optionnelle et son digest. Les fichiers `agent-image.json` et `agent-image-gpu.json` contiennent les références que Central utilise pour afficher et générer les commandes Docker; leurs sommes de contrôle restent dans la sortie CI. La release contient ces deux fichiers, `agent-update-manifest.sig` (signature ECDSA/SHA-256), la clé publique et les archives Agent. La clé publique permet de vérifier les valeurs avant tout remplacement d’agent. Une modification de l’URL de la forge ou du registre reste possible sans changer cette clé.
|
||||
|
||||
Avant de générer ou mettre à jour un Agent, configurer dans Central le réglage global `updates.forgepublicurl` avec l’origine HTTPS publique de Forgejo, par exemple `https://sources.tordais.cc`. Central construit l’endpoint fixe `https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases/latest`; l’endpoint calculé est affiché en lecture seule dans l’IHM. Les anciennes valeurs `updates.releaseapiurl` sont migrées automatiquement vers leur origine Forgejo. Le panneau d’installation n’affiche les commandes Linux/Windows que si cette API retourne la clé, le manifeste signé et les archives nécessaires; les commandes Docker exigent aussi un digest vérifié. Publier une version signée en poussant un tag Git `MAJOR.MINOR.PATCH` (suffixe prerelease accepté). Les merges ordinaires vers `main` mettent à jour Docker Hub pour les images touchées mais ne créent pas de release. Chaque release versionnée contient les archives Agent et leurs métadonnées signées consommées par les installateurs natifs et les mises à jour, ainsi que le ZIP d’installation serveur versionné; elle ne contient pas d’images Docker.
|
||||
|
||||
Pour installer une version précise du serveur, télécharger et extraire `heimdall-installers-<version>.zip` depuis sa release Gitea, puis lancer `install/install-server.sh` ou `install/install-server.ps1`. Ces copies utilisent les fichiers du bundle et épinglent l’image Central à la même version Docker Hub. Les scripts servis directement depuis `main` récupèrent le dernier bundle stable via l’API Gitea puis exécutent le script inclus, épinglé sur cette version. Sous Linux, ils requièrent `curl`, `jq`, `unzip`, Docker Compose et OpenSSL. La variable `HEIMDALL_INSTALLER_VERSION` sélectionne une version précise.
|
||||
|
||||
Les mises à jour automatiques natives sont désactivées par défaut dans les réglages globaux Agent; chaque site peut hériter de ce réglage ou le remplacer. L’Agent vérifie les releases toutes les 12 heures et attend que `publishedAt` ait au moins 24 heures avant d’appliquer une mise à jour automatique. Une demande manuelle d’administrateur peut déclencher la mise à jour immédiatement. Les installations Docker/Kubernetes ne font pas de polling d’image local : elles suivent le mécanisme de l’orchestrateur et le digest fourni par l’IHM.
|
||||
|
||||
## Installer un Agent natif
|
||||
|
||||
Central affiche une commande Bash ou PowerShell qui télécharge et exécute l’installateur pour le site, sans copier les scripts ni la clé sur l’hôte. L’installateur vérifie le manifeste et l’archive avant installation. Le runtime .NET 10, `jq`, `openssl` et `python3` doivent être présents sous Linux; Windows télécharge le runtime .NET requis si besoin. Le paramètre local de clé reste disponible pour les installations Linux isolées :
|
||||
|
||||
```sh
|
||||
sudo bash install/install-agent.sh \
|
||||
--central-url https://central.example.org \
|
||||
--site-token 'JETON_DE_SITE' \
|
||||
--update-public-key /chemin/local/agent-release-public.pem
|
||||
```
|
||||
|
||||
L’installateur Linux est servi par Central avec son superviseur. Il installe la release sous `/opt/heimdall/agent/releases/`; le service systemd utilise le lien `current`. Après téléchargement vérifié, le superviseur accorde jusqu’à 180 secondes au démarrage, exige ensuite 60 secondes de réponse continue de `/api/version` pour la version attendue et rétablit la release précédente si cette validation échoue.
|
||||
|
||||
Sous Windows, copiez la commande PowerShell générée dans l’IHM pour le site, en mode processus utilisateur ou service Windows. Elle télécharge le script depuis Central et applique `ExecutionPolicy Bypass` à la session PowerShell courante uniquement; elle ne change pas la stratégie persistante de la machine. L’installation comme service exige une session PowerShell élevée. Une stratégie imposée par une stratégie de groupe peut toujours interdire l’exécution.
|
||||
|
||||
Pour un Agent Docker, le Compose et les commandes `docker run` générés par l’IHM installent le dépôt d’image avec le tag `latest`; Compose et `docker run` vérifient le registre au démarrage. Le parcours CPU est sélectionné par défaut. Le parcours CUDA est proposé quand la release fournit l’image GPU signée; il demande aussi le NVIDIA Container Toolkit sur l’hôte. Aucun fichier de clé n’est à créer manuellement. Pour les mises à jour déclenchées ensuite par Central, l’Agent vérifie la signature et le digest d’image du manifeste signé avant de remplacer le conteneur. Les Agents configurés sur CUDA continuent de sélectionner l’image GPU pendant les mises à jour.
|
||||
|
||||
## Rotation
|
||||
|
||||
Une rotation de clé exige de déployer d’abord la nouvelle clé publique sur chaque Agent par une mise à jour locale de confiance, puis de publier les releases avec la nouvelle clé privée. Les Agents déjà installés refusent les releases signées uniquement par la nouvelle clé tant qu’elle n’a pas été ajoutée localement. Conserver une procédure de retour arrière et la dernière release vérifiée pendant la transition.
|
||||
|
||||
La CI distante doit encore démontrer une release signée complète sur un runner capable de joindre la forge et le registre. L’installation native Windows et son rollback doivent être validés sur Windows réel; Linux natif reste à valider sur un hôte Linux. Les installations Docker restent confiées au cycle d’image généré par l’IHM.
|
||||
@@ -1,387 +0,0 @@
|
||||
# Audit fonctionnel et technique Heimdall
|
||||
|
||||
Date : 20 octobre 2026. Révision auditée : `7792353`, avec l’état courant du répertoire de travail.
|
||||
|
||||
## Conclusion
|
||||
|
||||
Le projet possède un socle conséquent : API et interface Blazor unifiées, Identity/JWT, gestion des sites, agents, caméras, découverte réseau, pipeline FFmpeg/YOLO, stockage abstrait, notifications et maintenance. Cependant, plusieurs ensembles sont implémentés isolément sans parcours de bout en bout. La présence d’une entité, d’une option ou de tests unitaires ne permet pas de considérer la fonctionnalité comme livrée.
|
||||
|
||||
Les priorités sont la sécurité de l’authentification 2FA et de l’isolation multi-site, la confidentialité des réglages, la propagation des affectations aux agents, puis le raccordement de l’analyse distribuée et de la chaîne de snapshots. Le live WebRTC, l’enregistrement vidéo et plusieurs analyses spécialisées restent à construire. Le client natif a été supprimé à la demande du propriétaire ; l’accès mobile cible désormais la PWA du serveur, dont l’audit est détaillé dans [docs/pwa.md](../pwa.md).
|
||||
|
||||
Ce document recense les défauts observés et les absences identifiables dans le périmètre examiné. Il ne prétend pas démontrer l’absence de tout autre défaut, notamment matériel, concurrent ou opérationnel.
|
||||
|
||||
## Périmètre et méthode
|
||||
|
||||
- Lecture des spécifications, de la solution, des projets et du déploiement ; suivi des parcours UI → API → handlers → persistance et agent → Central.
|
||||
- Recherches des implémentations et de leurs appels, des fonctionnalités annoncées et des marqueurs d’incomplétude.
|
||||
- Exécution de `dotnet test Heimdall.slnx --verbosity minimal` ; tentative de tests Android `./gradlew :domain:test --no-daemon --console=plain`.
|
||||
- Sondes temporaires hors dépôt pour vérifier le comportement réel des channels .NET, la validation de chemins et le parseur cron Hangfire chargé depuis les binaires du projet.
|
||||
- Aucun correctif métier, aucune migration ni déploiement effectué. Le retrait demandé du client natif, de son job CI et de sa documentation a été effectué après l’inspection initiale. Les modifications étrangères à ce retrait ont été préservées.
|
||||
|
||||
Limites : pas de caméra physique, pas de validation WebRTC/TURN sur réseau réel, pas de livraison SMTP/ntfy réelle, pas de test de charge, pas de restauration de production ni d’audit exhaustif des dépendances/CVE. Les scripts d’installation et de sauvegarde ont été inventoriés ; leur fonctionnement complet n’est pas certifié par cet audit. Les anomalies de sécurité ci-dessous sont établies par inspection des contrôles ; elles n’ont pas fait l’objet d’une exploitation contre un service déployé.
|
||||
|
||||
Priorités : **P0** = sécurité à corriger avant exposition ; **P1** = parcours central cassé ou perte de données ; **P2** = fonction partielle ou incohérente ; **P3** = qualité documentaire/ergonomique. « Confirmé » désigne une preuve dans le code ou une sonde locale ; « à valider » désigne une conséquence dépendant de l’environnement.
|
||||
|
||||
## Couverture fonctionnelle observée
|
||||
|
||||
| Domaine | État observé | Réserves principales |
|
||||
|---|---|---|
|
||||
| Authentification, comptes, rôles | Présent, anomalies critiques | Parcours 2FA, compte verrouillé, durée des sessions |
|
||||
| Sites et accès caméras | Présent, isolation incomplète | Écritures, détails sites/agents, groupes, hubs |
|
||||
| Enregistrement agents, heartbeat, inventaire | Présent | Identité de l’agent non liée aux ressources ciblées |
|
||||
| Découverte ONVIF/mDNS/ports, tests de flux | Implémentée | Validation avec vrais modèles de caméras à réaliser |
|
||||
| Affectations et failover | Persistance présente | Propagation aux agents et absence de remplaçant |
|
||||
| Capture FFmpeg et analyse YOLO | Implémentées partiellement | File saturée, coordonnées, profils, GPU |
|
||||
| Analyse distante HTTP / RabbitMQ | Non raccordée de bout en bout | Endpoint broker, publication et consommateurs manquants |
|
||||
| Événements et historique | CRUD et UI présents | Images absentes du pipeline, pertes réseau, liens métier |
|
||||
| Snapshots et galerie | UI et stockage abstrait présents | Capture manuelle factice, upload/lecture absents |
|
||||
| Personnes et véhicules | CRUD présent | Reconnaissance automatique visage/plaque absente |
|
||||
| Notifications | Consultation, config et services présents | Détection → destinataires → livraison non raccordée |
|
||||
| Vidéo live WebRTC / PTZ / audio | Non livrés dans le code examiné | Snapshot historique présenté comme vue live |
|
||||
| Enregistrement et replay | Modèle persistant seulement | Segmentation, upload, API, lecteur, quotas absents |
|
||||
| Stockage/rétention | Providers et jobs présents | Objets orphelins, routage historique, chemin local |
|
||||
| Accès mobile PWA | Cible à implémenter, client natif retiré | Manifeste, worker, offline, sessions et Web Push : voir docs/pwa.md |
|
||||
| Exploitation | CI existante à reconstruire pour Gitea ; métriques, Docker et sauvegardes présents | Refonte complète des builds (BUILD-01), validation réelle et documentation |
|
||||
|
||||
## Anomalies de sécurité
|
||||
|
||||
### SEC-01 — P0 — Vérification 2FA sans preuve de première étape — confirmé
|
||||
|
||||
Sources : `src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs`, `src/Heimdall.Application/DTOs/AuthDto.cs`, `src/Heimdall.Web/Controllers/AuthController.cs`.
|
||||
|
||||
`Verify2fa` accepte un email et un code puis émet directement les tokens. Il ne valide ni challenge délivré après le mot de passe, ni verrouillage du compte, ni activation effective de la 2FA, ni confirmation email. Un TOTP ou code de récupération valide suffit sans validation préalable du mot de passe ; un compte verrouillé peut également atteindre l’émission de tokens par ce chemin.
|
||||
|
||||
Correction : challenge court, signé ou persisté, à usage unique, lié à l’utilisateur et délivré après mot de passe valide ; contrôle du statut du compte et compteur d’échecs ; consommation atomique des codes de récupération. Valider les refus sans challenge, après expiration, après verrouillage et lors d’un rejeu concurrent.
|
||||
|
||||
### SEC-02 — P1 — Le login rejette le résultat normal « RequiresTwoFactor » — confirmé
|
||||
|
||||
Sources : `Auth/Commands/Login/LoginHandler.cs` et `Infrastructure/Security/AuthSignInService.cs`.
|
||||
|
||||
L’adaptateur distingue `RequiresTwoFactor`, mais la branche 2FA du handler n’accepte que `Success`. Le résultat attendu après un mot de passe valide sur un compte 2FA est traité comme une erreur. Les mocks peuvent masquer cette incompatibilité.
|
||||
|
||||
Correction : raccorder explicitement ce résultat au challenge de SEC-01. Tester avec le vrai SignInManager et son stockage Identity.
|
||||
|
||||
### SEC-03 — P0 — Une clé agent peut cibler un autre agent ou une autre caméra — confirmé
|
||||
|
||||
Sources : `Web/Controllers/AgentsController.cs` (`Heartbeat`, `SubmitDiscovery`, `ReportCameraStatus`, `SubmitLogs`), `Web/Controllers/EventsController.cs`, `Infrastructure/Security/ApiKeyAuthenticationHandler.cs`, `Application/Agents/Commands/Heartbeat/HeartbeatHandler.cs`.
|
||||
|
||||
La clé porte un `site_id`, mais les routes utilisent les identifiants fournis sans les comparer systématiquement à cette identité. Le NameIdentifier de la clé correspond à l’entité ApiKey, pas à l’Agent. La vérification « caméra et agent du même site » de ReportCameraStatus ne suffit pas : l’agent de la route peut lui-même être usurpé. CreateEvent et AttachSnapshot ne vérifient pas le site de la clé.
|
||||
|
||||
Correction : résolution serveur clé → agent/site, puis contrôle centralisé de chaque ressource et affectation. Tests croisés avec deux sites et deux agents, incluant heartbeat, logs, événements, snapshots et découverte.
|
||||
|
||||
### SEC-04 — P0 — Abonnements SignalR insuffisamment autorisés — confirmé
|
||||
|
||||
Sources : `Web/Hubs/EventsHub.cs`, `MonitoringHub.cs`, `ConfigHub.cs`.
|
||||
|
||||
- EventsHub accepte tout GUID de site sans contrôle d’accès.
|
||||
- MonitoringHub vérifie seulement l’existence d’au moins une caméra accessible, sans rattacher cette caméra au site demandé ; JoinAdminBroadcast n’exige aucune permission administrateur.
|
||||
- ConfigHub permet à une clé valide de rejoindre le groupe d’un autre agent en fournissant son GUID.
|
||||
|
||||
Conséquence : réception de données ou réglages d’un périmètre non autorisé. Correction : autorisation sur site/caméra et identité agent dérivée de la clé, refus par défaut, permissions explicites sur les méthodes sensibles.
|
||||
|
||||
### SEC-05 — P0 — Les réglages globaux sensibles sont diffusés aux agents — confirmé
|
||||
|
||||
Sources : `Web/Controllers/SettingsController.cs` (`Create`, `Update`), `Web/Hubs/ConfigHub.cs` (`NotifyGlobalSettingChanged`), `Agent/Services/ConfigReceiverService.cs`.
|
||||
|
||||
La lecture complète filtre les paramètres `AgentScoped`, mais création/modification diffuse toute paire clé/valeur à `Clients.All`, y compris les réglages globaux d’intégration. Le broadcaster écrit aussi les valeurs en debug et l’agent les journalise en information.
|
||||
|
||||
Correction : diffuser uniquement les réglages autorisés pour les agents, sans secrets dans les logs ; préférer un signal de rechargement ciblé à l’envoi brut. Tester une modification SMTP/S3 avec un agent connecté et vérifier contenu reçu et logs.
|
||||
|
||||
### SEC-06 — P0 — Contrôles de périmètre absents sur plusieurs routes humaines — confirmé
|
||||
|
||||
Sources : `Web/Controllers/CamerasController.cs`, `EventsController.cs`, `SitesController.cs`, `AgentsController.cs`, handlers correspondants.
|
||||
|
||||
Les lectures de listes sites/caméras/événements ont un filtrage utilisateur, mais Update/Delete/Toggle caméra et Delete événement ne transportent pas d’identité utilisateur et les handlers ne font pas d’autorisation sur la ressource. Le détail d’un site et les lectures agents/logs utilisent une permission générale sans contrôle du site demandé. Un utilisateur ayant la permission générale correspondante peut cibler un identifiant hors de son périmètre.
|
||||
|
||||
Correction : appliquer un service d’autorisation de ressource à tous les chemins, y compris détails, écritures et exports. Définir explicitement si le référentiel personnes/véhicules doit être global ou limité aux sites : ce choix n’est pas suffisamment exprimé dans les parcours actuels.
|
||||
|
||||
### SEC-07 — P1 — Verrouillage utilisateur contourné par renouvellement — confirmé
|
||||
|
||||
Sources : `Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs`, `Users/Commands/LockUser/LockUserHandler.cs`, `Web/Program.cs` (`ConfigureCookieAuthentication`, `MapAuthEndpoints`).
|
||||
|
||||
RefreshToken vérifie l’existence de l’utilisateur mais pas son verrouillage. LockUser ne révoque pas les refresh tokens. Le cookie construit à partir du JWT est valable sept jours avec des claims copiés ; la révocation et l’actualisation des permissions de cette session doivent aussi être définies et testées.
|
||||
|
||||
Correction : statut utilisateur à chaque renouvellement, version de session/security stamp, invalidation des sessions lors de verrouillage et changement de droits. Ne pas confondre révocation immédiate et expiration naturelle d’un JWT existant.
|
||||
|
||||
### SEC-08 — P1 — Le stockage local accepte certains chemins hors racine — confirmé par sonde
|
||||
|
||||
Source : `Infrastructure/Storage/LocalStorageProvider.cs`, `ResolvePath`.
|
||||
|
||||
Le contrôle `path.StartsWith(_root)` accepte un répertoire frère dont le nom partage le préfixe : racine `/tmp/audit/storage`, clé `../storage-sibling/secret`. La sonde retourne `accepted=True` pour le chemin échappé. L’exploitabilité HTTP dépendra du raccordement des endpoints de stockage, actuellement absent.
|
||||
|
||||
Correction : comparaison avec séparateur de répertoire ou chemin relatif contrôlé, politique pour liens symboliques, tests de traversées et de répertoires frères.
|
||||
|
||||
### SEC-10 — P1 — Renouvellement automatique web court-circuité — confirmé
|
||||
|
||||
Source : `Web/Services/TokenRefreshHandler.cs`, TryRefreshTokenAsync.
|
||||
|
||||
Après un 401, la méthode retourne true dès qu’AccessToken n’est pas vide. Le cas normal d’un token expiré conserve justement une valeur non vide : aucun appel refresh n’est effectué et la requête est rejouée avec le même token expiré. Le contrôle doit comparer le token ayant échoué à un éventuel token renouvelé, pas sa seule présence. Le fallback de base URL du refresh sans HttpContext est également `http://localhost/` sans port effectif.
|
||||
|
||||
Correction : renouvellement sérialisé par session, comparaison de version/token, résolution du port réel, refus d’une boucle de retry ; test d’expiration dans une vraie session Blazor. Les handlers HTTP capturent aussi des services AuthState scoped via IHttpClientFactory : leur portée est à vérifier séparément de celle du circuit.
|
||||
|
||||
## Ruptures du pipeline et fonctionnalités absentes
|
||||
|
||||
### PIPE-01 — P1 — Analyse distribuée non raccordée — confirmé
|
||||
|
||||
Sources : `Infrastructure/Services/AnalysisJobSchedulerService.cs`, `Web/MassTransitConfiguration.cs`, `Agent/AnalysisJobConsumer.cs`, `Agent/Services/RemoteFrameBrokerService.cs`.
|
||||
|
||||
DispatchJobAsync enregistre l’état Dispatched sans publier AnalysisJobRequested. Aucun consommateur Central de AnalysisJobCompleted/Failed n’est enregistré ; aucun appel applicatif de CreateJobAsync n’a été trouvé hors de sa définition. Le mode HTTP distant poste vers `/api/frames`, dont aucun endpoint n’a été trouvé dans ce dépôt. Un broker externe pourrait fournir ce contrat, mais son déploiement n’est pas présent ici.
|
||||
|
||||
Correction : choisir un parcours supporté, raccorder ingestion → planification → transport → exécution → persistance résultat/événement, avec outbox, idempotence, timeout et observabilité.
|
||||
|
||||
### PIPE-02 — P1 — Routage et résultat du consommateur incomplets — confirmé
|
||||
|
||||
Sources : `Agent/MassTransitConfiguration.cs`, `Agent/AnalysisJobConsumer.cs`, contrats AnalysisJob*.
|
||||
|
||||
Les agents utilisent ConfigureEndpoints sans queue spécifique à l’identité de l’agent ; le consommateur abandonne les tâches dont AgentId ne correspond pas. En déploiement à queue partagée, un autre agent peut acquitter le travail du destinataire. Tous les jobs passent par le même détecteur YOLO et un résultat null (modèle absent, dégradation) devient un succès à zéro détection. Le cycle Start/Complete du planificateur n’est pas raccordé au transport.
|
||||
|
||||
Correction : adresse de queue agent ou routage explicite, type d’analyse explicite, erreurs distinctes de « zéro objet », transitions cohérentes et résultats détaillés persistés. Tester deux agents simultanés, modèle indisponible et messages dupliqués.
|
||||
|
||||
### PIPE-03 — P1 — Saturation de la file d’analyse : tâche orpheline — confirmé par sonde
|
||||
|
||||
Source : `Agent/Services/FrameAnalyzerService.cs`, construction du channel et AnalyzeFrameAsync.
|
||||
|
||||
Le commentaire suppose que DropWrite rend TryWrite false lorsque la file est pleine. La sonde .NET 10 montre `first=True, second=True, retained=1` : le nouvel élément est perdu mais l’écriture est annoncée réussie. Son TaskCompletionSource n’est jamais complété ; sans annulation, le pipeline reste bloqué. La destruction du service n’attend pas non plus la boucle avant de libérer la session ONNX et ne termine pas tous les jobs en attente.
|
||||
|
||||
Correction : mode Wait avec TryWrite pour refus explicite, ou callback de drop qui complète la tâche ; arrêt asynchrone ordonné et tests de saturation/arrêt.
|
||||
|
||||
### PIPE-04 — P1 — Coordonnées de détection erronées sur images non 640×640 — confirmé
|
||||
|
||||
Source : `Agent/Services/FrameAnalyzerService.cs`, RunInference.
|
||||
|
||||
L’image est redimensionnée avant la lecture de sa taille destinée à ParseYoloOutput. Le retour aux dimensions originales reçoit toujours 640×640 ; les bounding boxes ne correspondent donc pas au JPEG original renvoyé. Le prétraitement suppose aussi trois canaux sans conversion explicite RGB : robustesse à valider sur JPEG gris/CMYK.
|
||||
|
||||
Correction : conserver dimensions originales, établir une transformation documentée resize/letterbox et son inverse, forcer RGB et valider les métadonnées d’entrée/sortie du modèle.
|
||||
|
||||
### PIPE-05 — P2 — Détection de mouvement approximative et profils ignorés — confirmé
|
||||
|
||||
Sources : `Agent/Services/FrameMotionDetector.cs`, `SnapshotPipelineService.cs`, `AgentCameraConfig.cs`, `Application/Settings/Queries/GetEffectiveAgentConfig/GetEffectiveAgentConfigQuery.cs`.
|
||||
|
||||
Le mouvement est estimé par variation de taille JPEG, explicitement décrite comme provisoire. Les paramètres DetectPerson/Vehicle/Motion, FaceRecognition, LicensePlateRecognition et MinConfidence du profil ne sont pas transmis dans AgentCameraConfig ; le pipeline appelle l’analyse avec le seuil par défaut. Une option enregistrée n’a donc pas forcément d’effet sur l’exécution.
|
||||
|
||||
Correction : motion gate par pixels, profil versionné distribué à l’agent, seuils/filtres appliqués et tests montrant l’effet de chaque option.
|
||||
|
||||
### PIPE-06 — P2 — GPU inventorié mais inférence locale CPU — confirmé
|
||||
|
||||
Sources : `Agent/Services/FrameAnalyzerService.cs`, `Agent/Heimdall.Agent.csproj`, `Infrastructure/Services/AnalysisJobSchedulerService.cs`.
|
||||
|
||||
Le package ONNX Runtime et la session ne configurent pas de provider GPU. Le scheduler exige pourtant un GPU pour plusieurs types de jobs. Correction : providers réellement supportés, détection de disponibilité opérationnelle, fallback explicite et sélection selon capacités mesurées ; benchmark sur matériel cible.
|
||||
|
||||
### PIPE-07 — P1 — Affectations, modifications caméra et failover non poussés au pipeline — confirmé
|
||||
|
||||
Sources : `Infrastructure/Services/CameraAssignmentService.cs`, `Application/Assignments/Commands/AssignCamera/AssignCameraHandler.cs`, commandes caméra, `Agent/Services/ConfigReceiverService.cs`.
|
||||
|
||||
La configuration complète contient les caméras affectées, mais les mutations d’affectation/caméra ne déclenchent pas de notification de rechargement. L’agent charge sa configuration au démarrage ; la reconnexion rejoint le groupe sans resynchroniser l’état complet. Les changements peuvent rester invisibles jusqu’à un autre reload ou redémarrage.
|
||||
|
||||
Correction : événements de configuration après commit pour anciens/nouveaux agents, version de configuration et resynchronisation à chaque reconnexion. Vérifier ajout, retrait, changement RTSP et désactivation sur un agent déjà connecté.
|
||||
|
||||
### PIPE-08 — P1 — Failover sans remplaçant laisse un état incohérent — confirmé
|
||||
|
||||
Source : `Infrastructure/Services/CameraAssignmentService.cs`, FailoverAgentAsync.
|
||||
|
||||
Toutes les affectations sont libérées avant la recherche de remplaçants. Si aucun n’est disponible, Camera.AgentId conserve l’ancien agent, sans affectation active. Le prochain balayage ne retrouve plus ces affectations libérées ; le retour ultérieur d’un agent ne suffit pas à les reprendre par ce chemin.
|
||||
|
||||
Correction : état « en attente d’affectation », remise en file récurrente, cohérence Camera.AgentId/CameraAssignment dans une transaction et contrainte d’unicité de l’affectation active.
|
||||
|
||||
### PIPE-09 — P1 — Chaîne snapshot non livrée — confirmé
|
||||
|
||||
Sources : `Agent/Services/DetectionReporterService.cs`, `Web/Controllers/EventsController.cs`, `Infrastructure/Storage/*`, `Web/Components/Pages/CamerasPage.razor` (TakeSnapshot), `CameraDetail.razor`.
|
||||
|
||||
L’agent publie les métadonnées mais n’upload pas le JPEG et ne raccorde pas l’image à l’événement. Les providers Upload/Download n’ont pas d’appel métier trouvé. Aucun endpoint de capture/upload/lecture caméra n’est exposé. Le bouton TakeSnapshot affiche seulement un snackbar puis Task.CompletedTask ; RefreshSnapshot relit l’historique.
|
||||
|
||||
Correction : commande de capture avec identifiant de corrélation, upload authentifié et borné, miniature, association événement, lecture autorisée ou URL signée et état réel dans l’UI.
|
||||
|
||||
### PIPE-10 — P1 — Événements perdus pendant une indisponibilité réseau — confirmé
|
||||
|
||||
Source : `Agent/Services/DetectionReporterService.cs`.
|
||||
|
||||
Le comportement documenté est de perdre les rapports échoués, sans retry durable. Une panne Central/réseau efface donc des détections de sécurité. Correction : spool local borné et persistant, identifiant d’événement agent, reprise avec backoff et déduplication serveur ; mesurer l’âge et le nombre d’événements en attente.
|
||||
|
||||
### PIPE-11 — P1 — Le bonus GPU exclut certains agents valides — confirmé
|
||||
|
||||
Source : `Infrastructure/Services/AnalysisJobSchedulerService.cs`, ComputeAgentScore et SelectBestAgentInternalAsync.
|
||||
|
||||
Un agent GPU du même site, sans charge, reçoit un score -2 pour un job ne nécessitant pas strictement de GPU. Le filtre `.Where(x => x.Score >= 0)` interprète ensuite toute valeur négative comme une disqualification. Le meilleur agent peut donc être retiré des candidats alors qu’il satisfait CPU/RAM.
|
||||
|
||||
Correction : représenter l’éligibilité séparément du score, ou employer un marqueur impossible à confondre avec un bonus ; tester agent GPU seul, même site/autre site, avec et sans charge, pour chaque type de job.
|
||||
|
||||
### FEAT-01 — P2 — Live WebRTC, PTZ et audio absents du parcours livré — confirmé
|
||||
|
||||
Sources : `Web/Program.cs` (hubs mappés), `Web/Components/Pages/CameraDetail.razor`, inventaire des fichiers de streaming.
|
||||
|
||||
Pas de hub de signaling ou pipeline SIPSorcery trouvé ; le détail web montre le dernier snapshot événementiel rafraîchi, potentiellement ancien. Le client natif a été retiré ; le streaming devra être fourni par la surface web/PWA. Coturn dans Docker et des permissions Live ne constituent pas un parcours de streaming.
|
||||
|
||||
À implémenter : signaling autorisé, gestion sessions, transport média, ICE/TURN, reconnexion et lecteur web/PWA ; commandes PTZ/audio selon caméras et capacités réellement prises en charge. Afficher l’horodatage et éviter l’indication trompeuse « live » tant que le flux n’est pas actif.
|
||||
|
||||
### FEAT-02 — P2 — Enregistrement, replay et politiques de stockage non livrés — confirmé
|
||||
|
||||
Sources : `Domain/Entities/Recording.cs`, `StoragePolicy.cs`, `Infrastructure/Jobs/RetentionCheckJob.cs` et inventaire API/UI.
|
||||
|
||||
Le modèle et sa configuration EF existent ; aucun producteur métier Recording, service de segmentation, API de recherche/lecture/export ni page de replay trouvé. À construire : segments FFmpeg, journal d’upload, recherche temporelle, lecture seek/range, quotas, politiques et reprise après crash.
|
||||
|
||||
### FEAT-03 — P2 — Reconnaissance visage et plaques non livrées — confirmé
|
||||
|
||||
Sources : `Agent/AnalysisJobConsumer.cs`, `FrameAnalyzerService.cs`, handlers Persons/Vehicles, entités KnownFace/LicensePlate.
|
||||
|
||||
Le CRUD personnes/embeddings/véhicules existe, mais aucun pipeline d’extraction d’embeddings, matching, OCR plaque ou génération automatique des liens métier n’a été trouvé. Le consommateur exécute YOLO quel que soit le type de job. Ne pas exposer ces options comme actives avant d’avoir modèles, seuils, résultats structurés et fixtures de validation.
|
||||
|
||||
### FEAT-04 — P2 — Droits par groupe enregistrés mais ignorés — confirmé
|
||||
|
||||
Sources : `Application/Groups/Commands/AddCameraToGroup/AddCameraToGroupCommand.cs`, `Infrastructure/Services/CameraAccessService.cs`.
|
||||
|
||||
Le service d’accès additionne UserCameraAccess, UserCamera et UserSite, mais jamais UserGroup/GroupCameraAccess. Donner une caméra à un groupe ne donne donc pas accès aux membres via ces contrôles. Ajouter les groupes dans toutes les méthodes de filtrage et tester ajout/retrait d’un membre.
|
||||
|
||||
### FEAT-05 — P1 — Détections non transformées en notifications utilisateur — confirmé
|
||||
|
||||
Sources : `Application/Events/Notifications/EventCreatedNotificationHandler.cs`, `Infrastructure/Services/NotificationService.cs`, `Jobs/SendNotificationJob.cs`.
|
||||
|
||||
Le handler EventCreated ne fait que diffuser sur EventsHub. Aucun appel métier de CreateNotificationAsync n’a été trouvé ; les services et préférences existent mais la sélection des destinataires et la création des alertes ne sont pas raccordées. L’envoi externe existant se fait directement dans NotificationService et absorbe les erreurs, sans utiliser SendNotificationJob pour une reprise durable.
|
||||
|
||||
Correction : règles événement → destinataires autorisés → préférence → notification persistée → livraison par canal, avec outbox et statuts. Le rate limiter est partagé par caméra/type, sans utilisateur : appliqué dans une boucle de destinataires, il peut priver les derniers destinataires de notification. Séparer déduplication événement et limitation de livraison.
|
||||
|
||||
## Stockage, exploitation et interface
|
||||
|
||||
### OPS-01 — P1 — Rétention SQL sans suppression des fichiers — confirmé
|
||||
|
||||
Sources : `Infrastructure/Jobs/RetentionCheckJob.cs`, `CleanupUnknownFacesJob.cs`, providers de stockage.
|
||||
|
||||
Les jobs suppriment les références SQL. S3CleanupJob est mentionné dans des commentaires mais aucune implémentation trouvée. Les objets restent sans référence, ce qui empêche une rétention effective et peut saturer le stockage.
|
||||
|
||||
Correction : tombstones/outbox de suppression conservant provider, bucket et clé, purge idempotente avec retry, réconciliation des orphelins et contrôle des fichiers staging. Ne supprimer la dernière référence qu’après journalisation du travail de purge.
|
||||
|
||||
### OPS-02 — P2 — Changement de provider sans routage historique — confirmé
|
||||
|
||||
Source : `Infrastructure/Storage/StorageProviderFactory.cs`.
|
||||
|
||||
Chaque opération utilise le provider actuellement sélectionné ; le fichier historique peut se trouver sur l’ancien provider. Un fallback silencieux S3 → Local masque aussi une mauvaise configuration. Les clients S3 sont recréés à chaque résolution sans gestion explicite de leur libération. Persister la localisation de chaque objet, résoudre par objet et rendre les erreurs de configuration visibles.
|
||||
|
||||
### OPS-03 — P2 — Purge des partitions anciennes inopérante — confirmé
|
||||
|
||||
Source : `Infrastructure/Jobs/PartitionManagerJob.cs`.
|
||||
|
||||
Le nom `camera_events_2025_01` compte 21 caractères ; le parseur exige au moins 22 et utilise les offsets 15 et 20 au lieu de 14 et 19. Les noms générés par le job ne peuvent pas être reconnus pour purge. Le reader reste également ouvert avant les commandes DROP sur la même connexion : à corriger lors de la remise en service de cette branche.
|
||||
|
||||
Correction : parsing strict du préfixe et suffixe, fermeture du reader avant DDL, test PostgreSQL avec partitions passée/courante/future et noms non conformes.
|
||||
|
||||
### OPS-04 — P2 — Timeout sweep planifié chaque seconde — confirmé
|
||||
|
||||
Source : `Infrastructure/BackgroundJobs/JobSetup.cs`.
|
||||
|
||||
Le cron `*/1 * * * * *` à six champs désigne chaque seconde, malgré le commentaire « every 60s ». La sonde confirme que la version Hangfire du projet accepte les crons à six champs ; il ne s’agit pas d’une erreur de syntaxe. Utiliser `* * * * *` pour une fréquence minute et vérifier les occurrences, la concurrence entre sweeps et les métriques de requêtes.
|
||||
|
||||
### OPS-05 — P1 — Mise à jour agent : autorisation incompatible et action manuelle factice — confirmé
|
||||
|
||||
Sources : `Web/Controllers/UpdatesController.cs`, `Agent/Services/AgentUpdateService.cs`.
|
||||
|
||||
L’agent appelle latest avec X-API-Key alors que la route accepte seulement JwtBearer/Cookies. TriggerAgentUpdate retourne les informations de release sans envoyer de commande à l’agent. La promesse d’une mise à jour déclenchée ne correspond pas à l’action effectuée.
|
||||
|
||||
Correction : endpoint de manifeste autorisé pour agents, commande ciblée et état d’avancement ; validation obligatoire de l’artefact, arrêt contrôlé de capture, remplacement atomique et rollback. Validation supplémentaire nécessaire selon exécution native/conteneur et fichier effectivement remplaçable.
|
||||
|
||||
### OPS-06 — P1 — Le démarrage Docker documenté utilise des noms JWT incohérents — confirmé
|
||||
|
||||
Sources : `.env.example`, `docker/docker-compose.yml`.
|
||||
|
||||
L’exemple fournit JWT__KEY/JWT__REFRESHKEY tandis que le compose interpole JWT__Key/JWT__RefreshKey. Les variables d’environnement/interpolations sont sensibles à la casse sous Linux. Une copie de l’exemple ne renseigne donc pas les variables attendues par le compose. La commande de validation compose le confirme avec des avertissements de variables JWT vides ; elle signale aussi HEIMDALL_SITE_TOKEN absent, alors que l’exemple fournit Agent__SiteToken.
|
||||
|
||||
Correction : noms identiques partout et variables obligatoires `${...:?message}` ; vérifier `docker compose --env-file .env.example ... config` sans afficher les valeurs secrètes dans les logs CI. Des mots de passe par défaut et des ports d’infrastructure publiés restent présents : distinguer explicitement la configuration de développement de celle à exposer.
|
||||
|
||||
### UI-01 — P2 — Galerie limitée et fallback d’image mal formé — confirmé
|
||||
|
||||
Source : `Web/Components/Pages/SnapshotsPage.razor`.
|
||||
|
||||
La page charge seulement les 100 premiers événements puis filtre côté client les snapshots et la recherche ; elle peut annoncer qu’aucun snapshot n’existe alors qu’il est plus ancien. Le texte de recherche annonce la caméra mais le filtre ne regarde que type/label. L’attribut `src="@ev.SnapshotThumbUrl ?? ev.SnapshotUrl"` n’encapsule pas l’expression C# complète ; utiliser `@(ev.SnapshotThumbUrl ?? ev.SnapshotUrl)` et vérifier le DOM.
|
||||
|
||||
Correction : recherche/pagination serveur sur les événements avec snapshot, filtrage caméra, états de pagination et tests de rendu du src avec et sans miniature.
|
||||
|
||||
### UI-02 — P2 — Historique d’une personne filtré par nom, pas par identité — confirmé
|
||||
|
||||
Source : `Web/Components/Pages/PersonDetailPage.razor`, LoadEvents/LoadVehicles.
|
||||
|
||||
L’UI récupère les 50 premiers événements FaceRecognized puis filtre un Contains(DisplayName). Les homonymes, renommages et pages suivantes donnent des faux positifs/négatifs. Les véhicules sont aussi filtrés après récupération d’une liste paginée. Prévoir des filtres API PersonId et une pagination associée ; générer les liens métier depuis les analyses.
|
||||
|
||||
### UI-03 — P2 — Résumés email : période et périmètre incohérents — confirmé
|
||||
|
||||
Sources : `Infrastructure/Jobs/DailyDigestJob.cs`, `WeeklyDigestJob.cs`.
|
||||
|
||||
Le résumé quotidien compte depuis hier à minuit sans borne haute, tout en parlant d’« aujourd’hui ». Les caméras sont résolues uniquement via UserSites, sans la politique complète d’accès caméra/groupe. Définir les intervalles fermés/ouverts, le fuseau utilisateur/site et la même autorisation que l’API ; tester accès caméra seul, groupe et changement d’heure.
|
||||
|
||||
### UI-04 — P1 — Gestion utilisateurs en échec dans les tests navigateur — observé, cause à isoler
|
||||
|
||||
Sources : `tests/Heimdall.E2E.Tests/Pages/UserManagementTests.cs`, `Web/Components/Pages/UsersPage.razor`, `Web/Services/HeimdallApiClient.cs`.
|
||||
|
||||
La session d’audit observe des échecs de liste administrateur, création, modification et reset : l’email attendu n’apparaît pas dans l’UI, avec assertions ou timeouts. La création préalable par API réussit dans certains de ces scénarios : ne pas conclure à un défaut de persistance sans preuve. Instrumenter les réponses HTTP internes, l’état d’authentification du circuit et le DOM au moment de l’échec ; vérifier ensuite les sélecteurs et la pagination. Le scope des handlers HTTP et la restauration de session sont des pistes, pas une cause racine démontrée.
|
||||
|
||||
## Accès mobile : remplacement par la PWA
|
||||
|
||||
Le client natif initialement inspecté avait des incohérences de routes/DTOs, une URL serveur non raccordée, une session non persistée, une 2FA incompatible et un live non implémenté. Il a été entièrement retiré à la demande du propriétaire ; ses corrections ne font plus partie du plan actif.
|
||||
|
||||
L’audit détaillé de la nouvelle cible, avec écarts locaux, architecture, critères d’acceptation et chiffrage, se trouve dans [Audit PWA](../pwa.md). Priorité : rendre l’application serveur installable et fiable en ligne, avec écran hors connexion, puis ajouter Web Push. La consultation métier hors ligne est une option qui nécessite du code exécuté côté navigateur.
|
||||
|
||||
## Qualité, tests et documentation
|
||||
|
||||
### BUILD-01 — P1 — Builds et chaîne CI/CD à refaire entièrement pour Gitea
|
||||
|
||||
**Exigence de cadrage ajoutée à la demande du propriétaire : la chaîne de build doit être reconstruite complètement avec Gitea comme cible.** Les workflows existants ne constituent pas le socle de livraison à conserver par simples retouches. Leur présence et leur validation syntaxique ne valent pas validation sur Gitea.
|
||||
|
||||
Périmètre : workflows Gitea Actions et runners, restauration des dépendances, compilation .NET, tests unitaires/intégration/navigateur, publication serveur/PWA et agent, construction des images, versionnement, artefacts, registre et releases. Retirer les dépendances implicites aux anciens environnements et les références opérationnelles Forgejo/GitHub non adaptées à la cible ; vérifier explicitement les actions réutilisées au lieu de supposer leur compatibilité. Aucun build natif mobile ne doit être réintroduit.
|
||||
|
||||
La refonte doit définir les déclencheurs PR/push/tag, les checks bloquants, les caches, les prérequis PostgreSQL/Chromium, les permissions et secrets, ainsi que la traçabilité commit → tests → artefacts/images → release. Les échecs de tests ou de publication ne doivent pas devenir des succès masqués.
|
||||
|
||||
Acceptation : depuis un checkout propre, un runner Gitea exécute la chaîne complète ; une PR défaillante est bloquée ; un tag produit des artefacts et images versionnés, vérifiables et publiés sur les destinations configurées. Les logs ne divulguent aucun secret. La version Gitea, les runners et les destinations de publication restent à préciser pendant la conception.
|
||||
|
||||
### QA-01 — P2 — Tests majoritairement locaux aux composants
|
||||
|
||||
Les suites existantes constituent un bon socle, mais les ruptures détectées exigent des tests traversant plusieurs composants : Identity réel pour 2FA, deux sites pour autorisation, deux agents pour RabbitMQ, capture → objet stocké → événement → galerie, préférence → notification → canal, et les scénarios PWA de session, cache et Web Push. Les placeholders de tests encore présents ne prouvent aucune couverture fonctionnelle.
|
||||
|
||||
Les tests E2E nécessitent navigateur et PostgreSQL ; leur résultat doit être distingué de celui des tests unitaires. Les tests matériels ne sont pas remplacés par la réussite des suites avec mocks. Les résultats exacts de cette session sont consignés dans `2026-10-20-validation.md`.
|
||||
|
||||
### DOC-01 — P3 — Plan historique et architecture documentaire obsolètes
|
||||
|
||||
Sources : `docs/implementation.md`, `docs/README.md`, `readme.md`.
|
||||
|
||||
Le plan présente plusieurs fonctions déjà codées comme « en attente », annonce encore des projets Api/Workers séparés et des nombres de tests obsolètes. Le README documente Bearer pour les clés agents, alors que le handler REST exige X-API-Key hors des hubs. Les routes snapshot/événements et l’état du live sont également à aligner.
|
||||
|
||||
Correction : matrice de livraison fondée sur parcours validés, documentation des routes générée, séparation de l’architecture actuelle et de la cible. Ne pas réutiliser les cases cochées historiques comme preuve d’achèvement.
|
||||
|
||||
## Vérifications complémentaires nécessaires
|
||||
|
||||
1. Caméras RTSP/ONVIF de plusieurs fabricants, authentification, perte réseau, codecs et redémarrage FFmpeg.
|
||||
2. Charge de nombreuses caméras, backpressure, files, mémoire, latence, CPU/GPU et contention PostgreSQL.
|
||||
3. Migrations depuis une base existante, partitionnement effectif, rétention et restauration isolée des sauvegardes.
|
||||
4. S3 réel, credentials, bucket, liens signés, permissions, changement de provider et reprise d’upload.
|
||||
5. Livraison email/ntfy, indisponibilité de canal, fan-out et absence de fuite entre utilisateurs.
|
||||
6. Distribution native/conteneur, intégrité/rollback des updates et arrêt propre.
|
||||
7. Contrôles anti-CSRF des mutations acceptant les cookies, restrictions CORS/TLS et révocation des sessions en environnement déployé.
|
||||
8. Inventaire de dépendances et vulnérabilités à jour ; les suppressions NU1902/NU1903 dans Directory.Build.props empêchent de considérer une restauration silencieuse comme un audit de sécurité réussi.
|
||||
|
||||
Le plan de réalisation se trouve dans `2026-10-20-plan-implementation.md`.
|
||||
|
||||
## Repères précis pour la revue
|
||||
|
||||
Ces liens correspondent aux fichiers inspectés ; les numéros désignent le début de la logique concernée à la révision auditée.
|
||||
|
||||
| Constats | Fichier et ligne |
|
||||
|---|---|
|
||||
| SEC-01 | [src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs:39](../../src/Heimdall.Application/Auth/Commands/Verify2fa/Verify2faHandler.cs#L39) |
|
||||
| SEC-02 | [src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs:58](../../src/Heimdall.Application/Auth/Commands/Login/LoginHandler.cs#L58) |
|
||||
| SEC-03 | [src/Heimdall.Web/Controllers/AgentsController.cs:59](../../src/Heimdall.Web/Controllers/AgentsController.cs#L59) |
|
||||
| SEC-04 | [src/Heimdall.Web/Hubs/MonitoringHub.cs:39](../../src/Heimdall.Web/Hubs/MonitoringHub.cs#L39) |
|
||||
| SEC-04 | [src/Heimdall.Web/Hubs/ConfigHub.cs:26](../../src/Heimdall.Web/Hubs/ConfigHub.cs#L26) |
|
||||
| SEC-05 | [src/Heimdall.Web/Controllers/SettingsController.cs:97](../../src/Heimdall.Web/Controllers/SettingsController.cs#L97) |
|
||||
| SEC-06 | [src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs:28](../../src/Heimdall.Application/Cameras/Commands/UpdateCamera/UpdateCameraCommand.cs#L28) |
|
||||
| SEC-07 | [src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs:61](../../src/Heimdall.Application/Auth/Commands/RefreshToken/RefreshTokenHandler.cs#L61) |
|
||||
| SEC-08 | [src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs:28](../../src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs#L28) |
|
||||
| PIPE-01 | [src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs:86](../../src/Heimdall.Infrastructure/Services/AnalysisJobSchedulerService.cs#L86) |
|
||||
| PIPE-02 | [src/Heimdall.Agent/AnalysisJobConsumer.cs:53](../../src/Heimdall.Agent/AnalysisJobConsumer.cs#L53) |
|
||||
| PIPE-03 | [src/Heimdall.Agent/Services/FrameAnalyzerService.cs:148](../../src/Heimdall.Agent/Services/FrameAnalyzerService.cs#L148) |
|
||||
| PIPE-04 | [src/Heimdall.Agent/Services/FrameAnalyzerService.cs:309](../../src/Heimdall.Agent/Services/FrameAnalyzerService.cs#L309) |
|
||||
| PIPE-05 | [src/Heimdall.Agent/Services/FrameMotionDetector.cs:24](../../src/Heimdall.Agent/Services/FrameMotionDetector.cs#L24) |
|
||||
| PIPE-07 | [src/Heimdall.Agent/Services/ConfigReceiverService.cs:103](../../src/Heimdall.Agent/Services/ConfigReceiverService.cs#L103) |
|
||||
| PIPE-08 | [src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs:150](../../src/Heimdall.Infrastructure/Services/CameraAssignmentService.cs#L150) |
|
||||
| PIPE-09 | [src/Heimdall.Web/Components/Pages/CamerasPage.razor:533](../../src/Heimdall.Web/Components/Pages/CamerasPage.razor#L533) |
|
||||
| FEAT-04 | [src/Heimdall.Infrastructure/Services/CameraAccessService.cs:28](../../src/Heimdall.Infrastructure/Services/CameraAccessService.cs#L28) |
|
||||
| FEAT-05 | [src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs:12](../../src/Heimdall.Application/Events/Notifications/EventCreatedNotificationHandler.cs#L12) |
|
||||
| OPS-03 | [src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs:95](../../src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs#L95) |
|
||||
| OPS-04 | [src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs:64](../../src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs#L64) |
|
||||
| OPS-05 | [src/Heimdall.Web/Controllers/UpdatesController.cs:59](../../src/Heimdall.Web/Controllers/UpdatesController.cs#L59) |
|
||||
| UI-01 | [src/Heimdall.Web/Components/Pages/SnapshotsPage.razor:44](../../src/Heimdall.Web/Components/Pages/SnapshotsPage.razor#L44) |
|
||||
@@ -1,21 +0,0 @@
|
||||
# Lot 2 — Hubs autorisés et absence de secrets dans les diffusions
|
||||
|
||||
Suite de la PR politique API et groupes. Périmètre SEC-04/SEC-05 et raccordement SEC-03/FEAT-04, sans changement fonctionnel au pipeline ni au lot connexion/session.
|
||||
|
||||
## Diffusions
|
||||
|
||||
EventsHub autorise le site demandé puis inscrit uniquement les caméras effectivement accessibles. Le broadcaster adresse les abonnés de la caméra de l’événement, jamais tous les abonnés du site. Les GUID sont normalisés. MonitoringHub exige un droit sur le site entier ; un accès caméra partiel ne donne pas l’inventaire et les statuts des autres ressources du site. JoinAdminBroadcast exige le rôle Admin en base. ConfigHub exige la relation persistée clé → agent/site et interdit un autre agent, même dans le même site.
|
||||
|
||||
Un registre de connexions est utilisé par les trois broadcasters. Chaque envoi résout à nouveau l’identité et le droit depuis la base : retrait de groupe/site, suppression d’agent et révocation/expiration de clé sont pris en compte sans attendre une reconnexion. Les groupes SignalR ne sont pas considérés comme une preuve durable d’autorisation. Le registre est nettoyé à la déconnexion ; un redémarrage implique la reconnexion et le réabonnement habituels.
|
||||
|
||||
## Configuration et journaux
|
||||
|
||||
Seules les clés AppSetting existantes et AgentScoped sont diffusées ; les overrides de clés serveur sont refusés à l’écriture et exclus du rechargement complet, y compris les anciens overrides persistés. La commande interne de découverte conserve son contrat producteur `discovery.scan.requested = 1`, mais est transportée par un événement séparé `DiscoveryScanRequested` sans clé ni valeur ; `SettingChanged` n’accepte que des clés AgentScoped. Les credentials caméra chiffrés et la configuration des seules caméras affectées continuent à être produits côté serveur par le chargement complet existant.
|
||||
|
||||
Les contrôleurs transmettent désormais explicitement le champ AgentScoped des demandes de création/modification. Les logs de configuration ne contiennent plus de valeurs, même pour une clé inconnue ou une valeur invalide. Les journaux d’audit caméra ne sérialisent plus les URL RTSP ; les logs de capture, découverte et test de flux n’impriment plus les URL susceptibles d’inclure userinfo ou tokens. Les erreurs réseau/configuration sont consignées par type, sans message d’exception externe. Le filtre d’exception HTTP conserve le type et l’identifiant de trace, sans message susceptible de contenir une valeur sensible.
|
||||
|
||||
## Preuves et limites
|
||||
|
||||
Tests : abonnements caméra directs/groupes/sites, refus site B, monitoring partiel refusé, broadcast Admin, refus d’usurpation ConfigHub, révocation après abonnement, exclusion SMTP/S3 du push et du rechargement et rejet d’override serveur. Validation locale exécutée le 20 octobre 2026 avec .NET SDK 10.0.112 (`dotnet test <projet> --no-restore --verbosity minimal`) : Web 385/385, Agent 356/356, Application 504/504 et Infrastructure 223/223 ; aucun test ignoré. `git diff --check` passe. Un test de régression vérifie également le nettoyage des anciennes inscriptions lors d’un réabonnement après retrait des droits. Ces résultats ne couvrent pas les suites navigateur ou une infrastructure externe réelle.
|
||||
|
||||
Le registre est local à l’instance, conformément au déploiement SignalR actuel sans backplane. Un déploiement distribué devra transporter les abonnements ou diffuser sur chaque instance avec la même réautorisation ; aucune promesse de fan-out multi-instance n’est faite. La réautorisation ajoute des lectures par destinataire et doit être mesurée avant une montée en charge. Les changements de droits entre la vérification et l’envoi restent soumis à la course normale d’une requête en cours. Les anciens journaux déjà persistés ne sont pas purgés par ces changements. La sécurité des objets snapshot eux-mêmes relève du lot 4. La validation par caméra réelle et les essais SMTP/S3 réels ne sont pas remplacés par les tests locaux.
|
||||
@@ -1,24 +0,0 @@
|
||||
# Lot 2 — Politique API et droits groupes
|
||||
|
||||
Périmètre : SEC-03, SEC-06 et FEAT-04 du rapport du 20 octobre 2026. Les hubs et SEC-05 font l’objet de la PR suivante. Aucun fichier AGENTS.md trouvé dans les ancêtres ni dans ce worktree. Aucun changement au lot connexion/session, au pipeline ou à la CI ; aucun merge ni déploiement.
|
||||
|
||||
## Contrat d’accès
|
||||
|
||||
- Le demandeur est explicitement humain ou agent. Les sujets absents, vides, contradictoires, utilisateurs inconnus et clés sans relation unique avec un agent actif sont refusés.
|
||||
- Une clé doit être active, non expirée et liée par son hash complet à exactement un agent du même site. Un simple identifiant de clé/site ne permet plus d’agir au nom d’un autre agent. Les clés génériques créées manuellement sans agent enregistré restent inutilisables comme identité agent ; la procédure d’enregistrement existante crée les deux enregistrements compatibles, sans migration.
|
||||
- Admin conserve toutes les ressources existantes ; Supervisor et Viewer conservent leurs permissions d’action existantes. L’autorisation d’une action et son périmètre sont deux conditions cumulatives.
|
||||
- Les droits caméra sont l’union de UserCameraAccess (caméra ou site entier), UserCamera, UserSite et UserGroup → GroupCameraAccess. Un grant spécifique dont SiteId ne correspond pas au site de la caméra ne donne aucun droit. Un groupe supprimé ne donne aucun droit. Aucune règle de refus prioritaire n’est introduite.
|
||||
- La même expression IQueryable sert au contrôle de détail, aux listes et aux filtres avant pagination. Les événements héritent du droit de leur caméra. Les listes de sites peuvent identifier un site contenant une caméra autorisée ; cela ne donne pas de droit sur ses autres caméras, ses agents, son inventaire ou ses credentials.
|
||||
- Les informations et opérations portant sur le site entier ou ses agents exigent un droit explicite sur tout le site (UserSite ou UserCameraAccess sans CameraId), ou Admin. Les agrégats globaux Stats sont réservés à Admin. Les listes globales d’agents sont filtrées avant pagination selon ces mêmes droits complets.
|
||||
- Un agent peut écrire uniquement pour lui-même et pour les caméras qui lui sont actuellement affectées dans son site, y compris l’ingestion d’événements, le statut et l’attachement d’un snapshot. Les autorisations d’un agent sont relues depuis la base pour chaque requête.
|
||||
- Un filtre MVC commun vérifie les ressources avant l’appel métier : Cameras, Sites, Agents, Events, Assignments, Settings, Discovery et mise à jour ciblée d’agent. Les sessions opaques de test de flux sans propriétaire persistant sont réservées à Admin. Les routes anonymes d’enregistrement restent contrôlées par leur token d’enregistrement.
|
||||
|
||||
## Personnes et véhicules
|
||||
|
||||
Les registres Person/KnownFace et Vehicle/LicensePlate sont **globaux à l’installation**, car ils ne portent pas de SiteId. Leurs routes continuent à exiger Person.Read/Write et Vehicle.Read/Write : Viewer lit, Supervisor et Admin lisent/écrivent. Une permission sur ce registre global n’ouvre aucun événement ou caméra supplémentaire ; l’historique événementiel reste filtré par caméra. Une isolation locale de ces registres demanderait un contrat métier et une migration distincts ; aucun rattachement implicite par nom ou par dernier événement n’est utilisé.
|
||||
|
||||
## Preuves et limites
|
||||
|
||||
Les tests de ce thème couvrent la matrice Admin/Supervisor/Viewer × sites A/B × direct/groupe/site/aucun, l’union des grants, le retrait d’un membre, les détails et mutations caméra, les routes agent et l’ingestion hors affectation. Les tests de rôle portent sur le périmètre ; les permissions d’action restent celles déclarées sur les contrôleurs. Un test du véritable AuthenticationHandler vérifie hash, sujet agent/site, clé non liée, expirée et agent supprimé.
|
||||
|
||||
Validation locale exécutée le 20 octobre 2026 avec .NET SDK 10.0.112 (`dotnet test <projet> --no-restore --verbosity minimal`) : Application 504/504, Infrastructure 223/223, Web 385/385 et Agent 356/356 ; aucun test ignoré. `git diff --check` passe. Les tests SQLite prouvent aussi la traduction relationnelle des expressions ; ils ne constituent pas une campagne PostgreSQL, navigateur ou matériel. Le filtre est la frontière HTTP ; les handlers internes restent utilisables par les jobs serveur de confiance. Toute nouvelle route portant une ressource doit être ajoutée explicitement à cette frontière et à sa matrice de tests.
|
||||
@@ -1,167 +0,0 @@
|
||||
{
|
||||
"suite": "ops targeted",
|
||||
"sdk": "10.0.112",
|
||||
"postgres": "17-alpine via Testcontainers",
|
||||
"passed": 39,
|
||||
"failed": 0,
|
||||
"skipped": 0,
|
||||
"trx_sha256": "53a74f1711738bb65383f71ebe3df69ceba4d523b6cad321ec4ae11d70681171",
|
||||
"tests": [
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteAsync_NoAgents_JobsStayPending",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteAsync_PendingJobs_DispatchesToAgents",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteAsync_SecurityJobDispatchedBeforeBackground",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteTimeoutSweepAsync_HealthyJobs_Ignored",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteTimeoutSweepAsync_TimedOutJob_RetriesOrDeadLetters",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.DeleteBatch_RemovesAll",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.Delete_RemovesObject",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.DirectoryLinks_IncludingDangling_AreRejected(dangling: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.DirectoryLinks_IncludingDangling_AreRejected(dangling: True)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.Download_Missing_ReturnsNull",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.HealthCheck_True",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \".\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"../sibling/file\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"/absolute/file\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"C:/absolute/file\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a/..\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a/./b\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a//b\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a\\\\b\")",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.LeafAndRootLinks_AreRejected",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.PathTraversal_Throws",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.SiblingWithRootPrefix_IsRejected",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.UploadDownload_RoundTrips",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.MaintenanceScheduleTests.Dispatch_DoesNotRunASecondTimeoutSweep",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.MaintenanceScheduleTests.TimeoutSweep_HasMinuteOccurrencesAndDistributedLock",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionManagerJobTests.Execute_DropsOnlyExpiredAttachedPartitions_AndClosesReaderBeforeDdl",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"Camera_events_2025_01\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_+025_01\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_0000_01\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_0001_12\", valid: True)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025-01\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_00\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_01\", valid: True)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_01_extra\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_1\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_13\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_01\", valid: False)",
|
||||
"outcome": "Passed"
|
||||
},
|
||||
{
|
||||
"name": "Heimdall.Infrastructure.Tests.SweepLockTests.PostgreSqlLock_ExcludesAnotherWorker_AndIsReleased",
|
||||
"outcome": "Passed"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
# Lot 3 — preuves et limites de livraison
|
||||
|
||||
Périmètre : PIPE-03 à PIPE-08, plus PIPE-11 isolé. Référence : [audit complet](2026-10-20-audit-complet.md). Aucun changement de sécurité des hubs/claims, d’authentification, de CI ou de déploiement.
|
||||
|
||||
## Découpage de revue
|
||||
|
||||
1. Exécution : refus explicite à saturation (compteur), continuations asynchrones, drainage avant libération ONNX, timeout natif de 15 s par inférence, validation du contrat COCO YOLOv8, RGB explicite et coordonnées originales, erreurs de jobs et capacités CPU effectives.
|
||||
2. Configuration : profil version 1, migration additive nullable, mise à jour via PUT caméra, motion gate pixel avec seuil de pixels changés, amplitude minimale et zone normalisée, intervalles, classes et confiance appliqués ; remplacement complet de la configuration après connexion/reconnexion et toutes les 30 s, invalidation après sauvegarde.
|
||||
3. Affectations : historique et AgentId cohérents, attente sans remplaçant, réconciliation périodique après reprise, cohérence du statut offline avant failover.
|
||||
|
||||
## Contrat et compatibilité
|
||||
|
||||
Le champ optionnel `DetectionProfile` du PUT caméra contient le DTO `DetectionProfileDto`. `Version=1`, modèle `yolov8n`, classes personne/véhicule/animal, seuil de confiance, motion gate et intervalles de capture sont pris en charge. Les seuils/coordonnées de zone sont dans [0,1]. `MotionThreshold` est la proportion minimale de pixels ayant changé ; `MotionPixelThreshold` est leur amplitude RGB moyenne minimale. Première image ou changement de profil : nouvelle référence de mouvement. `RequireMotionForAI=false` autorise l’analyse sans mouvement. Un profil invalide ou de version inconnue est refusé et le snapshot précédent est conservé.
|
||||
|
||||
Les profils historiques sans JSON utilisent leurs valeurs existantes. La migration ajoute seulement `ExecutionProfileJson` nullable ; rollback : supprimer cette colonne (les valeurs historiques restent, les nouveaux profils JSON sont perdus). Les options package, modèles alternatifs et analyses visage/OCR ne sont pas annoncées comme capacités exécutables. Le binaire actuel utilise ONNX CPU ; l’inventaire GPU reste matériel et `HasGpu=false` décrit la capacité d’inférence effective. Sans modèle, les cœurs d’inférence annoncés valent zéro et la santé devient unhealthy ; aucun job n’est publié completed à partir d’un résultat indisponible.
|
||||
|
||||
## Dépendance lot 2
|
||||
|
||||
Les invalidations réutilisent `IConfigBroadcastService.NotifyAllAgentsReload`, sans URLs ni secrets dans le message. Chaque agent recharge son snapshot par l’API existante. Le lot 2 doit garantir l’identité agent, l’autorisation des abonnements et de cette API, ainsi que le filtrage AgentScoped. Aucun remplacement de sa politique ni de ses claims dans ces PR. Le raccordement du PUT caméra ajoute seulement le DTO, sans modifier la politique d’accès.
|
||||
|
||||
La notification est best effort après la transaction implicite de SaveChangesAsync ; la reconnexion et le polling récupèrent les notifications perdues. Les appels actuels n’utilisent pas de transaction explicite englobante ; un futur appel sous transaction explicite devra différer la notification jusqu’à son commit externe. Une outbox durable relève du lot 5.
|
||||
|
||||
## Validation
|
||||
|
||||
Premier passage final infrastructure : **56 réussis, 0 échec, 0 ignoré**, PostgreSQL 17 Testcontainers, filtre `CameraAssignmentServiceTests|AnalysisJobSchedulerServiceTests` (58 s de tests, compilation comprise séparément). La matrice GPU couvre chaque type de job, même/autre site et vide/en charge. Le passage précédent avait échoué sur une fixture de reprise désactivée par défaut ; fixture corrigée en caméra Online puis suite relancée.
|
||||
|
||||
Commande : `dotnet test tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj --no-restore --filter 'FullyQualifiedName~CameraAssignmentServiceTests|FullyQualifiedName~AnalysisJobSchedulerServiceTests' --nologo -v minimal -m:1 -p:UseSharedCompilation=false`.
|
||||
|
||||
Validation de reprise du 20 octobre 2026 :
|
||||
|
||||
- Suite agent complète : **363 réussis, 0 échec, 0 ignoré** (38 s). Le test SignalR démarre un serveur HTTP local, coupe le transport HTTP et vérifie la réinscription au groupe ainsi que le remplacement complet du snapshot après reconnexion, y compris la suppression de l’ancienne caméra et la désactivation de la nouvelle. Un premier essai utilisant HubCallerContext.Abort ne simulait pas correctement la perte de transport ; la fixture utilise désormais HttpContext.Abort.
|
||||
- Infrastructure ciblée : **57 réussis, 0 échec, 0 ignoré** (9 s), avec le même filtre ci-dessus. Inclut l’aller-retour PUT/profil persisté/configuration effective et le refus d’une version inconnue sans modification du nom de caméra. Le namespace du substitut ICredentialProtector a été corrigé avant ce passage.
|
||||
- ReportCameraStatusCommandTests : **6 réussis, 0 échec, 0 ignoré** (542 ms), dont le refus de réactivation d’une caméra désactivée par un rapport en vol.
|
||||
|
||||
Commande agent : `dotnet test tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj --no-restore --nologo -v minimal -m:1 -p:UseSharedCompilation=false`.
|
||||
|
||||
Commande application : `dotnet test tests/Heimdall.Application.Tests/Heimdall.Application.Tests.csproj --no-restore --filter FullyQualifiedName~ReportCameraStatusCommandTests --nologo -v minimal -m:1 -p:UseSharedCompilation=false`.
|
||||
|
||||
Les tests GPU de scoring utilisent des capacités persistées simulées ; ils ne prouvent pas une exécution CUDA. Une campagne matérielle RTSP/GPU et une réception SignalR sur réseau dégradé restent distinctes des tests automatiques locaux. Aucun lien de PR n’est consigné à ce stade.
|
||||
@@ -1,201 +0,0 @@
|
||||
# Plan d’implémentation après audit
|
||||
|
||||
Référence : [rapport du 20 octobre 2026](2026-10-20-audit-complet.md). Ce plan décrit les travaux à réaliser ; aucun de ces correctifs n’a été appliqué pendant l’audit.
|
||||
|
||||
## Objectif et ordre de livraison
|
||||
|
||||
Livrer d’abord un parcours fiable : agent autorisé → caméra affectée → capture → détection → événement et image persistés → consultation autorisée → alerte utilisateur. Étendre ensuite à la vidéo live, aux enregistrements et à l’analyse spécialisée. La PWA du serveur devient l’unique cible mobile ; voir [l’audit PWA](../pwa.md).
|
||||
|
||||
Les estimations ci-dessous sont des ordres de grandeur en jours de développement effectif, incluant les tests ciblés. Elles supposent la disponibilité des environnements PostgreSQL/RabbitMQ/S3 et d’au moins une caméra ; elles ne constituent pas un engagement de calendrier. Les analyses biométriques/OCR et WebRTC sont particulièrement dépendantes du matériel et des critères produit.
|
||||
|
||||
## Lot 0 — Reconstruire entièrement les builds pour Gitea
|
||||
|
||||
Priorité P1, chantier transversal à démarrer en premier. Référence BUILD-01. Estimation à établir après inventaire des livrables et choix des runners ; **non incluse dans le total actuel**.
|
||||
|
||||
1. Définir la cible Gitea : version, runners et architectures, registre d’images, stockage des artefacts et mécanisme de release.
|
||||
2. Reconcevoir les workflows PR/push/tag et leurs dépendances ; sélectionner des actions compatibles et épinglées, avec permissions minimales et secrets dédiés.
|
||||
3. Refaire restauration, compilation et tests .NET depuis un checkout propre ; provisionner PostgreSQL et Chromium pour les suites concernées, conserver rapports et résultats bloquants.
|
||||
4. Refaire la publication serveur/PWA et agent, les builds d’images, le versionnement et la publication des artefacts/releases ; ne pas réintroduire de build natif mobile.
|
||||
5. Établir caches, rétention, traçabilité des sorties, contrôles de sécurité et procédure de reprise ; supprimer les workflows remplacés et les dépendances aux anciens environnements.
|
||||
6. Valider la chaîne directement sur Gitea, y compris un échec de PR et une release de test sur tag.
|
||||
|
||||
Acceptation : PR bloquée si les contrôles obligatoires échouent ; build propre reproductible ; artefacts/images rattachés au commit et à la version ; publication vérifiée ; secrets absents des logs. Une validation YAML locale ne suffit pas. Le déploiement éventuel doit être défini séparément de la production des artefacts.
|
||||
|
||||
## Lot 1 — Sécuriser la connexion et la session
|
||||
|
||||
Priorité P0/P1. Défauts SEC-01, SEC-02, SEC-07, SEC-10. Estimation : 4–7 jours.
|
||||
|
||||
Travaux :
|
||||
|
||||
1. Introduire un contrat de challenge 2FA lié à une tentative de connexion validée par mot de passe : identifiant opaque, expiration courte, compteur, consommation unique.
|
||||
2. Traiter RequiresTwoFactor correctement, sans émission prématurée de session authentifiée. Réutiliser les composants Identity pour la vérification et le verrouillage.
|
||||
3. Vérifier compte verrouillé, activation 2FA et confirmation email avant émission des tokens.
|
||||
4. Rendre la consommation des codes de récupération atomique, y compris entre instances.
|
||||
5. Corriger le renouvellement automatique web après 401 (token expiré non vide, portée par session, base URL du serveur) ; vérifier statut utilisateur au renouvellement ; invalider les sessions après verrouillage/changement de droits ; définir durée maximale et revalidation des cookies.
|
||||
6. Adapter le parcours Blazor et la documentation du contrat ; préparer la reprise de session de la PWA.
|
||||
|
||||
Acceptation : login réel avec/sans 2FA, challenge absent/expiré/rejoué refusé, code de récupération consommé une seule fois, refresh d’un compte verrouillé refusé, session révoquée conformément à la politique décidée. Tester avec Identity réel, pas seulement un mock du service de connexion.
|
||||
|
||||
## Lot 2 — Appliquer l’isolation aux API et aux hubs
|
||||
|
||||
Priorité P0. Défauts SEC-03 à SEC-06, FEAT-04. Estimation : 5–9 jours. Peut commencer indépendamment du lot 1.
|
||||
|
||||
Travaux :
|
||||
|
||||
1. Créer une représentation explicite du demandeur humain/agent et résoudre la relation clé → agent/site côté serveur.
|
||||
2. Fournir une politique unique d’accès aux ressources : site, caméra, agent, événement ; refuser les identités absentes ou incohérentes.
|
||||
3. Appliquer cette politique aux routes de détail et d’écriture, pas seulement aux listes.
|
||||
4. Intégrer les droits des groupes à toutes les requêtes et méthodes d’autorisation ; préciser les règles d’union avec UserSites et accès directs.
|
||||
5. Sécuriser JoinSiteEvents, JoinSiteMonitoring, JoinAdminBroadcast et JoinAgentGroup. Pour un utilisateur limité à certaines caméras, éviter de lui envoyer tous les événements du site via un groupe trop large.
|
||||
6. Ne diffuser que les clés AgentScoped autorisées, supprimer les valeurs sensibles des logs, y compris sur l’agent.
|
||||
7. Documenter la portée globale ou locale des personnes/véhicules et l’appliquer de façon cohérente.
|
||||
|
||||
Acceptation : matrice Admin/Supervisor/Viewer/clé agent × sites A/B × accès direct/groupe/aucun. Les abonnements, lectures et mutations hors périmètre échouent. Une modification SMTP/S3 n’arrive jamais dans le flux ni les logs d’un agent.
|
||||
|
||||
## Lot 3 — Fiabiliser l’exécution agent et les configurations
|
||||
|
||||
Priorité P1. Défauts PIPE-03 à PIPE-08. Estimation : 6–10 jours. Dépend du contrôle d’identité du lot 2 pour les pushes ciblés.
|
||||
|
||||
Travaux :
|
||||
|
||||
1. Corriger le channel borné : refus explicite ou complétion du travail supprimé ; compteurs de saturation ; arrêt ordonné avant Dispose ONNX.
|
||||
2. Corriger la transformation des coordonnées et normaliser les canaux image ; vérifier le contrat du modèle chargé.
|
||||
3. Ajouter un DTO versionné de profil de détection dans la configuration caméra ; propager les modifications et appliquer seuils/options dans le pipeline.
|
||||
4. Publier les invalidations de configuration après commit : caméra créée/modifiée/désactivée, affectation changée, failover. Recharger l’état complet après reconnexion.
|
||||
5. Rendre cohérentes les affectations et Camera.AgentId ; maintenir les caméras sans remplaçant en attente et les reprendre automatiquement.
|
||||
6. Remplacer la variation de taille JPEG par un motion gate pixel avec seuil et zone paramétrables.
|
||||
7. Exposer les capacités d’exécution effectives CPU/GPU et la disponibilité du modèle ; empêcher qu’une indisponibilité soit présentée comme un résultat négatif.
|
||||
|
||||
Acceptation : saturation contrôlée sans attente infinie, arrêt sans tâches orphelines, bounding boxes correctes sur image 1920×1080, profil appliqué, désactivation prise en compte sans redémarrage, panne/reprise d’un agent avec et sans remplaçant, resynchronisation après perte de SignalR.
|
||||
|
||||
## Lot 4 — Livrer les snapshots de bout en bout
|
||||
|
||||
Priorité P1. Défauts PIPE-09, SEC-08, UI-01. Estimation : 5–8 jours. Dépend des lots 2 et 3.
|
||||
|
||||
Travaux :
|
||||
|
||||
1. Corriger ResolvePath et les tests de confinement avant d’exposer les opérations de stockage.
|
||||
2. Définir la référence d’objet : identifiant, provider, bucket/racine, clé, taille, type MIME, empreinte, état d’upload.
|
||||
3. Implémenter l’upload authentifié et borné avec validation du contenu, miniature et association à l’événement ; gérer les uploads incomplets.
|
||||
4. Proposer une lecture autorisée ou URL signée de durée limitée ; ne pas contourner le filtrage caméra avec une URL permanente publique.
|
||||
5. Raccorder la commande de capture manuelle à l’agent avec corrélation et résultat observable dans l’UI.
|
||||
6. Ajouter filtres « avec snapshot », recherche caméra/type et pagination serveur pour galerie et dernières images.
|
||||
7. Corriger le fallback Razor et afficher date/âge de capture.
|
||||
|
||||
Acceptation : une détection produit une image visible après rechargement de l’UI ; un clic de capture produit un nouveau timestamp ; un utilisateur non autorisé ne lit pas l’objet ; interruption/reprise d’upload ne crée ni faux succès ni référence cassée.
|
||||
|
||||
## Lot 5 — Garantir la remontée durable des détections et les alertes
|
||||
|
||||
Priorité P1. Défauts PIPE-10, FEAT-05, UI-03. Estimation : 6–10 jours. Dépend des lots 2 à 4.
|
||||
|
||||
Travaux :
|
||||
|
||||
1. Spool local persistant et borné des événements avec identifiant stable, priorité et politique de saturation visible.
|
||||
2. Endpoint d’ingestion idempotent ; outbox transactionnelle serveur pour diffusion et notifications.
|
||||
3. Résoudre les destinataires via la même politique d’accès, puis préférences et abonnements ; séparer déduplication événement et rate limit par destinataire/canal.
|
||||
4. Raccorder le centre de notifications et les jobs externes avec retry, état de livraison et dead-letter consultable.
|
||||
5. Tester et coder les templates email, sans interpolation HTML non échappée de contenu utilisateur.
|
||||
6. Corriger les fenêtres des résumés quotidien/hebdomadaire, fuseaux et droits ; prévoir un renvoi sans doublon.
|
||||
|
||||
Acceptation : coupure réseau de cinq minutes puis reprise sans perte ni doublon ; deux utilisateurs autorisés reçoivent chacun leur alerte ; aucun utilisateur hors périmètre ; canal SMTP indisponible repris après rétablissement ; dates du résumé vérifiables.
|
||||
|
||||
## Lot 6 — Raccorder l’analyse distribuée
|
||||
|
||||
Priorité P1. Défauts PIPE-01, PIPE-02, PIPE-06, PIPE-11. Estimation : 6–10 jours. Dépend des lots 2, 3 et 5.
|
||||
|
||||
Décision de conception à formaliser dans une ADR : RabbitMQ est le chemin déjà équipé en contrats/consommateur ; le retenir comme parcours principal évite de maintenir deux modes incomplets. Si le broker HTTP externe est conservé, livrer son contrat, son déploiement, sa politique d’accès et ses tests séparément.
|
||||
|
||||
Travaux :
|
||||
|
||||
1. Brancher les producteurs de jobs aux captures avec règles de priorité et bornage de charge.
|
||||
2. Utiliser une référence de frame persistée/autorisé plutôt que des blobs Base64 illimités dans les messages.
|
||||
3. Publier les demandes via outbox ; adresser précisément une queue par agent et empêcher les acquittements par un autre agent.
|
||||
4. Implémenter les consommateurs Central Started/Completed/Failed et les transitions idempotentes ; persister le résultat structuré et créer les événements utiles.
|
||||
5. Traiter indisponibilité modèle/provider, timeout, annulation et retry distinctement de « aucune détection ».
|
||||
6. Configurer le provider GPU réellement disponible et son fallback ; corriger scoring/capacités et limites de concurrence.
|
||||
7. Empêcher les doubles dispatchs entre instances avec prise atomique du job et lease.
|
||||
|
||||
Acceptation : job suivi de Pending à Completed ou DeadLettered, résultat visible ; deux agents consomment uniquement leurs travaux ; redémarrage du broker et messages dupliqués sans double résultat ; absence de modèle visible comme erreur.
|
||||
|
||||
## Lot 7 — Rétention et exploitation fiables
|
||||
|
||||
Priorité P1/P2. Défauts OPS-01 à OPS-04, OPS-06. Estimation : 4–7 jours. Peut commencer dès le lot 2 ; la gestion d’objets dépend du lot 4.
|
||||
|
||||
Travaux :
|
||||
|
||||
1. Uniformiser les noms des variables Docker, exiger les secrets indispensables et valider le rendu compose dans la CI sans révéler de secrets.
|
||||
2. Corriger le parseur de partitions et fermer les readers avant DDL ; tester sur PostgreSQL.
|
||||
3. Corriger le cron du timeout sweep, éviter les chevauchements concurrents, valider les occurrences attendues.
|
||||
4. Implémenter tombstones/purge fichiers avec retries et réconciliation ; inclure les objets staging et les médias liés à des suppressions métier.
|
||||
5. Résoudre les objets selon leur provider historique ; rendre un provider indisponible visible, éviter un fallback silencieux qui change la destination.
|
||||
6. Tester la restauration isolée de PostgreSQL, des objets et des clés Data Protection ; définir RPO/RTO et procédure mesurée.
|
||||
7. Vérifier readiness, métriques et alertes : modèle absent, queue pleine, backlog, disque, jobs bloqués, perte de configuration et échec livraison.
|
||||
|
||||
Acceptation : base et fichiers expirés supprimés de manière reprise/idempotente, objets récents préservés, ancien objet lisible après changement de provider, reprise d’un backup démontrée, compose de référence validé.
|
||||
|
||||
## Lot 8 — Rendre les mises à jour agent opérationnelles
|
||||
|
||||
Priorité P1/P2. Défaut OPS-05. Estimation : 3–6 jours. Dépend du lot 2.
|
||||
|
||||
Travaux : autoriser la lecture du manifeste par la bonne identité agent ; envoyer une commande ciblée pour l’action manuelle ; exposer progression et version effective ; vérifier hash/signature avant exécution ; arrêt propre, remplacement atomique du bon artefact et rollback si la nouvelle version ne devient pas saine. Distinguer binaire natif et image Docker, et traiter les archives de release selon leur format.
|
||||
|
||||
Acceptation : action manuelle observée par l’agent, téléchargement refusé si intégrité incorrecte, échec d’installation récupérable, redémarrage avec capture et identité conservées. Tests dans un environnement agent jetable.
|
||||
|
||||
## Lot 9 — Rendre le serveur installable en PWA
|
||||
|
||||
Priorité P1/P2. Référence : [audit et plan PWA](../pwa.md). Estimation : **16–28 jours-personne**, hors corrections auth/métier déjà comptées. Le client natif et son job CI ont été supprimés ; aucune remise en état native n’est planifiée.
|
||||
|
||||
Travaux : manifeste et icônes ; HTTPS/proxy fiable ; service worker limité aux assets publics et page hors connexion ; ressources essentielles locales ; expérience tactile ; reprise après veille/coupure ; correction des sessions ; abonnement et envoi Web Push par utilisateur/appareil ; mise à jour contrôlée des caches ; tests sur build publié et appareils réels.
|
||||
|
||||
Acceptation : installation, reprise et logout testés sur mobile/desktop ; aucun cache de données privées en V1 ; push avec application fermée, permissions/refus, droits révoqués et liens autorisés. Le fonctionnement métier reste connecté avec Interactive Server.
|
||||
|
||||
Option ultérieure : consultation métier hors ligne par une couche cliente autonome et stockage local isolé, **20–40 jours-personne supplémentaires à affiner**, sur décision de périmètre. Cette option ne fait pas partie du chiffrage de base.
|
||||
|
||||
## Lot 10 — Livrer la vidéo live web et PWA
|
||||
|
||||
Priorité P2. Défaut FEAT-01. Estimation : 10–18 jours. Dépend des lots 2, 3 et 9 pour la PWA.
|
||||
|
||||
Travaux : architecture média et coûts CPU/bande passante à fixer ; signaling autorisé ; création/fin de sessions ; ICE et TURN ; player web compatible mobile/PWA ; audio/PTZ si capacités compatibles ; timeout, reconnexion, indication fraîcheur et libération des ressources. Définir le nombre de spectateurs/caméras simultanés et les codecs supportés avant implémentation.
|
||||
|
||||
Acceptation : streaming sur LAN puis réseau externe nécessitant TURN, coupure/reconnexion, deux spectateurs, révocation d’accès, contrôle de latence selon objectif produit défini ; aucun processus/port/session restant après fermeture.
|
||||
|
||||
## Lot 11 — Livrer enregistrements et replay
|
||||
|
||||
Priorité P2. Défaut FEAT-02. Estimation : 10–18 jours. Dépend des lots 3, 4 et 7.
|
||||
|
||||
Travaux : segmentation FFmpeg, mode continu/sur événement, manifeste et intégrité, upload avec reprise, index temporel et association Recording, API paginée, lecteur avec recherche/range, export autorisé, politiques de rétention/quotas par site/caméra et occupation disque.
|
||||
|
||||
Acceptation : lecture d’un intervalle traversant plusieurs segments, coupure agent/stockage puis reprise, audio/horodatage cohérents, quota respecté, export autorisé et purge sans fuite d’objets.
|
||||
|
||||
## Lot 12 — Analyses spécialisées et liens métier
|
||||
|
||||
Priorité P2. Défauts FEAT-03, UI-02, profils PIPE-05. Estimation : 12–25 jours, à réestimer après prototype sur données représentatives. Dépend des lots 4, 5 et 6.
|
||||
|
||||
Travaux : choisir modèles/licences/compatibilités matériel, extraire et comparer embeddings faciaux, détection plaque + OCR + normalisation, gérer seuils et inconnus ; persister PersonId/VehicleId/plate dans les résultats et événements ; filtres API exacts et historique paginé ; activer les options seulement pour les agents disposant du pipeline effectif. Prévoir gestion de conservation et suppression des données associées.
|
||||
|
||||
Acceptation : jeu de validation versionné avec cas positifs/négatifs, métriques de faux positifs/faux négatifs et latence ; absence de confusion sur homonymes/renommages ; aucun job spécialisé exécuté silencieusement comme détection générique.
|
||||
|
||||
## Lot 13 — Documenter et valider la livraison
|
||||
|
||||
Priorité P2/P3. Défauts QA-01, DOC-01 et investigation UI-04. Effort transversal + 3–5 jours de consolidation.
|
||||
|
||||
Travaux : isoler et corriger les échecs navigateur de gestion utilisateurs, avec capture des réponses HTTP et du DOM ; remplacer l’état historique par une matrice « implémenté / validé / partiel / prévu » ; documenter l’architecture unifiée et les routes générées ; actualiser exemples API keys, Docker et limites du live. Intégrer tests de contrat et scénarios transversaux dans la CI, distinguer les tests dépendants de PostgreSQL/navigateur/matériel et rendre les prérequis explicites. Ajouter un contrôle de dépendances séparé des suppressions de warnings. Réaliser une campagne caméra/réseau et une campagne de charge sur objectifs chiffrés validés.
|
||||
|
||||
Acceptation : une installation depuis la documentation permet le parcours principal ; chaque fonction annoncée dispose d’un scénario de réception reproductible ; les tests ignorés et les résultats matériels ne sont pas assimilés à des tests passés.
|
||||
|
||||
## Jalons et dépendances
|
||||
|
||||
| Jalon | Lots | Résultat exigé |
|
||||
|---|---|---|
|
||||
| Socle — Builds Gitea | 0 | Chaîne reconstruite et validée sur runners Gitea |
|
||||
| A — Exposition maîtrisée | 1, 2, confinement du 4, configuration du 7 | Authentification et isolation testées ; aucune diffusion de secrets |
|
||||
| B — Surveillance utile | 3, 4, 5 | Détection persistée avec image et alerte, même après panne réseau |
|
||||
| C — Exploitation et distribution | 6, 7, 8 | Jobs distants suivis, purge et restauration, updates vérifiées |
|
||||
| D — Serveur installable en PWA | 9 | Installation, reprise mobile et Web Push validés |
|
||||
| E — Vidéo complète | 10, 11 | Live puis recherche/replay d’enregistrements |
|
||||
| F — Intelligence spécialisée | 12 | Reconnaissance évaluée et liée aux objets métier |
|
||||
| Réception finale | 13, critères de chaque lot | Documentation et preuves de réception cohérentes |
|
||||
|
||||
Ne pas lancer l’ensemble comme une seule PR. Découper chaque lot en changements revoyables : contrat/migration compatible, implémentation, raccordement UI/agent, puis scénario d’acceptation. Garder les nouvelles capacités désactivées tant que le pipeline requis n’est pas disponible ; planifier les migrations avec conservation des objets et rollback.
|
||||
|
||||
Le total brut des estimations représente environ **90–165 jours-personne**, hors refonte complète des builds Gitea (lot 0, à chiffrer), option métier hors ligne, marge matérielle et changements de périmètre. Il doit être réévalué à la fin du jalon B, avant l’investissement dans le live, le replay et les analyses spécialisées. Les fonctionnalités absentes peuvent être explicitement retirées d’une première version ; elles ne doivent pas être présentées comme livrées.
|
||||
@@ -1,33 +0,0 @@
|
||||
# Correctifs d’exploitation indépendants — PR A
|
||||
|
||||
Périmètre : SEC-08 (confinement local), OPS-03, OPS-04 et OPS-06 du rapport et du plan du 20 octobre 2026. Ce document ne clôture ni l’audit complet ni le lot 7.
|
||||
|
||||
## Changements
|
||||
|
||||
- Stockage local : seules des clés relatives à segments non vides, séparés par `/`, sont acceptées. Racine, `.`/`..`, chemins absolus Unix/Windows, antislashs et préfixes de lecteurs sont refusés. La vérification porte sur la relation au répertoire racine, sans comparaison de simple préfixe. Les liens symboliques/reparse points sont refusés sur la racine, ses ancêtres, les dossiers et les feuilles, y compris les liens pendants. Les uploads gardent staging et renommage atomique.
|
||||
- Partitions : format exact `camera_events_YYYY_MM`, chiffres ASCII et date valide ; seuls les enfants du parent `public.camera_events` sont candidats. Le reader est libéré avant le DDL. La connexion reste la propriété du DbContext. Une table indépendante portant un nom conforme est préservée.
|
||||
- Timeouts : cron cinq champs `* * * * *`, suppression du sweep redondant du dispatcher et verrou distribué Hangfire PostgreSQL sur le sweep dédié. Les appels directs hors Hangfire ne passent pas par son filtre ; les appelants de production sont les jobs configurés. Le verrou évite le chevauchement des sweeps, pas les autres transitions métier du scheduler (lots 3/6).
|
||||
- Compose : interpolation JWT en majuscules alignée sur `.env.example`, noms `HEIMDALL_*` alignés pour l’agent, secrets indispensables sans fallback dans la référence de développement. La production conserve ses fichiers secrets. Le mot de passe RabbitMQ de l’agent doit correspondre au fichier secret du broker. `DATABASE_URL` et `POSTGRES_PASSWORD` doivent désigner les mêmes credentials. Les exemples sont exclusivement destinés au développement ; ils ne démontrent pas un déploiement sécurisé.
|
||||
|
||||
## Vérification reproductible
|
||||
|
||||
```sh
|
||||
bash scripts/ci/validate-compose.sh
|
||||
dotnet test tests/Heimdall.Infrastructure.Tests -m:2 \
|
||||
--filter 'FullyQualifiedName~LocalStorageProviderTests|FullyQualifiedName~Partition|FullyQualifiedName~MaintenanceScheduleTests|FullyQualifiedName~SweepLockTests|FullyQualifiedName~AnalysisJobDispatcherJobTests' \
|
||||
--logger 'trx;LogFileName=ops-targeted.trx'
|
||||
```
|
||||
|
||||
Le script Compose valide silencieusement la référence, la production et l’overlay backup ; il exige aussi l’échec de chaque variable indispensable vide. Il ne démarre aucun service et ne prouve pas la disponibilité des fichiers secrets en production.
|
||||
|
||||
Résultats locaux : **39 réussis, 0 échoué, 0 ignoré** (.NET SDK 10.0.112, PostgreSQL 17 Testcontainers, durée tests 52 s). Les contrôles Compose positifs et négatifs passent. Le détail compact est dans `2026-10-20-ops-tests.json`. Une première exécution avait révélé une interaction de fixtures (tables Hangfire empêchant EnsureCreated) ; le test de verrou utilise désormais sa propre base jetable, comme le test de partitions. Aucun test distant de cette PR n’est revendiqué : la branche principale ne contient aucun workflow.
|
||||
|
||||
## Conditions et travaux restants
|
||||
|
||||
Le stockage et ses ancêtres doivent être modifiables uniquement par le compte de service et les administrateurs de confiance. Les contrôles managés de liens ne constituent pas une protection contre un processus local hostile ayant le droit de remplacer des répertoires entre vérification et ouverture (TOCTOU). Aucune nouvelle API média n’est exposée par cette PR.
|
||||
|
||||
La purge des objets, les tombstones/outbox et la résolution des providers historiques restent dépendants du contrat d’objets du lot 4. OPS-01/OPS-02, staging/orphelins, restauration mesurée, RPO/RTO et campagne de métriques ne sont pas déclarés corrigés. Les lots auth, accès et pipeline/scoring sont hors périmètre.
|
||||
|
||||
## Inventaire distant (lecture seule, sans valeurs secrètes)
|
||||
|
||||
API Gitea consultée avec les credentials existants : version `28.1.0`, Actions activé, branche principale `main`, trois runners d’instance en ligne (`runner-odin`, `runner-murin`, `runner-hugin`, label `ubuntu-latest`). Aucun runner propre au dépôt, secret/variable Actions de dépôt ni protection de branche. Les listes de packages conteneurs du propriétaire, releases et artefacts du dépôt sont vides à la consultation. L’API ne donne pas la configuration hôte effective des runners ni leur accès Docker. Aucun secret n’a été imprimé. Aucun déploiement ni tag/release de test déclenché.
|
||||
@@ -1,106 +0,0 @@
|
||||
# Preuves et limites de validation de l’audit
|
||||
|
||||
Révision : `7792353`. Environnement : Linux x64, SDK .NET `10.0.112`, runtime .NET `10.0.12`, Docker `29.8.1`. Les suites dépendant de PostgreSQL ont pu utiliser Testcontainers ; Chromium était disponible pour Playwright.
|
||||
|
||||
## Tests .NET
|
||||
|
||||
Commande exécutée depuis la racine :
|
||||
|
||||
```bash
|
||||
dotnet test Heimdall.slnx --verbosity minimal
|
||||
```
|
||||
|
||||
| Suite | Réussis | Échoués | Ignorés |
|
||||
|---|---:|---:|---:|
|
||||
| Domain | 179 | 0 | 0 |
|
||||
| Application | 504 | 0 | 0 |
|
||||
| Infrastructure | 223 | 0 | 0 |
|
||||
| API | 2 | 0 | 0 |
|
||||
| Web (bUnit et services) | 350 | 0 | 0 |
|
||||
| Agent | 355 | 0 | 0 |
|
||||
| Intégration | 138 | 0 | 0 |
|
||||
| **Sous-total hors E2E** | **1 751** | **0** | **0** |
|
||||
|
||||
La compilation des projets de la solution a permis d’atteindre l’exécution de toutes ces suites. Cela ne valide pas les parcours matériels ni les fonctionnalités non raccordées.
|
||||
|
||||
Résultat Playwright final : **29 réussis, 4 échoués, 0 ignoré, 33 au total** (4 min 34 s). Échecs dans UserManagementTests :
|
||||
|
||||
- Users_page_lists_admin_when_authenticated : email admin attendu absent du DOM.
|
||||
- Admin_can_create_a_viewer_user_via_the_dialog : timeout sur l’apparition du nouvel utilisateur.
|
||||
- Admin_can_edit_user_display_name_and_roles : timeout sur l’apparition de l’utilisateur.
|
||||
- Admin_can_reset_user_password : timeout sur l’apparition de l’utilisateur.
|
||||
|
||||
**Total solution : 1 780 réussis, 4 échoués, 0 ignoré, 1 784 tests.** La commande complète échoue donc ; l’application n’est pas déclarée entièrement validée. Les causes racines des quatre échecs navigateur restent à isoler (UI-04).
|
||||
|
||||
## Vérification native avant retrait (historique)
|
||||
|
||||
Commande :
|
||||
|
||||
```bash
|
||||
cd src/Heimdall.Mobile
|
||||
./gradlew :domain:test --no-daemon --console=plain
|
||||
```
|
||||
|
||||
Résultat : échec de préparation du build, avant exécution des tests. Le plugin Android ne trouve pas de SDK : `SDK location not found`, `ANDROID_HOME` ou `sdk.dir` nécessaire. Ce résultat ne démontrait pas un défaut de compilation Kotlin. Le client natif a ensuite été supprimé à la demande du propriétaire ; il n’est plus un livrable à valider.
|
||||
|
||||
## Configuration Docker
|
||||
|
||||
Commande de validation, sans afficher le rendu contenant les secrets :
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet
|
||||
```
|
||||
|
||||
La commande accepte la syntaxe mais avertit que `JWT__Key`, `JWT__RefreshKey` et `HEIMDALL_SITE_TOKEN` sont absents et remplacés par des valeurs vides. L’exemple définit respectivement `JWT__KEY`, `JWT__REFRESHKEY` et `Agent__SiteToken`. Le scénario « copier l’exemple puis lancer le compose » nécessite donc une correction ; une syntaxe compose valide ne garantit pas que le service démarre avec une configuration utilisable.
|
||||
|
||||
## Sondes de comportement
|
||||
|
||||
Un petit projet console temporaire hors dépôt a chargé les assemblies disponibles après compilation. Aucun changement du code métier n’a été nécessaire.
|
||||
|
||||
### DropWrite et TryWrite
|
||||
|
||||
```csharp
|
||||
var c = Channel.CreateBounded<int>(new BoundedChannelOptions(1) {
|
||||
FullMode = BoundedChannelFullMode.DropWrite
|
||||
});
|
||||
var first = c.Writer.TryWrite(1);
|
||||
var second = c.Writer.TryWrite(2);
|
||||
var retained = await c.Reader.ReadAsync();
|
||||
```
|
||||
|
||||
Résultat : `first=True, second=True, retained=1`. Le second élément est abandonné sans `TryWrite=false`. La branche de FrameAnalyzerService qui devrait compléter la tâche rejetée ne peut donc pas traiter ce cas de saturation.
|
||||
|
||||
### Confinement des chemins
|
||||
|
||||
```csharp
|
||||
var root = "/tmp/audit/storage";
|
||||
var path = Path.GetFullPath(Path.Combine(root, "../storage-sibling/secret"));
|
||||
var accepted = path.StartsWith(root, StringComparison.Ordinal);
|
||||
```
|
||||
|
||||
Résultat : chemin `/tmp/audit/storage-sibling/secret`, `accepted=True`. Ce test ne lit ni n’écrit un fichier sensible ; il démontre l’insuffisance du test de préfixe utilisé par le provider.
|
||||
|
||||
### Partitions
|
||||
|
||||
`"camera_events_2025_01".Length` vaut 21. Le contrôle courant exige 22. L’année commence à l’index 14, le mois à l’index 19 ; le code utilise 15 et 20. Les partitions produites par le job ne passent pas son propre parseur de purge.
|
||||
|
||||
### Cron Hangfire
|
||||
|
||||
La méthode interne de validation cron de l’assembly Hangfire.Core du projet a été appelée par réflexion : `*/30 * * * * *`, `*/1 * * * * *` et `* * * * *` sont acceptés. L’audit ne retient donc pas l’hypothèse initialement envisagée d’un cron à six champs invalide. Le défaut constaté est la fréquence du timeout sweep : chaque seconde, au lieu de la minute annoncée par le commentaire.
|
||||
|
||||
## Traçabilité
|
||||
|
||||
Les sorties brutes de cette session sont conservées temporairement dans :
|
||||
|
||||
- `/tmp/heimdall-audit-tests.log`
|
||||
- `/tmp/heimdall-audit-mobile.log`
|
||||
- `/tmp/heimdall-audit-compose.log`
|
||||
- `/tmp/heimdall-audit-probes/`
|
||||
|
||||
Ces chemins temporaires ne font pas partie des livrables versionnés et peuvent disparaître. Les résultats utiles sont retranscrits ci-dessus ; les logs complets ne sont pas ajoutés au dépôt afin d’éviter d’y conserver des données de test ou des valeurs de configuration inutiles.
|
||||
|
||||
## Vérification du retrait natif et de la documentation PWA
|
||||
|
||||
Le répertoire natif, sa spécification dédiée, le job CI et sa dépendance de clôture ont été retirés. Les références actives à l’ancien projet, à Gradle et au job natif ont été recherchées dans le dépôt. La CI YAML a été parsée avec PyYAML et les dépendances de jobs résolues : 10 jobs restants, aucune dépendance manquante. La solution .NET n’incluait pas ce projet.
|
||||
|
||||
Le rapport PWA repose sur l’inspection du code et des documentations officielles référencées. Aucun manifeste, worker ou endpoint push n’a été ajouté : l’implémentation PWA n’était pas demandée, son audit et son plan sont livrés.
|
||||
@@ -0,0 +1,277 @@
|
||||
# Docker Compose deployment
|
||||
|
||||
The required stack is PostgreSQL and Heimdall Central. The Agent is deployed
|
||||
separately on each camera-network host; the Central UI supplies an Agent
|
||||
Compose file using the `latest` tag for each site. RustFS, ntfy, Ollama, TURN,
|
||||
Redis and scheduled backups have separate Compose files and can be left out.
|
||||
|
||||
## Central and database
|
||||
|
||||
For a new Linux server, run the interactive installer directly from the source
|
||||
repository; cloning the repository is not required:
|
||||
|
||||
```bash
|
||||
SOURCE_BASE_URL="${HEIMDALL_SOURCE_BASE_URL:-https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main}"
|
||||
curl -fsSL "$SOURCE_BASE_URL/install/install-server.sh" | HEIMDALL_SOURCE_BASE_URL="$SOURCE_BASE_URL" bash
|
||||
```
|
||||
|
||||
The installer uses `eltruncho/heimdall:latest` from Docker Hub, creates a
|
||||
minimal Central + PostgreSQL Compose project, and configures the maintained
|
||||
`nickfedor/watchtower` fork to check the explicitly labelled Central container
|
||||
every 24 hours. Watchtower uses `--cleanup` to remove the previous Central
|
||||
image after updating; it does not remove PostgreSQL data or named volumes.
|
||||
`pull_policy: always` also makes each `docker compose up` pull the configured
|
||||
images, including optional service Compose files. It generates PostgreSQL and JWT secrets locally and writes them to a
|
||||
mode-600 `.env` and secret file in the chosen installation directory. It asks
|
||||
which optional services to prepare and whether to start each one. Selected
|
||||
optional Compose files and backup scripts are fetched individually; no
|
||||
repository checkout is created. Integration URLs and credentials remain
|
||||
configured in Central's UI. The script requires an interactive terminal and
|
||||
reads prompts from it even when downloaded with a pipe.
|
||||
|
||||
Running either installer again in the same directory offers to refresh the
|
||||
generated Compose. It first validates the new file, saves the previous one as
|
||||
`docker-compose.yml.bak.<timestamp>`, and replaces it. Existing `.env`, secret
|
||||
files, and Docker volumes are preserved. If the new Compose requires an env
|
||||
key that is missing, the installer adds a generated secret or a default value
|
||||
without changing existing entries. It does not rotate the PostgreSQL password;
|
||||
the existing secret file and `DATABASE_URL` must remain paired. Declining the
|
||||
update leaves the installation unchanged. Inspect custom Compose edits in the
|
||||
backup before deciding whether to carry them into future generated versions.
|
||||
If you choose an optional service again, its refreshed Compose or script asset
|
||||
also gets a timestamped backup before replacement.
|
||||
|
||||
Watchtower needs access to `/var/run/docker.sock`, which grants broad control
|
||||
over the Docker host. The upstream project describes itself for homelabs and
|
||||
similar setups and does not recommend it for commercial/production workloads;
|
||||
automatic latest-tag updates also do not provide staged rollout or rollback.
|
||||
For stricter production change control, disable/remove the Watchtower service
|
||||
and deploy a reviewed image digest through an orchestrator or release process.
|
||||
|
||||
On Windows 10/11 with Docker Desktop in Linux-container mode, use PowerShell to
|
||||
download and run the matching installer without cloning the repository:
|
||||
|
||||
```powershell
|
||||
$sourceBase = if ($env:HEIMDALL_SOURCE_BASE_URL) { $env:HEIMDALL_SOURCE_BASE_URL.TrimEnd('/') } else { 'https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main' }
|
||||
$installer = Join-Path $env:TEMP 'heimdall-install-server.ps1'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri "$sourceBase/install/install-server.ps1" -OutFile $installer
|
||||
Set-ExecutionPolicy -Scope Process Bypass -Force
|
||||
& $installer
|
||||
Remove-Item $installer
|
||||
```
|
||||
|
||||
The execution-policy bypass applies only to the current PowerShell process; a
|
||||
Group Policy can still block script execution. Both installers generate secrets
|
||||
locally and keep them in the selected installation directory. The scripts use the
|
||||
source URL shown above by default. To pin a reviewed revision, set
|
||||
`HEIMDALL_SOURCE_BASE_URL` to its `raw/commit/<SHA>` URL before downloading and
|
||||
running the installer; this also selects optional Compose and backup files. An
|
||||
offline installation must provide those selected assets.
|
||||
|
||||
The repository's `docker/docker-compose.prod.yml` is a manual alternative for
|
||||
operators who need a custom layout. It includes the same scoped Watchtower
|
||||
service and pull policies. Keep `docker/.env` private (mode 600) and create a
|
||||
PostgreSQL password file; its value must match the password in `DATABASE_URL`.
|
||||
The `.env.example` file contains development credentials and must not be used
|
||||
unchanged for a production deployment.
|
||||
|
||||
```sh
|
||||
umask 077
|
||||
mkdir -p -m 700 docker/secrets
|
||||
db_password="$(openssl rand -hex 32)"
|
||||
printf '%s' "$db_password" > docker/secrets/db_password
|
||||
cat > docker/.env <<EOF
|
||||
POSTGRES_DB=heimdall
|
||||
POSTGRES_USER=heimdall
|
||||
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=${db_password}
|
||||
JWT__KEY=$(openssl rand -hex 32)
|
||||
JWT__REFRESHKEY=$(openssl rand -hex 32)
|
||||
JWT__ISSUER=heimdall
|
||||
JWT__AUDIENCE=heimdall-api
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
WEB_PORT=5000
|
||||
RECORDING_STORAGE_QUOTA_MAX_BYTES=1099511627776
|
||||
Cors__AllowedOrigins=https://heimdall.example.org
|
||||
EOF
|
||||
unset db_password
|
||||
# Replace the example origin above with the public origin of your Central.
|
||||
# The recording quota defaults to 1 TiB (1099511627776 bytes).
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
Central images also include Tesseract OCR and its English language data. The
|
||||
manual license-plate crop reader is opt-in and defaults to disabled. Core and
|
||||
production Compose files, plus both server installer templates, map
|
||||
`PLATE_OCR_ENABLED` to Central's `PlateOcr__Enabled` option. Installer-generated
|
||||
`.env` files set it to `false`; set `PLATE_OCR_ENABLED=true` and recreate the
|
||||
Central service to enable the feature. Existing installer upgrades preserve an
|
||||
existing value and add `false` only when the key is absent.
|
||||
|
||||
When enabled, an authorized operator can upload a JPEG/PNG plate crop from the
|
||||
camera detail page. Processing runs on Central; the temporary crop is removed
|
||||
after processing, while the candidate text and history event are persisted.
|
||||
The feature limits uploads to 512 KiB and images to four megapixels. It does
|
||||
not detect plates in video or perform face recognition, and the OCR result is
|
||||
not a verified identity. Review retention/privacy implications in
|
||||
[`skills/vision-identity/SKILL.md`](../skills/vision-identity/SKILL.md) before
|
||||
enabling it.
|
||||
|
||||
The development Compose builds Central from the local source and starts only
|
||||
Central plus PostgreSQL:
|
||||
|
||||
```sh
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d
|
||||
```
|
||||
|
||||
For a disposable local installation, copy `.env.example` to an ignored
|
||||
temporary env file, replace the sample database/JWT values with generated
|
||||
values, and choose unused loopback ports. Use a unique Compose project name and
|
||||
`HEIMDALL_NETWORK_NAME`; after checking `/healthz`, stop only that project with
|
||||
`docker compose -p <project> ... down --volumes --remove-orphans`. Verify its
|
||||
containers, volumes, and network are gone. Never use `.env.example` unchanged
|
||||
for an exposed or production deployment. The disposable recipe is maintained
|
||||
in [`skills/deployment-guide-acceptance/SKILL.md`](../skills/deployment-guide-acceptance/SKILL.md).
|
||||
|
||||
## Agent
|
||||
|
||||
Prefer the Compose shown in the Central UI's site installation panel. It uses
|
||||
the Agent image's `latest` tag and includes the site token, public Central URL,
|
||||
Agent name and release public key. Compose uses `pull_policy: always` so an
|
||||
explicit `docker compose up` checks for the latest image. Save it as
|
||||
`docker-compose.yml`, then run `docker compose up -d`. The generated Compose
|
||||
contains the pinned trust key; no separate PEM file is required. Updates
|
||||
dispatched later by Central continue to verify the digest in the signed release
|
||||
manifest before replacing the running container.
|
||||
|
||||
The Agent Compose is generated by Central's UI for the selected site; there is
|
||||
no production Agent Compose in this repository. For local development only,
|
||||
use `docker/docker-compose.agent.dev.yml` with a development site token and the
|
||||
local Central URL. The published Agent image uses CPU inference. The optional
|
||||
NVIDIA, AMD and Intel overlays expose hardware for inventory; they do not
|
||||
enable GPU inference.
|
||||
|
||||
Docker Agents mount `/var/run/docker.sock` so the Agent can pull and replace its
|
||||
container when Central dispatches an update. This socket grants broad control
|
||||
of the Docker host, effectively host-administrator access. Keep it only on
|
||||
hosts where that trust is acceptable. The Agent image includes the Docker CLI
|
||||
client; it does not run a Docker daemon. Updates preserve the previous image
|
||||
for rollback if the replacement fails its health check. On Linux, start the
|
||||
generated Compose with `DOCKER_GID="$(stat -c '%g' /var/run/docker.sock)"
|
||||
docker compose up -d` so the non-root Agent process can access hosts whose
|
||||
socket is owned by the Docker group. The UI's `docker run` command determines
|
||||
this group ID from the host socket automatically.
|
||||
|
||||
## Optional software
|
||||
|
||||
Start Central first to create the shared `heimdall-net` network. Optional
|
||||
services then join that network where applicable, so their Compose projects
|
||||
remain separate while Central can resolve their service names.
|
||||
|
||||
```sh
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.ollama.yml up -d
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.ntfy.yml up -d
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.rustfs.yml up -d
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.coturn.yml up -d
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.redis.yml up -d
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.backup.yml up -d
|
||||
```
|
||||
|
||||
Configure Ollama at `http://ollama:11434` in Central's AI settings when enabled.
|
||||
Choose RustFS as the storage provider in Central and use `http://rustfs:9000` as
|
||||
its endpoint. Configure the ntfy server URL in Central's notification settings.
|
||||
Live view can connect directly when ICE succeeds. For clients behind restrictive NAT/firewalls, deploy and validate TURN, then configure its URLs and matching shared secret in Central; without a reachable relay, those clients may not connect.
|
||||
Redis is provided as a standalone service but is not currently required by
|
||||
Central. Backups are independent of the core startup and require the core
|
||||
network and PostgreSQL service to be running.
|
||||
|
||||
See [GPU Agent notes](gpu-runtime.md) and
|
||||
[Agent update signing](agent-release-signing.md) for device access and
|
||||
trusted-key setup.
|
||||
|
||||
## Optional live video with WebRTC
|
||||
|
||||
The live-view vertical uses the separately maintained MediaMTX image. It is not
|
||||
started with the core stack. Configure Central with the public `HEIMDALL_WHEP_URL`
|
||||
and `HEIMDALL_PUBLISH_RTSPS_URL` (including scheme, host and port only). Provide
|
||||
`HEIMDALL_MEDIAMTX_AUTH_URL` to the MediaMTX container; when both services share
|
||||
the default Docker network this can use the Central service name and internal
|
||||
port. Configure `HEIMDALL_WEBRTC_PUBLIC_HOST`,
|
||||
`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and `HEIMDALL_LIVE_MEDIA_CERT_DIR` for the
|
||||
public listener and its TLS certificate (`server.crt` and `server.key`). The
|
||||
certificate must cover both public WHEP and RTSPS hostnames. Open the configured
|
||||
RTSPS/WHEP TCP ports and WebRTC ICE UDP port in the firewall. Add STUN URLs under
|
||||
`LiveMedia:IceServers`; for TURN REST credentials set
|
||||
`LiveMedia:Turn:Urls` and `LiveMedia:Turn:SharedSecret`. Central returns
|
||||
five-minute HMAC credentials to the browser; the shared secret is never sent.
|
||||
When using `docker-compose.coturn.yml`, the installer stores its shared secret
|
||||
at `optional/secrets/coturn_secret`. Configure the matching TURN shared secret
|
||||
in Central from that protected file and protect Central's `.env` with owner-only
|
||||
permissions. Coturn publishes TCP/UDP 3478 and UDP relay ports 49160–49200 by
|
||||
default; forward those ports through the host firewall/NAT. Set
|
||||
`COTURN_RELAY_PORT_MIN` and `COTURN_RELAY_PORT_MAX` together if you need a
|
||||
different relay range, and `COTURN_EXTERNAL_IP` when coturn must advertise an
|
||||
address other than the container's detected address. Use Docker's default bridge network; coturn must not use `network_mode: host` when relying on published ports.
|
||||
|
||||
Start the core project first so its external `heimdall-net` network exists, then
|
||||
start MediaMTX with a separate project name:
|
||||
|
||||
```sh
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.webrtc.yml -p heimdall-live up -d
|
||||
```
|
||||
|
||||
Stop only this optional project with `docker compose ... -p heimdall-live down`.
|
||||
Live publishing requires an assigned Agent and an online, enabled camera. Agent
|
||||
relays are video-only H.264 passthrough, limited to two simultaneous cameras per
|
||||
Agent. Central reserves eight viewers per camera and two per user in its process;
|
||||
use one Central instance until shared reservation storage is configured. A stream
|
||||
with a browser-incompatible codec is not transcoded. The WHEP read session
|
||||
expires after ten minutes; the browser deletes the WHEP resource on
|
||||
stop/navigation. Physical camera and external TURN validation remain deployment
|
||||
acceptance work.
|
||||
|
||||
### Disposable live-view acceptance
|
||||
|
||||
For an isolated local playback test, use the local-only override and synthetic
|
||||
source Compose files. Generate a unique `.env` outside the repository with new
|
||||
PostgreSQL/JWT secrets, loopback ports, `HEIMDALL_NETWORK_NAME`,
|
||||
`HEIMDALL_WEBRTC_ALLOWED_ORIGIN`, and
|
||||
`HEIMDALL_MEDIAMTX_AUTH_URL=http://heimdall:8080/api/live-media/auth`.
|
||||
Configure `HEIMDALL_WHEP_URL=http://127.0.0.1:<whep-port>`,
|
||||
`HEIMDALL_PUBLISH_RTSPS_URL=rtsp://127.0.0.1:<publish-port>`,
|
||||
`HEIMDALL_ALLOW_INSECURE_HTTP=true`,
|
||||
`HEIMDALL_ALLOW_INSECURE_RTSP=true`, and
|
||||
`HEIMDALL_WEBRTC_ALLOWED_ORIGIN=http://localhost:<web-port>`. Set
|
||||
`HEIMDALL_NETWORK_NAME` to a unique network name and select unused values for
|
||||
`WEB_PORT`, `HEIMDALL_TEST_PUBLISH_PORT`, `HEIMDALL_TEST_WHEP_PORT`,
|
||||
`HEIMDALL_TEST_ICE_PORT`, `HEIMDALL_SYNTHETIC_RTSP_PORT`, and
|
||||
`HEIMDALL_TEST_AGENT_PORT`. Insecure protocols are allowed only because all media
|
||||
ports bind to loopback in this recipe. Then start Central, the local MediaMTX,
|
||||
and synthetic source from changed source, excluding the Agent until a site token
|
||||
is available:
|
||||
|
||||
```sh
|
||||
docker compose -p "$project" --env-file "$env_file" \
|
||||
-f docker/docker-compose.yml \
|
||||
-f docker/docker-compose.webrtc-local-test.yml \
|
||||
-f docker/docker-compose.webrtc-test.yml \
|
||||
up -d --build postgresql heimdall mediamtx synthetic-camera synthetic-camera-publisher
|
||||
```
|
||||
|
||||
Complete first-admin setup, create a site, put its generated test site token in
|
||||
the disposable `.env`, and start `heimdall-agent` from the same Compose files.
|
||||
Create and assign an online camera with the synthetic source RTSP URL, then open
|
||||
its detail page and start live video. Verify an ungranted user is denied, stop
|
||||
and disable the camera, and check the Agent process and WHEP session are closed.
|
||||
Use unique ports and the unique network value for each run. Tear down only this
|
||||
project with `down --volumes --remove-orphans`, confirm its containers, named
|
||||
volumes and network are gone, and delete its temporary environment/secret files.
|
||||
This recipe is HTTP/RTSP loopback-only; production configuration remains RTSPS
|
||||
and HTTPS with a trusted certificate.
|
||||
|
||||
A source-built disposable acceptance on 5 November 2026 decoded a 640×360 synthetic
|
||||
frame through the actual `live-view.js` module in Chromium. WHEP resource deletion
|
||||
returned 200, Central session release returned 204, and disabling the camera
|
||||
reduced the Agent publisher count from one to zero. The project teardown left no
|
||||
containers, volumes, or network. MediaMTX origins and public ICE host must be passed
|
||||
through its `MTX_WEBRTCALLOWORIGINS` and `MTX_WEBRTCADDITIONALHOSTS` environment
|
||||
variables; placeholders inside `mediamtx.yml` are not expanded.
|
||||
@@ -0,0 +1,33 @@
|
||||
# CI Gitea et images Heimdall
|
||||
|
||||
La chaîne active est `.gitea/workflows/build.yml`. Le job `changes` détecte le graphe touché. Les PR compilent et testent le code concerné, puis construisent/scannent uniquement les images dont les fichiers ou dépendances ont changé. Les jobs d’image tournent en parallèle après `verify`. `CI policy` doit être configuré comme contrôle obligatoire de `main`.
|
||||
|
||||
## Sélection des runners
|
||||
|
||||
Les jobs exigent `runs-on: [ubuntu-latest, build-agent]`. Déclarer `build-agent:host` sur les runners de build autorisés, jamais sur `runner-aaja`, qui appartient à un autre environnement. Le premier label détermine l'exécution en conteneur ; `build-agent` est une contrainte de placement. Le workflow est en attente si aucun runner éligible n'est disponible.
|
||||
|
||||
Chaque runner lit sa configuration au démarrage. Ne pas rediriger `sources.tordais.cc` vers `host-gateway` dans `container.options` : cela a empêché les checkouts. Le workflow ne publie pas de rapports comme artefacts distants : les fichiers `artifacts/` sont utilisés dans le job (par exemple pour le seuil de couverture), puis disparaissent avec celui-ci. Le run historique #442 a signalé `CreateArtifact: EHOSTUNREACH`; aucun job courant ne dépend du service artefacts pour réussir.
|
||||
|
||||
Le workflow Renovate lit l’API Forgejo dans la variable d’action `FORGEJO_API_ENDPOINT` et le jeton du bot dans le secret `RENOVATE_TOKEN`; l’endpoint doit être l’URL HTTPS de l’API qui se termine par `/api/v1`. Forgejo réserve les noms de variables commençant par `GITEA_`. Avant de démarrer Renovate, le workflow vérifie que le jeton authentifie `/user` et peut lire le dépôt `arnaud.dartois/Heimdall`. Une réponse HTTP 401/403 indique un secret manquant, invalide ou insuffisamment autorisé; le bot doit avoir lecture et écriture du dépôt pour créer des PR. Le précontrôle confirme seulement la lecture : un run qui ouvre ou actualise une PR reste nécessaire pour prouver l’accès en écriture. Le workflow ne journalise ni les jetons ni les réponses API.
|
||||
|
||||
`scripts/ci/cleanup-docker.sh` journalise l'espace et élimine avant/après les builds les anciennes images Heimdall, les volumes Trivy abandonnés, les couches de build inutilisées depuis plus de 30 minutes et les images pendantes. Il ne purge pas les volumes, réseaux ou images nommées des autres projets. Le run #194 sur `runner-odin` a récupéré 95,89 Go avant build et 7,703 Go après job ; les 1 965 tests, deux images et scans ont réussi.
|
||||
|
||||
## Tests
|
||||
|
||||
`CI policy` sélectionne les workflows qui nécessitent une validation lourde par comparaison Git. `test-plan.py` sélectionne les suites affectées et leurs projets de build selon les fichiers modifiés et les `ProjectReference` transitifs; `build-plan.py` ne compile que ces cibles sur une PR. Un changement de solution, SDK, configuration de build, Docker ou CI élargit le plan à toute la solution. Si la comparaison Git du plan est impossible, toutes les suites sont exécutées. Le restore NuGet verrouillé reste solution-wide pour la vérification des dépendances, mais les compilations ciblées ne recompilent pas les graphes Agent/Web sans lien avec les fichiers touchés. Les pushes sur `main` qui passent le filtre de chemins exécutent toutes les suites ; les tags `*.*.*` ne sont pas filtrés par chemins et exécutent toutes les suites. Le plan est écrit dans `artifacts/tests/plan.json` et chaque suite apparaît dans une étape distincte. Chaque suite utilise sa propre base PostgreSQL jetable ; les tests navigateur installent Chromium seulement lorsqu'ils sont sélectionnés.
|
||||
|
||||
## Publication continue
|
||||
|
||||
Les PR ne reçoivent aucun secret de publication et ne poussent aucune image. Les runs du même ref sont sérialisés pour qu’un build plus lent d’un commit ancien ne remette pas `latest` en arrière. Après validation sur `main`, chaque job touché publie sur Docker Hub son image `sha-<SHA>` et déplace uniquement son propre tag `latest`. Les builds inchangés sont sautés, y compris si le changement ne concerne que la documentation, le compose de déploiement ou un autre composant.
|
||||
|
||||
Une version est publiée en poussant un tag `MAJOR.MINOR.PATCH` (suffixe prerelease accepté). Le workflow complet construit/scanne les images serveur, Agent CPU et Agent GPU une seule fois, puis publie leurs tags `sha-<SHA>` et version sur Docker Hub. Le job release réutilise ces images pour recueillir les digests; il ne les reconstruit pas et ne les rescane pas. Gitea reçoit `heimdall-installers-<version>.zip` pour Central, plus les archives Agent signées, leur clé publique, leur manifeste et les références d’images CPU/GPU nécessaires aux mises à jour natives. Provenance, liste de digests et checksums restent dans la sortie interne CI. Les couches Docker ne sont jamais attachées à Gitea. Les scripts Central `.sh` et `.ps1` récupèrent l’API de la dernière release stable, téléchargent le ZIP correspondant et exécutent son script épinglé à cette version; `HEIMDALL_INSTALLER_VERSION` permet de demander une version explicite. Le panneau d’installation Central confirme la release signée et masque les commandes natives tant que les assets nécessaires ne sont pas disponibles.
|
||||
|
||||
Le namespace `eltruncho` correspond au Compose de production actuel. Les secrets Actions `DOCKERHUB_USERNAME`, `DOCKERHUB_TOKEN` et `RELEASE_SIGNING_KEY_B64` doivent être disponibles pour les jobs qui publient. Le job de tag utilise le jeton intégré `GITEA_TOKEN`, avec `contents: write` et `pull-requests: read`, uniquement dans ce job; aucun PAT durable `RELEASE_TOKEN` n’est requis et les PR ne reçoivent pas ce droit d’écriture. `RELEASE_SERVER_URL` est une variable Actions contenant l’origine HTTPS publique de la forge. Les identifiants Docker sont transmis à `docker login` sur stdin et stockés dans une configuration temporaire supprimée en sortie.
|
||||
|
||||
## Renovate
|
||||
|
||||
`.gitea/workflows/renovate.yml` exécute Renovate chaque lundi et sur déclenchement manuel. Le secret `RENOVATE_TOKEN` doit appartenir à un compte bot Gitea autorisé à lire et écrire le dépôt et à ouvrir des PR. `renovate.json` couvre NuGet, les lockfiles, Docker et les actions Gitea ; aucune PR n'est fusionnée automatiquement. Vérifier la première exécution planifiée et les lockfiles générés avant de considérer l'automatisation opérationnelle.
|
||||
|
||||
## Vérification et limites
|
||||
|
||||
Le run #194 a validé la compilation, 1 965 tests, les archives, les deux images, la sécurité et le nettoyage. Le run #196 a validé la séparation des jobs d'images sur `runner-murin` et `runner-hugin`. La publication Docker Hub, la release signée et la protection de branche doivent encore être exercées sur l'instance. Le suivi des tâches et preuves est dans les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
|
||||
@@ -0,0 +1,32 @@
|
||||
# GPU device access and inference status
|
||||
|
||||
The default Agent image and install path use `CPUExecutionProvider` and do not
|
||||
require NVIDIA. The optional amd64 CUDA image is built from
|
||||
`docker/Dockerfile.agent.gpu` and published as `eltruncho/heimdall-agent-gpu`.
|
||||
Its immutable image digest is stored in the signed `agent-image-gpu.json`
|
||||
release asset. Central offers the NVIDIA install option when that signed
|
||||
release metadata is present. Existing Agent Compose files remain CPU-only.
|
||||
|
||||
ONNX Runtime 1.22 GPU uses CUDA 12.8 and cuDNN 9. The optional image pins NVIDIA
|
||||
`12.8.1-cudnn-runtime-ubuntu24.04` to amd64 manifest
|
||||
`sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9` and
|
||||
uses the separate locked GPU NuGet dependency graph. See the [ONNX Runtime CUDA
|
||||
provider compatibility table](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html)
|
||||
and [NVIDIA CUDA image tag](https://hub.docker.com/r/nvidia/cuda/tags?name=12.8.1-cudnn-runtime-ubuntu24.04).
|
||||
|
||||
The installer sets `Agent__InferenceExecutionProvider=CUDA` and requests all
|
||||
NVIDIA devices for that variant. CUDA initialization failure logs a warning
|
||||
and falls back to CPU. A physical GPU, compatible host driver and NVIDIA
|
||||
Container Toolkit are required; see the [NVIDIA Container Toolkit install guide](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html).
|
||||
|
||||
The `docker-compose.gpu-{nvidia,amd,intel}.yml` files remain inventory-only
|
||||
overlays. For local development, the CPU default is
|
||||
`docker/docker-compose.agent.dev.yml`; use
|
||||
`docker/docker-compose.agent.dev.gpu-nvidia.yml` with `--profile gpu-nvidia` to
|
||||
select the opt-in CUDA runtime, which fixes the Compose target to amd64 for its architecture-pinned NVIDIA base. Intel and AMD inventory hosts may need
|
||||
`VIDEO_GID` and `RENDER_GID` set to host group IDs that can access `/dev/dri`.
|
||||
|
||||
The image and Compose build acceptance and physical CUDA execution have not
|
||||
been run for this change. Local tests cover CPU fallback, CPU/GPU installer
|
||||
configuration and signed CPU/GPU release manifests; hardware execution remains
|
||||
open.
|
||||
@@ -74,7 +74,7 @@ public class RetentionCheckJob
|
||||
|
||||
_db.Recordings.RemoveRange(expired);
|
||||
|
||||
// 2. Supprimer les fichiers du storage (Alarik/S3)
|
||||
// 2. Supprimer les fichiers du storage (RustFS/S3)
|
||||
foreach (var recording in expired)
|
||||
{
|
||||
await storageProvider.DeleteAsync(recording.StoragePath, ct);
|
||||
@@ -103,7 +103,7 @@ public class S3CleanupJob
|
||||
{
|
||||
public async Task ExecuteAsync(CancellationToken ct)
|
||||
{
|
||||
// 1. Lister les fichiers dans Alarik (prefix recordings/)
|
||||
// 1. Lister les fichiers dans RustFS (prefix recordings/)
|
||||
var allFiles = await _storage.ListAsync("recordings/", ct);
|
||||
|
||||
// 2. Récupérer les chemins enregistrés en DB
|
||||
|
||||
+23
-14
@@ -1,5 +1,7 @@
|
||||
# Heimdall — Plan d'implémentation
|
||||
|
||||
> **Document historique (MVP — juillet 2026).** Les statuts de phases ci-dessous ne reflètent pas l’état courant du dépôt. Pour le suivi à jour, consulter les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
|
||||
|
||||
**Principe :** On implémente d'abord le **plus simple et le plus important**.
|
||||
La **vidéo live** arrive en dernier dans l'IHM.
|
||||
|
||||
@@ -19,9 +21,9 @@ La **vidéo live** arrive en dernier dans l'IHM.
|
||||
✅ Phase 10 : Camera Management API [FAIT]
|
||||
⏳ Phase 11 : Video Pipeline (FFmpeg) [EN ATTENTE - hardware requis]
|
||||
⏳ Phase 12 : AI Pipeline [EN ATTENTE - hardware requis]
|
||||
⏳ Phase 13 : Storage (Alarik/S3) [EN ATTENTE - v2]
|
||||
⏳ Phase 13 : Storage (RustFS/S3) [EN ATTENTE - v2]
|
||||
⏳ Phase 14 : SignalR Hubs [EN ATTENTE - v2]
|
||||
✅ Phase 15 : Hangfire Central [FAIT - heartbeat monitor]
|
||||
✅ Phase 15 : Hangfire Central [FAIT - surveillance heartbeat et failover]
|
||||
⏳ Phase 16 : Hangfire Agent (InMemory) [EN ATTENTE - v2]
|
||||
⏳ Phase 17 : Notifications [EN ATTENTE - v2]
|
||||
✅ Phase 18 : Blazor UI [FAIT - 13 pages]
|
||||
@@ -68,8 +70,9 @@ Heimdall/
|
||||
├── docker/
|
||||
│ ├── Dockerfile.central # Multi-stage ✅
|
||||
│ ├── Dockerfile.agent # Multi-stage ✅
|
||||
│ ├── docker-compose.yml # PostgreSQL + Alarik + Central + Agent + Workers ✅
|
||||
│ └── docker-compose.override.yml # Dev overrides ✅
|
||||
│ ├── docker-compose.yml # Central de développement + PostgreSQL
|
||||
│ ├── docker-compose.prod.yml # Central de production + PostgreSQL
|
||||
│ └── docker-compose.<service>.yml # Logiciels optionnels isolés
|
||||
├── docs/
|
||||
│ ├── MASTER_SPECIFICATION.md # Spec complète
|
||||
│ ├── implementation.md # ← ce fichier
|
||||
@@ -242,7 +245,7 @@ Interfaces, DTOs, validateurs.
|
||||
|
||||
| Service | Méthodes |
|
||||
|---------|----------|
|
||||
| `IAuthService` | Register, Login, Verify2fa, RefreshToken, RegisterAdmin |
|
||||
| `IAuthService` | BootstrapAdmin, Login, Verify2fa, RefreshToken, ChangePassword |
|
||||
| `ISiteService` | Create, GetById, List, Update, Delete, GenerateToken |
|
||||
| `IAgentService` | Register, Heartbeat, GetById, ListBySite |
|
||||
| `IUserService` | List, GetById, Create, Update, AssignRoles, AssignSites, ResetPassword, Lock, Unlock |
|
||||
@@ -282,11 +285,15 @@ Authentification AVANT d'exposer l'API.
|
||||
|
||||
| Méthode | Route | Auth | Status |
|
||||
|---|---|---|---|
|
||||
| `POST` | `/api/auth/register` | — | ✅ |
|
||||
| `GET` | `/api/auth/bootstrap-status` | — | ✅ |
|
||||
| `POST` | `/api/auth/bootstrap-admin` | — (first account only) | ✅ |
|
||||
| `POST` | `/api/auth/login` | — | ✅ |
|
||||
| `POST` | `/api/auth/2fa/verify` | — | ✅ |
|
||||
| `POST` | `/api/auth/refresh` | — | ✅ |
|
||||
| `POST` | `/api/auth/register-admin` | Test/Dev only | ✅ |
|
||||
| `POST` | `/api/auth/register` | Retired (404) | ✅ |
|
||||
| `POST` | `/api/auth/register-admin` | Retired (404) | ✅ |
|
||||
| `/api/users/*` | User creation and lifecycle | Admin.Users; surfaced in `/users` UI | ✅ |
|
||||
| `PUT` | `/api/roles/{name}/permissions` | Admin.Manage; surfaced in `/admin/claims` UI (Admin role fixed) | ✅ |
|
||||
|
||||
---
|
||||
|
||||
@@ -333,10 +340,12 @@ Le token d'enregistrement est :
|
||||
| API Key envoyée dans header Authorization | ✅ |
|
||||
| Détection GPU/CPU capabilities | ✅ |
|
||||
|
||||
### HeartbeatMonitor (Hangfire)
|
||||
### Surveillance heartbeat et failover (Hangfire)
|
||||
|
||||
- Job planifié toutes les minutes ✅
|
||||
- Marque les agents Offline après 90s sans heartbeat ✅
|
||||
- Vérification et failover planifiés toutes les minutes ✅
|
||||
- Le délai utilise l'intervalle global ou la surcharge de l'agent, avec deux intervalles et une marge d'ordonnanceur (minimum 90 s) ✅
|
||||
- Le job de failover effectue la transition Offline et réessaie la réaffectation des caméras actives des agents déjà Offline ✅
|
||||
- Les intervalles sont limités à 5–300 s, conformément à la plage appliquée par l'Agent ✅
|
||||
|
||||
---
|
||||
|
||||
@@ -371,7 +380,7 @@ Reporté après le MVP logiciel.
|
||||
|
||||
# Phase 11 — Video Pipeline (FFmpeg)
|
||||
# Phase 12 — AI Pipeline
|
||||
# Phase 13 — Storage (Alarik/S3)
|
||||
# Phase 13 — Storage (RustFS/S3)
|
||||
# Phase 14 — SignalR Hubs
|
||||
|
||||
🔴 **Nécessitent du hardware + dépendances natives.**
|
||||
@@ -464,7 +473,7 @@ Reportées en v2.
|
||||
|
||||
# Phase 21 — Application web installable (PWA)
|
||||
|
||||
Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et le [plan actualisé](audits/2026-10-20-plan-implementation.md).
|
||||
Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et les [issues Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues).
|
||||
|
||||
---
|
||||
|
||||
@@ -499,7 +508,7 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et le [plan actual
|
||||
- [ ] Serilog + Seq/GlitchTip
|
||||
- [ ] Métriques Prometheus
|
||||
- [ ] Backup PostgreSQL automatisé
|
||||
- [ ] Backup Alarik (S3 → S3)
|
||||
- [ ] Backup RustFS (S3 → S3)
|
||||
- [ ] Tests de charge (k6)
|
||||
- [ ] Security audit (pentest)
|
||||
|
||||
@@ -515,5 +524,5 @@ Le client natif a été retiré. Voir [l’audit PWA](pwa.md) et le [plan actual
|
||||
| Tests | 34 (13 domain + 16 integration + 5 placeholder) |
|
||||
| Build | 0 errors, 0 warnings |
|
||||
| Commits | 45 |
|
||||
| Conteneurs Docker | 6 (postgresql, alarik, alarik-console, central, workers, agent) |
|
||||
| Conteneurs Docker | 5 (postgresql, rustfs, central, workers, agent) |
|
||||
| Endpoints API | 30+ |
|
||||
@@ -0,0 +1,76 @@
|
||||
# Métriques Prometheus
|
||||
|
||||
Central et chaque Agent exposent les métriques .NET sur `/metrics`. Configurez
|
||||
Prometheus pour scraper le serveur et chaque Agent; l'endpoint n'exige pas
|
||||
d'authentification et doit rester accessible uniquement sur un réseau de
|
||||
supervision de confiance.
|
||||
|
||||
## Signaux santé des Agents et du Central
|
||||
|
||||
| Famille | Nom OpenTelemetry | Type | Signification |
|
||||
|---|---|---|---|
|
||||
| File de snapshots | `heimdall.ai.queue.depth` | Gauge | Nombre de snapshots en attente d'analyse |
|
||||
| Snapshots rejetés | `heimdall.ai.queue.dropped` | Counter | Total de snapshots rejetés lorsque la file Agent est pleine |
|
||||
| File d'inférence | `heimdall.ai.inference.queue.depth` | Gauge | Frames en attente dans la file d'inférence bornée |
|
||||
| Frames rejetées | `heimdall.ai.inference.queue.rejected` | Counter | Total de frames rejetées lorsque la file d'inférence est pleine |
|
||||
| Disque Agent | `heimdall.agent.disk.usage.percent` | Gauge | Pourcentage utilisé sur le système de fichiers de l'Agent; absent quand la plateforme ne fournit pas de mesure |
|
||||
| Configuration Central reçue | `heimdall.agent.central_configuration.received` | Gauge 0/1 | Passe à 1 après acceptation d'un snapshot complet Central valide, y compris un snapshot vide |
|
||||
| Âge file Hangfire | `heimdall.hangfire.jobs.oldest_enqueued.age` | Gauge, secondes | Âge maximal observé parmi les 100 premiers jobs de chaque file |
|
||||
| Âge traitement Hangfire | `heimdall.hangfire.jobs.oldest_processing.age` | Gauge, secondes | Âge maximal observé parmi les 100 premiers jobs en traitement |
|
||||
| Jobs Hangfire échoués | `heimdall.hangfire.jobs.failed` | Gauge | Nombre de jobs actuellement en état Failed selon l'API de monitoring Hangfire |
|
||||
| API de monitoring Hangfire | `heimdall.hangfire.monitoring.available` | Gauge 0/1 | Indique si le dernier relevé de l'API de monitoring a réussi |
|
||||
| Outbox notifications dues | `heimdall.notifications.outbox.pending_due` | Gauge | Livraisons Pending dont la prochaine tentative est due; les retries futurs sont exclus |
|
||||
| Âge outbox dû | `heimdall.notifications.outbox.oldest_pending_due.age` | Gauge, secondes | Durée depuis l'échéance de la livraison due la plus ancienne |
|
||||
| Baux outbox expirés | `heimdall.notifications.outbox.expired_leases` | Gauge | Livraisons toujours Processing dont le bail est expiré |
|
||||
| Échecs outbox terminaux | `heimdall.notifications.outbox.failed` | Gauge | Livraisons en état Failed terminal |
|
||||
| Lecture outbox | `heimdall.notifications.outbox.monitoring.available` | Gauge 0/1 | Indique si le dernier relevé EF Core a réussi |
|
||||
|
||||
Le nom Prometheus peut être normalisé par l'exporteur .NET (points remplacés
|
||||
par des underscores et les compteurs convertis en séries `_total`). Vérifiez
|
||||
les noms réellement exposés par `/metrics` avant de créer vos règles.
|
||||
|
||||
Ces signaux rendent les pertes et la capacité observables, mais Heimdall ne
|
||||
choisit pas de seuil d'alerte disque/file à votre place. Les seuils dépendent du
|
||||
matériel, du nombre de caméras et de la charge d'analyse; définissez-les dans
|
||||
votre système de supervision. Les files et compteurs de l'Agent appartiennent à
|
||||
son processus et repartent de zéro après un redémarrage. Les gauges Hangfire
|
||||
sont mesurées par le Central à partir de l'API de monitoring et de l'état
|
||||
persisté dans son stockage.
|
||||
|
||||
## Exemple de règles d'alerte Prometheus
|
||||
|
||||
Le fichier [`deploy/prometheus/heimdall-alerts.yml`](../deploy/prometheus/heimdall-alerts.yml)
|
||||
fournit des règles d'exemple pour les pertes de snapshots, les rejets
|
||||
d'inférence, les files durablement occupées, le disque, les jobs Hangfire et l’outbox de notifications. Importez-le dans
|
||||
`rule_files` de Prometheus ou dans votre gestionnaire de règles. Les règles
|
||||
Agent ciblent `job="heimdall-agent"`; les règles Hangfire et outbox
|
||||
ciblent `job="heimdall-central"`. Adaptez chacun de ces labels à votre
|
||||
configuration. La règle de configuration Agent exige aussi le label de scrape
|
||||
`central_config_expected="true"`; n'ajoutez ce label qu'aux Agents affectés à
|
||||
un site Central qui doit leur fournir une configuration. Vérifiez les noms
|
||||
exposés par `/metrics` après configuration de l'exporteur.
|
||||
|
||||
Le seuil disque de 90 %, la durée de backlog de 10 minutes et les seuils
|
||||
Hangfire de 15/30 minutes sont des valeurs d'exemple à adapter au matériel, au
|
||||
nombre de caméras, à la latence attendue et à la durée normale des tâches. Les
|
||||
alertes de notifications différencient les échecs terminaux, les lignes dues et
|
||||
les leases expirées; une livraison en backoff n'est pas considérée en retard
|
||||
avant `NextAttemptAt`.
|
||||
Les alertes de perte se déclenchent lorsqu'un compteur augmente pendant la
|
||||
fenêtre de cinq minutes, sans délai `for` qui pourrait masquer un rejet bref.
|
||||
Les règles de backlog signalent une file occupée pendant toute la fenêtre, ce
|
||||
qui indique une charge persistante sans prouver qu'un traitement est bloqué.
|
||||
Les métriques Hangfire utilisent son API de monitoring, inspectent au plus les
|
||||
100 premiers jobs de chaque file et les 100 premiers en traitement par relevé,
|
||||
et n'exposent ni identifiant ni contenu de job. L'âge observé peut donc manquer
|
||||
un job plus ancien au-delà de ces pages. Une métrique de disponibilité indique
|
||||
les échecs de lecture; lorsque sa valeur est 0, les autres valeurs Hangfire ne
|
||||
sont pas à interpréter comme un relevé valide. Les métriques de l'outbox
|
||||
proviennent d'agrégats EF Core exécutés par le Central. Aucun canal, destinataire,
|
||||
URL, identifiant de livraison ou type d'erreur n'est exposé comme valeur ou label.
|
||||
Si `heimdall.notifications.outbox.monitoring.available` vaut 0, les autres
|
||||
valeurs d'outbox ne représentent pas un relevé valide.
|
||||
La métrique de configuration reste à 1 tant que le snapshot reçu est conservé
|
||||
en mémoire; elle détecte l'absence de configuration Central valide au démarrage,
|
||||
pas une interruption SignalR transitoire. Un Agent autonome ou pas encore affecté
|
||||
à un site ne doit pas porter le label `central_config_expected="true"`.
|
||||
+34
-36
@@ -1,6 +1,6 @@
|
||||
# Audit PWA du serveur Heimdall et plan de réalisation
|
||||
|
||||
Date : 20 octobre 2026. Périmètre : `src/Heimdall.Web`, API, authentification, hubs, notifications et déploiement. L’application native a été retirée à la demande du propriétaire ; la cible mobile est désormais l’application web existante. Ce document décrit une évolution à implémenter, pas une PWA déjà livrée.
|
||||
Mis à jour le 24 octobre 2026. Périmètre : `src/Heimdall.Web`, API, authentification, hubs, notifications et déploiement. L’application native a été retirée à la demande du propriétaire ; la cible mobile est désormais l’application web existante. La PR #64 livre le manifeste, une icône SVG, l’enregistrement d’un service worker et une page hors connexion statique. Ce socle ne rend pas les écrans métier utilisables hors ligne : les composants Interactive Server dépendent toujours du serveur.
|
||||
|
||||
## Décision recommandée
|
||||
|
||||
@@ -25,19 +25,23 @@ Les critères d’installation varient selon navigateur ; manifeste et contexte
|
||||
| Élément | Constat dans le dépôt | Action |
|
||||
|---|---|---|
|
||||
| Rendu | App.razor impose InteractiveServer, prerender désactivé | Conserver en V1 ; écran hors ligne indépendant de Blazor |
|
||||
| Manifeste | Aucun `.webmanifest` ni lien rel=manifest | Créer et raccorder |
|
||||
| Icônes | Favicon uniquement | Icônes dédiées, variantes maskable et Apple touch |
|
||||
| Service worker | Aucun script/enregistrement trouvé | Ajouter stratégie limitée, versionnée et testée |
|
||||
| Hors connexion | Message d’erreur réseau dans App.razor | Ajouter page statique et états de reconnexion cohérents |
|
||||
| Reconnexion | Composant ReconnectModal et module JS existent, sans insertion trouvée dans App/Layouts | Raccorder explicitement et valider sa compatibilité au runtime |
|
||||
| Manifeste | `manifest.webmanifest` est lié dans `App.razor` ; nom, langue, couleurs, scope `/` et icône SVG sont définis | Valider l’installation sur les navigateurs ciblés ; ajouter des icônes raster si nécessaire |
|
||||
| Icônes | Favicon existant et icône SVG PWA déclarée `any maskable` | Vérifier le rendu réel ; fournir les variantes raster et Apple touch si requises par les plateformes ciblées |
|
||||
| Service worker | `service-worker.js` versionne le cache public et ne sert la page hors connexion qu’en échec de navigation GET même origine ; une nouvelle version attend désormais l’action de rechargement | Parcours local publié testé par E2E ; valider les appareils et le rollback sur un déploiement |
|
||||
| Hors connexion | `offline.html` est une page statique ; seuls cette page, le manifeste et l’icône sont mis en cache | Vérifier les scénarios réseau sur appareils ; aucune donnée métier ou réponse authentifiée n’est disponible hors ligne |
|
||||
| Reconnexion | L’indicateur Blazor d’erreur de circuit et ses actions de reprise/rechargement sont présents dans `App.razor` | Veille prolongée, changement réseau et reprise de session restent à valider sur appareils |
|
||||
| Web Push | Aucun PushSubscription, PushManager ou configuration VAPID | Construire backend et client |
|
||||
| Notifications | SignalR, email, ntfy et préférences existent | Réutiliser la sélection de destinataires, ajouter un canal navigateur |
|
||||
| Auth | Cookie + JWT + refresh maison | Corriger les défauts SEC-01/02/07/10 de l’audit général |
|
||||
| Ressources externes | Google Fonts et Font Awesome CDN dans App.razor | Héberger les ressources essentielles localement |
|
||||
| Layout mobile | MudDrawer responsive, quelques règles CSS mobiles | Auditer chaque écran et dialog sur petit écran |
|
||||
| Langue | `<html lang="en">` pour une UI largement française | Définir la langue réellement affichée |
|
||||
| Langue | `App.razor` indique `lang="fr"` ; le manifeste indique `fr-FR` | Vérifier les contenus localisés par utilisateur lorsque la localisation sera livrée |
|
||||
| HTTPS/proxy | HSTS présent ; redirection conditionnelle ; pas de UseForwardedHeaders observé | Documenter TLS externe et reconnaître uniquement les proxies de confiance |
|
||||
| Tests | bUnit et Playwright disponibles | Étendre aux scénarios PWA et appareils réels |
|
||||
| Tests | E2E Playwright vérifie le manifeste, les icônes publiques, le contenu exact du cache et la navigation hors ligne | Installation, mises à jour à deux onglets, rollback, mobile et HTTPS restent à valider sur appareils/déploiement |
|
||||
|
||||
### État du socle livré par la PR #64
|
||||
|
||||
Le déploiement actuel suppose que Heimdall est servi à la racine de l’origine (`/`) : le manifeste, le scope, l’enregistrement du worker et ses chemins sont absolus. Un hébergement sous un préfixe (`PathBase`) n’est pas pris en charge. Le worker ne met pas en cache le HTML de l’application, les réponses API, les hubs, les médias ou les données privées. Hors connexion, seule la page statique d’information fonctionne ; les interactions Blazor nécessitent une connexion au serveur. L’aide d’installation utilise `beforeinstallprompt` lorsqu’il est disponible et explique sinon le menu du navigateur, notamment « Sur l’écran d’accueil » sur Safari iOS. Les mises à jour du worker restent en attente jusqu’au choix explicite « Recharger ». L’installation réelle exige une origine HTTPS reconnue (sauf localhost de développement). La validation Android/iOS/desktop, la reprise mobile, le rollback sur déploiement et Web Push restent à faire.
|
||||
|
||||
Sources locales principales : [App.razor](../src/Heimdall.Web/Components/App.razor), [Program.cs](../src/Heimdall.Web/Program.cs), [MainLayout](../src/Heimdall.Web/Components/Layout/MainLayout.razor), [ReconnectModal](../src/Heimdall.Web/Components/Layout/ReconnectModal.razor), [AuthStateProvider](../src/Heimdall.Web/Services/HeimdallAuthStateProvider.cs), [NotificationService](../src/Heimdall.Infrastructure/Services/NotificationService.cs).
|
||||
|
||||
@@ -45,9 +49,9 @@ Sources locales principales : [App.razor](../src/Heimdall.Web/Components/App.raz
|
||||
|
||||
### PWA-01 — Identité et installation
|
||||
|
||||
Créer `wwwroot/manifest.webmanifest` avec une identité stable par instance : id, name, short_name, start_url, scope, display=standalone, couleurs, langue et icônes. Prévoir 192×192 et 512×512, une variante maskable et une Apple touch icon. Ne mettre ni token ni identifiant de session dans start_url. Décider explicitement si seul le déploiement à la racine est supporté en V1 ; sinon rendre base href, scope, registration et routes compatibles avec PathBase.
|
||||
Le manifeste, son lien dans `App.razor`, l’identité stable, la langue et l’icône SVG sont livrés par la PR #64. Le déploiement supporté est à la racine de l’origine (`/`) ; `PathBase` n’est pas pris en charge. Restent à valider l’installation sur les navigateurs cibles, les icônes raster/Apple si nécessaires et les deep links disponibles avant de les proposer comme raccourcis.
|
||||
|
||||
Raccorder manifeste et métadonnées dans App.razor, fournir une aide « installer » progressive : événement d’installation quand disponible, instructions propres au navigateur sinon. Un navigateur sans installation doit garder une interface utilisable. Vérifier les deep links `/events/...` réellement disponibles avant de les utiliser dans raccourcis et notifications.
|
||||
L’interface propose l’installation via l’événement natif quand le navigateur le fournit et donne des instructions de menu adaptées au navigateur sinon. Un navigateur sans installation garde une interface utilisable. Les tests E2E valident le manifeste et les ressources d’installation sans authentification ; l’installation effective exige des appareils et une origine HTTPS de déploiement.
|
||||
|
||||
### PWA-02 — HTTPS utilisable en auto-hébergement
|
||||
|
||||
@@ -57,28 +61,28 @@ Documenter DNS/certificat, accès LAN ou VPN, renouvellement, redirection HTTPS
|
||||
|
||||
### PWA-03 — Service worker borné et cache sûr
|
||||
|
||||
Ajouter un service worker servi à une URL stable, son module d’enregistrement et une page `offline.html` lisible sans circuit Blazor. Prévoir un cache versionné des seuls assets publics indispensables et un nettoyage des anciennes versions. Les phases install/activate et le contrôle des requêtes relèvent du [cycle de vie des service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
|
||||
La PR #64 livre le service worker à URL stable, son enregistrement et la page `offline.html`. Il garde un cache versionné limité à cette page, au manifeste et à l’icône, et supprime les anciens caches. Il ne met pas en cache les CSS, scripts, HTML applicatifs ni réponses métier. Les navigations GET même origine sont réseau d’abord avec page hors connexion en cas d’erreur réseau, sauf routes opérationnelles, API et techniques exclues. Les phases install/activate et le contrôle des requêtes relèvent du [cycle de vie des service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API).
|
||||
|
||||
Politique proposée pour V1 :
|
||||
Politique effectivement livrée et éléments restants :
|
||||
|
||||
| Requête | Stratégie |
|
||||
|---|---|
|
||||
| Manifeste/service-worker.js | Revalidation ; ne pas leur appliquer un cache immuable |
|
||||
| CSS/JS/fonts/icônes publics avec empreinte | Cache-first versionné/autorisé explicitement |
|
||||
| Navigation HTML | Réseau ; page offline statique uniquement en cas d’échec réseau |
|
||||
| Réponse 401/403/500 | Conserver le statut ; ne pas la transformer en succès hors ligne |
|
||||
| `/api/*`, `/_auth/*`, `/hubs/*`, `/_blazor*`, negotiate | Exclusion du cache ; fonctionnement réseau normal |
|
||||
| `/hangfire`, `/metrics`, health, documentation technique | Hors cache et hors fallback PWA |
|
||||
| Manifeste/service-worker.js | Le worker ne les intercepte pas ; appliquer une politique HTTP réévaluable au déploiement |
|
||||
| CSS/JS/fonts/icônes | Pas de cache par le service worker ; chargement HTTP normal |
|
||||
| Navigation HTML GET même origine | Réseau ; page offline statique uniquement sur erreur réseau, sans cache HTML |
|
||||
| Réponse HTTP 401/403/500 | Réponse serveur conservée ; `fetch` réussit au niveau transport et n’active pas le fallback |
|
||||
| `/api/*`, `/_auth/*`, `/hubs/*`, `/_blazor*` | Exclusion du fallback ; fonctionnement réseau normal |
|
||||
| `/hangfire`, `/metrics`, `/health*`, `/swagger`, `/openapi`, `/scalar`, `/docs` | Exclusion du fallback ; fonctionnement réseau normal |
|
||||
| Snapshots, visages, exports, vidéos | Aucun cache persistant personnalisé en V1 ; vérifier aussi les en-têtes HTTP |
|
||||
| POST/PUT/PATCH/DELETE | Ne pas mettre en file ni rejouer automatiquement en V1 |
|
||||
|
||||
Ne pas servir systématiquement la racine en fallback pour toutes les URLs : un appel API ne doit jamais recevoir une page HTML avec statut 200. Ne pas mettre en cache la page HTML personnalisée d’un utilisateur. Le worker ne doit pas prétendre que les écrans métier fonctionnent sans le serveur.
|
||||
Ne pas servir systématiquement `offline.html` pour toutes les navigations : une route opérationnelle, un endpoint ou une documentation technique ne doit pas recevoir une page HTML avec statut 200 à la place de sa réponse. Ne pas mettre en cache la page HTML personnalisée d’un utilisateur. Le worker ne doit pas prétendre que les écrans métier fonctionnent sans le serveur.
|
||||
|
||||
### PWA-04 — Mise à jour sans casser les circuits
|
||||
|
||||
Ajouter un numéro de version, un état « nouvelle version disponible » et une action de rechargement explicite. Éviter une activation forcée au milieu d’un formulaire ou d’une session live ; gérer les onglets multiples, les vieux caches et le déploiement d’une version serveur incompatible avec les assets déjà chargés. La validation doit porter sur le résultat de `dotnet publish`, pas uniquement sur le serveur de développement.
|
||||
Le cache est versionné et les anciennes versions sont nettoyées à l’activation. Une nouvelle version installée reste en attente ; l’interface annonce sa disponibilité et transmet `ACTIVATE_UPDATE` uniquement après le clic sur « Recharger », puis recharge à `controllerchange`. Cela évite le remplacement forcé au milieu d’un formulaire ou d’une session live. Les E2E vérifient le shell public et la réponse hors ligne ; les onglets multiples et le rollback d’un build publié restent à vérifier sur un navigateur de déploiement.
|
||||
|
||||
Établir un mécanisme de récupération si un mauvais worker est déployé : URL stable réévaluable, nouvelle version nettoyant les caches, procédure opérateur et test de rollback. Une mise à jour de l’application serveur et une mise à jour du cache navigateur sont deux cycles à coordonner.
|
||||
L’URL stable et le nettoyage des caches sont en place. Il reste à établir une procédure opérateur et tester le rollback d’un worker défectueux. Une mise à jour de l’application serveur et une mise à jour du cache navigateur sont deux cycles à coordonner.
|
||||
|
||||
### PWA-05 — Authentification et reprise mobile
|
||||
|
||||
@@ -118,29 +122,23 @@ Définir IndexedDB, schéma versionné, TTL/quota, clés par instance/utilisateu
|
||||
|
||||
Cette option doit être décidée séparément ; elle n’est pas un prérequis pour une première PWA installable.
|
||||
|
||||
## Fichiers et composants à créer ou modifier
|
||||
## État des fichiers et composants
|
||||
|
||||
| Surface | Travaux prévus |
|
||||
|---|---|
|
||||
| `Web/Components/App.razor` | Manifeste, métadonnées, langue, scripts et reconnexion |
|
||||
| `Web/wwwroot/manifest.webmanifest` | Nouveau manifeste |
|
||||
| `Web/wwwroot/icons/` | Nouveaux assets d’installation |
|
||||
| `Web/wwwroot/service-worker.js` | Nouveau worker avec cache/notification bornés |
|
||||
| `Web/wwwroot/offline.html`, `js/pwa.js` | Écran autonome, installation et mises à jour |
|
||||
| `Web/wwwroot/app.css`, layouts et pages | Safe areas, mobile, dialogs, navigation |
|
||||
| `Web/Program.cs` | Proxy de confiance, headers, configuration push et endpoints |
|
||||
| Domain/Application/Infrastructure | Souscriptions Web Push, migration, services et jobs |
|
||||
| Profil/Notifications | Préférences appareil, permissions et test d’envoi |
|
||||
| CI/Playwright/docker/docs | Publication, scénarios PWA, TLS et procédure de mise à jour |
|
||||
|
||||
Ces chemins sont des propositions de réalisation ; ils n’existent pas encore tous.
|
||||
| `Web/Components/App.razor`, manifeste SVG | Livrés ; aide d’installation, variantes raster/Apple et deep links restent à valider |
|
||||
| `Web/wwwroot/service-worker.js`, `js/pwa-register.js`, `offline.html` | Livrés ; exclusions opérationnelles, mise à jour et rollback sont suivis |
|
||||
| `Web/wwwroot/app.css`, layouts et pages | Ajustements tactiles, reconnexion et mobile restent à concevoir/valider |
|
||||
| `Web/Program.cs` | HTTPS/proxy de confiance à valider selon le déploiement |
|
||||
| Domain/Application/Infrastructure, profil/notifications | Souscriptions Web Push, migration, services, jobs et préférences à implémenter |
|
||||
| CI/Playwright/docker/docs | Tests publiés, appareils, TLS, procédure de mise à jour et rollback restent à faire |
|
||||
|
||||
## Plan priorisé et critères de réception
|
||||
|
||||
| Lot | Dépendances | Effort indicatif | Critère de réception |
|
||||
|---|---|---:|---|
|
||||
| P1 — Socle installable et HTTPS | Auth/isolation de l’audit général | 2–4 j | Installation et ouverture standalone, bonnes icônes, HTTPS réel |
|
||||
| P2 — Worker, assets et écran offline | P1 | 3–5 j | Redémarrage hors réseau affiche l’écran prévu ; API/auth/médias jamais en cache |
|
||||
| P1 — Valider le socle installable et HTTPS | Manifeste et worker livrés ; déploiement configuré | 2–4 j | Installation et ouverture standalone, icônes ciblées, HTTPS réel |
|
||||
| P2 — Valider worker et écran offline | Worker, cache public et écran offline livrés | 3–5 j | Hors réseau affiche l’écran prévu ; routes exclues et données métier jamais mises en cache ; update/rollback vérifiés |
|
||||
| P3 — Sessions, reprise et mobile | Correctifs auth + P2 | 4–7 j | Veille, réseau changé, circuit expiré, formulaires et logout validés |
|
||||
| P4 — Web Push et préférences | Pipeline notifications + P1/P2 | 5–8 j | Deux appareils d’un utilisateur, appli fermée, clic autorisé, révocation et endpoint expiré |
|
||||
| P5 — Publication et tests multi-plateforme | P1–P4 | 2–4 j | Mise à jour/rollback, caches, sécurité et tests réels documentés |
|
||||
|
||||
@@ -214,7 +214,7 @@ public class MonitoringHub : Hub
|
||||
|---|---|---|---|
|
||||
| `AgentStatusChanged` | `AgentStatusDto` | Groupe monitoring du site | Agent online/offline |
|
||||
| `CameraStatusChanged` | `CameraStatusDto` | Groupe monitoring du site | Caméra online/offline |
|
||||
| `StorageUsageUpdated` | `StorageDto` | Admin | Espace Alarik mis à jour |
|
||||
| `StorageUsageUpdated` | `StorageDto` | Admin | Espace RustFS mis à jour |
|
||||
| `GpuUsageUpdated` | `GpuDto` | Admin | Utilisation GPU agent (ONNX Runtime) |
|
||||
| `JobStatusChanged` | `JobDto` | Admin | Un job Hangfire échoue |
|
||||
| `SystemHealthChanged` | `HealthDto` | Admin | Health check global |
|
||||
|
||||
+6
-6
@@ -25,7 +25,7 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
|
||||
- Live vidéo : WebRTC P2P (SIPSorcery), latence < 500 ms
|
||||
- IA locale : ONNX Runtime (GPU sur agents équipés, mutualisable inter-sites) + Ollama (LLM résumés)
|
||||
- Espace utilisateur : Admin (global) + User (site-scope)
|
||||
- Stockage : Alarik/S3 centralisé
|
||||
- Stockage : RustFS/S3 centralisé
|
||||
- Temps réel : SignalR (5 hubs)
|
||||
- Jobs planifiés : Hangfire (Central PGSQL + Agent InMemory)
|
||||
- Stack : .NET 10, Blazor MudBlazor, PostgreSQL
|
||||
@@ -42,11 +42,11 @@ Heimdall is a modern self-hosted intelligent video surveillance platform.
|
||||
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
|
||||
│ │ API │ │ Web │ │ Workers │ │ Broker IA │ │
|
||||
│ │ REST + │ │ Blazor │ │ Hangfire │ │ Ollama │ │
|
||||
│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ Alarik │ │
|
||||
│ │ SignalR │ │ MudBlazor│ │ Jobs │ │ RustFS │ │
|
||||
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────────────────┘ │
|
||||
│ │ │ │ │
|
||||
│ └──────────────┴─────────────┘ │
|
||||
│ │ PostgreSQL / Alarik │
|
||||
│ │ PostgreSQL / RustFS │
|
||||
└─────────────────────────┼────────────────────────────────────────┘
|
||||
│
|
||||
HTTPS REST + SignalR (signaling)
|
||||
@@ -171,7 +171,7 @@ Voir `docs/hangfire-usage.md` pour le code complet de chaque job.
|
||||
|
||||
## Stockage & Rétention — `docs/hangfire-usage.md`
|
||||
|
||||
- Alarik (par défaut), S3-compatible (AWS S3, MinIO), Local (fallback)
|
||||
- RustFS (par défaut), S3-compatible (AWS S3, MinIO), Local (fallback)
|
||||
- L'Agent écrit les segments directement sur S3
|
||||
- Retention configurable par caméra (7-90 jours)
|
||||
- Hangfire purge les fichiers expirés
|
||||
@@ -204,7 +204,7 @@ services:
|
||||
heimdall-worker: # Hangfire jobs (PostgreSQL)
|
||||
heimdall-agent: # SIPSorcery + FFmpeg (InMemory Hangfire)
|
||||
postgresql: # Base de données
|
||||
alarik: # Stockage S3 (enregistrements)
|
||||
rustfs: # Stockage S3 (enregistrements)
|
||||
# IA lourde (détection, visages, LPR) : agents GPU ONNX Runtime — pas de service central
|
||||
ollama: # LLM local (résumés)
|
||||
mediamtx: # SFU WebRTC (optionnel, multi-user)
|
||||
@@ -236,7 +236,7 @@ Auto-détection GPU par l'Agent au démarrage (NVENC > QSV > VAAPI > CPU).
|
||||
- Serilog (structure logging)
|
||||
- OpenTelemetry ready
|
||||
- Sentry SDK compatible GlitchTip
|
||||
- Healthchecks (API, Agent, DB, Alarik, Broker IA, Ollama)
|
||||
- Healthchecks (API, Agent, DB, RustFS, Broker IA, Ollama)
|
||||
- Tests : xUnit + Shouldly + NSubstitute + bUnit + Testcontainers
|
||||
|
||||
---
|
||||
|
||||
+57
-7
@@ -226,19 +226,62 @@ Dashboard shows agent offline state
|
||||
│ │ │ Token: a1b2c3d4-... (caché après création)│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ Commande Docker à exécuter sur le site distant : │ │
|
||||
│ │ Installer l'Agent │ │
|
||||
│ │ Déployez le connecteur sur la machine du site. │ │
|
||||
│ │ Release signée disponible : vX.Y.Z │ │
|
||||
│ │ │ │
|
||||
│ │ Système d'exploitation │ │
|
||||
│ │ [🐧 Linux] [⊞ Windows] [🐳 Docker] │ │
|
||||
│ │ │ │
|
||||
│ │ Méthode │ │
|
||||
│ │ [Exécution] [Service systemd] │ │
|
||||
│ │ │ │
|
||||
│ │ Configuration (Docker avec image GPU disponible)│ │
|
||||
│ │ [ ] Utiliser l'inférence GPU NVIDIA │ │
|
||||
│ │ │ │
|
||||
│ │ Commandes │ │
|
||||
│ │ Installer │ │
|
||||
│ │ ┌──────────────────────────────────────────┐ │ │
|
||||
│ │ │ docker run -e HEIMDALL_CENTRAL_URL=... │ │ │
|
||||
│ │ │ -e HEIMDALL_SITE_TOKEN=... │ │ │
|
||||
│ │ │ heimdall/agent:latest │ │ │
|
||||
│ │ │ curl ... install-agent.sh ... [⧉]│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ Lancer │ │
|
||||
│ │ ┌──────────────────────────────────────────┐ │ │
|
||||
│ │ │ sudo systemctl start heimdall-agent [⧉]│ │ │
|
||||
│ │ └──────────────────────────────────────────┘ │ │
|
||||
│ │ │ │
|
||||
│ │ [Copier la commande] [× Révoquer le token] │ │
|
||||
│ │ [× Révoquer le token] │ │
|
||||
│ └──────────────────────────────────────────────────┘ │
|
||||
└──────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, `MudSnackbar` (copié)
|
||||
**Components** : `MudTabs`, `MudTable`, `MudChip`, `MudTextField`, `MudButton`, panneau installateur (`SiteInstallPanel`), commandes copiables avec `MudIconButton` et `MudTooltip`, `MudSnackbar` (copié)
|
||||
|
||||
### Parcours d'installation Agent
|
||||
|
||||
Le panneau suit le parcours de l'installateur Pangolin : choix de plateforme en tuiles, choix de méthode en tuiles, configuration optionnelle puis étapes de commandes. Les tuiles sont en trois colonnes sur écran large et s'empilent sur petit écran; les méthodes prennent toute la largeur disponible. La tuile sélectionnée garde un contour et un fond teinté de la couleur primaire.
|
||||
|
||||
```text
|
||||
Système d'exploitation
|
||||
[Linux] [Windows] [Docker]
|
||||
|
||||
Méthode
|
||||
[Exécution] [Service systemd]
|
||||
|
||||
Configuration (Docker uniquement si l'image GPU est publiée)
|
||||
[ ] Utiliser l'inférence GPU NVIDIA
|
||||
|
||||
Commandes
|
||||
Installer
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ commande/script [⧉]│
|
||||
└──────────────────────────────────────────────┘
|
||||
Lancer
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ commande de démarrage [⧉]│
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Docker Compose affiche le YAML comme une étape « Configuration », suivie des commandes pour démarrer et vérifier l'Agent. Chaque bloc a une copie intégrée en haut à droite; après copie, l'icône devient une coche. Les commandes d'installation restent masquées tant que la release signée correspondante n'est pas disponible. Docker exige aussi les métadonnées d'image vérifiées de la release, puis installe l'image publiée avec le tag `latest`; les remplacements déclenchés par Central restent vérifiés par digest signé. En cas d'indisponibilité, le panneau montre une alerte explicite à la place des commandes.
|
||||
|
||||
### États — Détail Site
|
||||
|
||||
@@ -477,7 +520,10 @@ Liste globale de tous les agents déployés sur l'ensemble des sites.
|
||||
**Auth** : `Admin.Users`
|
||||
|
||||
Tableau des utilisateurs avec création, modification, verrouillage,
|
||||
réinitialisation de mot de passe et assignment des rôles.
|
||||
réinitialisation de mot de passe et assignment des rôles. Le panneau d'accès caméra
|
||||
charge l'ensemble des accès directs, conserve les modifications en brouillon et les
|
||||
remplace en une opération atomique. Au-delà de 500 entrées, les remplacements et ajouts
|
||||
sont bloqués, mais les accès existants peuvent être révoqués un par un.
|
||||
|
||||
**Components** : `MudTable`, `MudDialog` (création/édition), `MudCheckBox` (rôles), pagination
|
||||
|
||||
@@ -579,6 +625,10 @@ Matrice complète des 15 permissions système avec coches par rôle
|
||||
Accessible depuis `MudBadge` dans la barre de navigation.
|
||||
Les événements arrivent en temps réel via SignalR.
|
||||
|
||||
### Source des releases Heimdall
|
||||
|
||||
Dans **Réglages**, l’administrateur saisit uniquement l’URL HTTPS publique de Forgejo. Heimdall affiche l’API `.../api/v1/repos/arnaud.dartois/Heimdall/releases/latest` calculée automatiquement en lecture seule. L’URL publique est éditable; le propriétaire, le dépôt et le chemin de release ne le sont pas. Le blocage « aucune release signée utilisable » reste affiché tant que l’API ne retourne pas une release avec clé, manifeste signé, signature et assets Agent.
|
||||
|
||||
### Configuration notifications
|
||||
|
||||
```text
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"sdk": {
|
||||
"version": "10.0.100",
|
||||
"rollForward": "latestFeature",
|
||||
"allowPrerelease": false
|
||||
}
|
||||
}
|
||||
@@ -26,8 +26,13 @@ CONFIG_DIR="${HOME}/.config/heima-manager"
|
||||
LOG_DIR="${CONFIG_DIR}/logs"
|
||||
CLINE_DIR="${HOME}/.config/cline"
|
||||
KANBAN_DIR="${HOME}/.config/kanban"
|
||||
SKILL_SERVER="${SKILL_SERVER_URL:-https://skill.tordais.cc}"
|
||||
MEMORIZER_URL="${MEMORIZER_URL:-https://memorizer.tordais.cc}"
|
||||
SKILL_SERVER="${SKILL_SERVER_URL:-}"
|
||||
MEMORIZER_URL="${MEMORIZER_URL:-}"
|
||||
|
||||
if [[ -z "$SKILL_SERVER" || -z "$MEMORIZER_URL" ]]; then
|
||||
err "SKILL_SERVER_URL and MEMORIZER_URL must be set to their API origins."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$HEIMA_DIR" "$CONFIG_DIR" "$LOG_DIR" "$CLINE_DIR" "$KANBAN_DIR"
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run a native agent and roll back a release that fails its startup probe."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
root = Path(os.environ["Agent__UpdateInstallRoot"]).resolve()
|
||||
releases = root / "releases"
|
||||
current = root / "current"
|
||||
pending = root / "pending-update.json"
|
||||
dotnet = os.environ.get("HEIMDALL_DOTNET", "/usr/bin/dotnet")
|
||||
process = None
|
||||
|
||||
|
||||
def terminate(_signum, _frame):
|
||||
if process is not None and process.poll() is None:
|
||||
process.terminate()
|
||||
|
||||
|
||||
signal.signal(signal.SIGTERM, terminate)
|
||||
signal.signal(signal.SIGINT, terminate)
|
||||
|
||||
|
||||
def within_releases(path):
|
||||
resolved = Path(path).resolve()
|
||||
return resolved != releases and releases in resolved.parents
|
||||
|
||||
|
||||
def restore(previous):
|
||||
if not within_releases(previous):
|
||||
raise RuntimeError("Rollback target is outside the release root")
|
||||
replacement = root / (".rollback-" + str(os.getpid()))
|
||||
replacement.symlink_to(previous, target_is_directory=True)
|
||||
os.replace(replacement, current)
|
||||
pending.unlink(missing_ok=True)
|
||||
|
||||
|
||||
try:
|
||||
marker = json.loads(pending.read_text()) if pending.exists() else None
|
||||
if marker is not None and (not within_releases(marker["previous"]) or
|
||||
not within_releases(current)):
|
||||
raise RuntimeError("Invalid pending update marker")
|
||||
process = subprocess.Popen([dotnet, str(current / "Heimdall.Agent.dll")], cwd=current)
|
||||
if marker is not None:
|
||||
wanted = str(marker["version"]).removeprefix("v")
|
||||
deadline = time.monotonic() + 180
|
||||
healthy_since = None
|
||||
healthy = False
|
||||
while time.monotonic() < deadline and process.poll() is None:
|
||||
try:
|
||||
with urllib.request.urlopen("http://127.0.0.1:8081/api/version", timeout=3) as response:
|
||||
info = json.load(response)
|
||||
if str(info.get("version", "")).split("+")[0].removeprefix("v") == wanted:
|
||||
healthy_since = healthy_since or time.monotonic()
|
||||
if time.monotonic() - healthy_since >= 60:
|
||||
healthy = True
|
||||
break
|
||||
else:
|
||||
healthy_since = None
|
||||
except (urllib.error.URLError, TimeoutError, ValueError):
|
||||
healthy_since = None
|
||||
time.sleep(2)
|
||||
if not healthy:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
restore(marker["previous"])
|
||||
raise RuntimeError("Updated agent failed startup; previous release restored")
|
||||
pending.unlink(missing_ok=True)
|
||||
sys.exit(process.wait())
|
||||
except Exception as error:
|
||||
print(f"Agent supervisor: {error}", file=sys.stderr)
|
||||
sys.exit(75)
|
||||
@@ -0,0 +1,237 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][ValidateRange(1, 2147483647)][int] $AgentPid,
|
||||
[Parameter(Mandatory = $true)][string] $InstallRoot,
|
||||
[Parameter(Mandatory = $true)][string] $ArchivePath,
|
||||
[Parameter(Mandatory = $true)][string] $Version,
|
||||
[Parameter(Mandatory = $true)][ValidatePattern('^[A-Fa-f0-9]{64}$')][string] $ExpectedSha256,
|
||||
[Parameter(Mandatory = $true)][string] $DotnetPath,
|
||||
[string] $ServiceName,
|
||||
[string] $HealthUrl = 'http://127.0.0.1:8081/api/version'
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
$StartupTimeout = [TimeSpan]::FromSeconds(180)
|
||||
$StablePeriod = [TimeSpan]::FromSeconds(60)
|
||||
|
||||
function Get-Sha256([string] $Path) {
|
||||
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
}
|
||||
|
||||
function Assert-SafeArchive([string] $Path) {
|
||||
if ((Get-Item -LiteralPath $Path).Length -gt 2GB) { throw 'Update archive exceeds 2 GiB.' }
|
||||
$entries = & tar.exe -tzf $Path
|
||||
if ($LASTEXITCODE -ne 0 -or $entries.Count -gt 20000) { throw 'Update archive cannot be inspected or has too many entries.' }
|
||||
foreach ($entry in $entries) {
|
||||
$name = ([string]$entry).Replace('\', '/')
|
||||
if ([string]::IsNullOrWhiteSpace($name) -or $name.StartsWith('/') -or
|
||||
$name -match '^[A-Za-z]:' -or ($name -split '/') -contains '..') {
|
||||
throw 'Update archive contains an unsafe path.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Start-Agent([string] $Directory, [string] $RuntimePath) {
|
||||
$assembly = Join-Path $Directory 'Heimdall.Agent.dll'
|
||||
if (-not (Test-Path -LiteralPath $assembly -PathType Leaf)) { throw 'Release directory has no Agent assembly.' }
|
||||
$quotedAssembly = '"' + $assembly.Replace('"', '\"') + '"'
|
||||
return Start-Process -FilePath $RuntimePath -ArgumentList $quotedAssembly -WorkingDirectory $Directory -WindowStyle Hidden -PassThru
|
||||
}
|
||||
|
||||
function Stop-AgentProcess($Process) {
|
||||
if ($null -ne $Process -and -not $Process.HasExited) {
|
||||
Stop-Process -Id $Process.Id -Force -ErrorAction SilentlyContinue
|
||||
try { $Process.WaitForExit(10000) } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-ForHealthyVersion($Process, [string] $ExpectedVersion) {
|
||||
$deadline = [DateTime]::UtcNow + $StartupTimeout
|
||||
$healthySince = $null
|
||||
while ([DateTime]::UtcNow -lt $deadline) {
|
||||
if ($Process.HasExited) { return $false }
|
||||
try {
|
||||
$health = Invoke-RestMethod -Method Get -Uri $HealthUrl -TimeoutSec 3
|
||||
$actual = ([string]$health.version).Split('+')[0].TrimStart('v', 'V')
|
||||
$wanted = $ExpectedVersion.Split('+')[0].TrimStart('v', 'V')
|
||||
if ($actual -eq $wanted) {
|
||||
if ($null -eq $healthySince) { $healthySince = [DateTime]::UtcNow }
|
||||
if ([DateTime]::UtcNow - $healthySince -ge $StablePeriod) { return $true }
|
||||
}
|
||||
else { $healthySince = $null }
|
||||
}
|
||||
catch { $healthySince = $null }
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
function Wait-ForHealthyService([string] $Name, [string] $ExpectedVersion) {
|
||||
$deadline = [DateTime]::UtcNow + $StartupTimeout
|
||||
$healthySince = $null
|
||||
while ([DateTime]::UtcNow -lt $deadline) {
|
||||
$service = Get-Service -Name $Name -ErrorAction SilentlyContinue
|
||||
if ($null -eq $service -or $service.Status.ToString() -ne 'Running') {
|
||||
$healthySince = $null
|
||||
Start-Sleep -Seconds 2
|
||||
continue
|
||||
}
|
||||
try {
|
||||
$health = Invoke-RestMethod -Method Get -Uri $HealthUrl -TimeoutSec 3
|
||||
$actual = ([string]$health.version).Split('+')[0].TrimStart('v', 'V')
|
||||
$wanted = if ($ExpectedVersion) { $ExpectedVersion.Split('+')[0].TrimStart('v', 'V') } else { $null }
|
||||
if (-not $wanted -or $actual -eq $wanted) {
|
||||
if ($null -eq $healthySince) { $healthySince = [DateTime]::UtcNow }
|
||||
if ([DateTime]::UtcNow - $healthySince -ge $StablePeriod) { return $true }
|
||||
}
|
||||
else { $healthySince = $null }
|
||||
}
|
||||
catch { $healthySince = $null }
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
return $false
|
||||
}
|
||||
|
||||
$root = [IO.Path]::GetFullPath($InstallRoot).TrimEnd('\')
|
||||
$releases = Join-Path $root 'releases'
|
||||
$current = Join-Path $root 'current'
|
||||
$sourceArchive = [IO.Path]::GetFullPath($ArchivePath)
|
||||
$versionLeaf = $Version.TrimStart('v', 'V')
|
||||
if ($versionLeaf -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$') { throw 'Invalid update version.' }
|
||||
if (-not (Test-Path -LiteralPath $current -PathType Container)) { throw 'Managed current Agent directory is missing.' }
|
||||
if ((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) {
|
||||
throw 'The current Agent directory cannot be a reparse point.'
|
||||
}
|
||||
if ([IO.Path]::IsPathRooted($DotnetPath) -and -not (Test-Path -LiteralPath $DotnetPath -PathType Leaf)) {
|
||||
throw 'The configured .NET host was not found.'
|
||||
}
|
||||
New-Item -ItemType Directory -Path $releases -Force | Out-Null
|
||||
if (-not (Test-Path -LiteralPath $sourceArchive -PathType Leaf)) { throw 'Update archive is missing.' }
|
||||
$archive = Join-Path $releases ('.update-' + [Guid]::NewGuid().ToString('N') + '.tar.gz')
|
||||
Copy-Item -LiteralPath $sourceArchive -Destination $archive
|
||||
if ((Get-Sha256 $archive) -ine $ExpectedSha256) {
|
||||
Remove-Item -LiteralPath $archive -Force
|
||||
throw 'Update archive SHA-256 verification failed.'
|
||||
}
|
||||
try { Assert-SafeArchive $archive }
|
||||
catch {
|
||||
Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue
|
||||
throw
|
||||
}
|
||||
|
||||
# Wait until the old Agent has completely left its working directory before replacing files.
|
||||
try {
|
||||
$old = Get-Process -Id $AgentPid -ErrorAction Stop
|
||||
$old.WaitForExit(180000) | Out-Null
|
||||
if (-not $old.HasExited) { throw 'Previous Agent process did not stop within 180 seconds.' }
|
||||
}
|
||||
catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
|
||||
# The process may have exited between the helper launch and this lookup.
|
||||
}
|
||||
catch {
|
||||
Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue
|
||||
throw
|
||||
}
|
||||
|
||||
if ($ServiceName) {
|
||||
$serviceDeadline = [DateTime]::UtcNow.AddSeconds(30)
|
||||
do {
|
||||
$service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
|
||||
if ($null -eq $service -or $service.Status.ToString() -eq 'Stopped') { break }
|
||||
Start-Sleep -Seconds 1
|
||||
} while ([DateTime]::UtcNow -lt $serviceDeadline)
|
||||
if ($service -and $service.Status.ToString() -ne 'Stopped') {
|
||||
Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue
|
||||
throw "Windows Service '$ServiceName' did not stop after its Agent process exited."
|
||||
}
|
||||
}
|
||||
|
||||
$stage = Join-Path $releases ('.staging-' + [Guid]::NewGuid().ToString('N'))
|
||||
$previous = Join-Path $releases ('.previous-' + [Guid]::NewGuid().ToString('N'))
|
||||
$failed = Join-Path $releases ('.failed-' + [Guid]::NewGuid().ToString('N'))
|
||||
$versionRoot = Join-Path $releases $versionLeaf
|
||||
New-Item -ItemType Directory -Path $stage | Out-Null
|
||||
$newProcess = $null
|
||||
$swapped = $false
|
||||
|
||||
try {
|
||||
& tar.exe -xzf $archive -C $stage
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath (Join-Path $stage 'Heimdall.Agent.dll') -PathType Leaf)) {
|
||||
throw 'Update archive extraction failed.'
|
||||
}
|
||||
if (Test-Path -LiteralPath $versionRoot) { throw "Release $versionLeaf is already present." }
|
||||
Move-Item -LiteralPath $stage -Destination $versionRoot
|
||||
|
||||
# Directory moves stay on the same volume. Keep the old tree until the new process passes its startup probe.
|
||||
Move-Item -LiteralPath $current -Destination $previous
|
||||
try {
|
||||
Copy-Item -LiteralPath $versionRoot -Destination $current -Recurse
|
||||
$swapped = $true
|
||||
}
|
||||
catch {
|
||||
if (Test-Path -LiteralPath $current -PathType Container) {
|
||||
Remove-Item -LiteralPath $current -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Move-Item -LiteralPath $previous -Destination $current
|
||||
throw
|
||||
}
|
||||
|
||||
if ($ServiceName) {
|
||||
Start-Service -Name $ServiceName
|
||||
if (-not (Wait-ForHealthyService $ServiceName $Version)) {
|
||||
throw 'Updated Windows Service failed its startup and 60-second stability checks.'
|
||||
}
|
||||
}
|
||||
else {
|
||||
$newProcess = Start-Agent $current $DotnetPath
|
||||
if (-not (Wait-ForHealthyVersion $newProcess $Version)) {
|
||||
throw 'Updated Agent failed its startup and 60-second stability checks.'
|
||||
}
|
||||
}
|
||||
|
||||
Remove-Item -LiteralPath $previous -Recurse -Force
|
||||
Write-Output "Agent update to $Version passed startup verification."
|
||||
if (-not $ServiceName) {
|
||||
# Keep this supervisor alive with the launched console Agent.
|
||||
$newProcess.WaitForExit()
|
||||
}
|
||||
}
|
||||
catch {
|
||||
$failure = $_
|
||||
if ($ServiceName) { Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue }
|
||||
else { Stop-AgentProcess $newProcess }
|
||||
if ($swapped -and (Test-Path -LiteralPath $current -PathType Container)) {
|
||||
Move-Item -LiteralPath $current -Destination $failed
|
||||
}
|
||||
if (Test-Path -LiteralPath $previous -PathType Container) {
|
||||
Move-Item -LiteralPath $previous -Destination $current
|
||||
try {
|
||||
if ($ServiceName) {
|
||||
Start-Service -Name $ServiceName
|
||||
if (-not (Wait-ForHealthyService $ServiceName $null)) { throw 'Restored service did not pass its health check.' }
|
||||
}
|
||||
else {
|
||||
$rollbackProcess = Start-Agent $current $DotnetPath
|
||||
$rollbackProcess.WaitForExit()
|
||||
}
|
||||
Write-Warning 'The previous Agent release was restored and restarted.'
|
||||
}
|
||||
catch { Write-Error "Rollback restart failed: $($_.Exception.Message)" }
|
||||
}
|
||||
if (Test-Path -LiteralPath $versionRoot -PathType Container) {
|
||||
Remove-Item -LiteralPath $versionRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
throw $failure
|
||||
}
|
||||
finally {
|
||||
if (Test-Path -LiteralPath $stage -PathType Container) {
|
||||
Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if (Test-Path -LiteralPath $failed -PathType Container) {
|
||||
Remove-Item -LiteralPath $failed -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if (Test-Path -LiteralPath $archive -PathType Leaf) {
|
||||
Remove-Item -LiteralPath $archive -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string] $CentralUrl,
|
||||
[Parameter(Mandatory = $true)][string] $SiteToken,
|
||||
[Parameter(Mandatory = $true)][string] $AgentName,
|
||||
[string] $InstallDirectory = (Join-Path $env:LOCALAPPDATA 'Heimdall\Agent'),
|
||||
[switch] $InstallAsService,
|
||||
[switch] $InstallOnly,
|
||||
[string] $ServiceName = 'HeimdallAgent',
|
||||
[switch] $SkipRuntimeInstall
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
|
||||
function Get-Sha256([string] $Path) {
|
||||
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
}
|
||||
|
||||
function Assert-HttpsUrl([string] $Value, [string] $Description) {
|
||||
$uri = [Uri]::new($Value)
|
||||
if ($uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Fragment) {
|
||||
throw "$Description must be an HTTPS URL without credentials or fragment."
|
||||
}
|
||||
return $uri
|
||||
}
|
||||
|
||||
function Convert-DerSignatureToP1363([byte[]] $Signature) {
|
||||
if ($Signature.Length -lt 8 -or $Signature[0] -ne 0x30) { throw 'Invalid ECDSA signature encoding.' }
|
||||
$offset = 2
|
||||
if ($Signature[$offset] -ne 0x02) { throw 'Invalid ECDSA signature encoding.' }
|
||||
$rLength = [int]$Signature[$offset + 1]
|
||||
$offset += 2
|
||||
if ($rLength -lt 1 -or $offset + $rLength + 2 -gt $Signature.Length) { throw 'Invalid ECDSA signature encoding.' }
|
||||
[byte[]]$r = $Signature[$offset..($offset + $rLength - 1)]
|
||||
$offset += $rLength
|
||||
if ($Signature[$offset] -ne 0x02) { throw 'Invalid ECDSA signature encoding.' }
|
||||
$sLength = [int]$Signature[$offset + 1]
|
||||
$offset += 2
|
||||
if ($sLength -lt 1 -or $offset + $sLength -ne $Signature.Length) { throw 'Invalid ECDSA signature encoding.' }
|
||||
[byte[]]$s = $Signature[$offset..($offset + $sLength - 1)]
|
||||
while ($r.Length -gt 1 -and $r[0] -eq 0) { $r = $r[1..($r.Length - 1)] }
|
||||
while ($s.Length -gt 1 -and $s[0] -eq 0) { $s = $s[1..($s.Length - 1)] }
|
||||
if ($r.Length -gt 32 -or $s.Length -gt 32) { throw 'ECDSA signature is not P-256.' }
|
||||
$fixed = New-Object byte[] 64
|
||||
[Array]::Copy($r, 0, $fixed, 32 - $r.Length, $r.Length)
|
||||
[Array]::Copy($s, 0, $fixed, 64 - $s.Length, $s.Length)
|
||||
return ,$fixed
|
||||
}
|
||||
|
||||
function Test-EcdsaP256Signature([byte[]] $Data, [byte[]] $Signature, [string] $PublicKeyPem) {
|
||||
# Windows PowerShell 5 uses .NET Framework, which lacks ImportFromPem. Parse the
|
||||
# fixed P-256 SubjectPublicKeyInfo emitted by OpenSSL and import a CNG public blob.
|
||||
$body = ($PublicKeyPem -replace '-----BEGIN PUBLIC KEY-----|-----END PUBLIC KEY-----|\s', '')
|
||||
$spki = [Convert]::FromBase64String($body)
|
||||
$prefix = [byte[]](0x30,0x59,0x30,0x13,0x06,0x07,0x2a,0x86,0x48,0xce,0x3d,0x02,0x01,
|
||||
0x06,0x08,0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07,0x03,0x42,0x00,0x04)
|
||||
if ($spki.Length -ne 91) { throw 'The release public key is not a valid ECDSA P-256 public key.' }
|
||||
for ($i = 0; $i -lt $prefix.Length; $i++) {
|
||||
if ($spki[$i] -ne $prefix[$i]) { throw 'The release public key is not ECDSA P-256.' }
|
||||
}
|
||||
|
||||
$blob = New-Object byte[] 72
|
||||
[BitConverter]::GetBytes([UInt32]0x31534345).CopyTo($blob, 0) # BCRYPT_ECDSA_PUBLIC_P256_MAGIC (ECS1)
|
||||
[BitConverter]::GetBytes([UInt32]32).CopyTo($blob, 4)
|
||||
[Array]::Copy($spki, 27, $blob, 8, 64)
|
||||
$key = [Security.Cryptography.CngKey]::Import($blob, [Security.Cryptography.CngKeyBlobFormat]::EccPublicBlob)
|
||||
$ecdsa = New-Object -TypeName Security.Cryptography.ECDsaCng -ArgumentList $key
|
||||
try {
|
||||
$fixedSignature = Convert-DerSignatureToP1363 $Signature
|
||||
return $ecdsa.VerifyData($Data, $fixedSignature, [Security.Cryptography.HashAlgorithmName]::SHA256)
|
||||
}
|
||||
finally {
|
||||
$ecdsa.Dispose()
|
||||
$key.Dispose()
|
||||
}
|
||||
}
|
||||
|
||||
$central = Assert-HttpsUrl $CentralUrl 'Central URL'
|
||||
$CentralUrl = $central.AbsoluteUri.TrimEnd('/')
|
||||
if ([string]::IsNullOrWhiteSpace($SiteToken)) { throw 'SiteToken is required.' }
|
||||
if ([string]::IsNullOrWhiteSpace($AgentName)) { throw 'AgentName is required.' }
|
||||
if ($InstallAsService) {
|
||||
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
throw 'Windows Service installation requires an elevated PowerShell session (Run as Administrator).'
|
||||
}
|
||||
if ($ServiceName -notmatch '^[A-Za-z0-9_.-]{1,80}$') { throw 'ServiceName contains unsupported characters.' }
|
||||
if (-not $PSBoundParameters.ContainsKey('InstallDirectory')) {
|
||||
$slug = ($AgentName.ToLowerInvariant() -replace '[^a-z0-9]+', '-').Trim('-')
|
||||
if (-not $slug) { $slug = 'site' }
|
||||
$InstallDirectory = Join-Path $env:ProgramData "Heimdall\Agent-$slug"
|
||||
}
|
||||
}
|
||||
if (-not [Environment]::Is64BitOperatingSystem -or $env:PROCESSOR_ARCHITECTURE -notin @('AMD64', 'ARM64')) {
|
||||
throw 'This native installer currently supports 64-bit Windows only.'
|
||||
}
|
||||
|
||||
$platform = 'win-x64'
|
||||
$tempRoot = Join-Path ([IO.Path]::GetTempPath()) ('heimdall-agent-' + [Guid]::NewGuid().ToString('N'))
|
||||
$releaseRoot = [IO.Path]::GetFullPath($InstallDirectory)
|
||||
$releasesRoot = Join-Path $releaseRoot 'releases'
|
||||
$releasePath = Join-Path $releaseRoot 'current'
|
||||
if (Test-Path -LiteralPath $releasePath) {
|
||||
throw 'A Heimdall Agent is already installed here. Use its automatic updater or choose another InstallDirectory.'
|
||||
}
|
||||
if ($InstallAsService -and (Get-Service -Name $ServiceName -ErrorAction SilentlyContinue)) {
|
||||
throw "Windows Service '$ServiceName' already exists. Choose another ServiceName or uninstall the existing service first."
|
||||
}
|
||||
New-Item -ItemType Directory -Path $tempRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $releaseRoot -Force | Out-Null
|
||||
New-Item -ItemType Directory -Path $releasesRoot -Force | Out-Null
|
||||
$stage = $null
|
||||
$versionRoot = $null
|
||||
|
||||
try {
|
||||
$release = Invoke-RestMethod -Method Get -Uri "$CentralUrl/api/updates/latest" -TimeoutSec 30
|
||||
if (-not $release.updatePublicKeyPem) { throw 'Central did not provide the signed release public key.' }
|
||||
if (-not $release.signedManifest -or -not $release.manifestSignature) { throw 'The release has no signed manifest.' }
|
||||
|
||||
$manifestBytes = [Convert]::FromBase64String([string]$release.signedManifest)
|
||||
$signatureBytes = [Convert]::FromBase64String([string]$release.manifestSignature)
|
||||
$manifestJson = [Text.Encoding]::UTF8.GetString($manifestBytes)
|
||||
$manifest = $manifestJson | ConvertFrom-Json
|
||||
if ([string]$manifest.version -ne [string]$release.version) { throw 'Release version differs from its signed manifest.' }
|
||||
|
||||
if (-not (Test-EcdsaP256Signature $manifestBytes $signatureBytes ([string]$release.updatePublicKeyPem))) {
|
||||
throw 'Release signature verification failed.'
|
||||
}
|
||||
|
||||
$assetPlatform = if ($manifest.assets.PSObject.Properties.Name -contains $platform) { $platform }
|
||||
elseif ($manifest.assets.PSObject.Properties.Name -contains 'portable') { 'portable' }
|
||||
else { throw "The signed release has no archive for $platform or portable .NET." }
|
||||
$expectedHash = [string]$manifest.assets.$assetPlatform
|
||||
if ($expectedHash -notmatch '^[A-Fa-f0-9]{64}$') { throw 'The signed archive digest is invalid.' }
|
||||
$asset = $release.assets.$assetPlatform
|
||||
if (-not $asset -or -not $asset.url -or -not $asset.sha256) { throw 'Central did not provide the signed Agent archive.' }
|
||||
$assetUri = Assert-HttpsUrl ([string]$asset.url) 'Agent archive URL'
|
||||
if ([string]$asset.sha256 -ine $expectedHash) { throw 'Release archive digest differs from the signed manifest.' }
|
||||
|
||||
$archivePath = Join-Path $tempRoot 'agent.tar.gz'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $assetUri.AbsoluteUri -OutFile $archivePath -TimeoutSec 600
|
||||
if ((Get-Sha256 $archivePath) -ine $expectedHash) { throw 'Downloaded Agent archive SHA-256 does not match the signed manifest.' }
|
||||
|
||||
$supervisorPath = Join-Path $releaseRoot 'agent-update-supervisor.ps1'
|
||||
$supervisorTemp = Join-Path $tempRoot 'agent-update-supervisor.ps1'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri "$CentralUrl/install/agent-update-supervisor.ps1" -OutFile $supervisorTemp -TimeoutSec 30
|
||||
if (-not (Test-Path -LiteralPath $supervisorTemp -PathType Leaf)) { throw 'Windows update supervisor download failed.' }
|
||||
|
||||
$dotnet = Get-Command dotnet -ErrorAction SilentlyContinue
|
||||
$runtimeInfo = if ($dotnet) { & dotnet --list-runtimes } else { @() }
|
||||
$runtimeRoot = Join-Path $releaseRoot 'runtime'
|
||||
if (-not ($runtimeInfo -match 'Microsoft.AspNetCore.App 10\.')) {
|
||||
if ($SkipRuntimeInstall) { throw '.NET 10 ASP.NET Core Runtime is required but not installed.' }
|
||||
$bootstrap = Join-Path $tempRoot 'dotnet-install.ps1'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri 'https://dot.net/v1/dotnet-install.ps1' -OutFile $bootstrap -TimeoutSec 30
|
||||
Unblock-File -LiteralPath $bootstrap
|
||||
& $bootstrap -Runtime aspnetcore -Channel '10.0' -InstallDir $runtimeRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw '.NET 10 ASP.NET Core Runtime installation failed.' }
|
||||
$env:PATH = "$runtimeRoot;$env:PATH"
|
||||
$env:DOTNET_ROOT = $runtimeRoot
|
||||
}
|
||||
$dotnetInfo = & dotnet --list-runtimes
|
||||
if (-not ($dotnetInfo -match 'Microsoft.AspNetCore.App 10\.')) {
|
||||
throw 'The Agent requires the .NET 10 ASP.NET Core Runtime. Install it and run this installer again.'
|
||||
}
|
||||
|
||||
if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
|
||||
$winget = Get-Command winget -ErrorAction SilentlyContinue
|
||||
if (-not $winget) { throw 'FFmpeg is required for camera capture. Install FFmpeg and add it to PATH, then run this command again.' }
|
||||
$answer = Read-Host 'FFmpeg is required for camera capture. Install it now with WinGet? [Y/n]'
|
||||
if ($answer -and $answer -notmatch '^(y|yes)$') { throw 'FFmpeg installation was declined.' }
|
||||
if ($InstallAsService) {
|
||||
& winget install --exact --id Gyan.FFmpeg --scope machine --accept-package-agreements --accept-source-agreements
|
||||
}
|
||||
else {
|
||||
& winget install --exact --id Gyan.FFmpeg --accept-package-agreements --accept-source-agreements
|
||||
}
|
||||
if ($LASTEXITCODE -ne 0) { throw 'WinGet could not install FFmpeg.' }
|
||||
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine') + ';' +
|
||||
[Environment]::GetEnvironmentVariable('Path', 'User')
|
||||
if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
|
||||
throw 'FFmpeg was installed but is not available in this PowerShell session. Open a new terminal and run the install command again.'
|
||||
}
|
||||
}
|
||||
|
||||
$listing = & tar.exe -tzf $archivePath
|
||||
if ($LASTEXITCODE -ne 0 -or $listing.Count -gt 20000 -or (Get-Item $archivePath).Length -gt 2GB) {
|
||||
throw 'Cannot inspect the Agent archive or it exceeds extraction limits.'
|
||||
}
|
||||
foreach ($entry in $listing) {
|
||||
$normalized = $entry.Replace('\', '/')
|
||||
if ($normalized.StartsWith('/') -or $normalized -match '^[A-Za-z]:' -or
|
||||
($normalized -split '/') -contains '..') {
|
||||
throw 'Agent archive contains an unsafe path.'
|
||||
}
|
||||
}
|
||||
$verboseListing = & tar.exe -tvzf $archivePath
|
||||
if ($LASTEXITCODE -ne 0 -or @($verboseListing | Where-Object { $_ -match '^[lh][rwx-]{9}\s' }).Count -gt 0) {
|
||||
throw 'Agent archive contains a link or unsupported entry.'
|
||||
}
|
||||
$stage = Join-Path $releasesRoot ('.staging-' + [Guid]::NewGuid().ToString('N'))
|
||||
New-Item -ItemType Directory -Path $stage | Out-Null
|
||||
& tar.exe -xzf $archivePath -C $stage
|
||||
if ($LASTEXITCODE -ne 0 -or -not (Test-Path (Join-Path $stage 'Heimdall.Agent.dll'))) {
|
||||
Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
|
||||
throw 'Agent archive extraction failed or did not contain Heimdall.Agent.dll.'
|
||||
}
|
||||
|
||||
$versionLeaf = ([string]$release.version).TrimStart('v', 'V')
|
||||
if ($versionLeaf -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$') { throw 'Invalid signed release version.' }
|
||||
$versionRoot = Join-Path $releasesRoot $versionLeaf
|
||||
if (Test-Path -LiteralPath $versionRoot) { throw "Release $versionLeaf is already installed." }
|
||||
Move-Item -LiteralPath $stage -Destination $versionRoot
|
||||
Copy-Item -LiteralPath $versionRoot -Destination $releasePath -Recurse
|
||||
|
||||
Move-Item -LiteralPath $supervisorTemp -Destination $supervisorPath -Force
|
||||
|
||||
$stateDirectory = Join-Path $releaseRoot 'state'
|
||||
New-Item -ItemType Directory -Path $stateDirectory -Force | Out-Null
|
||||
$env:ASPNETCORE_URLS = 'http://127.0.0.1:8081'
|
||||
if ($InstallAsService) {
|
||||
$publicKeyPath = Join-Path $releaseRoot 'update-public-key.pem'
|
||||
Set-Content -LiteralPath $publicKeyPath -Value ([string]$release.updatePublicKeyPem) -Encoding Ascii
|
||||
$binaryPath = '"{0}" "{1}"' -f (Get-Command dotnet).Source, (Join-Path $releasePath 'Heimdall.Agent.dll')
|
||||
New-Service -Name $ServiceName -DisplayName "Heimdall Agent ($AgentName)" -Description "Heimdall camera agent for site $AgentName" `
|
||||
-BinaryPathName $binaryPath -StartupType Automatic | Out-Null
|
||||
|
||||
$serviceKey = "HKLM:\SYSTEM\CurrentControlSet\Services\$ServiceName"
|
||||
$environment = @(
|
||||
"ASPNETCORE_URLS=http://127.0.0.1:8081",
|
||||
'ASPNETCORE_ENVIRONMENT=Production',
|
||||
"Agent__CentralUrl=$CentralUrl",
|
||||
"Agent__SiteToken=$SiteToken",
|
||||
"Agent__AgentName=$AgentName",
|
||||
"Agent__StateDirectory=$stateDirectory",
|
||||
"MODEL_PATH=$(Join-Path $releasePath 'models\yolov8n.onnx')",
|
||||
"Agent__UpdateInstallRoot=$releaseRoot",
|
||||
"Agent__UpdatePublicKeyPath=$publicKeyPath",
|
||||
"Agent__UpdateSupervisorPath=$supervisorPath",
|
||||
"Agent__UpdateWindowsServiceName=$ServiceName"
|
||||
)
|
||||
New-ItemProperty -LiteralPath $serviceKey -Name Environment -PropertyType MultiString -Value $environment -Force | Out-Null
|
||||
|
||||
# Environment contains the enrollment token. Restrict registry access and files to SYSTEM and administrators.
|
||||
$registryAcl = New-Object Security.AccessControl.RegistrySecurity
|
||||
$registryAcl.SetAccessRuleProtection($true, $false)
|
||||
$registryAcl.SetOwner([Security.Principal.NTAccount]::new('BUILTIN\Administrators'))
|
||||
$registryAcl.AddAccessRule([Security.AccessControl.RegistryAccessRule]::new('NT AUTHORITY\SYSTEM', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
||||
$registryAcl.AddAccessRule([Security.AccessControl.RegistryAccessRule]::new('BUILTIN\Administrators', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
||||
Set-Acl -LiteralPath $serviceKey -AclObject $registryAcl
|
||||
|
||||
$rootAcl = New-Object Security.AccessControl.DirectorySecurity
|
||||
$rootAcl.SetAccessRuleProtection($true, $false)
|
||||
$rootAcl.SetOwner([Security.Principal.NTAccount]::new('BUILTIN\Administrators'))
|
||||
$rootAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('NT AUTHORITY\SYSTEM', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
||||
$rootAcl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new('BUILTIN\Administrators', 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
|
||||
Set-Acl -LiteralPath $releaseRoot -AclObject $rootAcl
|
||||
|
||||
if ($InstallOnly) {
|
||||
Write-Host "Installed Windows Service '$ServiceName'. Start it with: Start-Service -Name '$ServiceName'"
|
||||
return
|
||||
}
|
||||
Start-Service -Name $ServiceName
|
||||
$deadline = [DateTime]::UtcNow.AddSeconds(180)
|
||||
do {
|
||||
try {
|
||||
$health = Invoke-RestMethod -Method Get -Uri 'http://127.0.0.1:8081/api/version' -TimeoutSec 3
|
||||
if (([string]$health.version).Split('+')[0].TrimStart('v', 'V') -eq ([string]$release.version).TrimStart('v', 'V')) {
|
||||
Write-Host "Windows Service '$ServiceName' started Heimdall Agent $($release.version)."
|
||||
return
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
Start-Sleep -Seconds 2
|
||||
} while ([DateTime]::UtcNow -lt $deadline)
|
||||
Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue
|
||||
throw "Windows Service '$ServiceName' failed its startup health check."
|
||||
}
|
||||
|
||||
if ($InstallOnly) {
|
||||
Write-Host "Installed Heimdall Agent $($release.version) under '$releaseRoot'. Start it from PowerShell with the command shown by Central."
|
||||
return
|
||||
}
|
||||
|
||||
$env:Agent__CentralUrl = $CentralUrl
|
||||
$env:Agent__SiteToken = $SiteToken
|
||||
$env:Agent__AgentName = $AgentName
|
||||
$env:Agent__StateDirectory = $stateDirectory
|
||||
$env:Agent__UpdatePublicKeyPem = [string]$release.updatePublicKeyPem
|
||||
$env:Agent__UpdateInstallRoot = $releaseRoot
|
||||
$env:Agent__UpdateSupervisorPath = $supervisorPath
|
||||
Write-Host "Starting Heimdall Agent $($release.version) for site '$AgentName'. Press Ctrl+C to stop."
|
||||
Push-Location $releasePath
|
||||
try { & dotnet (Join-Path $releasePath 'Heimdall.Agent.dll') }
|
||||
finally { Pop-Location }
|
||||
}
|
||||
finally {
|
||||
if ($stage -and (Test-Path -LiteralPath $stage -PathType Container)) {
|
||||
Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
if ($versionRoot -and -not (Test-Path -LiteralPath $releasePath) -and
|
||||
(Test-Path -LiteralPath $versionRoot -PathType Container)) {
|
||||
Remove-Item -LiteralPath $versionRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
Remove-Item -LiteralPath $tempRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
+170
-18
@@ -1,24 +1,164 @@
|
||||
#!/usr/bin/env bash
|
||||
# install-agent.sh — Heimdall Agent installer for Linux
|
||||
set -euo pipefail
|
||||
CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall"
|
||||
BINARY_NAME="heimdall-agent" INSTALL_DIR="/usr/local/bin" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall"
|
||||
while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
|
||||
[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" ]] && { echo "Error: --central-url and --site-token required" >&2; exit 1; }
|
||||
CENTRAL_URL="" SITE_TOKEN="" AGENT_NAME="" STATE_DIR="/var/lib/heimdall" UPDATE_PUBLIC_KEY="" ALLOW_INSECURE_HTTP=false RUN_MODE=false INSTALL_ONLY=false
|
||||
INSTALL_ROOT="/opt/heimdall/agent" SERVICE_NAME="heimdall-agent" SERVICE_USER="heimdall"
|
||||
while [[ $# -gt 0 ]]; do case "$1" in --central-url) CENTRAL_URL="$2"; shift 2;; --site-token) SITE_TOKEN="$2"; shift 2;; --update-public-key) UPDATE_PUBLIC_KEY="$2"; shift 2;; --agent-name) AGENT_NAME="$2"; shift 2;; --state-dir) STATE_DIR="$2"; shift 2;; --allow-insecure-http) ALLOW_INSECURE_HTTP=true; shift;; --run) RUN_MODE=true; shift;; --install-only) INSTALL_ONLY=true; shift;; -h|--help) echo "Usage: $0 --central-url URL --site-token TOKEN [--agent-name NAME] [--run | --install-only] [--update-public-key LOCAL_PEM] [--state-dir PATH] [--allow-insecure-http]"; exit 0;; *) echo "Unknown: $1" >&2; exit 1;; esac; done
|
||||
[[ -z "$CENTRAL_URL" || -z "$SITE_TOKEN" ]] && { echo "Error: --central-url and --site-token are required" >&2; exit 1; }
|
||||
[[ "$RUN_MODE" == true && "$INSTALL_ONLY" == true ]] && { echo '--run and --install-only cannot be combined' >&2; exit 1; }
|
||||
if [[ -n "$UPDATE_PUBLIC_KEY" && ! -f "$UPDATE_PUBLIC_KEY" ]]; then echo 'Publisher public key file is missing' >&2; exit 1; fi
|
||||
CENTRAL_URL="${CENTRAL_URL%/}"
|
||||
if [[ "$CENTRAL_URL" != https://* && ! ( "$ALLOW_INSECURE_HTTP" == true && "$CENTRAL_URL" == http://* ) ]]; then
|
||||
echo "Error: --central-url must use HTTPS (or explicitly opt in with --allow-insecure-http on an isolated network)" >&2
|
||||
exit 1
|
||||
fi
|
||||
ARCH=$(uname -m); case "$ARCH" in x86_64|amd64) PLATFORM="linux-x64";; aarch64|arm64) PLATFORM="linux-arm64";; armv7l|armhf) PLATFORM="linux-arm";; *) echo "Unsupported: $ARCH" >&2; exit 1;; esac
|
||||
echo "Installing Heimdall Agent for $PLATFORM..."
|
||||
RELEASE_JSON=$(curl -sf "$CENTRAL_URL/api/updates/latest") || { echo "Failed to fetch release" >&2; exit 1; }
|
||||
if command -v jq &>/dev/null; then VERSION=$(echo "$RELEASE_JSON" | jq -r '.version'); DOWNLOAD_URL=$(echo "$RELEASE_JSON" | jq -r ".assets[\"$PLATFORM\"].url // empty"); EXPECTED_SHA256=$(echo "$RELEASE_JSON" | jq -r ".assets[\"$PLATFORM\"].sha256 // empty"); else VERSION=$(echo "$RELEASE_JSON" | grep -o '"version":"[^"]*"' | head -1 | cut -d'"' -f4); DOWNLOAD_URL=$(echo "$RELEASE_JSON" | grep -o "\"$PLATFORM\"" -A5 | grep -o '"url":"[^"]*"' | head -1 | cut -d'"' -f4); EXPECTED_SHA256=$(echo "$RELEASE_JSON" | grep -o "\"$PLATFORM\"" -A5 | grep -o '"sha256":"[^"]*"' | head -1 | cut -d'"' -f4); fi
|
||||
[[ -z "$DOWNLOAD_URL" ]] && { echo "No binary for $PLATFORM" >&2; exit 1; }
|
||||
echo "Latest version: $VERSION"
|
||||
TMP_DIR=$(mktemp -d); trap 'rm -rf "$TMP_DIR"' EXIT
|
||||
curl -sfL "$DOWNLOAD_URL" -o "$TMP_DIR/$BINARY_NAME" || { echo "Download failed" >&2; exit 1; }
|
||||
if [[ -n "$EXPECTED_SHA256" ]]; then ACTUAL=$(sha256sum "$TMP_DIR/$BINARY_NAME" | cut -d' ' -f1); [[ "$ACTUAL" != "$EXPECTED_SHA256" ]] && { echo "SHA256 mismatch" >&2; exit 1; }; echo "SHA256 verified"; fi
|
||||
chmod +x "$TMP_DIR/$BINARY_NAME"; [[ $EUID -eq 0 ]] && cp "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/$BINARY_NAME" || sudo cp "$TMP_DIR/$BINARY_NAME" "$INSTALL_DIR/$BINARY_NAME"
|
||||
missing=()
|
||||
for tool in curl jq openssl python3; do command -v "$tool" >/dev/null || missing+=("$tool"); done
|
||||
if ((${#missing[@]})); then
|
||||
if command -v apt-get >/dev/null; then
|
||||
apt-get update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${missing[@]}"
|
||||
elif command -v dnf >/dev/null; then
|
||||
dnf install -y "${missing[@]}"
|
||||
elif command -v apk >/dev/null; then
|
||||
apk add --no-cache "${missing[@]}"
|
||||
else
|
||||
echo "Install these prerequisites and rerun: ${missing[*]}" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
if command -v dotnet >/dev/null; then
|
||||
DOTNET_BIN=$(command -v dotnet)
|
||||
else
|
||||
DOTNET_BIN="/opt/heimdall/dotnet/dotnet"
|
||||
curl -fsSL --proto '=https' --proto-redir '=https' https://dot.net/v1/dotnet-install.sh -o "$TMP_DIR/dotnet-install.sh"
|
||||
install -d -m 755 /opt/heimdall/dotnet
|
||||
bash "$TMP_DIR/dotnet-install.sh" --channel 10.0 --runtime aspnetcore --install-dir /opt/heimdall/dotnet
|
||||
fi
|
||||
"$DOTNET_BIN" --list-runtimes | grep -q '^Microsoft.AspNetCore.App 10\.' || {
|
||||
echo 'A compatible ASP.NET Core 10 runtime is required' >&2; exit 1;
|
||||
}
|
||||
RELEASE_METADATA_URL="$CENTRAL_URL/api/updates/latest"
|
||||
for attempt in 1 2 3; do
|
||||
CURL_PROTOCOL=https
|
||||
[[ "$CENTRAL_URL" == https://* ]] || CURL_PROTOCOL=http
|
||||
HTTP_STATUS=$(curl -sS --proto "$CURL_PROTOCOL" \
|
||||
--connect-timeout 10 --max-time 30 \
|
||||
-w '%{http_code}' "$RELEASE_METADATA_URL" -o "$TMP_DIR/release.json") && CURL_STATUS=0 || CURL_STATUS=$?
|
||||
if [[ "$CURL_STATUS" -eq 0 && "$HTTP_STATUS" =~ ^2[0-9][0-9]$ ]]; then
|
||||
break
|
||||
fi
|
||||
if [[ "$CURL_STATUS" -ne 0 && "$HTTP_STATUS" == 000 ]] || [[ "$HTTP_STATUS" =~ ^(408|425|429|5[0-9][0-9])$ ]]; then
|
||||
if [[ "$attempt" -lt 3 ]]; then
|
||||
delay=$((attempt * 2))
|
||||
echo "Release metadata request failed temporarily (attempt $attempt/3); retrying in ${delay}s." >&2
|
||||
sleep "$delay"
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
echo "Failed to fetch release metadata from Central (HTTP ${HTTP_STATUS:-000}; curl exit ${CURL_STATUS})." >&2
|
||||
exit 1
|
||||
done
|
||||
if [[ -z "$UPDATE_PUBLIC_KEY" ]]; then
|
||||
jq -er '.updatePublicKeyPem | select(type == "string" and length > 0 and length <= 4096)' "$TMP_DIR/release.json" > "$TMP_DIR/update-public-key.pem" || {
|
||||
echo 'Central release metadata has no valid publisher public key' >&2; exit 1;
|
||||
}
|
||||
UPDATE_PUBLIC_KEY="$TMP_DIR/update-public-key.pem"
|
||||
fi
|
||||
openssl pkey -pubin -in "$UPDATE_PUBLIC_KEY" -noout >/dev/null || { echo 'Invalid publisher public key' >&2; exit 1; }
|
||||
openssl pkey -pubin -in "$UPDATE_PUBLIC_KEY" -text -noout 2>/dev/null | grep -q 'ASN1 OID: prime256v1' || {
|
||||
echo 'Publisher public key must use ECDSA P-256' >&2
|
||||
exit 1
|
||||
}
|
||||
jq -r '.signedManifest // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.json" || { echo 'Invalid signed manifest encoding' >&2; exit 1; }
|
||||
jq -r '.manifestSignature // empty' "$TMP_DIR/release.json" | base64 -d > "$TMP_DIR/manifest.sig" || { echo 'Invalid release signature encoding' >&2; exit 1; }
|
||||
openssl dgst -sha256 -verify "$UPDATE_PUBLIC_KEY" -signature "$TMP_DIR/manifest.sig" "$TMP_DIR/manifest.json" >/dev/null || { echo 'Release signature verification failed' >&2; exit 1; }
|
||||
VERSION=$(jq -r '.version' "$TMP_DIR/manifest.json")
|
||||
[[ "$VERSION" == "$(jq -r '.version' "$TMP_DIR/release.json")" && "$VERSION" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+([._-][0-9A-Za-z.-]+)?$ ]] || { echo 'Invalid signed release version' >&2; exit 1; }
|
||||
ASSET_PLATFORM=$(jq -r --arg platform "$PLATFORM" 'if .assets[$platform] then $platform elif .assets.portable then "portable" else empty end' "$TMP_DIR/manifest.json")
|
||||
[[ -n "$ASSET_PLATFORM" ]] || { echo "No signed archive for $PLATFORM" >&2; exit 1; }
|
||||
EXPECTED_SHA256=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform]' "$TMP_DIR/manifest.json")
|
||||
DOWNLOAD_URL=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform].url // empty' "$TMP_DIR/release.json")
|
||||
RELEASE_SHA256=$(jq -r --arg platform "$ASSET_PLATFORM" '.assets[$platform].sha256 // empty' "$TMP_DIR/release.json")
|
||||
[[ "$EXPECTED_SHA256" =~ ^[[:xdigit:]]{64}$ && "${EXPECTED_SHA256,,}" == "${RELEASE_SHA256,,}" && "$DOWNLOAD_URL" == https://* ]] || { echo 'Release archive differs from signed manifest' >&2; exit 1; }
|
||||
curl -fsSL --proto '=https' --proto-redir '=https' "$DOWNLOAD_URL" -o "$TMP_DIR/agent.tar.gz" || { echo "Download failed" >&2; exit 1; }
|
||||
ACTUAL=$(sha256sum "$TMP_DIR/agent.tar.gz" | cut -d' ' -f1); [[ "${ACTUAL,,}" == "${EXPECTED_SHA256,,}" ]] || { echo "SHA256 mismatch" >&2; exit 1; }
|
||||
echo "Signed archive verified: $VERSION"
|
||||
mkdir -p "$TMP_DIR/agent"
|
||||
python3 - "$TMP_DIR/agent.tar.gz" "$TMP_DIR/agent" <<'PY'
|
||||
import pathlib, shutil, sys, tarfile
|
||||
root=pathlib.Path(sys.argv[2]).resolve()
|
||||
with tarfile.open(sys.argv[1], 'r:gz') as archive:
|
||||
members=archive.getmembers()
|
||||
if len(members)>20000 or sum(m.size for m in members)>2_000_000_000:
|
||||
raise SystemExit('Archive exceeds extraction limits')
|
||||
for member in members:
|
||||
if not (member.isfile() or member.isdir()):
|
||||
raise SystemExit('Archive contains a link or unsupported entry')
|
||||
target=(root/member.name).resolve()
|
||||
if target!=root and root not in target.parents:
|
||||
raise SystemExit('Archive path escapes extraction root')
|
||||
if member.isdir():
|
||||
target.mkdir(parents=True,exist_ok=True)
|
||||
else:
|
||||
target.parent.mkdir(parents=True,exist_ok=True)
|
||||
with archive.extractfile(member) as source, open(target,'xb') as output:
|
||||
shutil.copyfileobj(source,output)
|
||||
PY
|
||||
[[ -f "$TMP_DIR/agent/Heimdall.Agent.dll" ]] || { echo 'Archive has no agent assembly' >&2; exit 1; }
|
||||
id "$SERVICE_USER" &>/dev/null || sudo useradd --system --no-create-home --shell /usr/sbin/nologin "$SERVICE_USER" 2>/dev/null || true
|
||||
sudo mkdir -p "$STATE_DIR" && sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR" && sudo chmod 700 "$STATE_DIR"
|
||||
AGENT_NAME_ENV=""; [[ -n "$AGENT_NAME" ]] && AGENT_NAME_ENV="Environment=Agent__AgentName=$AGENT_NAME"
|
||||
sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 750 "$INSTALL_ROOT" "$INSTALL_ROOT/releases"
|
||||
[[ ! -e "$INSTALL_ROOT/releases/$VERSION" ]] || { echo 'Release already installed' >&2; exit 1; }
|
||||
sudo mv "$TMP_DIR/agent" "$INSTALL_ROOT/releases/$VERSION"
|
||||
sudo chown -R "$SERVICE_USER:$SERVICE_USER" "$INSTALL_ROOT/releases/$VERSION"
|
||||
sudo ln -sfn "$INSTALL_ROOT/releases/$VERSION" "$INSTALL_ROOT/current"
|
||||
sudo install -d -o root -g root -m 755 /etc/heimdall
|
||||
sudo install -o root -g root -m 644 "$UPDATE_PUBLIC_KEY" /etc/heimdall/update-public-key.pem
|
||||
sudo install -d -o root -g root -m 755 /usr/local/libexec
|
||||
SUPERVISOR_SOURCE="$(dirname "$0")/agent-supervisor.py"
|
||||
if [[ ! -f "$SUPERVISOR_SOURCE" ]]; then
|
||||
SUPERVISOR_SOURCE="$TMP_DIR/agent-supervisor.py"
|
||||
curl -fsS "$CENTRAL_URL/install/agent-supervisor.py" -o "$SUPERVISOR_SOURCE" || {
|
||||
echo 'Failed to download the Heimdall Agent supervisor from Central' >&2; exit 1;
|
||||
}
|
||||
fi
|
||||
sudo install -o root -g root -m 755 "$SUPERVISOR_SOURCE" /usr/local/libexec/heimdall-agent-supervisor.py
|
||||
sudo install -d -o root -g root -m 700 /etc/heimdall/credentials
|
||||
printf '%s' "$SITE_TOKEN" | sudo tee /etc/heimdall/credentials/site-token >/dev/null
|
||||
sudo chmod 600 /etc/heimdall/credentials/site-token
|
||||
sudo install -d -o "$SERVICE_USER" -g "$SERVICE_USER" -m 700 "$STATE_DIR/credentials"
|
||||
printf '%s' "$SITE_TOKEN" | sudo tee "$STATE_DIR/credentials/site-token" >/dev/null
|
||||
sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR/credentials/site-token"
|
||||
sudo chmod 600 "$STATE_DIR/credentials/site-token"
|
||||
AGENT_NAME_CREDENTIAL=""
|
||||
if [[ -n "$AGENT_NAME" ]]; then
|
||||
printf '%s' "$AGENT_NAME" | sudo tee /etc/heimdall/credentials/agent-name >/dev/null
|
||||
sudo chmod 600 /etc/heimdall/credentials/agent-name
|
||||
printf '%s' "$AGENT_NAME" | sudo tee "$STATE_DIR/credentials/agent-name" >/dev/null
|
||||
sudo chown "$SERVICE_USER:$SERVICE_USER" "$STATE_DIR/credentials/agent-name"
|
||||
sudo chmod 600 "$STATE_DIR/credentials/agent-name"
|
||||
AGENT_NAME_CREDENTIAL="LoadCredential=agent-name:/etc/heimdall/credentials/agent-name"
|
||||
fi
|
||||
if [[ "$RUN_MODE" == true ]]; then
|
||||
echo "Starting Heimdall Agent $VERSION in foreground; press Ctrl+C to stop."
|
||||
sudo -u "$SERVICE_USER" env \
|
||||
CREDENTIALS_DIRECTORY="$STATE_DIR/credentials" \
|
||||
ASPNETCORE_URLS=http://127.0.0.1:8081 \
|
||||
HEIMDALL_DOTNET="$DOTNET_BIN" \
|
||||
ASPNETCORE_ENVIRONMENT=Production \
|
||||
Agent__CentralUrl="$CENTRAL_URL" \
|
||||
Agent__AgentName="$AGENT_NAME" \
|
||||
Agent__AllowInsecureHttp="$ALLOW_INSECURE_HTTP" \
|
||||
Agent__StateDirectory="$STATE_DIR" \
|
||||
Agent__UpdateInstallRoot="$INSTALL_ROOT" \
|
||||
Agent__UpdatePublicKeyPath=/etc/heimdall/update-public-key.pem \
|
||||
/usr/bin/python3 /usr/local/libexec/heimdall-agent-supervisor.py
|
||||
exit $?
|
||||
fi
|
||||
cat <<EOF | sudo tee /etc/systemd/system/$SERVICE_NAME.service >/dev/null
|
||||
[Unit]
|
||||
Description=Heimdall Agent
|
||||
@@ -26,15 +166,27 @@ After=network-online.target
|
||||
[Service]
|
||||
Type=simple
|
||||
User=$SERVICE_USER
|
||||
ExecStart=$INSTALL_DIR/$BINARY_NAME
|
||||
Restart=on-failure
|
||||
ExecStart=/usr/bin/python3 /usr/local/libexec/heimdall-agent-supervisor.py
|
||||
WorkingDirectory=$INSTALL_ROOT/current
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
Environment=ASPNETCORE_URLS=http://127.0.0.1:8081
|
||||
Environment=HEIMDALL_DOTNET=$DOTNET_BIN
|
||||
Environment=ASPNETCORE_ENVIRONMENT=Production
|
||||
Environment=Agent__CentralUrl=$CENTRAL_URL
|
||||
Environment=Agent__SiteToken=$SITE_TOKEN
|
||||
Environment=Agent__AllowInsecureHttp=$ALLOW_INSECURE_HTTP
|
||||
Environment=Agent__StateDirectory=$STATE_DIR
|
||||
$AGENT_NAME_ENV
|
||||
Environment=Agent__UpdateInstallRoot=$INSTALL_ROOT
|
||||
Environment=Agent__UpdatePublicKeyPath=/etc/heimdall/update-public-key.pem
|
||||
LoadCredential=site-token:/etc/heimdall/credentials/site-token
|
||||
$AGENT_NAME_CREDENTIAL
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME" && sudo systemctl start "$SERVICE_NAME"
|
||||
echo "Done! Version: $VERSION, Service: $SERVICE_NAME"
|
||||
sudo systemctl daemon-reload && sudo systemctl enable "$SERVICE_NAME"
|
||||
if [[ "$INSTALL_ONLY" == true ]]; then
|
||||
echo "Installed version $VERSION and enabled $SERVICE_NAME. Start it with: sudo systemctl start $SERVICE_NAME"
|
||||
else
|
||||
sudo systemctl start "$SERVICE_NAME"
|
||||
echo "Done! Version: $VERSION, Service: $SERVICE_NAME"
|
||||
fi
|
||||
@@ -0,0 +1,389 @@
|
||||
[CmdletBinding()]
|
||||
param()
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$ProgressPreference = 'SilentlyContinue'
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
$script:PackageReleaseVersion = 'unversioned'
|
||||
$script:ReleaseApiUrl = if ($env:HEIMDALL_RELEASE_API_URL) {
|
||||
$env:HEIMDALL_RELEASE_API_URL.TrimEnd('/')
|
||||
} else {
|
||||
'https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases'
|
||||
}
|
||||
$script:SourceBaseUrl = if ($env:HEIMDALL_SOURCE_BASE_URL) {
|
||||
$env:HEIMDALL_SOURCE_BASE_URL.TrimEnd('/')
|
||||
} else {
|
||||
'https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main'
|
||||
}
|
||||
|
||||
if ([Environment]::OSVersion.Platform -ne [PlatformID]::Win32NT) {
|
||||
throw 'Cet installateur est prévu pour Windows PowerShell ou PowerShell sous Windows.'
|
||||
}
|
||||
|
||||
$installerVersion = if ($env:HEIMDALL_INSTALLER_VERSION) { $env:HEIMDALL_INSTALLER_VERSION } else { $script:PackageReleaseVersion }
|
||||
if ($script:PackageReleaseVersion -eq 'unversioned') {
|
||||
$releaseUri = "$script:ReleaseApiUrl/latest"
|
||||
if ($env:HEIMDALL_INSTALLER_VERSION) {
|
||||
$installerVersion = $env:HEIMDALL_INSTALLER_VERSION
|
||||
if ($installerVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$') {
|
||||
throw 'Version Heimdall invalide.'
|
||||
}
|
||||
$releaseUri = "$script:ReleaseApiUrl/tags/$installerVersion"
|
||||
}
|
||||
$bootstrapRoot = Join-Path ([IO.Path]::GetTempPath()) ('heimdall-installer-' + [Guid]::NewGuid().ToString('N'))
|
||||
$bundlePath = Join-Path $bootstrapRoot 'installers.zip'
|
||||
$null = New-Item -ItemType Directory -Path $bootstrapRoot
|
||||
try {
|
||||
$release = Invoke-RestMethod -Method Get -Uri $releaseUri -TimeoutSec 30
|
||||
$resolvedVersion = [string]$release.tag_name
|
||||
if ($resolvedVersion -notmatch '^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$') {
|
||||
throw 'La release Heimdall retournée a une version invalide.'
|
||||
}
|
||||
$installerName = "heimdall-installers-$resolvedVersion.zip"
|
||||
$installerAsset = @($release.assets) | Where-Object { $_.name -eq $installerName } | Select-Object -First 1
|
||||
if (-not $installerAsset -or $installerAsset.browser_download_url -notmatch '^https://') {
|
||||
throw "La release ne contient pas son bundle d'installation versionné."
|
||||
}
|
||||
$digestProperty = $installerAsset.PSObject.Properties['digest']
|
||||
$assetDigest = if ($null -ne $digestProperty) { $digestProperty.Value } else { $null }
|
||||
if ($null -ne $assetDigest) {
|
||||
if ($assetDigest -isnot [string] -or $assetDigest -notmatch '^sha256:[A-Fa-f0-9]{64}$') {
|
||||
throw 'Le digest Gitea du bundle est invalide.'
|
||||
}
|
||||
$expectedHash = $assetDigest.Substring(7)
|
||||
} else {
|
||||
$checksumName = "$installerName.sha256"
|
||||
$checksumAsset = @($release.assets) | Where-Object { $_.name -eq $checksumName } | Select-Object -First 1
|
||||
if (-not $checksumAsset -or $checksumAsset.browser_download_url -notmatch '^https://') {
|
||||
throw 'La release ne fournit pas le checksum publié du bundle.'
|
||||
}
|
||||
$checksumPath = Join-Path $bootstrapRoot 'installers.zip.sha256'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $checksumAsset.browser_download_url -OutFile $checksumPath -TimeoutSec 30
|
||||
$checksumText = [IO.File]::ReadAllText($checksumPath)
|
||||
$escapedName = [Regex]::Escape($installerName)
|
||||
$checksumMatches = [Regex]::Matches($checksumText, "(?m)^([A-Fa-f0-9]{64})\s+\*?$escapedName\s*$")
|
||||
if ($checksumMatches.Count -ne 1) { throw 'Le checksum publié du bundle est invalide.' }
|
||||
$expectedHash = $checksumMatches[0].Groups[1].Value
|
||||
}
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $installerAsset.browser_download_url -OutFile $bundlePath -TimeoutSec 120
|
||||
$actualHash = (Get-FileHash -LiteralPath $bundlePath -Algorithm SHA256).Hash
|
||||
if ($actualHash -ne $expectedHash) { throw 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' }
|
||||
Expand-Archive -LiteralPath $bundlePath -DestinationPath $bootstrapRoot -Force
|
||||
$packagedScript = Join-Path $bootstrapRoot 'install\install-server.ps1'
|
||||
if (-not (Test-Path -LiteralPath $packagedScript)) { throw 'Le bundle ne contient pas install/install-server.ps1.' }
|
||||
$env:HEIMDALL_INSTALLER_VERSION = $resolvedVersion
|
||||
& $packagedScript
|
||||
if ($LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
return
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $bootstrapRoot -Recurse -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
function Read-Answer {
|
||||
param([string]$Prompt, [string]$Default)
|
||||
$answer = Read-Host "$Prompt [$Default]"
|
||||
if ([string]::IsNullOrWhiteSpace($answer)) { return $Default }
|
||||
return $answer.Trim()
|
||||
}
|
||||
|
||||
function Read-YesNo {
|
||||
param([string]$Prompt, [string]$Default = 'n')
|
||||
return (Read-Answer -Prompt $Prompt -Default $Default) -match '^(?i:o|oui|y|yes)$'
|
||||
}
|
||||
|
||||
function New-RandomHex {
|
||||
param([int]$ByteCount = 32)
|
||||
$bytes = [byte[]]::new($ByteCount)
|
||||
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
try { $rng.GetBytes($bytes) } finally { $rng.Dispose() }
|
||||
return [BitConverter]::ToString($bytes).Replace('-', '').ToLowerInvariant()
|
||||
}
|
||||
|
||||
function Set-PrivateAcl {
|
||||
param([string]$Path, [bool]$IsDirectory = $false)
|
||||
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
$acl = Get-Acl -LiteralPath $Path
|
||||
$acl.SetAccessRuleProtection($true, $false)
|
||||
foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRuleAll($rule) }
|
||||
$inheritance = if ($IsDirectory) {
|
||||
[System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor
|
||||
[System.Security.AccessControl.InheritanceFlags]::ObjectInherit
|
||||
} else { [System.Security.AccessControl.InheritanceFlags]::None }
|
||||
$rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
|
||||
$identity,
|
||||
[System.Security.AccessControl.FileSystemRights]::FullControl,
|
||||
$inheritance,
|
||||
[System.Security.AccessControl.PropagationFlags]::None,
|
||||
[System.Security.AccessControl.AccessControlType]::Allow)
|
||||
[void]$acl.AddAccessRule($rule)
|
||||
Set-Acl -LiteralPath $Path -AclObject $acl
|
||||
}
|
||||
|
||||
function Ensure-EnvValue {
|
||||
param([string]$Content, [string]$Name, [string]$Value)
|
||||
if ($Content -match "(?m)^$([regex]::Escape($Name))=") { return $Content }
|
||||
return "$($Content.TrimEnd())`r`n$Name=$Value`r`n"
|
||||
}
|
||||
|
||||
function Get-SourceAsset {
|
||||
param([string]$RelativePath, [string]$DestinationPath)
|
||||
$assetUri = "$script:SourceBaseUrl/$RelativePath"
|
||||
$assetTempPath = "$DestinationPath.tmp.$([guid]::NewGuid().ToString('N'))"
|
||||
try {
|
||||
Invoke-WebRequest -UseBasicParsing -Uri $assetUri -OutFile $assetTempPath -TimeoutSec 60
|
||||
if (Test-Path -LiteralPath $DestinationPath) {
|
||||
$backupPath = "$DestinationPath.bak.$(Get-Date -Format 'yyyyMMddTHHmmssfffZ')"
|
||||
Copy-Item -LiteralPath $DestinationPath -Destination $backupPath
|
||||
}
|
||||
Move-Item -LiteralPath $assetTempPath -Destination $DestinationPath -Force
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $assetTempPath) { Remove-Item -LiteralPath $assetTempPath -Force }
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-DockerCompose {
|
||||
param([string[]]$ComposeArguments)
|
||||
& docker compose @ComposeArguments
|
||||
if ($LASTEXITCODE -ne 0) { throw "docker compose a échoué (code $LASTEXITCODE)." }
|
||||
}
|
||||
|
||||
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { throw 'Docker est requis.' }
|
||||
& docker compose version | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Le plugin Docker Compose est requis.' }
|
||||
|
||||
Write-Host 'Installation de Heimdall Central (serveur + PostgreSQL).'
|
||||
$defaultDestination = Join-Path $HOME 'heimdall'
|
||||
$destination = [IO.Path]::GetFullPath((Read-Answer "Dossier d’installation" $defaultDestination))
|
||||
$composePath = Join-Path $destination 'docker-compose.yml'
|
||||
$envPath = Join-Path $destination '.env'
|
||||
$dbPasswordPath = Join-Path (Join-Path $destination 'secrets') 'db_password'
|
||||
$isExisting = (Test-Path -LiteralPath $composePath) -or (Test-Path -LiteralPath $envPath)
|
||||
if ($isExisting) {
|
||||
if (-not (Test-Path -LiteralPath $composePath) -or -not (Test-Path -LiteralPath $envPath) -or
|
||||
-not (Test-Path -LiteralPath $dbPasswordPath)) {
|
||||
throw 'Installation existante incomplète; aucun fichier modifié.'
|
||||
}
|
||||
if (-not (Read-YesNo 'Installation existante : mettre à jour le Compose (sauvegarde du précédent), en conservant .env, secrets et volumes ?' 'o')) {
|
||||
Write-Host 'Installation laissée inchangée.'
|
||||
return
|
||||
}
|
||||
$webPort = 5000
|
||||
$corsOrigin = '*'
|
||||
} else {
|
||||
$webPortText = Read-Answer 'Port HTTP du serveur' '5000'
|
||||
$corsOrigin = Read-Answer 'Origine(s) autorisée(s) par CORS' '*'
|
||||
$webPort = 0
|
||||
if (-not [int]::TryParse($webPortText, [ref]$webPort) -or $webPort -lt 1 -or $webPort -gt 65535) {
|
||||
throw 'Port invalide.'
|
||||
}
|
||||
if ($corsOrigin -notmatch '^[A-Za-z0-9*.,:/_-]+$') { throw 'Origine CORS invalide.' }
|
||||
}
|
||||
|
||||
$null = New-Item -ItemType Directory -Path $destination -Force
|
||||
$secretsDirectory = Join-Path $destination 'secrets'
|
||||
$optionalDirectory = Join-Path $destination 'optional'
|
||||
$optionalSecretsDirectory = Join-Path $optionalDirectory 'secrets'
|
||||
$null = New-Item -ItemType Directory -Path $secretsDirectory -Force
|
||||
$null = New-Item -ItemType Directory -Path $optionalSecretsDirectory -Force
|
||||
Set-PrivateAcl -Path $destination -IsDirectory $true
|
||||
Set-PrivateAcl -Path $secretsDirectory -IsDirectory $true
|
||||
Set-PrivateAcl -Path $optionalDirectory -IsDirectory $true
|
||||
Set-PrivateAcl -Path $optionalSecretsDirectory -IsDirectory $true
|
||||
|
||||
$envContent = $null
|
||||
if (-not $isExisting) {
|
||||
$dbPassword = New-RandomHex
|
||||
$jwtKey = New-RandomHex
|
||||
$jwtRefreshKey = New-RandomHex
|
||||
[IO.File]::WriteAllText($dbPasswordPath, $dbPassword, [Text.Encoding]::ASCII)
|
||||
Set-PrivateAcl -Path $dbPasswordPath
|
||||
$envContent = @"
|
||||
POSTGRES_DB=heimdall
|
||||
POSTGRES_USER=heimdall
|
||||
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=$dbPassword
|
||||
JWT__KEY=$jwtKey
|
||||
JWT__REFRESHKEY=$jwtRefreshKey
|
||||
JWT__ISSUER=heimdall
|
||||
JWT__AUDIENCE=heimdall-api
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
WEB_PORT=$webPort
|
||||
Cors__AllowedOrigins=$corsOrigin
|
||||
TZ=Europe/Paris
|
||||
REDIS_PASSWORD=$(New-RandomHex)
|
||||
HEIMDALL_DATA_VOLUME=heimdall_heimdall_data
|
||||
PLATE_OCR_ENABLED=false
|
||||
"@
|
||||
[IO.File]::WriteAllText($envPath, $envContent.TrimStart("`r", "`n"), [Text.Encoding]::ASCII)
|
||||
Set-PrivateAcl -Path $envPath
|
||||
} else {
|
||||
$envContent = [IO.File]::ReadAllText($envPath)
|
||||
if ($envContent -notmatch '(?m)^DATABASE_URL=') {
|
||||
throw 'DATABASE_URL est absent du .env existant; complète-le sans changer le mot de passe PostgreSQL avant de relancer.'
|
||||
}
|
||||
$envContent = Ensure-EnvValue $envContent 'JWT__KEY' (New-RandomHex)
|
||||
$envContent = Ensure-EnvValue $envContent 'JWT__REFRESHKEY' (New-RandomHex)
|
||||
$envContent = Ensure-EnvValue $envContent 'POSTGRES_DB' 'heimdall'
|
||||
$envContent = Ensure-EnvValue $envContent 'POSTGRES_USER' 'heimdall'
|
||||
$envContent = Ensure-EnvValue $envContent 'JWT__ISSUER' 'heimdall'
|
||||
$envContent = Ensure-EnvValue $envContent 'JWT__AUDIENCE' 'heimdall-api'
|
||||
$envContent = Ensure-EnvValue $envContent 'ASPNETCORE_ENVIRONMENT' 'Production'
|
||||
$envContent = Ensure-EnvValue $envContent 'WEB_PORT' '5000'
|
||||
$envContent = Ensure-EnvValue $envContent 'Cors__AllowedOrigins' '*'
|
||||
$envContent = Ensure-EnvValue $envContent 'TZ' 'Europe/Paris'
|
||||
$envContent = Ensure-EnvValue $envContent 'REDIS_PASSWORD' (New-RandomHex)
|
||||
$envContent = Ensure-EnvValue $envContent 'HEIMDALL_DATA_VOLUME' 'heimdall_heimdall_data'
|
||||
$envContent = Ensure-EnvValue $envContent 'PLATE_OCR_ENABLED' 'false'
|
||||
[IO.File]::WriteAllText($envPath, $envContent, [Text.Encoding]::ASCII)
|
||||
Set-PrivateAcl -Path $envPath
|
||||
}
|
||||
|
||||
$composeContent = @'
|
||||
name: heimdall
|
||||
|
||||
services:
|
||||
postgresql:
|
||||
image: postgres:17-alpine
|
||||
pull_policy: always
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||
secrets: [db_password]
|
||||
volumes: [pgdata:/var/lib/postgresql/data]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
networks: [heimdall-net]
|
||||
|
||||
heimdall:
|
||||
image: eltruncho/heimdall:latest
|
||||
pull_policy: always
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: "true"
|
||||
environment:
|
||||
DATABASE_URL: ${DATABASE_URL:?missing DATABASE_URL}
|
||||
JWT__Issuer: ${JWT__ISSUER}
|
||||
JWT__Audience: ${JWT__AUDIENCE}
|
||||
JWT__KEY: ${JWT__KEY:?missing JWT__KEY}
|
||||
JWT__REFRESHKEY: ${JWT__REFRESHKEY:?missing JWT__REFRESHKEY}
|
||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT}
|
||||
ASPNETCORE_URLS: http://+:8080
|
||||
Cors__AllowedOrigins: ${Cors__AllowedOrigins}
|
||||
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
|
||||
ports: ["${WEB_PORT}:8080"]
|
||||
volumes:
|
||||
- heimdall_data:/var/lib/heimdall
|
||||
- heimdall_data:/app/data
|
||||
depends_on:
|
||||
postgresql:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://127.0.0.1:8080/healthz"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
restart: unless-stopped
|
||||
networks: [heimdall-net]
|
||||
|
||||
watchtower:
|
||||
image: nickfedor/watchtower:1.23.2
|
||||
pull_policy: always
|
||||
command: ["--cleanup", "--label-enable", "--interval", "86400"]
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
restart: unless-stopped
|
||||
networks: [heimdall-net]
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
heimdall_data:
|
||||
|
||||
secrets:
|
||||
db_password:
|
||||
file: ./secrets/db_password
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
driver: bridge
|
||||
'@
|
||||
$composeTempPath = Join-Path $destination ".docker-compose.$([guid]::NewGuid().ToString('N')).tmp"
|
||||
[IO.File]::WriteAllText($composeTempPath, $composeContent, [Text.Encoding]::ASCII)
|
||||
Set-PrivateAcl -Path $composeTempPath
|
||||
|
||||
$selected = [Collections.Generic.List[string]]::new()
|
||||
foreach ($service in @('ollama', 'ntfy', 'rustfs', 'coturn', 'redis', 'backup')) {
|
||||
$prompt = if ($service -eq 'backup') {
|
||||
'Activer les sauvegardes planifiées (nécessite une configuration dédiée) ?'
|
||||
} else { "Installer le service optionnel $service ?" }
|
||||
if (Read-YesNo $prompt) {
|
||||
$selected.Add($service)
|
||||
$assetPath = Join-Path $optionalDirectory "docker-compose.$service.yml"
|
||||
Get-SourceAsset "docker/docker-compose.$service.yml" $assetPath
|
||||
Set-PrivateAcl -Path $assetPath
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Compose généré dans $composePath"
|
||||
Write-Host "Variables protégées dans $envPath et secret PostgreSQL dans secrets (ACL utilisateur uniquement)."
|
||||
Write-Host 'Validation du Compose avant démarrage…'
|
||||
try {
|
||||
Invoke-DockerCompose @('--env-file', $envPath, '-f', $composeTempPath, 'config', '--quiet')
|
||||
if ($isExisting) {
|
||||
$backupPath = "$composePath.bak.$(Get-Date -Format 'yyyyMMddTHHmmssfffZ')"
|
||||
Copy-Item -LiteralPath $composePath -Destination $backupPath
|
||||
Write-Host "Ancien Compose sauvegardé dans $backupPath"
|
||||
}
|
||||
Move-Item -LiteralPath $composeTempPath -Destination $composePath -Force
|
||||
} finally {
|
||||
if (Test-Path -LiteralPath $composeTempPath) { Remove-Item -LiteralPath $composeTempPath -Force }
|
||||
}
|
||||
$startCore = Read-YesNo 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o'
|
||||
if ($startCore) {
|
||||
Invoke-DockerCompose @('--env-file', $envPath, '-f', $composePath, 'up', '-d')
|
||||
}
|
||||
|
||||
foreach ($service in $selected) {
|
||||
switch ($service) {
|
||||
'rustfs' {
|
||||
$accessKeyPath = Join-Path $optionalSecretsDirectory 'rustfs_access_key'
|
||||
$secretKeyPath = Join-Path $optionalSecretsDirectory 'rustfs_secret_key'
|
||||
[IO.File]::WriteAllText($accessKeyPath, "heimdall$(New-RandomHex 8)", [Text.Encoding]::ASCII)
|
||||
[IO.File]::WriteAllText($secretKeyPath, (New-RandomHex), [Text.Encoding]::ASCII)
|
||||
Set-PrivateAcl $accessKeyPath
|
||||
Set-PrivateAcl $secretKeyPath
|
||||
}
|
||||
'coturn' {
|
||||
$coturnSecretPath = Join-Path $optionalSecretsDirectory 'coturn_secret'
|
||||
[IO.File]::WriteAllText($coturnSecretPath, (New-RandomHex), [Text.Encoding]::ASCII)
|
||||
Set-PrivateAcl $coturnSecretPath
|
||||
}
|
||||
'backup' {
|
||||
$backupScriptsPath = Join-Path $optionalDirectory 'scripts'
|
||||
$null = New-Item -ItemType Directory -Path $backupScriptsPath -Force
|
||||
Set-PrivateAcl -Path $backupScriptsPath -IsDirectory $true
|
||||
foreach ($name in @('backup.sh', 'backup-protected-data.sh', 'backup-rustfs.sh', 'restore.sh', 'restore-protected-data.sh')) {
|
||||
$assetPath = Join-Path $backupScriptsPath $name
|
||||
Get-SourceAsset "docker/scripts/$name" $assetPath
|
||||
Set-PrivateAcl -Path $assetPath
|
||||
}
|
||||
$backupDbPassword = Join-Path $optionalSecretsDirectory 'db_password'
|
||||
Copy-Item -LiteralPath $dbPasswordPath -Destination $backupDbPassword
|
||||
Set-PrivateAcl -Path $backupDbPassword
|
||||
}
|
||||
}
|
||||
if ($startCore -and (Read-YesNo "Démarrer le service optionnel $service ?" 'o')) {
|
||||
Invoke-DockerCompose @('--project-name', "heimdall-$service", '--env-file', $envPath,
|
||||
'-f', (Join-Path $optionalDirectory "docker-compose.$service.yml"), 'up', '-d')
|
||||
} else {
|
||||
Write-Host "Service $service préparé dans $optionalDirectory."
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Configurez ensuite les intégrations activées depuis les paramètres de Central; leurs valeurs restent gérées par l’IHM."
|
||||
Executable
+327
@@ -0,0 +1,327 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_PATH="${BASH_SOURCE[0]:-}"
|
||||
SCRIPT_DIR=""
|
||||
if [[ -n "$SCRIPT_PATH" ]]; then
|
||||
SCRIPT_DIR="$(cd -- "$(dirname -- "$SCRIPT_PATH")" && pwd)"
|
||||
fi
|
||||
readonly SOURCE_BASE_URL="${HEIMDALL_SOURCE_BASE_URL:-https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main}"
|
||||
readonly PACKAGE_RELEASE_VERSION="unversioned"
|
||||
readonly RELEASE_API_URL="${HEIMDALL_RELEASE_API_URL:-https://sources.tordais.cc/api/v1/repos/arnaud.dartois/Heimdall/releases}"
|
||||
REPO_ROOT=""
|
||||
if [[ -n "$SCRIPT_DIR" && -f "${SCRIPT_DIR}/../docker/docker-compose.ollama.yml" ]]; then
|
||||
REPO_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd)"
|
||||
fi
|
||||
|
||||
say() { printf '%s\n' "$*"; }
|
||||
ask() {
|
||||
local prompt="$1" default="$2" answer
|
||||
if [[ -r /dev/tty && -w /dev/tty ]]; then
|
||||
read -r -p "${prompt} [${default}] " answer </dev/tty
|
||||
else
|
||||
read -r -p "${prompt} [${default}] " answer
|
||||
fi
|
||||
printf '%s' "${answer:-$default}"
|
||||
}
|
||||
if [[ ! -t 0 && (! -r /dev/tty || ! -w /dev/tty) ]]; then
|
||||
echo "Ce script nécessite un terminal interactif." >&2
|
||||
exit 2
|
||||
fi
|
||||
for command in docker openssl curl jq unzip; do
|
||||
command -v "$command" >/dev/null || { echo "Commande requise absente : $command" >&2; exit 1; }
|
||||
done
|
||||
docker compose version >/dev/null
|
||||
|
||||
# A raw-branch bootstrap resolves the latest stable installer bundle, then
|
||||
# re-enters the version-pinned script contained in that bundle. Packaged copies
|
||||
# already carry their version and never resolve a moving release again.
|
||||
installer_version="$PACKAGE_RELEASE_VERSION"
|
||||
if [[ "$PACKAGE_RELEASE_VERSION" == unversioned ]]; then
|
||||
release_api="$RELEASE_API_URL/latest"
|
||||
if [[ -n "${HEIMDALL_INSTALLER_VERSION:-}" ]]; then
|
||||
installer_version="$HEIMDALL_INSTALLER_VERSION"
|
||||
[[ "$installer_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] || {
|
||||
echo 'Version Heimdall invalide.' >&2; exit 1;
|
||||
}
|
||||
release_api="$RELEASE_API_URL/tags/$installer_version"
|
||||
fi
|
||||
bootstrap_dir="$(mktemp -d "${TMPDIR:-/tmp}/heimdall-installer.XXXXXX")"
|
||||
cleanup_bootstrap() { rm -rf -- "$bootstrap_dir"; }
|
||||
trap cleanup_bootstrap EXIT
|
||||
if ! curl --fail --silent --show-error --location "$release_api" --output "$bootstrap_dir/release.json"; then
|
||||
echo 'Impossible de récupérer la dernière release Heimdall.' >&2; exit 1
|
||||
fi
|
||||
resolved_version="$(jq -er '.tag_name | select(type == "string" and test("^[0-9]+\\.[0-9]+\\.[0-9]+([.-][0-9A-Za-z.-]+)?$"))' "$bootstrap_dir/release.json")" || {
|
||||
echo 'La release Heimdall retournée a une version invalide.' >&2; exit 1;
|
||||
}
|
||||
installer_asset="heimdall-installers-$resolved_version.zip"
|
||||
asset_json="$(jq -ce --arg name "$installer_asset" '.assets[] | select(.name == $name)' "$bootstrap_dir/release.json")" || {
|
||||
echo 'La release ne contient pas son bundle d’installation versionné.' >&2; exit 1;
|
||||
}
|
||||
installer_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$asset_json")" || {
|
||||
echo 'URL HTTPS du bundle d’installation invalide.' >&2; exit 1;
|
||||
}
|
||||
asset_digest_type="$(jq -r 'if has("digest") then (.digest | type) else "missing" end' <<<"$asset_json")"
|
||||
asset_digest="$(jq -r '.digest // empty' <<<"$asset_json")"
|
||||
if [[ "$asset_digest_type" != null && "$asset_digest_type" != missing ]]; then
|
||||
[[ "$asset_digest_type" == string && "$asset_digest" =~ ^sha256:[A-Fa-f0-9]{64}$ ]] || {
|
||||
echo 'Le digest Gitea du bundle est invalide.' >&2; exit 1;
|
||||
}
|
||||
expected_sha256="${asset_digest#sha256:}"
|
||||
else
|
||||
checksum_asset_json="$(jq -ce --arg name "$installer_asset.sha256" '.assets[]? | select(.name == $name)' "$bootstrap_dir/release.json")" || {
|
||||
echo 'La release ne fournit pas le checksum publié du bundle.' >&2; exit 1;
|
||||
}
|
||||
checksum_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$checksum_asset_json")" || {
|
||||
echo 'URL HTTPS du checksum du bundle invalide.' >&2; exit 1;
|
||||
}
|
||||
curl --fail --silent --show-error --location "$checksum_url" --output "$bootstrap_dir/installers.zip.sha256"
|
||||
expected_sha256="$(awk -v name="$installer_asset" '$2 == name && $1 ~ /^[A-Fa-f0-9]{64}$/ { print tolower($1); count++ } END { if (count != 1) exit 1 }' "$bootstrap_dir/installers.zip.sha256")" || {
|
||||
echo 'Le checksum publié du bundle est invalide.' >&2; exit 1;
|
||||
}
|
||||
fi
|
||||
curl --fail --silent --show-error --location "$installer_url" --output "$bootstrap_dir/installers.zip"
|
||||
actual_sha256="$(sha256sum "$bootstrap_dir/installers.zip" | cut -d ' ' -f 1)"
|
||||
[[ "${actual_sha256,,}" == "${expected_sha256,,}" ]] || { echo 'Le SHA-256 du bundle téléchargé ne correspond pas à la release.' >&2; exit 1; }
|
||||
unzip -q "$bootstrap_dir/installers.zip" -d "$bootstrap_dir/bundle"
|
||||
packaged_script="$bootstrap_dir/bundle/install/install-server.sh"
|
||||
[[ -f "$packaged_script" ]] || { echo 'Le bundle ne contient pas install/install-server.sh.' >&2; exit 1; }
|
||||
HEIMDALL_INSTALLER_VERSION="$resolved_version" bash "$packaged_script" "$@"
|
||||
exit $?
|
||||
fi
|
||||
|
||||
copy_source_asset() {
|
||||
local relative_path="$1" destination_path="$2" asset_tmp="${2}.tmp.$$"
|
||||
if [[ -n "$REPO_ROOT" && -f "$REPO_ROOT/$relative_path" ]]; then
|
||||
cp "$REPO_ROOT/$relative_path" "$asset_tmp"
|
||||
else
|
||||
if ! curl --fail --silent --show-error --location \
|
||||
"$SOURCE_BASE_URL/$relative_path" --output "$asset_tmp"; then
|
||||
rm -f "$asset_tmp"
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
if [[ -e "$destination_path" ]]; then
|
||||
cp -p "$destination_path" "$destination_path.bak.$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
fi
|
||||
mv -f "$asset_tmp" "$destination_path"
|
||||
}
|
||||
|
||||
say "Installation de Heimdall Central (serveur + PostgreSQL)."
|
||||
destination="$(ask 'Dossier d’installation' "$HOME/heimdall")"
|
||||
compose_path="$destination/docker-compose.yml"
|
||||
env_path="$destination/.env"
|
||||
is_existing=no
|
||||
if [[ -e "$compose_path" || -e "$env_path" ]]; then
|
||||
if [[ ! -f "$compose_path" || ! -f "$env_path" || ! -f "$destination/secrets/db_password" ]]; then
|
||||
echo "Installation existante incomplète; aucun fichier n’a été modifié." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [[ "$(ask 'Installation existante : mettre à jour le Compose (sauvegarde du précédent), en conservant .env, secrets et volumes ?' 'o')" =~ ^([nN]|[nN][oO][nN]?)$ ]]; then
|
||||
say "Installation laissée inchangée."
|
||||
exit 0
|
||||
fi
|
||||
is_existing=yes
|
||||
else
|
||||
web_port="$(ask 'Port HTTP du serveur' '5000')"
|
||||
cors_origin="$(ask 'Origine(s) autorisée(s) par CORS' '*')"
|
||||
[[ "$web_port" =~ ^[0-9]{1,5}$ ]] && (( web_port >= 1 && web_port <= 65535 )) || { echo "Port invalide." >&2; exit 1; }
|
||||
[[ "$cors_origin" =~ ^[A-Za-z0-9*.,:/_-]+$ ]] || { echo "Origine CORS invalide." >&2; exit 1; }
|
||||
fi
|
||||
|
||||
mkdir -p "$destination/secrets" "$destination/optional" "$destination/optional/secrets"
|
||||
chmod 700 "$destination" "$destination/secrets" "$destination/optional"
|
||||
|
||||
if [[ "$is_existing" == no ]]; then
|
||||
db_password="$(openssl rand -hex 32)"
|
||||
jwt_key="$(openssl rand -hex 32)"
|
||||
jwt_refresh_key="$(openssl rand -hex 32)"
|
||||
printf '%s' "$db_password" > "$destination/secrets/db_password"
|
||||
chmod 600 "$destination/secrets/db_password"
|
||||
cat > "$env_path" <<EOF
|
||||
POSTGRES_DB=heimdall
|
||||
POSTGRES_USER=heimdall
|
||||
DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=${db_password}
|
||||
JWT__KEY=${jwt_key}
|
||||
JWT__REFRESHKEY=${jwt_refresh_key}
|
||||
JWT__ISSUER=heimdall
|
||||
JWT__AUDIENCE=heimdall-api
|
||||
ASPNETCORE_ENVIRONMENT=Production
|
||||
WEB_PORT=${web_port}
|
||||
Cors__AllowedOrigins=${cors_origin}
|
||||
TZ=Europe/Paris
|
||||
REDIS_PASSWORD=$(openssl rand -hex 32)
|
||||
HEIMDALL_DATA_VOLUME=heimdall_heimdall_data
|
||||
PLATE_OCR_ENABLED=false
|
||||
EOF
|
||||
chmod 600 "$env_path"
|
||||
else
|
||||
ensure_env_value() {
|
||||
local key="$1" value="$2"
|
||||
if ! grep -q "^${key}=" "$env_path"; then
|
||||
printf '\n%s=%s\n' "$key" "$value" >> "$env_path"
|
||||
fi
|
||||
}
|
||||
if ! grep -q '^DATABASE_URL=' "$env_path"; then
|
||||
echo "DATABASE_URL est absent du .env existant; complète-le sans changer le mot de passe PostgreSQL avant de relancer." >&2
|
||||
exit 1
|
||||
fi
|
||||
ensure_env_value JWT__KEY "$(openssl rand -hex 32)"
|
||||
ensure_env_value JWT__REFRESHKEY "$(openssl rand -hex 32)"
|
||||
ensure_env_value POSTGRES_DB heimdall
|
||||
ensure_env_value POSTGRES_USER heimdall
|
||||
ensure_env_value JWT__ISSUER heimdall
|
||||
ensure_env_value JWT__AUDIENCE heimdall-api
|
||||
ensure_env_value ASPNETCORE_ENVIRONMENT Production
|
||||
ensure_env_value WEB_PORT 5000
|
||||
ensure_env_value Cors__AllowedOrigins '*'
|
||||
ensure_env_value TZ Europe/Paris
|
||||
ensure_env_value REDIS_PASSWORD "$(openssl rand -hex 32)"
|
||||
ensure_env_value HEIMDALL_DATA_VOLUME heimdall_heimdall_data
|
||||
ensure_env_value PLATE_OCR_ENABLED false
|
||||
chmod 600 "$env_path"
|
||||
fi
|
||||
|
||||
compose_tmp="$(mktemp "$destination/.docker-compose.yml.XXXXXX")"
|
||||
trap 'rm -f "${compose_tmp:-}"' EXIT
|
||||
cat > "$compose_tmp" <<'COMPOSE'
|
||||
name: heimdall
|
||||
|
||||
services:
|
||||
postgresql:
|
||||
image: postgres:17-alpine
|
||||
pull_policy: always
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
|
||||
secrets: [db_password]
|
||||
volumes: [pgdata:/var/lib/postgresql/data]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 30s
|
||||
restart: unless-stopped
|
||||
networks: [heimdall-net]
|
||||
|
||||
heimdall:
|
||||
image: eltruncho/heimdall:latest
|
||||
pull_policy: always
|
||||
labels:
|
||||
com.centurylinklabs.watchtower.enable: "true"
|
||||
environment:
|
||||
DATABASE_URL: ${DATABASE_URL:?missing DATABASE_URL}
|
||||
JWT__Issuer: ${JWT__ISSUER}
|
||||
JWT__Audience: ${JWT__AUDIENCE}
|
||||
JWT__KEY: ${JWT__KEY:?missing JWT__KEY}
|
||||
JWT__REFRESHKEY: ${JWT__REFRESHKEY:?missing JWT__REFRESHKEY}
|
||||
ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT}
|
||||
ASPNETCORE_URLS: http://+:8080
|
||||
Cors__AllowedOrigins: ${Cors__AllowedOrigins}
|
||||
PlateOcr__Enabled: ${PLATE_OCR_ENABLED:-false}
|
||||
ports: ["${WEB_PORT}:8080"]
|
||||
volumes:
|
||||
- heimdall_data:/var/lib/heimdall
|
||||
- heimdall_data:/app/data
|
||||
depends_on:
|
||||
postgresql:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--output-document=/dev/null", "http://127.0.0.1:8080/healthz"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
restart: unless-stopped
|
||||
networks: [heimdall-net]
|
||||
|
||||
watchtower:
|
||||
image: nickfedor/watchtower:1.23.2
|
||||
pull_policy: always
|
||||
command: ["--cleanup", "--label-enable", "--interval", "86400"]
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
restart: unless-stopped
|
||||
networks: [heimdall-net]
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
heimdall_data:
|
||||
|
||||
secrets:
|
||||
db_password:
|
||||
file: ./secrets/db_password
|
||||
|
||||
networks:
|
||||
heimdall-net:
|
||||
name: heimdall-net
|
||||
driver: bridge
|
||||
COMPOSE
|
||||
chmod 600 "$compose_tmp"
|
||||
docker compose --env-file "$env_path" -f "$compose_tmp" config --quiet
|
||||
if [[ "$is_existing" == yes ]]; then
|
||||
backup_path="$compose_path.bak.$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
cp -p "$compose_path" "$backup_path"
|
||||
say "Ancien Compose sauvegardé dans $backup_path"
|
||||
fi
|
||||
mv -f "$compose_tmp" "$compose_path"
|
||||
compose_tmp=""
|
||||
trap - EXIT
|
||||
|
||||
declare -a selected=()
|
||||
for service in ollama ntfy rustfs coturn redis backup; do
|
||||
if [[ "$service" == backup ]]; then
|
||||
prompt="Activer les sauvegardes planifiées (nécessite une configuration dédiée) ?"
|
||||
else
|
||||
prompt="Installer le service optionnel ${service} ?"
|
||||
fi
|
||||
if [[ "$(ask "$prompt" 'n')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
|
||||
selected+=("$service")
|
||||
copy_source_asset "docker/docker-compose.${service}.yml" \
|
||||
"$destination/optional/docker-compose.${service}.yml"
|
||||
chmod 600 "$destination/optional/docker-compose.${service}.yml"
|
||||
fi
|
||||
done
|
||||
|
||||
say "Compose généré dans $destination/docker-compose.yml"
|
||||
say "Variables protégées dans $destination/.env (mode 600), secret PostgreSQL dans secrets/ (mode 600)."
|
||||
say "Validation du Compose avant démarrage…"
|
||||
start_core=no
|
||||
if [[ "$(ask 'Démarrer PostgreSQL et Heimdall maintenant ?' 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
|
||||
docker compose --env-file "$env_path" -f "$compose_path" up -d
|
||||
start_core=yes
|
||||
fi
|
||||
|
||||
for service in "${selected[@]}"; do
|
||||
case "$service" in
|
||||
rustfs)
|
||||
printf '%s' "heimdall$(openssl rand -hex 8)" > "$destination/optional/secrets/rustfs_access_key"
|
||||
openssl rand -hex 32 > "$destination/optional/secrets/rustfs_secret_key"
|
||||
chmod 600 "$destination/optional/secrets/rustfs_access_key" "$destination/optional/secrets/rustfs_secret_key"
|
||||
;;
|
||||
coturn)
|
||||
openssl rand -hex 32 > "$destination/optional/secrets/coturn_secret"
|
||||
chmod 600 "$destination/optional/secrets/coturn_secret"
|
||||
;;
|
||||
backup)
|
||||
mkdir -p "$destination/optional/scripts"
|
||||
for script_name in backup.sh backup-protected-data.sh backup-rustfs.sh restore.sh restore-protected-data.sh; do
|
||||
copy_source_asset "docker/scripts/$script_name" \
|
||||
"$destination/optional/scripts/$script_name"
|
||||
done
|
||||
chmod 700 "$destination/optional/scripts" "$destination/optional/scripts"/*.sh
|
||||
cp "$destination/secrets/db_password" "$destination/optional/secrets/db_password"
|
||||
chmod 600 "$destination/optional/secrets/db_password"
|
||||
;;
|
||||
esac
|
||||
if [[ "$start_core" == yes ]] && [[ "$(ask "Démarrer le service optionnel ${service} ?" 'o')" =~ ^([oO]|[oO][uU][iI]|[yY]|[yY][eE][sS])$ ]]; then
|
||||
docker compose --project-name "heimdall-${service}" --env-file "$destination/.env" \
|
||||
-f "$destination/optional/docker-compose.${service}.yml" up -d
|
||||
else
|
||||
say "Service ${service} préparé dans $destination/optional/."
|
||||
fi
|
||||
done
|
||||
say "Configurez ensuite les intégrations activées depuis les paramètres de Central; leurs valeurs restent gérées par l’IHM."
|
||||
@@ -35,50 +35,93 @@ Heimdall.Web (Api + Blazor UI) Heimdall.Agent
|
||||
|
||||
## Démarrage rapide
|
||||
|
||||
### 1. Production (images Docker Hub)
|
||||
### 1. Production : installer le Central sans cloner le dépôt
|
||||
|
||||
Prérequis Linux : Docker Engine avec le plugin Compose, OpenSSL et curl; le
|
||||
compte doit pouvoir utiliser Docker. La commande télécharge et exécute le script
|
||||
interactif directement depuis le dépôt :
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Éditer les secrets (JWT__Key, mots de passe)
|
||||
nano .env
|
||||
|
||||
docker compose -f docker/docker-compose.prod.yml up -d
|
||||
SOURCE_BASE_URL="${HEIMDALL_SOURCE_BASE_URL:-https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main}"
|
||||
curl -fsSL "$SOURCE_BASE_URL/install/install-server.sh" | HEIMDALL_SOURCE_BASE_URL="$SOURCE_BASE_URL" bash
|
||||
```
|
||||
|
||||
**Accès** :
|
||||
L’installateur demande un terminal interactif et lit ses réponses directement
|
||||
depuis le terminal. Il crée le Compose Central + PostgreSQL, le `.env` protégé
|
||||
et le secret de base de données; les Compose et scripts facultatifs sont
|
||||
téléchargés seulement si tu les sélectionnes. L’image Central vient de Docker
|
||||
Hub. Les paramètres applicatifs et intégrations se configurent ensuite dans
|
||||
l’IHM.
|
||||
|
||||
Sur Windows 10/11 avec Docker Desktop configuré en conteneurs Linux, ouvre
|
||||
PowerShell avec les droits nécessaires pour utiliser Docker et lance :
|
||||
|
||||
```powershell
|
||||
$sourceBase = if ($env:HEIMDALL_SOURCE_BASE_URL) { $env:HEIMDALL_SOURCE_BASE_URL.TrimEnd('/') } else { 'https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main' }
|
||||
$installer = Join-Path $env:TEMP 'heimdall-install-server.ps1'
|
||||
Invoke-WebRequest -UseBasicParsing -Uri "$sourceBase/install/install-server.ps1" -OutFile $installer
|
||||
Set-ExecutionPolicy -Scope Process Bypass -Force
|
||||
& $installer
|
||||
Remove-Item $installer
|
||||
```
|
||||
|
||||
Le contournement PowerShell est limité au processus courant. Une stratégie
|
||||
imposée par une GPO peut toujours interdire l’exécution. Les deux installateurs
|
||||
génèrent les secrets localement et ne les envoient pas au dépôt. Les installateurs utilisent cette URL source par défaut. Pour installer depuis
|
||||
une révision précise, définis `HEIMDALL_SOURCE_BASE_URL` sur son URL
|
||||
`raw/commit/<SHA>` avant la commande; la même valeur sert aux fichiers
|
||||
facultatifs téléchargés par l’installateur. Une installation sans accès Internet
|
||||
doit recevoir également les scripts Compose et de sauvegarde choisis.
|
||||
|
||||
Voir aussi le [guide de déploiement](docs/docker-compose.md).
|
||||
|
||||
Une fois le serveur démarré, ouvrez `http://<adresse-du-serveur>:5000` (ou le
|
||||
port choisi dans l’installateur). Choisissez une origine CORS correspondant à
|
||||
l’URL utilisée par les navigateurs clients.
|
||||
|
||||
### 2. Installer un Agent depuis le Central
|
||||
|
||||
Créez ou ouvrez le site dans l’IHM, puis utilisez le panneau d’installation du
|
||||
site. Choisissez Linux, Windows ou Docker et la méthode proposée. Pour Linux et
|
||||
Windows, copiez la commande affichée sur l’hôte distant : elle télécharge le
|
||||
script depuis le Central et l’exécute avec les identifiants propres à ce site.
|
||||
L’installation Linux peut créer un service systemd; l’installation Windows
|
||||
peut créer un service Windows (PowerShell administrateur requis). Pour Docker,
|
||||
utilisez le Compose généré par l’IHM, qui suit le tag `latest`. Aucun fichier de
|
||||
clé ni Compose de production ne doit être copié depuis le dépôt. Voir le
|
||||
[guide de signature et de mise à jour Agent](docs/agent-release-signing.md).
|
||||
Le Compose Docker monte le socket Docker de l’hôte pour permettre les mises à
|
||||
jour pilotées par Central; ce socket donne à l’Agent un contrôle étendu sur
|
||||
l’hôte. N’installez ce mode que sur un hôte de confiance.
|
||||
|
||||
### 3. Développement local
|
||||
|
||||
```bash
|
||||
cp .env.example docker/.env
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d
|
||||
```
|
||||
|
||||
Le Compose de développement construit Central depuis les sources et démarre
|
||||
PostgreSQL. Pour développer l’Agent localement, utilisez séparément
|
||||
`docker/docker-compose.agent.dev.yml` avec un token de site de développement.
|
||||
|
||||
**Accès locaux par défaut** :
|
||||
|
||||
| Service | URL |
|
||||
|---------|-----|
|
||||
| Web UI + API | http://localhost:5000 |
|
||||
| API | http://localhost:5000/api |
|
||||
| API Docs (dev) | http://localhost:5000/scalar |
|
||||
| Alarik Console | http://localhost:9001 |
|
||||
|
||||
### 2. Build local (développement)
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Éditer les secrets
|
||||
nano .env
|
||||
|
||||
docker compose -f docker/docker-compose.yml up -d
|
||||
```
|
||||
|
||||
### 3. Développement avec hot-reload
|
||||
### Développement avec hot-reload
|
||||
|
||||
Prérequis : .NET 10 SDK, Docker
|
||||
|
||||
```bash
|
||||
# Démarrer l'infrastructure (PostgreSQL + Alarik)
|
||||
docker compose -f docker/docker-compose.yml -f docker/docker-compose.override.yml up -d
|
||||
# Démarrer PostgreSQL sans lancer le serveur conteneurisé
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml up -d postgresql
|
||||
|
||||
# Lancer l'API (terminal 1)
|
||||
make dev-api
|
||||
|
||||
# Lancer le worker (terminal 2)
|
||||
make dev-worker
|
||||
|
||||
# Lancer le web UI (terminal 3)
|
||||
# L'API, l'UI Blazor et les jobs tournent dans le même processus
|
||||
make dev-web
|
||||
```
|
||||
|
||||
@@ -86,16 +129,14 @@ make dev-web
|
||||
|
||||
```bash
|
||||
make build # Build .NET
|
||||
make test # Run tests (~1550+ tests unitaires + intégration)
|
||||
make test # Exécute les projets de tests de Heimdall.slnx
|
||||
make docker-up # docker compose up (dev)
|
||||
make docker-down # docker compose down (dev)
|
||||
make docker-build # Rebuild images without cache
|
||||
make docker-logs # Tail logs
|
||||
make docker-ps # List running services
|
||||
make docker-reset # Stop + remove everything
|
||||
make dev-api # API en dev
|
||||
make dev-web # Web UI en dev
|
||||
make dev-worker # Workers en dev
|
||||
make dev-web # API + Web UI + jobs dans un processus
|
||||
make migration-add NAME=xxx # Ajouter une migration EF
|
||||
```
|
||||
|
||||
@@ -107,24 +148,28 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall :
|
||||
|
||||
| Fichier | Usage | Description |
|
||||
|---------|-------|-------------|
|
||||
| `docker-compose.yml` | Développement | Build local des images + infra complète |
|
||||
| `docker-compose.prod.yml` | Production | Images pré-buildées depuis Docker Hub |
|
||||
| `docker-compose.local.yml` | Production (override) | Image locale tant que la CI n'a pas publié les fixes |
|
||||
| `docker-compose.yml` | Développement | PostgreSQL et Central local |
|
||||
| `docker-compose.prod.yml` | Production | PostgreSQL et Central depuis Docker Hub |
|
||||
| `docker-compose.agent.dev.yml` | Développement Agent | Agent local autonome, connecté au Central de développement |
|
||||
| `docker-compose.{backup,coturn,ntfy,ollama,redis,rustfs}.yml` | Logiciels facultatifs | Un Compose isolé par logiciel |
|
||||
| `docker-compose.gpu-{amd,intel,nvidia}.yml` | Matériel Agent facultatif | Overlays d’inventaire GPU; n’activent pas l’inférence GPU |
|
||||
| `Dockerfile` | Build | Image Central (UI + API + jobs) |
|
||||
| `Dockerfile.agent` | Build | Image agent avec FFmpeg |
|
||||
| `docker/secrets/` | Production | Clés secrètes (JWT, DB, RabbitMQ, Coturn, etc.) |
|
||||
| Docker Hub | Publication | Images `eltruncho/heimdall` et `eltruncho/heimdall-agent` |
|
||||
| `install/install-server.sh` | Production Linux | Génère le Compose Central, le `.env` et le secret PostgreSQL hors du dépôt; utilisable depuis le dépôt ou téléchargé en ligne |
|
||||
| `install/install-server.ps1` | Production Windows | Même parcours interactif PowerShell, sans cloner le dépôt |
|
||||
|
||||
Pour la production, utilisez l’installateur serveur interactif ci-dessus et les commandes/Compose Agent fournis par l’IHM. `docker-compose.prod.yml` reste disponible pour une configuration manuelle avancée; il exige que l’opérateur prépare correctement `.env` et `docker/secrets/db_password`. Aucun Compose Agent de production statique n’est conservé dans le dépôt.
|
||||
|
||||
### Services
|
||||
|
||||
| Service | Image | Port par défaut | Dépend de |
|
||||
|---|---|---|---|
|
||||
| `postgresql` | `postgres:17-alpine` | 5432 | — |
|
||||
| `alarik` | `ghcr.io/achtungsoftware/alarik` | 9000 | — |
|
||||
| `alarik-console` | `ghcr.io/achtungsoftware/alarik-console` | 9001 | alarik |
|
||||
| `rustfs` | `rustfs/rustfs:latest` | 9000 (S3), 9001 (console) | — |
|
||||
| `heimdall` | `heimdall:latest` (dev) / `eltruncho/heimdall:latest` (prod) | 5000 | postgresql (healthy) |
|
||||
| `heimdall-agent` | `heimdall-agent:latest` (dev) / `eltruncho/heimdall-agent:latest` (prod) | — | heimdall |
|
||||
| `heimdall-agent` | `heimdall-agent:latest` (dev) / `eltruncho/heimdall-agent@digest` (prod) | — | heimdall |
|
||||
| `ntfy` | `binwiederhier/ntfy` | 8080 | — |
|
||||
| `rabbitmq` | `rabbitmq:3-management` | 5672/15672 | — |
|
||||
| `coturn` | `coturn/coturn:4.6` | 3478 | — |
|
||||
| `ollama` | `ollama/ollama:latest` | 11434 | — |
|
||||
| `redis` | `redis:7-alpine` | 6379 | — |
|
||||
@@ -134,60 +179,57 @@ Le dossier `docker/` contient tout nécessaire pour déployer Heimdall :
|
||||
| Volume | Monté sur | Persiste |
|
||||
|--------|-----------|----------|
|
||||
| `pgdata` | `/var/lib/postgresql/data` | Données PostgreSQL |
|
||||
| `alarik_storage` | `/app/Storage` | Objets S3 (vidéos, snapshots) |
|
||||
| `rustfs_data` | `/data` | Objets S3 (vidéos, snapshots) |
|
||||
| `agent_state` | `/var/lib/heimdall` | Identité et état des agents |
|
||||
| `heimdall_data` | `/var/lib/heimdall` | Données locales (Central) |
|
||||
| `ntfy_data` | `/var/lib/ntfy` | Notifications ntfy |
|
||||
| `ollama_data` | `/root/.ollama` | Modèles LLM |
|
||||
| `redis_data` | `/data` | Cache Redis |
|
||||
| `rabbitmq_data` | `/var/lib/rabbitmq` | Messages RabbitMQ |
|
||||
|
||||
### Réseau
|
||||
|
||||
Tous les services sont sur le réseau `heimdall-net` (bridge). La communication interne
|
||||
se fait par noms de service (ex: `http://heimdall:8080`). L'agent utilise le réseau hôte
|
||||
(`network_mode: host`) pour découvrir les caméras sur le LAN.
|
||||
Central, PostgreSQL et les services facultatifs utilisent le réseau `heimdall-net`
|
||||
(bridge); la communication interne se fait par noms de service (ex. `http://heimdall:8080`).
|
||||
L’Agent Docker de développement utilise le réseau hôte (`network_mode: host`) pour
|
||||
découvrir les caméras du LAN. Les Agents natifs s’exécutent directement sur leur hôte.
|
||||
|
||||
### Variables d'environnement
|
||||
### Configuration
|
||||
|
||||
| Variable | Default | Services | Description |
|
||||
|----------|---------|----------|-------------|
|
||||
| `DATABASE_URL` | `Host=postgresql;...` | heimdall | Connexion PostgreSQL |
|
||||
| `POSTGRES_DB` | `heimdall` | postgresql | Nom de la base |
|
||||
| `POSTGRES_USER` | `heimdall` | postgresql | Utilisateur PostgreSQL |
|
||||
| `POSTGRES_PASSWORD` | `heimdall` | postgresql | Mot de passe PostgreSQL |
|
||||
| `JWT__Key` | (required) | heimdall | Clé JWT (32+ caractères) |
|
||||
| `JWT__RefreshKey` | (required) | heimdall | Clé refresh JWT (32+ caractères) |
|
||||
| `JWT__Issuer` | `heimdall` | heimdall | Issuer JWT |
|
||||
| `JWT__Audience` | `heimdall-api` | heimdall | Audience JWT |
|
||||
| `ASPNETCORE_ENVIRONMENT` | `Production` | heimdall, agent | Environnement .NET |
|
||||
| `Cors__AllowedOrigins` | `*` | heimdall | Origines CORS |
|
||||
| `SENTRY_DSN` | `(optional)` | heimdall, agent | Sentry/GlitchTip DSN |
|
||||
| `HEIMDALL_CENTRAL_URL` | `http://localhost:5010` | agent | URL publique du Central (API + UI) |
|
||||
| `HEIMDALL_SITE_TOKEN` | (required for agent) | agent | Token d'enregistrement |
|
||||
| `HEIMDALL_AGENT_NAME` | `agent-01` | agent | Nom de l'agent |
|
||||
| `HEIMDALL_HEARTBEAT_INTERVAL` | `30` | agent | Intervalle heartbeat (s) |
|
||||
| `HEIMDALL_REGISTRATION_RETRIES` | `5` | agent | Tentatives d'enregistrement |
|
||||
| `ALARIK_API_PORT` | `9000` | alarik | Port API Alarik |
|
||||
| `ALARIK_CONSOLE_PORT` | `9001` | alarik-console | Port console Alarik |
|
||||
| `ALARIK_ADMIN_USERNAME` | `heimdall` | alarik | Admin Alarik |
|
||||
| `ALARIK_ADMIN_PASSWORD` | `heimdall123` | alarik | Password Alarik |
|
||||
| `ALARIK_JWT` | (required) | alarik | JWT secret Alarik |
|
||||
| `WEB_PORT` | `5000` | heimdall | Port exposé (API + UI unifiés) |
|
||||
| `RABBITMQ_USER` | `heimdall` | heimdall, agent | Utilisateur RabbitMQ |
|
||||
| `RABBITMQ_PASSWORD` | `heimdall123` | heimdall, agent | Password RabbitMQ |
|
||||
| `COTURN_SECRET` | (required) | coturn | Secret TURN |
|
||||
| `OLLAMA_PORT` | `11434` | ollama | Port Ollama |
|
||||
L’installateur serveur génère les secrets techniques requis par Central et
|
||||
PostgreSQL. Configurez dans l’IHM les intégrations (courriel, notifications,
|
||||
IA, stockage et source des releases), puis les réglages qui peuvent être
|
||||
spécifiques à un site sur la page de ce site. `.env.example` et
|
||||
`docker/docker-compose.agent.dev.yml` servent au développement local; leurs
|
||||
valeurs d’exemple ne conviennent pas à une installation exposée.
|
||||
|
||||
### Migration depuis Alarik
|
||||
|
||||
RustFS expose la même API S3 utilisée par Heimdall. Après démarrage, ouvrez
|
||||
`http://localhost:9001`, puis configurez dans **Paramètres → Stockage** l'endpoint
|
||||
`http://rustfs:9000`, le bucket et les identifiants RustFS. L'API Heimdall et les
|
||||
appels S3 restent inchangés.
|
||||
|
||||
Le volume `rustfs_data` est neuf; les objets déjà stockés dans Alarik n'y sont pas
|
||||
copiés automatiquement. Avant de retirer l'ancien service, arrêtez les écritures et
|
||||
copiez les objets avec `mc mirror`, en configurant les alias `old` et `new` avec les
|
||||
endpoints et identifiants correspondants :
|
||||
|
||||
```bash
|
||||
mc mirror old/heimdall new/heimdall
|
||||
```
|
||||
|
||||
Vérifiez les snapshots et enregistrements depuis Heimdall avant de supprimer
|
||||
l'ancien volume ou service.
|
||||
|
||||
### Dépannage Docker
|
||||
|
||||
**Les conteneurs ne démarrent pas :**
|
||||
```bash
|
||||
# Voir les logs de tous les services
|
||||
docker compose -f docker/docker-compose.yml logs -f
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml logs -f
|
||||
|
||||
# Vérifier l'état
|
||||
docker compose -f docker/docker-compose.yml ps
|
||||
docker compose --env-file docker/.env -f docker/docker-compose.yml ps
|
||||
```
|
||||
|
||||
**PostgreSQL n'est pas prêt :** Le healthcheck attend 30s avant de considérer
|
||||
@@ -205,12 +247,24 @@ Générer un token via `POST /api/sites/{id}/tokens` sur l'API.
|
||||
|
||||
## Authentification
|
||||
|
||||
La source des mises à jour se configure dans les paramètres globaux de Central.
|
||||
L'agent lit le nom et le digest
|
||||
de l'image dans le manifeste authentifié de Central ; le dépôt d'image Agent est
|
||||
publié dans `eltruncho/heimdall-agent` et celui du serveur dans
|
||||
`eltruncho/heimdall` sur Docker Hub.
|
||||
La [procédure de signature des releases agent](docs/agent-release-signing.md)
|
||||
décrit la clé publique locale requise pour les mises à jour natives et Docker.
|
||||
|
||||
| Méthode | Usage | Endpoints |
|
||||
|---------|-------|-----------|
|
||||
| **JWT** | Humains (Admin/Supervisor/Viewer) | `POST /api/auth/login` |
|
||||
| **API Key** | Agents | `Authorization: Bearer <key>` |
|
||||
| **API Key** | Agents (REST) | `X-API-Key: <key>` |
|
||||
| **2FA TOTP** | Sécurité renforcée | `POST /api/auth/2fa/verify` |
|
||||
|
||||
Au premier démarrage, ouvrez `/setup` pour créer le compte administrateur initial. L’assistant
|
||||
n’est disponible que tant que la base ne contient aucun compte, puis redirige vers la connexion.
|
||||
Les créations de compte suivantes sont réservées aux administrateurs depuis la gestion des utilisateurs.
|
||||
|
||||
Compte par défaut (dev) :
|
||||
- `admin@heimdall.test` / `Admin123!Pass` — Admin
|
||||
|
||||
@@ -220,9 +274,10 @@ Compte par défaut (dev) :
|
||||
|
||||
| Méthode | Endpoint | Auth | Description |
|
||||
|---------|----------|------|-------------|
|
||||
| POST | `/api/auth/register` | - | Créer un compte |
|
||||
| GET | `/api/auth/bootstrap-status` | - | Indiquer si la configuration initiale est requise |
|
||||
| POST | `/api/auth/bootstrap-admin` | - (une seule fois, base vide) | Créer le premier administrateur |
|
||||
| POST | `/api/auth/login` | - | Connexion |
|
||||
| POST | `/api/auth/2fa/verify` | JWT | Vérification 2FA |
|
||||
| POST | `/api/auth/2fa/verify` | Challenge après mot de passe | Vérification TOTP ou code de récupération |
|
||||
| POST | `/api/auth/refresh` | JWT | Rafraîchir token |
|
||||
| GET | `/api/sites` | JWT | Lister les sites |
|
||||
| POST | `/api/sites` | JWT | Créer un site |
|
||||
@@ -230,9 +285,9 @@ Compte par défaut (dev) :
|
||||
| PUT | `/api/sites/{id}` | JWT | Modifier un site |
|
||||
| DELETE | `/api/sites/{id}` | JWT | Supprimer un site |
|
||||
| POST | `/api/sites/{id}/tokens` | JWT | Générer token agent |
|
||||
| GET | `/api/users` | JWT | Lister utilisateurs |
|
||||
| POST | `/api/users` | JWT | Créer utilisateur |
|
||||
| GET | `/api/users/{id}` | JWT | Détail utilisateur |
|
||||
| GET | `/api/users` | Admin | Lister utilisateurs |
|
||||
| POST | `/api/users` | Admin | Créer utilisateur |
|
||||
| GET | `/api/users/{id}` | Admin | Détail utilisateur |
|
||||
| PUT | `/api/users/{id}/roles` | JWT | Modifier rôles |
|
||||
| POST | `/api/users/{id}/lock` | JWT | Verrouiller compte |
|
||||
| POST | `/api/users/{id}/reset-password` | JWT | Reset mot de passe |
|
||||
@@ -252,9 +307,16 @@ Compte par défaut (dev) :
|
||||
| GET | `/api/settings` | JWT | Configuration |
|
||||
| PUT | `/api/settings` | JWT | Modifier configuration |
|
||||
| GET | `/healthz` | - | Health check |
|
||||
| POST | `/api/cameras/{id}/snapshot` | API Key | Upload snapshot |
|
||||
| GET | `/api/cameras/{id}/events` | JWT | Événements d'une caméra |
|
||||
| POST | `/api/cameras/discover` | JWT | Découverte de caméras |
|
||||
| PUT | `/api/events/{id}/snapshot/content` | API Key | Téléverser un JPEG borné pour un événement de la caméra de l’agent |
|
||||
| GET | `/api/events/{id}/snapshot/content` | JWT/cookie | Lire le JPEG stocké après contrôle d’accès à la caméra |
|
||||
| POST | `/api/events/{id}/snapshot` | API Key | Ancienne route retirée (`410 Gone`) |
|
||||
| GET | `/api/events/camera/{cameraId}` | JWT | Événements récents d'une caméra (`count` optionnel) |
|
||||
| POST | `/api/cameras/{id}/snapshot` | JWT/cookie | Demander une nouvelle capture à l'agent assigné ; retourne un `requestId` corrélé à l'événement produit |
|
||||
| GET | `/api/events` | JWT | Rechercher des événements paginés et filtrés |
|
||||
| POST | `/api/agents/{id}/discovery` | API Key | Soumettre les résultats de découverte de caméras d'un agent |
|
||||
| POST | `/api/cameras/{id}/toggle-status` | JWT | Activer ou désactiver une caméra |
|
||||
|
||||
Le [backlog Gitea](https://sources.tordais.cc/arnaud.dartois/Heimdall/issues) conserve les travaux, preuves d’acceptation et validations restantes.
|
||||
|
||||
---
|
||||
|
||||
@@ -262,7 +324,7 @@ Compte par défaut (dev) :
|
||||
|
||||
- **JWT** 15min access + refresh token
|
||||
- **API Key** HMACSHA256 + comparaison constant-time
|
||||
- **Rate limiting** : 10 req/min auth, 200 req/min API
|
||||
- **Rate limiting** : authentification 5 requêtes/15 min, API 100/min, 2FA 5/min, snapshots 1000/min (limites configurées dans `Heimdall.Web`)
|
||||
- **CORS** configurable via `Cors__AllowedOrigins`
|
||||
- **Journal d'audit** : toutes les actions critiques sont loguées
|
||||
- **ASP.NET Identity** : lockout après 5 tentatives
|
||||
@@ -275,17 +337,10 @@ Compte par défaut (dev) :
|
||||
|
||||
```bash
|
||||
# Tout exécuter
|
||||
dotnet test
|
||||
dotnet test Heimdall.slnx
|
||||
```
|
||||
|
||||
| Suite | Tests | Ce qui est testé |
|
||||
|-------|-------|------------------|
|
||||
| Domain | ~172 | Entités (Site, Agent, Camera), énums, primitives |
|
||||
| Application | ~476 | Handlers CQRS (Auth, Sites, Users, Caméras, Agents), validators, mappings |
|
||||
| Infrastructure | ~207 | EF Core, Identity, JWT/API Key, jobs, discovery |
|
||||
| Web | ~350 | Composants bUnit (pages IHM), clients API, hubs |
|
||||
| Agent | ~346 | Registration, heartbeat, état, config, FFmpeg, métriques |
|
||||
| **Total** | **~1551** | Dénombrement réel par attributs `[Fact]`/`[Theory]` |
|
||||
La solution inclut les tests du domaine, de l’application, de l’infrastructure, de l’API/Web, de l’agent, les tests d’intégration PostgreSQL et les tests E2E Playwright. Le nombre de tests évolue avec le code; la CI exécute les suites avec `bash scripts/ci/verify.sh`.
|
||||
|
||||
---
|
||||
|
||||
@@ -294,15 +349,14 @@ dotnet test
|
||||
| Technologie | Version |
|
||||
|-------------|---------|
|
||||
| .NET | 10.0 |
|
||||
| EF Core | 10.0.8 |
|
||||
| EF Core | 10.0.13 |
|
||||
| Npgsql | 10.0.3 |
|
||||
| PostgreSQL | 17 |
|
||||
| Blazor Server | 10.0 |
|
||||
| MudBlazor | 9.1.0 |
|
||||
| MudBlazor | 9.8.0 |
|
||||
| Hangfire | 1.8.17 |
|
||||
| Alarik (S3) | latest |
|
||||
| RustFS (S3) | latest |
|
||||
| SignalR | 10.0 |
|
||||
| MassTransit / RabbitMQ | 8.x / 3.x |
|
||||
| SIPSorcery (WebRTC) | 10.0 |
|
||||
| ONNX Runtime | 1.20+ |
|
||||
| xUnit + Shouldly | — |
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["config:best-practices"],
|
||||
"timezone": "Europe/Berlin",
|
||||
"schedule": ["before 06:00 on monday"],
|
||||
"prConcurrentLimit": 5,
|
||||
"lockFileMaintenance": {"enabled": true},
|
||||
"packageRules": [
|
||||
{
|
||||
"matchManagers": ["nuget"],
|
||||
"groupName": ".NET dependencies"
|
||||
},
|
||||
{
|
||||
"matchManagers": ["dockerfile", "docker-compose", "github-actions"],
|
||||
"groupName": "CI and container images"
|
||||
}
|
||||
]
|
||||
}
|
||||
Executable
+494
@@ -0,0 +1,494 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline acceptance for one tagged image and installer release with synthetic doubles."""
|
||||
import base64
|
||||
import email
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from email import policy
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REPOSITORY = 'arnaud.dartois/Heimdall'
|
||||
DOCKER_TOKEN = 'offline-docker-token-not-valid'
|
||||
RELEASE_TOKEN = 'offline-gitea-token-not-valid'
|
||||
SERVER_DIGEST = 'sha256:' + '1' * 64
|
||||
AGENT_DIGEST = 'sha256:' + '2' * 64
|
||||
GPU_AGENT_DIGEST = 'sha256:' + '3' * 64
|
||||
|
||||
|
||||
def run(command, *, cwd, env, label):
|
||||
result = subprocess.run(command, cwd=cwd, env=env, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
output = (result.stdout + result.stderr).replace(DOCKER_TOKEN, '[redacted]').replace(RELEASE_TOKEN, '[redacted]')
|
||||
if label == 'publish.sh':
|
||||
provenance_path = cwd / 'artifacts/packages/provenance.json'
|
||||
if provenance_path.exists():
|
||||
output += '\nOffline provenance: ' + json.dumps(json.loads(provenance_path.read_text()), sort_keys=True)
|
||||
raise RuntimeError(f'{label} failed ({result.returncode}):\n{output[-12000:]}')
|
||||
return result.stdout
|
||||
|
||||
|
||||
def main():
|
||||
artifacts_dir = ROOT / 'artifacts'
|
||||
if artifacts_dir.exists():
|
||||
raise RuntimeError('Refusing to overwrite or remove an existing artifacts/ directory; run from a clean worktree.')
|
||||
with tempfile.TemporaryDirectory(prefix='heimdall-release-offline-') as temp_name:
|
||||
temp = Path(temp_name)
|
||||
cert = temp / 'localhost.pem'
|
||||
private_cert_key = temp / 'localhost-key.pem'
|
||||
release_key = temp / 'release-key.pem'
|
||||
fakebin = temp / 'bin'
|
||||
fakebin.mkdir()
|
||||
docker_log = temp / 'docker-commands.jsonl'
|
||||
release_state = {'release': None, 'assets': {}, 'authorized': 0}
|
||||
|
||||
subprocess.run([
|
||||
'openssl', 'req', '-x509', '-newkey', 'rsa:2048', '-sha256', '-days', '1', '-nodes',
|
||||
'-keyout', str(private_cert_key), '-out', str(cert), '-subj', '/CN=127.0.0.1',
|
||||
'-addext', 'subjectAltName=IP:127.0.0.1',
|
||||
], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
subprocess.run(['openssl', 'ecparam', '-name', 'prime256v1', '-genkey', '-noout', '-out', str(release_key)],
|
||||
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
signing_key_b64 = base64.b64encode(release_key.read_bytes()).decode('ascii')
|
||||
|
||||
docker_stub = r'''#!/usr/bin/env python3
|
||||
import json, os, sys
|
||||
args = sys.argv[1:]
|
||||
log = os.environ['OFFLINE_DOCKER_LOG']
|
||||
with open(log, 'a') as f: f.write(json.dumps(args) + '\n')
|
||||
if args[:1] == ['build']:
|
||||
sys.exit(12) # Release publication must reuse the scanned image builds.
|
||||
if args[:2] == ['login', 'docker.io']:
|
||||
if sys.stdin.read().strip() != os.environ['DOCKERHUB_TOKEN'] or os.environ.get('DOCKERHUB_USERNAME') != 'offline-user':
|
||||
sys.exit(11)
|
||||
sys.exit(0)
|
||||
if args[:2] == ['compose', 'version']:
|
||||
marker = os.environ.get('OFFLINE_STOP_COMPOSE_MARKER')
|
||||
if marker:
|
||||
try:
|
||||
open(marker, 'x').close()
|
||||
except FileExistsError:
|
||||
sys.exit(37)
|
||||
print('Docker Compose version v2.offline')
|
||||
sys.exit(0)
|
||||
if args[:1] == ['pull']:
|
||||
sys.exit(0) # Synthetic registry pull; never contact Docker Hub.
|
||||
if args[:1] == ['tag']:
|
||||
sys.exit(0)
|
||||
if args[:1] == ['push']:
|
||||
sys.exit(0) # Simulated push only; no registry client exists in this stub.
|
||||
if args[:2] == ['image', 'inspect']:
|
||||
image = args[2].split(':', 1)[0]
|
||||
if image.endswith('heimdall-agent-gpu'):
|
||||
digest = os.environ['OFFLINE_GPU_DIGEST']
|
||||
elif image.endswith('heimdall-agent'):
|
||||
digest = os.environ['OFFLINE_AGENT_DIGEST']
|
||||
else:
|
||||
digest = os.environ['OFFLINE_SERVER_DIGEST']
|
||||
if '--format' in args and 'RepoDigests' in args[args.index('--format') + 1]:
|
||||
print(image + '@' + digest)
|
||||
elif '--format' in args and 'org.opencontainers.image.revision' in args[args.index('--format') + 1]:
|
||||
print(os.environ['OFFLINE_COMMIT'])
|
||||
sys.exit(0)
|
||||
if args[:1] == ['save']:
|
||||
from pathlib import Path
|
||||
Path(args[args.index('-o') + 1]).write_bytes(b'offline-image-archive')
|
||||
sys.exit(0)
|
||||
if args[:2] == ['volume', 'create']:
|
||||
print(args[2])
|
||||
sys.exit(0)
|
||||
if args[:1] == ['create']:
|
||||
print('offline-scanner-container')
|
||||
sys.exit(0)
|
||||
if args[:1] == ['cp'] or args[:1] == ['rm'] or args[:2] == ['volume', 'rm']:
|
||||
sys.exit(0)
|
||||
if args[:2] == ['start', '--attach']:
|
||||
print('{"Results":[]}')
|
||||
sys.exit(0)
|
||||
if args[:1] == ['inspect']:
|
||||
print('exited 0')
|
||||
sys.exit(0)
|
||||
sys.exit(12)
|
||||
'''
|
||||
docker_path = fakebin / 'docker'
|
||||
docker_path.write_text(docker_stub)
|
||||
docker_path.chmod(0o700)
|
||||
curl_stub = r'''#!/usr/bin/env python3
|
||||
import hashlib, json, os, shutil, sys
|
||||
args = sys.argv[1:]
|
||||
url = next(value for value in args if value.startswith('https://'))
|
||||
output = args[args.index('--output') + 1]
|
||||
with open(os.environ['OFFLINE_CURL_LOG'], 'a') as log:
|
||||
log.write(url + '\n')
|
||||
if url.endswith('/releases/latest'):
|
||||
installer_path = os.environ['OFFLINE_INSTALLER_ZIP']
|
||||
if os.environ.get('OFFLINE_BAD_API_DIGEST') == '1':
|
||||
digest = 'invalid'
|
||||
elif os.environ.get('OFFLINE_NULL_ASSET_DIGEST') == '1':
|
||||
digest = None
|
||||
else:
|
||||
digest = 'sha256:' + hashlib.sha256(open(installer_path,'rb').read()).hexdigest()
|
||||
payload = json.dumps({'tag_name':'1.2.3','assets':[{
|
||||
'name':'heimdall-installers-1.2.3.zip',
|
||||
'digest':digest,
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}, {
|
||||
'name':'heimdall-installers-1.2.3.zip.sha256',
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]}).encode()
|
||||
open(output, 'wb').write(payload)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip':
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'], output)
|
||||
elif url == 'https://release.test/heimdall-installers-1.2.3.zip.sha256':
|
||||
if os.environ.get('OFFLINE_BAD_CHECKSUM') == '1':
|
||||
open(output, 'w').write('0' * 64 + ' heimdall-installers-1.2.3.zip\n')
|
||||
else:
|
||||
shutil.copyfile(os.environ['OFFLINE_INSTALLER_ZIP'] + '.sha256', output)
|
||||
else:
|
||||
sys.exit(22)
|
||||
'''
|
||||
curl_path = fakebin / 'curl'
|
||||
curl_path.write_text(curl_stub)
|
||||
curl_path.chmod(0o700)
|
||||
curl_log = temp / 'installer-bootstrap-urls.txt'
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_args):
|
||||
return
|
||||
|
||||
def _authorized(self):
|
||||
ok = self.headers.get('Authorization') == 'token ' + RELEASE_TOKEN
|
||||
if ok:
|
||||
release_state['authorized'] += 1
|
||||
return ok
|
||||
|
||||
def _json(self, status, value):
|
||||
payload = json.dumps(value).encode()
|
||||
self.send_response(status)
|
||||
self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(payload)))
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
def do_GET(self):
|
||||
path = urlsplit(self.path).path
|
||||
if path == '/token':
|
||||
expected = 'Basic ' + base64.b64encode(
|
||||
b'offline-user:' + DOCKER_TOKEN.encode()).decode('ascii')
|
||||
if self.headers.get('Authorization') != expected:
|
||||
self._json(401, {})
|
||||
return
|
||||
self._json(200, {'token': 'offline-registry-bearer'})
|
||||
return
|
||||
if path.startswith('/v2/') and '/manifests/sha-' in path:
|
||||
if self.headers.get('Authorization') != 'Bearer offline-registry-bearer':
|
||||
self._json(401, {})
|
||||
return
|
||||
if self.headers.get('Accept') is None:
|
||||
self._json(406, {})
|
||||
return
|
||||
digest = (GPU_AGENT_DIGEST if 'heimdall-agent-gpu' in path else
|
||||
AGENT_DIGEST if 'heimdall-agent' in path else SERVER_DIGEST)
|
||||
self.send_response(200)
|
||||
self.send_header('Docker-Content-Digest', digest)
|
||||
self.send_header('Content-Length', '0')
|
||||
self.end_headers()
|
||||
return
|
||||
if not self._authorized():
|
||||
self._json(401, {})
|
||||
return
|
||||
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
if '/compare/' in path:
|
||||
self._json(200, {'commits': [{'sha': 'synthetic-merge-commit'}]})
|
||||
elif path.endswith('/commits/synthetic-merge-commit/pull'):
|
||||
self._json(200, {'number': 42, 'merged': True, 'title': 'Offline acceptance feature',
|
||||
'html_url': 'https://gitea.test/pulls/42'})
|
||||
elif path.endswith('/releases/latest'):
|
||||
self._json(200, {'tag_name': '1.2.3', 'assets': [{
|
||||
'name': 'heimdall-installers-1.2.3.zip',
|
||||
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip'}, {
|
||||
'name': 'heimdall-installers-1.2.3.zip.sha256',
|
||||
'browser_download_url': 'https://release.test/heimdall-installers-1.2.3.zip.sha256'}]})
|
||||
elif path.endswith('/releases/tags/1.2.3'):
|
||||
self._json(404, {'message': 'not found'})
|
||||
elif path.endswith('/releases/7301/assets'):
|
||||
self._json(200, [])
|
||||
else:
|
||||
self._json(404, {'message': 'unexpected request'})
|
||||
|
||||
def do_POST(self):
|
||||
if not self._authorized():
|
||||
self._json(401, {})
|
||||
return
|
||||
path = urlsplit(self.path).path
|
||||
body = self.rfile.read(int(self.headers.get('Content-Length', '0')))
|
||||
if path.endswith('/releases'):
|
||||
release = json.loads(body)
|
||||
assert release['tag_name'] == '1.2.3'
|
||||
assert release['name'] == '1.2.3'
|
||||
assert release['draft'] is True
|
||||
assert release['prerelease'] is False
|
||||
assert 'Offline acceptance feature' in release['body']
|
||||
assert release['target_commitish'] == subprocess.check_output(
|
||||
['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
release_state['release'] = release
|
||||
self._json(201, {'id': 7301, 'draft': True, 'prerelease': True,
|
||||
'tag_name': release['tag_name'],
|
||||
'html_url': 'https://gitea.test/releases/7301'})
|
||||
return
|
||||
if path.endswith('/releases/7301/assets'):
|
||||
content_type = self.headers.get('Content-Type')
|
||||
message = email.message_from_bytes(
|
||||
b'Content-Type: ' + content_type.encode() + b'\r\nMIME-Version: 1.0\r\n\r\n' + body,
|
||||
policy=policy.default,
|
||||
)
|
||||
parts = list(message.iter_parts())
|
||||
assert len(parts) == 1
|
||||
filename = parts[0].get_filename()
|
||||
assert filename and filename not in release_state['assets']
|
||||
release_state['assets'][filename] = parts[0].get_payload(decode=True)
|
||||
self._json(201, {'id': 8000 + len(release_state['assets']), 'name': filename})
|
||||
return
|
||||
self._json(404, {'message': 'unexpected request'})
|
||||
|
||||
def do_PATCH(self):
|
||||
if not self._authorized():
|
||||
self._json(401, {})
|
||||
return
|
||||
path = urlsplit(self.path).path
|
||||
body = json.loads(self.rfile.read(int(self.headers.get('Content-Length', '0'))))
|
||||
if path.endswith('/releases/7301'):
|
||||
assert set(release_state['assets']) >= {
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256'}
|
||||
assert 'heimdall-web-portable-1.2.3.tar.gz' not in release_state['assets']
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
release_state['release']['draft'] = body['draft']
|
||||
release_state['release']['prerelease'] = body['prerelease']
|
||||
self._json(200, release_state['release'])
|
||||
return
|
||||
self._json(404, {'message': 'unexpected request'})
|
||||
|
||||
server = ThreadingHTTPServer(('127.0.0.1', 0), Handler)
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(cert, private_cert_key)
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
|
||||
try:
|
||||
origin = f'https://127.0.0.1:{server.server_port}'
|
||||
env = os.environ.copy()
|
||||
env.update({
|
||||
'PATH': str(fakebin) + os.pathsep + os.environ['PATH'],
|
||||
'SSL_CERT_FILE': str(cert),
|
||||
'NO_PROXY': '127.0.0.1,localhost',
|
||||
'no_proxy': '127.0.0.1,localhost',
|
||||
'BUILD_REF': 'refs/tags/1.2.3',
|
||||
'BUILD_REPOSITORY': REPOSITORY,
|
||||
'BUILD_RUN_ID': 'offline-acceptance',
|
||||
'BUILD_SERVER_URL': origin,
|
||||
'EXPECTED_BUILD_SERVER_URL': origin,
|
||||
'DOCKERHUB_USERNAME': 'offline-user',
|
||||
'DOCKERHUB_TOKEN': DOCKER_TOKEN,
|
||||
'DOCKER_REGISTRY_TOKEN_URL': origin,
|
||||
'DOCKER_REGISTRY_URL': origin,
|
||||
'RELEASE_TOKEN': RELEASE_TOKEN,
|
||||
'RELEASE_SIGNING_KEY_B64': signing_key_b64,
|
||||
'OFFLINE_DOCKER_LOG': str(docker_log),
|
||||
'OFFLINE_SERVER_DIGEST': SERVER_DIGEST,
|
||||
'OFFLINE_AGENT_DIGEST': AGENT_DIGEST,
|
||||
'OFFLINE_GPU_DIGEST': GPU_AGENT_DIGEST,
|
||||
'OFFLINE_COMMIT': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip(),
|
||||
'RELEASE_NOTES_FILE': str(artifacts_dir/'release-notes.md'),
|
||||
'RELEASE_TAG': '1.2.3',
|
||||
})
|
||||
run(['bash', 'scripts/ci/package.sh'], cwd=ROOT, env=env, label='package.sh')
|
||||
with __import__('zipfile').ZipFile(ROOT / 'artifacts/packages/heimdall-installers-1.2.3.zip') as bundle:
|
||||
package_server_script = bundle.read('install/install-server.sh').decode()
|
||||
assert 'PACKAGE_RELEASE_VERSION="1.2.3"' in package_server_script, package_server_script[:1200]
|
||||
launcher_env = env.copy()
|
||||
launcher_env.update({
|
||||
'HEIMDALL_RELEASE_API_URL': origin + '/api/v1/repos/' + REPOSITORY + '/releases',
|
||||
'OFFLINE_CURL_LOG': str(curl_log),
|
||||
'OFFLINE_INSTALLER_ZIP': str(ROOT / 'artifacts/packages/heimdall-installers-1.2.3.zip'),
|
||||
'OFFLINE_STOP_COMPOSE_MARKER': str(temp / 'compose-version-probe'),
|
||||
'TMPDIR': str(temp),
|
||||
})
|
||||
launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=launcher_env, capture_output=True, text=True)
|
||||
launcher_output = launcher.stdout + launcher.stderr
|
||||
assert launcher.returncode == 37 and (temp / 'compose-version-probe').exists(), (
|
||||
f'installer bootstrap exit={launcher.returncode}; URLs={curl_log.read_text() if curl_log.exists() else "<none>"}; '
|
||||
+ launcher_output[-2000:])
|
||||
bootstrap_urls = curl_log.read_text().splitlines()
|
||||
assert bootstrap_urls == [
|
||||
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
]
|
||||
checksum_log = curl_log
|
||||
checksum_env = launcher_env.copy()
|
||||
checksum_env.update({
|
||||
'OFFLINE_CURL_LOG': str(checksum_log),
|
||||
'OFFLINE_NULL_ASSET_DIGEST': '1',
|
||||
'HEIMDALL_INSTALLER_VERSION': '',
|
||||
})
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=checksum_env, capture_output=True, text=True)
|
||||
checksum_output = checksum_launcher.stdout + checksum_launcher.stderr
|
||||
assert checksum_launcher.returncode == 37 and (temp / 'compose-version-probe').exists(), (
|
||||
f'checksum fallback exit={checksum_launcher.returncode}; '
|
||||
f'URLs={checksum_log.read_text() if checksum_log.exists() else "<none>"}; '
|
||||
+ checksum_output[-2000:])
|
||||
assert checksum_log.read_text().splitlines() == [
|
||||
launcher_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
], (f'checksum fallback did not request expected assets; '
|
||||
f'HEIMDALL_INSTALLER_VERSION={checksum_env.get("HEIMDALL_INSTALLER_VERSION")!r}; '
|
||||
f'log={checksum_log.read_text() if checksum_log.exists() else "<missing>"}; '
|
||||
f'returncode={checksum_launcher.returncode}; output={checksum_output[-2000:]}')
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
bad_checksum_log = temp / 'installer-bootstrap-bad-checksum-urls.txt'
|
||||
bad_checksum_env = checksum_env.copy()
|
||||
bad_checksum_env.update({
|
||||
'OFFLINE_CURL_LOG': str(bad_checksum_log),
|
||||
'OFFLINE_BAD_CHECKSUM': '1',
|
||||
})
|
||||
bad_checksum_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=bad_checksum_env, capture_output=True, text=True)
|
||||
bad_checksum_output = bad_checksum_launcher.stdout + bad_checksum_launcher.stderr
|
||||
assert bad_checksum_launcher.returncode != 0 and 'ne correspond pas à la release' in bad_checksum_output, (
|
||||
f'bad checksum was not rejected; returncode={bad_checksum_launcher.returncode}; '
|
||||
f'output={bad_checksum_output[-2000:]}')
|
||||
assert bad_checksum_log.read_text().splitlines() == [
|
||||
bad_checksum_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip.sha256',
|
||||
'https://release.test/heimdall-installers-1.2.3.zip',
|
||||
]
|
||||
(temp / 'compose-version-probe').unlink(missing_ok=True)
|
||||
invalid_digest_log = temp / 'installer-bootstrap-invalid-digest-urls.txt'
|
||||
invalid_digest_env = checksum_env.copy()
|
||||
invalid_digest_env.update({
|
||||
'OFFLINE_CURL_LOG': str(invalid_digest_log),
|
||||
'OFFLINE_BAD_API_DIGEST': '1',
|
||||
})
|
||||
invalid_digest_launcher = subprocess.run(['bash', 'install/install-server.sh'], cwd=ROOT,
|
||||
env=invalid_digest_env, capture_output=True, text=True)
|
||||
invalid_digest_output = invalid_digest_launcher.stdout + invalid_digest_launcher.stderr
|
||||
assert invalid_digest_launcher.returncode != 0 and 'digest Gitea du bundle est invalide' in invalid_digest_output, (
|
||||
f'malformed API digest was not rejected; returncode={invalid_digest_launcher.returncode}; '
|
||||
f'output={invalid_digest_output[-2000:]}')
|
||||
assert invalid_digest_log.read_text().splitlines() == [
|
||||
invalid_digest_env['HEIMDALL_RELEASE_API_URL'] + '/latest',
|
||||
]
|
||||
commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=ROOT, text=True).strip()
|
||||
env['GITEA_TOKEN'] = RELEASE_TOKEN
|
||||
env['BEFORE_SHA'] = commit + '^'
|
||||
env['CURRENT_SHA'] = commit
|
||||
run([sys.executable, 'scripts/ci/release-notes.py'], cwd=ROOT, env=env, label='release-notes.py')
|
||||
for component in ('server', 'agent', 'agent-gpu'):
|
||||
main_env = env.copy()
|
||||
main_env['BUILD_REF'] = 'refs/heads/main'
|
||||
run(['bash', 'scripts/ci/push-images.sh', component], cwd=ROOT, env=main_env,
|
||||
label=f'push-images.sh {component} main')
|
||||
run(['bash', 'scripts/ci/push-images.sh', component], cwd=ROOT, env=env,
|
||||
label=f'push-images.sh {component} tag')
|
||||
run(['bash', 'scripts/ci/publish.sh'], cwd=ROOT, env=env, label='publish.sh')
|
||||
|
||||
packages = ROOT / 'artifacts/packages'
|
||||
public_key = temp / 'release-public.pem'
|
||||
public_key.write_bytes(release_state['assets']['agent-release-public.pem'])
|
||||
manifest_bytes = release_state['assets']['agent-update-manifest.json']
|
||||
signature = temp / 'manifest.sig'
|
||||
signature.write_bytes(release_state['assets']['agent-update-manifest.sig'])
|
||||
manifest = json.loads(manifest_bytes)
|
||||
assert manifest['version'] == '1.2.3'
|
||||
assert manifest['containerImage'] == 'eltruncho/heimdall-agent'
|
||||
assert manifest['containerImageDigest'] == AGENT_DIGEST
|
||||
assert manifest['containerImageGpu'] == 'eltruncho/heimdall-agent-gpu'
|
||||
assert manifest['containerImageGpuDigest'] == GPU_AGENT_DIGEST
|
||||
provenance = json.loads((packages / 'provenance.json').read_text())
|
||||
assert provenance['commit'] == commit and provenance['ref'] == 'refs/tags/1.2.3'
|
||||
agent_image = json.loads(release_state['assets']['agent-image.json'])
|
||||
assert agent_image == {'digest': AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent'}
|
||||
gpu_agent_image = json.loads(release_state['assets']['agent-image-gpu.json'])
|
||||
assert gpu_agent_image == {'digest': GPU_AGENT_DIGEST, 'image': 'eltruncho/heimdall-agent-gpu'}
|
||||
for platform, digest in manifest['assets'].items():
|
||||
archive = f'heimdall-agent-{platform}-1.2.3.tar.gz'
|
||||
assert hashlib.sha256(release_state['assets'][archive]).hexdigest() == digest
|
||||
subprocess.run(['openssl', 'dgst', '-sha256', '-verify', str(public_key),
|
||||
'-signature', str(signature), str(packages / 'agent-update-manifest.json')],
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
checksums = (packages / 'SHA256SUMS').read_text().splitlines()
|
||||
for line in checksums:
|
||||
digest, filename = line.split(maxsplit=1)
|
||||
filename = filename.lstrip('* ')
|
||||
assert (packages / filename).is_file(), f'missing package checksum input {filename}'
|
||||
assert hashlib.sha256((packages / filename).read_bytes()).hexdigest() == digest, filename
|
||||
image_digests = (packages / 'image-digests.txt').read_text().splitlines()
|
||||
assert len(image_digests) == 3
|
||||
assert sum(AGENT_DIGEST in item for item in image_digests) == 1
|
||||
assert sum(GPU_AGENT_DIGEST in item for item in image_digests) == 1
|
||||
with __import__('zipfile').ZipFile(packages/'heimdall-installers-1.2.3.zip') as bundle:
|
||||
assert 'install/install-server.sh' in bundle.namelist()
|
||||
assert 'install/install-server.ps1' in bundle.namelist()
|
||||
assert 'docker/docker-compose.yml' in bundle.namelist()
|
||||
server_script = bundle.read('install/install-server.sh').decode()
|
||||
windows_script = bundle.read('install/install-server.ps1').decode()
|
||||
assert '/raw/tag/1.2.3' in server_script
|
||||
assert 'eltruncho/heimdall:1.2.3' in server_script
|
||||
assert 'PACKAGE_RELEASE_VERSION="1.2.3"' in server_script
|
||||
assert "PackageReleaseVersion = '1.2.3'" in windows_script
|
||||
assert 'install/install-agent.sh' in bundle.namelist()
|
||||
assert 'install/install-agent.ps1' in bundle.namelist()
|
||||
checksum_asset = packages / 'heimdall-installers-1.2.3.zip.sha256'
|
||||
checksum, filename = checksum_asset.read_text().split()
|
||||
assert filename == 'heimdall-installers-1.2.3.zip'
|
||||
assert checksum == hashlib.sha256((packages / filename).read_bytes()).hexdigest()
|
||||
expected_release_assets = {
|
||||
'heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig',
|
||||
'agent-image.json', 'agent-image-gpu.json',
|
||||
*[f'heimdall-agent-{platform}-1.2.3.tar.gz' for platform in manifest['assets']],
|
||||
}
|
||||
assert set(release_state['assets']) == expected_release_assets
|
||||
assert not ({'provenance.json', 'image-digests.txt', 'SHA256SUMS'} & set(release_state['assets']))
|
||||
docker_calls = [json.loads(line) for line in docker_log.read_text().splitlines()]
|
||||
assert sum(call[:1] == ['build'] for call in docker_calls) == 0
|
||||
pushes = {call[1] for call in docker_calls if call[:1] == ['push']}
|
||||
assert len(pushes) == 9
|
||||
for image in ('eltruncho/heimdall', 'eltruncho/heimdall-agent', 'eltruncho/heimdall-agent-gpu'):
|
||||
assert f'{image}:sha-{commit}' in pushes
|
||||
assert f'{image}:latest' in pushes
|
||||
assert f'{image}:1.2.3' in pushes
|
||||
assert sum(call[:1] == ['login'] for call in docker_calls) == 7
|
||||
assert release_state['release']['draft'] is False
|
||||
assert release_state['release']['prerelease'] is False
|
||||
assert len(release_state['assets']) == len(expected_release_assets)
|
||||
assert release_state['authorized'] >= 7
|
||||
assert sum(call[:1] == ['push'] for call in docker_calls if call[0] != 'login') == 12
|
||||
print(f'Offline version release simulation passed: installer ZIP, Agent archives, P-256 signature, {len(release_state["assets"])} Gitea assets, immutable image refs, and selective Docker Hub tags.')
|
||||
print('No real Docker CLI, Docker Hub registry, or Gitea server was contacted.')
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join(timeout=5)
|
||||
if artifacts_dir.exists():
|
||||
shutil.rmtree(artifacts_dir)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq
|
||||
apt-get install -y --no-install-recommends ca-certificates curl git jq python3 unzip postgresql-client docker.io docker-compose-v2
|
||||
# Fail explicitly if a runner cannot provide the required Docker build service.
|
||||
docker version --format '{{.Server.Version}}'
|
||||
docker compose version
|
||||
[[ "$(uname -m)" == x86_64 ]] || { echo 'The current image lane requires an amd64 runner' >&2; exit 1; }
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build only the projects selected by test-plan.py after solution restore."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PLAN = ROOT / "artifacts" / "tests" / "plan.json"
|
||||
|
||||
|
||||
def main() -> None:
|
||||
plan = json.loads(PLAN.read_text())
|
||||
targets = plan.get("build_projects")
|
||||
if not isinstance(targets, list) or any(not isinstance(target, str) for target in targets):
|
||||
raise SystemExit("Test plan has an invalid build_projects list")
|
||||
if not targets:
|
||||
print("No .NET build targets selected")
|
||||
return
|
||||
|
||||
for target in targets:
|
||||
path = ROOT / target
|
||||
if not path.is_file():
|
||||
raise SystemExit(f"Build target does not exist: {target}")
|
||||
print(f"Building affected target: {target}", flush=True)
|
||||
subprocess.run(
|
||||
["dotnet", "build", target, "-c", "Release", "--no-restore", "-m:2"],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Set Gitea workflow outputs for validation and affected container images."""
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
|
||||
def changed_paths() -> list[str]:
|
||||
event = os.environ.get("EVENT_NAME", "")
|
||||
ref = os.environ.get("REF", "")
|
||||
if event == "push" and ref.startswith("refs/tags/"):
|
||||
tag = ref.removeprefix("refs/tags/")
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:[.-][0-9A-Za-z.-]+)?", tag):
|
||||
raise SystemExit("Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix")
|
||||
return ["*"]
|
||||
if event == "pull_request":
|
||||
base = os.environ["PR_BASE_SHA"]
|
||||
return subprocess.check_output(
|
||||
["git", "diff", "--name-only", f"{base}...HEAD"], text=True
|
||||
).splitlines()
|
||||
before = os.environ.get("PUSH_BEFORE_SHA", "")
|
||||
current = os.environ.get("CURRENT_SHA", "HEAD")
|
||||
if before and before != "0" * 40:
|
||||
return subprocess.check_output(
|
||||
["git", "diff", "--name-only", before, current], text=True
|
||||
).splitlines()
|
||||
return ["*"]
|
||||
|
||||
|
||||
def under(path: str, *prefixes: str) -> bool:
|
||||
return any(path == prefix or path.startswith(prefix.rstrip("/") + "/") for prefix in prefixes)
|
||||
|
||||
|
||||
def scope_for(paths: list[str]) -> dict[str, bool]:
|
||||
all_images = "*" in paths
|
||||
validation_prefixes = ("src/", "tests/", "scripts/ci/", "docker/", "install/", "models/")
|
||||
validation_files = {
|
||||
"Heimdall.slnx", "global.json", ".dockerignore", ".env.example", "Makefile",
|
||||
"GitVersion.yml", "GitVersion.Agent.yml", "Directory.Packages.props", "NuGet.Config",
|
||||
}
|
||||
run_validation = all_images or any(
|
||||
under(path, *validation_prefixes) or path in validation_files or
|
||||
path.startswith(".gitea/workflows/") or path.startswith("Directory.Build.")
|
||||
for path in paths
|
||||
)
|
||||
|
||||
# Shared projects included by both Docker build graphs.
|
||||
shared = {
|
||||
"global.json", "Directory.Packages.props", "NuGet.Config", "GitVersion.yml",
|
||||
}
|
||||
shared_image_change = all_images or any(
|
||||
path in shared or path.startswith("Directory.Build.") for path in paths
|
||||
)
|
||||
server = shared_image_change or any(
|
||||
under(path, "src/Heimdall.Web", "src/Heimdall.Infrastructure",
|
||||
"src/Heimdall.Application", "src/Heimdall.Domain",
|
||||
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts")
|
||||
or path == "docker/Dockerfile" or under(path, "install")
|
||||
for path in paths
|
||||
)
|
||||
agent_projects = (
|
||||
"src/Heimdall.Agent", "src/Heimdall.Application", "src/Heimdall.Domain",
|
||||
"src/Heimdall.Domain.Primitives", "src/Heimdall.Contracts", "src/Heimdall.Mdns",
|
||||
)
|
||||
agent_common = any(
|
||||
under(path, *agent_projects) or path == "models/yolov8n.onnx"
|
||||
for path in paths
|
||||
)
|
||||
agent = shared_image_change or agent_common or any(
|
||||
path == "docker/Dockerfile.agent" or path == "GitVersion.Agent.yml"
|
||||
for path in paths
|
||||
)
|
||||
agent_gpu = shared_image_change or agent_common or any(
|
||||
path == "docker/Dockerfile.agent.gpu" or path == "GitVersion.Agent.yml"
|
||||
for path in paths
|
||||
)
|
||||
return {
|
||||
"run_validation": run_validation,
|
||||
"build_server": server,
|
||||
"build_agent": agent,
|
||||
"build_agent_gpu": agent_gpu,
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
output = os.environ.get("GITEA_OUTPUT")
|
||||
if not output:
|
||||
raise SystemExit("GITEA_OUTPUT is required")
|
||||
with open(output, "a", encoding="utf-8") as stream:
|
||||
for name, selected in scope_for(changed_paths()).items():
|
||||
stream.write(f"{name}={'true' if selected else 'false'}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Fail closed when NuGet reports vulnerable direct or transitive packages."""
|
||||
import json
|
||||
import sys
|
||||
|
||||
with open(sys.argv[1], encoding="utf-8") as report:
|
||||
data = json.load(report)
|
||||
if data.get("version") != 1 or not isinstance(data.get("projects"), list) or not data["projects"]:
|
||||
raise SystemExit("Invalid or empty NuGet advisory report")
|
||||
if data.get("problems"):
|
||||
raise SystemExit("NuGet advisory lookup failed; see retained report")
|
||||
findings = []
|
||||
for project in data.get("projects", []):
|
||||
for framework in project.get("frameworks", []):
|
||||
for group in ("topLevelPackages", "transitivePackages"):
|
||||
for package in framework.get(group, []):
|
||||
for advisory in package.get("vulnerabilities", []):
|
||||
if advisory.get("severity", "").lower() in ("high", "critical"):
|
||||
findings.append((package["id"], advisory["severity"], advisory["advisoryurl"]))
|
||||
for package, severity, url in sorted(set(findings)):
|
||||
print(f"{severity}: {package}: {url}")
|
||||
if findings:
|
||||
raise SystemExit("HIGH/CRITICAL dependency advisories block publication")
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Enforce the camera-access coverage target from affected .NET test suites."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
THRESHOLD = 80.01
|
||||
TARGETS = {
|
||||
"CameraAccessService.cs": ("src/Heimdall.Infrastructure/Services/CameraAccessService.cs", "Heimdall.Infrastructure.Tests"),
|
||||
"ResourceAccess.cs": ("src/Heimdall.Web/Security/ResourceAccess.cs", "Heimdall.Web.Tests"),
|
||||
"ResourceAccessFilter.cs": ("src/Heimdall.Web/Security/ResourceAccessFilter.cs", "Heimdall.Web.Tests"),
|
||||
"UserCameraAccessController.cs": ("src/Heimdall.Web/Controllers/UserCameraAccessController.cs", "Heimdall.Web.Tests"),
|
||||
"CreateUserCameraAccessCommand.cs": ("src/Heimdall.Application/Assignments/Commands/CreateUserCameraAccess/CreateUserCameraAccessCommand.cs", "Heimdall.Application.Tests"),
|
||||
"DeleteUserCameraAccessCommand.cs": ("src/Heimdall.Application/Assignments/Commands/DeleteUserCameraAccess/DeleteUserCameraAccessCommand.cs", "Heimdall.Application.Tests"),
|
||||
"UpdateUserCameraAccessCommand.cs": ("src/Heimdall.Application/Assignments/Commands/UpdateUserCameraAccess/UpdateUserCameraAccessCommand.cs", "Heimdall.Application.Tests"),
|
||||
"ReplaceUserCameraAccessCommandHandler.cs": ("src/Heimdall.Application/Assignments/Commands/ReplaceUserCameraAccess/ReplaceUserCameraAccessCommandHandler.cs", "Heimdall.Application.Tests"),
|
||||
"GetUserCameraAccessQuery.cs": ("src/Heimdall.Application/Assignments/Queries/GetUserCameraAccess/GetUserCameraAccessQuery.cs", "Heimdall.Application.Tests"),
|
||||
"ListUserCameraAccessQuery.cs": ("src/Heimdall.Application/Assignments/Queries/ListUserCameraAccess/ListUserCameraAccessQuery.cs", "Heimdall.Application.Tests"),
|
||||
"ListUserCameraAccessByCameraQuery.cs": ("src/Heimdall.Application/Assignments/Queries/ListUserCameraAccessByCamera/ListUserCameraAccessByCameraQuery.cs", "Heimdall.Application.Tests"),
|
||||
"UserCameraAccessMappingProfile.cs": ("src/Heimdall.Application/Assignments/Mapping/UserCameraAccessMappingProfile.cs", "Heimdall.Application.Tests"),
|
||||
}
|
||||
|
||||
|
||||
def coverage_for(path: Path, target: str) -> tuple[int, int]:
|
||||
covered = valid = 0
|
||||
target_name = Path(target).name
|
||||
target_suffix = target.removeprefix("src/")
|
||||
for report in path.rglob("coverage.cobertura.xml"):
|
||||
root = ET.parse(report).getroot()
|
||||
for item in root.iter("class"):
|
||||
filename = item.get("filename", "").replace("\\", "/")
|
||||
if not (filename.endswith(target) or filename.endswith(target_suffix) or Path(filename).name == target_name):
|
||||
continue
|
||||
lines = item.findall("./lines/line")
|
||||
valid += len(lines)
|
||||
covered += sum(int(line.get("hits", "0")) > 0 for line in lines)
|
||||
return covered, valid
|
||||
|
||||
|
||||
def main() -> int:
|
||||
artifacts = Path(sys.argv[1])
|
||||
plan_path = Path(sys.argv[2])
|
||||
suites = set(json.loads(plan_path.read_text()).get("suites", []))
|
||||
targets = [(name, source) for name, (source, suite) in TARGETS.items() if suite in suites]
|
||||
if not targets:
|
||||
print("Skipping camera-access coverage: no relevant test suite was selected.")
|
||||
return 0
|
||||
|
||||
failed = False
|
||||
for name, source in targets:
|
||||
suite = TARGETS[name][1]
|
||||
covered, valid = coverage_for(artifacts / suite, source)
|
||||
percent = 100.0 * covered / valid if valid else 0.0
|
||||
print(f"{name}: {covered}/{valid} lines ({percent:.2f}%; required >80%)")
|
||||
if valid == 0 or percent < THRESHOLD:
|
||||
failed = True
|
||||
if failed:
|
||||
print("Camera-access coverage is missing or below the required threshold.", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reject direct database commands in production source outside documented EF exceptions."""
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE_ROOT = ROOT / "src"
|
||||
|
||||
# These operations cannot be expressed portably through EF's LINQ/change tracker.
|
||||
# Keep the exception narrow by path and explain it in the file next to the operation.
|
||||
EF_CORE_EXCEPTIONS = {
|
||||
"src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs": "PostgreSQL VACUUM/REINDEX and catalog inspection",
|
||||
"src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs": "PostgreSQL partition DDL and catalog inspection",
|
||||
"src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs": "transaction-scoped PostgreSQL advisory lock",
|
||||
"src/Heimdall.Infrastructure/Storage/RecordingQuotaGuard.cs": "transaction-scoped PostgreSQL advisory lock for serialized recording quota checks",
|
||||
"src/Heimdall.Infrastructure/Jobs/AgentMetricSampleJob.cs": "idempotent PostgreSQL bulk insert with ON CONFLICT DO NOTHING",
|
||||
"src/Heimdall.Agent/Data/AgentOutboxDatabaseInitializer.cs": "baseline and migrate pre-EF local SQLite outbox schemas",
|
||||
}
|
||||
|
||||
DATABASE_API = re.compile(
|
||||
r"\b(?:Sqlite|Npgsql|Sql|MySql|Db)(?:Connection|Command|DataReader)\b"
|
||||
r"|\.CreateCommand\s*\(|\.GetDbConnection\s*\(|\.CommandText\s*=|"
|
||||
r"\.Execute(?:Reader|NonQuery|Scalar)(?:Async)?\s*\(|\b(?:ExecuteSqlRaw|ExecuteSqlInterpolated|"
|
||||
r"SqlQueryRaw|SqlQuery|FromSqlRaw|FromSqlInterpolated|FromSql)\s*(?:Async)?\s*\(",
|
||||
)
|
||||
|
||||
|
||||
def inspect_source(path: str, content: str) -> list[str]:
|
||||
"""Return policy violations for one repository-relative C# source file."""
|
||||
if not path.startswith("src/") or "/Migrations/" in path or path.endswith(".Designer.cs"):
|
||||
return []
|
||||
if not DATABASE_API.search(content):
|
||||
return []
|
||||
rationale = EF_CORE_EXCEPTIONS.get(path)
|
||||
if rationale and "EF Core exception:" in content:
|
||||
return []
|
||||
return [f"{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception"]
|
||||
|
||||
|
||||
def check_tree(root: Path = ROOT) -> list[str]:
|
||||
failures = []
|
||||
for path in sorted((root / "src").rglob("*.cs")):
|
||||
relative = path.relative_to(root).as_posix()
|
||||
try:
|
||||
content = path.read_text(encoding="utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
failures.append(f"{relative}: source is not valid UTF-8")
|
||||
continue
|
||||
failures.extend(inspect_source(relative, content))
|
||||
return failures
|
||||
|
||||
|
||||
def main() -> int:
|
||||
failures = check_tree()
|
||||
if failures:
|
||||
print("EF Core persistence policy violations:", file=sys.stderr)
|
||||
print("\n".join(f"- {failure}" for failure in failures), file=sys.stderr)
|
||||
return 1
|
||||
print("EF Core persistence policy passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# Clean Heimdall images/scan volumes and Docker's unreferenced build layers.
|
||||
set -euo pipefail
|
||||
|
||||
phase=${1:?Expected before or after}
|
||||
[[ "$phase" == before || "$phase" == after ]] || exit 2
|
||||
|
||||
echo "Docker storage before $phase cleanup"
|
||||
docker system df || true
|
||||
df -h /workspace 2>/dev/null || true
|
||||
df -i /workspace 2>/dev/null || true
|
||||
|
||||
# Images are tagged with this source by scripts/ci/images.sh. Never delete an
|
||||
# image used by a running container; docker image rm without --force refuses it.
|
||||
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Gitea repository is required}"
|
||||
source_label="org.opencontainers.image.source=${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
|
||||
while IFS= read -r image_id; do
|
||||
[[ -n "$image_id" ]] && docker image rm "$image_id" >/dev/null 2>&1 || true
|
||||
done < <(docker image ls --filter "label=$source_label" --format '{{.ID}}' | sort -u)
|
||||
|
||||
# A cancelled security step may leave its dedicated Trivy database volume.
|
||||
# Docker refuses removal while a scanner container still uses the volume.
|
||||
while IFS= read -r volume; do
|
||||
if [[ "$volume" =~ ^heimdall-trivy-cache-[0-9a-f]{40}$ ]]; then
|
||||
docker volume rm "$volume" >/dev/null 2>&1 || true
|
||||
fi
|
||||
done < <(docker volume ls --format '{{.Name}}')
|
||||
|
||||
# These commands affect only unused cache older than 30 minutes and dangling
|
||||
# images. Tagged images and named volumes from other projects are preserved.
|
||||
# Do not prune named volumes, tagged images from other projects, or networks.
|
||||
docker builder prune --force --filter until=30m || true
|
||||
docker image prune --force || true
|
||||
|
||||
echo "Docker storage after $phase cleanup"
|
||||
docker system df || true
|
||||
df -h /workspace 2>/dev/null || true
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rapport markdown des vulnérabilités HIGH/CRITICAL du JSON OWASP Dependency-Check.
|
||||
Usage: dc_report.py <dependency-check-report.json> [count]
|
||||
(2e argument 'count' → affiche uniquement le nombre de vulnérabilités)"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
try:
|
||||
data = json.load(open(sys.argv[1]))
|
||||
except Exception:
|
||||
print("")
|
||||
sys.exit(0)
|
||||
|
||||
mode_count = len(sys.argv) > 2 and sys.argv[2] == "count"
|
||||
|
||||
vulns = []
|
||||
seen = set()
|
||||
for dep in data.get("dependencies", []):
|
||||
for v in dep.get("vulnerabilities", []):
|
||||
sev = (v.get("cvssv3", {}) or {}).get("baseScore", 0)
|
||||
sev_label = v.get("severity", "UNKNOWN")
|
||||
if sev < 7.0 and sev_label not in ("HIGH", "CRITICAL"):
|
||||
continue
|
||||
vid = v.get("name", "CVE-?")
|
||||
if vid in seen:
|
||||
continue
|
||||
seen.add(vid)
|
||||
vulns.append((vid, sev_label, sev, dep.get("fileName", "?"), (v.get("description", "") or "")[:80]))
|
||||
|
||||
if mode_count:
|
||||
print(len(vulns))
|
||||
sys.exit(0)
|
||||
|
||||
if not vulns:
|
||||
print("")
|
||||
sys.exit(0)
|
||||
|
||||
print(f"### 🛡️ OWASP Dependency-Check — Vulnerabilités HIGH/CRITICAL ({len(vulns)})")
|
||||
print("")
|
||||
print("| CVE | Sévérité | Dépendance | Description |")
|
||||
print("|---|---|---|---|")
|
||||
for vid, sev_label, sev, fname, desc in vulns:
|
||||
print(f"| {vid} | {sev_label} (CVSS {sev}) | {fname} | {desc} |")
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Resolve the canonical digest for an immutable Docker Hub repository tag."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def endpoint(name, default, path):
|
||||
value = os.environ.get(name, default).rstrip('/')
|
||||
if not value.startswith('https://') or '@' in value:
|
||||
raise SystemExit('Registry endpoint must be HTTPS')
|
||||
return value + path
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) != 3:
|
||||
raise SystemExit('usage: dockerhub-tag-digest.py REPOSITORY IMMUTABLE_TAG')
|
||||
repository, tag = sys.argv[1:]
|
||||
if not re.fullmatch(r'[a-z0-9._-]+/[a-z0-9._-]+', repository):
|
||||
raise SystemExit('Invalid Docker Hub repository')
|
||||
if not re.fullmatch(r'sha-[0-9a-f]{40}', tag):
|
||||
raise SystemExit('Expected an immutable full-commit image tag')
|
||||
username = os.environ.get('DOCKERHUB_USERNAME', '')
|
||||
password = os.environ.get('DOCKERHUB_TOKEN', '')
|
||||
if not username or not password:
|
||||
raise SystemExit('Docker Hub credentials are required to resolve image digest')
|
||||
|
||||
token_url = endpoint('DOCKER_REGISTRY_TOKEN_URL', 'https://auth.docker.io',
|
||||
'/token?' + urlencode({'service': 'registry.docker.io',
|
||||
'scope': 'repository:' + repository + ':pull'}))
|
||||
registry_url = endpoint('DOCKER_REGISTRY_URL', 'https://registry-1.docker.io',
|
||||
'/v2/' + repository + '/manifests/' + tag)
|
||||
import base64
|
||||
credentials = base64.b64encode((username + ':' + password).encode()).decode('ascii')
|
||||
try:
|
||||
token_request = Request(token_url, headers={'Authorization': 'Basic ' + credentials,
|
||||
'Accept': 'application/json'})
|
||||
with urlopen(token_request, timeout=30) as response:
|
||||
token_data = json.load(response)
|
||||
bearer = token_data.get('token') or token_data.get('access_token')
|
||||
if not isinstance(bearer, str) or not bearer:
|
||||
raise SystemExit('Docker Hub did not return a registry bearer token')
|
||||
manifest_request = Request(registry_url, headers={
|
||||
'Authorization': 'Bearer ' + bearer,
|
||||
'Accept': ', '.join([
|
||||
'application/vnd.oci.image.index.v1+json',
|
||||
'application/vnd.docker.distribution.manifest.list.v2+json',
|
||||
'application/vnd.oci.image.manifest.v1+json',
|
||||
'application/vnd.docker.distribution.manifest.v2+json',
|
||||
]),
|
||||
})
|
||||
with urlopen(manifest_request, timeout=30) as response:
|
||||
digest = response.headers.get('Docker-Content-Digest', '')
|
||||
except (HTTPError, URLError, TimeoutError, OSError, ValueError):
|
||||
raise SystemExit('Unable to resolve immutable Docker Hub image digest')
|
||||
if not re.fullmatch(r'sha256:[0-9a-f]{64}', digest):
|
||||
raise SystemExit('Docker Hub returned an invalid image digest')
|
||||
print(digest)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
if [[ "${BUILD_REF:-}" == refs/tags/* ]]; then
|
||||
version=${BUILD_REF#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
: "${BUILD_SERVER_URL:?Gitea server URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Gitea repository is required}"
|
||||
source_url="${BUILD_SERVER_URL%/}/${BUILD_REPOSITORY}"
|
||||
case "${1:-all}" in
|
||||
all) components=(server agent agent-gpu) ;;
|
||||
server|agent|agent-gpu) components=("$1") ;;
|
||||
*) echo 'Usage: images.sh [server|agent|agent-gpu|all]' >&2; exit 2 ;;
|
||||
esac
|
||||
for component in "${components[@]}"; do
|
||||
file=docker/Dockerfile
|
||||
[[ "$component" == agent ]] && file=docker/Dockerfile.agent
|
||||
[[ "$component" == agent-gpu ]] && file=docker/Dockerfile.agent.gpu
|
||||
docker build --pull --platform linux/amd64 -f "$file" --build-arg "VERSION=$version" \
|
||||
--label "org.opencontainers.image.revision=$sha" \
|
||||
--label "org.opencontainers.image.version=$version" \
|
||||
--label "org.opencontainers.image.source=$source_url" \
|
||||
-t "heimdall-$component:ci-$sha" .
|
||||
done
|
||||
@@ -1,27 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Injecte des secrets au format dotenv dans $GITHUB_ENV (steps suivants du job).
|
||||
Usage: inject_env.py <dotenv-content>
|
||||
Sûr pour les valeurs multi-lignes et caractères spéciaux (délimiteur EOF)."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
dotenv = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
out = os.environ.get("GITHUB_ENV")
|
||||
if not out:
|
||||
print("GITHUB_ENV non défini — rien à injecter")
|
||||
sys.exit(0)
|
||||
|
||||
count = 0
|
||||
with open(out, "a") as f:
|
||||
for line in dotenv.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, _, val = line.partition("=")
|
||||
key = key.strip()
|
||||
val = val.strip().strip("'").strip('"')
|
||||
if not key:
|
||||
continue
|
||||
f.write(f"{key}<<HEIMDALL_EOF\n{val}\nHEIMDALL_EOF\n")
|
||||
count += 1
|
||||
print(f"Secrets Infisical injectés dans l'environnement du job ({count} clés)")
|
||||
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
sha=$(git rev-parse HEAD)
|
||||
ref=${BUILD_REF:-}
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
version=${ref#refs/tags/}
|
||||
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]] || {
|
||||
echo 'Release tags must be MAJOR.MINOR.PATCH with an optional prerelease suffix.' >&2; exit 2;
|
||||
}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
mkdir -p artifacts/packages
|
||||
component=Agent
|
||||
rid=portable
|
||||
out="artifacts/publish/$component-$rid"
|
||||
dotnet publish "src/Heimdall.Agent" -c Release --self-contained false \
|
||||
-p:RestoreLockedMode=true -p:Version="$version" -p:SourceRevisionId="$sha" -p:ContinuousIntegrationBuild=true -o "$out"
|
||||
mkdir -p "$out/models"
|
||||
cp models/yolov8n.onnx "$out/models/"
|
||||
epoch=$(git show -s --format=%ct HEAD)
|
||||
tar --sort=name --mtime="@$epoch" --owner=0 --group=0 --numeric-owner -cf - -C "$out" . | gzip -1 -n > "artifacts/packages/heimdall-agent-$rid-$version.tar.gz"
|
||||
python3 - "$version" "$ref" <<'PY'
|
||||
import os,sys,zipfile
|
||||
from datetime import datetime,timezone
|
||||
from pathlib import Path
|
||||
|
||||
version, ref = sys.argv[1:]
|
||||
epoch = int(__import__('subprocess').check_output(['git','show','-s','--format=%ct','HEAD'],text=True))
|
||||
stamp = datetime.fromtimestamp(max(epoch, 315532800), timezone.utc).timetuple()[:6]
|
||||
tag = version
|
||||
source_base = f"https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/tag/{tag}"
|
||||
files = [Path('install/install-server.sh'), Path('install/install-server.ps1')]
|
||||
files += sorted(Path('install').glob('*.sh'))
|
||||
files += sorted(Path('install').glob('*.ps1'))
|
||||
files += sorted(Path('install').glob('*.py'))
|
||||
files += sorted(Path('docker').glob('docker-compose*.yml'))
|
||||
files += sorted(Path('docker/scripts').glob('*')) if Path('docker/scripts').exists() else []
|
||||
archive = Path(f'artifacts/packages/heimdall-installers-{version}.zip')
|
||||
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as bundle:
|
||||
for path in sorted(set(files)):
|
||||
if not path.is_file():
|
||||
continue
|
||||
data = path.read_bytes()
|
||||
if path.name in {'install-server.sh', 'install-server.ps1'} or path.name.startswith('docker-compose'):
|
||||
text = data.decode('utf-8')
|
||||
text = text.replace('https://sources.tordais.cc/arnaud.dartois/Heimdall/raw/branch/main', source_base)
|
||||
text = text.replace('eltruncho/heimdall:latest', f'eltruncho/heimdall:{version}')
|
||||
text = text.replace('PACKAGE_RELEASE_VERSION="unversioned"', f'PACKAGE_RELEASE_VERSION="{version}"')
|
||||
text = text.replace("PackageReleaseVersion = 'unversioned'", f"PackageReleaseVersion = '{version}'")
|
||||
data = text.encode('utf-8')
|
||||
entry = zipfile.ZipInfo(path.as_posix(), stamp)
|
||||
entry.compress_type = zipfile.ZIP_DEFLATED
|
||||
entry.external_attr = (0o100755 if path.suffix in {'.sh', '.py'} else 0o100644) << 16
|
||||
bundle.writestr(entry, data)
|
||||
PY
|
||||
python3 - "$sha" "$version" "$ref" <<'PY'
|
||||
import json,os,sys
|
||||
from pathlib import Path
|
||||
Path('artifacts/packages/provenance.json').write_text(json.dumps({
|
||||
'commit':sys.argv[1], 'version':sys.argv[2], 'ref':sys.argv[3],
|
||||
'repository':os.environ.get('BUILD_REPOSITORY'), 'run_id':os.environ.get('BUILD_RUN_ID'),
|
||||
'targets':['Agent native updater'], 'rids':['portable-framework-dependent'],
|
||||
'runtime':'framework-dependent .NET 10', 'mobile_native':False}, indent=2)+'\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum *.tar.gz heimdall-installers-*.zip provenance.json > SHA256SUMS)
|
||||
installer_bundle="artifacts/packages/heimdall-installers-$version.zip"
|
||||
(cd artifacts/packages && sha256sum "$(basename "$installer_bundle")" > "$(basename "$installer_bundle").sha256")
|
||||
printf '%s' "$version" > artifacts/version
|
||||
@@ -1,135 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Parse les logs `dotnet test` et produit un résumé markdown (tests + coverage).
|
||||
|
||||
Usage:
|
||||
parse_test_log.py <log1> <log2> ... [--coverage-dir <dir>]
|
||||
|
||||
Lit les fichiers de log (générés par les jobs CI) et les rapports coverage
|
||||
cobertura (optionnel) ; sort le markdown sur stdout.
|
||||
|
||||
Comportement :
|
||||
- Si des tests ont tourné : tableau agrégé (Passed/Failed/Skipped/Total)
|
||||
+ liste des tests échoués nommément (si l'info est dans le log).
|
||||
- Si AUCUN test n'a tourné : message explicite signalant un échec avant
|
||||
l'exécution (et non plus une sortie vide silencieuse qui faisait afficher
|
||||
« Pas de résultats » au récap PR).
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
args = sys.argv[1:]
|
||||
cov_dir = None
|
||||
if "--coverage-dir" in args:
|
||||
i = args.index("--coverage-dir")
|
||||
cov_dir = args[i + 1]
|
||||
del args[i:i + 2]
|
||||
logs = [a for a in args if os.path.isfile(a)]
|
||||
|
||||
results = [] # (projet, failed, passed, skipped, total, status)
|
||||
error_lines = [] # erreurs de compilation
|
||||
failed_tests = [] # noms des tests échoués
|
||||
|
||||
for f in sorted(logs):
|
||||
try:
|
||||
with open(f, errors="replace") as fh:
|
||||
content = fh.read()
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
# --- Comptes agrégés (Pattern 1 : avec nom de DLL) ---
|
||||
for m in re.finditer(
|
||||
r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)[^:]*-[^:]*\[?\s*([\w.]+)\.dll",
|
||||
content,
|
||||
):
|
||||
results.append((m.group(6), m.group(2), m.group(3), m.group(4), m.group(5), m.group(1)))
|
||||
|
||||
# --- Comptes agrégés (Pattern 2 : sans nom de DLL) ---
|
||||
for m in re.finditer(
|
||||
r"(Passed!|Failed!)\s+-\s+Failed:\s*(\d+),\s+Passed:\s*(\d+),\s+Skipped:\s*(\d+),\s+Total:\s*(\d+)",
|
||||
content,
|
||||
):
|
||||
tot, passed = m.group(5), m.group(3)
|
||||
if any(r[4] == tot and r[2] == passed for r in results):
|
||||
continue
|
||||
line_start = content.rfind("\n", 0, m.start()) + 1
|
||||
line_end = content.find("\n", m.end())
|
||||
line = content[line_start:line_end] if line_end > 0 else content[line_start:]
|
||||
dll_match = re.search(r"-\s*([\w.]+)\.dll", line)
|
||||
proj = dll_match.group(1) if dll_match else "unknown"
|
||||
results.append((proj, m.group(2), m.group(3), m.group(4), m.group(5), m.group(1)))
|
||||
|
||||
# --- Erreurs de compilation ---
|
||||
for m in re.finditer(r"error CS\d+:\s*(.+)", content):
|
||||
error_lines.append(m.group(1).strip()[:120])
|
||||
|
||||
# --- Noms des tests échoués : lignes commençant par "Failed <nom qualifié>" ---
|
||||
# (le compteur « Failed! » porte un '!' collé, donc pas de collision avec ce pattern)
|
||||
for m in re.finditer(r"^\s*Failed\s+([A-Za-z_][\w.]*\.\w[\w.]*)\s", content, re.MULTILINE):
|
||||
name = m.group(1).strip()
|
||||
if name not in failed_tests:
|
||||
failed_tests.append(name)
|
||||
|
||||
if not results and not error_lines and not failed_tests:
|
||||
# Aucune exécution de test détectée : le job a échoué AVANT de lancer dotnet test,
|
||||
# ou il a été skippé. On le dit explicitement plutôt que de sortir vide.
|
||||
if logs:
|
||||
print("_⚠️ Le job n'a produit aucun résultat de test (échec avant l'exécution ou build/DB en amont). Voir le log du job CI._")
|
||||
else:
|
||||
print("_⚠️ Aucun log de test produit par ce job._")
|
||||
sys.exit(0)
|
||||
|
||||
# Dédupliquer par projet
|
||||
seen = set()
|
||||
unique_results = []
|
||||
for r in results:
|
||||
if r[0] not in seen:
|
||||
seen.add(r[0])
|
||||
unique_results.append(r)
|
||||
results = unique_results
|
||||
|
||||
out = []
|
||||
if results:
|
||||
out.append("| Projet | Statut | Passed | Failed | Skipped | Total |")
|
||||
out.append("|---|---|---|---|---|---|")
|
||||
for proj, failed, passed, skipped, total, status in results:
|
||||
icon = "🟢" if status == "Passed!" else "🔴"
|
||||
out.append(f"| `{proj}` | {icon} | {passed} | {failed} | {skipped} | {total} |")
|
||||
failed_total = sum(int(r[1]) for r in results)
|
||||
passed_total = sum(int(r[2]) for r in results)
|
||||
if failed_total:
|
||||
out.append(f"\n**❌ {failed_total} test(s) en échec** — {passed_total} passent.")
|
||||
else:
|
||||
out.append(f"\n**✅ {passed_total} tests passent.**")
|
||||
|
||||
# Liste nominative des tests échoués
|
||||
if failed_tests:
|
||||
out.append("\n**Tests en échec :**")
|
||||
for name in failed_tests[:40]:
|
||||
out.append(f"- ❌ `{name}`")
|
||||
if len(failed_tests) > 40:
|
||||
out.append(f"\n_… et {len(failed_tests) - 40} autre(s) (voir log)_")
|
||||
|
||||
if error_lines:
|
||||
out.append("\n**Erreurs de compilation détectées :**")
|
||||
for e in error_lines[:10]:
|
||||
out.append(f"- `{e}`")
|
||||
|
||||
# Coverage moyen (cobertura)
|
||||
if cov_dir:
|
||||
rates = []
|
||||
for cf in glob.glob(os.path.join(cov_dir, "**", "*.cobertura.xml"), recursive=True):
|
||||
try:
|
||||
with open(cf, errors="replace") as fh:
|
||||
data = fh.read()
|
||||
lm = re.search(r'line-rate="([\d.]+)"', data)
|
||||
if lm:
|
||||
rates.append(float(lm.group(1)))
|
||||
except OSError:
|
||||
continue
|
||||
if rates:
|
||||
avg = sum(rates) / len(rates) * 100
|
||||
out.append(f"\n**Coverage moyen : {avg:.1f}%** ({len(rates)} projet(s))")
|
||||
|
||||
print("\n".join(out))
|
||||
@@ -1,43 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Poste un commentaire markdown sur une PR Forgejo.
|
||||
|
||||
Usage:
|
||||
post_comment.py <texte> [titre]
|
||||
|
||||
Env requis : FORGEJO_TOKEN, REPO (owner/repo), PR_NUMBER.
|
||||
Si REPO/PR_NUMBER/FORGEJO_TOKEN absents → warning, sortie 0 (commentaire ignoré).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
text = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
title = sys.argv[2] if len(sys.argv) > 2 else "CI"
|
||||
|
||||
repo = os.environ.get("REPO", "")
|
||||
pr = os.environ.get("PR_NUMBER", "")
|
||||
token = os.environ.get("FORGEJO_TOKEN", "")
|
||||
|
||||
if not text.strip():
|
||||
print("Rien à commenter — sortie sans commentaire")
|
||||
raise SystemExit(0)
|
||||
|
||||
body = f"## 🤖 {title}\n\n{text}\n\n_Généré automatiquement par la CI._"
|
||||
|
||||
if not repo or not pr or not token:
|
||||
print("::warning::REPO/PR_NUMBER/FORGEJO_TOKEN manquants — commentaire ignoré")
|
||||
raise SystemExit(0)
|
||||
|
||||
url = f"https://forgejo.tordais.cc/api/v1/repos/{repo}/issues/{pr}/comments"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps({"body": body}).encode(),
|
||||
headers={"Authorization": f"token {token}", "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
print(f"Commentaire posté sur la PR #{pr}")
|
||||
except Exception as e:
|
||||
print(f"::warning::Impossible de poster le commentaire: {e}")
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Poste un commentaire CVE (Trivy + Dependency-Check) sur une PR Forgejo.
|
||||
Usage: post_cve_comment.py
|
||||
Env: FORGEJO_TOKEN, TRIVY_REPORT, DC_REPORT, REPO, PR_NUMBER"""
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
body = ""
|
||||
trivy = os.environ.get("TRIVY_REPORT", "")
|
||||
dc = os.environ.get("DC_REPORT", "")
|
||||
if trivy:
|
||||
body += "\n" + trivy + "\n"
|
||||
if dc:
|
||||
body += "\n" + dc + "\n"
|
||||
if not body.strip():
|
||||
print("Aucune CVE à signaler — pas de commentaire")
|
||||
raise SystemExit(0)
|
||||
|
||||
body = "## 🛡️ Rapport sécurité — CVE détectées\n\n" + body + "\n\n_Généré automatiquement par la CI (Trivy / OWASP Dependency-Check)._"
|
||||
|
||||
repo = os.environ.get("REPO", "")
|
||||
pr = os.environ.get("PR_NUMBER", "")
|
||||
token = os.environ.get("FORGEJO_TOKEN", "")
|
||||
if not repo or not pr or not token:
|
||||
print("::warning::REPO/PR_NUMBER/FORGEJO_TOKEN manquants — commentaire ignoré")
|
||||
raise SystemExit(0)
|
||||
|
||||
url = f"https://forgejo.tordais.cc/api/v1/repos/{repo}/issues/{pr}/comments"
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=json.dumps({"body": body}).encode(),
|
||||
headers={"Authorization": f"token {token}", "Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
urllib.request.urlopen(req)
|
||||
print(f"Commentaire CVE posté sur la PR #{pr}")
|
||||
except Exception as e:
|
||||
print(f"::warning::Impossible de poster le commentaire CVE: {e}")
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
: "${RELEASE_TOKEN:?Dedicated Gitea release token is required}"
|
||||
: "${RELEASE_SIGNING_KEY_B64:?Publisher ECDSA P-256 private key is required}"
|
||||
: "${BUILD_SERVER_URL:?Gitea URL is required}"
|
||||
: "${EXPECTED_BUILD_SERVER_URL:?Expected Gitea URL is required}"
|
||||
: "${BUILD_REPOSITORY:?Repository is required}"
|
||||
python3 - "$BUILD_SERVER_URL" "$EXPECTED_BUILD_SERVER_URL" <<'PY'
|
||||
import sys
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
actual, expected = (urlsplit(value) for value in sys.argv[1:])
|
||||
def valid_origin(value):
|
||||
return (value.scheme == 'https' and bool(value.hostname) and
|
||||
value.path in ('', '/') and not value.query and not value.fragment and
|
||||
value.username is None and value.password is None)
|
||||
|
||||
if (not valid_origin(actual) or not valid_origin(expected) or
|
||||
actual.hostname.lower() != expected.hostname.lower() or
|
||||
(actual.port or 443) != (expected.port or 443)):
|
||||
raise SystemExit('Unexpected publication host')
|
||||
PY
|
||||
[[ "$BUILD_REPOSITORY" == arnaud.dartois/Heimdall ]] || { echo 'Unexpected publication repository' >&2; exit 1; }
|
||||
sha=$(git rev-parse HEAD)
|
||||
umask 077
|
||||
signing_key=$(mktemp)
|
||||
trap 'rm -f "$signing_key"' EXIT
|
||||
printf '%s' "$RELEASE_SIGNING_KEY_B64" | base64 -d > "$signing_key"
|
||||
openssl pkey -in "$signing_key" -noout >/dev/null
|
||||
openssl ec -in "$signing_key" -noout -text 2>/dev/null | grep -q 'ASN1 OID: prime256v1' || {
|
||||
echo 'Release signing key must use ECDSA P-256' >&2
|
||||
exit 1
|
||||
}
|
||||
openssl pkey -in "$signing_key" -pubout -out artifacts/packages/agent-release-public.pem
|
||||
(cd artifacts/packages && sha256sum agent-release-public.pem >> SHA256SUMS)
|
||||
[[ "$BUILD_REF" == refs/tags/* ]] || { echo 'Release publication is restricted to version tags MAJOR.MINOR.PATCH' >&2; exit 1; }
|
||||
tag=${BUILD_REF#refs/tags/}
|
||||
python3 - "$sha" "$tag" <<'PY'
|
||||
import json,sys
|
||||
with open('artifacts/packages/provenance.json') as f:p=json.load(f)
|
||||
if p['commit'] != sys.argv[1] or p['version'] != sys.argv[2] or p['ref'] != 'refs/tags/' + sys.argv[2]:
|
||||
raise SystemExit('Artifact provenance does not match the verified version tag')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum --check SHA256SUMS)
|
||||
version=$(python3 -c 'import json;print(json.load(open("artifacts/packages/provenance.json"))["version"])')
|
||||
printf '%s' "$version" > artifacts/version
|
||||
# The three image jobs have already built, scanned and pushed this exact commit.
|
||||
# Pull only those immutable refs here; this job must not rebuild or rescan images.
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"; rm -f "$signing_key"' EXIT
|
||||
server_image=eltruncho/heimdall
|
||||
agent_image=eltruncho/heimdall-agent
|
||||
agent_gpu_image=eltruncho/heimdall-agent-gpu
|
||||
: "${DOCKERHUB_USERNAME:?Docker Hub user is required}"
|
||||
: "${DOCKERHUB_TOKEN:?Docker Hub token is required}"
|
||||
printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin
|
||||
: > artifacts/image-digests.txt
|
||||
for component in server agent agent-gpu; do
|
||||
if [[ "$component" == agent ]]; then
|
||||
image=$agent_image
|
||||
elif [[ "$component" == agent-gpu ]]; then
|
||||
image=$agent_gpu_image
|
||||
else
|
||||
image=$server_image
|
||||
fi
|
||||
docker pull "$image:sha-$sha"
|
||||
revision=$(docker image inspect "$image:sha-$sha" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')
|
||||
[[ "$revision" == "$sha" ]] || { echo 'Pulled image does not match the versioned source commit' >&2; exit 1; }
|
||||
digest=$(python3 scripts/ci/dockerhub-tag-digest.py "$image" "sha-$sha")
|
||||
printf '%s@%s\n' "$image" "$digest" >> artifacts/image-digests.txt
|
||||
done
|
||||
cp artifacts/image-digests.txt artifacts/packages/image-digests.txt
|
||||
(cd artifacts/packages && sha256sum image-digests.txt >> SHA256SUMS)
|
||||
python3 - "$agent_image" <<'PY'
|
||||
import json,sys
|
||||
repository=sys.argv[1]
|
||||
matches=set()
|
||||
for line in open('artifacts/image-digests.txt'):
|
||||
ref=line.strip()
|
||||
if '@' not in ref: continue
|
||||
image,digest=ref.rsplit('@',1)
|
||||
if image == repository and digest.startswith('sha256:') and len(digest) == 71:
|
||||
matches.add(digest)
|
||||
if len(matches) != 1:
|
||||
raise SystemExit('Expected one immutable agent image digest for configured repository')
|
||||
with open('artifacts/packages/agent-image.json','w') as f:
|
||||
json.dump({'image':repository,'digest':matches.pop()},f,sort_keys=True,separators=(',',':'))
|
||||
f.write('\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum agent-image.json >> SHA256SUMS)
|
||||
python3 - "$agent_gpu_image" <<'PY'
|
||||
import json,sys
|
||||
repository=sys.argv[1]
|
||||
matches=set()
|
||||
for line in open('artifacts/image-digests.txt'):
|
||||
ref=line.strip()
|
||||
if '@' not in ref: continue
|
||||
image,digest=ref.rsplit('@',1)
|
||||
if image == repository and digest.startswith('sha256:') and len(digest) == 71:
|
||||
matches.add(digest)
|
||||
if len(matches) != 1:
|
||||
raise SystemExit('Expected one immutable GPU agent image digest for configured repository')
|
||||
with open('artifacts/packages/agent-image-gpu.json','w') as f:
|
||||
json.dump({'image':repository,'digest':matches.pop()},f,sort_keys=True,separators=(',',':'))
|
||||
f.write('\n')
|
||||
PY
|
||||
(cd artifacts/packages && sha256sum agent-image-gpu.json >> SHA256SUMS)
|
||||
python3 - <<'PY'
|
||||
import hashlib,json,re
|
||||
from pathlib import Path
|
||||
root=Path('artifacts/packages')
|
||||
image=json.loads((root/'agent-image.json').read_text())
|
||||
gpu_image=json.loads((root/'agent-image-gpu.json').read_text())
|
||||
package_version=Path('artifacts/version').read_text().strip()
|
||||
version=package_version
|
||||
assets={}
|
||||
for path in root.glob('heimdall-agent-*.tar.gz'):
|
||||
suffix=f'-{package_version}.tar.gz'
|
||||
if not path.name.endswith(suffix):
|
||||
continue
|
||||
platform=path.name[len('heimdall-agent-'):-len(suffix)]
|
||||
if not re.fullmatch(r'[a-z0-9-]+',platform):
|
||||
raise SystemExit('Invalid agent archive platform')
|
||||
assets[platform]=hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
if not assets:
|
||||
raise SystemExit('No agent archive to sign')
|
||||
payload={'version':version,'assets':assets,'containerImage':image['image'],
|
||||
'containerImageDigest':image['digest'],'containerImageGpu':gpu_image['image'],
|
||||
'containerImageGpuDigest':gpu_image['digest']}
|
||||
(root/'agent-update-manifest.json').write_text(
|
||||
json.dumps(payload,sort_keys=True,separators=(',',':'))+'\n')
|
||||
PY
|
||||
openssl dgst -sha256 -sign "$signing_key" \
|
||||
-out artifacts/packages/agent-update-manifest.sig artifacts/packages/agent-update-manifest.json
|
||||
(cd artifacts/packages && sha256sum agent-update-manifest.json agent-update-manifest.sig >> SHA256SUMS)
|
||||
python3 scripts/ci/release-gitea.py
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mode=${1:?Expected server, agent or agent-gpu}
|
||||
case "$mode" in server|agent|agent-gpu) ;; *) echo 'Usage: push-images.sh server|agent|agent-gpu' >&2; exit 2 ;; esac
|
||||
sha=$(git rev-parse HEAD)
|
||||
ref=${BUILD_REF:-}
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
version=${ref#refs/tags/}
|
||||
else
|
||||
version="0.0.0-ci.${sha:0:12}"
|
||||
fi
|
||||
export DOCKER_CONFIG
|
||||
DOCKER_CONFIG=$(mktemp -d)
|
||||
trap 'rm -rf "$DOCKER_CONFIG"' EXIT
|
||||
repository() {
|
||||
case "$1" in
|
||||
server) printf 'eltruncho/heimdall' ;;
|
||||
agent) printf 'eltruncho/heimdall-agent' ;;
|
||||
agent-gpu) printf 'eltruncho/heimdall-agent-gpu' ;;
|
||||
esac
|
||||
}
|
||||
: "${DOCKERHUB_USERNAME:?Docker Hub user is required}"
|
||||
: "${DOCKERHUB_TOKEN:?Docker Hub token is required}"
|
||||
printf '%s' "$DOCKERHUB_TOKEN" | docker login docker.io -u "$DOCKERHUB_USERNAME" --password-stdin
|
||||
repo=$(repository "$mode")
|
||||
docker image inspect "heimdall-$mode:ci-$sha" >/dev/null
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:sha-$sha"
|
||||
docker push "$repo:sha-$sha"
|
||||
if [[ "$ref" == refs/tags/* ]]; then
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:$version"
|
||||
docker push "$repo:$version"
|
||||
elif [[ "$ref" == refs/heads/main ]]; then
|
||||
docker tag "heimdall-$mode:ci-$sha" "$repo:latest"
|
||||
docker push "$repo:latest"
|
||||
fi
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Create/update the Gitea release for one verified version tag."""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
base = os.environ['BUILD_SERVER_URL'] + '/api/v1/repos/' + os.environ['BUILD_REPOSITORY']
|
||||
token = os.environ['RELEASE_TOKEN']
|
||||
provenance = json.loads(Path('artifacts/packages/provenance.json').read_text())
|
||||
tag = os.environ['RELEASE_TAG']
|
||||
if tag != provenance['version']:
|
||||
raise SystemExit('Release tag does not match the packaged application version')
|
||||
|
||||
def request(path, method='GET', body=None, content_type='application/json', missing=False):
|
||||
data = json.dumps(body).encode() if content_type == 'application/json' and body is not None else body
|
||||
req = urllib.request.Request(base+path, data=data, method=method, headers={
|
||||
'Authorization': 'token '+token, 'Content-Type': content_type})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=90) as response:
|
||||
payload = response.read()
|
||||
return json.loads(payload) if payload else None
|
||||
except urllib.error.HTTPError as error:
|
||||
if missing and error.code == 404:
|
||||
return None
|
||||
raise SystemExit(f'Gitea release API failed: HTTP {error.code}') from None
|
||||
|
||||
release = request('/releases/tags/'+urllib.parse.quote(tag, safe=''), missing=True)
|
||||
package_root = Path('artifacts/packages')
|
||||
installer_bundle = package_root / f'heimdall-installers-{tag}.zip'
|
||||
installer_checksum = package_root / f'{installer_bundle.name}.sha256'
|
||||
agent_archives = sorted(package_root.glob(f'heimdall-agent-*-{tag}.tar.gz'))
|
||||
required_assets = [installer_bundle, installer_checksum, package_root / 'agent-release-public.pem',
|
||||
package_root / 'agent-update-manifest.json', package_root / 'agent-update-manifest.sig',
|
||||
package_root / 'agent-image.json', package_root / 'agent-image-gpu.json']
|
||||
if any(not path.is_file() for path in required_assets) or not agent_archives:
|
||||
raise SystemExit('Installer bundle or signed Agent update assets are missing')
|
||||
# CI provenance, image digests, and general checksum bookkeeping stay in the
|
||||
# build artifacts. Publish the installer bundle's checksum as a sidecar so
|
||||
# bootstraps can verify it when the Gitea asset API omits its digest field.
|
||||
package_files = sorted([*required_assets, *agent_archives])
|
||||
if release is None:
|
||||
release = request('/releases', 'POST', {
|
||||
'tag_name': tag, 'target_commitish': provenance['commit'], 'name': provenance['version'],
|
||||
'draft': True, 'prerelease': '-' in provenance['version'],
|
||||
'body': f"Automated Heimdall release `{provenance['version']}` from `{provenance['commit']}`.\n"
|
||||
f"Actions run: {provenance['run_id']}\n\n"
|
||||
'## Changes\n'
|
||||
+ Path(os.environ['RELEASE_NOTES_FILE']).read_text()})
|
||||
if release.get('tag_name') != tag:
|
||||
raise SystemExit('Refusing to mutate a release not owned by this commit')
|
||||
assets_path = f"/releases/{release['id']}/assets"
|
||||
assets = request(assets_path)
|
||||
expected_names = {path.name for path in package_files}
|
||||
if not release.get('draft'):
|
||||
if {asset.get('name') for asset in assets} != expected_names:
|
||||
raise SystemExit('Published release has incomplete assets; refusing to mutate it')
|
||||
print('Release already published: '+release['html_url'])
|
||||
raise SystemExit(0)
|
||||
|
||||
# Keep the release invisible to `/releases/latest` until all signed assets are present.
|
||||
for asset in assets:
|
||||
request(f"/releases/{release['id']}/assets/{asset['id']}", 'DELETE')
|
||||
for path in package_files:
|
||||
boundary = uuid.uuid4().hex
|
||||
payload = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode()
|
||||
+ path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode())
|
||||
request(f"/releases/{release['id']}/assets?name="+urllib.parse.quote(path.name),
|
||||
'POST', payload, 'multipart/form-data; boundary='+boundary)
|
||||
|
||||
expected_prerelease = '-' in provenance['version']
|
||||
published = request(f"/releases/{release['id']}", 'PATCH', {
|
||||
'draft': False,
|
||||
'prerelease': expected_prerelease,
|
||||
})
|
||||
if published.get('draft') is not False or published.get('prerelease') is not expected_prerelease:
|
||||
raise SystemExit('Gitea did not publish the completed release with the expected latest status')
|
||||
print('Published release: '+release['html_url'])
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Generate release notes from pull requests merged since the previous version tag."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
base = os.environ['BUILD_SERVER_URL'].rstrip('/') + '/api/v1/repos/' + os.environ['BUILD_REPOSITORY']
|
||||
token = os.environ['GITEA_TOKEN']
|
||||
before = os.environ['BEFORE_SHA']
|
||||
current = os.environ['CURRENT_SHA']
|
||||
|
||||
|
||||
def get(path):
|
||||
request = urllib.request.Request(base + path, headers={
|
||||
'Authorization': 'token ' + token,
|
||||
'Accept': 'application/json',
|
||||
})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return json.load(response)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 404:
|
||||
return None
|
||||
raise SystemExit(f'Gitea release notes API failed: HTTP {error.code}') from None
|
||||
|
||||
|
||||
comparison = get('/compare/' + urllib.parse.quote(before, safe='') + '...' + urllib.parse.quote(current, safe=''))
|
||||
if comparison is None:
|
||||
raise SystemExit('Gitea could not compare the previous and current main commits')
|
||||
pulls = {}
|
||||
for commit in comparison.get('commits', []):
|
||||
pull = get('/commits/' + urllib.parse.quote(commit['sha'], safe='') + '/pull')
|
||||
if pull and pull.get('merged') and pull.get('number'):
|
||||
pulls[pull['number']] = pull
|
||||
|
||||
lines = []
|
||||
for number, pull in sorted(pulls.items()):
|
||||
title = pull.get('title') or f'Pull request #{number}'
|
||||
url = pull.get('html_url') or f"{base.removesuffix('/api/v1/repos/' + os.environ['BUILD_REPOSITORY'])}/pulls/{number}"
|
||||
lines.append(f'- {title} ([#{number}]({url}))')
|
||||
|
||||
if not lines:
|
||||
lines = [f'- Changes merged in commit `{current}`.']
|
||||
|
||||
Path('artifacts/release-notes.md').write_text('\n'.join(lines) + '\n')
|
||||
print(f'Generated release notes for {len(pulls)} merged pull request(s).')
|
||||
@@ -1,184 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""release_notes.py — Génère les release notes Forgejo depuis le dernier tag du même préfixe.
|
||||
|
||||
Usage:
|
||||
release_notes.py [TAG] [PREFIX] [REPO_URL]
|
||||
|
||||
TAG : tag de la release courante (défaut : détecté via git describe)
|
||||
PREFIX : préfixe de tag (défaut : 'v') — les notes ne comparent qu'avec
|
||||
les tags du même préfixe (ex. 'agent-v' pour l'agent)
|
||||
REPO_URL : base d'URL du repo pour les liens commits (défaut : forgejo.tordais.cc)
|
||||
|
||||
Sortie : markdown prêt pour le body d'une release Forgejo (stdout).
|
||||
"""
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import datetime
|
||||
|
||||
|
||||
CATEGORIES = {
|
||||
"feat": ("✨ Features", "feature"),
|
||||
"fix": ("🐛 Fixes", "bug"),
|
||||
"perf": ("⚡ Performance", "perf"),
|
||||
"chore": ("🧹 Maintenance", "chore"),
|
||||
"refactor": ("🧹 Maintenance", "refactor"),
|
||||
"docs": ("🧹 Maintenance", "docs"),
|
||||
"style": ("🧹 Maintenance", "style"),
|
||||
"build": ("🧹 Maintenance", "build"),
|
||||
"ci": ("🧹 Maintenance", "ci"),
|
||||
"test": ("🧹 Maintenance", "test"),
|
||||
"revert": ("↩️ Reverts", "revert"),
|
||||
}
|
||||
|
||||
|
||||
def git(*args):
|
||||
r = subprocess.run(["git", *args], capture_output=True, text=True)
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def git_or_none(*args):
|
||||
r = subprocess.run(["git", *args], capture_output=True, text=True)
|
||||
return r.stdout.strip() if r.returncode == 0 else ""
|
||||
|
||||
|
||||
def tag_date(t):
|
||||
return git_or_none("log", "-1", "--format=%ct", t)
|
||||
|
||||
|
||||
def detect_repo():
|
||||
"""Détecte owner/repo depuis le remote git origin."""
|
||||
url = git_or_none("remote", "get-url", "origin")
|
||||
if not url:
|
||||
return None
|
||||
# https://host/owner/repo.git ou git@host:owner/repo.git
|
||||
m = re.search(r'[:/]([^/]+)/([^/]+?)(?:\.git)?$', url)
|
||||
if m:
|
||||
return f"{m.group(1)}/{m.group(2)}"
|
||||
return None
|
||||
|
||||
|
||||
def parse_commit(line):
|
||||
"""'abc1234|message' -> (sha, subject)"""
|
||||
if "|" in line:
|
||||
sha, subject = line.split("|", 1)
|
||||
else:
|
||||
sha, subject = line, line
|
||||
return sha, subject
|
||||
|
||||
|
||||
def categorize(subject):
|
||||
subject_l = subject.lower()
|
||||
for prefix, (title, _) in CATEGORIES.items():
|
||||
if subject_l.startswith(prefix + ":") or subject_l.startswith(prefix + "("):
|
||||
return title
|
||||
return "📦 Autres"
|
||||
|
||||
|
||||
def link_issues(subject, forgejo_url, repo_slug):
|
||||
"""Convertit les références #N en liens cliquables — scan unique sans double-processing.
|
||||
|
||||
Formats gérés (par priorité) :
|
||||
- Fixes/Closes/Resolves/Refs/See #61 → [Fixes #61](URL)
|
||||
- (#154) → [(#154)](URL)
|
||||
- #42 standalone → [#42](URL)
|
||||
"""
|
||||
if not repo_slug:
|
||||
return subject
|
||||
|
||||
base = f"https://{forgejo_url}/{repo_slug}/issues"
|
||||
|
||||
# Scan unique : tous les patterns dans un seul regex, groupes nommés
|
||||
combined = re.compile(
|
||||
r'(?P<kw>(?:Fixes|Closes|Resolves|Refs|See)\s+#(?P<kw_n>\d+))'
|
||||
r'|\(#(?P<paren_n>\d+)\)'
|
||||
r'|(?<!\w)#(?P<stand_n>\d+)\b'
|
||||
)
|
||||
|
||||
# Collecte de toutes les insertions (offset → replacement)
|
||||
insertions = []
|
||||
for m in combined.finditer(subject):
|
||||
if m.group('kw'):
|
||||
kw_text, num = m.group('kw'), m.group('kw_n')
|
||||
replacement = f"[{kw_text}]({base}/{num})"
|
||||
elif m.group('paren_n'):
|
||||
num = m.group('paren_n')
|
||||
replacement = f"[(#{num})]({base}/{num})"
|
||||
else:
|
||||
num = m.group('stand_n')
|
||||
replacement = f"[#{num}]({base}/{num})"
|
||||
insertions.append((m.start(), m.end(), replacement))
|
||||
|
||||
if not insertions:
|
||||
return subject
|
||||
|
||||
# Reconstruction de la chaîne en une passe
|
||||
parts = []
|
||||
prev_end = 0
|
||||
for start, end, repl in insertions:
|
||||
parts.append(subject[prev_end:start])
|
||||
parts.append(repl)
|
||||
prev_end = end
|
||||
parts.append(subject[prev_end:])
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def main():
|
||||
tag = sys.argv[1] if len(sys.argv) > 1 else git("describe", "--tags", "--abbrev=0") or ""
|
||||
prefix = sys.argv[2] if len(sys.argv) > 2 else "v"
|
||||
forgejo_url = sys.argv[3] if len(sys.argv) > 3 else "forgejo.tordais.cc"
|
||||
|
||||
# Détection automatique owner/repo pour les liens issues
|
||||
repo_slug = detect_repo()
|
||||
|
||||
# Dernier tag du même préfixe, antérieur à celui-ci (par date du commit tagué)
|
||||
all_tags = [t for t in git("tag", "--list").splitlines() if t.startswith(prefix) and t != tag]
|
||||
all_tags.sort(key=lambda t: (tag_date(t) or "0"), reverse=True)
|
||||
prev = all_tags[0] if all_tags else None
|
||||
|
||||
if prev:
|
||||
raw = git("log", f"{prev}..{tag}", "--pretty=format:%h|%s")
|
||||
elif tag:
|
||||
raw = git("log", tag, "--pretty=format:%h|%s")
|
||||
else:
|
||||
raw = git("log", "--pretty=format:%h|%s")
|
||||
|
||||
commits = [parse_commit(l) for l in raw.splitlines() if l]
|
||||
|
||||
if not commits:
|
||||
print(f"## {tag} — {datetime.date.today().isoformat()}\n\n_No commits._")
|
||||
return 0
|
||||
|
||||
grouped = {}
|
||||
for sha, subject in commits:
|
||||
grouped.setdefault(categorize(subject), []).append((sha, subject))
|
||||
|
||||
today = datetime.date.today().isoformat()
|
||||
lines = [f"## {tag} — {today}", ""]
|
||||
|
||||
for title in ["✨ Features", "🐛 Fixes", "⚡ Performance", "↩️ Reverts", "🧹 Maintenance", "📦 Autres"]:
|
||||
items = grouped.get(title)
|
||||
if not items:
|
||||
continue
|
||||
lines.append(f"### {title}")
|
||||
lines.append("")
|
||||
for sha, subject in items:
|
||||
linked = link_issues(subject, forgejo_url, repo_slug)
|
||||
lines.append(f"- {linked} ([`{sha}`](https://{forgejo_url}/commit/{sha}))")
|
||||
lines.append("")
|
||||
|
||||
# Liste complète repliable
|
||||
lines.append(f"<details><summary>🔗 {len(commits)} commits</summary>")
|
||||
lines.append("")
|
||||
for sha, subject in commits:
|
||||
linked = link_issues(subject, forgejo_url, repo_slug)
|
||||
lines.append(f"- [`{sha}`](https://{forgejo_url}/commit/{sha}) {linked}")
|
||||
lines.append("")
|
||||
lines.append("</details>")
|
||||
|
||||
print("\n".join(lines))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,60 @@
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const endpoint = process.env.RENOVATE_ENDPOINT;
|
||||
const token = process.env.RENOVATE_TOKEN;
|
||||
const repository = 'arnaud.dartois/Heimdall';
|
||||
|
||||
export function validateEndpoint(value) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(value);
|
||||
} catch {
|
||||
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
|
||||
}
|
||||
|
||||
if (parsed.protocol !== 'https:' || parsed.username || parsed.password ||
|
||||
parsed.search || parsed.hash || !parsed.pathname.replace(/\/$/, '').endsWith('/api/v1')) {
|
||||
throw new Error('FORGEJO_API_ENDPOINT must be a valid HTTPS URL ending in /api/v1.');
|
||||
}
|
||||
|
||||
return parsed.href.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
export async function checkGiteaAccess(apiEndpoint, accessToken, fetchImpl = fetch) {
|
||||
const root = `${validateEndpoint(apiEndpoint)}/`;
|
||||
const urls = [new URL('user', root), new URL(`repos/${repository}`, root)];
|
||||
|
||||
for (const url of urls) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetchImpl(url, {
|
||||
headers: { Authorization: `token ${accessToken}`, Accept: 'application/json' },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Gitea API preflight could not connect (${error?.name ?? 'network error'}).`);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const detail = response.status === 401 || response.status === 403
|
||||
? 'Check that RENOVATE_TOKEN is active and has repository read and write access.'
|
||||
: 'Check FORGEJO_API_ENDPOINT and the Forgejo API availability.';
|
||||
throw new Error(`Gitea API preflight failed with HTTP ${response.status}. ${detail}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
if (!token) {
|
||||
console.error('RENOVATE_TOKEN is missing. Configure it as a Gitea Actions secret.');
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
try {
|
||||
await checkGiteaAccess(endpoint, token);
|
||||
console.log('Renovate token authenticated with Gitea and can read the target repository.');
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { checkGiteaAccess, validateEndpoint } from './renovate-preflight.mjs';
|
||||
|
||||
test('accepts an HTTPS Forgejo API endpoint and trims its trailing slash', () => {
|
||||
assert.equal(validateEndpoint('https://forge.example/api/v1/'), 'https://forge.example/api/v1');
|
||||
});
|
||||
|
||||
test('rejects non-HTTPS, malformed, and non-API endpoints', () => {
|
||||
for (const value of ['http://forge.example/api/v1', 'https://forge.example/', 'not a URL']) {
|
||||
assert.throws(() => validateEndpoint(value), /FORGEJO_API_ENDPOINT.*HTTPS URL ending in \/api\/v1/);
|
||||
}
|
||||
});
|
||||
|
||||
test('checks identity and repository reads without exposing the token', async () => {
|
||||
const calls = [];
|
||||
await checkGiteaAccess('https://forge.example/api/v1', 'secret-token', async (url, options) => {
|
||||
calls.push({ url: url.href, authorization: options.headers.Authorization });
|
||||
return { ok: true, status: 200 };
|
||||
});
|
||||
assert.deepEqual(calls.map(call => new URL(call.url).pathname), [
|
||||
'/api/v1/user', '/api/v1/repos/arnaud.dartois/Heimdall',
|
||||
]);
|
||||
assert.ok(calls.every(call => call.authorization === 'token secret-token'));
|
||||
});
|
||||
|
||||
test('reports authentication status without printing response details or credentials', async () => {
|
||||
await assert.rejects(
|
||||
checkGiteaAccess('https://forge.example/api/v1', 'secret-token', async () => ({
|
||||
ok: false, status: 403,
|
||||
})),
|
||||
error => error.message.includes('HTTP 403') &&
|
||||
error.message.includes('repository read and write access') &&
|
||||
!error.message.includes('secret-token'),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
mode=${1:-all}
|
||||
case "$mode" in dependencies|server|agent|agent-gpu|all) ;; *) echo 'Usage: security.sh [dependencies|server|agent|agent-gpu|all]' >&2; exit 2 ;; esac
|
||||
skip_restore=false
|
||||
if [[ $# -gt 1 ]]; then
|
||||
if [[ "$mode" == dependencies && $# == 2 && "${2}" == --no-restore ]]; then
|
||||
skip_restore=true
|
||||
else
|
||||
echo 'Usage: security.sh [dependencies [--no-restore]|server|agent|all]' >&2
|
||||
exit 2
|
||||
fi
|
||||
fi
|
||||
mkdir -p artifacts/security
|
||||
status=0
|
||||
if [[ "$mode" == dependencies || "$mode" == all ]]; then
|
||||
echo "Checking restored NuGet dependencies for advisories"
|
||||
if [[ "$skip_restore" == false ]]; then
|
||||
dotnet restore Heimdall.slnx --locked-mode
|
||||
fi
|
||||
dotnet list Heimdall.slnx package --no-restore --vulnerable --include-transitive --format json > artifacts/security/nuget.json || {
|
||||
echo "NuGet advisory query failed; see artifacts/security/nuget.json" >&2
|
||||
exit 1
|
||||
}
|
||||
python3 scripts/ci/check-advisories.py artifacts/security/nuget.json || status=1
|
||||
fi
|
||||
[[ "$mode" == dependencies ]] && exit "$status"
|
||||
sha=$(git rev-parse HEAD)
|
||||
scanner=aquasec/trivy:0.69.3@sha256:bcc376de8d77cfe086a917230e818dc9f8528e3c852f7b1aff648949b6258d1c
|
||||
cache_volume="heimdall-trivy-cache-$sha"
|
||||
echo "Creating Trivy cache volume"
|
||||
docker volume create "$cache_volume" >/dev/null || { echo "Could not create Trivy cache volume" >&2; exit 1; }
|
||||
trap 'docker volume rm "$cache_volume" >/dev/null 2>&1 || true' EXIT
|
||||
scan_image() (
|
||||
set -euo pipefail
|
||||
component=$1
|
||||
archive=$(mktemp)
|
||||
scanner_container=""
|
||||
trap 'rm -f "$archive"; if [[ -n "$scanner_container" ]]; then docker rm -f "$scanner_container" >/dev/null 2>&1 || true; fi' EXIT
|
||||
echo "Exporting heimdall-$component:ci-$sha for Trivy"
|
||||
docker save "heimdall-$component:ci-$sha" -o "$archive" || { echo "Could not export heimdall-$component:ci-$sha" >&2; exit 1; }
|
||||
report="artifacts/security/$component.json"
|
||||
# Trivy reopens archive entries: stdin cannot serve as a seekable image tar.
|
||||
# Docker cp streams from the job container, without daemon-host bind paths.
|
||||
# Share the database between scans and retry an infrastructure failure once;
|
||||
# a completed report with findings still fails the gate immediately.
|
||||
for attempt in 1 2; do
|
||||
scanner_container=$(docker create --mount "source=$cache_volume,target=/root/.cache/trivy" \
|
||||
"$scanner" image \
|
||||
--db-repository ghcr.io/aquasecurity/trivy-db:2 \
|
||||
--db-repository mirror.gcr.io/aquasec/trivy-db:2 \
|
||||
--input /tmp/image.tar --scanners vuln \
|
||||
--severity HIGH,CRITICAL --exit-code 1 --format json) || { echo "Could not create Trivy scanner for $component" >&2; exit 1; }
|
||||
docker cp "$archive" "$scanner_container:/tmp/image.tar" >/dev/null || { echo "Could not copy image archive to Trivy scanner for $component" >&2; exit 1; }
|
||||
cli_status=0
|
||||
docker start --attach "$scanner_container" > "$report" || cli_status=$?
|
||||
state=$(docker inspect "$scanner_container" --format '{{.State.Status}} {{.State.ExitCode}}') || exit 1
|
||||
if [[ -s "$report" ]]; then
|
||||
[[ "$cli_status" == 0 && "$state" == "exited 0" ]] || echo "Trivy scan failed for $component (exit=$cli_status, state=$state); report retained at $report" >&2
|
||||
[[ "$cli_status" == 0 && "$state" == "exited 0" ]]
|
||||
exit $?
|
||||
fi
|
||||
docker rm -f "$scanner_container" >/dev/null 2>&1 || true
|
||||
scanner_container=""
|
||||
if [[ "$attempt" == 1 ]]; then
|
||||
echo "Trivy infrastructure failure for $component; retrying once" >&2
|
||||
sleep 2
|
||||
fi
|
||||
done
|
||||
echo "Trivy returned no report for $component after retry" >&2
|
||||
exit 1
|
||||
)
|
||||
case "$mode" in
|
||||
all) components=(server agent agent-gpu) ;;
|
||||
*) components=("$mode") ;;
|
||||
esac
|
||||
for component in "${components[@]}"; do
|
||||
if ! docker image inspect "heimdall-$component:ci-$sha" >/dev/null 2>&1; then
|
||||
echo "Missing image for security scan: $component" >&2
|
||||
status=1
|
||||
continue
|
||||
fi
|
||||
scan_image "$component" || status=1
|
||||
done
|
||||
exit "$status"
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Choose affected test projects for a PR; test everything on main and tags."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TESTS = sorted(path for path in (ROOT / "tests").glob("*/*.csproj") if path.stem != "Heimdall.TestCommon")
|
||||
SOURCES = sorted((ROOT / "src").glob("*/*.csproj"))
|
||||
ALL_PROJECTS = [*SOURCES, *(ROOT / "tests").glob("*/*.csproj")]
|
||||
|
||||
|
||||
def references(project: Path) -> set[Path]:
|
||||
tree = ET.parse(project)
|
||||
return {
|
||||
(project.parent / item.attrib["Include"].replace("\\", "/")).resolve()
|
||||
for item in tree.iter("ProjectReference")
|
||||
}
|
||||
|
||||
|
||||
def referenced_projects(project: Path, graph: dict[Path, set[Path]]) -> set[Path]:
|
||||
result: set[Path] = set()
|
||||
pending = list(graph.get(project, set()))
|
||||
while pending:
|
||||
dependency = pending.pop()
|
||||
if dependency in result:
|
||||
continue
|
||||
result.add(dependency)
|
||||
pending.extend(graph.get(dependency, set()))
|
||||
return result
|
||||
|
||||
|
||||
def build_targets(affected: set[Path], suites: list[str], graph: dict[Path, set[Path]],
|
||||
mode: str) -> list[str]:
|
||||
if mode == "all":
|
||||
return ["Heimdall.slnx"]
|
||||
|
||||
suite_projects = [project for project in TESTS if project.stem in suites]
|
||||
covered_sources = set().union(*(referenced_projects(project, graph) for project in suite_projects)) if suite_projects else set()
|
||||
targets = [*suite_projects, *(project for project in SOURCES
|
||||
if project.resolve() in affected and project.resolve() not in covered_sources)]
|
||||
return sorted({project.resolve().relative_to(ROOT).as_posix() for project in targets})
|
||||
|
||||
|
||||
def changed_files() -> list[str] | None:
|
||||
if os.environ.get("GITEA_EVENT_NAME") != "pull_request":
|
||||
return None
|
||||
result = subprocess.run(
|
||||
["git", "diff", "--name-only", "origin/main...HEAD"],
|
||||
cwd=ROOT, text=True, capture_output=True, check=False,
|
||||
)
|
||||
return result.stdout.splitlines() if result.returncode == 0 else None
|
||||
|
||||
|
||||
def plan(changed: list[str] | None) -> dict[str, object]:
|
||||
if changed is None:
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": [], "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, {}, "all")}
|
||||
|
||||
all_paths = {p.resolve() for p in ALL_PROJECTS}
|
||||
graph = {project: references(project) for project in all_paths}
|
||||
changed_projects: set[Path] = set()
|
||||
broad = False
|
||||
for name in changed:
|
||||
parts = Path(name).parts
|
||||
if parts and parts[0] in {"src", "tests"} and len(parts) >= 3:
|
||||
if name.endswith(".csproj"):
|
||||
broad = True
|
||||
matches = list((ROOT / parts[0] / parts[1]).glob("*.csproj"))
|
||||
changed_projects.update(p.resolve() for p in matches)
|
||||
elif parts and parts[0] in {"src", "tests"}:
|
||||
broad = True
|
||||
elif name.startswith(("scripts/ci/", "docker/", "models/")) or name in {
|
||||
"Heimdall.slnx", "global.json", "Directory.Build.props",
|
||||
"Directory.Build.targets", "GitVersion.yml", "GitVersion.yaml",
|
||||
}:
|
||||
broad = True
|
||||
|
||||
if not broad and changed and not changed_projects and all(
|
||||
name.startswith(("docs/", "skills/"))
|
||||
or name in {"readme.md", "AGENTS.md", ".gitea/PULL_REQUEST_TEMPLATE.md"}
|
||||
for name in changed
|
||||
):
|
||||
return {"mode": "affected", "changed": changed, "suites": [], "build_projects": []}
|
||||
|
||||
if broad or (changed and not changed_projects):
|
||||
suites = [p.stem for p in TESTS]
|
||||
return {"mode": "all", "changed": changed, "suites": suites,
|
||||
"build_projects": build_targets(set(), suites, graph, "all")}
|
||||
|
||||
affected = set(changed_projects)
|
||||
while True:
|
||||
additions = {project for project, refs in graph.items() if refs & affected}
|
||||
if additions <= affected:
|
||||
break
|
||||
affected |= additions
|
||||
|
||||
suites = [p.stem for p in TESTS if p.resolve() in affected]
|
||||
projects = build_targets(affected, suites, graph, "affected")
|
||||
return {"mode": "affected", "changed": changed, "suites": suites,
|
||||
"build_projects": projects}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = plan(changed_files())
|
||||
output = ROOT / "artifacts" / "tests" / "plan.json"
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(result, indent=2) + "\n")
|
||||
print(f"Test plan: {result['mode']} — {', '.join(result['suites']) or 'no .NET suite'}")
|
||||
print(f"Build targets: {', '.join(result['build_projects']) or 'none'}")
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
name=${1:?Test project name required}
|
||||
project="tests/$name/$name.csproj"
|
||||
[[ -f "$project" ]] || { echo "Unknown test project: $name" >&2; exit 2; }
|
||||
set +e
|
||||
python3 - "$name" <<'PY'
|
||||
import json, sys
|
||||
plan = json.load(open('artifacts/tests/plan.json'))
|
||||
if sys.argv[1] not in plan['suites']:
|
||||
print(f"Skipping unaffected suite {sys.argv[1]}")
|
||||
raise SystemExit(10)
|
||||
PY
|
||||
status=$?
|
||||
set -e
|
||||
if [[ "$status" == 10 ]]; then exit 0; fi
|
||||
if [[ "$status" != 0 ]]; then exit "$status"; fi
|
||||
: "${DATABASE_URL:?A disposable PostgreSQL database is required}"
|
||||
dbname="ci_${name//./_}"
|
||||
psql --no-password -v ON_ERROR_STOP=1 -c "CREATE DATABASE \"$dbname\"" >/dev/null
|
||||
if [[ "$name" == Heimdall.E2E.Tests ]]; then
|
||||
node tests/Heimdall.E2E.Tests/bin/Release/net10.0/.playwright/package/cli.js install --with-deps chromium
|
||||
fi
|
||||
coverage_args=()
|
||||
if [[ "$name" == Heimdall.Application.Tests || "$name" == Heimdall.Infrastructure.Tests || "$name" == Heimdall.Web.Tests ]]; then
|
||||
coverage_args=(--collect:"XPlat Code Coverage")
|
||||
fi
|
||||
DATABASE_URL="$DATABASE_URL;Database=$dbname" \
|
||||
dotnet test "$project" -c Release --no-build --no-restore \
|
||||
--logger 'trx;LogFileName=results.trx' --results-directory "artifacts/tests/$name" \
|
||||
"${coverage_args[@]}"
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Contract tests for security gates and versioned release uploads, without network."""
|
||||
import contextlib
|
||||
import io
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
REPO_ROOT = ROOT.parent.parent
|
||||
|
||||
def load_change_scope():
|
||||
spec = importlib.util.spec_from_file_location('heimdall_change_scope', ROOT/'change_scope.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
class ChangeScopeTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.scope = load_change_scope().scope_for
|
||||
|
||||
def test_documentation_does_not_build_or_validate_images(self):
|
||||
self.assertEqual(self.scope(['docs/operations.md']), {
|
||||
'run_validation': False, 'build_server': False,
|
||||
'build_agent': False, 'build_agent_gpu': False,
|
||||
})
|
||||
|
||||
def test_ci_script_changes_validate_without_building_container_images(self):
|
||||
result = self.scope(['.gitea/workflows/build.yml', 'scripts/ci/change_scope.py'])
|
||||
self.assertTrue(result['run_validation'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(False, False, False))
|
||||
|
||||
def test_server_only_change_selects_only_server_image(self):
|
||||
result = self.scope(['src/Heimdall.Web/Controllers/HealthController.cs'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(True, False, False))
|
||||
|
||||
def test_agent_change_selects_cpu_and_gpu_images(self):
|
||||
result = self.scope(['src/Heimdall.Agent/Program.cs'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(False, True, True))
|
||||
|
||||
def test_shared_project_selects_all_dependent_images(self):
|
||||
result = self.scope(['src/Heimdall.Application/Services/AgentService.cs'])
|
||||
self.assertEqual((result['build_server'], result['build_agent'], result['build_agent_gpu']),
|
||||
(True, True, True))
|
||||
|
||||
def test_version_tag_selects_every_image(self):
|
||||
self.assertTrue(all(self.scope(['*']).values()))
|
||||
|
||||
def test_version_tag_must_be_semver_before_build_jobs_start(self):
|
||||
with patch.dict(os.environ, {'EVENT_NAME': 'push', 'REF': 'refs/tags/not-a-version'}):
|
||||
with self.assertRaises(SystemExit):
|
||||
load_change_scope().changed_paths()
|
||||
|
||||
class PublicationWorkflowTests(unittest.TestCase):
|
||||
def test_release_write_token_is_tag_only_and_not_a_long_lived_pat_secret(self):
|
||||
workflow = (REPO_ROOT/'.gitea/workflows/build.yml').read_text()
|
||||
self.assertNotIn('secrets.RELEASE_TOKEN', workflow)
|
||||
self.assertEqual(workflow.count('secrets.GITEA_TOKEN'), 2)
|
||||
publish = workflow.split(' publish:\n', 1)[1]
|
||||
self.assertIn("startsWith(gitea.ref, 'refs/tags/')", publish)
|
||||
self.assertIn(' contents: write', publish)
|
||||
self.assertIn(' pull-requests: read', publish)
|
||||
self.assertNotIn('secrets.GITEA_TOKEN', workflow.split(' publish:\n', 1)[0])
|
||||
|
||||
class PowerShellInstallerTests(unittest.TestCase):
|
||||
@unittest.skipUnless(shutil.which('pwsh'), 'PowerShell is not installed')
|
||||
def test_server_installer_has_valid_powershell_syntax(self):
|
||||
parser = "$tokens=$null; $errors=$null; [void][System.Management.Automation.Language.Parser]::ParseFile((Resolve-Path 'install/install-server.ps1'), [ref]$tokens, [ref]$errors); if ($errors.Count) { $errors | ForEach-Object { Write-Error $_.Message }; exit 1 }"
|
||||
result = subprocess.run([shutil.which('pwsh'), '-NoProfile', '-Command', parser],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
class PwaAssetTests(unittest.TestCase):
|
||||
def test_manifest_raster_icons_exist_with_declared_dimensions(self):
|
||||
manifest = json.loads((REPO_ROOT/'src/Heimdall.Web/wwwroot/manifest.webmanifest').read_text())
|
||||
icons = {icon['sizes']: icon for icon in manifest['icons'] if icon['type'] == 'image/png'}
|
||||
for size in (192, 512):
|
||||
with self.subTest(size=size):
|
||||
icon = icons[f'{size}x{size}']
|
||||
self.assertTrue(icon['src'].startswith('/'))
|
||||
image = REPO_ROOT/'src/Heimdall.Web/wwwroot'/icon['src'].lstrip('/')
|
||||
data = image.read_bytes()
|
||||
self.assertEqual(data[:8], b'\x89PNG\r\n\x1a\n')
|
||||
self.assertEqual(int.from_bytes(data[16:20], 'big'), size)
|
||||
self.assertEqual(int.from_bytes(data[20:24], 'big'), size)
|
||||
|
||||
def test_apple_touch_icon_exists_at_declared_size(self):
|
||||
app = (REPO_ROOT/'src/Heimdall.Web/Components/App.razor').read_text()
|
||||
self.assertIn('rel="apple-touch-icon" sizes="180x180" href="pwa-icon-180.png"', app)
|
||||
data = (REPO_ROOT/'src/Heimdall.Web/wwwroot/pwa-icon-180.png').read_bytes()
|
||||
self.assertEqual(data[:8], b'\x89PNG\r\n\x1a\n')
|
||||
self.assertEqual(int.from_bytes(data[16:20], 'big'), 180)
|
||||
self.assertEqual(int.from_bytes(data[20:24], 'big'), 180)
|
||||
|
||||
def load_test_plan():
|
||||
spec = importlib.util.spec_from_file_location('heimdall_test_plan', ROOT/'test-plan.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
def load_build_plan():
|
||||
spec = importlib.util.spec_from_file_location('heimdall_build_plan', ROOT/'build-plan.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
def load_efcore_policy():
|
||||
spec = importlib.util.spec_from_file_location('efcore_policy', ROOT/'check-efcore-usage.py')
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
class EfCorePolicyTests(unittest.TestCase):
|
||||
def test_current_production_sources_follow_policy(self):
|
||||
self.assertEqual(load_efcore_policy().check_tree(REPO_ROOT), [])
|
||||
|
||||
def test_agent_ado_net_is_rejected(self):
|
||||
failures = load_efcore_policy().inspect_source(
|
||||
'src/Heimdall.Agent/Services/Example.cs',
|
||||
'using Microsoft.Data.Sqlite; var connection = new SqliteConnection();')
|
||||
self.assertEqual(len(failures), 1)
|
||||
|
||||
def test_provider_specific_sql_requires_explicit_exception_marker(self):
|
||||
policy = load_efcore_policy()
|
||||
path = 'src/Heimdall.Infrastructure/Jobs/DatabaseMaintenanceJob.cs'
|
||||
self.assertEqual(policy.inspect_source(path, 'db.Database.ExecuteSqlRaw("VACUUM");'), [
|
||||
f'{path}: direct database API is not allowed; use EF Core or document an approved provider-specific exception'])
|
||||
self.assertEqual(policy.inspect_source(path, '// EF Core exception: PostgreSQL maintenance\ndb.Database.ExecuteSqlRaw("VACUUM");'), [])
|
||||
|
||||
class TestPlanTests(unittest.TestCase):
|
||||
def test_domain_change_reaches_dependent_suites(self):
|
||||
suites = load_test_plan().plan(['src/Heimdall.Domain/Camera.cs'])['suites']
|
||||
self.assertIn('Heimdall.Domain.Tests', suites)
|
||||
self.assertIn('Heimdall.IntegrationTests', suites)
|
||||
self.assertIn('Heimdall.E2E.Tests', suites)
|
||||
|
||||
def test_agent_change_does_not_run_unrelated_web_tests(self):
|
||||
plan = load_test_plan().plan(['src/Heimdall.Agent/Program.cs'])
|
||||
suites = plan['suites']
|
||||
self.assertIn('Heimdall.Agent.Tests', suites)
|
||||
self.assertNotIn('Heimdall.Web.Tests', suites)
|
||||
self.assertIn('tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj', plan['build_projects'])
|
||||
self.assertFalse(any('Heimdall.Web' in target for target in plan['build_projects']))
|
||||
|
||||
def test_web_change_does_not_rebuild_agent(self):
|
||||
plan = load_test_plan().plan(['src/Heimdall.Web/Components/App.razor'])
|
||||
self.assertIn('Heimdall.Web.Tests', plan['suites'])
|
||||
self.assertFalse(any('Heimdall.Agent' in target for target in plan['build_projects']))
|
||||
self.assertFalse(any('Heimdall.slnx' == target for target in plan['build_projects']))
|
||||
|
||||
def test_solution_change_runs_all_and_docs_change_runs_none(self):
|
||||
planner = load_test_plan()
|
||||
solution = planner.plan(['global.json'])
|
||||
self.assertEqual(len(solution['suites']), len(planner.TESTS))
|
||||
self.assertEqual(solution['build_projects'], ['Heimdall.slnx'])
|
||||
docs = planner.plan(['docs/README.md'])
|
||||
self.assertEqual(docs['suites'], [])
|
||||
self.assertEqual(docs['build_projects'], [])
|
||||
|
||||
def test_removed_backlog_file_does_not_skip_validation_as_docs_only(self):
|
||||
planner = load_test_plan()
|
||||
result = planner.plan(['todo.md'])
|
||||
self.assertEqual(result['mode'], 'all')
|
||||
self.assertEqual(len(result['suites']), len(planner.TESTS))
|
||||
self.assertEqual(result['build_projects'], ['Heimdall.slnx'])
|
||||
|
||||
class BuildPlanTests(unittest.TestCase):
|
||||
def test_builds_only_existing_targets_from_the_plan(self):
|
||||
builder = load_build_plan()
|
||||
with tempfile.TemporaryDirectory() as temporary:
|
||||
root = Path(temporary)
|
||||
target = 'tests/Heimdall.Agent.Tests/Heimdall.Agent.Tests.csproj'
|
||||
project = root/target
|
||||
project.parent.mkdir(parents=True)
|
||||
project.write_text('<Project />')
|
||||
plan_path = root/'artifacts/tests/plan.json'
|
||||
plan_path.parent.mkdir(parents=True)
|
||||
plan_path.write_text(json.dumps({'build_projects':[target]}))
|
||||
builder.ROOT = root
|
||||
builder.PLAN = plan_path
|
||||
with patch('subprocess.run') as run, contextlib.redirect_stdout(io.StringIO()):
|
||||
builder.main()
|
||||
run.assert_called_once_with(
|
||||
['dotnet','build',target,'-c','Release','--no-restore','-m:2'],
|
||||
cwd=root, check=True)
|
||||
|
||||
class GpuAgentImageTests(unittest.TestCase):
|
||||
def test_cpu_default_stays_independent_of_nvidia_runtime(self):
|
||||
dockerfile = (REPO_ROOT/'docker/Dockerfile.agent').read_text()
|
||||
compose = (REPO_ROOT/'docker/docker-compose.agent.dev.yml').read_text()
|
||||
self.assertNotIn('nvidia/cuda', dockerfile)
|
||||
self.assertNotIn('Agent__InferenceExecutionProvider: CUDA', compose)
|
||||
self.assertNotIn('driver: nvidia', compose)
|
||||
|
||||
def test_gpu_runtime_and_optional_overlay_pin_cuda_runtime_and_provider(self):
|
||||
dockerfile = (REPO_ROOT/'docker/Dockerfile.agent.gpu').read_text()
|
||||
compose = (REPO_ROOT/'docker/docker-compose.agent.dev.gpu-nvidia.yml').read_text()
|
||||
self.assertIn('nvidia/cuda:12.8.1-cudnn-runtime-ubuntu24.04@sha256:9175fa92f96de35a8cfb9493f0dfcf9435c7a597e9d95ad41d2cae382a95e3f9', dockerfile)
|
||||
self.assertIn('Microsoft.ML.OnnxRuntime.Gpu', (REPO_ROOT/'src/Heimdall.Agent/Heimdall.Agent.csproj').read_text())
|
||||
self.assertIn('Agent__InferenceExecutionProvider: CUDA', compose)
|
||||
self.assertIn('driver: nvidia', compose)
|
||||
self.assertIn('capabilities: [gpu]', compose)
|
||||
self.assertIn('image: heimdall-agent:gpu-local', compose)
|
||||
state_init = compose.split(' agent-state-init:', 1)[1]
|
||||
self.assertIn('dockerfile: docker/Dockerfile.agent.gpu', state_init)
|
||||
|
||||
class NativeAgentUpdateTests(unittest.TestCase):
|
||||
def test_supervisor_rolls_back_failed_startup_to_previous_release(self):
|
||||
with tempfile.TemporaryDirectory(prefix='hmd-supervisor-test-') as temporary:
|
||||
root = Path(temporary)
|
||||
old_release = root/'releases'/'v1.0.0'
|
||||
new_release = root/'releases'/'v1.0.1'
|
||||
old_release.mkdir(parents=True)
|
||||
new_release.mkdir()
|
||||
(old_release/'Heimdall.Agent.dll').write_bytes(b'old synthetic release')
|
||||
(new_release/'Heimdall.Agent.dll').write_bytes(b'new synthetic release')
|
||||
current = root/'current'
|
||||
current.symlink_to(new_release, target_is_directory=True)
|
||||
pending = root/'pending-update.json'
|
||||
pending.write_text(json.dumps({'version': '1.0.1', 'previous': str(old_release)}))
|
||||
dotnet = root/'fake-dotnet'
|
||||
dotnet.write_text('#!/bin/sh\nexit 1\n')
|
||||
dotnet.chmod(0o755)
|
||||
|
||||
environment = os.environ.copy()
|
||||
environment['Agent__UpdateInstallRoot'] = str(root)
|
||||
environment['HEIMDALL_DOTNET'] = str(dotnet)
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(REPO_ROOT/'install/agent-supervisor.py')],
|
||||
env=environment, capture_output=True, text=True, timeout=10)
|
||||
|
||||
self.assertEqual(result.returncode, 75, result.stderr)
|
||||
self.assertEqual(current.resolve(), old_release.resolve())
|
||||
self.assertFalse(pending.exists())
|
||||
self.assertIn('previous release restored', result.stderr)
|
||||
|
||||
class AdvisoryTests(unittest.TestCase):
|
||||
def check(self, data):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
path = Path(temp)/'report.json'
|
||||
path.write_text(json.dumps(data))
|
||||
return subprocess.run([sys.executable, str(ROOT/'check-advisories.py'), str(path)],
|
||||
capture_output=True, text=True).returncode
|
||||
|
||||
def test_high_and_critical_transitive_advisories_fail(self):
|
||||
for severity in ('High', 'Critical'):
|
||||
report = {'version': 1, 'projects': [{'frameworks': [{'transitivePackages': [{
|
||||
'id': 'Example', 'vulnerabilities': [{'severity': severity, 'advisoryurl': 'https://example.test'}]
|
||||
}]}]}]}
|
||||
self.assertNotEqual(self.check(report), 0)
|
||||
|
||||
def test_clean_report_passes(self):
|
||||
self.assertEqual(self.check({'version': 1, 'projects': [{'frameworks': []}]}), 0)
|
||||
|
||||
def test_failed_empty_and_invalid_reports_fail_closed(self):
|
||||
for report in ({}, {'version': 1, 'projects': []},
|
||||
{'version': 1, 'projects': [{}], 'problems': [{'message': 'offline'}]}):
|
||||
self.assertNotEqual(self.check(report), 0)
|
||||
|
||||
class ReleaseTests(unittest.TestCase):
|
||||
def execute(self):
|
||||
calls = []
|
||||
class Response(io.BytesIO):
|
||||
def __enter__(self): return self
|
||||
def __exit__(self, *args): self.close()
|
||||
def fake_request(req, timeout):
|
||||
calls.append(req)
|
||||
if req.method == 'GET' and '/releases/tags/' in req.full_url:
|
||||
return Response(json.dumps({'id': 7, 'draft': False, 'tag_name': '1.2.3',
|
||||
'html_url': 'https://example.test/releases/7'}).encode())
|
||||
if req.method == 'GET':
|
||||
names = ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']
|
||||
return Response(json.dumps([{'id':index+8,'name':name} for index,name in enumerate(names)]).encode())
|
||||
if req.method == 'DELETE': return Response(b'')
|
||||
return Response(b'{"id":9}')
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)/'artifacts/packages'
|
||||
directory.mkdir(parents=True)
|
||||
(directory/'provenance.json').write_text(json.dumps({'commit':'abc123','run_id':'42','version':'1.2.3'}))
|
||||
for name in ['heimdall-installers-1.2.3.zip', 'heimdall-installers-1.2.3.zip.sha256', 'agent-release-public.pem',
|
||||
'agent-update-manifest.json', 'agent-update-manifest.sig', 'agent-image.json',
|
||||
'agent-image-gpu.json', 'heimdall-agent-portable-1.2.3.tar.gz']:
|
||||
(directory/name).write_bytes(b'archive')
|
||||
(directory/'agent-release-public.pem').write_bytes(b'key')
|
||||
notes = Path(temp)/'release-notes.md'
|
||||
notes.write_text('- Feature from PR #3.\n')
|
||||
original = Path.cwd()
|
||||
try:
|
||||
os.chdir(temp)
|
||||
with patch.dict(os.environ, {'BUILD_SERVER_URL':'https://example.test',
|
||||
'BUILD_REPOSITORY':'owner/repo','RELEASE_TAG':'1.2.3','RELEASE_TOKEN':'dummy',
|
||||
'RELEASE_NOTES_FILE':str(notes)}), \
|
||||
patch('urllib.request.urlopen', fake_request), contextlib.redirect_stdout(io.StringIO()):
|
||||
try:
|
||||
runpy.run_path(str(ROOT/'release-gitea.py'), run_name='__main__')
|
||||
except SystemExit as result:
|
||||
if result.code != 0:
|
||||
raise
|
||||
finally:
|
||||
os.chdir(original)
|
||||
return calls
|
||||
|
||||
def test_complete_published_release_is_not_mutated_on_rerun(self):
|
||||
calls = self.execute()
|
||||
self.assertTrue(any('/releases/tags/1.2.3' in call.full_url for call in calls))
|
||||
self.assertEqual([call.method for call in calls], ['GET', 'GET'])
|
||||
|
||||
class OfflineReleaseAcceptanceTests(unittest.TestCase):
|
||||
def test_publish_signs_and_uploads_cpu_and_gpu_image_manifests(self):
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(ROOT/'accept-release-offline.py')],
|
||||
cwd=REPO_ROOT, capture_output=True, text=True)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertIn('installer ZIP', result.stdout)
|
||||
self.assertIn('selective Docker Hub tags', result.stdout)
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loaded 100 of 786 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user