Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c0c8ecf46 | ||
|
|
dc8a313deb |
No files matched your search
@@ -44,8 +44,27 @@ if ($script:PackageReleaseVersion -eq 'unversioned') {
|
||||
if (-not $installerAsset -or $installerAsset.browser_download_url -notmatch '^https://') {
|
||||
throw "La release ne contient pas son bundle d'installation versionné."
|
||||
}
|
||||
$expectedHash = [string]$installerAsset.digest -replace '^sha256:', ''
|
||||
if ($expectedHash -notmatch '^[A-Fa-f0-9]{64}$') { throw 'La release ne fournit pas le SHA-256 du bundle.' }
|
||||
$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.' }
|
||||
|
||||
@@ -62,9 +62,25 @@ if [[ "$PACKAGE_RELEASE_VERSION" == unversioned ]]; then
|
||||
installer_url="$(jq -er '.browser_download_url | select(startswith("https://"))' <<<"$asset_json")" || {
|
||||
echo 'URL HTTPS du bundle d’installation invalide.' >&2; exit 1;
|
||||
}
|
||||
expected_sha256="$(jq -er '.digest | select(test("^sha256:[A-Fa-f0-9]{64}$")) | sub("^sha256:"; "")' <<<"$asset_json")" || {
|
||||
echo 'La release ne fournit pas le SHA-256 du bundle.' >&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; }
|
||||
|
||||
@@ -131,13 +131,27 @@ 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':'sha256:' + hashlib.sha256(open(os.environ['OFFLINE_INSTALLER_ZIP'],'rb').read()).hexdigest(),
|
||||
'browser_download_url':'https://release.test/heimdall-installers-1.2.3.zip'}]}).encode()
|
||||
'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)
|
||||
'''
|
||||
@@ -200,7 +214,9 @@ else:
|
||||
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'}]})
|
||||
'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'):
|
||||
@@ -252,7 +268,7 @@ else:
|
||||
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', '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']
|
||||
@@ -318,6 +334,65 @@ else:
|
||||
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 + '^'
|
||||
@@ -379,8 +454,12 @@ else:
|
||||
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', 'agent-release-public.pem',
|
||||
'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']],
|
||||
|
||||
@@ -64,4 +64,6 @@ Path('artifacts/packages/provenance.json').write_text(json.dumps({
|
||||
'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
|
||||
@@ -30,15 +30,16 @@ def request(path, method='GET', body=None, content_type='application/json', miss
|
||||
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, package_root / 'agent-release-public.pem',
|
||||
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 checksum bookkeeping stay in the build
|
||||
# artifacts. Gitea releases expose only the Central installer bundle and the
|
||||
# files Central/Agent need to verify and install native Agent updates.
|
||||
# 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', {
|
||||
|
||||
@@ -279,7 +279,7 @@ class ReleaseTests(unittest.TestCase):
|
||||
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', 'agent-release-public.pem',
|
||||
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())
|
||||
@@ -289,7 +289,7 @@ class ReleaseTests(unittest.TestCase):
|
||||
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', 'agent-release-public.pem',
|
||||
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')
|
||||
|
||||
@@ -9,14 +9,18 @@ Read `AGENTS.md`, the Toggle caméra #59/#199 Gitea issue, `skills/heimdall-dotn
|
||||
|
||||
## Implementation path
|
||||
|
||||
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central.
|
||||
- `POST /api/cameras/{id}/toggle-status` requires the normal camera-write permission and persists `Camera.Status` in Central. Enabling a Disabled camera sets it to Offline (enabled, connectivity not yet confirmed); only an Agent status report can set it Online. Toggling any enabled status sets it to Disabled.
|
||||
- Agent status reports require the API key to resolve to the same Agent ID in the route and the camera to be assigned to that Agent. Authenticate and authorize both resources with `ResourceAccess`; never trust the route ID alone. Keep the existing same-site camera check in `ReportCameraStatusCommandHandler`.
|
||||
- `AppDbContext.SaveChangesAsync` publishes a payload-free config invalidation after camera/assignment/profile changes. Agent refetches its authorized full camera snapshot over its ConfigHub/API path and acknowledges the digest.
|
||||
- `GetEffectiveAgentConfigQuery` emits `camera.<id>.enabled` from the persisted status. `CameraConfigStore` atomically replaces the snapshot and raises `Changed`.
|
||||
- `SnapshotPipelineService` reconciles enabled assignments with `CameraStreamService`; disabling/removing an assignment kills FFmpeg, awaits its read loop cleanup and releases its stream permit. Enabling starts the stream. Keep central status authoritative; an Agent status report must not re-enable a disabled camera.
|
||||
- Camera counts and lists consider only Online cameras connected. An enabled Offline/Error camera remains enabled in the Agent configuration but is not counted as Online. UI toggle messages treat every status except Disabled as enabled.
|
||||
- Agent identity and API key are protected in `AgentState` under the configured state directory. Mount a project-scoped volume there so a restart reuses the same Agent identity and the Central configuration is refetched from persistent camera state.
|
||||
|
||||
## Local verification
|
||||
|
||||
The Central status contract is covered by `ToggleCameraStatusCommandTests` and the `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` relational API test: activation persists Offline, the authorized same-site Agent status endpoint can confirm Online, and a subsequent administrative toggle persists Disabled. Run these focused tests alongside the Agent lifecycle suites when changing this contract.
|
||||
|
||||
Run the focused Agent lifecycle suites:
|
||||
|
||||
```bash
|
||||
@@ -51,3 +55,9 @@ The fifth disposable Compose attempt used `/proc/*/comm == ffmpeg`, avoiding sel
|
||||
## Sixth source-built run
|
||||
|
||||
The sixth run kept the FFmpeg process deadline separate from the config ACK deadline and verified exact initial digest equality between the Central config version and Agent `LastAppliedCameraConfigVersion`. It failed the OFF process bound: Central and Agent effective config both showed Disabled, but `/proc/*/comm` reached zero only after the two-second assertion timed out. No restart-OFF/persisted identity acceptance ran. Treat OFF <2 seconds and OFF restart persistence as unverified; investigate the measured delay before changing the acceptance threshold.
|
||||
|
||||
## Camera status contract acceptance
|
||||
|
||||
For status semantics (issue #291), run `CamerasControllerTests.ToggleStatus_WithAuth_TogglesCamera` against PostgreSQL and the `ToggleCameraStatusCommandTests` suite. The relational test must assert Disabled → Offline and the online counter remains zero before connectivity, register and heartbeat a synthetic same-site Agent, reject its report before camera assignment, assign the synthetic camera, accept that Agent's Online report, reject a request that uses its API key with a different route Agent ID, and then confirm admin toggle → Disabled.
|
||||
|
||||
A source-built disposable Central + PostgreSQL Compose run on 2026-11-11 used project `heimdall-291-acceptance-1794427561-8428`, synthetic bootstrap/site/Agent/camera data, loopback ports 18543/15439, and image `heimdall:heimdall-291-acceptance-1794427561-8428-central`. It observed health HTTP 200, activation Offline, online count 0, then Agent-confirmed Online and online count 1. Cleanup verified zero project containers, volumes and networks, the exact image tag absent, and temporary files removed. This is software acceptance only; it does not satisfy `validation:field` hardware/deployment evidence.
|
||||
@@ -0,0 +1,23 @@
|
||||
---
|
||||
name: installer-checksum-acceptance
|
||||
description: Build and verify the versioned Central installer checksum asset and both server bootstrap verification paths.
|
||||
---
|
||||
|
||||
# Central installer checksum acceptance
|
||||
|
||||
Use this workflow when changing `install/install-server.sh`, `install/install-server.ps1`, `scripts/ci/package.sh`, or the release asset set in `scripts/ci/release-gitea.py`.
|
||||
|
||||
## Release contract
|
||||
|
||||
- `package.sh` creates `heimdall-installers-<version>.zip.sha256` beside the ZIP. Its single standard `sha256sum` line names the ZIP asset exactly, with no workspace-relative path.
|
||||
- `release-gitea.py` requires and publishes both files before making a release visible. The sidecar is part of the exact expected asset set for already-published releases.
|
||||
- The raw Linux and Windows bootstraps prefer a valid `sha256:<64 hex>` digest from the matching release API asset. If the digest is absent or null, they find the correspondingly named checksum asset, require an HTTPS download URL and exactly one checksum line naming the ZIP, download the ZIP, and compare its SHA-256 before extraction or execution.
|
||||
- A malformed, non-null API digest fails closed. Do not fall back from an invalid digest or calculate the expected checksum from the ZIP that is being verified.
|
||||
|
||||
## Acceptance
|
||||
|
||||
1. Run `python3 scripts/ci/accept-release-offline.py` in a clean dedicated checkout. Its TLS loopback Gitea double and fake Docker CLI must prove release asset publication, the API digest-present path, the Forgejo-compatible `digest: null` sidecar path, rejection of a mismatched sidecar, and fail-closed behavior for a malformed non-null API digest. Assert the expected installer asset names and the sidecar content against the produced ZIP.
|
||||
2. Run `python3 -m unittest scripts.ci.test_ci` (or the repository's equivalent CI policy test command) and verify release asset fixtures include the sidecar.
|
||||
3. Run `bash -n install/install-server.sh`; if `pwsh` is available, parse `install/install-server.ps1` without invoking Windows-only installation actions.
|
||||
4. For any disposable Compose validation required by the behavior change, follow `skills/compose-disposable-recipe/SKILL.md`: use source-built unique tags and isolated credentials/ports/volumes, install cleanup before build/start, and verify project resources and exact image tags are absent afterward.
|
||||
5. Record local and CI evidence in the Gitea issue and PR. Do not claim a production Gitea release, `/releases/latest`, Docker Hub, runner, or deployed installer was validated by the offline API double.
|
||||
@@ -19,9 +19,9 @@ Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_s
|
||||
- Runs for the same ref are serialized so a slower older `main` run cannot overwrite a newer `latest` image.
|
||||
- A `MAJOR.MINOR.PATCH` tag (optional prerelease suffix allowed) is a version release. It validates the complete source and builds/scans server, Agent CPU, and Agent GPU images once each. The verified images are pushed to Docker Hub as `sha-<full-sha>` and the application version.
|
||||
- After merge of a release-worthy PR, use the current stable tag and all unreleased changes to calculate the SemVer increment according to `pr-release-versioning`. Fetch `main`, verify the merged commit is reachable from it, verify the selected tag is unused, create an annotated tag at the merged commit, and push it to trigger this workflow. Never ask the user to choose a version or release, infer a version from the PR title alone, or force-update an existing tag. Documentation and skills-only changes do not get a tag.
|
||||
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to verify their source revision, then resolves canonical digests from Docker Hub Registry v2 using the immutable commit tags. It creates a signed Gitea release containing `heimdall-installers-<version>.zip`, framework-dependent Agent archives, the public key, signed update manifest, and CPU/GPU image digest manifests. Local Docker `RepoDigests` can contain multiple values and must not be used as a uniqueness check. Build provenance, image-digest bookkeeping, and checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
|
||||
- The tag release job does not build or scan Docker images. It pulls the already scanned immutable image refs to verify their source revision, then resolves canonical digests from Docker Hub Registry v2 using the immutable commit tags. It creates a signed Gitea release containing `heimdall-installers-<version>.zip`, its `heimdall-installers-<version>.zip.sha256` sidecar, framework-dependent Agent archives, the public key, signed update manifest, and CPU/GPU image digest manifests. Local Docker `RepoDigests` can contain multiple values and must not be used as a uniqueness check. Build provenance, image-digest bookkeeping, and unrelated checksums stay in CI package output and are not uploaded as end-user release assets. It never uploads Docker image archives to Gitea.
|
||||
- The package script uses fast gzip compression for the framework-dependent release archives to reduce release-job CPU time; keep the archive names and layout stable for Linux and Windows installers.
|
||||
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), verifies the Gitea SHA-256 asset digest, downloads that version's ZIP, and runs its version-pinned script. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
|
||||
- The installer ZIP preserves the `install/` and `docker/` layout consumed by the Linux and Windows server installers. The package job writes a checksum sidecar with the archive's exact asset filename. A raw-branch `.sh` or `.ps1` bootstrap resolves Gitea's latest stable version (or an explicit `HEIMDALL_INSTALLER_VERSION`), uses a valid Gitea SHA-256 asset digest when present and otherwise downloads and parses the published sidecar, then verifies the ZIP before running its version-pinned script. A malformed non-null Gitea digest is a hard failure; it must not be silently replaced by the sidecar. Versioned bundle scripts pin their source assets and server image to the same tag and do not resolve a moving release. Direct Agent install scripts served by Central continue to download Agent payloads through Central's configured Gitea release API.
|
||||
- Gitea release creation is idempotent by version tag. A release remains draft until every expected asset is uploaded; stable versions publish as releases and versions with a prerelease suffix publish as prereleases.
|
||||
- Central stores only the public Forgejo origin in `updates.forgepublicurl` and constructs the canonical Heimdall `releases/latest` API route in code. Preserve the legacy setting migration and never make the derived API route editable in Settings.
|
||||
- The Site Install panel displays the configured signed release version and only exposes native install commands when the signed manifest, key, and platform assets are available. Docker commands also require a verified image digest.
|
||||
@@ -34,7 +34,7 @@ Use this skill for changes to `.gitea/workflows/build.yml`, `scripts/ci/change_s
|
||||
|
||||
## Offline end-to-end acceptance
|
||||
|
||||
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
|
||||
Run `python3 scripts/ci/accept-release-offline.py` from a clean dedicated worktree. It invokes package, release-note, and release scripts with disposable ECDSA P-256 credentials, a loopback-only TLS Gitea API double, synthetic pull request data, and a fake Docker CLI. It checks the version-pinned Linux/Windows installer ZIP and its published checksum sidecar, installer bootstrap with both a valid API digest and `digest: null`, Agent archive checksums, manifest signature, Docker Hub immutable refs/digests, the exact minimal release asset set, and proves the publication script does not build or scan images. The fake Docker CLI must never contact a registry; the API double must reject non-synthetic authorization and suppress request logging.
|
||||
|
||||
For build-scope changes, validate that documentation-only, Central-only, Agent-only, and shared-project file sets produce the intended image outputs. For behavior/deployment changes, also run the required disposable source-built Compose recipe with generated credentials, ports, project name, and unique local image tags. Its EXIT trap must verify project containers, volumes, and networks are gone and remove/verify absence of only its exact image tags.
|
||||
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ public class ToggleCameraStatusCommandHandler : IRequestHandler<ToggleCameraStat
|
||||
var oldStatus = camera.Status;
|
||||
|
||||
var newStatus = camera.Status == CameraStatus.Disabled
|
||||
? CameraStatus.Online
|
||||
? CameraStatus.Offline
|
||||
: CameraStatus.Disabled;
|
||||
|
||||
camera.SetStatus(newStatus);
|
||||
|
||||
@@ -633,7 +633,7 @@ else
|
||||
if (result.Succeeded && result.Data is not null)
|
||||
{
|
||||
_camera.Status = result.Data.Status;
|
||||
Snackbar.Add(result.Data.Status == "Online" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
|
||||
Snackbar.Add(result.Data.Status != "Disabled" ? Text["CameraDetail_Enabled"] : Text["CameraDetail_Disabled"], Severity.Success);
|
||||
}
|
||||
else _editError = result.ErrorMessage ?? Text["CameraDetail_StatusError"];
|
||||
}
|
||||
|
||||
@@ -638,7 +638,7 @@
|
||||
{
|
||||
camera.Status = result.Data.Status;
|
||||
Snackbar.Add(
|
||||
result.Data.Status == "Online" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
|
||||
result.Data.Status != "Disabled" ? string.Format(Language.Culture, Text["CamerasPage_CameraEnabled"], camera.Name) : string.Format(Language.Culture, Text["CamerasPage_CameraDisabled"], camera.Name),
|
||||
Severity.Success);
|
||||
}
|
||||
else
|
||||
|
||||
@@ -10,6 +10,7 @@ using Heimdall.Application.AgentLogs.Queries.GetAgentLogs;
|
||||
using Heimdall.Application.Inventory.Queries.GetAgentMetricHistory;
|
||||
using Heimdall.Application.Cameras.Commands.ReportCameraStatus;
|
||||
using Heimdall.Application.DTOs;
|
||||
using Heimdall.Api.Security;
|
||||
using Heimdall.Domain.Enums;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using MediatR;
|
||||
@@ -24,6 +25,8 @@ namespace Heimdall.Api.Controllers;
|
||||
[EnableRateLimiting("Api")]
|
||||
public class AgentsController : ControllerBase
|
||||
{
|
||||
private readonly ResourceAccess _resourceAccess;
|
||||
|
||||
/// <summary>Query parameters for agent log retrieval.</summary>
|
||||
public record AgentLogsQuery(
|
||||
[FromQuery] int Page = 1,
|
||||
@@ -35,7 +38,11 @@ public class AgentsController : ControllerBase
|
||||
|
||||
private readonly IMediator _mediator;
|
||||
|
||||
public AgentsController(IMediator mediator) => _mediator = mediator;
|
||||
public AgentsController(IMediator mediator, ResourceAccess resourceAccess)
|
||||
{
|
||||
_mediator = mediator;
|
||||
_resourceAccess = resourceAccess;
|
||||
}
|
||||
|
||||
/// <summary>Register an agent using a site registration token.</summary>
|
||||
[AllowAnonymous]
|
||||
@@ -149,6 +156,12 @@ public class AgentsController : ControllerBase
|
||||
public async Task<IActionResult> ReportCameraStatus(
|
||||
Guid id, Guid cameraId, [FromBody] ReportCameraStatusRequest request, CancellationToken ct)
|
||||
{
|
||||
var requester = await _resourceAccess.ResolveAsync(User, ct);
|
||||
if (requester is null || requester.Kind != RequesterKind.Agent ||
|
||||
!await _resourceAccess.AgentAsync(requester, id, ct) ||
|
||||
!await _resourceAccess.CameraAsync(requester, cameraId, ct))
|
||||
return Forbid();
|
||||
|
||||
if (!Enum.TryParse<CameraStatus>(request.Status, true, out var status))
|
||||
return BadRequest(new { error = $"Invalid status: {request.Status}" });
|
||||
|
||||
|
||||
@@ -171,7 +171,7 @@ public class CamerasController : ControllerBase
|
||||
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
|
||||
}
|
||||
|
||||
/// <summary>Toggle a camera between Online and Disabled.</summary>
|
||||
/// <summary>Toggle a camera between enabled (initially Offline) and Disabled.</summary>
|
||||
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.CameraWrite)]
|
||||
[HttpPost("{id:guid}/toggle-status")]
|
||||
[ProducesResponseType(typeof(CameraResponse), StatusCodes.Status200OK)]
|
||||
|
||||
@@ -20,7 +20,7 @@ public class ToggleCameraStatusCommandTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Toggle_disabled_camera_should_set_online()
|
||||
public async Task Toggle_disabled_camera_should_set_offline_until_agent_confirms_connectivity()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Cameras.Returns(MockDbSetHelper.CreateFor<Camera>([_disabledCamera]));
|
||||
@@ -30,7 +30,7 @@ public class ToggleCameraStatusCommandTests
|
||||
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
result.Data.ShouldNotBeNull();
|
||||
result.Data.Status.ShouldBe(CameraStatus.Online);
|
||||
result.Data.Status.ShouldBe(CameraStatus.Offline);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -76,6 +76,6 @@ public class ToggleCameraStatusCommandTests
|
||||
context.AuditLogs.Received(1).Add(Arg.Is<AuditLog>(log => log != null
|
||||
&& log.UserId == actorId && log.Action == "Camera.StatusChanged"
|
||||
&& log.OldValue!.Contains("\"status\":\"Disabled\"")
|
||||
&& log.NewValue!.Contains("\"status\":\"Online\"")));
|
||||
&& log.NewValue!.Contains("\"status\":\"Offline\"")));
|
||||
}
|
||||
}
|
||||
@@ -67,11 +67,58 @@ public class CamerasControllerTests : PostgresTestBase
|
||||
var cameraId = cameraContent.GetProperty("id").GetGuid();
|
||||
cameraContent.GetProperty("status").GetString().ShouldBe("Disabled");
|
||||
|
||||
// Toggle → Online
|
||||
// Activation is enabled but has no connectivity evidence yet.
|
||||
var toggleResponse = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);
|
||||
toggleResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
var toggled = await toggleResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
toggled.GetProperty("status").GetString().ShouldBe("Online");
|
||||
toggled.GetProperty("status").GetString().ShouldBe("Offline");
|
||||
|
||||
var cameraResponse = await client.GetAsync($"api/cameras/{cameraId}");
|
||||
var camera = await cameraResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
camera.GetProperty("status").GetString().ShouldBe("Offline");
|
||||
|
||||
var tokenResponse = await client.PostAsync($"api/sites/{siteId}/tokens", null);
|
||||
var siteToken = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>())
|
||||
.GetProperty("token").GetString()!;
|
||||
var registerResponse = await client.PostAsJsonAsync("api/agents/register", new
|
||||
{
|
||||
token = siteToken,
|
||||
hostname = "camera-connectivity-agent",
|
||||
version = "1.0.0-test"
|
||||
});
|
||||
var registration = await registerResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var agentId = registration.GetProperty("agentId").GetGuid();
|
||||
var apiKey = registration.GetProperty("apiKey").GetString()!;
|
||||
var agentClient = Factory.CreateClient();
|
||||
agentClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
|
||||
|
||||
var heartbeatResponse = await agentClient.PostAsJsonAsync(
|
||||
$"api/agents/{agentId}/heartbeat", new { publicIp = "127.0.0.1" });
|
||||
heartbeatResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var unassignedReport = await agentClient.PutAsJsonAsync(
|
||||
$"api/agents/{agentId}/cameras/{cameraId}/status", new { status = "Online" });
|
||||
unassignedReport.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
|
||||
var assignmentResponse = await client.PostAsJsonAsync("api/assignments", new
|
||||
{
|
||||
cameraId,
|
||||
agentId,
|
||||
reason = "integration test"
|
||||
});
|
||||
assignmentResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var reportResponse = await agentClient.PutAsJsonAsync(
|
||||
$"api/agents/{agentId}/cameras/{cameraId}/status", new { status = "Online" });
|
||||
reportResponse.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK);
|
||||
|
||||
var wrongAgentReport = await agentClient.PutAsJsonAsync(
|
||||
$"api/agents/{Guid.NewGuid()}/cameras/{cameraId}/status", new { status = "Offline" });
|
||||
wrongAgentReport.StatusCode.ShouldBe(System.Net.HttpStatusCode.Forbidden);
|
||||
|
||||
cameraResponse = await client.GetAsync($"api/cameras/{cameraId}");
|
||||
camera = await cameraResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
camera.GetProperty("status").GetString().ShouldBe("Online");
|
||||
|
||||
// Toggle back → Disabled
|
||||
var toggleBack = await client.PostAsync($"api/cameras/{cameraId}/toggle-status", null);
|
||||
|
||||
Reference in new issue
Block a user