Compare commits

..
139 changed files with 681 additions and 33423 deletions
@@ -1 +0,0 @@
{"schemaVersion":"nodedc.mission-core-map-access.v1","state":"enabled"}
-122
View File
@@ -1,122 +0,0 @@
# Device Core: external B2 VPS foundation v1
Draft, 2026-09-30. Not installed. Canonical design recorded in DCPLATFORM-21.
This transition precedes the normal Device Core application release. It keeps
its image and existing infrastructure, adds one Core private bind mount and
`DEVICE_B2_SECRET_ROOT`, and executes one SHA-pinned additive SQL transaction.
Neither Manager nor PostgreSQL is recreated. No build, pull, port or network change.
The fixed artifact contains only:
- `docker-compose.device-b2-foundation.yml`
- `deployment/device-b2-foundation-v1.sql`
- `deployment/device-b2-foundation-v1.json`
It is built by Device Core's `infra/deploy-runner/build_device_b2_foundation.py`.
The source SQL SHA is `dc5608eccb8f628aab49390d245e6758505bb8a459a49705c375c3ca59b3e03b`.
The initial predecessor is accepted r14, source
`6ca6738bab22d0fdef714b90c68959363106ee5b`, archive SHA
`385c2fec8fce300cb80a93edfbcb0d537e34755b0ccc35294c0102b3c4a7f724`.
The accepted network-priority override remains part of effective Compose.
Preflight proves exact predecessor source and its applied archive, empty feature
schema, absent private directory, current healthy runtime and immutable effective
Compose delta. The local Core tag must equal its running image. Fresh root runner
promotion and plan/apply are still required; local tests do not prove NAS state.
Apply owns schema execution/receipt, private directory UID/GID1000 mode0700,
Core-only recreation using its existing image, health, exact before/after runtime
comparison with only the new mount/env removed, unchanged dependent containers,
existing Compose/source files and unrelated services. Schema acceptance compares
all ordered columns/types/nullability and constraint definitions to a fixed
contract. PostgreSQL18's separately catalogued NOT NULL constraints are omitted
from the constraint list because nullability is checked independently; NAS uses
PostgreSQL16. This is a scoped schema normalization, not runtime guard relaxation.
Rollback restores source and the original Core configuration with the same image.
It may remove only its verified, complete and empty new schema and empty key
directory. Any unexpected schema, inserted data or key is retained and triggers
reconciliation; it is never erased to make rollback appear successful.
Normal later `device-core-release` operations include the new Compose file only
when a complete matching canonical receipt and applied archive prove ownership.
They also validate the installed private directory, actual mount/environment,
and exact schema on preflight and acceptance. A SQL failure before Core recreation
does not mark runtime as changed or restart Core during rollback.
Existing Dockerfile/migration immutability remains unchanged.
Runner016 was installed (SHA256
`1cda852fec9e940cfbec835b27159f04e96b13e24b6bbcd3ef87dd1a91f306aa`),
but plan001 rejected the effective Compose comparison before mutation. Official
Compose2.20.1 reproduced that rejection on all five current NAS Compose files:
the sole mismatch was the new mount's `bind: {}` versus an expected explicit
`create_host_path: false`. Existing synthetic tests missed this serializer form.
The corrected transition is `device-b2-foundation-v1-20260930-002`;001 is rejected
by identity and must not be applied. SQL, source YAML, predecessor and runtime
scope are unchanged.
Runner017 normalizes only omitted/false `create_host_path` on this one new bind,
in private comparison copies, alongside the existing false `read_only` rule.
Actual config hashes remain untouched. True/null/non-boolean values, missing
bind objects, unknown bind options, duplicate mounts and unrelated changes fail.
See `fixtures/device-b2-foundation-compose220` for real parser output and exact
reproduction. Qualification with that fixture and with all five NAS files proves
the old failure and corrected exact comparison. This is local parser evidence,
not proof of NAS apply or runtime acceptance.
## Foundation002 failure and exact reconciliation
Runner017 was installed and plan002 passed. Apply002 created the schema and
recreated Core, then failed `Device Core predecessor service is not healthy`.
Automatic rollback recreated Core again; its acceptance also failed. Canonical
failed ledger80 records `started_apply=true`, `rollback_status=failed:DeployError`
at `2026-09-30T13:45:49+00:00`. Incident archive SHA is
`da1c97fb0fd2ed9f50acf198c0492b27a5d7273009c0a85b9231fd8c60a70222`;
backup is `device-b2-foundation-device-b2-foundation-v1-20260930-002-20260930-164433`.
The archive, journal and seven backup-file digests are pinned in the runner.
The acceptance order was wrong: the strict healthy snapshot ran before the
existing bounded readiness/HTTP checks. The tests now exercise the actual
readiness loop through `starting` to `healthy` for both apply and rollback.
Both cases fail on017 and pass on018. Persistently unhealthy containers still
fail after the existing grace window; image/config/dependency guards are intact.
Historical failed-generation health states were not saved, so `starting` is a
reproduced defect, not a retroactively observed Docker status for this incident.
Read-only SMB observation found all three foundation files and its vault absent.
Public Manager health returned200/ok. These facts do not prove restored database
and runtime. No second application attempt is allowed until exact reconciliation.
`device-b2-foundation-reconciliation` is a separate metadata-only component.
Identity: `device-b2-foundation-reconciliation-v1-20260930-001`.
Its sole payload is `deployment/device-b2-foundation-reconciliation-v1.json`;
builder: `infra/deploy-runner/build_device_b2_reconciliation.py`.
Root is `/volume1/docker/nodedc-device-plane`, with no build or selected services.
Plan and apply independently prove:
- exact failed row/archive and immutable before/schema/backup partition evidence;
- accepted r14 baseline and no different unresolved foundation transition;
- no foundation files, private directory, or any of the three new schema objects;
- readiness, original Core image/config, unchanged other containers, Compose
files and application source.
Apply writes only the descriptor and canonical backup/journal/archive, then
repeats the proof before success. Its rollback removes only that new descriptor;
neither path issues runtime mutations or DDL. Only a complete matching receipt
and applied archive can acknowledge this one failed002 record. The original
failed journal/archive/backup remain immutable. A marker alone, altered history,
another failure, remaining schema/data/keys or runtime drift blocks acceptance.
Ordinary app releases also check this barrier even if no foundation overlay is
present. No generic health/fingerprint or unrelated registry rules are weakened.
After reconciliation, a fresh foundation003 plan/apply may add the original
unchanged YAML and SQL.003 is a new immutable identity;001/002 cannot be replayed.
Preparation of018 or a local test is not production reconciliation acceptance.
Local validation: foundation boundary/negative tests, deterministic artifact,
real archive through runner loader, existing release/network-priority/autodeploy
and Device Plane registry regression. SQL was also executed after all17 existing
migrations in temporary PGlite PostgreSQL WASM, with cross-company foreign-key
and contour uniqueness checks. This is SQL validation, not NAS runtime acceptance.
The actual Device Core connect/link SQL also passed against that database.
-338
View File
@@ -81,347 +81,9 @@ Supported components in this source:
- `n8n-private-extension`
- `module-foundry`
- `device-plane`
- `gitea`
- `proxy-contur`
- `dc-amd-proxy`
## Fresh Gitea installation
`gitea` is a one-time, fresh-install-only component. Its artifact contains
only the reviewed Compose file and strict deployment descriptor; it contains
no database, repository, user, token, key, hook, runtime data or secret. Build
the deterministic artifact locally with:
```bash
node infra/deploy-runner/build-gitea-fresh-install-artifact.mjs \
gitea-fresh-install-YYYYMMDD-NNN
```
The runtime is fixed to Gitea `1.27.1-rootless` by exact digest and
`linux/amd64`. The runner never pulls it: the exact image must first be loaded
through a separately reviewed trusted image-acquisition step. Compose is
invoked with `--pull never --no-deps`, uses `network_mode: none`, publishes no
ports, and serves only the host-mounted Unix socket
`/volume1/docker/nodedc-gitea/socket/gitea.sock`. It exposes no SSH port, uses
fresh SQLite, enables no LFS, and mounts two runner-generated secrets by URI.
Registration and password Basic auth are disabled, while MFA is enforced;
hooks, webhooks, migrations, packages, Actions, OAuth2/OpenID, federation and
update checks are disabled. HTTP Git with PAT remains the intended trusted
client path; PAT clone/push acceptance belongs to the later reviewed
user/repository restoration transition, not this empty installation. LFS may
only be enabled by that later transition after its secret and restart behavior
has been accepted against the pinned runtime.
Plan and apply fail closed unless all live prerequisites are already true:
- `/volume1/docker/nodedc-gitea`, the `nodedc-gitea` project, and any stale
`nodedc-gitea_internal` network are absent; TCP/4022 is closed and Docker
publishes neither TCP/3000 nor TCP/4022;
- Docker Server is exactly 24.0.2, Compose is at least 2.20.1, and the exact
pinned image ID and RepoDigest are local for linux/amd64 with image user
`1000:1000`;
- the separate root-owned Nginx bridge
`/usr/local/etc/nginx/conf.d/http.nodedc-gitea-uds.conf` matches its exact
reviewed bytes, owner/mode and SHA-256; Nginx 1.23.1 configuration validates,
and only its root/uid-1023 processes own `127.0.0.1:3000`. The bridge proxies
to the Unix socket, preserves Host/X-Real-IP/XFF/XFP, rate-limits login and
bounds concurrent requests without limiting Git request bodies;
- DSM reverse-proxy UUID `5bc46027-0307-4261-af7e-4f94a3c508c9` persistently
and in generated nginx config routes `git.dcserve.ru:443` to
`127.0.0.1:3000`; the generated vhost must also retain its exact host guard
and canonical Host/X-Real-IP/XFF/XFP forwarding directives, so the UDS
bridge never trusts a client-supplied `X-Real-IP`;
- the emergency broad INPUT DROP for TCP/3000 has been removed, while the
legacy `172.22.0.222:3000` OUTPUT DROP and TCP/4022 INPUT DROP remain;
- any legacy container named `gitea` is stopped with restart policy `no`.
Changing DSM reverse proxy/firewall rules, acquiring evidence from the old
root, restoring trusted users/repositories, and loading the pinned image are
separate reviewed transitions. This component never reads or mounts
`/volume1/docker/gitea` and never starts the legacy container. Failed apply
stops/removes only the `nodedc-gitea` candidate, proves that it is absent, and
quarantines the complete newly created root (including data/config/socket/secrets) for
evidence, and restores the absent source/root state without deleting runtime
evidence. If candidate absence cannot be proven, rollback preserves the root in
place and records reconciliation-required instead of disconnecting live bind
mounts.
Run the policy suite before publishing:
```bash
PYTHONDONTWRITEBYTECODE=1 \
python3 infra/deploy-runner/test_gitea_fresh_install.py -v
```
## Gitea incident salvage (clean-state recovery)
The additive `gitea-incident-salvage` slice is the reviewed recovery design for
incident `gitea-20260814`. It does not upgrade or mount the compromised state.
The candidate starts with a new SQLite database, new config, new runtime
secrets, new email addresses and new password hashes. The exact v2 decision
bundle is embedded as inert, digest-bound data:
- 2 new active identities (`dctouch`, admin; `SILVER`, non-admin), each with a
new root-contained one-time password and mandatory password change;
- 8 new locked identities with random discarded passwords, inactive,
restricted and prohibited from login;
- 45 exact repositories: 32 private `dctouch` repositories and 13 public
`SILVER` repositories. The other 962 legacy users and 2013 legacy repository
rows are not imported into the clean database.
The successor v3 descriptor embeds the owner-confirmed, canonical
`confirmed-disposition-v1.json` and the additive
`confirmed-closure-disposition-v1.json`. Both are bound to the exact snapshot,
database, identity decision, reference manifest, unsupported-state report,
schema catalog and semantic-topics hashes. The original disposition's 105
reference decisions are explicit rows, not namespace wildcards: 85 normal
heads, 4 tags and 4 wiki heads are eligible for later live reconstruction; the
exact 5 pull refs and 7 remote refs are sealed archive-only evidence and can
never be auto-promoted. The closure disposition authorizes only bounded
plan-time inventory and records the target policy for access, collaboration,
issue/PR metadata, attachments, releases, labels, projects, units, Packages
and Actions. Observed hashes do not become activation authority, and the new
closure-report digest is deliberately unpinned until separate review.
Build the deterministic review artifact locally with:
```bash
node infra/deploy-runner/build-gitea-incident-salvage-artifact.mjs \
gitea-incident-salvage-subrelation-closure-20260814-006
```
The original v1 descriptor and `...salvage-20260814-001.tgz` remain immutable.
The exact `...salvage-disposition-20260814-002.tgz` also remains immutable and
must not be retried: its plan failed safely because it assumed every nonempty
`repository.topics` TEXT value was a JSON array. A bounded immutable-database
classification proved all 45 kept rows are instead exact four-byte canonical
JSON `null`, Gitea's semantic empty representation. The `...topics-...-003`
artifact is the forward fix with a new patch id and digest.
That exact `...topics-...-003` artifact is now also an immutable predecessor.
The local pre-audit `...closure-...-004` draft must not be staged: review found
orphan-join and nullable-Actions gaps. The local
`...closure-reviewed-...-005` artifact is also stale and must not be staged:
its primary closure was fail-closed, but it retained a broad polymorphic-
subrelation blocker. The additive `...subrelation-closure-...-006` successor
closes the concrete comment/history/merger relations in the pinned snapshot
schema and is the only artifact produced by the current builder.
The successor builder refuses to overwrite an existing artifact basename and
publishes from an exclusively created same-directory temporary file using an
atomic no-clobber hard link. A failed build removes only its private temporary
file. The disposition is sorted, compact ASCII JSON with one terminal LF.
The runtime pin is
`docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49a…3abd2c`, with exact
linux/amd64 OCI image ID `sha256:272085a8…bc5c4c6`. It runs as `1000:1000`,
uses the direct Gitea binary, `network_mode: none`, no Docker ports, no SSH and
no LFS. Candidate restart policy is `no`. The existing reviewed Nginx bridge
cannot reach the candidate while the socket parent is mode `0700`; publication
is an explicit post-acceptance change to `0750`, followed by public TLS and
smart-HTTP checks. Only after those checks may restart policy become
`unless-stopped`. The transition never changes or enforces two-factor
authentication.
The snapshot boundary is exact: UUID
`f5a3fe3a-93ea-bb4d-847f-6221a6bcbc9f`, immutable SQLite SHA-256
`8db9e74a…1a13052`, and the 972/2058 decisions must recompute from the database
row by row. The runner enumerates only each v2 `repo_relative_path` and
`wiki_relative_path`. It rejects symlinks, special files, hard links, NOCOW,
alternates, shallow/replace/grafts/worktrees, promisor state, unknown object
material and incomplete pack/index pairs. One preloaded mount inventory also
guards the `objects` and `refs` roots plus every traversed directory and file:
all must remain on the trusted snapshot device, outside nested mountpoints and,
for directories, outside nested Btrfs subvolumes. Traversal errors fail closed.
Forbidden-path probes (`objects/info/alternates`, grafts, replace refs and the
other listed sentinels) lstat each path component without following links and
validate every ancestor before probing its child; a symlink or mount boundary
therefore stops the plan before any lookup can escape the snapshot tree.
Only three exact derived-file classes observed in the bounded 45-repository
inventory are excluded: dumb-HTTP `objects/info/packs`,
`objects/pack/pack-<oid>.bitmap` with its exact complete pack/index pair, and
monolithic `objects/info/commit-graph`. Each must be a bounded regular,
single-link, non-NOCOW file. The reference manifest records its exact path,
class and byte size, but the runner neither reads nor copies the excluded
bytes. Unobserved `.rev`, MIDX and split commit-graph layouts stay fail-closed;
`.promisor`, `.mtimes`, `.keep`, unknown and temporary lookalikes are not
classified as disposable accelerators.
The same inventory found receive-pack quarantine directories matching only an
exact direct child `objects/tmp_objdir-incoming-[A-Za-z0-9]{6}`. A match must
retain the reviewed uid/gid `1000:1000`, mode `0755`, single-link and non-NOCOW
directory metadata. Its exact path and lstat fields are recorded, then the
subtree is pruned without reading, hashing, copying or reflinking contents; the
sealed read-only incident snapshot retains the forensic copy. Any name,
metadata, mount or subvolume drift remains a hard stop. A reviewed reference/OID
manifest is required; raw HEAD/refs files are never copied. The intended data
path is same-filesystem per-file `--reflink=always`, with no byte-copy fallback
and a bounded exclusive-allocation gate.
This slice is intentionally **NO-GO for apply** at the current review point.
`plan` inventories and prints the exact ref-manifest digest, byte length and
canonical compact JSON. The JSON is the reviewable, hash-bound reference/OID
artifact: it contains approved repository identities, ref names/OIDs, object
totals and stat-bound derived/quarantine exclusions, but no Git object bytes,
hooks or config. The same plan prints the canonical unsupported-state report
and a separate incident-closure report, each with its SHA-256, byte length and
compact ASCII JSON. The closure report is evidence only: its disposition keeps
`expectedSha256` and `expectedBytes` null and retains an explicit review-pin
blocker.
The reviewed plan evidence bound by the disposition is reference manifest
`9cddaf0e…a311` (36,010 bytes), unsupported-state report
`4b2cecf8…106ac` (119,468 bytes), and schema catalog
`b5e3b677…b6db`. The report has exact 45 repository rows with empty
`schema_missing`, `schema_mismatch`, and `anomalies` arrays. These facts close
only the owner's material-state decision; fsck/reachability, physical blob
inventory, sanitized archive creation and candidate acceptance remain separate
verifiers.
The unsupported-state report has one deterministic row for every one of the
45 kept repository IDs, including explicit zeroes. It separates direct
repository-relation counts, directional base/head PR counts, repo-unit type
counts, text-metadata presence booleans and denormalized numeric hints; it does
not add overlapping relations into a misleading grand total. LFS rows are
reported per repository with validated logical byte sums and distinct-OID
aggregates, including size conflicts and sharing with non-kept repositories.
Every association sharing a kept OID must also have an integer repository ID
that resolves to the exact snapshot `repository` table; invalid and orphan
owners make shared/unique byte aggregates unavailable and add a data-anomaly
blocker.
Attachments are reported per repository with validated logical byte sums and
explicit, overlapping issue/comment/release/unlinked link splits. Neither
category claims that a physical blob exists; no title, body, note, comment,
config, URL, token, key, secret, hash payload or blob content is selected or
exported.
The report also embeds the exact `PRAGMA table_xinfo` catalog and explicit
label-to-table-to-repository-column map for a code-owned allowlist of relevant
tables. `sqlite_master` must prove an ordinary, non-virtual table before any
row query; SQLite 3.37+ adds `PRAGMA table_list` ordinary-main-table proof. On
an older compatible SQLite, the weaker object-kind capability is recorded and
adds a coverage blocker. `query_only=ON` and `trusted_schema=OFF` are read back
before the snapshot connection is accepted. Only column identifiers and
structural metadata are exported, never DDL, defaults or row values. The v3
closure inventory follows code-owned, schema-attested primary joins for the
issue/PR dependency tables (comments, assignees, content histories, labels, issue
users/watches, reactions, reviews/state, dependencies, notifications,
stopwatches, tracked time and auto-merge), plus projects/boards, releases,
attachments, Packages and Actions. It emits only IDs required to prove joins,
actor classes, counts, declared sizes and SQLite byte lengths; it never selects
or prints text bodies, names, URLs, package metadata, workflow payloads,
credentials, tokens, secrets or logs. Package and Actions target features stay
disabled and no legacy row is importable. The successor additionally closes
every concrete FK-like comment field in the pinned schema (labels, projects,
milestones, tracked time, assignees, dependency, review and cross-reference),
content-history-to-comment, review-team and pull-merger provenance. Target
repository and local actor IDs are classified through the exact 2058/972
decisions. Migrated external-author IDs are never treated as local users and
are represented only by presence counts and author-name byte lengths. A
nonzero comment-assignee or review-reviewer team must resolve to an exact team
and organization; because no organization/team allowlist exists, its row,
team and organization IDs enter a sealed HOLD inventory and add the narrowly
scoped `issue-pr-team-mapping-hold` blocker. Orphans, conflicting user/team
identities, invalid cross-reference pairs and schema/type drift fail closed.
The report is still not a physical-file or sanitized-archive verifier, so
those separate blockers remain explicit.
The schema-catalog digest is recorded as observed evidence but deliberately
remains unpinned as reviewed activation authority. Schema absence/type drift,
invalid numeric/OID state or aggregate overflow is a hard error. `apply` fails
before creating `/volume1/docker/nodedc-gitea` until all of the following are
registered:
- root-owned Btrfs proof that the named snapshot UUID is read-only;
- exact stopped/restart-`no` legacy container image ID, image ref and sole
`/volume1/docker/gitea:/data` bind inspect;
- a separately verified exact reference/OID manifest digest, fsck,
reachability and selected-object reconstruction;
- immutable sanitized archives for issues, PRs, comments, releases, labels,
projects and repository descriptions, with no legacy row import;
- physical attachment inventory and reachable LFS pointer/OID/size/SHA proof;
- kept-user mapping before any collaboration recreation; and
- package/Actions schema plus physical zero closure and target unit-policy
acceptance.
All 25 direct repository relations have explicit dispositions, including the
15 exact zero-and-drop categories. Pull base/head counts remain directional
views of the same five PRs. All repository numeric hints are dropped and
recomputed. Repo-unit types 1–10 are total: clean types 1–5 and 8 are recreated
once per repository; external wiki/tracker are forbidden; Packages (9) and
Actions (10) are absent in the target and remain globally disabled. Legacy
unit config is never imported. The topics verifier accepts exact JSON `null`
as semantic empty state, or a canonical JSON array of sorted unique lowercase
names matching `^[a-z0-9][-.a-z0-9]*$` with at most 35 UTF-8 bytes. SQL NULL,
whitespace/case variants, quoted `"null"`, objects, numbers, booleans and
noncanonical arrays fail closed. The current snapshot must prove exactly 45
serialized JSON nulls, zero serialized arrays, zero material topics and zero
`repo_topic` rows; target cache is rebuilt from relations.
The activation hook remains frozen until these blockers are closed and the
full clean-database recreation, reflink reconstruction, doctor/fsck,
credential-table zeroing, rollback and public acceptance path has its own
runtime smoke. The current reviewed source identities are:
- runner `nodedc-deploy` SHA-256
`c766985aa02fe911fa5a873717276f3503d9cecded448e41dc6945030dcbce9e`;
- deterministic builder SHA-256
`b92076583aeab854015a05deb9d942c8dfcf3ca475fd3d52115d402d6f61acca`;
- salvage policy test SHA-256
`99b96b6179286a78e7d53ee6a923fc092e3471a8cece382a472449d455ad212c`;
- fresh-install policy test SHA-256
`20653c640142c25e7d2ef712048acc7889c56e1d519e2d03b5cad4127e48947c`;
- confirmed disposition SHA-256
`0a066724bcf6e4933133db6cab6cc273393e3c262dd00dda0bbf9ceebd84f78c`;
- confirmed closure disposition SHA-256
`7ed66d9848268431a703fe24b22c41afbaa7c5ff48949604d6fc448d93e0d243`;
- successor v3 descriptor SHA-256
`9b98eb1a1640fd5569cf051a621837379b167eff4527313a43a0a851e7cc181a`;
- deterministic local review artifact
`nodedc-gitea-gitea-incident-salvage-subrelation-closure-20260814-006.tgz`
SHA-256
`d3e598cf892b1371912dcd9cef64caa991dd23613e48fe979d0f95d493c23d53`.
Only after that exact runner is separately reviewed, promoted to the
root-owned runner path and its installed SHA-256 is re-attested may the exact
artifact be staged into the canonical inbox for a canonical `plan` command.
Staging is evidence collection only; it grants no authority to run `apply`.
The legacy identity is now pinned to the observed ref `gitea/gitea:latest`
and immutable image ID
`sha256:bf95d9a45ce4fe38b027d051cdc4a4bc531513489fa6244af4074efbb1c376d6`.
The mutable tag is provenance only. Every plan re-inspects exact name
`/gitea`, stopped state, restart `no`, and the sole RW bind
`/volume1/docker/gitea:/data`; drift is a hard stop.
The successor plan must report these exact remaining blockers:
- `attachment-physical-verifier-pending`;
- `candidate-root-activation-hard-frozen`;
- `closure-report-review-pin-pending`;
- `collaboration-kept-user-mapping-verifier-pending`;
- `forensic-ref-archive-verifier-pending`;
- `issue-pr-metadata-sanitized-archive-verifier-pending`;
- `lfs-reachable-pointer-physical-verifier-pending`;
- `package-action-physical-closure-verifier-pending`;
- `reference-manifest-fsck-reachability-verifier-pending`;
- `repository-object-reconstruction-verifier-pending`;
- `target-unit-policy-acceptance-pending`;
- `unsupported-schema-catalog-verifier-pending`.
Any other blocker or identity drift is also a stop. `apply` remains prohibited
and hard-frozen before root creation until a subsequent reviewed runner
revision closes every blocker and implements and smoke-tests the complete
activation/rollback path. The successor files must be independently reviewed
before any runner promotion or inbox staging.
Run the bounded policy suite with:
```bash
PYTHONDONTWRITEBYTECODE=1 \
python3 infra/deploy-runner/test_gitea_incident_salvage.py -v
```
The frozen local cutoff passes 54 incident-salvage tests and 26 fresh-install
tests, plus Python compilation and `git diff --check`.
`n8n-private-extension` is a staging-only trust boundary for reviewed offline
n8n private-node releases. Its artifact may contain exactly one digest-bound
`n8n-nodes-ndc` release with `package.tgz`, `release.json` and
@@ -1,222 +0,0 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import {
cp,
lstat,
mkdir,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const fixtureRoot = resolve(scriptDir, "fixtures/gitea");
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [patchId = "gitea-fresh-install-20260813-001", ...extra] =
process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
throw new Error("usage: build-gitea-fresh-install-artifact.mjs [patch-id]");
}
const composeRelative = "docker-compose.gitea.yml";
const descriptorRelative = "deployment/gitea-fresh-install-v1.json";
const files = [composeRelative, descriptorRelative];
const stage = await mkdtemp(join(tmpdir(), "nodedc-gitea-artifact-"));
const payload = join(stage, "payload");
const target = join(artifactDir, `nodedc-gitea-${patchId}.tgz`);
await assertFixtureContract();
try {
await mkdir(payload, { recursive: true });
for (const relative of files) {
const source = resolve(fixtureRoot, relative);
const sourceStat = await lstat(source);
if (sourceStat.isSymbolicLink() || !sourceStat.isFile()) {
throw new Error(`gitea_fixture_type_rejected:${relative}`);
}
const destination = join(payload, relative);
await mkdir(dirname(destination), { recursive: true });
await cp(source, destination, { force: true, verbatimSymlinks: true });
}
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=gitea\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
const tar = spawnSync(
"python3",
["-c", canonicalTarScript(), target, stage],
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
);
if (tar.status !== 0) {
throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
}
const digest = sha256(await readFile(target));
console.log(JSON.stringify({
ok: true,
patchId,
artifact: target,
sha256: digest,
component: "gitea",
entries: files,
services: ["gitea"],
image: "docker.gitea.com/gitea:1.27.1-rootless@sha256:89dc3c214b3992e5bb01e05ad21139d7a8b302d3ea3d8942d3f7e904e92af148",
installMode: "fresh-only",
database: "fresh-sqlite-only",
lfs: "disabled-pending-reviewed-restore-transition",
transport: "unix:/run/gitea/gitea.sock",
networkMode: "none",
minimumComposeVersion: "2.20.1",
preserved: ["legacy-gitea-root-unread-and-untouched"],
excluded: [
"secrets",
"runtime-data",
"database",
"repositories",
"users",
"tokens",
"ssh-keys",
"hooks",
],
}, null, 2));
} finally {
await rm(stage, { recursive: true, force: true });
}
async function assertFixtureContract() {
const composeBytes = await readFile(resolve(fixtureRoot, composeRelative));
const compose = composeBytes.toString("utf8");
const descriptor = JSON.parse(
await readFile(resolve(fixtureRoot, descriptorRelative), "utf8"),
);
const expectedImage =
"docker.gitea.com/gitea:1.27.1-rootless@sha256:89dc3c214b3992e5bb01e05ad21139d7a8b302d3ea3d8942d3f7e904e92af148";
const required = [
`image: ${expectedImage}`,
"platform: linux/amd64",
"pull_policy: never",
"network_mode: none",
'user: "1000:1000"',
"stop_grace_period: 30s",
"driver: json-file",
'max-size: "10m"',
'max-file: "3"',
"GITEA__server__PROTOCOL: http+unix",
"GITEA__server__HTTP_ADDR: /run/gitea/gitea.sock",
'GITEA__server__UNIX_SOCKET_PERMISSION: "0666"',
"GITEA__server__LOCAL_ROOT_URL: http://unix/",
'GITEA__server__DISABLE_SSH: "true"',
'GITEA__server__LFS_START_SERVER: "false"',
'GITEA__server__LFS_ALLOW_PURE_SSH: "false"',
"GITEA__security__SECRET_KEY_URI: file:/run/secrets/gitea_secret_key",
"GITEA__security__INTERNAL_TOKEN_URI: file:/run/secrets/gitea_internal_token",
"GITEA__security__TWO_FACTOR_AUTH: enforced",
'GITEA__security__REVERSE_PROXY_LIMIT: "1"',
"GITEA__security__ALLOWED_HOST_LIST: loopback",
"GITEA__security__REVERSE_PROXY_TRUSTED_PROXIES: 127.0.0.0/8,::1/128",
'GITEA__service__DISABLE_REGISTRATION: "true"',
'GITEA__service__ENABLE_REVERSE_PROXY_AUTHENTICATION: "false"',
'GITEA__service__ENABLE_REVERSE_PROXY_AUTHENTICATION_API: "false"',
'GITEA__service__ENABLE_REVERSE_PROXY_AUTO_REGISTRATION: "false"',
'GITEA__service__ENABLE_BASIC_AUTHENTICATION: "false"',
'GITEA__admin__DISABLE_REGULAR_ORG_CREATION: "true"',
"GITEA__admin__USER_DISABLED_FEATURES: deletion,manage_ssh_keys,manage_gpg_keys,change_username",
'GITEA__security__DISABLE_GIT_HOOKS: "true"',
'GITEA__security__DISABLE_WEBHOOKS: "true"',
'GITEA__repository__DISABLE_MIGRATIONS: "true"',
'GITEA__packages__ENABLED: "false"',
'GITEA__oauth2__ENABLED: "false"',
'GITEA__openid__ENABLE_OPENID_SIGNIN: "false"',
'GITEA__cron.update_checker__ENABLED: "false"',
"source: /volume1/docker/nodedc-gitea/socket",
"target: /run/gitea",
"create_host_path: false",
"read_only: true",
"no-new-privileges:true",
];
for (const fragment of required) {
if (!compose.includes(fragment)) {
throw new Error(`gitea_compose_boundary_missing:${fragment}`);
}
}
for (const forbidden of [
"4022",
"2222:2222",
"0.0.0.0:3000",
"ports:",
"networks:",
"/var/run/docker.sock",
"/volume1/docker/gitea",
"privileged: true",
"pull_policy: always",
"__FILE",
"GITEA__security__SECRET_KEY:",
"GITEA__security__INTERNAL_TOKEN:",
"GITEA__server__LFS_JWT_SECRET:",
"GITEA__server__LFS_JWT_SECRET_URI",
"gitea_lfs_jwt_secret",
"lfs-jwt-secret",
"GITEA__server__REVERSE_PROXY_LIMIT",
"GITEA__server__REVERSE_PROXY_TRUSTED_PROXIES",
"GITEA__security__ENABLE_REVERSE_PROXY_AUTHENTICATION",
"GITEA__security__ENABLE_REVERSE_PROXY_AUTHENTICATION_API",
"GITEA__security__ENABLE_REVERSE_PROXY_AUTO_REGISTRATION",
"GITEA__service__DISABLE_REGULAR_ORG_CREATION",
"GITEA__service__USER_DISABLED_FEATURES",
]) {
if (compose.includes(forbidden)) {
throw new Error(`gitea_compose_boundary_violation:${forbidden}`);
}
}
if (
descriptor.schemaVersion !== "nodedc.gitea.fresh-install.v1"
|| descriptor.action !== "fresh-install"
|| descriptor.component !== "gitea"
|| descriptor.compose?.sha256 !== sha256(composeBytes)
|| descriptor.runtime?.image !== expectedImage
|| descriptor.runtime?.minimumComposeVersion !== "2.20.1"
|| descriptor.runtime?.lfs !== "disabled-pending-reviewed-restore-transition"
|| descriptor.runtime?.transport !== "unix:/run/gitea/gitea.sock"
|| descriptor.runtime?.networkMode !== "none"
|| descriptor.runtime?.logging !== "bounded-json-file-10m-x3"
|| descriptor.runtime?.stopGracePeriod !== "30s"
|| descriptor.trust?.artifactSecrets !== "forbidden"
|| descriptor.trust?.legacyRootAccess !== "forbidden"
) {
throw new Error("gitea_descriptor_contract_mismatch");
}
}
function sha256(bytes) {
return createHash("sha256").update(bytes).digest("hex");
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -1,322 +0,0 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import {
cp,
link,
lstat,
mkdir,
mkdtemp,
readFile,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const fixtureRoot = resolve(scriptDir, "fixtures/gitea-salvage");
const decisionRoot = resolve(
scriptDir,
"../../../security-incidents/gitea-20260814/confirmed-decisions-v2",
);
const artifactDir = resolve(
process.env.NODEDC_DEPLOY_ARTIFACT_DIR
|| resolve(scriptDir, "../deploy-artifacts"),
);
const [patchId = "gitea-incident-salvage-subrelation-closure-20260814-006", ...extra] =
process.argv.slice(2);
if (extra.length || !/^[A-Za-z0-9._-]{1,96}$/.test(patchId)) {
throw new Error(
"usage: build-gitea-incident-salvage-artifact.mjs [patch-id]",
);
}
const composeRelative = "docker-compose.gitea.yml";
const descriptorRelative = "deployment/gitea-incident-salvage-v3.json";
const decisionPrefix = "deployment/gitea-incident-salvage";
const dispositionRelative = `${decisionPrefix}/confirmed-disposition-v1.json`;
const closureDispositionRelative =
`${decisionPrefix}/confirmed-closure-disposition-v1.json`;
const descriptorSha256 =
"9b98eb1a1640fd5569cf051a621837379b167eff4527313a43a0a851e7cc181a";
const dispositionSha256 =
"0a066724bcf6e4933133db6cab6cc273393e3c262dd00dda0bbf9ceebd84f78c";
const closureDispositionSha256 =
"7ed66d9848268431a703fe24b22c41afbaa7c5ff48949604d6fc448d93e0d243";
const decisionFiles = [
["confirmed-decision.json", "dc9528462624158eb44218d37cc7054d551ca2d7ded562592982aa3f34c9fc2a"],
["users.decisions.csv", "e3b82f1073a86eea9e567edff062dd1689d21ec0edcf3ed92e844da9351ee8b6"],
["repositories.decisions.csv", "76b4bae2ab5cec490330c19bfc5ae9429abf7636705ae028c1c64fd54a6a0493"],
];
const files = [
composeRelative,
descriptorRelative,
dispositionRelative,
closureDispositionRelative,
...decisionFiles.map(([name]) => `${decisionPrefix}/${name}`),
];
const stage = await mkdtemp(join(tmpdir(), "nodedc-gitea-salvage-artifact-"));
const payload = join(stage, "payload");
const target = join(artifactDir, `nodedc-gitea-${patchId}.tgz`);
const targetTemporary = join(
artifactDir,
`.${basename(target)}.${process.pid}.tmp`,
);
await assertSourceContract();
try {
await mkdir(payload, { recursive: true });
for (const relative of [
composeRelative,
descriptorRelative,
dispositionRelative,
closureDispositionRelative,
]) {
await copyRegularFile(resolve(fixtureRoot, relative), join(payload, relative), relative);
}
for (const [name] of decisionFiles) {
await copyRegularFile(
resolve(decisionRoot, name),
join(payload, decisionPrefix, name),
`${decisionPrefix}/${name}`,
);
}
await writeFile(
join(stage, "manifest.env"),
`id=${patchId}\ncomponent=gitea\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${files.join("\n")}\n`, "utf8");
await mkdir(artifactDir, { recursive: true });
const tar = spawnSync(
"python3",
["-c", canonicalTarScript(), targetTemporary, stage],
{ encoding: "utf8", maxBuffer: 16 * 1024 * 1024 },
);
if (tar.status !== 0) {
throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
}
try {
await link(targetTemporary, target);
} catch (error) {
if (error?.code === "EEXIST") {
throw new Error("gitea_salvage_artifact_target_already_exists");
}
throw error;
}
console.log(JSON.stringify({
ok: true,
patchId,
artifact: target,
sha256: sha256(await readFile(target)),
component: "gitea",
transition: "clean-state-incident-salvage",
entries: files,
services: ["gitea"],
image: "docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c",
decisions: {
users: { active: 2, locked: 8, delete: 962 },
repositories: { keep: 45, delete: 2013 },
},
disposition: {
sha256: dispositionSha256,
forensicRefs: 105,
liveRefs: 93,
archiveOnlyRefs: 12,
},
closureDisposition: {
sha256: closureDispositionSha256,
state: "plan-report-review-pending",
},
stateBoundary: "new-database-config-secrets-identities",
repositoryBoundary: "exact-45-object-and-validated-ref-material-only",
networkMode: "none",
transport: "unix:/run/gitea/gitea.sock",
stagePolicy: "after-exact-runner-promotion-plan-only",
applyPolicy: "hard-frozen-before-root-creation",
}, null, 2));
} finally {
await rm(targetTemporary, { force: true });
await rm(stage, { recursive: true, force: true });
}
async function copyRegularFile(source, destination, label) {
const sourceStat = await lstat(source);
if (sourceStat.isSymbolicLink() || !sourceStat.isFile()) {
throw new Error(`gitea_salvage_source_type_rejected:${label}`);
}
await mkdir(dirname(destination), { recursive: true });
await cp(source, destination, { force: true, verbatimSymlinks: true });
}
function canonicalJson(value) {
if (Array.isArray(value)) {
return value.map(canonicalJson);
}
if (value && typeof value === "object") {
return Object.fromEntries(
Object.keys(value).sort().map((key) => [key, canonicalJson(value[key])]),
);
}
return value;
}
async function assertSourceContract() {
for (const [name, expected] of decisionFiles) {
const bytes = await readFile(resolve(decisionRoot, name));
if (sha256(bytes) !== expected) {
throw new Error(`gitea_salvage_decision_digest_mismatch:${name}`);
}
}
const composeBytes = await readFile(resolve(fixtureRoot, composeRelative));
const compose = composeBytes.toString("utf8");
const descriptorBytes = await readFile(
resolve(fixtureRoot, descriptorRelative),
);
const descriptor = JSON.parse(descriptorBytes.toString("utf8"));
if (sha256(descriptorBytes) !== descriptorSha256) {
throw new Error("gitea_salvage_descriptor_digest_mismatch");
}
const dispositionBytes = await readFile(
resolve(fixtureRoot, dispositionRelative),
);
const disposition = JSON.parse(dispositionBytes.toString("utf8"));
if (sha256(dispositionBytes) !== dispositionSha256) {
throw new Error("gitea_salvage_disposition_digest_mismatch");
}
const canonicalDisposition = Buffer.from(
`${JSON.stringify(canonicalJson(disposition))}\n`,
"utf8",
);
if (!dispositionBytes.equals(canonicalDisposition)) {
throw new Error("gitea_salvage_disposition_not_canonical");
}
const closureDispositionBytes = await readFile(
resolve(fixtureRoot, closureDispositionRelative),
);
const closureDisposition = JSON.parse(closureDispositionBytes.toString("utf8"));
if (sha256(closureDispositionBytes) !== closureDispositionSha256) {
throw new Error("gitea_salvage_closure_disposition_digest_mismatch");
}
const canonicalClosureDisposition = Buffer.from(
`${JSON.stringify(canonicalJson(closureDisposition))}\n`,
"utf8",
);
if (!closureDispositionBytes.equals(canonicalClosureDisposition)) {
throw new Error("gitea_salvage_closure_disposition_not_canonical");
}
const expectedImage =
"docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c";
for (const required of [
`image: ${expectedImage}`,
"platform: linux/amd64",
"pull_policy: never",
"network_mode: none",
'user: "1000:1000"',
"entrypoint:",
"- /usr/local/bin/gitea",
"- /etc/gitea/app.ini",
"read_only: true",
"cap_drop:",
"- ALL",
"no-new-privileges:true",
"source: /volume1/docker/nodedc-gitea/data",
"target: /data",
"source: /volume1/docker/nodedc-gitea/config",
"target: /etc/gitea",
"source: /volume1/docker/nodedc-gitea/socket",
"target: /run/gitea",
"create_host_path: false",
]) {
if (!compose.includes(required)) {
throw new Error(`gitea_salvage_compose_boundary_missing:${required}`);
}
}
for (const forbidden of [
"ports:",
"networks:",
"/var/run/docker.sock",
"/volume1/docker/gitea",
"privileged: true",
"4022",
"TWO_FACTOR_AUTH",
"LFS_JWT_SECRET",
]) {
if (compose.includes(forbidden)) {
throw new Error(`gitea_salvage_compose_boundary_violation:${forbidden}`);
}
}
if (
descriptor.schemaVersion !== "nodedc.gitea.incident-salvage.v3"
|| descriptor.action !== "clean-state-salvage"
|| descriptor.compose?.sha256 !== sha256(composeBytes)
|| descriptor.runtime?.image !== expectedImage
|| descriptor.runtime?.networkMode !== "none"
|| descriptor.runtime?.database !== "new-sqlite-1.27.2-only"
|| descriptor.disposition?.file !== dispositionRelative
|| descriptor.disposition?.sha256 !== dispositionSha256
|| descriptor.closureDisposition?.file !== closureDispositionRelative
|| descriptor.closureDisposition?.sha256 !== closureDispositionSha256
|| descriptor.closureDisposition?.predecessorArtifactSha256
!== "d6870b5583a2f329eadb4e6cda65fdf4d271532df5ffbf8bfb1403968a434672"
|| descriptor.trust?.legacyDatabaseImported !== false
|| descriptor.trust?.legacyCredentialsImported !== false
|| descriptor.identity?.twoFactorAuthentication
!== "not-configured-by-transition"
) {
throw new Error("gitea_salvage_descriptor_contract_mismatch");
}
if (
disposition.schemaVersion !== "nodedc.gitea.incident-disposition.v1"
|| disposition.incidentId !== "gitea-20260814"
|| disposition.activation?.allowedOperation !== "canonical-plan-only"
|| disposition.activation?.applyFrozen !== true
|| disposition.activation?.freezeBoundary
!== "before-candidate-root-creation"
|| disposition.referencePolicy?.forensicScope?.allDiscoveredRefs !== 105
|| disposition.referencePolicy?.exactDecisions?.length !== 105
|| disposition.referencePolicy?.liveRestore?.totalRefs !== 93
|| disposition.referencePolicy?.archiveOnly?.totalRefs !== 12
) {
throw new Error("gitea_salvage_disposition_contract_mismatch");
}
if (
closureDisposition.schemaVersion
!== "nodedc.gitea.incident-closure-disposition.v1"
|| closureDisposition.incidentId !== "gitea-20260814"
|| closureDisposition.activation?.allowedOperation !== "canonical-plan-only"
|| closureDisposition.activation?.applyFrozen !== true
|| closureDisposition.closureReport?.expectedSha256 !== null
|| closureDisposition.predecessor?.dispositionSha256 !== dispositionSha256
|| closureDisposition.remainingBlockers
?.includes("closure-report-review-pin-pending") !== true
) {
throw new Error("gitea_salvage_closure_disposition_contract_mismatch");
}
}
function sha256(bytes) {
return createHash("sha256").update(bytes).digest("hex");
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'xb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -1,48 +0,0 @@
#!/usr/bin/env python3
"""Deterministic data-only declaration for the registered NAS map access domain."""
import argparse
import gzip
import hashlib
import io
import json
import re
import tarfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def build(patch, state="enabled"):
if not re.fullmatch(r"[A-Za-z0-9._-]{1,96}", patch) or state not in ("enabled", "disabled"):
raise ValueError("Invalid map access release")
descriptor = json.loads((ROOT / "deployment/mission-core-map-access/access.json").read_text())
if descriptor != {"schemaVersion": "nodedc.mission-core-map-access.v1", "state": "enabled"}:
raise ValueError("Unexpected source contract")
descriptor["state"] = state
members = {
"manifest.env": f"id={patch}\ncomponent=mission-core-map-access\ntype=app-overlay\n".encode(),
"files.txt": b"access.json\n",
"payload/access.json": (json.dumps(descriptor, sort_keys=True, separators=(",", ":")) + "\n").encode(),
}
result = io.BytesIO()
with gzip.GzipFile(fileobj=result, mode="wb", filename="", mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as archive:
for name, content in members.items():
member = tarfile.TarInfo(name); member.mode = 0o644; member.size = len(content)
archive.addfile(member, io.BytesIO(content))
return result.getvalue()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("patch")
parser.add_argument("--state", choices=("enabled", "disabled"), default="enabled")
args = parser.parse_args()
raw = build(args.patch, args.state)
target = ROOT / "infra/deploy-artifacts" / ("nodedc-" + args.patch + ".tgz")
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("xb") as output:
output.write(raw)
digest = hashlib.sha256(raw).hexdigest()
target.with_suffix(target.suffix + ".sha256").write_text(digest + " " + target.name + "\n")
print(json.dumps({"artifact": str(target), "sha256": digest, "bytes": len(raw)}))
@@ -12,36 +12,26 @@ const taskerRoot = resolve(
process.env.NODEDC_TASKMANAGER_ROOT || resolve(platformRoot, "../../data/dc_taskmanager/NODEDC_TASKMANAGER"),
);
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
const [release = "20260829-001", ...extra] = process.argv.slice(2);
const [release = "20260821-002", ...extra] = process.argv.slice(2);
if (extra.length || release !== "20260829-001") {
throw new Error("usage: build-tasker-attachment-formats-artifact.mjs [20260829-001]");
if (extra.length || release !== "20260821-002") {
throw new Error("usage: build-tasker-comments-route-diagnostics-artifact.mjs [20260821-002]");
}
const descriptor = {
artifactBasename: `nodedc-tasker-attachment-formats-${release}.tgz`,
artifactBasename: `nodedc-tasker-comments-route-diagnostics-${release}.tgz`,
component: "tasker",
expectedCommit: "f9308539bfe71e4e2359c47ed5c230fa1fb386c9",
files: [
"plane-src/apps/api/plane/settings/common.py",
"plane-src/apps/web/core/components/issues/attachment/attachment-list-item.tsx",
"plane-src/apps/web/core/components/issues/peek-overview/view.tsx",
"plane-src/apps/web/styles/globals.css",
"plane-src/packages/services/src/file/helper.ts",
],
patchId: `tasker-attachment-formats-${release}`,
sourceRoot: taskerRoot,
expectedCommit: "0df65d85dd8a04f2d2532235d482864a6f6cfd3d",
files: ["plane-src/apps/api/plane/authentication/views/nodedc_agent_adapter.py"],
patchId: `tasker-comments-route-diagnostics-${release}`,
};
const sourceCommit = gitOutput(descriptor.sourceRoot, ["rev-parse", "HEAD"]);
if (sourceCommit !== descriptor.expectedCommit) {
throw new Error(`source_commit_mismatch:${descriptor.component}:${sourceCommit}`);
}
const sourceStatus = gitOutput(descriptor.sourceRoot, ["status", "--porcelain"]);
if (sourceStatus) throw new Error(`source_worktree_not_clean:${descriptor.component}`);
const sourceCommit = gitOutput(taskerRoot, ["rev-parse", "HEAD"]);
if (sourceCommit !== descriptor.expectedCommit) throw new Error(`source_commit_mismatch:${sourceCommit}`);
if (gitOutput(taskerRoot, ["status", "--porcelain"])) throw new Error("source_worktree_not_clean:tasker");
await mkdir(artifactDir, { recursive: true });
const stage = await mkdtemp(join(tmpdir(), "nodedc-tasker-attachment-formats-"));
const stage = await mkdtemp(join(tmpdir(), "nodedc-tasker-comments-route-diagnostics-"));
const payload = join(stage, "payload");
const artifact = join(artifactDir, descriptor.artifactBasename);
@@ -49,11 +39,9 @@ try {
await assertFresh(artifact);
await mkdir(payload, { recursive: true });
for (const relativePath of descriptor.files) {
const source = resolve(descriptor.sourceRoot, relativePath);
const source = resolve(taskerRoot, relativePath);
const sourceStat = await lstat(source);
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
throw new Error(`source_file_rejected:${descriptor.component}:${relativePath}`);
}
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) throw new Error(`source_file_rejected:${relativePath}`);
const destination = join(payload, relativePath);
await mkdir(dirname(destination), { recursive: true });
await cp(source, destination, { force: false, verbatimSymlinks: true });
@@ -70,7 +58,7 @@ try {
encoding: "utf8",
maxBuffer: 128 * 1024 * 1024,
});
if (tar.status !== 0) throw new Error(`tar_failed:${descriptor.component}:${tar.stderr || tar.stdout}`);
if (tar.status !== 0) throw new Error(`tar_failed:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256").update(await readFile(artifact)).digest("hex");
console.log(
@@ -95,7 +83,7 @@ try {
function gitOutput(cwd, args) {
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
if (result.status !== 0) throw new Error(`git_failed:${cwd}:${args.join("_")}:${result.stderr || result.stdout}`);
if (result.status !== 0) throw new Error(`git_failed:${args.join("_")}:${result.stderr || result.stdout}`);
return result.stdout.trim();
}
@@ -0,0 +1,138 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(scriptDir, "../..");
const taskerRoot = resolve(
process.env.NODEDC_TASKMANAGER_ROOT || resolve(platformRoot, "../../data/dc_taskmanager/NODEDC_TASKMANAGER"),
);
const opsAgentsRoot = resolve(
process.env.NODEDC_OPS_AGENTS_ROOT || resolve(platformRoot, "../../data/NODEDC_TASKMANAGER_CODEXAPI"),
);
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
const [release = "20260821-001", ...extra] = process.argv.slice(2);
if (extra.length || release !== "20260821-001") {
throw new Error("usage: build-tasker-ops-comments-inventory-artifacts.mjs [20260821-001]");
}
const descriptors = [
{
artifactBasename: `nodedc-tasker-comments-inventory-${release}.tgz`,
component: "tasker",
expectedCommit: "42988b9cbea0a9a0b85a817c2dcb5b396aeda197",
files: [
"plane-src/apps/api/plane/authentication/views/nodedc_agent_adapter.py",
"plane-src/apps/api/plane/urls.py",
],
patchId: `tasker-comments-inventory-${release}`,
sourceRoot: taskerRoot,
},
{
artifactBasename: `nodedc-ops-agents-comments-inventory-${release}.tgz`,
component: "ops-agents",
expectedCommit: "d4fea6b29001df10444cae2ea95bc8259b22c763",
files: [
"src/mcp/tool-runtime.ts",
"src/routes/tools.ts",
"src/tasker/client.ts",
],
patchId: `ops-agents-comments-inventory-${release}`,
sourceRoot: opsAgentsRoot,
},
];
await mkdir(artifactDir, { recursive: true });
const artifacts = [];
for (const descriptor of descriptors) {
const sourceCommit = gitOutput(descriptor.sourceRoot, ["rev-parse", "HEAD"]);
if (sourceCommit !== descriptor.expectedCommit) {
throw new Error(`source_commit_mismatch:${descriptor.component}:${sourceCommit}`);
}
const sourceStatus = gitOutput(descriptor.sourceRoot, ["status", "--porcelain"]);
if (sourceStatus) throw new Error(`source_worktree_not_clean:${descriptor.component}`);
const stage = await mkdtemp(join(tmpdir(), `nodedc-${descriptor.component}-comments-inventory-`));
const payload = join(stage, "payload");
const artifact = join(artifactDir, descriptor.artifactBasename);
try {
await assertFresh(artifact);
await mkdir(payload, { recursive: true });
for (const relativePath of descriptor.files) {
const source = resolve(descriptor.sourceRoot, relativePath);
const sourceStat = await lstat(source);
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
throw new Error(`source_file_rejected:${descriptor.component}:${relativePath}`);
}
const destination = join(payload, relativePath);
await mkdir(dirname(destination), { recursive: true });
await cp(source, destination, { force: false, verbatimSymlinks: true });
}
await writeFile(
join(stage, "manifest.env"),
`id=${descriptor.patchId}\ncomponent=${descriptor.component}\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${descriptor.files.join("\n")}\n`, "utf8");
const tar = spawnSync("python3", ["-c", canonicalTarScript(), artifact, stage], {
encoding: "utf8",
maxBuffer: 128 * 1024 * 1024,
});
if (tar.status !== 0) throw new Error(`tar_failed:${descriptor.component}:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256").update(await readFile(artifact)).digest("hex");
artifacts.push({
artifact,
component: descriptor.component,
files: descriptor.files,
patchId: descriptor.patchId,
sha256,
sourceCommit,
});
} finally {
await rm(stage, { recursive: true, force: true });
}
}
console.log(JSON.stringify({ ok: true, release, deployOrder: ["tasker", "ops-agents"], artifacts }, null, 2));
function gitOutput(cwd, args) {
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
if (result.status !== 0) throw new Error(`git_failed:${cwd}:${args.join("_")}:${result.stderr || result.stdout}`);
return result.stdout.trim();
}
async function assertFresh(path) {
try {
await lstat(path);
} catch (error) {
if (error?.code === "ENOENT") return;
throw error;
}
throw new Error(`output_already_exists:${path}`);
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -0,0 +1,137 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { spawnSync } from "node:child_process";
import { cp, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const scriptDir = dirname(fileURLToPath(import.meta.url));
const platformRoot = resolve(scriptDir, "../..");
const taskerRoot = resolve(
process.env.NODEDC_TASKMANAGER_ROOT || resolve(platformRoot, "../../data/dc_taskmanager/NODEDC_TASKMANAGER"),
);
const opsAgentsRoot = resolve(
process.env.NODEDC_OPS_AGENTS_ROOT || resolve(platformRoot, "../../data/NODEDC_TASKMANAGER_CODEXAPI"),
);
const artifactDir = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || resolve(scriptDir, "../deploy-artifacts"));
const [release = "20260822-003", ...extra] = process.argv.slice(2);
if (extra.length || release !== "20260822-003") {
throw new Error("usage: build-tasker-ops-comments-read-artifacts.mjs [20260822-003]");
}
const descriptors = [
{
artifactBasename: `nodedc-tasker-comments-read-${release}.tgz`,
component: "tasker",
expectedCommit: "7f97c21886ff7dff314db89aa1877e2113e5570b",
files: [
"plane-src/apps/api/plane/authentication/views/nodedc_agent_adapter.py",
],
patchId: `tasker-comments-read-${release}`,
sourceRoot: taskerRoot,
},
{
artifactBasename: `nodedc-ops-agents-comments-read-${release}.tgz`,
component: "ops-agents",
expectedCommit: "6b63049d79eb975372d9f6a01cc32684563678a8",
files: [
"src/mcp/tool-runtime.ts",
"src/routes/tools.ts",
"src/tasker/client.ts",
],
patchId: `ops-agents-comments-read-${release}`,
sourceRoot: opsAgentsRoot,
},
];
await mkdir(artifactDir, { recursive: true });
const artifacts = [];
for (const descriptor of descriptors) {
const sourceCommit = gitOutput(descriptor.sourceRoot, ["rev-parse", "HEAD"]);
if (sourceCommit !== descriptor.expectedCommit) {
throw new Error(`source_commit_mismatch:${descriptor.component}:${sourceCommit}`);
}
const sourceStatus = gitOutput(descriptor.sourceRoot, ["status", "--porcelain"]);
if (sourceStatus) throw new Error(`source_worktree_not_clean:${descriptor.component}`);
const stage = await mkdtemp(join(tmpdir(), `nodedc-${descriptor.component}-comments-read-`));
const payload = join(stage, "payload");
const artifact = join(artifactDir, descriptor.artifactBasename);
try {
await assertFresh(artifact);
await mkdir(payload, { recursive: true });
for (const relativePath of descriptor.files) {
const source = resolve(descriptor.sourceRoot, relativePath);
const sourceStat = await lstat(source);
if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
throw new Error(`source_file_rejected:${descriptor.component}:${relativePath}`);
}
const destination = join(payload, relativePath);
await mkdir(dirname(destination), { recursive: true });
await cp(source, destination, { force: false, verbatimSymlinks: true });
}
await writeFile(
join(stage, "manifest.env"),
`id=${descriptor.patchId}\ncomponent=${descriptor.component}\ntype=app-overlay\n`,
"utf8",
);
await writeFile(join(stage, "files.txt"), `${descriptor.files.join("\n")}\n`, "utf8");
const tar = spawnSync("python3", ["-c", canonicalTarScript(), artifact, stage], {
encoding: "utf8",
maxBuffer: 128 * 1024 * 1024,
});
if (tar.status !== 0) throw new Error(`tar_failed:${descriptor.component}:${tar.stderr || tar.stdout}`);
const sha256 = createHash("sha256").update(await readFile(artifact)).digest("hex");
artifacts.push({
artifact,
component: descriptor.component,
files: descriptor.files,
patchId: descriptor.patchId,
sha256,
sourceCommit,
});
} finally {
await rm(stage, { recursive: true, force: true });
}
}
console.log(JSON.stringify({ ok: true, release, deployOrder: ["tasker", "ops-agents"], artifacts }, null, 2));
function gitOutput(cwd, args) {
const result = spawnSync("git", args, { cwd, encoding: "utf8" });
if (result.status !== 0) throw new Error(`git_failed:${cwd}:${args.join("_")}:${result.stderr || result.stdout}`);
return result.stdout.trim();
}
async function assertFresh(path) {
try {
await lstat(path);
} catch (error) {
if (error?.code === "ENOENT") return;
throw error;
}
throw new Error(`output_already_exists:${path}`);
}
function canonicalTarScript() {
return [
"import gzip,io,pathlib,sys,tarfile",
"root=pathlib.Path(sys.argv[2])",
"with open(sys.argv[1],'wb') as out:",
" with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
" with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
" for top in ('manifest.env','files.txt','payload'):",
" p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
" for x in paths:",
" info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
" info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
" with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
].join("\n");
}
@@ -1,44 +0,0 @@
#!/usr/bin/env python3
"""Deterministic data-only receipt for the exact B2 foundation002 incident."""
import argparse
import gzip
import hashlib
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import tarfile
loader = importlib.machinery.SourceFileLoader('b2_reconciliation_builder_runner', str(Path(__file__).with_name('nodedc-deploy')))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec)
loader.exec_module(R)
def build(destination):
data = {
'manifest.env': ('id=' + R.DEVICE_B2_RECON_ID + '\ncomponent=device-b2-foundation-reconciliation\ntype=app-overlay\n').encode(),
'files.txt': (R.DEVICE_B2_RECON_ENTRY + '\n').encode(),
'payload/' + R.DEVICE_B2_RECON_ENTRY: (json.dumps(R.device_b2_reconciliation_descriptor(), indent=2) + '\n').encode(),
}
destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
with destination.open('xb') as output:
with gzip.GzipFile(filename='', mode='wb', fileobj=output, mtime=0) as gz:
with tarfile.open(fileobj=gz, mode='w', format=tarfile.PAX_FORMAT) as archive:
for name, value in sorted(data.items()):
member = tarfile.TarInfo(name)
member.size = len(value)
member.mode = 0o644
member.mtime = 0
archive.addfile(member, io.BytesIO(value))
return {'id': R.DEVICE_B2_RECON_ID, 'component': 'device-b2-foundation-reconciliation',
'artifact': str(destination), 'sha256': hashlib.sha256(destination.read_bytes()).hexdigest(),
'entries': [R.DEVICE_B2_RECON_ENTRY], 'services': [], 'build': [], 'runtimeMutation': False}
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--output', required=True)
print(json.dumps(build(parser.parse_args().output), indent=2))
@@ -1,36 +0,0 @@
# B2 foundation: Compose 2.20.1 serialization regression
These JSON files are real `config --format json` output, generated from the
synthetic, secret-free `base.yml` and the exact production `override.yml`.
No Docker daemon, container, worker or production mutation is involved.
Official Docker Compose v2.20.1 Darwin arm64 release binary SHA256:
`e5449e23d14740092c4e764dd9e66cc693d8b02747167c045fd4edfd64fda958`.
Source: <https://github.com/docker/compose/releases/tag/v2.20.1>.
This is the upstream parser version; the NAS build is
`2.20.1-6047-g6817716`, not this exact binary.
Generate from this directory, using a separately SHA-verified binary:
```sh
"$COMPOSE_BINARY" -p nodedc-device-plane --env-file /dev/null \
--project-directory /volume1/docker/nodedc-device-plane \
-f base.yml config --format json > base.json
"$COMPOSE_BINARY" -p nodedc-device-plane --env-file /dev/null \
--project-directory /volume1/docker/nodedc-device-plane \
-f base.yml -f override.yml config --format json > candidate.json
```
JSON whitespace is formatted with Python `json.dumps(..., indent=2)`.
The new mount emits `bind: {}` and omits `read_only`: both booleans are false.
Runner016 incorrectly expected an explicit `create_host_path: false` property.
Runner017 removes that exact false property only from the new B2 mount inside
comparison copies. Raw config, its digest, fixed YAML, all old mounts and
other properties stay exact. True/null/numeric/string values and unknown bind
options are rejected. The source YAML must still explicitly disable directory
creation; accepting this JSON output cannot authorize a different YAML.
The same failure and fix were also reproduced using all five current NAS
Compose files through SMB, without reading any referenced secret file.
Only filenames, hashes and comparison outcomes are retained in public evidence;
the full effective configuration is not a fixture or a deploy payload.
@@ -1,67 +0,0 @@
{
"name": "nodedc-device-plane",
"networks": {
"default": {
"name": "nodedc-device-plane_default",
"ipam": {},
"external": false
},
"egress": {
"name": "nodedc-device-plane_egress",
"ipam": {},
"external": false
},
"private": {
"name": "nodedc-device-plane_private",
"ipam": {},
"external": false,
"internal": true
}
},
"services": {
"device-control-core": {
"command": null,
"entrypoint": null,
"environment": {
"EXISTING": "synthetic-preserved"
},
"image": "nodedc/device-control-core:local",
"networks": {
"egress": {},
"private": {
"priority": 100
}
},
"volumes": [
{
"type": "bind",
"source": "/synthetic/existing-secret-reference",
"target": "/run/existing-secret-reference",
"read_only": true,
"bind": {}
}
]
},
"device-postgres": {
"command": null,
"entrypoint": null,
"image": "postgres:16",
"networks": {
"default": null
},
"volumes": [
{
"type": "volume",
"source": "existing-data",
"target": "/var/lib/postgresql/data"
}
]
}
},
"volumes": {
"existing-data": {
"name": "nodedc-device-plane_existing-data",
"external": false
}
}
}
@@ -1,29 +0,0 @@
services:
device-control-core:
image: nodedc/device-control-core:local
environment:
EXISTING: synthetic-preserved
volumes:
- type: bind
source: /synthetic/existing-secret-reference
target: /run/existing-secret-reference
read_only: true
bind:
create_host_path: false
networks:
private:
priority: 100
egress:
priority: 0
device-postgres:
image: postgres:16
volumes:
- type: volume
source: existing-data
target: /var/lib/postgresql/data
networks:
private:
internal: true
egress: {}
volumes:
existing-data: {}
@@ -1,74 +0,0 @@
{
"name": "nodedc-device-plane",
"networks": {
"default": {
"name": "nodedc-device-plane_default",
"ipam": {},
"external": false
},
"egress": {
"name": "nodedc-device-plane_egress",
"ipam": {},
"external": false
},
"private": {
"name": "nodedc-device-plane_private",
"ipam": {},
"external": false,
"internal": true
}
},
"services": {
"device-control-core": {
"command": null,
"entrypoint": null,
"environment": {
"DEVICE_B2_SECRET_ROOT": "/run/nodedc-b2-connections",
"EXISTING": "synthetic-preserved"
},
"image": "nodedc/device-control-core:local",
"networks": {
"egress": {},
"private": {
"priority": 100
}
},
"volumes": [
{
"type": "bind",
"source": "/synthetic/existing-secret-reference",
"target": "/run/existing-secret-reference",
"read_only": true,
"bind": {}
},
{
"type": "bind",
"source": "/volume1/docker/nodedc-device-plane/private-b2-connections",
"target": "/run/nodedc-b2-connections",
"bind": {}
}
]
},
"device-postgres": {
"command": null,
"entrypoint": null,
"image": "postgres:16",
"networks": {
"default": null
},
"volumes": [
{
"type": "volume",
"source": "existing-data",
"target": "/var/lib/postgresql/data"
}
]
}
},
"volumes": {
"existing-data": {
"name": "nodedc-device-plane_existing-data",
"external": false
}
}
}
@@ -1,11 +0,0 @@
services:
device-control-core:
environment:
DEVICE_B2_SECRET_ROOT: /run/nodedc-b2-connections
volumes:
- type: bind
source: /volume1/docker/nodedc-device-plane/private-b2-connections
target: /run/nodedc-b2-connections
read_only: false
bind:
create_host_path: false
@@ -1,13 +0,0 @@
{
"schemaVersion": "nodedc.device-b2-shared-contours.v1",
"releaseId": "device-b2-shared-contours-v1-20261001-001",
"baselineReleaseId": "device-core-release-v1-r37-1b3001dfa12598af28882232336d837514502718",
"baselineSha256": "fca735b4177ba5397e2af31520682aeb17670a8d38a19176be2c08f07f37dffe",
"files": {
"deployment/device-b2-shared-contours-v1.sql": "caff93f717bbd61ebaf8ffec0b9b2ad04885da22c4e332c1a4586e149faab57a",
"deployment/device-b2-shared-contours-v1.rollback.sql": "f862da8316695d162167bd1fa854edcbf10d82f57462e3021cf199e72ef16b4f"
},
"transition": "one-contour-many-projects",
"services": [],
"rollback": "refuse-multiple-projects;preserve-all-rows"
}
@@ -1,20 +0,0 @@
begin;
set local lock_timeout = '5s';
set local statement_timeout = '30s';
lock table device_b2_contour_links in access exclusive mode;
do $$
begin
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-shared-contours/v1'
or (select pg_get_constraintdef(oid) from pg_constraint
where conrelid='device_b2_contour_links'::regclass and contype='p')
is distinct from 'PRIMARY KEY (source_id, contour_id, project_id)' then
raise exception 'device_b2_shared_contours_rollback_predecessor_mismatch';
end if;
if exists(select 1 from device_b2_contour_links group by source_id,contour_id having count(*)>1) then
raise exception 'device_b2_shared_contours_rollback_would_lose_links';
end if;
end $$;
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
alter table device_b2_contour_links add primary key (source_id, contour_id);
comment on table device_b2_contour_links is 'nodedc.device-b2-foundation/v1';
commit;
@@ -1,32 +0,0 @@
begin;
set local lock_timeout = '5s';
set local statement_timeout = '30s';
-- Separate, versioned foundation transition. Never run from application startup.
-- Preserve every assignment; only the identity of an assignment becomes a triple.
lock table device_b2_contour_links in access exclusive mode;
create temporary table device_b2_links_before on commit drop as
select * from device_b2_contour_links;
do $$
begin
if obj_description('device_b2_contour_links'::regclass) is distinct from 'nodedc.device-b2-foundation/v1'
or (select pg_get_constraintdef(oid) from pg_constraint
where conrelid='device_b2_contour_links'::regclass and contype='p')
is distinct from 'PRIMARY KEY (source_id, contour_id)' then
raise exception 'device_b2_shared_contours_predecessor_mismatch';
end if;
end $$;
alter table device_b2_contour_links drop constraint device_b2_contour_links_pkey;
alter table device_b2_contour_links add primary key (source_id, contour_id, project_id);
comment on table device_b2_contour_links is 'nodedc.device-b2-shared-contours/v1';
do $$
begin
if exists(
(select * from device_b2_links_before except all select * from device_b2_contour_links)
union all
(select * from device_b2_contour_links except all select * from device_b2_links_before)
) then
raise exception 'device_b2_shared_contours_row_preservation_failed';
end if;
end $$;
commit;
@@ -1,25 +0,0 @@
# Actual Compose 2.20.3 config output
`base.json` is an isolated synthetic two-service configuration, with no secrets,
mounts or published ports. `config.json` contains the full parsed JSON output of
the official Darwin ARM64 Compose v2.20.3 binary, SHA256
`51cd66bf94923ec8668f1a78c8740abb6cfbe1189da5720a8051a97be527372b`.
Reproduce without creating containers or contacting Docker Engine:
```sh
COMPOSE=/absolute/path/to/docker-compose-2.20.3
FIXTURE=infra/deploy-runner/fixtures/device-core-network-priority-compose220/base.json
"$COMPOSE" -p nodedc-ci-null-endpoint-repro -f "$FIXTURE" config --format json
"$COMPOSE" -p nodedc-ci-null-endpoint-repro -f "$FIXTURE" \
-f infra/device-core-deploy/docker-compose.network-priority.yml config --format json
```
The first output contains `null` for bare attachments. The second contains `{}`
for explicit zero-priority endpoints and `{"priority":100}` for private networks.
Do not replace nulls with hand-written fixture objects: that omission caused
runner014 to reject the initial NAS plan. The fixture regression reproduces
`Device Core network priority endpoint is invalid` on014 and passes on015.
It compares the full config, preserves raw config hashes and exercises negative
endpoint-type/property changes separately. This is synthetic source evidence;
it does not claim access to the NAS effective config or its exact Compose version.
@@ -1 +0,0 @@
{"services": {"device-control-core": {"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920", "pull_policy": "never", "command": ["node", "-e", "setInterval(()=>{},1000)"], "read_only": true, "cap_drop": ["ALL"], "security_opt": ["no-new-privileges:true"], "stop_grace_period": "1s", "mem_limit": "96m", "pids_limit": 32, "networks": ["device-plane-private", "device-plane-egress"]}, "device-manager": {"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920", "pull_policy": "never", "command": ["node", "-e", "setInterval(()=>{},1000)"], "read_only": true, "cap_drop": ["ALL"], "security_opt": ["no-new-privileges:true"], "stop_grace_period": "1s", "mem_limit": "96m", "pids_limit": 32, "networks": ["device-plane-private", "platform-edge"]}}, "networks": {"device-plane-private": {"internal": true}, "device-plane-egress": {}, "platform-edge": {}}}
@@ -1,148 +0,0 @@
{
"base": {
"name": "nodedc-ci-null-endpoint-repro",
"networks": {
"device-plane-egress": {
"name": "nodedc-ci-null-endpoint-repro_device-plane-egress",
"ipam": {},
"external": false
},
"device-plane-private": {
"name": "nodedc-ci-null-endpoint-repro_device-plane-private",
"ipam": {},
"external": false,
"internal": true
},
"platform-edge": {
"name": "nodedc-ci-null-endpoint-repro_platform-edge",
"ipam": {},
"external": false
}
},
"services": {
"device-control-core": {
"cap_drop": [
"ALL"
],
"command": [
"node",
"-e",
"setInterval(()=>{},1000)"
],
"entrypoint": null,
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
"mem_limit": "100663296",
"networks": {
"device-plane-egress": null,
"device-plane-private": null
},
"pids_limit": 32,
"pull_policy": "never",
"read_only": true,
"security_opt": [
"no-new-privileges:true"
],
"stop_grace_period": "1s"
},
"device-manager": {
"cap_drop": [
"ALL"
],
"command": [
"node",
"-e",
"setInterval(()=>{},1000)"
],
"entrypoint": null,
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
"mem_limit": "100663296",
"networks": {
"device-plane-private": null,
"platform-edge": null
},
"pids_limit": 32,
"pull_policy": "never",
"read_only": true,
"security_opt": [
"no-new-privileges:true"
],
"stop_grace_period": "1s"
}
}
},
"candidate": {
"name": "nodedc-ci-null-endpoint-repro",
"networks": {
"device-plane-egress": {
"name": "nodedc-ci-null-endpoint-repro_device-plane-egress",
"ipam": {},
"external": false
},
"device-plane-private": {
"name": "nodedc-ci-null-endpoint-repro_device-plane-private",
"ipam": {},
"external": false,
"internal": true
},
"platform-edge": {
"name": "nodedc-ci-null-endpoint-repro_platform-edge",
"ipam": {},
"external": false
}
},
"services": {
"device-control-core": {
"cap_drop": [
"ALL"
],
"command": [
"node",
"-e",
"setInterval(()=>{},1000)"
],
"entrypoint": null,
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
"mem_limit": "100663296",
"networks": {
"device-plane-egress": {},
"device-plane-private": {
"priority": 100
}
},
"pids_limit": 32,
"pull_policy": "never",
"read_only": true,
"security_opt": [
"no-new-privileges:true"
],
"stop_grace_period": "1s"
},
"device-manager": {
"cap_drop": [
"ALL"
],
"command": [
"node",
"-e",
"setInterval(()=>{},1000)"
],
"entrypoint": null,
"image": "sha256:968df39aedcea65eeb078fb336ed7191baf48f972b4479711397108be0966920",
"mem_limit": "100663296",
"networks": {
"device-plane-private": {
"priority": 100
},
"platform-edge": {}
},
"pids_limit": 32,
"pull_policy": "never",
"read_only": true,
"security_opt": [
"no-new-privileges:true"
],
"stop_grace_period": "1s"
}
}
}
}
@@ -1,112 +0,0 @@
{
"schemaVersion": "nodedc.gitea.incident-salvage.v1",
"action": "clean-state-salvage",
"component": "gitea",
"incidentId": "gitea-20260814",
"installRoot": "/volume1/docker/nodedc-gitea",
"compose": {
"file": "docker-compose.gitea.yml",
"project": "nodedc-gitea",
"service": "gitea",
"sha256": "2f031d5bfff4f42c73cabd8c94487ec3e4f1e1b0a96d3b7eec958904f735908a"
},
"runtime": {
"image": "docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c",
"imageId": "sha256:272085a806e6d182352cdb011c0ebab1d2efc7ec45247de84de5659c7bc5c4c6",
"repoDigest": "docker.gitea.com/gitea@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c",
"platform": "linux/amd64",
"pullPolicy": "never",
"entrypoint": "/usr/local/bin/gitea",
"runAs": "1000:1000",
"transport": "unix:/run/gitea/gitea.sock",
"networkMode": "none",
"ssh": "disabled-no-published-port",
"lfs": "unsupported-hard-stop",
"database": "new-sqlite-1.27.2-only",
"logging": "bounded-json-file-10m-x3",
"stopGracePeriod": "30s",
"candidateRestartPolicy": "no",
"acceptedRestartPolicy": "unless-stopped"
},
"decision": {
"schema": "nodedc.gitea.incident-decision/v2",
"manifestFile": "deployment/gitea-incident-salvage/confirmed-decision.json",
"manifestSha256": "dc9528462624158eb44218d37cc7054d551ca2d7ded562592982aa3f34c9fc2a",
"usersFile": "deployment/gitea-incident-salvage/users.decisions.csv",
"usersSha256": "e3b82f1073a86eea9e567edff062dd1689d21ec0edcf3ed92e844da9351ee8b6",
"repositoriesFile": "deployment/gitea-incident-salvage/repositories.decisions.csv",
"repositoriesSha256": "76b4bae2ab5cec490330c19bfc5ae9429abf7636705ae028c1c64fd54a6a0493",
"users": {
"active": 2,
"locked": 8,
"delete": 962
},
"repositories": {
"keep": 45,
"delete": 2013,
"dctouchPrivate": 32,
"silverPublic": 13
}
},
"snapshot": {
"root": "/volume1/.nodedc-security-snapshots/docker-gitea-incident-20260814",
"uuid": "f5a3fe3a-93ea-bb4d-847f-6221a6bcbc9f",
"readOnlyRequired": true,
"database": "gitea/gitea/gitea.db",
"databaseBytes": 182681600,
"databaseSha256": "8db9e74a5641662a808d8252c5d6c9de43fe9efd8687634bfbff2d4361a13052",
"repositoriesRoot": "gitea/git/repositories"
},
"trust": {
"legacyRootMounted": false,
"legacyDatabaseImported": false,
"legacyConfigImported": false,
"legacyCredentialsImported": false,
"artifactSecrets": "forbidden",
"runtimeSecrets": "runner-generated",
"repositorySelection": "exact-v2-rows-only",
"repositoryCopy": "same-filesystem-per-file-reflink-object-and-validated-ref-material-only",
"forbiddenRepositoryMaterial": [
"hooks",
"config",
"alternates",
"http-alternates",
"shallow",
"replace",
"grafts",
"worktrees",
"commondir",
"lfs"
],
"unsupportedDatabaseState": "zero-material-rows-required-before-apply"
},
"identity": {
"preserveNumericUserIds": false,
"preserveNumericRepositoryIds": false,
"oldToNewIdMapping": "/volume1/docker/nodedc-gitea/audit/identity-map.json",
"emails": "new-local-noreply-only",
"passwordHashes": "never-imported",
"activeBootstrapCredentials": "root-only-runner-state-require-change",
"lockedCredentials": "fresh-random-discarded-and-login-prohibited",
"twoFactorAuthentication": "not-configured-by-transition"
},
"externalPrerequisites": {
"legacyContainer": "exact-inspect-pin-required-stopped-restart-no",
"publicProxy": "reviewed-nginx-uds-bridge-and-dsm-loopback-upstream",
"firewall": "legacy-isolation-retained-and-loopback-3000-ready",
"candidatePublicationGate": "socket-parent-uid1000-gid1023-mode0700",
"publishAction": "runner-chmod-socket-parent-0750-after-internal-acceptance",
"mustPassBeforeApply": true
},
"acceptance": {
"users": "exact-10-row-by-row",
"repositories": "exact-45-row-by-row-and-visibility",
"credentialsSessionsKeysWebhooksActions": "zero",
"git": "fsck-all-and-public-smart-http-smoke",
"registration": "closed",
"ssh": "disabled",
"network": "none-no-ports",
"publicHttps": "required-before-ledger-success"
},
"rollback": "stop-remove-candidate-prove-absent-quarantine-new-root-never-start-legacy"
}
@@ -1,117 +0,0 @@
{
"schemaVersion": "nodedc.gitea.incident-salvage.v2",
"action": "clean-state-salvage",
"component": "gitea",
"incidentId": "gitea-20260814",
"installRoot": "/volume1/docker/nodedc-gitea",
"compose": {
"file": "docker-compose.gitea.yml",
"project": "nodedc-gitea",
"service": "gitea",
"sha256": "2f031d5bfff4f42c73cabd8c94487ec3e4f1e1b0a96d3b7eec958904f735908a"
},
"runtime": {
"image": "docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c",
"imageId": "sha256:272085a806e6d182352cdb011c0ebab1d2efc7ec45247de84de5659c7bc5c4c6",
"repoDigest": "docker.gitea.com/gitea@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c",
"platform": "linux/amd64",
"pullPolicy": "never",
"entrypoint": "/usr/local/bin/gitea",
"runAs": "1000:1000",
"transport": "unix:/run/gitea/gitea.sock",
"networkMode": "none",
"ssh": "disabled-no-published-port",
"lfs": "disabled-pending-reachable-pointer-physical-sha-verifier",
"database": "new-sqlite-1.27.2-only",
"logging": "bounded-json-file-10m-x3",
"stopGracePeriod": "30s",
"candidateRestartPolicy": "no",
"acceptedRestartPolicy": "unless-stopped"
},
"decision": {
"schema": "nodedc.gitea.incident-decision/v2",
"manifestFile": "deployment/gitea-incident-salvage/confirmed-decision.json",
"manifestSha256": "dc9528462624158eb44218d37cc7054d551ca2d7ded562592982aa3f34c9fc2a",
"usersFile": "deployment/gitea-incident-salvage/users.decisions.csv",
"usersSha256": "e3b82f1073a86eea9e567edff062dd1689d21ec0edcf3ed92e844da9351ee8b6",
"repositoriesFile": "deployment/gitea-incident-salvage/repositories.decisions.csv",
"repositoriesSha256": "76b4bae2ab5cec490330c19bfc5ae9429abf7636705ae028c1c64fd54a6a0493",
"users": {
"active": 2,
"locked": 8,
"delete": 962
},
"repositories": {
"keep": 45,
"delete": 2013,
"dctouchPrivate": 32,
"silverPublic": 13
}
},
"disposition": {
"schema": "nodedc.gitea.incident-disposition.v1",
"file": "deployment/gitea-incident-salvage/confirmed-disposition-v1.json",
"sha256": "0a066724bcf6e4933133db6cab6cc273393e3c262dd00dda0bbf9ceebd84f78c"
},
"snapshot": {
"root": "/volume1/.nodedc-security-snapshots/docker-gitea-incident-20260814",
"uuid": "f5a3fe3a-93ea-bb4d-847f-6221a6bcbc9f",
"readOnlyRequired": true,
"database": "gitea/gitea/gitea.db",
"databaseBytes": 182681600,
"databaseSha256": "8db9e74a5641662a808d8252c5d6c9de43fe9efd8687634bfbff2d4361a13052",
"repositoriesRoot": "gitea/git/repositories"
},
"trust": {
"legacyRootMounted": false,
"legacyDatabaseImported": false,
"legacyConfigImported": false,
"legacyCredentialsImported": false,
"artifactSecrets": "forbidden",
"runtimeSecrets": "runner-generated",
"repositorySelection": "exact-v2-rows-only",
"repositoryCopy": "same-filesystem-per-file-reflink-object-and-validated-ref-material-only",
"forbiddenRepositoryMaterial": [
"hooks",
"config",
"alternates",
"http-alternates",
"shallow",
"replace",
"grafts",
"worktrees",
"commondir",
"lfs"
],
"unsupportedDatabaseState": "confirmed-disposition-bound-no-legacy-row-import-verifiers-pending"
},
"identity": {
"preserveNumericUserIds": false,
"preserveNumericRepositoryIds": false,
"oldToNewIdMapping": "/volume1/docker/nodedc-gitea/audit/identity-map.json",
"emails": "new-local-noreply-only",
"passwordHashes": "never-imported",
"activeBootstrapCredentials": "root-only-runner-state-require-change",
"lockedCredentials": "fresh-random-discarded-and-login-prohibited",
"twoFactorAuthentication": "not-configured-by-transition"
},
"externalPrerequisites": {
"legacyContainer": "exact-inspect-pin-required-stopped-restart-no",
"publicProxy": "reviewed-nginx-uds-bridge-and-dsm-loopback-upstream",
"firewall": "legacy-isolation-retained-and-loopback-3000-ready",
"candidatePublicationGate": "socket-parent-uid1000-gid1023-mode0700",
"publishAction": "runner-chmod-socket-parent-0750-after-internal-acceptance",
"mustPassBeforeApply": true
},
"acceptance": {
"users": "exact-10-row-by-row",
"repositories": "exact-45-row-by-row-and-visibility",
"credentialsSessionsKeysWebhooksActions": "zero",
"git": "fsck-all-and-public-smart-http-smoke",
"registration": "closed",
"ssh": "disabled",
"network": "none-no-ports",
"publicHttps": "required-before-ledger-success"
},
"rollback": "stop-remove-candidate-prove-absent-quarantine-new-root-never-start-legacy"
}
@@ -1,123 +0,0 @@
{
"schemaVersion": "nodedc.gitea.incident-salvage.v3",
"action": "clean-state-salvage",
"component": "gitea",
"incidentId": "gitea-20260814",
"installRoot": "/volume1/docker/nodedc-gitea",
"compose": {
"file": "docker-compose.gitea.yml",
"project": "nodedc-gitea",
"service": "gitea",
"sha256": "2f031d5bfff4f42c73cabd8c94487ec3e4f1e1b0a96d3b7eec958904f735908a"
},
"runtime": {
"image": "docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c",
"imageId": "sha256:272085a806e6d182352cdb011c0ebab1d2efc7ec45247de84de5659c7bc5c4c6",
"repoDigest": "docker.gitea.com/gitea@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c",
"platform": "linux/amd64",
"pullPolicy": "never",
"entrypoint": "/usr/local/bin/gitea",
"runAs": "1000:1000",
"transport": "unix:/run/gitea/gitea.sock",
"networkMode": "none",
"ssh": "disabled-no-published-port",
"lfs": "disabled-pending-reachable-pointer-physical-sha-verifier",
"database": "new-sqlite-1.27.2-only",
"logging": "bounded-json-file-10m-x3",
"stopGracePeriod": "30s",
"candidateRestartPolicy": "no",
"acceptedRestartPolicy": "unless-stopped"
},
"decision": {
"schema": "nodedc.gitea.incident-decision/v2",
"manifestFile": "deployment/gitea-incident-salvage/confirmed-decision.json",
"manifestSha256": "dc9528462624158eb44218d37cc7054d551ca2d7ded562592982aa3f34c9fc2a",
"usersFile": "deployment/gitea-incident-salvage/users.decisions.csv",
"usersSha256": "e3b82f1073a86eea9e567edff062dd1689d21ec0edcf3ed92e844da9351ee8b6",
"repositoriesFile": "deployment/gitea-incident-salvage/repositories.decisions.csv",
"repositoriesSha256": "76b4bae2ab5cec490330c19bfc5ae9429abf7636705ae028c1c64fd54a6a0493",
"users": {
"active": 2,
"locked": 8,
"delete": 962
},
"repositories": {
"keep": 45,
"delete": 2013,
"dctouchPrivate": 32,
"silverPublic": 13
}
},
"disposition": {
"schema": "nodedc.gitea.incident-disposition.v1",
"file": "deployment/gitea-incident-salvage/confirmed-disposition-v1.json",
"sha256": "0a066724bcf6e4933133db6cab6cc273393e3c262dd00dda0bbf9ceebd84f78c"
},
"snapshot": {
"root": "/volume1/.nodedc-security-snapshots/docker-gitea-incident-20260814",
"uuid": "f5a3fe3a-93ea-bb4d-847f-6221a6bcbc9f",
"readOnlyRequired": true,
"database": "gitea/gitea/gitea.db",
"databaseBytes": 182681600,
"databaseSha256": "8db9e74a5641662a808d8252c5d6c9de43fe9efd8687634bfbff2d4361a13052",
"repositoriesRoot": "gitea/git/repositories"
},
"trust": {
"legacyRootMounted": false,
"legacyDatabaseImported": false,
"legacyConfigImported": false,
"legacyCredentialsImported": false,
"artifactSecrets": "forbidden",
"runtimeSecrets": "runner-generated",
"repositorySelection": "exact-v2-rows-only",
"repositoryCopy": "same-filesystem-per-file-reflink-object-and-validated-ref-material-only",
"forbiddenRepositoryMaterial": [
"hooks",
"config",
"alternates",
"http-alternates",
"shallow",
"replace",
"grafts",
"worktrees",
"commondir",
"lfs"
],
"unsupportedDatabaseState": "closure-disposition-bound-plan-report-review-and-verifiers-pending"
},
"identity": {
"preserveNumericUserIds": false,
"preserveNumericRepositoryIds": false,
"oldToNewIdMapping": "/volume1/docker/nodedc-gitea/audit/identity-map.json",
"emails": "new-local-noreply-only",
"passwordHashes": "never-imported",
"activeBootstrapCredentials": "root-only-runner-state-require-change",
"lockedCredentials": "fresh-random-discarded-and-login-prohibited",
"twoFactorAuthentication": "not-configured-by-transition"
},
"externalPrerequisites": {
"legacyContainer": "exact-inspect-pin-required-stopped-restart-no",
"publicProxy": "reviewed-nginx-uds-bridge-and-dsm-loopback-upstream",
"firewall": "legacy-isolation-retained-and-loopback-3000-ready",
"candidatePublicationGate": "socket-parent-uid1000-gid1023-mode0700",
"publishAction": "runner-chmod-socket-parent-0750-after-internal-acceptance",
"mustPassBeforeApply": true
},
"acceptance": {
"users": "exact-10-row-by-row",
"repositories": "exact-45-row-by-row-and-visibility",
"credentialsSessionsKeysWebhooksActions": "zero",
"git": "fsck-all-and-public-smart-http-smoke",
"registration": "closed",
"ssh": "disabled",
"network": "none-no-ports",
"publicHttps": "required-before-ledger-success"
},
"rollback": "stop-remove-candidate-prove-absent-quarantine-new-root-never-start-legacy",
"closureDisposition": {
"file": "deployment/gitea-incident-salvage/confirmed-closure-disposition-v1.json",
"predecessorArtifactSha256": "d6870b5583a2f329eadb4e6cda65fdf4d271532df5ffbf8bfb1403968a434672",
"schema": "nodedc.gitea.incident-closure-disposition.v1",
"sha256": "7ed66d9848268431a703fe24b22c41afbaa7c5ff48949604d6fc448d93e0d243"
}
}
@@ -1 +0,0 @@
{"activation":{"allowedOperation":"canonical-plan-only","applyFrozen":true,"freezeBoundary":"before-candidate-root-creation"},"authority":{"policyScope":"access-collaboration-issue-pr-attachment-release-label-project-unit-package-action-closure","source":"owner-instruction-in-current-incident-thread","state":"confirmed-policy-evidence-review-pending"},"closureReport":{"expectedBytes":null,"expectedSha256":null,"reviewState":"canonical-plan-output-unreviewed","schema":"nodedc.gitea.salvage-closure-inventory/v1"},"incidentId":"gitea-20260814","policies":{"accessCollaboration":{"accessCache":"DROP_RESET_RECOMPUTE","actorEvidence":"old-user-id-mode-and-kept-deleted-class-only","collaboration":"RECREATE_ONLY_KEPT_ACTORS_AFTER_REVIEWED_OLD_TO_NEW_ID_MAP","deletedActors":962,"keptActors":10,"legacyRowsImported":false,"sensitiveUserPayloadExported":false},"attachments":{"databaseManifest":"ID_UUID_RELATIONS_DECLARED_SIZE_ONLY","filenameOrContentExported":false,"legacyRowsImported":false,"physicalDisposition":"VERIFY_BYTES_THEN_SANITIZED_IMMUTABLE_ARCHIVE_ONLY","physicalPresenceClaimed":false},"issuesPullRequestsMetadata":{"archive":"SANITIZED_IMMUTABLE_ARCHIVE_ONLY","legacyRowsImported":false,"payloadExportedInPlan":false,"planEvidence":"PER_REPOSITORY_COUNTS_ACTOR_CLASSES_TEXT_BYTE_LENGTHS_ONLY","subrelationClosure":{"commentHistoryMerger":"SCHEMA_BOUND_EXACT_RELATION_COUNTS_AND_CLASSES","externalAuthors":"PRESENCE_AND_NAME_BYTE_LENGTHS_ONLY_NO_LOCAL_USER_MAPPING","legacyRowsImported":false,"teamRelations":"EXACT_ROW_TEAM_ORG_IDS_SEALED_HOLD_AND_BLOCK_IF_PRESENT"},"tables":["comment","issue","issue_assignees","issue_content_history","issue_dependency","issue_label","issue_user","issue_watch","notification","project","project_board","project_issue","pull_auto_merge","pull_request","reaction","review","review_state","stopwatch","tracked_time"]},"packagesActions":{"actionsTarget":"DISABLED","legacyPayloadSecretTokenLogImported":false,"packageTarget":"DISABLED","physicalDisposition":"DROP_ONLY_AFTER_SCHEMA_RELATION_AND_PHYSICAL_CLOSURE_VERIFIER","planEvidence":"RELATIONSHIP_COUNTS_AND_SAFE_DECLARED_SIZES_ONLY"},"releasesLabelsProjects":{"archive":"SANITIZED_IMMUTABLE_ARCHIVE_ONLY","legacyRowsImported":false,"payloadExportedInPlan":false},"repositoryState":{"cachedAccessCountersStarsWatches":"DROP_RESET_RECOMPUTE","legacyHooksWebhooksKeysTokensSessionsCredentialsSecrets":"IMPORT_ZERO","topics":"VERIFIED_SEMANTIC_EMPTY_REBUILD_ZERO"},"units":{"actionsType10":"DISABLED_ZERO_TARGET_ROWS","disabledTypes":[6,7,9,10],"enabledCleanTypes":[1,2,3,4,5,8],"legacyConfigImported":false,"legacyRowsImported":false,"packagesType9":"DISABLED_ZERO_TARGET_ROWS"}},"predecessor":{"artifactSha256":"d6870b5583a2f329eadb4e6cda65fdf4d271532df5ffbf8bfb1403968a434672","dispositionFile":"deployment/gitea-incident-salvage/confirmed-disposition-v1.json","dispositionSha256":"0a066724bcf6e4933133db6cab6cc273393e3c262dd00dda0bbf9ceebd84f78c"},"remainingBlockers":["attachment-physical-verifier-pending","candidate-root-activation-hard-frozen","closure-report-review-pin-pending","collaboration-kept-user-mapping-verifier-pending","forensic-ref-archive-verifier-pending","issue-pr-metadata-sanitized-archive-verifier-pending","lfs-reachable-pointer-physical-verifier-pending","package-action-physical-closure-verifier-pending","reference-manifest-fsck-reachability-verifier-pending","repository-object-reconstruction-verifier-pending","target-unit-policy-acceptance-pending","unsupported-schema-catalog-verifier-pending"],"schemaVersion":"nodedc.gitea.incident-closure-disposition.v1","scope":{"deletedRepositories":2013,"deletedUsers":962,"keptRepositories":45,"keptUsers":10},"sourceEvidence":{"databaseSha256":"8db9e74a5641662a808d8252c5d6c9de43fe9efd8687634bfbff2d4361a13052","identityDecisionManifestSha256":"dc9528462624158eb44218d37cc7054d551ca2d7ded562592982aa3f34c9fc2a","referenceManifestSha256":"9cddaf0e4d4cf22dd264a6ae589ccc50d29e07f85c55e9d34b14627cecb8a311","semanticTopicsSha256":"df6e3612186234bfcf3c172ef4e0fff933baaa691a510f9780ebf9e21c8d4d05","snapshotUuid":"f5a3fe3a-93ea-bb4d-847f-6221a6bcbc9f","unsupportedRepositoryReportSha256":"4b2cecf88c62fc5c4a43419885e88a01c9f9aac03133afb19dae0a7caef106ac","unsupportedSchemaCatalogSha256":"b5e3b6776926c4f1627fafd882362ed0ef986bfc86fc6ac6507a43976531b6db"}}
File diff suppressed because one or more lines are too long
@@ -1,62 +0,0 @@
name: nodedc-gitea
services:
gitea:
image: docker.gitea.com/gitea:1.27.2-rootless@sha256:7de5f49ada687b8c8d2938f547cdb7634839764ba51f297457bae35cee3abd2c
platform: linux/amd64
pull_policy: never
network_mode: none
user: "1000:1000"
entrypoint:
- /usr/local/bin/gitea
command:
- web
- --config
- /etc/gitea/app.ini
restart: "no"
stop_grace_period: 30s
init: true
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
pids_limit: 512
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
environment:
USER: git
HOME: /data/gitea
GITEA_WORK_DIR: /data/gitea
GITEA_CUSTOM: /data/gitea
volumes:
- type: bind
source: /volume1/docker/nodedc-gitea/data
target: /data
bind:
create_host_path: false
- type: bind
source: /volume1/docker/nodedc-gitea/config
target: /etc/gitea
read_only: true
bind:
create_host_path: false
- type: bind
source: /volume1/docker/nodedc-gitea/socket
target: /run/gitea
bind:
create_host_path: false
secrets:
- gitea_secret_key
- gitea_internal_token
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=256m
secrets:
gitea_secret_key:
file: /volume1/docker/nodedc-gitea/secrets/secret-key
gitea_internal_token:
file: /volume1/docker/nodedc-gitea/secrets/internal-token
@@ -1,42 +0,0 @@
{
"schemaVersion": "nodedc.gitea.fresh-install.v1",
"action": "fresh-install",
"component": "gitea",
"installRoot": "/volume1/docker/nodedc-gitea",
"compose": {
"file": "docker-compose.gitea.yml",
"project": "nodedc-gitea",
"service": "gitea",
"sha256": "25868a40996c405543b4627d06499b68f43556e607d839e969a400b0bc0ddadb"
},
"runtime": {
"image": "docker.gitea.com/gitea:1.27.1-rootless@sha256:89dc3c214b3992e5bb01e05ad21139d7a8b302d3ea3d8942d3f7e904e92af148",
"platform": "linux/amd64",
"pullPolicy": "never",
"minimumComposeVersion": "2.20.1",
"transport": "unix:/run/gitea/gitea.sock",
"socketBind": "/volume1/docker/nodedc-gitea/socket:/run/gitea",
"ssh": "disabled-no-published-port",
"database": "fresh-sqlite-only",
"lfs": "disabled-pending-reviewed-restore-transition",
"networkMode": "none",
"logging": "bounded-json-file-10m-x3",
"stopGracePeriod": "30s"
},
"trust": {
"artifactSecrets": "forbidden",
"runtimeSecrets": "runner-managed-file-mounts",
"legacyRootAccess": "forbidden",
"legacyDatabaseImport": "forbidden",
"legacyRepositoryImport": "forbidden"
},
"reverseProxyPrerequisite": {
"managedOutsideArtifact": true,
"requiredDsmUpstream": "127.0.0.1:3000",
"requiredNginxBridge": "/usr/local/etc/nginx/conf.d/http.nodedc-gitea-uds.conf",
"requiredNginxBridgeSha256": "164f37a12a4f91e656cf20bd5b109978d16d723bdfde236653722aaf820780c9",
"requiredUnixUpstream": "/volume1/docker/nodedc-gitea/socket/gitea.sock",
"mustBeCompletedBeforeApply": true
},
"rollback": "stop-candidate-preserve-fresh-runtime-state-and-restore-source"
}
@@ -1,128 +0,0 @@
name: nodedc-gitea
services:
gitea:
image: docker.gitea.com/gitea:1.27.1-rootless@sha256:89dc3c214b3992e5bb01e05ad21139d7a8b302d3ea3d8942d3f7e904e92af148
platform: linux/amd64
pull_policy: never
network_mode: none
user: "1000:1000"
restart: unless-stopped
stop_grace_period: 30s
init: true
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
pids_limit: 512
logging:
driver: json-file
options:
max-size: "10m"
max-file: "3"
environment:
GITEA_WORK_DIR: /var/lib/gitea
GITEA__database__DB_TYPE: sqlite3
GITEA__database__PATH: /var/lib/gitea/data/gitea.db
GITEA__server__DOMAIN: git.dcserve.ru
GITEA__server__ROOT_URL: https://git.dcserve.ru/
GITEA__server__PROTOCOL: http+unix
GITEA__server__HTTP_ADDR: /run/gitea/gitea.sock
GITEA__server__UNIX_SOCKET_PERMISSION: "0666"
GITEA__server__LOCAL_ROOT_URL: http://unix/
GITEA__server__DISABLE_SSH: "true"
GITEA__server__START_SSH_SERVER: "false"
GITEA__server__SSH_CREATE_AUTHORIZED_KEYS_FILE: "false"
GITEA__server__LFS_START_SERVER: "false"
GITEA__server__LFS_ALLOW_PURE_SSH: "false"
GITEA__server__OFFLINE_MODE: "true"
GITEA__server__LANDING_PAGE: login
GITEA__security__INSTALL_LOCK: "true"
GITEA__security__SECRET_KEY_URI: file:/run/secrets/gitea_secret_key
GITEA__security__INTERNAL_TOKEN_URI: file:/run/secrets/gitea_internal_token
GITEA__security__REVERSE_PROXY_LIMIT: "1"
GITEA__security__REVERSE_PROXY_TRUSTED_PROXIES: 127.0.0.0/8,::1/128
GITEA__security__DISABLE_GIT_HOOKS: "true"
GITEA__security__DISABLE_WEBHOOKS: "true"
GITEA__security__IMPORT_LOCAL_PATHS: "false"
GITEA__security__ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET: "true"
GITEA__security__PASSWORD_HASH_ALGO: argon2
GITEA__security__MIN_PASSWORD_LENGTH: "16"
GITEA__security__PASSWORD_COMPLEXITY: lower,upper,digit,spec
GITEA__security__TWO_FACTOR_AUTH: enforced
GITEA__security__DISABLE_QUERY_AUTH_TOKEN: "true"
GITEA__security__ALLOWED_HOST_LIST: loopback
GITEA__service__DISABLE_REGISTRATION: "true"
GITEA__service__REQUIRE_SIGNIN_VIEW: "true"
GITEA__service__SHOW_REGISTRATION_BUTTON: "false"
GITEA__service__DEFAULT_KEEP_EMAIL_PRIVATE: "true"
GITEA__service__DEFAULT_ALLOW_CREATE_ORGANIZATION: "false"
GITEA__service__DEFAULT_USER_IS_RESTRICTED: "true"
GITEA__service__DEFAULT_USER_VISIBILITY: private
GITEA__service__ALLOWED_USER_VISIBILITY_MODES: private
GITEA__service__DEFAULT_ORG_VISIBILITY: private
GITEA__service__ENABLE_REVERSE_PROXY_AUTHENTICATION: "false"
GITEA__service__ENABLE_REVERSE_PROXY_AUTHENTICATION_API: "false"
GITEA__service__ENABLE_REVERSE_PROXY_AUTO_REGISTRATION: "false"
GITEA__service__ENABLE_NOTIFY_MAIL: "false"
GITEA__service__ENABLE_BASIC_AUTHENTICATION: "false"
GITEA__admin__DISABLE_REGULAR_ORG_CREATION: "true"
GITEA__admin__USER_DISABLED_FEATURES: deletion,manage_ssh_keys,manage_gpg_keys,change_username
GITEA__repository__FORCE_PRIVATE: "true"
GITEA__repository__DEFAULT_PRIVATE: private
GITEA__repository__USER_MAX_CREATION_LIMIT: "0"
GITEA__repository__ORG_MAX_CREATION_LIMIT: "0"
GITEA__repository__ENABLE_PUSH_CREATE_USER: "false"
GITEA__repository__ENABLE_PUSH_CREATE_ORG: "false"
GITEA__repository__DISABLE_MIGRATIONS: "true"
GITEA__repository__ALLOW_ADOPTION_OF_UNADOPTED_REPOSITORIES: "false"
GITEA__repository__ALLOW_DELETION_OF_UNADOPTED_REPOSITORIES: "false"
GITEA__repository__DISABLE_HTTP_GIT: "false"
GITEA__repository.upload__ENABLED: "false"
GITEA__attachment__ENABLED: "false"
GITEA__actions__ENABLED: "false"
GITEA__packages__ENABLED: "false"
GITEA__oauth2__ENABLED: "false"
GITEA__oauth2_client__ENABLE_AUTO_REGISTRATION: "false"
GITEA__openid__ENABLE_OPENID_SIGNIN: "false"
GITEA__openid__ENABLE_OPENID_SIGNUP: "false"
GITEA__federation__ENABLED: "false"
GITEA__mailer__ENABLED: "false"
GITEA__session__COOKIE_SECURE: "true"
GITEA__session__SAME_SITE: strict
GITEA__api__ENABLE_SWAGGER: "false"
GITEA__migrations__ALLOW_LOCALNETWORKS: "false"
GITEA__migrations__SKIP_TLS_VERIFY: "false"
GITEA__cors__ENABLED: "false"
GITEA__metrics__ENABLED: "false"
GITEA__cron.update_checker__ENABLED: "false"
GITEA__log__MODE: console
GITEA__log__LEVEL: Info
volumes:
- type: bind
source: /volume1/docker/nodedc-gitea/data
target: /var/lib/gitea
bind:
create_host_path: false
- type: bind
source: /volume1/docker/nodedc-gitea/config
target: /etc/gitea
bind:
create_host_path: false
- type: bind
source: /volume1/docker/nodedc-gitea/socket
target: /run/gitea
bind:
create_host_path: false
secrets:
- gitea_secret_key
- gitea_internal_token
tmpfs:
- /tmp:rw,noexec,nosuid,nodev,size=256m
secrets:
gitea_secret_key:
file: /volume1/docker/nodedc-gitea/secrets/secret-key
gitea_internal_token:
file: /volume1/docker/nodedc-gitea/secrets/internal-token
File diff suppressed because it is too large Load Diff
@@ -1,202 +0,0 @@
"""Additive B2 foundation: exact scope and fail-closed preservation proofs."""
import copy
import importlib.machinery
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
loader=importlib.machinery.SourceFileLoader('b2_runner_test',str(Path(__file__).with_name('nodedc-deploy')))
spec=importlib.util.spec_from_loader(loader.name,loader);R=importlib.util.module_from_spec(spec);loader.exec_module(R)
def baseline():
return {'services':{'device-control-core':{'image':'same','environment':{'EXISTING':'preserved'},
'volumes':[{'type':'bind','source':'/private/current','target':'/run/current','read_only':True}],
'ports':[]},'device-postgres':{'image':'postgres:existing','volumes':['unchanged']}}}
def candidate():
v=baseline();c=v['services']['device-control-core']
c['environment']['DEVICE_B2_SECRET_ROOT']=R.DEVICE_B2_DESTINATION
c['volumes'].append({'type':'bind','source':str(R.DEVICE_B2_SECRET_ROOT),'target':R.DEVICE_B2_DESTINATION,
'read_only':False,'bind':{'create_host_path':False}})
return v
FIXTURE = Path(__file__).with_name('fixtures') / 'device-b2-foundation-compose220'
def compose_fixture():
return tuple(json.loads((FIXTURE / (name + '.json')).read_text()) for name in ('base', 'candidate'))
class Foundation(unittest.TestCase):
def test_source_yaml_and_new_identity_remain_exact(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / 'deployment').mkdir()
(root / R.DEVICE_B2_DESCRIPTOR).write_text(json.dumps(R.device_b2_descriptor()))
yaml = root / R.DEVICE_B2_OVERRIDE
yaml.write_text(R.DEVICE_B2_YAML)
# Isolate the YAML/identity guard; no database or SQL execution.
with mock.patch.object(R, 'sha256_file', return_value=R.DEVICE_B2_SQL_SHA):
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
for old_id in ('device-b2-foundation-v1-20260930-001', 'device-b2-foundation-v1-20260930-002'):
with self.assertRaises(R.DeployError):
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, old_id)
for replacement in ('true', 'null', '0'):
yaml.write_text(R.DEVICE_B2_YAML.replace('create_host_path: false', 'create_host_path: ' + replacement))
with self.subTest(replacement=replacement), self.assertRaises(R.DeployError):
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
yaml.write_text(R.DEVICE_B2_YAML.replace(' create_host_path: false\n', ''))
with self.assertRaises(R.DeployError):
R.validate_device_b2_payload(root, R.DEVICE_B2_ENTRIES, R.DEVICE_B2_ID)
def test_real_compose_2201_output_preserves_raw_inputs_and_digest(self):
base, actual = compose_fixture()
saved = copy.deepcopy((base, actual))
mount = next(v for v in actual['services']['device-control-core']['volumes']
if v['target'] == R.DEVICE_B2_DESTINATION)
self.assertEqual(mount['bind'], {})
self.assertNotIn('read_only', mount)
self.assertEqual(R.device_b2_config_proof(base, actual), R.device_release_drift_digest(actual))
self.assertEqual((base, actual), saved)
self.assertEqual((FIXTURE / 'override.yml').read_text(), R.DEVICE_B2_YAML)
def test_real_compose_new_mount_accepts_only_false_or_omitted_booleans(self):
base, actual = compose_fixture()
for read_only in ('omitted', False):
for create in ('omitted', False):
v = copy.deepcopy(actual)
mount = next(m for m in v['services']['device-control-core']['volumes']
if m['target'] == R.DEVICE_B2_DESTINATION)
if read_only != 'omitted': mount['read_only'] = read_only
if create != 'omitted': mount['bind']['create_host_path'] = create
with self.subTest(read_only=read_only, create=create):
R.device_b2_config_proof(base, v)
for key in ('read_only', 'create_host_path'):
for value in (True, None, 0, 1, 0.0, 'false', {}, []):
v = copy.deepcopy(actual)
mount = next(m for m in v['services']['device-control-core']['volumes']
if m['target'] == R.DEVICE_B2_DESTINATION)
target = mount if key == 'read_only' else mount['bind']
target[key] = value
with self.subTest(key=key, value=value), self.assertRaises(R.DeployError):
R.device_b2_config_proof(base, v)
def test_real_compose_rejects_other_mount_options_and_unrelated_changes(self):
base, actual = compose_fixture()
for mutation in ('source', 'type', 'bind-null', 'bind-absent', 'propagation',
'existing-bind', 'existing-readonly', 'duplicate', 'env', 'network', 'database'):
v = copy.deepcopy(actual)
core = v['services']['device-control-core']
mount = next(m for m in core['volumes'] if m['target'] == R.DEVICE_B2_DESTINATION)
existing = next(m for m in core['volumes'] if m['target'] != R.DEVICE_B2_DESTINATION)
if mutation == 'source': mount['source'] = '/other'
if mutation == 'type': mount['type'] = 'volume'
if mutation == 'bind-null': mount['bind'] = None
if mutation == 'bind-absent': mount.pop('bind')
if mutation == 'propagation': mount['bind']['propagation'] = 'rshared'
if mutation == 'existing-bind': existing['bind']['create_host_path'] = False
if mutation == 'existing-readonly': existing['read_only'] = False
if mutation == 'duplicate': core['volumes'].append(copy.deepcopy(mount))
if mutation == 'env': core['environment']['EXISTING'] = 'changed'
if mutation == 'network': core['networks']['private']['priority'] = 0
if mutation == 'database': v['services']['device-postgres']['image'] = 'changed'
with self.subTest(mutation=mutation), self.assertRaises(R.DeployError):
R.device_b2_config_proof(base, v)
def test_scope_has_only_core_and_no_build(self):
self.assertEqual(R.component_services('device-b2-foundation',R.DEVICE_B2_ENTRIES),('device-control-core',))
self.assertFalse(R.component_builds('device-b2-foundation',R.DEVICE_B2_ENTRIES))
self.assertTrue(R.component_compose_no_deps('device-b2-foundation',R.DEVICE_B2_ENTRIES))
for entries in [[],R.DEVICE_B2_ENTRIES[:-1],(*R.DEVICE_B2_ENTRIES,'services/device-postgres')]:
with self.assertRaises(R.DeployError):R.component_services('device-b2-foundation',entries)
for p in ['.env','secrets/key','deployment/other.sql','services/device-control-core/src/server.mjs','../escape','hooks.sh']:
with self.assertRaises(R.DeployError):R.allowed_payload_path('device-b2-foundation',p)
def test_config_delta_keeps_ports_database_and_other_environment(self):
R.device_b2_config_proof(baseline(),candidate())
for mutation in ['ports','database','environment','mount','readonly']:
v=candidate();c=v['services']['device-control-core']
if mutation=='ports':c['ports']=[{'target':42,'published':'42'}]
if mutation=='database':v['services']['device-postgres']['image']='different'
if mutation=='environment':c['environment']['EXISTING']='changed'
if mutation=='mount':c['volumes'][0]['read_only']=False
if mutation=='readonly':c['volumes'][-1]['read_only']=True
with self.subTest(mutation=mutation),self.assertRaises(R.DeployError):R.device_b2_config_proof(baseline(),v)
def test_runtime_strip_accepts_only_private_mount_and_env(self):
field={'HostConfig':{'Mounts':[{'Type':'bind','Source':str(R.DEVICE_B2_SECRET_ROOT),
'Target':R.DEVICE_B2_DESTINATION,'ReadOnly':False}]},
'Config':{'Env':['OTHER=one','DEVICE_B2_SECRET_ROOT='+R.DEVICE_B2_DESTINATION]},
'Mounts':[{'Type':'bind','Source':str(R.DEVICE_B2_SECRET_ROOT),'Destination':R.DEVICE_B2_DESTINATION,
'RW':True,'Propagation':'rprivate'}],'networks':['same']}
result=R.device_b2_strip_runtime(field)
self.assertEqual(result,{'HostConfig':{'Mounts':[]},'Config':{'Env':['OTHER=one']},'Mounts':[],'networks':['same']})
for part,key,value in [('Mounts','RW',False),('Mounts','Propagation','rshared'),('HostConfig','Source','/elsewhere')]:
wrong=copy.deepcopy(field)
target=wrong[part][0] if part=='Mounts' else wrong[part]['Mounts'][0]
target[key]=value
with self.assertRaises(R.DeployError):R.device_b2_strip_runtime(wrong)
def test_recreate_never_pulls_builds_or_selects_dependencies(self):
with mock.patch.object(R,'device_b2_base',return_value=['docker','compose']),mock.patch.object(R.subprocess,'run') as run:
R.device_b2_recreate(True)
cmd=run.call_args.args[0]
self.assertEqual(cmd[-1],'device-control-core')
self.assertIn('--no-build',cmd);self.assertIn('--no-deps',cmd)
self.assertEqual(cmd[cmd.index('--pull')+1],'never')
self.assertNotIn('device-postgres',cmd)
def test_schema_collision_and_unvalidated_constraints_fail(self):
with self.assertRaises(R.DeployError):R.validate_device_b2_schema([])
rows=copy.deepcopy(R.DEVICE_B2_EXPECTED_SCHEMA)
R.validate_device_b2_schema(rows)
rows[0]['validated']=False
with self.assertRaises(R.DeployError):R.validate_device_b2_schema(rows)
def test_failed_rollback_prevents_activation(self):
with mock.patch.object(R,'load_state',return_value=[{'component':'device-b2-foundation','started_apply':True,'rollback_status':'failed:DeployError'}]):
with self.assertRaises(R.DeployError):R.device_b2_failed_barrier()
def test_schema_failure_does_not_mark_or_restart_runtime(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); (root/'deployment').mkdir()
(root/R.DEVICE_B2_SQL).write_text('synthetic migration')
mark=mock.Mock()
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root),mock.patch.object(R,'device_b2_private_directory'),\
mock.patch.object(R,'device_b2_database',side_effect=R.DeployError('schema failed')),\
mock.patch.object(R,'device_b2_recreate') as recreate:
with self.assertRaises(R.DeployError):R.apply_device_b2({},root,mark)
mark.assert_not_called();recreate.assert_not_called()
def test_normal_releases_check_installed_schema_mount_and_vault(self):
with mock.patch.object(R,'device_b2_compose_files',return_value=('accepted-foundation',)),\
mock.patch.object(R,'device_b2_private_directory') as directory,\
mock.patch.object(R,'device_b2_schema',return_value=R.DEVICE_B2_EXPECTED_SCHEMA),\
mock.patch.object(R,'device_release_drift_sample',return_value={'device-control-core':{'fields':{}}}),\
mock.patch.object(R,'device_b2_strip_runtime',side_effect=R.DeployError('lost mount')):
with self.assertRaises(R.DeployError):R.validate_installed_device_b2()
directory.assert_called_once_with()
def test_marker_without_ledger_cannot_activate_compose(self):
with tempfile.TemporaryDirectory() as tmp,mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)),mock.patch.object(R,'load_state',return_value=[]):
(Path(tmp)/R.DEVICE_B2_OVERRIDE).write_text(R.DEVICE_B2_YAML)
with self.assertRaises(R.DeployError):R.device_b2_compose_files(())
def test_rollback_retains_nonempty_private_storage(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);vault=root/'vault';vault.mkdir();(vault/'credential').write_text('synthetic')
with mock.patch.object(R,'DEVICE_B2_SECRET_ROOT',vault),mock.patch.object(R,'restore_platform_overlay'),\
mock.patch.object(R,'device_b2_schema',return_value=[]),mock.patch.object(R,'device_b2_private_directory'),\
mock.patch.object(R,'device_b2_recreate'),mock.patch.object(R,'accept_device_b2') as accept:
with self.assertRaises(OSError):R.rollback_device_b2(root,root,(),'',{},True)
accept.assert_not_called()
self.assertEqual((vault/'credential').read_text(),'synthetic')
if __name__=='__main__':unittest.main()
@@ -1,276 +0,0 @@
"""Readiness convergence and metadata-only reconciliation; no Docker required."""
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import hashlib
import importlib.util
import io
import json
from pathlib import Path
from types import SimpleNamespace
import tempfile
import unittest
from unittest import mock
from test_device_b2_foundation import R
spec = importlib.util.spec_from_file_location('b2_reconciliation_builder', Path(__file__).with_name('build_device_b2_reconciliation.py'))
B = importlib.util.module_from_spec(spec)
spec.loader.exec_module(B)
def baseline_fields():
return {'HostConfig': {'Mounts': []}, 'Config': {'Env': ['PRESERVED=synthetic']}, 'Mounts': [], 'networks': ['private']}
def snapshot(fields):
return {service: {'service': service, 'containerId': service + '-old', 'imageId': 'same-image',
'health': 'healthy', 'running': True, 'status': 'running', 'restartCount': 0,
'runtimeConfigSha256': R.device_release_drift_digest(fields)}
for service in R.DEVICE_RELEASE_INVENTORY}
class Readiness(unittest.TestCase):
def accept_with_startup(self, rollback, unhealthy=False, drift=None):
fields = baseline_fields()
current_fields = copy.deepcopy(fields)
if not rollback:
current_fields['Config']['Env'].append('DEVICE_B2_SECRET_ROOT=' + R.DEVICE_B2_DESTINATION)
current_fields['HostConfig']['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
'Target': R.DEVICE_B2_DESTINATION, 'ReadOnly': False})
current_fields['Mounts'].append({'Type': 'bind', 'Source': str(R.DEVICE_B2_SECRET_ROOT),
'Destination': R.DEVICE_B2_DESTINATION, 'RW': True, 'Propagation': 'rprivate'})
before = {'runtime': snapshot(fields), 'compose': {}, 'otherComposeServices': {}, 'installedFiles': {}}
state = {'health': 'starting', 'polls': 0, 'snapshots': 0}
def inspect(command, **kwargs):
self.assertEqual(command[1], 'inspect')
service = command[-1]
if service == 'device-control-core':
state['polls'] += 1
state['health'] = 'unhealthy' if unhealthy else ('starting' if state['polls'] == 1 else 'healthy')
return SimpleNamespace(stdout=state['health'], stderr='', returncode=0)
return SimpleNamespace(stdout='healthy', stderr='', returncode=0)
def samples():
state['snapshots'] += 1
result = {service: {'runtime': copy.deepcopy(row), 'fields': copy.deepcopy(fields)}
for service, row in before['runtime'].items()}
core = result['device-control-core']
core['runtime']['containerId'] = 'new-generation'
core['runtime']['health'] = state['health']
core['fields'] = copy.deepcopy(current_fields)
if drift == 'image': core['runtime']['imageId'] = 'changed-image'
if drift == 'network': core['fields']['networks'] = ['other']
if drift == 'preserved': result['device-postgres']['runtime']['containerId'] = 'unexpected-recreate'
return result
with ExitStack() as stack:
stack.enter_context(mock.patch.object(R, 'compose_service_container_id', side_effect=lambda c, s: s))
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=inspect))
stack.enter_context(mock.patch.object(R.time, 'sleep'))
stack.enter_context(mock.patch.object(R, 'healthcheck_url'))
stack.enter_context(mock.patch.object(R, 'device_release_drift_sample', side_effect=samples))
stack.enter_context(mock.patch.object(R, 'device_release_other_compose_services', return_value={}))
stack.enter_context(mock.patch.object(R, 'collect_exact_files', return_value={}))
stack.enter_context(mock.patch.object(R, 'device_b2_private_directory'))
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=R.DEVICE_B2_EXPECTED_SCHEMA))
stack.enter_context(mock.patch.object(R, 'read_strict_json', return_value={'schemaSha256': R.device_release_drift_digest(R.DEVICE_B2_EXPECTED_SCHEMA)}))
stack.enter_context(redirect_stdout(io.StringIO()))
if unhealthy or drift:
with self.assertRaises(R.DeployError): R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
else:
R.accept_device_b2(before, Path('/synthetic'), rollback=rollback)
return state
def test_apply_and_rollback_wait_for_healthy_before_strict_snapshot(self):
for rollback in (False, True):
with self.subTest(rollback=rollback):
state = self.accept_with_startup(rollback)
self.assertEqual(state['polls'], 2)
self.assertGreater(state['snapshots'], 0)
def test_persistent_unhealthy_does_not_reach_snapshot_or_accept(self):
for rollback in (False, True):
state = self.accept_with_startup(rollback, unhealthy=True)
self.assertEqual(state['polls'], 60)
self.assertEqual(state['snapshots'], 0)
def test_readiness_never_weakens_image_network_or_preserved_service_guards(self):
for rollback in (False, True):
for drift in ('image', 'network', 'preserved'):
with self.subTest(rollback=rollback, drift=drift):
self.accept_with_startup(rollback, drift=drift)
class Reconciliation(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.live = self.root / 'live'
self.live.mkdir()
self.archive = self.root / 'reconciliation.tgz'
B.build(self.archive)
self.manifest, self.entries, self.payload = R.load_artifact(self.archive, self.root / 'unpack')
def test_real_archive_is_deterministic_data_only_and_has_no_runtime_action(self):
other = self.root / 'second.tgz'
B.build(other)
self.assertEqual(self.archive.read_bytes(), other.read_bytes())
with self.assertRaises(FileExistsError): B.build(other)
self.assertEqual(self.entries, [R.DEVICE_B2_RECON_ENTRY])
self.assertEqual(R.component_services(self.manifest['component'], self.entries), ())
self.assertFalse(R.component_builds(self.manifest['component'], self.entries))
with mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('runtime command forbidden')):
R.run_component_runtime(self.manifest['component'], self.entries, ())
for p in ('secrets/key', '.env', R.DEVICE_B2_SQL, R.DEVICE_B2_OVERRIDE, 'hooks.sh'):
with self.subTest(path=p), self.assertRaises(R.DeployError):
R.allowed_payload_path(self.manifest['component'], p)
for entries in ([], self.entries + ['services/device-control-core']):
with self.assertRaises(R.DeployError): R.component_services(self.manifest['component'], entries)
def test_descriptor_cannot_select_other_incident_or_commands(self):
descriptor = self.payload / R.DEVICE_B2_RECON_ENTRY
for key, value in [('failedReleaseId', 'another'), ('backupId', '../escape'), ('mode', 'restart'), ('command', 'sh')]:
d = R.device_b2_reconciliation_descriptor()
d[key] = value
descriptor.write_text(json.dumps(d))
with self.subTest(key=key), self.assertRaises(R.DeployError):
R.validate_device_b2_reconciliation_payload(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
def proof_context(self, stack, **overrides):
applied = [{'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA}]
failures = [R.device_b2_002_failed_row()]
stack.enter_context(mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live))
stack.enter_context(mock.patch.object(R, 'DEVICE_B2_SECRET_ROOT', self.live / 'vault'))
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={'proof': 'pinned-backup'}))
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=overrides.get('schema', [])))
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda path: overrides.get('failed', failures) if path == R.FAILED_STATE_FILE else overrides.get('applied', applied)))
return stack.enter_context(mock.patch.object(R, 'accept_device_b2'))
def test_readonly_proof_rejects_remaining_files_vault_schema_and_other_incident(self):
for case in ('good', 'file', 'symlink', 'vault', 'schema', 'newer-release', 'another-failed', 'installed-foundation'):
with self.subTest(case=case), ExitStack() as stack:
changes = {}
target = None
if case in ('file', 'symlink'):
target = self.live / R.DEVICE_B2_OVERRIDE
if case == 'file': target.write_text('retained')
else: target.symlink_to(self.live / 'missing')
if case == 'vault':
target = self.live / 'vault'; target.mkdir()
if case == 'schema': changes['schema'] = R.DEVICE_B2_EXPECTED_SCHEMA
if case == 'newer-release': changes['applied'] = []
if case == 'installed-foundation': changes['applied'] = [{'component': 'device-b2-foundation'}]
if case == 'another-failed': changes['failed'] = [R.device_b2_002_failed_row(), {'component': 'device-b2-foundation', 'started_apply': True, 'id': 'another'}]
accept = self.proof_context(stack, **changes)
stack.enter_context(redirect_stdout(io.StringIO()))
if case == 'good':
R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
accept.assert_called_once()
self.assertTrue(accept.call_args.kwargs['rollback'])
else:
with self.assertRaises(R.DeployError): R.preflight_device_b2_reconciliation(self.payload, self.entries, R.DEVICE_B2_RECON_ID)
accept.assert_not_called()
if target:
if target.is_dir(): target.rmdir()
else: target.unlink()
def test_marker_alone_cannot_clear_failure_and_other_failed_rows_never_match(self):
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[]):
self.assertFalse(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
marker = self.live / R.DEVICE_B2_RECON_ENTRY
marker.parent.mkdir()
marker.write_text(json.dumps(R.device_b2_reconciliation_descriptor()))
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
wrong = R.device_b2_002_failed_row(); wrong['sha256'] = '0'*64
self.assertFalse(R.device_b2_002_reconciled(wrong))
def test_failed_foundation_blocks_ordinary_releases_even_without_overlay(self):
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'load_state', return_value=[R.device_b2_002_failed_row()]):
with self.assertRaises(R.DeployError): R.device_b2_compose_files(())
def test_incident_evidence_checks_exact_journal_archive_and_every_backup_file(self):
failed_dir = self.root/'incident-failed'; failed_dir.mkdir()
backups = self.root/'incident-backups'; backups.mkdir()
backup = backups/R.DEVICE_B2_002_BACKUP; backup.mkdir()
files = {'device-b2-before.json': b'{"runtime":{}}', 'device-b2-schema.json': b'{}',
'manifest.env': b'synthetic', 'files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
'existing-files.txt': b'', 'missing-files.txt': ('\n'.join(R.DEVICE_B2_ENTRIES)+'\n').encode(),
'source-before.tgz': b'synthetic-empty-source'}
for name, value in files.items(): (backup/name).write_bytes(value)
archive = failed_dir/R.device_b2_002_failed_row()['artifact']; archive.write_bytes(b'synthetic-archive')
hashes = {name: hashlib.sha256(value).hexdigest() for name, value in files.items()}
with ExitStack() as stack:
for name, value in [('FAILED_DIR', failed_dir), ('BACKUPS_DIR', backups),
('DEVICE_B2_002_SHA', hashlib.sha256(archive.read_bytes()).hexdigest()),
('DEVICE_B2_002_BACKUP_HASHES', hashes)]:
stack.enter_context(mock.patch.object(R, name, value))
failed = [R.device_b2_002_failed_row()]; applied = []
stack.enter_context(mock.patch.object(R, 'load_state', side_effect=lambda p: failed if p == R.FAILED_STATE_FILE else applied))
self.assertEqual(R.device_b2_002_evidence(), {'runtime': {}})
for name, value in files.items():
(backup/name).write_bytes(value+b'changed')
with self.subTest(file=name), self.assertRaises(R.DeployError): R.device_b2_002_evidence()
(backup/name).write_bytes(value)
archive.write_bytes(b'changed')
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
archive.write_bytes(b'synthetic-archive')
applied.append({'id': R.DEVICE_B2_002_ID})
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
applied.clear()
failed[0]['rollback_status'] = 'different'
with self.assertRaises(R.DeployError): R.device_b2_002_evidence()
def execute_metadata_apply(self, fail_after_marker=False):
for name in ('inbox', 'applied', 'failed', 'backups', 'state', 'tmp'): (self.root / name).mkdir()
with ExitStack() as stack:
for name, value in [('INBOX', self.root/'inbox'), ('APPLIED_DIR', self.root/'applied'),
('FAILED_DIR', self.root/'failed'), ('BACKUPS_DIR', self.root/'backups'),
('STATE_DIR', self.root/'state'), ('TMP_DIR', self.root/'tmp'),
('STATE_FILE', self.root/'state/applied.jsonl'), ('FAILED_STATE_FILE', self.root/'state/failed.jsonl'),
('LOCK_DIR', self.root/'lock'), ('DEVICE_PLANE_ROOT', self.live),
('DEVICE_B2_SECRET_ROOT', self.live/'vault')]:
stack.enter_context(mock.patch.object(R, name, value))
stack.enter_context(mock.patch.dict(R.COMPONENTS, {'device-b2-foundation-reconciliation': {'payload_root': self.live, 'artifact_only': True, 'services': ()}}))
for name in ('require_root', 'ensure_layout', 'validate_artifact_location'):
stack.enter_context(mock.patch.object(R, name))
for name in ('run_build', 'run_compose', 'prepare_component_runtime'):
stack.enter_context(mock.patch.object(R, name, side_effect=AssertionError('runtime mutation forbidden')))
stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('external commands forbidden')))
stack.enter_context(mock.patch.object(R, 'device_b2_002_evidence', return_value={}))
stack.enter_context(mock.patch.object(R, 'device_b2_schema', return_value=[]))
events = []
def accept(*args, **kwargs):
installed = (self.live / R.DEVICE_B2_RECON_ENTRY).exists()
events.append('post' if installed else 'pre')
if fail_after_marker and installed: raise R.DeployError('injected restored runtime drift')
stack.enter_context(mock.patch.object(R, 'accept_device_b2', side_effect=accept))
R.append_jsonl(R.FAILED_STATE_FILE, R.device_b2_002_failed_row())
R.append_jsonl(R.STATE_FILE, {'component': 'device-core-release', 'id': R.DEVICE_B2_BASELINE_ID, 'sha256': R.DEVICE_B2_BASELINE_SHA})
stack.enter_context(redirect_stdout(io.StringIO())); stack.enter_context(redirect_stderr(io.StringIO()))
if fail_after_marker:
with self.assertRaises(R.DeployError): R.apply_artifact(self.archive)
self.assertFalse((self.live/R.DEVICE_B2_RECON_ENTRY).exists())
self.assertEqual(R.load_state(R.FAILED_STATE_FILE)[-1]['rollback_status'], 'ok:device-b2-reconciliation-marker-only')
self.assertEqual(len(R.load_state(R.STATE_FILE)), 1)
else:
R.apply_artifact(self.archive)
receipt = R.load_state(R.STATE_FILE)[-1]
self.assertEqual(receipt['component'], 'device-b2-foundation-reconciliation')
self.assertTrue(R.device_b2_002_reconciled(R.device_b2_002_failed_row()))
R.device_b2_failed_barrier()
self.assertEqual(len(R.load_state(R.FAILED_STATE_FILE)), 1) # Original failure retained.
(R.APPLIED_DIR/receipt['artifact']).write_bytes(b'changed archive')
with self.assertRaises(R.DeployError): R.device_b2_002_reconciled(R.device_b2_002_failed_row())
self.assertEqual(events, ['pre', 'post'])
def test_metadata_apply_uses_real_journal_archive_and_receipt_without_runtime_commands(self):
self.execute_metadata_apply()
def test_metadata_apply_failure_removes_only_new_marker_and_retains_incident(self):
self.execute_metadata_apply(fail_after_marker=True)
if __name__ == '__main__':
unittest.main()
@@ -1,186 +0,0 @@
"""Exact schema transition, receipt boundary and data-preserving rollback."""
import copy
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import shutil
import tarfile
import tempfile
import unittest
from unittest import mock
loader = importlib.machinery.SourceFileLoader('shared_runner_test', str(Path(__file__).with_name('nodedc-deploy')))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec); loader.exec_module(R)
FIXTURE = Path(__file__).with_name('fixtures')/'device-b2-shared-contours'
def archive(path, extra=None):
files = {'manifest.env': f'id={R.DEVICE_B2_SHARED_ID}\ncomponent=device-b2-shared-contours\ntype=app-overlay\n'.encode(),
'files.txt': ('\n'.join(R.DEVICE_B2_SHARED_ENTRIES)+'\n').encode(),
**{'payload/'+p: (FIXTURE/p).read_bytes() for p in R.DEVICE_B2_SHARED_ENTRIES}}
files.update(extra or {})
with tarfile.open(path, 'w:gz') as target:
for name, data in files.items():
entry=tarfile.TarInfo(name); entry.size=len(data); entry.mode=0o644
target.addfile(entry, io.BytesIO(data))
class SharedContours(unittest.TestCase):
def test_exact_archive_load_and_empty_runtime_scope(self):
with tempfile.TemporaryDirectory() as tmp:
path=Path(tmp)/'a.tgz'; archive(path)
_, entries, payload=R.load_artifact(path, Path(tmp)/'unpack')
R.validate_device_b2_shared_payload(payload, entries, R.DEVICE_B2_SHARED_ID)
self.assertEqual(R.component_services('device-b2-shared-contours', entries), ())
self.assertEqual(R.component_builds('device-b2-shared-contours', entries), ())
self.assertTrue(R.component_artifact_only('device-b2-shared-contours'))
self.assertEqual(R.component_root('device-b2-shared-contours'), R.DEVICE_PLANE_ROOT)
def test_extra_sql_env_hook_runtime_or_traversal_rejected(self):
for name in ('.env', 'hooks.sh', 'deployment/other.sql', 'secrets/admin.json', '../escape',
'services/device-control-core/src/server.mjs', 'runtime/db.dump'):
with self.subTest(name=name), self.assertRaises(R.DeployError):
R.allowed_payload_path('device-b2-shared-contours', name)
for entries in ((), R.DEVICE_B2_SHARED_ENTRIES[:-1], tuple(reversed(R.DEVICE_B2_SHARED_ENTRIES))):
with self.assertRaises(R.DeployError): R.component_services('device-b2-shared-contours', entries)
def test_modified_sql_descriptor_and_identity_rejected(self):
for rel in R.DEVICE_B2_SHARED_ENTRIES:
with self.subTest(rel=rel), tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); shutil.copytree(FIXTURE, root, dirs_exist_ok=True)
path=root/rel
if rel == R.DEVICE_B2_SHARED_DESCRIPTOR:
v=json.loads(path.read_text()); v['services']=['device-postgres']; path.write_text(json.dumps(v))
else: path.write_text('drop table device_b2_hosts;')
with self.assertRaises(R.DeployError):
R.validate_device_b2_shared_payload(root, R.DEVICE_B2_SHARED_ENTRIES, R.DEVICE_B2_SHARED_ID)
with self.assertRaises(R.DeployError):
R.validate_device_b2_shared_payload(FIXTURE, R.DEVICE_B2_SHARED_ENTRIES, 'unreviewed')
def test_forward_schema_is_exact_and_old_contract_is_unchanged(self):
old=copy.deepcopy(R.DEVICE_B2_EXPECTED_SCHEMA); new=R.device_b2_shared_schema()
R.validate_device_b2_schema(old)
with self.assertRaises(R.DeployError): R.validate_device_b2_schema(new)
R.validate_device_b2_schema(new, expected=R.device_b2_shared_schema())
self.assertEqual(R.DEVICE_B2_EXPECTED_SCHEMA, old)
self.assertEqual(old[1:], new[1:])
for key in ('constraints', 'fields', 'validated', 'columns'):
self.assertEqual(old[0][key], new[0][key])
for mutation in ('missing-fk', 'wrong-marker', 'extra-field', 'wrong-pk'):
value=copy.deepcopy(new)
if mutation=='missing-fk': value[0]['definitions'].pop(1)
if mutation=='wrong-marker': value[0]['marker']='other'
if mutation=='extra-field': value[0]['fields'].append(['unsafe','text',False])
if mutation=='wrong-pk': value[0]['definitions'][-1]='PRIMARY KEY (contour_id)'
with self.subTest(mutation=mutation), self.assertRaises(R.DeployError):
R.validate_device_b2_schema(value, expected=new)
def test_failed_mutation_blocks_normal_compose_even_without_overlay(self):
row={'component':'device-b2-shared-contours','started_apply':True,'rollback_status':'failed:DeployError'}
with mock.patch.object(R, 'load_state', return_value=[row]), self.assertRaises(R.DeployError):
R.device_b2_compose_files(())
for r in ({**row,'started_apply':False}, {**row,'rollback_status':'ok:device-b2-shared-contours'}):
with mock.patch.object(R,'load_state',return_value=[r]): R.device_b2_shared_failed_barrier()
def test_receipt_requires_all_files_unique_success_and_verified_archive(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp)/'live'; root.mkdir()
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'TMP_DIR',Path(tmp)), \
mock.patch.object(R,'load_state',return_value=[]):
self.assertFalse(R.device_b2_shared_receipt())
shutil.copytree(FIXTURE,root,dirs_exist_ok=True)
with self.assertRaises(R.DeployError): R.device_b2_shared_receipt()
row={'component':'device-b2-shared-contours','id':R.DEVICE_B2_SHARED_ID,'status':'ok'}
good=Path(tmp)/'good.tgz'; archive(good)
state=lambda path: [row] if path==R.STATE_FILE else []
with mock.patch.object(R,'load_state',side_effect=state), \
mock.patch.object(R,'device_release_applied_archive',return_value=good) as checked:
self.assertTrue(R.device_b2_shared_receipt()); checked.assert_called_once_with(row)
for rows in ([row,row],[{**row,'id':'other'}],[{**row,'status':'failed'}]):
with mock.patch.object(R,'load_state',side_effect=lambda p:rows if p==R.STATE_FILE else []), self.assertRaises(R.DeployError):
R.device_b2_shared_receipt()
with mock.patch.object(R,'load_state',side_effect=state), \
mock.patch.object(R,'device_release_applied_archive',side_effect=R.DeployError('archive mismatch')), \
self.assertRaises(R.DeployError): R.device_b2_shared_receipt()
def test_preflight_rejects_wrong_live_release_before_database_mutation(self):
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \
mock.patch.object(R,'load_state',return_value=[]), mock.patch.object(R,'device_b2_database') as db:
with self.assertRaisesRegex(R.DeployError,'r37'):
R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID)
db.assert_not_called()
def test_preflight_rejects_missing_foundation_and_wrong_source(self):
row={'component':'device-core-release','id':R.DEVICE_B2_SHARED_BASELINE,'sha256':R.DEVICE_B2_SHARED_BASELINE_SHA}
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'DEVICE_PLANE_ROOT',Path(tmp)), \
mock.patch.object(R,'TMP_DIR',Path(tmp)), \
mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.STATE_FILE else []), \
mock.patch.object(R,'device_release_applied_archive',return_value=Path(tmp)/'release.tgz'), \
mock.patch.object(R,'load_artifact',return_value=({'component':'device-core-release'}, R.DEVICE_RELEASE_ENTRIES,Path(tmp))), \
mock.patch.object(R,'collect_exact_files',side_effect=[{'a':'one'},{'a':'two'}]), \
self.assertRaisesRegex(R.DeployError,'source drift'):
R.preflight_device_b2_shared(FIXTURE,R.DEVICE_B2_SHARED_ENTRIES,R.DEVICE_B2_SHARED_ID)
def test_rollback_never_restores_old_data_over_new_links(self):
with mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \
mock.patch.object(R,'device_b2_database',side_effect=R.DeployError('would_lose_links')) as db, \
mock.patch.object(R,'restore_platform_overlay') as restore, \
mock.patch.object(R,'accept_device_b2_shared') as accept:
with self.assertRaisesRegex(R.DeployError,'would_lose_links'):
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
self.assertIn('rollback_would_lose_links',db.call_args.args[0])
restore.assert_not_called(); accept.assert_not_called()
def test_rollback_after_failed_transaction_restores_only_new_files(self):
with mock.patch.object(R,'device_b2_schema',return_value=R.DEVICE_B2_EXPECTED_SCHEMA), \
mock.patch.object(R,'device_b2_database') as db, \
mock.patch.object(R,'restore_platform_overlay') as restore, \
mock.patch.object(R,'accept_device_b2_shared') as accept:
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
db.assert_not_called(); restore.assert_called_once(); accept.assert_called_once_with({},Path('/unused'),rollback=True)
def test_unknown_schema_retained_without_destructive_attempt(self):
with mock.patch.object(R,'device_b2_schema',return_value=[]), mock.patch.object(R,'device_b2_database') as db, \
mock.patch.object(R,'restore_platform_overlay') as restore, self.assertRaises(R.DeployError):
R.rollback_device_b2_shared(FIXTURE,Path('/unused'),R.DEVICE_B2_SHARED_ENTRIES,'stamp',{})
db.assert_not_called(); restore.assert_not_called()
def test_private_table_backup_fixed_scope_and_failure_precedes_sql(self):
def dump(argv, **kwargs):
self.assertEqual(argv[-3:], ['--strict-names', '-t', 'public.device_b2_contour_links'])
kwargs['stdout'].write(b'PGDMP-synthetic-fixture')
return mock.Mock(returncode=0, stderr=b'')
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \
mock.patch.object(R.subprocess,'run',side_effect=dump), mock.patch.object(R,'device_b2_database') as sql:
root=Path(tmp)
R.backup_device_b2_shared(root,{'runtime':{}})
self.assertEqual((root/'device-b2-contour-links.dump').stat().st_mode & 0o777,0o600)
self.assertEqual((root/'device-b2-contour-links.dump.sha256').read_text().strip(),R.sha256_file(root/'device-b2-contour-links.dump'))
sql.assert_not_called()
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(R,'device_plane_service_container_ids',return_value=['postgres-existing']), \
mock.patch.object(R.subprocess,'run',return_value=mock.Mock(returncode=1,stderr=b'failed')), self.assertRaises(R.DeployError):
R.backup_device_b2_shared(Path(tmp),{})
def test_acceptance_checks_schema_backup_and_preserved_runtime_before_success(self):
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); shutil.copytree(FIXTURE,root,dirs_exist_ok=True)
dump=root/'device-b2-contour-links.dump'; dump.write_bytes(b'PGDMP-fixture'); dump.chmod(0o600)
(root/'device-b2-contour-links.dump.sha256').write_text(R.sha256_file(dump)+'\n')
before={'runtime':{'postgres':'same','core':'same'},'otherComposeServices':{},'compose':{},'installedFiles':{}}
with mock.patch.object(R,'DEVICE_PLANE_ROOT',root), mock.patch.object(R,'device_b2_schema',return_value=R.device_b2_shared_schema()), \
mock.patch.object(R,'device_b2_private_directory'), mock.patch.object(R,'run_healthchecks') as health, \
mock.patch.object(R,'device_release_runtime_snapshot_v2',return_value=before['runtime']) as runtime, \
mock.patch.object(R,'device_release_other_compose_services',return_value={}), \
mock.patch.object(R,'collect_exact_files',return_value={}):
R.accept_device_b2_shared(before,root)
health.assert_called_once_with('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
runtime.return_value={'postgres':'recreated','core':'same'}
with self.assertRaisesRegex(R.DeployError,'preserved service'): R.accept_device_b2_shared(before,root)
runtime.return_value=before['runtime']; dump.write_bytes(b'changed')
with self.assertRaisesRegex(R.DeployError,'backup changed'): R.accept_device_b2_shared(before,root)
if __name__ == '__main__': unittest.main()
@@ -1,126 +0,0 @@
"""Canonical bootstrap scope, unit ownership, live-dispatch ordering and receipts."""
import copy
from contextlib import ExitStack,redirect_stdout,redirect_stderr
import hashlib
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import stat
import sys
import tempfile
import unittest
from unittest import mock
loader=importlib.machinery.SourceFileLoader('autodeploy_runner',str(Path(__file__).with_name('nodedc-deploy')))
spec=importlib.util.spec_from_loader(loader.name,loader);R=importlib.util.module_from_spec(spec);loader.exec_module(R)
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'device-core-deploy'))
from build_autodeploy import bundle
from embed_library import section,START,END
class AutodeployTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.root=Path(self.tmp.name)
self.identity,self.data=bundle();self.artifact=self.root/'bootstrap.tgz';self.artifact.write_bytes(self.data)
self.work=self.root/'work';self.work.mkdir()
def test_deterministic_archive_and_canonical_scope(self):
self.assertEqual(bundle()[1],self.data)
manifest,entries,payload=R.load_artifact(self.artifact,self.work)
self.assertEqual(manifest['id'],self.identity);self.assertEqual(entries,[R.DEVICE_AUTODEPLOY_ENTRY])
self.assertEqual(R.component_services('device-core-autodeploy',entries),())
self.assertEqual(R.component_builds('device-core-autodeploy',entries),())
self.assertTrue(R.component_artifact_only('device-core-autodeploy'))
for path in ['deployment/other.json','runtime/token','docker-compose.yml','hook.py']:
with self.assertRaises(R.DeployError):R.allowed_payload_path('device-core-autodeploy',path)
def test_descriptor_cannot_change_authority_or_baseline(self):
m,e,p=R.load_artifact(self.artifact,self.work)
for key,value in [('firstRunNumber',1),('installer','/tmp/runner'),('services',['device-postgres']),('publishedPorts',[9000]),('baselineSourceCommit','a'*40)]:
d=copy.deepcopy(R.DEVICE_AUTODEPLOY_DESCRIPTOR);d[key]=value
(p/e[0]).write_text(json.dumps(d,sort_keys=True,indent=2)+'\n')
with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_autodeploy_payload(p,e,m['id'])
def test_generated_library_is_exact_and_operates_without_source_imports(self):
text=Path(R.__file__).read_text();actual=START+text.split(START,1)[1].split(END,1)[0]+END
self.assertEqual(actual,section())
Q,S,C,errors=R.device_autodeploy_library();q=Q(self.root/'queue',first_run_number=8)
self.assertIsNone(q.next_ready());q.close()
self.assertEqual(S('a'*40)._token,'a'*40)
def test_units_have_only_internal_worker_no_listeners_or_external_hooks(self):
units=R.device_autodeploy_units();self.assertEqual(set(units),{R.DEVICE_AUTODEPLOY_SERVICE,R.DEVICE_AUTODEPLOY_TIMER})
self.assertIn('ExecStart=/usr/bin/python3 /usr/local/sbin/nodedc-deploy --device-core-autodeploy-tick',units[R.DEVICE_AUTODEPLOY_SERVICE])
self.assertIn('OnUnitInactiveSec=30s',units[R.DEVICE_AUTODEPLOY_TIMER])
self.assertNotIn('Listen',str(units));self.assertNotIn('/Volumes/',str(units));self.assertNotIn('/inbox/',str(units))
def test_bootstrap_worker_cannot_deploy_before_canonical_receipt(self):
with mock.patch.object(R,'require_root'),mock.patch.object(R,'ensure_layout'),mock.patch.object(R,'device_autodeploy_activated',return_value=False),mock.patch.object(R,'device_autodeploy_read_token') as token:
self.assertEqual(R.device_autodeploy_tick(),0);token.assert_not_called()
def test_unit_install_and_rollback_preserve_applications_and_secrets(self):
unitdir=self.root/'units';unitdir.mkdir();live=self.root/'live';live.mkdir();secret=self.root/'secret';secret.write_text('retain')
before={'inventory':{'fixture':1}}
with mock.patch.object(R,'DEVICE_AUTODEPLOY_UNIT_DIR',unitdir),mock.patch.object(R,'device_autodeploy_import_token'),mock.patch.object(R,'device_autodeploy_ctl') as ctl,mock.patch.object(R,'accept_device_autodeploy'),mock.patch.object(R,'device_autodeploy_root_path'),mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R,'gitea_ci_inventory',return_value=before['inventory']):
R.apply_device_autodeploy(before)
for name,data in R.device_autodeploy_units().items():self.assertEqual((unitdir/name).read_text(),data)
R.rollback_device_autodeploy(live,self.root,[R.DEVICE_AUTODEPLOY_ENTRY],'stamp',before)
self.assertFalse(list(unitdir.iterdir()));self.assertEqual(secret.read_text(),'retain')
self.assertIn(mock.call('disable',R.DEVICE_AUTODEPLOY_TIMER,check=False),ctl.call_args_list)
def test_wrong_unit_bytes_and_inventory_prevent_false_acceptance(self):
d=self.root/'units';d.mkdir()
for name,value in R.device_autodeploy_units().items():(d/name).write_text(value)
(d/R.DEVICE_AUTODEPLOY_SERVICE).write_text('changed')
with mock.patch.object(R,'DEVICE_AUTODEPLOY_UNIT_DIR',d),mock.patch.object(R,'device_autodeploy_root_path'),self.assertRaises(R.DeployError):R.accept_device_autodeploy({'inventory':{}})
def execute(self,fail=False):
live=self.root/'live'
for name in ['inbox','applied','failed','backups','state','tmp']:(self.root/name).mkdir()
a=self.root/'inbox/bootstrap.tgz';a.write_bytes(self.data)
events=[];before={'inventory':{},'baseline':R.DEVICE_AUTODEPLOY_BASELINE}
def acceptance(*args):
events.append('accept')
if fail:raise R.DeployError('injected acceptance failure')
def rollback(root,backup,entries,stamp,proof):
events.append('rollback');R.restore_platform_overlay(root,backup,entries,stamp)
with ExitStack() as stack:
for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),('LOCK_DIR',self.root/'lock')]:stack.enter_context(mock.patch.object(R,name,value))
stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-autodeploy':{'payload_root':live,'bootstrap_root':True,'artifact_only':True,'services':()}}))
for name in ['require_root','ensure_layout','validate_artifact_location']:stack.enter_context(mock.patch.object(R,name))
stack.enter_context(mock.patch.object(R,'preflight_device_autodeploy',return_value=before))
stack.enter_context(mock.patch.object(R,'apply_device_autodeploy',side_effect=lambda b:events.append('install')))
stack.enter_context(mock.patch.object(R,'accept_device_autodeploy',side_effect=acceptance))
stack.enter_context(mock.patch.object(R,'rollback_device_autodeploy',side_effect=rollback))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail:
with self.assertRaises(R.DeployError):R.apply_artifact(a)
else:R.apply_artifact(a)
applied=R.load_state(R.STATE_FILE);failed=R.load_state(R.FAILED_STATE_FILE)
return events,applied,failed
def test_real_canonical_apply_success_after_acceptance(self):
events,applied,failed=self.execute()
self.assertEqual(events,['install','accept']);self.assertEqual(len(applied),1);self.assertFalse(failed)
self.assertEqual(applied[0]['sha256'],hashlib.sha256(self.data).hexdigest())
def test_real_canonical_failure_dispatches_only_own_rollback(self):
events,applied,failed=self.execute(True)
self.assertEqual(events,['install','accept','rollback']);self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'],'ok:device-core-autodeploy-bootstrap')
def test_receipt_requires_archive_backup_and_exact_digest(self):
applied=self.root/'applied';failed=self.root/'failed';backups=self.root/'backups'
for d in (applied,failed,backups):d.mkdir()
name='nodedc-device-core-release-v1-r8-'+'a'*40+'.tgz';identity=name[7:-4]
archive=applied/name;archive.write_bytes(b'archive');(backups/'backup').mkdir()
row={'artifact':name,'digest':hashlib.sha256(b'archive').hexdigest()}
record={'id':identity,'artifact':name,'component':'device-core-release','sha256':row['digest'],'backup_id':'backup','status':'ok'}
with mock.patch.object(R,'APPLIED_DIR',applied),mock.patch.object(R,'FAILED_DIR',failed),mock.patch.object(R,'BACKUPS_DIR',backups):
with mock.patch.object(R,'load_state',side_effect=[[record],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'deployed')
archive.write_bytes(b'changed')
with mock.patch.object(R,'load_state',side_effect=[[record],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'ambiguous')
with mock.patch.object(R,'load_state',side_effect=[[],[]]):self.assertEqual(R.DeviceAutodeployInstaller().receipt(row)[0],'ambiguous')
if __name__=='__main__':unittest.main()
@@ -1,158 +0,0 @@
"""The diagnostic domain must not weaken any release/reconciliation barrier."""
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import copy
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
from test_device_core_release import R, runtime
path = Path(__file__).resolve().parents[1] / 'device-core-deploy/build_drift_audit.py'
loader = importlib.machinery.SourceFileLoader('drift_builder', str(path))
spec = importlib.util.spec_from_loader(loader.name, loader)
B = importlib.util.module_from_spec(spec)
loader.exec_module(B)
def inspect_fixture():
return {'HostConfig': {'Binds': ['/host/a:/a:ro', '/host/b:/b:ro'],
'Mounts': [{'Source': '/host/c', 'Target': '/c', 'ReadOnly': True},
{'Source': '/host/d', 'Target': '/d', 'ReadOnly': True}],
'NetworkMode': 'private', 'Ulimits': [{'Name': 'nproc', 'Soft': 100}, {'Name': 'nofile', 'Soft': 128}],
'PortBindings': {}, 'ReadonlyRootfs': True, 'SecurityOpt': ['no-new-privileges:true']},
'Config': {'Env': ['SECRET=never-print-this-value', 'B=2', 'A=1'], 'User': '1000', 'Cmd': ['node', 'app.mjs']},
'Mounts': [{'Destination': '/b', 'Source': '/host/b', 'RW': False}, {'Destination': '/a', 'Source': '/host/a', 'RW': False}],
'NetworkSettings': {'Networks': {'private': {}, 'egress': {}}}}
class DriftAuditTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.artifact = self.root/'audit.tgz'; self.artifact.write_bytes(B.bundle()[1])
self.work = self.root/'work'; self.work.mkdir()
self.manifest, self.entries, self.payload = R.load_artifact(self.artifact, self.work)
def test_deterministic_fixed_descriptor_and_no_runtime_authority(self):
self.assertEqual(self.artifact.read_bytes(), B.bundle()[1])
self.assertEqual(tuple(self.entries), (R.DEVICE_RELEASE_DRIFT_AUDIT_ENTRY,))
component = self.manifest['component']
self.assertEqual(R.component_services(component, self.entries), ())
self.assertEqual(R.component_builds(component, self.entries), ())
self.assertEqual(R.component_compose_files(component), ())
self.assertTrue(R.component_artifact_only(component))
for rel in ['deployment/other.json', 'services/device-control-core/src/app.mjs', 'secrets/key']:
with self.subTest(rel=rel), self.assertRaises(R.DeployError): R.allowed_payload_path(component, rel)
descriptor = R.device_release_drift_audit_descriptor(); descriptor['mode'] = 'repair'
(self.payload/R.DEVICE_RELEASE_DRIFT_AUDIT_ENTRY).write_text(json.dumps(descriptor))
with self.assertRaises(R.DeployError): R.validate_device_release_drift_audit_payload(self.payload, self.entries, self.manifest['id'])
def test_diagnostic_fields_exactly_match_existing_production_hash(self):
info = inspect_fixture()
rows = [{k:v for k,v in row.items() if k != 'runtimeConfigSha256'} for row in runtime().values()]
inventory = {'schemaVersion': 'nodedc.device-plane.runtime-inventory.v1',
'composeProject': 'nodedc-device-plane', 'services': rows}
with mock.patch.object(R, 'device_plane_runtime_inventory', return_value=inventory), mock.patch.object(R, 'inspect_device_plane_container', return_value=copy.deepcopy(info)):
actual = R.device_release_runtime_snapshot()
expected = R.device_release_drift_digest(R.device_release_drift_fields(info))
self.assertTrue(all(row['runtimeConfigSha256'] == expected for row in actual.values()))
def test_permutations_find_exact_saved_hash_without_mutating_input(self):
fields = R.device_release_drift_fields(inspect_fixture()); saved = copy.deepcopy(fields)
saved['HostConfig']['Binds'].reverse(); saved['HostConfig']['Mounts'].reverse()
original = copy.deepcopy(fields)
result = R.device_release_drift_probe(fields, R.device_release_drift_digest(saved))
self.assertTrue(result['exactPreimageFound']); self.assertFalse(result['exactCurrentMatch'])
self.assertEqual(result['changedFields'], ['HostConfig.Binds', 'HostConfig.Mounts'])
self.assertEqual(fields, original)
def test_seven_mounts_are_supported_without_guessing_any_values(self):
fields = R.device_release_drift_fields(inspect_fixture()); fields['HostConfig']['Binds'] = None
fields['HostConfig']['Mounts'] = [{'Source': '/h/'+str(i), 'Target': '/t/'+str(i)} for i in range(7)]
saved = copy.deepcopy(fields); saved['HostConfig']['Mounts'].reverse()
result = R.device_release_drift_probe(fields, R.device_release_drift_digest(saved))
self.assertTrue(result['exactPreimageFound']); self.assertFalse(result['searchTruncated'])
self.assertEqual(result['changedFields'], ['HostConfig.Mounts'])
def test_network_mode_difference_is_reported_not_silently_normalized(self):
fields = R.device_release_drift_fields(inspect_fixture()); saved = copy.deepcopy(fields)
saved['HostConfig']['NetworkMode'] = 'egress'
result = R.device_release_drift_probe(fields, R.device_release_drift_digest(saved))
self.assertTrue(result['exactPreimageFound']); self.assertFalse(result['exactCurrentMatch'])
self.assertEqual(result['changedFields'], ['HostConfig.NetworkMode'])
self.assertEqual(result['matchingSavedNetworkMode'], 'egress')
def test_real_configuration_changes_never_become_order_proofs(self):
fields = R.device_release_drift_fields(inspect_fixture())
for section, key, value in [('HostConfig', 'ReadonlyRootfs', False), ('HostConfig', 'PortBindings', {'1/tcp': [{'HostPort': '1234'}]}), ('Config', 'Env', ['DIFFERENT=secret']), ('HostConfig', 'Binds', ['/h/changed:/a:ro'])]:
saved = copy.deepcopy(fields); saved[section][key] = value
with self.subTest(key=key):
self.assertFalse(R.device_release_drift_probe(fields, R.device_release_drift_digest(saved))['exactPreimageFound'])
def test_search_limit_and_duplicates_are_explicit_unresolved_results(self):
fields = R.device_release_drift_fields(inspect_fixture())
result = R.device_release_drift_probe(fields, 'a'*64, budget=2)
self.assertFalse(result['exactPreimageFound']); self.assertTrue(result['searchTruncated'])
self.assertEqual(result['candidatesChecked'], 2)
fields['HostConfig']['Binds'] *= 2
self.assertEqual(R.device_release_drift_probe(fields, 'a'*64)['reason'], 'ambiguous-duplicate-mounts')
def test_report_checks_all_services_and_never_emits_plaintext(self):
current = runtime(); fields = R.device_release_drift_fields(inspect_fixture())
for row in current.values(): row['runtimeConfigSha256'] = R.device_release_drift_digest(fields)
samples = {name: {'runtime': row, 'fields': fields} for name, row in current.items()}
changed = copy.deepcopy(samples); changed['device-control-core']['fields']['HostConfig']['ReadonlyRootfs'] = False
before = {'runtime': current, 'compose': {}, 'installedFiles': {}, 'otherComposeServices': {}}
with ExitStack() as stack:
for name, value in [('device_release_r5_evidence', before), ('collect_exact_files', {}), ('component_compose_files', ()), ('device_release_other_compose_services', {})]:
stack.enter_context(mock.patch.object(R, name, return_value=value))
stack.enter_context(mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.root/'live'))
stack.enter_context(mock.patch.object(R, 'device_release_drift_sample', side_effect=[samples, changed, samples]))
stack.enter_context(mock.patch.object(R, 'run_healthchecks', side_effect=R.DeployError('secret-must-not-be-printed')))
boundary = stack.enter_context(mock.patch.object(R, 'validate_device_manager_control_plane_runtime'))
mutation = stack.enter_context(mock.patch.object(R.subprocess, 'run'))
output = stack.enter_context(redirect_stdout(io.StringIO()))
report = R.device_release_drift_audit(self.payload, self.entries, self.manifest['id'])
rendered = output.getvalue()
self.assertFalse(report['applyAllowed']); self.assertFalse(report['mutation'])
self.assertEqual(set(report['services']), set(R.DEVICE_RELEASE_INVENTORY))
self.assertFalse(report['services']['device-control-core']['samplesStable'])
self.assertFalse(report['checks']['health']['ok']); self.assertTrue(report['checks']['source']['ok'])
self.assertTrue(boundary.call_args.kwargs['read_only']); mutation.assert_not_called()
for text in ['never-print-this-value', 'SECRET=', 'secret-must-not-be-printed', '/host/a']:
self.assertNotIn(text, rendered)
def test_apply_is_rejected_before_any_application_or_backup_action(self):
for directory in ['inbox', 'applied', 'failed', 'backups', 'state', 'tmp']:(self.root/directory).mkdir()
with ExitStack() as stack:
for name, value in [('INBOX', self.root/'inbox'), ('APPLIED_DIR', self.root/'applied'), ('FAILED_DIR', self.root/'failed'), ('BACKUPS_DIR', self.root/'backups'), ('STATE_DIR', self.root/'state'), ('TMP_DIR', self.root/'tmp'), ('STATE_FILE', self.root/'state/applied.jsonl'), ('FAILED_STATE_FILE', self.root/'state/failed.jsonl'), ('LOCK_DIR', self.root/'lock')]:
stack.enter_context(mock.patch.object(R, name, value))
for name in ['require_root', 'ensure_layout', 'validate_artifact_location']:
stack.enter_context(mock.patch.object(R, name))
command = stack.enter_context(mock.patch.object(R.subprocess, 'run'))
runtime_action = stack.enter_context(mock.patch.object(R, 'run_component_runtime'))
root = stack.enter_context(mock.patch.object(R, 'component_root'))
stack.enter_context(redirect_stdout(io.StringIO())); stack.enter_context(redirect_stderr(io.StringIO()))
with self.assertRaisesRegex(R.DeployError, 'plan-only; apply is forbidden'): R.apply_artifact(self.artifact)
command.assert_not_called(); runtime_action.assert_not_called(); root.assert_not_called()
self.assertEqual(list((self.root/'backups').iterdir()), [])
self.assertFalse(R.load_state(R.FAILED_STATE_FILE)[0]['started_apply'])
def test_plan_dispatches_only_the_registered_audit(self):
with mock.patch.object(R, 'validate_artifact_location'), mock.patch.object(R, 'ensure_layout'), \
mock.patch.object(R, 'TMP_DIR', self.root), \
mock.patch.object(R, 'device_release_drift_audit') as audit, \
mock.patch.object(R, 'preflight_device_release_reconciliation') as recovery, \
mock.patch.object(R, 'run_component_runtime') as mutation:
R.plan_artifact(self.artifact)
audit.assert_called_once()
self.assertEqual(audit.call_args.args[2], R.DEVICE_RELEASE_DRIFT_AUDIT_ID)
recovery.assert_not_called(); mutation.assert_not_called()
if __name__ == '__main__': unittest.main()
@@ -1,226 +0,0 @@
"""Order-only recovery must prove the legacy digest without relaxing values."""
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
from test_device_core_release import R, runtime, put
from test_device_core_reconciliation import B
from test_device_core_drift_audit import inspect_fixture
def samples_fixture():
samples = {}
for service, row in runtime().items():
fields = R.device_release_drift_fields(inspect_fixture())
fields['HostConfig']['Binds'] = None
count = 7 if service == 'device-control-core' else 3
fields['HostConfig']['Mounts'] = [
{'Type': 'bind', 'Source': '/host/'+str(i), 'Target': '/target/'+str(i),
'ReadOnly': True, 'BindOptions': {'Propagation': 'rprivate'}} for i in range(count)]
row['runtimeConfigSha256'] = R.device_release_drift_digest(fields)
samples[service] = {'runtime': row, 'fields': fields}
return samples
def evidence_fixture(samples):
return {'runtime': {s:copy.deepcopy(v['runtime']) for s,v in samples.items()},
'compose': {}, 'otherComposeServices': {}, 'installedFiles': {}}
def reorder(samples):
new = copy.deepcopy(samples)
for s in R.DEVICE_RELEASE_SERVICES:
new[s]['fields']['HostConfig']['Mounts'].reverse()
new[s]['runtime']['runtimeConfigSha256'] = R.device_release_drift_digest(new[s]['fields'])
new[s]['runtime']['containerId'] = 'a'*64
return new
class MountOrderTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.artifact = self.root/'proof-v2.tgz';self.artifact.write_bytes(B.bundle(2)[1])
work = self.root/'work';work.mkdir()
self.manifest,self.entries,self.payload = R.load_artifact(self.artifact,work)
def test_v2_bundle_fixed_data_only_and_v1_bytes_unchanged(self):
self.assertEqual(self.artifact.read_bytes(),B.bundle(2)[1])
self.assertEqual(tuple(self.entries),(R.DEVICE_RELEASE_RECONCILIATION_V2_ENTRY,))
self.assertEqual(self.manifest['id'],R.DEVICE_RELEASE_RECONCILIATION_V2_ID)
self.assertEqual(__import__('hashlib').sha256(B.bundle(1)[1]).hexdigest(),'68de2806a57253269bf9efb9d508cffbd1942fcca4cf9fc94b82d12fff0f322c')
for func in [R.component_services,R.component_builds]:
self.assertEqual(func(self.manifest['component'],self.entries),())
self.assertEqual(R.component_compose_files(self.manifest['component']),())
with self.assertRaises(R.DeployError):
R.component_services(self.manifest['component'],[R.DEVICE_RELEASE_RECONCILIATION_ENTRY,*self.entries])
for key,value in [('runtimeFingerprintVersion',1),('mode','restart'),('failedSha256','f'*64),('extra',True)]:
d = R.device_release_reconciliation_v2_descriptor();d[key] = value
(self.payload/self.entries[0]).write_text(json.dumps(d))
with self.subTest(key=key),self.assertRaises(R.DeployError):
R.validate_device_release_reconciliation_payload(self.payload,self.entries,self.manifest['id'])
def test_permutations_preserve_every_option_without_mutating_input(self):
a = samples_fixture()['device-control-core']['fields'];original = copy.deepcopy(a)
b = copy.deepcopy(a);b['HostConfig']['Mounts'].reverse()
self.assertNotEqual(R.device_release_drift_digest(a),R.device_release_drift_digest(b))
self.assertEqual(R.device_release_mounts_v2(a),R.device_release_mounts_v2(b))
self.assertEqual(R.device_release_mount_order_proof(b,R.device_release_drift_digest(a)),5041)
self.assertEqual(a,original)
def test_real_changes_and_binds_order_cannot_use_mount_order_proof(self):
fields = samples_fixture()['device-manager']['fields']
fields['HostConfig']['Binds'] = ['/host/a:/a:ro','/host/b:/b:ro']
digest = R.device_release_drift_digest(fields)
variants = []
for key,value in [('Source','/different'),('Target','/different'),('ReadOnly',False),('Type','volume'),('BindOptions',{'Propagation':'rshared'}),('VolumeOptions',{'NoCopy':True})]:
d = copy.deepcopy(fields);d['HostConfig']['Mounts'][0][key] = value;variants.append(d)
for section,key,value in [('HostConfig','NetworkMode','egress'),('HostConfig','Binds',list(reversed(fields['HostConfig']['Binds']))),('HostConfig','PortBindings',{'1/tcp':[{'HostPort':'1234'}]}),('HostConfig','ReadonlyRootfs',False),('Config','Env',['CHANGED=1']),('Config','Cmd',['other'])]:
d = copy.deepcopy(fields);d[section][key] = value;variants.append(d)
for i,d in enumerate(variants):
with self.subTest(variant=i):
self.assertNotEqual(R.device_release_mounts_v2(fields),R.device_release_mounts_v2(d))
with self.assertRaisesRegex(R.DeployError,'beyond HostConfig.Mounts order'):
R.device_release_mount_order_proof(d,digest)
def test_duplicate_or_ambiguous_targets_and_oversized_proof_fail_closed(self):
fields = samples_fixture()['device-manager']['fields']
for target in ['/target/1','relative','/a/../target','//target','/a/','/a\0b',None]:
d = copy.deepcopy(fields);d['HostConfig']['Mounts'][0]['Target'] = target
with self.subTest(target=target),self.assertRaises(R.DeployError):R.device_release_mounts_v2(d)
for value in ['invalid',[None],[{}]]:
d = copy.deepcopy(fields);d['HostConfig']['Mounts'] = value
with self.assertRaises(R.DeployError):R.device_release_mounts_v2(d)
d = copy.deepcopy(fields);d['HostConfig']['Mounts'] = [{'Target':'/t/'+str(i)} for i in range(8)]
with self.assertRaisesRegex(R.DeployError,'seven-mount'):R.device_release_mount_order_proof(d,R.device_release_drift_digest(d))
def test_none_absent_and_empty_mounts_remain_distinct(self):
fields = samples_fixture()['device-manager']['fields']
for mounts in [None,[]]:
d = copy.deepcopy(fields);d['HostConfig']['Mounts'] = mounts
self.assertEqual(d,R.device_release_mounts_v2(d))
d['HostConfig'].pop('Mounts');self.assertEqual(d,R.device_release_mounts_v2(d))
def test_three_samples_prove_exact_old_hashes_and_preserve_original_evidence(self):
original = samples_fixture();before = evidence_fixture(original);saved = copy.deepcopy(before)
current = reorder(original)
with mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current)),redirect_stdout(io.StringIO()) as output:
new = R.device_release_r5_mount_order_baseline(before)
self.assertEqual(before,saved);self.assertEqual(new['runtimeFingerprintVersion'],2)
for service in R.DEVICE_RELEASE_INVENTORY:
self.assertEqual(new['runtime'][service]['runtimeConfigSha256'],R.device_release_drift_digest(R.device_release_mounts_v2(original[service]['fields'])))
self.assertNotIn('SECRET=',output.getvalue());self.assertNotIn('/host/',output.getvalue())
def test_bad_image_unhealthy_preserved_recreation_and_unstable_sample_block_proof(self):
old = samples_fixture();before = evidence_fixture(old);current = reorder(old)
for service,key,value in [('device-manager','imageId','sha256:'+'f'*64),('device-control-core','running',False),('device-postgres','containerId','b'*64)]:
d = copy.deepcopy(current);d[service]['runtime'][key] = value
with self.subTest(service=service,key=key),mock.patch.object(R,'device_release_drift_sample',return_value=d),self.assertRaises(R.DeployError):
R.device_release_r5_mount_order_baseline(before)
d = copy.deepcopy(current);d['device-manager']['runtime']['restartCount'] += 1
with mock.patch.object(R,'device_release_drift_sample',side_effect=[current,d,current]),self.assertRaisesRegex(R.DeployError,'changed during'):R.device_release_r5_mount_order_baseline(before)
def test_snapshot_v2_is_stable_and_rejects_unhealthy_services(self):
current = samples_fixture();changed = reorder(current)
with mock.patch.object(R,'device_release_drift_sample',return_value=copy.deepcopy(current)):a = R.device_release_runtime_snapshot_v2()
with mock.patch.object(R,'device_release_drift_sample',return_value=copy.deepcopy(changed)):b = R.device_release_runtime_snapshot_v2()
self.assertEqual([r['runtimeConfigSha256'] for r in a.values()],[r['runtimeConfigSha256'] for r in b.values()])
changed['device-postgres']['runtime']['health'] = 'unhealthy'
with mock.patch.object(R,'device_release_drift_sample',return_value=changed),self.assertRaises(R.DeployError):R.device_release_runtime_snapshot_v2()
def acceptance_stack(self,stack):
for name,value in [('device_release_other_compose_services',{}),('component_compose_files',()),('collect_exact_files',{})]:
stack.enter_context(mock.patch.object(R,name,return_value=value))
stack.enter_context(mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root/'live'))
stack.enter_context(mock.patch.object(R,'validate_device_manager_control_plane_runtime'))
stack.enter_context(mock.patch.object(R,'validate_device_release_payload'))
def test_normal_release_and_rollback_use_versioned_hash_and_legacy_stays_strict(self):
original = samples_fixture();before = evidence_fixture(original);current = reorder(original)
with ExitStack() as stack:
self.acceptance_stack(stack)
stack.enter_context(mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current)))
stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot',return_value={s:v['runtime'] for s,v in current.items()}))
with self.assertRaisesRegex(R.DeployError,'configuration drift'):R.accept_device_release(before,rollback=True)
with redirect_stdout(io.StringIO()):new = R.device_release_r5_mount_order_baseline(before)
with redirect_stdout(io.StringIO()):R.accept_device_release(new,rollback=True)
new['descriptor'] = {'releaseId':'fixture','sourceCommit':'a'*40}
stack.enter_context(mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':new['runtime'][args[-1].split('/')[1].split(':')[0]]['imageId']}]))
with redirect_stdout(io.StringIO()):R.accept_device_release(new)
for version in [True,0,3,'2']:
with self.subTest(version=version),self.assertRaisesRegex(R.DeployError,'version mismatch'):R.accept_device_release({**before,'runtimeFingerprintVersion':version})
def test_preflight_records_v2_for_new_normal_release(self):
with ExitStack() as stack:
for name,value in [('validate_device_release_payload',{}),('device_release_predecessor',None),('collect_exact_files',{}),('component_compose_files',()),('device_release_other_compose_services',{}),('device_release_runtime_snapshot_v2',runtime())]:
stack.enter_context(mock.patch.object(R,name,return_value=value))
for name in ['validate_device_manager_control_plane_runtime','run_healthchecks']:
stack.enter_context(mock.patch.object(R,name))
legacy = stack.enter_context(mock.patch.object(R,'device_release_runtime_snapshot'))
detail = stack.enter_context(mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':{'Config.Env':'a'*64}}))
before = R.preflight_device_release(self.root,R.DEVICE_RELEASE_ENTRIES,'id')
self.assertEqual(before['runtimeFingerprintVersion'],2);legacy.assert_not_called()
self.assertEqual(before['runtimeFieldDigests'],{'device-manager':{'Config.Env':'a'*64}})
detail.assert_called_once_with(before['runtime'])
def test_preflight_and_post_health_dispatch_v2_only_with_exact_identity(self):
old = samples_fixture();before = evidence_fixture(old);current = reorder(old)
with ExitStack() as stack:
self.acceptance_stack(stack)
stack.enter_context(mock.patch.object(R,'device_release_r5_evidence',return_value=before))
stack.enter_context(mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current)))
stack.enter_context(mock.patch.object(R,'healthcheck_compose_service_with_grace'))
stack.enter_context(mock.patch.object(R,'healthcheck_url'))
command = stack.enter_context(mock.patch.object(R.subprocess,'run'))
with redirect_stdout(io.StringIO()):new = R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id'])
self.assertEqual(new['runtimeFingerprintVersion'],2)
# Post-copy acceptance reads the installed v2 descriptor and same real guards.
stack.enter_context(mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload))
with redirect_stdout(io.StringIO()):R.run_healthchecks(self.manifest['component'],self.entries,())
command.assert_not_called()
put(self.payload,R.DEVICE_RELEASE_RECONCILIATION_ENTRY,b'conflict')
with self.assertRaisesRegex(R.DeployError,'versions conflict'):
R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id'],marker_installed=True)
def execute_apply(self,fail=False):
live = self.root/'live';live.mkdir()
for directory in ['inbox','applied','failed','backups','state','tmp']:(self.root/directory).mkdir()
original = samples_fixture();before = evidence_fixture(original);current = reorder(original)
with ExitStack() as stack:
self.acceptance_stack(stack)
for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),('LOCK_DIR',self.root/'lock'),('DEVICE_PLANE_ROOT',live)]:
stack.enter_context(mock.patch.object(R,name,value))
config = {**R.COMPONENTS[self.manifest['component']],'payload_root':live}
stack.enter_context(mock.patch.dict(R.COMPONENTS,{self.manifest['component']:config}))
for name in ['require_root','ensure_layout','validate_artifact_location','healthcheck_compose_service_with_grace']:
stack.enter_context(mock.patch.object(R,name))
stack.enter_context(mock.patch.object(R,'device_release_r5_evidence',return_value=before))
stack.enter_context(mock.patch.object(R,'device_release_drift_sample',side_effect=lambda:copy.deepcopy(current)))
def http(check):
if fail and (live/self.entries[0]).exists():raise R.DeployError('injected post-copy health failure')
stack.enter_context(mock.patch.object(R,'healthcheck_url',side_effect=http))
command = stack.enter_context(mock.patch.object(R.subprocess,'run'))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail:
with self.assertRaises(R.DeployError):R.apply_artifact(self.artifact)
self.assertFalse((live/self.entries[0]).exists())
self.assertFalse(R.load_state(R.STATE_FILE))
self.assertEqual(R.load_state(R.FAILED_STATE_FILE)[0]['rollback_status'],'ok:device-core-release-reconciliation-marker-only')
else:
R.apply_artifact(self.artifact)
self.assertTrue(R.device_release_r5_reconciled(R.device_release_r5_failed_row()))
row = R.load_state(R.STATE_FILE)[0]
archive = R.APPLIED_DIR/row['artifact'];archive.write_bytes(archive.read_bytes()+b'tamper')
with self.assertRaises(R.DeployError):R.device_release_r5_reconciled(R.device_release_r5_failed_row())
command.assert_not_called()
def test_full_v2_apply_rechecks_proof_then_receipt_and_archive_unblock_only_r5(self):self.execute_apply()
def test_full_v2_failed_apply_removes_marker_without_touching_services(self):self.execute_apply(fail=True)
if __name__=='__main__':unittest.main()
@@ -1,359 +0,0 @@
"""Exact metadata transition, effective-config proof and unchanged runtime guards."""
import copy
from contextlib import ExitStack, redirect_stderr, redirect_stdout
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest import mock
from test_device_core_release import R, runtime, fixture, archive
SOURCE = Path(__file__).resolve().parents[1] / 'device-core-deploy'
spec = importlib.util.spec_from_file_location('priority_builder', SOURCE / 'build_network_priority.py')
BUILDER = importlib.util.module_from_spec(spec)
spec.loader.exec_module(BUILDER)
def effective():
return {'name': 'nodedc-device-plane', 'services': {
'device-control-core': {'image': 'nodedc/device-control-core:local', 'networks': {
'device-plane-private': {}, 'device-plane-egress': {}}},
'device-manager': {'image': 'nodedc/device-manager:local', 'environment': {'TOKEN': 'synthetic-secret'},
'networks': {'device-plane-private': {}, 'platform-edge': {}}},
'device-postgres': {'image': 'postgres:17', 'networks': {'device-plane-private': {}}}},
'networks': {'device-plane-private': {'internal': True}, 'device-plane-egress': {},
'platform-edge': {'external': True}}}
def prioritized():
value = effective()
for service in ('device-control-core', 'device-manager'):
value['services'][service]['networks']['device-plane-private']['priority'] = 100
return value
class PriorityTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.live = self.root / 'live'
self.live.mkdir()
identity, data = BUILDER.bundle()
self.artifact = self.root / ('nodedc-' + identity + '.tgz')
self.artifact.write_bytes(data)
work = self.root / 'unpack'
work.mkdir()
self.manifest, self.entries, self.payload = R.load_artifact(self.artifact, work)
def install_files(self):
for entry in self.entries:
path = self.live / entry
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes((self.payload / entry).read_bytes())
def test_deterministic_data_bundle_has_no_runtime_action(self):
self.assertEqual(BUILDER.bundle()[1], self.artifact.read_bytes())
self.assertEqual(self.manifest['component'], 'device-core-network-priority')
self.assertEqual(tuple(self.entries), R.DEVICE_PRIORITY_ENTRIES)
self.assertEqual((self.payload / self.entries[0]).read_bytes(), R.DEVICE_PRIORITY_YAML.encode())
self.assertEqual(R.component_services(self.manifest['component'], self.entries), ())
self.assertEqual(R.component_builds(self.manifest['component'], self.entries), ())
self.assertTrue(R.component_artifact_only(self.manifest['component']))
def test_path_and_service_scope_cannot_grow(self):
for entry in ('docker-compose.device-plane.yml', 'services/device-manager/a.py',
'deployment/other.json', 'secrets/token', 'data/db', '../escape'):
with self.subTest(entry=entry), self.assertRaises(R.DeployError):
R.allowed_payload_path('device-core-network-priority', entry)
for entries in ([], self.entries[:1], [*self.entries, 'services/device-postgres']):
with self.subTest(entries=entries), self.assertRaises(R.DeployError):
R.component_services('device-core-network-priority', entries)
def test_payload_rejects_identity_descriptor_and_yaml_changes(self):
for identity in ('arbitrary-id', 'device-core-network-priority-v1-20260930-001'):
with self.subTest(identity=identity), self.assertRaises(R.DeployError):
R.validate_device_priority_payload(self.payload, self.entries, identity)
descriptor = self.payload / R.DEVICE_PRIORITY_ENTRY
original = descriptor.read_bytes()
changed = json.loads(original)
changed['primaryPriority'] = 200
descriptor.write_text(json.dumps(changed))
with self.assertRaises(R.DeployError):
R.validate_device_priority_payload(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
descriptor.write_bytes(original)
path = self.payload / R.DEVICE_PRIORITY_COMPOSE
path.write_text(path.read_text().replace('priority: 100', 'priority: 0'))
with self.assertRaises(R.DeployError):
R.validate_device_priority_payload(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
def test_effective_config_proves_only_two_priority_changes_without_leaking_values(self):
base = effective()
candidate = prioritized()
saved = copy.deepcopy((base, candidate))
proof = R.device_priority_config_proof(base, candidate)
self.assertEqual((base, candidate), saved)
self.assertNotIn('synthetic-secret', json.dumps(proof))
self.assertEqual(len(proof['baseConfigSha256']), 64)
candidate['services']['device-manager']['networks']['platform-edge']['priority'] = 0
R.device_priority_config_proof(base, candidate)
def test_real_compose220_config_with_null_endpoints_passes_without_changing_raw_digests(self):
fixture = Path(__file__).parent / 'fixtures/device-core-network-priority-compose220/config.json'
value = json.loads(fixture.read_text())
before = copy.deepcopy(value)
self.assertIsNone(value['base']['services']['device-manager']['networks']['platform-edge'])
proof = R.device_priority_config_proof(value['base'], value['candidate'])
self.assertEqual(value, before)
self.assertEqual(proof['baseConfigSha256'], R.device_release_drift_digest(before['base']))
self.assertEqual(proof['candidateConfigSha256'], R.device_release_drift_digest(before['candidate']))
def test_null_endpoint_support_does_not_accept_other_types_or_missing_primary_priority(self):
for value in (False, True, 0, '', [], 'null', {'priority': None}, {'priority': 0.0}, {'priority': False}):
for side in ('base', 'candidate'):
base, candidate = effective(), prioritized()
config = base if side == 'base' else candidate
config['services']['device-manager']['networks']['platform-edge'] = value
with self.subTest(side=side, endpoint=value), self.assertRaises(R.DeployError):
R.device_priority_config_proof(base, candidate)
candidate = prioritized()
candidate['services']['device-manager']['networks']['device-plane-private'] = None
with self.assertRaises(R.DeployError):
R.device_priority_config_proof(effective(), candidate)
def test_null_equivalence_is_local_and_preserves_endpoint_options(self):
base, candidate = effective(), prioritized()
base['services']['device-manager']['networks']['platform-edge'] = None
candidate['services']['device-manager']['networks']['platform-edge'] = {'aliases': ['foreign']}
with self.assertRaises(R.DeployError):
R.device_priority_config_proof(base, candidate)
base, candidate = effective(), prioritized()
candidate['services']['device-postgres']['networks']['device-plane-private'] = None
with self.assertRaises(R.DeployError):
R.device_priority_config_proof(base, candidate)
base, candidate = effective(), prioritized()
for config in (base, candidate):
config['services']['device-manager']['networks']['platform-edge'] = {'aliases': ['unchanged']}
R.device_priority_config_proof(base, candidate)
def test_network_and_nonnetwork_changes_remain_rejected(self):
mutations = (
lambda c: c['services']['device-manager'].update(ports=['8080:80']),
lambda c: c['services']['device-manager']['environment'].update(TOKEN='different'),
lambda c: c['networks']['device-plane-private'].update(internal=False),
lambda c: c['services']['device-postgres'].update(image='other'),
lambda c: c['services']['device-manager']['networks'].update(other={}),
lambda c: c['services']['device-manager']['networks']['platform-edge'].update(priority=100),
lambda c: c['services']['device-manager']['networks']['device-plane-private'].update(priority=True),
lambda c: c['services']['device-manager']['networks']['device-plane-private'].update(aliases=['foreign']),
)
for mutate in mutations:
c = prioritized()
mutate(c)
with self.subTest(candidate=c), self.assertRaises(R.DeployError):
R.device_priority_config_proof(effective(), c)
with self.assertRaises(R.DeployError):
R.device_priority_config_proof(prioritized(), prioritized())
def test_config_reader_never_returns_command_stderr(self):
result = mock.Mock(returncode=1, stdout='', stderr='SECRET=do-not-log')
with mock.patch.object(R, 'compose_base_cmd', return_value=['docker', 'compose']), \
mock.patch.object(R.subprocess, 'run', return_value=result), \
self.assertRaises(R.DeployError) as caught:
R.device_priority_config(self.payload / R.DEVICE_PRIORITY_COMPOSE)
self.assertNotIn('SECRET', str(caught.exception))
def test_activation_needs_both_files_and_unique_matching_archive_receipt(self):
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
mock.patch.object(R, 'APPLIED_DIR', self.root), mock.patch.object(R, 'load_state', return_value=[]):
self.assertEqual(R.device_priority_compose_files(('base.yml',)), ('base.yml',))
self.install_files()
with self.assertRaisesRegex(R.DeployError, 'unique canonical receipt'):
R.device_priority_compose_files(('base.yml',))
row = {'id': R.DEVICE_PRIORITY_ID, 'component': 'device-core-network-priority', 'status': 'ok',
'sha256': R.sha256_file(self.artifact), 'artifact': self.artifact.name}
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
mock.patch.object(R, 'APPLIED_DIR', self.root), \
mock.patch.object(R, 'load_state', side_effect=lambda p: [row] if p == R.STATE_FILE else []):
self.assertEqual(R.device_priority_compose_files(('base.yml',)),
('base.yml', self.live / R.DEVICE_PRIORITY_COMPOSE))
(self.live / R.DEVICE_PRIORITY_ENTRY).unlink()
with self.assertRaisesRegex(R.DeployError, 'incomplete'):
R.device_priority_compose_files(('base.yml',))
def test_uncertain_priority_rollback_blocks_later_release_even_without_marker(self):
row = {'component': 'device-core-network-priority', 'started_apply': True, 'rollback_status': 'failed:DeployError'}
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), \
mock.patch.object(R, 'load_state', return_value=[row]), \
self.assertRaisesRegex(R.DeployError, 'reconciliation'):
R.device_priority_compose_files(('base.yml',))
def test_activation_rejects_duplicate_or_failed_receipt_and_altered_archive(self):
self.install_files()
row = {'id': R.DEVICE_PRIORITY_ID, 'component': 'device-core-network-priority', 'status': 'ok',
'sha256': R.sha256_file(self.artifact), 'artifact': self.artifact.name}
for rows in ([row, row], [{**row, 'status': 'failed'}], [{**row, 'sha256': '0' * 64}]):
with self.subTest(rows=rows), mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), \
mock.patch.object(R, 'TMP_DIR', self.root), mock.patch.object(R, 'APPLIED_DIR', self.root), \
mock.patch.object(R, 'load_state', side_effect=lambda p: rows if p == R.STATE_FILE else []), \
self.assertRaises(R.DeployError):
R.device_priority_compose_files(('base.yml',))
def test_normal_release_executor_uses_accepted_override_without_expanding_scope(self):
self.install_files()
row = {'id': R.DEVICE_PRIORITY_ID, 'component': 'device-core-network-priority', 'status': 'ok',
'sha256': R.sha256_file(self.artifact), 'artifact': self.artifact.name}
original = R.component_compose_files
def files(component, **kwargs):
if component == 'device-plane':
return (self.live / 'base.yml',)
return original(component, **kwargs)
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
mock.patch.object(R, 'APPLIED_DIR', self.root), mock.patch.object(R, 'component_compose_files', side_effect=files), \
mock.patch.object(R, 'load_state', side_effect=lambda p: [row] if p == R.STATE_FILE else []), \
mock.patch.object(R.subprocess, 'run') as command:
R.run_device_release_compose(R.DEVICE_RELEASE_SERVICES, R.DEVICE_RELEASE_ENTRIES)
calls = command.call_args_list
self.assertEqual(len(calls), 2)
up = calls[0].args[0]
index = up.index('up')
self.assertEqual(up[index:], ['up', '-d', '--force-recreate', '--pull', 'never', '--no-build', '--no-deps',
*R.DEVICE_RELEASE_SERVICES])
self.assertEqual(up[index - 2:index], ['-f', str(self.live / R.DEVICE_PRIORITY_COMPOSE)])
self.assertEqual(calls[1].args[0], [*up[:index], 'ps'])
def test_baseline_proves_archive_receipt_and_live_tree(self):
d = fixture(self.live, number=12, sha='b2660df9e26afe977bfa62efd35a8397eac4898b')
a = self.root / 'baseline.tgz'
archive(self.live, a, d)
sha = R.sha256_file(a)
row = {'id': R.DEVICE_PRIORITY_BASELINE, 'component': 'device-core-release',
'status': 'ok', 'sha256': sha, 'artifact': a.name}
with mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live), mock.patch.object(R, 'TMP_DIR', self.root), \
mock.patch.object(R, 'DEVICE_PRIORITY_BASELINE_SHA', sha), mock.patch.object(R, 'APPLIED_DIR', self.root), \
mock.patch.object(R, 'load_state', side_effect=lambda p: [row] if p == R.STATE_FILE else []):
expected = R.device_priority_baseline()
self.assertIn(R.DEVICE_RELEASE_ENTRY, expected)
(self.live / 'services/device-manager/server/app.mjs').write_text('changed')
with self.assertRaisesRegex(R.DeployError, 'source drift'):
R.device_priority_baseline()
def prepare_preflight(self, stack):
stack.enter_context(mock.patch.object(R, 'DEVICE_PLANE_ROOT', self.live))
stack.enter_context(mock.patch.object(R, 'device_priority_baseline', return_value={'app': 'hash'}))
stack.enter_context(mock.patch.object(R, 'run_healthchecks'))
stack.enter_context(mock.patch.object(R, 'validate_device_manager_control_plane_runtime'))
stack.enter_context(mock.patch.object(R, 'device_release_runtime_snapshot_v2', return_value=runtime()))
digests = {s: {'HostConfig.NetworkMode': R.device_release_drift_digest('nodedc-device-plane-private')}
for s in R.DEVICE_RELEASE_SERVICES}
digests['device-control-core']['networks'] = R.device_release_drift_digest(['nodedc-device-plane-egress', 'nodedc-device-plane-private'])
digests['device-manager']['networks'] = R.device_release_drift_digest(['nodedc-device-plane-private', 'nodedc-platform_edge'])
fields = stack.enter_context(mock.patch.object(R, 'device_release_capture_field_digests', return_value=digests))
stack.enter_context(mock.patch.object(R, 'device_priority_config', side_effect=lambda override=None: prioritized() if override else effective()))
stack.enter_context(mock.patch.object(R, 'component_compose_files', return_value=()))
stack.enter_context(mock.patch.object(R, 'device_release_other_compose_services', return_value={}))
stack.enter_context(mock.patch.object(R.subprocess, 'run', return_value=mock.Mock(stdout='2.20.3\n')))
return fields
def test_preflight_refuses_primary_switch_and_already_installed_transition(self):
with ExitStack() as stack:
fields = self.prepare_preflight(stack)
before = R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
self.assertEqual(before['composeVersion'], '2.20.3')
fields.return_value['device-manager']['HostConfig.NetworkMode'] = R.device_release_drift_digest('nodedc-platform_edge')
with self.assertRaisesRegex(R.DeployError, 'existing private primary'):
R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
self.install_files()
with self.assertRaisesRegex(R.DeployError, 'initial-only'):
R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
def test_acceptance_requires_unchanged_runtime_and_exact_candidate(self):
with ExitStack() as stack:
self.prepare_preflight(stack)
before = R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
self.install_files()
with redirect_stdout(io.StringIO()):
R.accept_device_priority(before)
changed = runtime()
changed['device-manager']['containerId'] = 'changed'
with mock.patch.object(R, 'device_release_runtime_snapshot_v2', return_value=changed), \
self.assertRaisesRegex(R.DeployError, 'preserved source/runtime'):
R.accept_device_priority(before)
with self.assertRaisesRegex(R.DeployError, 'left activation files'):
R.accept_device_priority(before, rollback=True)
for entry in self.entries:
(self.live / entry).unlink()
with redirect_stdout(io.StringIO()):
R.accept_device_priority(before, rollback=True)
def test_preflight_refuses_an_extra_attached_network(self):
with ExitStack() as stack:
fields = self.prepare_preflight(stack)
fields.return_value['device-manager']['networks'] = R.device_release_drift_digest(
['nodedc-device-plane-private', 'nodedc-platform_edge', 'foreign'])
with self.assertRaisesRegex(R.DeployError, 'network set mismatch'):
R.preflight_device_priority(self.payload, self.entries, R.DEVICE_PRIORITY_ID)
def execute(self, fail=False, rollback_fail=False):
config = {**R.COMPONENTS['device-core-network-priority'], 'payload_root': self.live}
for name in ('inbox', 'applied', 'failed', 'backups', 'state', 'tmp'):
(self.root / name).mkdir()
events = []
before = {'runtime': runtime(), 'baseConfigSha256': 'a' * 64}
with ExitStack() as stack:
for name, value in [('INBOX', self.root / 'inbox'), ('APPLIED_DIR', self.root / 'applied'),
('FAILED_DIR', self.root / 'failed'), ('BACKUPS_DIR', self.root / 'backups'),
('STATE_DIR', self.root / 'state'), ('TMP_DIR', self.root / 'tmp'),
('STATE_FILE', self.root / 'state/applied.jsonl'), ('FAILED_STATE_FILE', self.root / 'state/failed.jsonl'),
('LOCK_DIR', self.root / 'lock'), ('DEVICE_PLANE_ROOT', self.live)]:
stack.enter_context(mock.patch.object(R, name, value))
stack.enter_context(mock.patch.dict(R.COMPONENTS, {'device-core-network-priority': config}))
for name in ('require_root', 'ensure_layout', 'validate_artifact_location'):
stack.enter_context(mock.patch.object(R, name))
stack.enter_context(mock.patch.object(R, 'preflight_device_priority', return_value=before))
commands = stack.enter_context(mock.patch.object(R.subprocess, 'run', side_effect=AssertionError('no external runtime commands')))
build = stack.enter_context(mock.patch.object(R, 'run_build', side_effect=AssertionError('no build')))
def accept(value, rollback=False):
events.append('rollback' if rollback else 'accept')
self.assertEqual(value, before)
for entry in self.entries:
self.assertEqual((self.live / entry).exists(), not rollback)
if (fail and not rollback) or (rollback_fail and rollback):
raise R.DeployError('injected acceptance failure')
stack.enter_context(mock.patch.object(R, 'accept_device_priority', side_effect=accept))
stack.enter_context(redirect_stdout(io.StringIO()))
stack.enter_context(redirect_stderr(io.StringIO()))
if fail:
with self.assertRaises(R.DeployError):
R.apply_artifact(self.artifact)
else:
R.apply_artifact(self.artifact)
commands.assert_not_called()
build.assert_not_called()
applied, failed = R.load_state(R.STATE_FILE), R.load_state(R.FAILED_STATE_FILE)
return events, applied, failed
def test_real_apply_dispatch_is_metadata_only_and_journals_after_acceptance(self):
events, applied, failed = self.execute()
self.assertEqual(events, ['accept'])
self.assertEqual(len(applied), 1)
self.assertFalse(failed)
self.assertFalse(self.artifact.exists())
def test_real_apply_dispatch_rolls_back_only_new_files(self):
events, applied, failed = self.execute(fail=True)
self.assertEqual(events, ['accept', 'rollback'])
self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'], 'ok:device-core-network-priority-metadata-only')
def test_real_apply_dispatch_retains_failed_rollback(self):
_, applied, failed = self.execute(fail=True, rollback_fail=True)
self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'], 'failed:DeployError')
if __name__ == '__main__':
unittest.main()
@@ -1,178 +0,0 @@
"""Evidence-only r5 reconciliation never installs or starts an application."""
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import copy
import hashlib
import io
import importlib.machinery
import importlib.util
import json
from pathlib import Path
import tempfile
import tarfile
import unittest
from unittest import mock
from test_device_core_release import R, fixture, runtime, put
path=Path(__file__).resolve().parents[1]/'device-core-deploy/build_reconciliation.py'
loader=importlib.machinery.SourceFileLoader('reconciliation_builder',str(path))
spec=importlib.util.spec_from_loader(loader.name,loader);B=importlib.util.module_from_spec(spec);loader.exec_module(B)
class ReconciliationTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup);self.root=Path(self.tmp.name)
self.artifact=self.root/'proof.tgz';self.artifact.write_bytes(B.bundle()[1]);self.work=self.root/'work';self.work.mkdir()
self.manifest,self.entries,self.payload=R.load_artifact(self.artifact,self.work)
def test_deterministic_descriptor_only_has_no_runtime_authority(self):
self.assertEqual(self.artifact.read_bytes(),B.bundle()[1])
self.assertEqual(tuple(self.entries),(R.DEVICE_RELEASE_RECONCILIATION_ENTRY,))
component=self.manifest['component']
self.assertTrue(R.component_artifact_only(component))
self.assertEqual(R.component_services(component,self.entries),())
self.assertEqual(R.component_builds(component,self.entries),())
self.assertEqual(R.component_compose_files(component),())
for rel in ['services/device-manager','deployment/other.json','docker-compose.yml','secrets/key']:
with self.subTest(rel=rel),self.assertRaises(R.DeployError):R.allowed_payload_path(component,rel)
for entries in [[],[R.DEVICE_RELEASE_RECONCILIATION_ENTRY,'services/device-manager']]:
with self.assertRaises(R.DeployError):R.component_services(component,entries)
with mock.patch.object(R,'run_build') as build,mock.patch.object(R,'run_compose') as compose,mock.patch.object(R,'prepare_component_runtime') as prepare:
R.run_component_runtime(component,self.entries,())
build.assert_not_called();compose.assert_not_called();prepare.assert_not_called()
def test_descriptor_cannot_reconcile_another_failure_or_enable_mutation(self):
for key,value in [('failedSha256','f'*64),('mode','restart'),('backupId','elsewhere'),('services',['device-postgres'])]:
d=R.device_release_reconciliation_descriptor();d[key]=value
(self.payload/R.DEVICE_RELEASE_RECONCILIATION_ENTRY).write_text(json.dumps(d))
with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_release_reconciliation_payload(self.payload,self.entries,self.manifest['id'])
def test_journal_ambiguity_and_applied_conflict_fail_closed(self):
expected=R.device_release_r5_failed_row()
for rows in [[],[expected,expected],[{**expected,'rollback_status':'ok:other'}]]:
with self.subTest(rows=len(rows)),mock.patch.object(R,'load_state',return_value=rows),self.assertRaisesRegex(R.DeployError,'journal mismatch'):R.device_release_r5_evidence()
with mock.patch.object(R,'load_state',return_value=[expected]),self.assertRaisesRegex(R.DeployError,'conflicts'):R.device_release_r5_evidence()
def test_unrelated_failed_rollback_cannot_use_this_receipt(self):
row=R.device_release_r5_failed_row();row['id']='unrelated'
self.assertFalse(R.device_release_r5_reconciled(row))
def test_marker_without_applied_receipt_never_unblocks_release(self):
with mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload),mock.patch.object(R,'load_state',return_value=[]),self.assertRaisesRegex(R.DeployError,'lacks.*receipt'):
R.device_release_r5_reconciled(R.device_release_r5_failed_row())
def test_plan_rejects_orphan_marker_before_any_runtime_check(self):
with mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload),mock.patch.object(R,'device_release_r5_evidence') as evidence,self.assertRaisesRegex(R.DeployError,'already exists'):
R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id'])
evidence.assert_not_called()
def test_reconciliation_requires_health_and_exact_restored_runtime_without_build(self):
calls=[]
with ExitStack() as stack:
stack.enter_context(mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root/'live'))
stack.enter_context(mock.patch.object(R,'device_release_r5_evidence',return_value={'fixture':True}))
stack.enter_context(mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')))
accept=stack.enter_context(mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('restored')))
command=stack.enter_context(mock.patch.object(R.subprocess,'run'))
R.preflight_device_release_reconciliation(self.payload,self.entries,self.manifest['id'])
self.assertEqual(calls,['health','restored']);self.assertTrue(accept.call_args.kwargs['rollback']);command.assert_not_called()
def test_existing_health_contract_is_explicit_and_legacy_is_preserved(self):
expected=R.device_release_healthchecks()[0]['expected_json']
self.assertEqual(expected['discoveryIngest'],'enabled')
self.assertEqual(expected['managementApi'],'enabled')
self.assertEqual(expected['commandTransport'],'typed-service-ping-v1')
old=R.component_healthchecks('device-plane',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)[0]['expected_json']
self.assertEqual(old['discoveryIngest'],'disabled');self.assertEqual(old['commandTransport'],'disabled')
with mock.patch.object(R,'healthcheck_compose_service_with_grace'),mock.patch.object(R,'healthcheck_url') as http:
R.run_healthchecks('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
self.assertEqual([c.args[0] for c in http.call_args_list],list(R.device_release_healthchecks()))
def evidence_fixture(self, stack):
failed = self.root/'failed';failed.mkdir()
backups = self.root/'backups';backups.mkdir()
backup = backups/R.DEVICE_RELEASE_R5_BACKUP;backup.mkdir()
source = self.root/'old-source';source.mkdir();fixture(source)
(source/R.DEVICE_RELEASE_ENTRY).unlink()
entries = R.DEVICE_RELEASE_ENTRIES[:-1]
before = {'installedFiles':R.collect_exact_files(source,entries,'fixture')}
(backup/'device-release-before.json').write_text(json.dumps(before))
(backup/'existing-files.txt').write_text('\n'.join(entries)+'\n')
(backup/'missing-files.txt').write_text(R.DEVICE_RELEASE_ENTRY+'\n')
(backup/'manifest.env').write_text('fixture')
(backup/'files.txt').write_text('\n'.join(R.DEVICE_RELEASE_ENTRIES)+'\n')
with tarfile.open(backup/'source-before.tgz','w:gz') as tar:
for entry in entries:tar.add(source/entry,arcname=entry)
failed_archive=failed/R.device_release_r5_failed_row()['artifact'];failed_archive.write_bytes(b'failed-fixture')
stack.enter_context(mock.patch.object(R,'DEVICE_RELEASE_R5_SHA',R.sha256_file(failed_archive)))
stack.enter_context(mock.patch.object(R,'DEVICE_RELEASE_R5_BACKUP_HASHES',{p.name:R.sha256_file(p) for p in backup.iterdir()}))
stack.enter_context(mock.patch.object(R,'FAILED_DIR',failed))
stack.enter_context(mock.patch.object(R,'BACKUPS_DIR',backups))
stack.enter_context(mock.patch.object(R,'TMP_DIR',self.root))
stack.enter_context(mock.patch.object(R,'load_state',side_effect=lambda p:[R.device_release_r5_failed_row()] if p==R.FAILED_STATE_FILE else []))
return backup,failed_archive,before
def test_exact_evidence_checks_bytes_and_source_partition(self):
with ExitStack() as stack:
backup,failed,before=self.evidence_fixture(stack)
self.assertEqual(R.device_release_r5_evidence(),before)
for path in [failed,*(backup/p for p in R.DEVICE_RELEASE_R5_BACKUP_HASHES)]:
saved=path.read_bytes();path.write_bytes(saved+b'tamper')
with self.subTest(path=path.name),self.assertRaises(R.DeployError):R.device_release_r5_evidence()
path.write_bytes(saved)
# Even internally hash-consistent backups must describe the same restored source.
before['installedFiles']['package.json']='f'*64
proof=backup/'device-release-before.json';proof.write_text(json.dumps(before))
with mock.patch.dict(R.DEVICE_RELEASE_R5_BACKUP_HASHES,{'device-release-before.json':R.sha256_file(proof)}),self.assertRaisesRegex(R.DeployError,'source/runtime evidence conflict'):
R.device_release_r5_evidence()
def test_restoration_rejects_wrong_images_config_and_preserved_services(self):
old=runtime();before={'runtime':old,'compose':{},'otherComposeServices':{},'installedFiles':{}}
for service,key,value in [('device-control-core','imageId','sha256:'+'e'*64),('device-manager','runtimeConfigSha256','e'*64),('device-postgres','containerId','c'*64)]:
current=copy.deepcopy(old);current[service][key]=value
with self.subTest(service=service,key=key),mock.patch.object(R,'device_release_runtime_snapshot',return_value=current),self.assertRaises(R.DeployError):
R.accept_device_release(before,rollback=True)
with mock.patch.object(R,'device_release_runtime_snapshot',return_value=old),mock.patch.object(R,'device_release_other_compose_services',return_value={'other':'drift'}),self.assertRaisesRegex(R.DeployError,'unrelated Compose service'):
R.accept_device_release(before,rollback=True)
def test_missing_secret_never_creates_or_repairs_it(self):
secret=self.root/'absent/token'
with mock.patch.object(R,'PLATFORM_DEVICE_CORE_INTERNAL_TOKEN_FILE',secret),mock.patch.object(R.os,'chown') as chown,mock.patch.object(R,'ensure_platform_runtime_secret') as ensure,self.assertRaisesRegex(R.DeployError,'missing'):
R.validate_device_release_hub_secret()
self.assertFalse(secret.parent.exists());chown.assert_not_called();ensure.assert_not_called()
def execute_metadata_apply(self,fail_health=False):
live=self.root/'live';live.mkdir();put(live,'services/device-manager/untouched',b'old')
for directory in ['inbox','applied','failed','backups','state','tmp']:(self.root/directory).mkdir()
config={**R.COMPONENTS['device-core-release-reconciliation'],'payload_root':live}
with ExitStack() as stack:
for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),('LOCK_DIR',self.root/'lock'),('DEVICE_PLANE_ROOT',live)]:
stack.enter_context(mock.patch.object(R,name,value))
stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-release-reconciliation':config}))
for name in ['require_root','ensure_layout','validate_artifact_location','preflight_device_release_reconciliation']:
stack.enter_context(mock.patch.object(R,name))
command=stack.enter_context(mock.patch.object(R.subprocess,'run'))
build=stack.enter_context(mock.patch.object(R,'run_build'))
compose=stack.enter_context(mock.patch.object(R,'run_compose'))
stack.enter_context(mock.patch.object(R,'run_healthchecks',side_effect=R.DeployError('injected health') if fail_health else None))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail_health:
with self.assertRaises(R.DeployError):R.apply_artifact(self.artifact)
else:R.apply_artifact(self.artifact)
command.assert_not_called();build.assert_not_called();compose.assert_not_called()
self.assertEqual((live/'services/device-manager/untouched').read_bytes(),b'old')
self.assertEqual((live/R.DEVICE_RELEASE_RECONCILIATION_ENTRY).exists(),not fail_health)
return R.load_state(R.STATE_FILE),R.load_state(R.FAILED_STATE_FILE)
def test_apply_records_receipt_without_runtime_action(self):
applied,failed=self.execute_metadata_apply()
self.assertEqual(len(applied),1);self.assertFalse(failed)
self.assertEqual(applied[0]['component'],'device-core-release-reconciliation')
def test_failed_reconciliation_removes_only_marker(self):
applied,failed=self.execute_metadata_apply(fail_health=True)
self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release-reconciliation-marker-only')
if __name__=='__main__':unittest.main()
@@ -1,267 +0,0 @@
"""Recurring release boundary, source provenance and exact rollback tests."""
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import hashlib
import importlib.machinery
import importlib.util
import io
import json
from pathlib import Path
import shutil
import tarfile
import tempfile
import unittest
from unittest import mock
loader = importlib.machinery.SourceFileLoader('device_release_runner', str(Path(__file__).with_name('nodedc-deploy')))
spec = importlib.util.spec_from_loader(loader.name, loader)
R = importlib.util.module_from_spec(spec)
loader.exec_module(R)
def put(root, rel, data):
target = root / rel
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
def fixture(root, number=12, sha='a'*40):
files = {'.dockerignore': b'.env\nsecrets\n', 'package.json': b'{}', 'package-lock.json': b'{}',
'services/device-control-core/Dockerfile': b'FROM node:22-alpine\n',
'services/device-manager/Dockerfile': b'FROM node:22-alpine\n',
'services/device-control-core/src/server.mjs': b'fixture',
'services/device-control-core/migrations/001.sql': b'-- fixture',
'services/device-manager/server/app.mjs': b'fixture',
'services/device-manager/dist/index.html': b'<div>fixture</div>'}
for entry in R.DEVICE_RELEASE_ENTRIES[3:6]: files[entry+'/src/index.mjs'] = b'fixture'
digest = hashlib.sha256()
name = b'index.html'; data = files['services/device-manager/dist/index.html']
digest.update(len(name).to_bytes(8,'big')+name+len(data).to_bytes(8,'big')+data)
identity = 'device-core-release-v1-r'+str(number)+'-'+sha
d = {'schemaVersion':'nodedc.device-core.release.v1','repository':'SILVER/NODEDC_DEVICE_CORE',
'repositoryId':38,'branch':'main','sourceCommit':sha,'runId':number,'runNumber':number,
'releaseId':identity,'filesSha256':{k:hashlib.sha256(v).hexdigest() for k,v in files.items()},
'packagedManagerDistSha256':digest.hexdigest(),
'qualification':{'schema':'nodedc.device-core.qualification.v1','status':'qualified','deployed':False,
'sourceCommit':sha,'steps':R.DEVICE_RELEASE_STEPS,'packageLockSha256':hashlib.sha256(b'{}').hexdigest(),
'sources':{}}}
files[R.DEVICE_RELEASE_ENTRY] = json.dumps(d).encode()
for path, value in files.items(): put(root, path, value)
return d
def archive(root, destination, d):
with tarfile.open(destination,'w:gz') as a:
for name, data in [('manifest.env', ('id='+d['releaseId']+'\ncomponent=device-core-release\ntype=app-overlay\n').encode()),
('files.txt', ('\n'.join(R.DEVICE_RELEASE_ENTRIES)+'\n').encode())]:
info=tarfile.TarInfo(name);info.size=len(data);a.addfile(info,io.BytesIO(data))
a.add(root,arcname='payload')
def runtime():
return {s:{'service':s,'containerId':str(i)*64,'imageId':'sha256:'+str(i)*64,
'status':'running','running':True,'health':'healthy','restartCount':0,'runtimeConfigSha256':'f'*64}
for i,s in enumerate(R.DEVICE_RELEASE_INVENTORY,1)}
class ReleaseTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.root=Path(self.tmp.name);self.payload=self.root/'payload';self.payload.mkdir()
self.d=fixture(self.payload);self.a=self.root/'release.tgz';archive(self.payload,self.a,self.d)
def test_real_archive_exact_scope_and_builds(self):
work=self.root/'work';work.mkdir()
manifest, entries, _=R.load_artifact(self.a,work)
self.assertEqual(manifest['id'],self.d['releaseId'])
self.assertEqual(R.component_services('device-core-release',entries),R.DEVICE_RELEASE_SERVICES)
self.assertEqual(len(R.component_builds('device-core-release',entries)),2)
self.assertTrue(R.component_compose_no_deps('device-core-release',entries))
with mock.patch.object(R,'component_compose_files', wraps=R.component_compose_files) as f, mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root):
# New component delegates effective Compose to its existing owner.
R.component_compose_files('device-core-release')
self.assertIn(mock.call('device-plane'),f.call_args_list)
def test_no_partial_or_broad_service_selection(self):
for entries in [None,[],R.DEVICE_RELEASE_ENTRIES[:-1],list(R.DEVICE_RELEASE_ENTRIES)+['services/device-gateway']]:
with self.subTest(entries=entries),self.assertRaises(R.DeployError):R.component_services('device-core-release',entries)
def test_path_boundary_rejects_infrastructure_and_secrets(self):
for rel in ['docker-compose.device-plane.yml','services/device-gateway/src/app.mjs',
'services/device-manager/.env','services/device-manager/secrets/key',
'services/device-control-core/test/a.mjs','../escape','data/db','infra/watch.py',
'services/device-control-core/runtime/cache','services/device-manager/dist/a.pem']:
with self.subTest(rel=rel),self.assertRaises(R.DeployError):R.allowed_payload_path('device-core-release',rel)
def test_identity_and_qualification_cannot_select_another_target(self):
for key,value in [('repository','SILVER/other'),('repositoryId',True),('branch','develop'),
('runId',True),('runNumber',0),('sourceCommit','main'),('services',['device-postgres']),
('packagedManagerDistSha256','f'*64),('qualification',{})]:
d=copy.deepcopy(self.d);d[key]=value;put(self.payload,R.DEVICE_RELEASE_ENTRY,json.dumps(d).encode())
with self.subTest(key=key),self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_payload_tampering_missing_files_and_extra_files(self):
path=self.payload/'services/device-manager/dist/index.html'
old=path.read_bytes();path.write_bytes(old+b'changed')
with self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
path.write_bytes(old);put(self.payload,'services/device-manager/server/extra.mjs',b'new')
with self.assertRaises(R.DeployError):R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_packaged_digest_uses_lexical_paths_including_file_directory_prefixes(self):
files={'favicon.ico':b'icon','favicon/icon.png':b'image','index.html':b'<div>fixture</div>'}
digest=hashlib.sha256()
for name,value in sorted(files.items()):
put(self.payload,'services/device-manager/dist/'+name,value)
self.d['filesSha256']['services/device-manager/dist/'+name]=hashlib.sha256(value).hexdigest()
encoded=name.encode();digest.update(len(encoded).to_bytes(8,'big')+encoded+len(value).to_bytes(8,'big')+value)
self.d['packagedManagerDistSha256']=digest.hexdigest()
put(self.payload,R.DEVICE_RELEASE_ENTRY,json.dumps(self.d).encode())
R.validate_device_release_payload(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
def test_new_schema_or_build_recipe_requires_a_separate_domain(self):
live=self.root/'live';shutil.copytree(self.payload,live)
for rel in ['services/device-control-core/migrations/001.sql','services/device-manager/Dockerfile']:
previous=(live/rel).read_bytes();(live/rel).write_bytes(b'drift')
with mock.patch.object(R,'DEVICE_PLANE_ROOT',live),mock.patch.object(R,'device_release_predecessor',return_value=None),mock.patch.object(R,'validate_device_manager_control_plane_runtime') as runtime_check,self.assertRaisesRegex(R.DeployError,'immutable database/build foundation'):
R.preflight_device_release(self.payload,R.DEVICE_RELEASE_ENTRIES,self.d['releaseId'])
runtime_check.assert_not_called();(live/rel).write_bytes(previous)
def test_predecessor_from_canonical_archive_rejects_stale_or_source_drift(self):
live=self.root/'live';shutil.copytree(self.payload,live)
row={'id':self.d['releaseId'],'artifact':self.a.name,'status':'ok','component':'device-core-release','sha256':R.sha256_file(self.a)}
with mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.STATE_FILE else []),mock.patch.object(R,'APPLIED_DIR',self.root),mock.patch.object(R,'DEVICE_PLANE_ROOT',live),mock.patch.object(R,'TMP_DIR',self.root):
newer={'runNumber':13,'sourceCommit':'b'*40}
self.assertEqual(R.device_release_predecessor(newer)['releaseId'],self.d['releaseId'])
for value in [{'runNumber':12,'sourceCommit':'b'*40},{'runNumber':13,'sourceCommit':'a'*40}]:
with self.assertRaises(R.DeployError):R.device_release_predecessor(value)
put(live,'services/device-manager/server/drift.mjs',b'changed')
with self.assertRaisesRegex(R.DeployError,'differs'):R.device_release_predecessor(newer)
def test_failed_rollback_blocks_later_release(self):
row={'component':'device-core-release','started_apply':True,'rollback_status':'failed:RuntimeError'}
with mock.patch.object(R,'load_state',side_effect=lambda p:[row] if p==R.FAILED_STATE_FILE else []),self.assertRaisesRegex(R.DeployError,'reconciliation'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_orphan_descriptor_never_becomes_accepted_predecessor(self):
with mock.patch.object(R,'load_state',return_value=[]),mock.patch.object(R,'DEVICE_PLANE_ROOT',self.payload),self.assertRaisesRegex(R.DeployError,'no canonical'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_initial_predecessor_is_required(self):
with mock.patch.object(R,'load_state',return_value=[]),mock.patch.object(R,'DEVICE_PLANE_ROOT',self.root/'missing'),self.assertRaisesRegex(R.DeployError,'journal mismatch'):
R.device_release_predecessor({'runNumber':13,'sourceCommit':'b'*40})
def test_rollback_uses_previous_images_without_build_or_registry(self):
before={'runtime':runtime()}; calls=[]
with mock.patch.object(R,'restore_platform_overlay',side_effect=lambda *a:calls.append('source')),mock.patch.object(R.subprocess,'run',side_effect=lambda *a,**k:calls.append(a[0])),mock.patch.object(R,'run_device_release_compose',side_effect=lambda *a:calls.append('compose')),mock.patch.object(R,'run_healthchecks',side_effect=lambda *a:calls.append('health')),mock.patch.object(R,'accept_device_release',side_effect=lambda *a,**k:calls.append('accept')),mock.patch.object(R,'run_build') as build:
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',before,True)
self.assertEqual(calls[0],'source');self.assertEqual(calls[-3:],['compose','health','accept']);build.assert_not_called()
self.assertEqual([x[1:3] for x in calls if isinstance(x,list)],[['image','tag'],['image','tag']])
self.assertEqual(calls[1][-2],before['runtime']['device-control-core']['imageId'])
def test_build_failure_restores_tags_but_does_not_restart_services(self):
with mock.patch.object(R,'restore_platform_overlay'),mock.patch.object(R.subprocess,'run') as command,mock.patch.object(R,'run_device_release_compose') as compose,mock.patch.object(R,'run_healthchecks') as health,mock.patch.object(R,'accept_device_release'):
R.rollback_device_release(self.root,self.root,R.DEVICE_RELEASE_ENTRIES,'stamp',{'runtime':runtime()},False)
self.assertEqual(command.call_count,2);compose.assert_not_called();health.assert_not_called()
def test_acceptance_rejects_preserved_service_recreation_or_new_config(self):
old=runtime();before={'runtime':old,'compose':{},'descriptor':self.d}
for service,key,value in [('device-postgres','containerId','z'*64),('device-manager','runtimeConfigSha256','e'*64),('device-control-core','containerId',old['device-control-core']['containerId'])]:
new=copy.deepcopy(old)
for selected in R.DEVICE_RELEASE_SERVICES:new[selected]['containerId']='c'*64
new[service][key]=value
with self.subTest(service=service,key=key),mock.patch.object(R,'device_release_runtime_snapshot',return_value=new),mock.patch.object(R,'docker_json',side_effect=lambda args,label:[{'Id':old[args[-1].split('/')[1].split(':')[0]]['imageId']}]),self.assertRaises(R.DeployError):R.accept_device_release(before)
def test_compose_never_rebuilds_pulls_or_starts_dependencies(self):
with mock.patch.object(R,'compose_base_cmd',return_value=['docker','compose']),mock.patch.object(R,'component_compose_root',return_value=self.root),mock.patch.object(R.subprocess,'run') as command:
R.run_device_release_compose(R.DEVICE_RELEASE_SERVICES,R.DEVICE_RELEASE_ENTRIES)
cmd=command.call_args_list[0].args[0]
for arg in ['--no-deps','--no-build','--force-recreate']:self.assertIn(arg,cmd)
self.assertEqual(cmd[cmd.index('--pull')+1],'never');self.assertEqual(cmd[-2:],list(R.DEVICE_RELEASE_SERVICES))
def execute_apply(self, *, fail_at=None, failure_message=None):
live=self.root/'live';live.mkdir()
old=fixture(live,number=11,sha='b'*40)
before={'runtime':runtime(),'compose':{},'descriptor':self.d,'otherComposeServices':{},
'installedFiles':R.collect_exact_files(live,R.DEVICE_RELEASE_ENTRIES,'test')}
events=[]
config={**R.COMPONENTS['device-core-release'],'payload_root':live,'compose_root':live}
for directory in ['inbox','applied','failed','backups','state','tmp']:(self.root/directory).mkdir()
compose=live/'compose.yml';compose.write_text('fixture')
def operation(name):
def call(*args,**kwargs):
events.append(name)
if name==fail_at:raise R.DeployError(failure_message or 'injected '+name)
return call
with ExitStack() as stack:
for name,value in [('INBOX',self.root/'inbox'),('APPLIED_DIR',self.root/'applied'),
('FAILED_DIR',self.root/'failed'),('BACKUPS_DIR',self.root/'backups'),
('STATE_DIR',self.root/'state'),('TMP_DIR',self.root/'tmp'),
('STATE_FILE',self.root/'state/applied.jsonl'),('FAILED_STATE_FILE',self.root/'state/failed.jsonl'),
('LOCK_DIR',self.root/'lock'),('DOCKER',Path('/usr/bin/true'))]:
stack.enter_context(mock.patch.object(R,name,value))
stack.enter_context(mock.patch.dict(R.COMPONENTS,{'device-core-release':config}))
for name in ['require_root','ensure_layout','validate_artifact_location']:
stack.enter_context(mock.patch.object(R,name))
stack.enter_context(mock.patch.object(R,'component_compose_files',return_value=(compose,)))
stack.enter_context(mock.patch.object(R,'preflight_device_release',return_value=before))
for name,label in [('run_build','build'),('run_device_release_compose','compose'),('run_healthchecks','health')]:
stack.enter_context(mock.patch.object(R,name,side_effect=operation(label)))
def acceptance(*args,**kwargs):
if kwargs.get('rollback'):
events.append('rollback-accept')
self.assertEqual(R.collect_exact_files(live,R.DEVICE_RELEASE_ENTRIES,'restored'),before['installedFiles'])
else:operation('accept')()
stack.enter_context(mock.patch.object(R,'accept_device_release',side_effect=acceptance))
stack.enter_context(mock.patch.object(R.subprocess,'run',side_effect=operation('tag')))
stack.enter_context(redirect_stdout(io.StringIO()));stack.enter_context(redirect_stderr(io.StringIO()))
if fail_at:
with self.assertRaises(R.DeployError):R.apply_artifact(self.a)
else:R.apply_artifact(self.a)
applied=R.load_state(R.STATE_FILE);failed=R.load_state(R.FAILED_STATE_FILE)
return events,applied,failed
def test_apply_journals_success_only_after_acceptance(self):
events,applied,failed=self.execute_apply()
self.assertEqual(events,['build','compose','health','accept'])
self.assertEqual(len(applied),1);self.assertFalse(failed)
self.assertEqual(applied[0]['sha256'],R.sha256_file(self.root/'applied/release.tgz'))
self.assertFalse(self.a.exists())
def test_failed_build_preserves_runtime_and_restores_source_and_tags(self):
events,applied,failed=self.execute_apply(fail_at='build')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release')
self.assertEqual(events,['build','tag','tag','rollback-accept'])
def test_failed_acceptance_rolls_back_before_failure_journal(self):
events,applied,failed=self.execute_apply(fail_at='accept')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release')
self.assertEqual(events,['build','compose','health','accept','tag','tag','compose','health','rollback-accept'])
def test_drift_details_survive_rollback_in_the_canonical_failed_receipt(self):
fields={'HostConfig':{'NetworkMode':'private'},'Config':{'Env':['TOKEN=private-value']},'Mounts':[],'networks':['private','edge']}
previous=R.device_release_field_digests(fields)
fields['HostConfig']['NetworkMode']='edge'
current=R.device_release_field_digests(fields)
before={'runtime':runtime(),'runtimeFieldDigests':{'device-manager':previous}}
with mock.patch.object(R,'device_release_capture_field_digests',return_value={'device-manager':current}):
message=R.device_release_runtime_drift_message(before,runtime(),'device-manager')
events,applied,failed=self.execute_apply(fail_at='accept',failure_message=message)
self.assertFalse(applied)
self.assertEqual(failed[0]['rollback_status'],'ok:device-core-release')
self.assertEqual(failed[0]['message'],message)
self.assertIn('HostConfig.NetworkMode',message)
self.assertNotIn('private-value',json.dumps(failed))
self.assertEqual(events[-1],'rollback-accept')
def test_persistent_health_failure_is_reconciliation_required(self):
events,applied,failed=self.execute_apply(fail_at='health')
self.assertFalse(applied);self.assertEqual(failed[0]['rollback_status'],'failed:DeployError')
self.assertNotIn('rollback-accept',events)
def test_health_checks_selected_and_preserved_services(self):
with mock.patch.object(R,'healthcheck_compose_service_with_grace') as check,mock.patch.object(R,'healthcheck_url'),mock.patch.object(R,'component_healthchecks',return_value=[]):
R.run_healthchecks('device-core-release',R.DEVICE_RELEASE_ENTRIES,R.DEVICE_RELEASE_SERVICES)
self.assertEqual([x.args[1] for x in check.call_args_list],list(R.DEVICE_RELEASE_INVENTORY))
if __name__=='__main__':unittest.main()
@@ -1,110 +0,0 @@
"""Retain the failing configuration difference without weakening its gate."""
import copy
import json
import unittest
from unittest import mock
from test_device_core_release import R, runtime
def fields():
return {"HostConfig": {"NetworkMode": "private", "ReadonlyRootfs": True,
"Mounts": [{"Type": "bind", "Source": "/secret-a", "Target": "/a", "ReadOnly": True},
{"Type": "bind", "Source": "/data-b", "Target": "/b", "ReadOnly": False}]},
"Config": {"Env": ["SECRET=synthetic-value-never-log"], "User": "1000",
"Cmd": ["node", "app.mjs"], "Entrypoint": None,
"WorkingDir": "/app", "ExposedPorts": {"18122/tcp": {}}},
"Mounts": [], "networks": ["private", "edge"]}
class RuntimeEvidenceTests(unittest.TestCase):
def observations(self, value=None):
value = value or fields()
rows = runtime()
samples = {}
for service, row in rows.items():
row["runtimeConfigSha256"] = R.device_release_drift_digest(R.device_release_mounts_v2(value))
samples[service] = {"runtime": copy.deepcopy(row), "fields": copy.deepcopy(value)}
return rows, samples
def test_capture_is_hash_only_and_does_not_change_normalized_fingerprint(self):
rows, samples = self.observations()
original = copy.deepcopy(samples)
with mock.patch.object(R, "device_release_drift_sample", return_value=samples):
result = R.device_release_capture_field_digests(rows)
self.assertEqual(samples, original)
encoded = json.dumps(result)
for private in ("synthetic-value-never-log", "/secret-a", "/data-b", "18122/tcp"):
self.assertNotIn(private, encoded)
self.assertIn("Config.Env", result["device-manager"])
self.assertEqual(result["device-manager"]["Config.Env"], R.device_release_drift_digest(fields()["Config"]["Env"]))
def test_unstable_generation_image_and_fields_are_rejected(self):
for kind in ("containerId", "imageId", "configuration"):
rows, samples = self.observations()
if kind == "configuration":
samples["device-manager"]["fields"]["HostConfig"]["ReadonlyRootfs"] = False
else:
samples["device-manager"]["runtime"][kind] = "changed"
with self.subTest(kind=kind), mock.patch.object(R, "device_release_drift_sample", return_value=samples):
with self.assertRaisesRegex(R.DeployError, "changed while capturing"):
R.device_release_capture_field_digests(rows)
def test_unknown_inventory_is_rejected(self):
rows, samples = self.observations()
samples.pop("device-manager")
with mock.patch.object(R, "device_release_drift_sample", return_value=samples):
with self.assertRaisesRegex(R.DeployError, "inventory changed"):
R.device_release_capture_field_digests(rows)
def test_mount_order_has_same_evidence_but_mount_options_do_not(self):
a = fields(); b = copy.deepcopy(a); b["HostConfig"]["Mounts"].reverse()
digest = lambda f: R.device_release_field_digests(R.device_release_mounts_v2(f))
self.assertEqual(digest(a), digest(b))
b["HostConfig"]["Mounts"][0]["ReadOnly"] = True
self.assertNotEqual(digest(a), digest(b))
def test_mismatch_remains_rejected_and_reports_only_changed_field_hashes(self):
old, _ = self.observations()
value = fields(); value["HostConfig"]["NetworkMode"] = "edge"
current, samples = self.observations(value)
before = {"runtimeFingerprintVersion": 2, "runtime": old,
"runtimeFieldDigests": {s: R.device_release_field_digests(R.device_release_mounts_v2(fields())) for s in old}}
# Only the recreated Manager differs; preserved services remain exact.
current = copy.deepcopy(old); current["device-manager"] = samples["device-manager"]["runtime"]
samples = {s: {"runtime": current[s], "fields": value if s == "device-manager" else fields()} for s in current}
with mock.patch.object(R, "device_release_runtime_snapshot_v2", return_value=current), \
mock.patch.object(R, "device_release_drift_sample", return_value=samples):
with self.assertRaises(R.DeployError) as caught:
R.accept_device_release(before, rollback=True)
message = str(caught.exception)
report = json.loads(message.split("; field_evidence=", 1)[1])
self.assertEqual(report["evidence"], "captured")
self.assertEqual([x["path"] for x in report["changedFields"]], ["HostConfig.NetworkMode"])
self.assertNotEqual(report["expectedSha256"], report["actualSha256"])
self.assertNotIn("synthetic-value-never-log", message)
self.assertNotIn('"edge"', message)
def test_failed_observation_does_not_mask_rejection_or_leak_error(self):
rows, _ = self.observations()
before = {"runtime": rows, "runtimeFieldDigests": {"device-manager": R.device_release_field_digests(fields())}}
with mock.patch.object(R, "device_release_drift_sample", side_effect=OSError("SECRET=cannot-print")):
text = R.device_release_runtime_drift_message(before, rows, "device-manager")
self.assertIn('"evidence":"unavailable"', text)
self.assertNotIn("cannot-print", text)
def test_legacy_snapshot_keeps_exact_failure_and_requires_no_extra_inspect(self):
rows, _ = self.observations()
with mock.patch.object(R, "device_release_drift_sample") as probe:
text = R.device_release_runtime_drift_message({"runtime": rows}, rows, "device-manager")
self.assertEqual(text, "Device Core release runtime configuration drift: device-manager")
probe.assert_not_called()
def test_untrusted_field_name_is_never_emitted(self):
value = fields(); value["HostConfig"]["SECRET=value"] = "sensitive"
with self.assertRaisesRegex(R.DeployError, "field name is invalid"):
R.device_release_field_digests(value)
if __name__ == "__main__":
unittest.main()
@@ -1,9 +1,7 @@
#!/usr/bin/env python3
import importlib.machinery
import importlib.util
import inspect
import json
import stat
import tempfile
import unittest
from pathlib import Path
@@ -29,978 +27,6 @@ RUNNER = load_runner()
class DevicePlaneRegistryTest(unittest.TestCase):
def test_manager_v9_pins_v8_and_host_telemetry_workspace(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V9_PREDECESSOR_PATCH_ID,
"device-manager-release-v8-20260822-039",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V9_CONTROL_CORE_PREDECESSOR_PATCH_ID,
"device-control-core-release-v3-20260822-040",
)
boundaries = RUNNER.expected_device_plane_manager_release_v9_boundaries()
self.assertEqual(
boundaries["telemetryWorkspace"],
"mission-core-compute-module-parity-v1",
)
self.assertEqual(
boundaries["telemetryFreshness"],
"fifteen-seconds-missing-stale-not-unhealthy",
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V9_ENTRIES,
),
("device-manager",),
)
def test_manager_v10_pins_successful_v8_and_control_core_v4(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V10_PREDECESSOR_PATCH_ID,
"device-manager-release-v8-20260822-039",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V10_CONTROL_CORE_PREDECESSOR_PATCH_ID,
"device-control-core-release-v4-20260823-047",
)
boundaries = RUNNER.expected_device_plane_manager_release_v10_boundaries()
self.assertEqual(
boundaries["controlCorePredecessor"]["artifactSha256"],
"4aecceeb8d400fdd3dbec8fc86b151691f389d165e72677f396f8994823b6b5c",
)
self.assertEqual(
boundaries["telemetryWorkspace"],
"mission-core-compute-module-parity-v1",
)
self.assertTrue(
RUNNER.is_device_plane_manager_release_v10_slice(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V10_ENTRIES,
)
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V10_ENTRIES,
),
("device-manager",),
)
def test_manager_v11_pins_v10_and_mission_core_visual_parity(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V11_PREDECESSOR_PATCH_ID,
"device-manager-release-v10-20260823-048",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V11_PREDECESSOR_ARTIFACT_SHA256,
"e6b983a314db4f8c27d89062dfedf5ed0523cc30421170799d181a19e2d85d4c",
)
boundaries = RUNNER.expected_device_plane_manager_release_v11_boundaries()
self.assertEqual(
boundaries["missionCoreReference"],
"compute-modules-workspace-71c8b04",
)
self.assertEqual(
boundaries["telemetryWorkspace"],
"mission-core-compute-module-visual-parity-v2",
)
self.assertEqual(
boundaries["telemetrySurface"],
"borderless-soft-surface-v1",
)
self.assertEqual(
boundaries["telemetryScroll"],
"reset-on-workspace-transition-v1",
)
self.assertTrue(
RUNNER.is_device_plane_manager_release_v11_slice(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V11_ENTRIES,
)
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V11_ENTRIES,
),
("device-manager",),
)
def test_manager_v12_pins_v11_and_adaptive_telemetry_graphs(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V12_PREDECESSOR_PATCH_ID,
"device-manager-release-v11-20260823-049",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V12_PREDECESSOR_ARTIFACT_SHA256,
"c1e2056b50bfbb0d03d077461d0c27cc56cc52967c3f5620be14871c8a6d5cf0",
)
boundaries = RUNNER.expected_device_plane_manager_release_v12_boundaries()
self.assertEqual(
boundaries["telemetryWorkspace"],
"mission-core-compute-module-adaptive-window-v3",
)
self.assertEqual(
boundaries["telemetryGraphScale"],
"adaptive-observed-window-explicit-domain-v1",
)
self.assertEqual(
boundaries["telemetryNetworkMissingSemantics"],
"missing-counters-never-zero-v1",
)
self.assertTrue(
RUNNER.is_device_plane_manager_release_v12_slice(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V12_ENTRIES,
)
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V12_ENTRIES,
),
("device-manager",),
)
def test_manager_v13_pins_v12_and_host_inventory_accordion(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V13_PREDECESSOR_PATCH_ID,
"device-manager-release-v12-20260823-050",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V13_PREDECESSOR_ARTIFACT_SHA256,
"1a49839140e5f2e49763d78f24ee47d946e244bcfde15a9c38266e8bd14c0d49",
)
boundaries = RUNNER.expected_device_plane_manager_release_v13_boundaries()
self.assertEqual(
boundaries["hostInventoryComposition"],
"mission-core-compute-host-accordion-v2",
)
self.assertEqual(
boundaries["hostInventoryRow"],
"compact-centered-accordion-v1",
)
self.assertEqual(
boundaries["hostInventoryRelations"],
"host-scoped-endpoint-deployment-service-v1",
)
self.assertEqual(
boundaries["telemetryWorkspace"],
"mission-core-compute-module-adaptive-window-v3",
)
self.assertTrue(
RUNNER.is_device_plane_manager_release_v13_slice(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V13_ENTRIES,
)
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V13_ENTRIES,
),
("device-manager",),
)
def test_control_core_v3_registers_telemetry_contract_slice(self):
predecessor = {
"kind": "release",
"patchId": "device-control-core-release-v2-20260822-038",
"artifactSha256": (
"e2d062b82b022dba662522b5d6e192026ac964d78950d903295ca3cbbc95ab28"
),
}
descriptor = RUNNER.expected_device_plane_control_core_release_descriptor(
"device-control-core-release-v3-20260822-040",
predecessor,
schema_version="v3",
)
self.assertEqual(
descriptor["telemetryTransport"],
"edge-channel-host-telemetry-observed-v1",
)
self.assertEqual(
descriptor["telemetryStorage"],
"device-control-core-postgres-seven-day-retention",
)
self.assertTrue(
RUNNER.is_device_plane_control_core_release_v3_slice(
"device-plane",
RUNNER.DEVICE_PLANE_CONTROL_CORE_RELEASE_V3_ENTRIES,
)
)
def test_control_core_v4_pins_terminal_recovery_046(self):
predecessor = {
"kind": "migration-replay-checkpoint-recovery",
"patchId": (
"device-control-core-migration-replay-checkpoint-recovery-"
"20260822-046"
),
"artifactSha256": (
"46000c76977fb583fc7c9cf74ecf624efd8b404f7b8d0322e0270e7b8ac6e450"
),
}
descriptor = RUNNER.expected_device_plane_control_core_release_descriptor(
RUNNER.DEVICE_PLANE_CONTROL_CORE_RELEASE_V4_PATCH_ID,
predecessor,
schema_version="v4",
)
self.assertEqual(
descriptor["schemaVersion"],
"nodedc.device-plane.device-control-core-release.v4",
)
self.assertEqual(
descriptor["recoveryPredecessor"],
"terminal-applied-046-exact-source-runtime-database",
)
self.assertEqual(
descriptor["databaseSchemaOutcome"],
"migration-017-host-telemetry-table-present",
)
self.assertTrue(
RUNNER.is_device_plane_control_core_release_v4_slice(
"device-plane",
RUNNER.DEVICE_PLANE_CONTROL_CORE_RELEASE_V4_ENTRIES,
)
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_CONTROL_CORE_RELEASE_V4_ENTRIES,
),
("device-control-core",),
)
def test_control_core_v4_health_contract_keeps_typed_commands(self):
checks = RUNNER.component_healthchecks(
"device-plane",
RUNNER.DEVICE_PLANE_CONTROL_CORE_RELEASE_V4_ENTRIES,
("device-control-core",),
)
self.assertEqual(
checks[0]["expected_json"]["commandTransport"],
"typed-service-ping-v1",
)
def test_control_core_v4_telemetry_database_acceptance(self):
result = mock.Mock(
returncode=0,
stdout="true\t19\t2\ttrue\t0\t0\n",
stderr="",
)
with (
mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("a" * 64,),
),
mock.patch.object(
RUNNER.subprocess,
"run",
return_value=result,
),
):
evidence = (
RUNNER.collect_device_plane_control_core_host_telemetry_database_evidence()
)
self.assertTrue(evidence["tablePresent"])
self.assertEqual(evidence["columnCount"], 19)
self.assertEqual(evidence["indexCount"], 2)
self.assertEqual(evidence["expiredSampleCount"], 0)
def test_control_core_v4_telemetry_database_rejects_missing_index(self):
result = mock.Mock(
returncode=0,
stdout="true\t19\t1\ttrue\t0\t0\n",
stderr="",
)
with (
mock.patch.object(
RUNNER,
"device_plane_service_container_ids",
return_value=("a" * 64,),
),
mock.patch.object(
RUNNER.subprocess,
"run",
return_value=result,
),
self.assertRaisesRegex(
RUNNER.DeployError,
"host telemetry database invariant mismatch",
),
):
RUNNER.collect_device_plane_control_core_host_telemetry_database_evidence()
def test_manager_v8_pins_production_v6_and_canonical_ontology_runtime(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V8_PREDECESSOR_PATCH_ID,
"device-manager-release-v6-20260822-035",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V8_PREDECESSOR_ARTIFACT_SHA256,
"193faabe930e2b3f212f8eb45288e39f850ec714528b28881095be654baf9a80",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V8_CONTROL_CORE_PREDECESSOR_PATCH_ID,
"device-control-core-release-v2-20260822-038",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V8_CONTROL_CORE_PREDECESSOR_ARTIFACT_SHA256,
"e2d062b82b022dba662522b5d6e192026ac964d78950d903295ca3cbbc95ab28",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V8_COMPOSE_SHA256,
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V6_COMPOSE_SHA256,
)
boundaries = RUNNER.expected_device_plane_manager_release_v8_boundaries()
self.assertEqual(
boundaries["infrastructureHostProjection"],
"ontology-backed-host-runtime-v1",
)
self.assertEqual(
boundaries["ontologyFoundation"],
"ontology-core-device-foundation-20260822-001",
)
self.assertEqual(boundaries["ontologyCatalogHash"], "229c61c02a790906")
self.assertEqual(
boundaries["assetBinding"],
"temporal-device-asset-binding-v1",
)
self.assertEqual(
boundaries["healthEvidence"],
"ttl-observation-missing-not-unhealthy-v1",
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V8_ENTRIES,
),
("device-manager",),
)
def test_manager_v7_pins_v6_and_live_edge_host_projection(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V7_PREDECESSOR_PATCH_ID,
"device-manager-release-v6-20260822-035",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V7_PREDECESSOR_ARTIFACT_SHA256,
"193faabe930e2b3f212f8eb45288e39f850ec714528b28881095be654baf9a80",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V7_CONTROL_CORE_PREDECESSOR_PATCH_ID,
"device-control-core-release-v2-20260822-036",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V7_CONTROL_CORE_PREDECESSOR_ARTIFACT_SHA256,
"8708cc4b59fa0cd5e9c6e6a7b2654ba01ea60271549167aca2631f94000d3da3",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V7_COMPOSE_SHA256,
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V6_COMPOSE_SHA256,
)
boundaries = RUNNER.expected_device_plane_manager_release_v7_boundaries()
self.assertEqual(
boundaries["infrastructureHostProjection"],
"edge-registration-live-channel-v1",
)
self.assertEqual(
boundaries["ontologyStatus"],
"generic-host-domain-candidate-not-canonical",
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V7_ENTRIES,
),
("device-manager",),
)
def test_manager_v6_pins_034_and_canonical_favicon_boundary(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V6_PREDECESSOR_PATCH_ID,
"device-manager-release-v5-20260822-034",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V6_PREDECESSOR_ARTIFACT_SHA256,
"acc1d2ae2cda66861054826928c25d01a2428e688cc8132a9c381831bf29ab5a",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V6_COMPOSE_SHA256,
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V5_COMPOSE_SHA256,
)
boundaries = RUNNER.expected_device_plane_manager_release_v6_boundaries()
self.assertEqual(boundaries["faviconSet"], "nodedc-adaptive-v1")
self.assertEqual(
boundaries["overviewLayout"],
"mission-core-landing-stage-v1",
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V6_ENTRIES,
),
("device-manager",),
)
def test_manager_v5_pins_033_and_mission_core_overview_layout(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V5_PREDECESSOR_PATCH_ID,
"device-manager-release-v4-20260822-033",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V5_PREDECESSOR_ARTIFACT_SHA256,
"52ba322042f1e4f595bbfea99f8bb35630b15984e0da648dc55348bc9e5b2066",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V5_COMPOSE_SHA256,
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V4_COMPOSE_SHA256,
)
boundaries = RUNNER.expected_device_plane_manager_release_v5_boundaries()
self.assertEqual(
boundaries["overviewLayout"],
"mission-core-landing-stage-v1",
)
self.assertEqual(
RUNNER.component_services(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V5_ENTRIES,
),
("device-manager",),
)
def test_manager_v4_pins_032_and_persistent_white_boundary(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V4_PREDECESSOR_PATCH_ID,
"device-manager-release-v3-20260822-032",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V4_PREDECESSOR_ARTIFACT_SHA256,
"6e0eb3a0a6f19ceab92d46832b93bffbcea21247dbdc2ea50625a51ff460e4ca",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V4_COMPOSE_SHA256,
"e7dff0f5873ad4586bd55946d3db2bb86092a5e149e886d120adc041e056c256",
)
boundaries = RUNNER.expected_device_plane_manager_release_v4_boundaries()
self.assertEqual(boundaries["defaultAccentHex"], "#f5f5f5")
self.assertEqual(
boundaries["presentationDataHostPath"],
"/volume1/docker/nodedc-device-plane/data/device-manager",
)
self.assertEqual(
boundaries["presentationDataContainerPath"],
"/var/lib/nodedc-device-manager",
)
def test_manager_v3_targets_applied_control_core_recovery(self):
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V3_CONTROL_CORE_PREDECESSOR_PATCH_ID,
"device-control-core-release-v2-20260821-030",
)
self.assertEqual(
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V3_CONTROL_CORE_PREDECESSOR_ARTIFACT_SHA256,
"8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454",
)
self.assertEqual(
RUNNER.expected_device_plane_manager_release_v3_boundaries()[
"controlCorePredecessor"
],
{
"patchId": (
"device-control-core-release-v2-20260821-030"
),
"artifactSha256": (
"8459521a662541a5a87cb0188991cdcfb51727427db8ec2a232ce4846bfc3454"
),
},
)
def test_control_core_predecessor_health_is_phase_scoped(self):
with self.assertRaisesRegex(
RUNNER.DeployError,
"preflight phase is invalid",
):
RUNNER.validate_device_plane_control_core_release_predecessor(
Path("/not-used"),
preflight_phase="unknown",
)
plan_source = inspect.getsource(RUNNER.plan_artifact)
self.assertIn(
'validate_device_plane_control_core_release_predecessor(\n'
' payload_dir,\n'
' preflight_phase="plan",',
plan_source,
)
apply_source = inspect.getsource(RUNNER.apply_artifact)
self.assertIn(
'validate_device_plane_control_core_release_predecessor(\n'
' payload_dir,\n'
' preflight_phase="apply",',
apply_source,
)
def test_control_core_preflight_health_excludes_selected_target(self):
descriptor = {
"preservedServices": [
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target",
],
}
with mock.patch.object(
RUNNER,
"healthcheck_compose_service",
) as healthcheck:
services = (
RUNNER.validate_device_plane_control_core_preserved_runtime_health(
descriptor
)
)
self.assertEqual(
services,
(
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target",
),
)
self.assertEqual(
healthcheck.call_args_list,
[
mock.call("device-plane", "device-manager"),
mock.call("device-plane", "device-gateway"),
mock.call("device-plane", "device-postgres"),
mock.call("device-plane", "device-backhaul-target"),
],
)
self.assertNotIn(
mock.call("device-plane", "device-control-core"),
healthcheck.call_args_list,
)
def test_control_core_selected_predecessor_may_be_unhealthy(self):
inventory = {
"schemaVersion": "nodedc.device-plane.runtime-inventory.v1",
"composeProject": "nodedc-device-plane",
"services": [{
"service": "device-control-core",
"containerId": "a" * 64,
"imageId": "sha256:" + "b" * 64,
"status": "running",
"running": True,
"health": "unhealthy",
"restartCount": 4,
}],
}
with mock.patch.object(
RUNNER,
"device_plane_runtime_inventory",
return_value=inventory,
):
selected = (
RUNNER.validate_device_plane_control_core_selected_predecessor_runtime()
)
self.assertEqual(selected["health"], "unhealthy")
def test_control_core_selected_predecessor_may_be_restarting(self):
inventory = {
"schemaVersion": "nodedc.device-plane.runtime-inventory.v1",
"composeProject": "nodedc-device-plane",
"services": [{
"service": "device-control-core",
"containerId": "a" * 64,
"imageId": "sha256:" + "b" * 64,
"status": "restarting",
"running": True,
"health": "starting",
"restartCount": 5,
}],
}
with mock.patch.object(
RUNNER,
"device_plane_runtime_inventory",
return_value=inventory,
):
selected = (
RUNNER.validate_device_plane_control_core_selected_predecessor_runtime()
)
self.assertEqual(selected["status"], "restarting")
self.assertEqual(selected["health"], "starting")
def test_control_core_rollback_accepts_restored_unhealthy_boundary(self):
service_names = (
"device-control-core",
"device-manager",
"device-gateway",
"device-postgres",
"device-backhaul-target",
)
inventory = {
"schemaVersion": "nodedc.device-plane.runtime-inventory.v1",
"composeProject": "nodedc-device-plane",
"services": [
{
"service": service,
"containerId": chr(97 + index) * 64,
"imageId": "sha256:" + str(index + 1) * 64,
"status": "running",
"running": True,
"health": "unhealthy" if index == 0 else "healthy",
"restartCount": index,
}
for index, service in enumerate(service_names)
],
}
restored_id = "f" * 64
restored = {
"Id": restored_id,
"State": {
"Status": "running",
"Running": True,
"Health": {"Status": "unhealthy"},
},
}
preserved_inventory = {
**inventory,
"services": inventory["services"][1:],
}
with (
mock.patch.object(
RUNNER,
"healthcheck_compose_service_with_grace",
) as preserved_health,
mock.patch.object(
RUNNER,
"device_plane_runtime_inventory",
return_value=preserved_inventory,
),
mock.patch.object(
RUNNER,
"compose_service_container_id",
return_value=restored_id,
),
mock.patch.object(
RUNNER,
"inspect_device_plane_container",
return_value=restored,
),
):
accepted = (
RUNNER.accept_device_plane_control_core_rollback_runtime(
inventory
)
)
self.assertEqual(accepted["health"], "unhealthy")
self.assertEqual(accepted["status"], "running")
self.assertEqual(accepted["predecessorHealth"], "unhealthy")
self.assertEqual(
preserved_health.call_args_list,
[
mock.call("device-plane", "device-manager"),
mock.call("device-plane", "device-gateway"),
mock.call("device-plane", "device-postgres"),
mock.call("device-plane", "device-backhaul-target"),
],
)
def test_control_core_post_apply_health_includes_backhaul(self):
with (
mock.patch.object(
RUNNER,
"healthcheck_compose_service_with_grace",
) as healthcheck,
mock.patch.object(
RUNNER,
"component_healthchecks",
return_value=(),
),
mock.patch.object(
RUNNER,
"validate_device_manager_control_plane_runtime",
),
):
RUNNER.run_healthchecks(
"device-plane",
RUNNER.DEVICE_PLANE_CONTROL_CORE_RELEASE_V2_ENTRIES,
("device-control-core",),
)
self.assertEqual(
healthcheck.call_args_list,
[
mock.call("device-plane", "device-control-core"),
mock.call("device-plane", "device-manager"),
mock.call("device-plane", "device-gateway"),
mock.call("device-plane", "device-postgres"),
mock.call("device-plane", "device-backhaul-target"),
],
)
def test_manager_v3_post_apply_uses_private_egress_core_boundary(self):
with (
mock.patch.object(
RUNNER,
"healthcheck_compose_service_with_grace",
),
mock.patch.object(
RUNNER,
"component_healthchecks",
return_value=(),
),
mock.patch.object(
RUNNER,
"validate_device_manager_control_plane_runtime",
) as runtime_acceptance,
):
RUNNER.run_healthchecks(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V3_ENTRIES,
("device-manager",),
)
runtime_acceptance.assert_called_once_with(
require_edge_channel=True,
core_network_mode="private-egress",
)
def test_manager_v4_post_apply_requires_persistent_data(self):
with (
mock.patch.object(
RUNNER,
"healthcheck_compose_service_with_grace",
),
mock.patch.object(
RUNNER,
"component_healthchecks",
return_value=(),
),
mock.patch.object(
RUNNER,
"validate_device_manager_control_plane_runtime",
) as runtime_acceptance,
):
RUNNER.run_healthchecks(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V4_ENTRIES,
("device-manager",),
)
runtime_acceptance.assert_called_once_with(
require_edge_channel=True,
core_network_mode="private-egress",
require_persistent_data=True,
)
def test_manager_v5_post_apply_preserves_persistent_data_gate(self):
with (
mock.patch.object(
RUNNER,
"healthcheck_compose_service_with_grace",
),
mock.patch.object(
RUNNER,
"component_healthchecks",
return_value=(),
),
mock.patch.object(
RUNNER,
"validate_device_manager_control_plane_runtime",
) as runtime_acceptance,
):
RUNNER.run_healthchecks(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V5_ENTRIES,
("device-manager",),
)
runtime_acceptance.assert_called_once_with(
require_edge_channel=True,
core_network_mode="private-egress",
require_persistent_data=True,
)
def test_manager_v6_post_apply_preserves_persistent_data_gate(self):
with (
mock.patch.object(
RUNNER,
"healthcheck_compose_service_with_grace",
),
mock.patch.object(
RUNNER,
"component_healthchecks",
return_value=(),
),
mock.patch.object(
RUNNER,
"validate_device_manager_control_plane_runtime",
) as runtime_acceptance,
):
RUNNER.run_healthchecks(
"device-plane",
RUNNER.DEVICE_PLANE_MANAGER_RELEASE_V6_ENTRIES,
("device-manager",),
)
runtime_acceptance.assert_called_once_with(
require_edge_channel=True,
core_network_mode="private-egress",
require_persistent_data=True,
)
def test_manager_v4_prepare_owns_new_parent_and_managed_data_directory(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-manager-v4-data-",
) as directory:
data_dir = Path(directory) / "data" / "device-manager"
with (
mock.patch.object(
RUNNER,
"DEVICE_PLANE_MANAGER_DATA_DIR",
data_dir,
),
mock.patch.object(RUNNER.os, "chown") as chown,
mock.patch.object(
RUNNER,
"validate_device_plane_manager_persistent_data_metadata",
return_value="uid-1000-gid-1000-mode-0750",
) as validate,
):
result = RUNNER.ensure_device_plane_manager_persistent_data()
self.assertEqual(result, "uid-1000-gid-1000-mode-0750")
self.assertEqual(
chown.call_args_list,
[
mock.call(data_dir.parent, 0, 0),
mock.call(data_dir, 1000, 1000),
],
)
validate.assert_called_once_with()
def test_manager_v4_prepare_preserves_existing_safe_parent_metadata(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-manager-v4-parent-",
) as directory:
data_parent = Path(directory) / "data"
data_parent.mkdir(mode=0o700)
data_dir = data_parent / "device-manager"
with (
mock.patch.object(
RUNNER,
"DEVICE_PLANE_MANAGER_DATA_DIR",
data_dir,
),
mock.patch.object(RUNNER.os, "chown") as chown,
mock.patch.object(
RUNNER,
"validate_device_plane_manager_persistent_data_metadata",
return_value="uid-1000-gid-1000-mode-0750",
),
):
RUNNER.ensure_device_plane_manager_persistent_data()
self.assertEqual(stat.S_IMODE(data_parent.stat().st_mode), 0o700)
chown.assert_called_once_with(data_dir, 1000, 1000)
def test_manager_v4_prepare_rejects_symlink_parent_before_child_creation(self):
with tempfile.TemporaryDirectory(
prefix="nodedc-manager-v4-symlink-",
) as directory:
root = Path(directory)
outside = root / "outside"
outside.mkdir()
data_parent = root / "data"
data_parent.symlink_to(outside, target_is_directory=True)
with mock.patch.object(
RUNNER,
"DEVICE_PLANE_MANAGER_DATA_DIR",
data_parent / "device-manager",
):
with self.assertRaisesRegex(
RUNNER.DeployError,
"persistent data parent is unsafe",
):
RUNNER.ensure_device_plane_manager_persistent_data()
self.assertFalse((outside / "device-manager").exists())
def test_manager_predecessor_health_is_phase_scoped(self):
with self.assertRaisesRegex(
RUNNER.DeployError,
"preflight phase is invalid",
):
RUNNER.validate_device_plane_manager_activation_predecessor(
Path("/not-used"),
preflight_phase="unknown",
)
plan_source = inspect.getsource(RUNNER.plan_artifact)
self.assertIn('preflight_phase="plan"', plan_source)
apply_source = inspect.getsource(RUNNER.apply_artifact)
self.assertIn('preflight_phase="apply"', apply_source)
def test_manager_v3_health_gate_checks_only_preserved_services(self):
descriptor = {
"schemaVersion": (
"nodedc.device-plane.device-manager-release.v3"
),
}
with mock.patch.object(
RUNNER,
"healthcheck_compose_service",
) as healthcheck:
services = (
RUNNER.validate_device_plane_manager_preserved_runtime_health(
descriptor
)
)
self.assertEqual(
services,
("device-control-core", "device-postgres"),
)
self.assertEqual(
healthcheck.call_args_list,
[
mock.call("device-plane", "device-control-core"),
mock.call("device-plane", "device-postgres"),
],
)
self.assertNotIn(
mock.call("device-plane", "device-manager"),
healthcheck.call_args_list,
)
def test_legacy_manager_health_gate_excludes_selected_services(self):
descriptor = {
"schemaVersion": (
"nodedc.device-plane.device-manager-release.v2"
),
}
with mock.patch.object(
RUNNER,
"healthcheck_compose_service",
) as healthcheck:
services = (
RUNNER.validate_device_plane_manager_preserved_runtime_health(
descriptor
)
)
self.assertEqual(services, ("device-postgres",))
healthcheck.assert_called_once_with(
"device-plane",
"device-postgres",
)
def test_registry_has_exact_roots_project_and_stateless_services(self):
component = RUNNER.COMPONENTS["device-plane"]
root = Path("/volume1/docker/nodedc-device-plane")
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,95 +0,0 @@
import hashlib
import importlib.machinery
import importlib.util
import io
import json
import stat
from types import SimpleNamespace
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
ROOT = Path(__file__).resolve().parent
def load(name, path):
loader = importlib.machinery.SourceFileLoader(name, str(path))
spec = importlib.util.spec_from_loader(name, loader)
module = importlib.util.module_from_spec(spec); loader.exec_module(module)
return module
R = load("map_access_runner", ROOT / "nodedc-deploy")
B = load("map_access_builder", ROOT / "build-mission-core-map-access-artifact.py")
class MapAccessTests(unittest.TestCase):
def test_scope_never_selects_docker_or_accepts_host_policy_payload(self):
name = "mission-core-map-access"
self.assertEqual(R.component_services(name, ["access.json"]), ())
self.assertEqual(R.component_builds(name, ["access.json"]), ())
self.assertTrue(R.component_artifact_only(name))
self.assertTrue(R.allowed_payload_path(name, "access.json"))
for path in ("sshd_config", "../sshd_config", "script.py", "docker-compose.yml", ".env", "secrets/key"):
with self.assertRaises(R.DeployError): R.allowed_payload_path(name, path)
def test_deterministic_data_bundle_and_fail_closed_descriptor(self):
raw = B.build("map-access-test-001")
self.assertEqual(raw, B.build("map-access-test-001"))
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
artifact = root / "candidate.tgz"
artifact.write_bytes(raw)
with tarfile.open(fileobj=io.BytesIO(raw)) as archive:
self.assertEqual(archive.getnames(), ["manifest.env", "files.txt", "payload/access.json"])
unpacked = root / "unpacked"
unpacked.mkdir()
manifest, entries, payload = R.load_artifact(artifact, unpacked)
self.assertEqual(manifest["component"], "mission-core-map-access")
self.assertEqual(R.read_map_access_descriptor(payload, entries), "enabled")
for value in ({"schemaVersion":"nodedc.mission-core-map-access.v1","state":"enabled","user":"root"}, {"schemaVersion":"unknown","state":"enabled"}):
(payload/"access.json").write_text(json.dumps(value))
with self.assertRaises(R.DeployError): R.read_map_access_descriptor(payload, entries)
def test_exact_predecessor_idempotence_and_explicit_disable(self):
base = b"AllowTcpForwarding no\n"
with patch.object(R, "MAP_ACCESS_BASE_SHA", hashlib.sha256(base).hexdigest()):
enabled = R.map_access_policy(base, "enabled")
self.assertEqual(enabled, base + R.MAP_ACCESS_APPEND)
self.assertEqual(R.map_access_policy(enabled, "enabled"), enabled)
self.assertEqual(R.map_access_policy(enabled, "disabled"), base)
for drift in (base+b"# external drift\n", enabled+b"# external drift\n", enabled+R.MAP_ACCESS_APPEND):
with self.assertRaises(R.DeployError): R.map_access_policy(drift, "enabled")
def test_effective_policy_may_only_change_exact_user_and_destination(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(R, "TMP_DIR", Path(tmp)), patch.object(R.subprocess,"run") as run:
run.return_value.returncode=0
candidate=Path(tmp)/"candidate";candidate.write_bytes(R.MAP_ACCESS_APPEND)
baseline={"allowtcpforwarding":"no", "permitopen":"any", "passwordauthentication":"yes"}
def effective(config,user,address):
value=dict(baseline)
if str(config)==str(candidate) and user=="dctouch":value.update(allowtcpforwarding="local",permitopen="127.0.0.1:18103")
return value
with patch.object(R,"map_access_effective",side_effect=effective):R.map_access_validate_candidate(b"baseline",candidate)
def broad(config,user,address):
value=effective(config,user,address)
if str(config)==str(candidate):value["permitopen"]="any"
return value
with patch.object(R,"map_access_effective",side_effect=broad), self.assertRaises(R.DeployError):R.map_access_validate_candidate(b"baseline",candidate)
def test_reload_failure_is_routed_to_domain_rollback(self):
with tempfile.TemporaryDirectory() as tmp, patch.object(R,"preflight_map_access",return_value=(b"old",b"new")), patch.object(R,"map_access_replace") as replace, patch.object(R,"map_access_reload",side_effect=R.DeployError("reload")):
with self.assertRaises(R.DeployError):R.apply_map_access(Path(tmp),["access.json"])
replace.assert_called_once_with(b"new")
def test_rollback_restores_exact_policy_and_descriptor(self):
base=b"AllowTcpForwarding no\n"
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp); backup=root/"backup"; backup.mkdir()
(backup/"sshd-config-before").write_bytes(base)
calls=[]
metadata=SimpleNamespace(st_mode=stat.S_IFREG|0o600,st_uid=0)
with patch.object(R,"MAP_ACCESS_BASE_SHA",hashlib.sha256(base).hexdigest()), patch.object(Path,"lstat",return_value=metadata), patch.object(R,"map_access_read_config",side_effect=[base+R.MAP_ACCESS_APPEND,base]), patch.object(R,"map_access_validate_candidate"), patch.object(R,"map_access_replace",side_effect=lambda value:calls.append(("replace",value))), patch.object(R,"map_access_reload",side_effect=lambda:calls.append(("reload",))), patch.object(R,"restore_overlay_source",side_effect=lambda *args:calls.append(("restore",))):
R.rollback_map_access(root,backup,["access.json"],"stamp")
self.assertEqual(calls,[("replace",base),("reload",),("restore",)])
if __name__ == "__main__": unittest.main()
@@ -1,109 +0,0 @@
#!/usr/bin/env python3
import hashlib
import importlib.machinery
import importlib.util
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
PLATFORM_ROOT = SCRIPT_DIR.parent.parent
BUILDER_PATH = SCRIPT_DIR / "build-tasker-attachment-formats-artifact.mjs"
RUNNER_PATH = SCRIPT_DIR / "nodedc-deploy"
RELEASE = "20260829-001"
SOURCE_COMMIT = "f9308539bfe71e4e2359c47ed5c230fa1fb386c9"
EXPECTED_FILES = {
"plane-src/apps/api/plane/settings/common.py",
"plane-src/apps/web/core/components/issues/attachment/attachment-list-item.tsx",
"plane-src/apps/web/core/components/issues/peek-overview/view.tsx",
"plane-src/apps/web/styles/globals.css",
"plane-src/packages/services/src/file/helper.ts",
}
def load_runner():
loader = importlib.machinery.SourceFileLoader("nodedc_tasker_attachment_formats_runner", str(RUNNER_PATH))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
class TaskerAttachmentFormatsArtifactTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary = tempfile.TemporaryDirectory(prefix="nodedc-tasker-attachment-formats-")
cls.root = Path(cls.temporary.name)
cls.builds = []
for index in range(2):
output = cls.root / f"build-{index}"
output.mkdir()
env = os.environ.copy()
env["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(output)
result = subprocess.run(
["node", str(BUILDER_PATH), RELEASE],
cwd=PLATFORM_ROOT,
env=env,
check=True,
capture_output=True,
text=True,
)
cls.builds.append(json.loads(result.stdout))
@classmethod
def tearDownClass(cls):
cls.temporary.cleanup()
def test_artifact_is_reproducible_and_runner_accepted(self):
first = self.builds[0]
second = self.builds[1]
first_path = Path(first["artifact"])
second_path = Path(second["artifact"])
first_bytes = first_path.read_bytes()
self.assertEqual(first_bytes, second_path.read_bytes())
self.assertEqual(first_bytes[4:8], bytes(4))
self.assertEqual(first["sha256"], hashlib.sha256(first_bytes).hexdigest())
self.assertEqual(first["sourceCommit"], SOURCE_COMMIT)
self.assertEqual(first["patchId"], f"tasker-attachment-formats-{RELEASE}")
self.assertEqual(set(first["files"]), EXPECTED_FILES)
with tempfile.TemporaryDirectory() as directory:
manifest, entries, payload = RUNNER.load_artifact(first_path, Path(directory))
self.assertEqual(manifest, {
"id": first["patchId"],
"component": "tasker",
"type": "app-overlay",
})
self.assertEqual(entries, first["files"])
for relative_path in entries:
self.assertTrue((payload / relative_path).is_file())
def test_runner_selects_only_registered_tasker_scope(self):
entries = self.builds[0]["files"]
self.assertEqual(RUNNER.component_services("tasker", entries), ("api", "worker", "beat-worker", "web"))
self.assertEqual(len(RUNNER.component_builds("tasker", entries)), 2)
def test_builder_rejects_an_unexpected_release(self):
env = os.environ.copy()
env["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(self.root / "unexpected-release")
result = subprocess.run(
["node", str(BUILDER_PATH), "20260829-002"],
cwd=PLATFORM_ROOT,
env=env,
capture_output=True,
text=True,
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("usage: build-tasker-attachment-formats-artifact.mjs", result.stderr)
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
import hashlib
import importlib.machinery
import importlib.util
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
PLATFORM_ROOT = SCRIPT_DIR.parent.parent
BUILDER_PATH = SCRIPT_DIR / "build-tasker-comments-route-diagnostics-artifact.mjs"
RUNNER_PATH = SCRIPT_DIR / "nodedc-deploy"
RELEASE = "20260821-002"
def load_runner():
loader = importlib.machinery.SourceFileLoader("nodedc_comments_route_diagnostics_runner", str(RUNNER_PATH))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
class TaskerCommentsRouteDiagnosticsArtifactTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary = tempfile.TemporaryDirectory(prefix="nodedc-comments-route-diagnostics-")
cls.results = []
for index in range(2):
output = Path(cls.temporary.name) / f"build-{index}"
output.mkdir()
env = os.environ.copy()
env["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(output)
result = subprocess.run(
["node", str(BUILDER_PATH), RELEASE],
cwd=PLATFORM_ROOT,
env=env,
check=True,
capture_output=True,
text=True,
)
cls.results.append(json.loads(result.stdout))
@classmethod
def tearDownClass(cls):
cls.temporary.cleanup()
def test_artifact_is_reproducible_and_runner_accepted(self):
first = self.results[0]
second = self.results[1]
first_path = Path(first["artifact"])
second_path = Path(second["artifact"])
first_bytes = first_path.read_bytes()
self.assertEqual(first_bytes, second_path.read_bytes())
self.assertEqual(first_bytes[4:8], bytes(4))
self.assertEqual(first["sha256"], hashlib.sha256(first_bytes).hexdigest())
self.assertEqual(first["sourceCommit"], "0df65d85dd8a04f2d2532235d482864a6f6cfd3d")
self.assertEqual(
first["files"],
["plane-src/apps/api/plane/authentication/views/nodedc_agent_adapter.py"],
)
with tempfile.TemporaryDirectory() as directory:
manifest, entries, payload = RUNNER.load_artifact(first_path, Path(directory))
self.assertEqual(manifest["component"], "tasker")
self.assertEqual(manifest["id"], first["patchId"])
self.assertEqual(entries, first["files"])
self.assertTrue((payload / first["files"][0]).is_file())
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
import hashlib
import importlib.machinery
import importlib.util
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
PLATFORM_ROOT = SCRIPT_DIR.parent.parent
BUILDER_PATH = SCRIPT_DIR / "build-tasker-ops-comments-inventory-artifacts.mjs"
RUNNER_PATH = SCRIPT_DIR / "nodedc-deploy"
RELEASE = "20260821-001"
def load_runner():
loader = importlib.machinery.SourceFileLoader("nodedc_comments_inventory_runner", str(RUNNER_PATH))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
class TaskerOpsCommentsInventoryArtifactTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary = tempfile.TemporaryDirectory(prefix="nodedc-comments-inventory-")
cls.root = Path(cls.temporary.name)
cls.builds = []
for index in range(2):
output = cls.root / f"build-{index}"
output.mkdir()
env = os.environ.copy()
env["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(output)
result = subprocess.run(
["node", str(BUILDER_PATH), RELEASE],
cwd=PLATFORM_ROOT,
env=env,
check=True,
capture_output=True,
text=True,
)
cls.builds.append(json.loads(result.stdout))
@classmethod
def tearDownClass(cls):
cls.temporary.cleanup()
def artifact(self, build_index, component):
return next(item for item in self.builds[build_index]["artifacts"] if item["component"] == component)
def test_artifacts_are_reproducible_and_runner_accepted(self):
self.assertEqual(self.builds[0]["deployOrder"], ["tasker", "ops-agents"])
for component in ("tasker", "ops-agents"):
first = self.artifact(0, component)
second = self.artifact(1, component)
first_path = Path(first["artifact"])
second_path = Path(second["artifact"])
first_bytes = first_path.read_bytes()
self.assertEqual(first_bytes, second_path.read_bytes())
self.assertEqual(first_bytes[4:8], bytes(4))
self.assertEqual(first["sha256"], hashlib.sha256(first_bytes).hexdigest())
with tempfile.TemporaryDirectory() as directory:
manifest, entries, payload = RUNNER.load_artifact(first_path, Path(directory))
self.assertEqual(manifest["component"], component)
self.assertEqual(manifest["id"], first["patchId"])
self.assertEqual(entries, first["files"])
for relative_path in entries:
self.assertTrue((payload / relative_path).is_file())
def test_tasker_overlay_contains_only_comment_audit_runtime(self):
tasker = self.artifact(0, "tasker")
self.assertEqual(tasker["sourceCommit"], "42988b9cbea0a9a0b85a817c2dcb5b396aeda197")
self.assertEqual(
set(tasker["files"]),
{
"plane-src/apps/api/plane/authentication/views/nodedc_agent_adapter.py",
"plane-src/apps/api/plane/urls.py",
},
)
def test_ops_agents_overlay_contains_only_comment_audit_runtime(self):
ops_agents = self.artifact(0, "ops-agents")
self.assertEqual(ops_agents["sourceCommit"], "d4fea6b29001df10444cae2ea95bc8259b22c763")
self.assertEqual(
set(ops_agents["files"]),
{"src/mcp/tool-runtime.ts", "src/routes/tools.ts", "src/tasker/client.ts"},
)
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
import hashlib
import importlib.machinery
import importlib.util
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
PLATFORM_ROOT = SCRIPT_DIR.parent.parent
BUILDER_PATH = SCRIPT_DIR / "build-tasker-ops-comments-read-artifacts.mjs"
RUNNER_PATH = SCRIPT_DIR / "nodedc-deploy"
RELEASE = "20260822-003"
def load_runner():
loader = importlib.machinery.SourceFileLoader("nodedc_comments_read_runner", str(RUNNER_PATH))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
RUNNER = load_runner()
class TaskerOpsCommentsReadArtifactTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temporary = tempfile.TemporaryDirectory(prefix="nodedc-comments-read-")
cls.root = Path(cls.temporary.name)
cls.builds = []
for index in range(2):
output = cls.root / f"build-{index}"
output.mkdir()
env = os.environ.copy()
env["NODEDC_DEPLOY_ARTIFACT_DIR"] = str(output)
result = subprocess.run(
["node", str(BUILDER_PATH), RELEASE],
cwd=PLATFORM_ROOT,
env=env,
check=True,
capture_output=True,
text=True,
)
cls.builds.append(json.loads(result.stdout))
@classmethod
def tearDownClass(cls):
cls.temporary.cleanup()
def artifact(self, build_index, component):
return next(item for item in self.builds[build_index]["artifacts"] if item["component"] == component)
def test_artifacts_are_reproducible_and_runner_accepted(self):
self.assertEqual(self.builds[0]["deployOrder"], ["tasker", "ops-agents"])
for component in ("tasker", "ops-agents"):
first = self.artifact(0, component)
second = self.artifact(1, component)
first_path = Path(first["artifact"])
second_path = Path(second["artifact"])
first_bytes = first_path.read_bytes()
self.assertEqual(first_bytes, second_path.read_bytes())
self.assertEqual(first_bytes[4:8], bytes(4))
self.assertEqual(first["sha256"], hashlib.sha256(first_bytes).hexdigest())
with tempfile.TemporaryDirectory() as directory:
manifest, entries, payload = RUNNER.load_artifact(first_path, Path(directory))
self.assertEqual(manifest["component"], component)
self.assertEqual(manifest["id"], first["patchId"])
self.assertEqual(entries, first["files"])
for relative_path in entries:
self.assertTrue((payload / relative_path).is_file())
def test_tasker_overlay_contains_only_active_comment_reader(self):
tasker = self.artifact(0, "tasker")
self.assertEqual(tasker["sourceCommit"], "7f97c21886ff7dff314db89aa1877e2113e5570b")
self.assertEqual(
tasker["files"],
["plane-src/apps/api/plane/authentication/views/nodedc_agent_adapter.py"],
)
def test_ops_agents_overlay_contains_only_active_comment_reader(self):
ops_agents = self.artifact(0, "ops-agents")
self.assertEqual(ops_agents["sourceCommit"], "6b63049d79eb975372d9f6a01cc32684563678a8")
self.assertEqual(
set(ops_agents["files"]),
{"src/mcp/tool-runtime.ts", "src/routes/tools.ts", "src/tasker/client.ts"},
)
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -1,198 +0,0 @@
# Device Core automatic deployment acceptance
Evidence dates: 2026-09-29/30. Automatic releases r11/r12 and subsequently
r13/r14 were accepted in sequence without manual NAS commands. The latter pair
used accepted network-priority002 under root runner015; see
[the full production acceptance register](NETWORK_PRIORITY_20260930.md). Earlier r9 was rejected by runtime
acceptance and successfully rolled back; its exact cause remains unresolved.
This report concerns Device Core only. B2 multi-client contours are
a separate implementation in `NODEDC_MISSION_CORE_ARNAVI-VPS`.
## Installed authority
Current installed Platform source: `50dc3b1a2cb1191484f5b90de2d2702b14127425`.
Root runner SHA-256:
`7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`.
The operator's promotion on 2026-09-30 returned `verify-install-ok`, Python3.8.15.
This is runner015. Its metadata002 acceptance and subsequent automatic releases
are recorded in [the network-priority report](NETWORK_PRIORITY_20260930.md).
The runner013 details below describe the earlier instrumentation checkpoint.
Bootstrap and runs8/9 used preceding runner012, SHA
`c1301d1072f3d5d39ba422a09847a05a5aad8a753c816d7fb6916d1f1cadd9c6`,
from Platform `f7416bc59a19a9ac53c4f4591eaf50a7f4a41641`.
Controller artifact:
`nodedc-device-core-autodeploy-v1-20260929-001.tgz`, SHA-256
`fe9298baa5f41a35c2705ee9946b730ff2de7d5b5c9b2b8eb1b4cca0bc8ed12b`.
Canonical ledger386 records success at18:35:52Z, with backup
`device-core-autodeploy-device-core-autodeploy-v1-20260929-001-20260929-213533`.
Native timer, private token import, no published ports and preservation of
existing applications were checked by canonical apply.
The temporary Mac token file and NAS enrollment staging were removed after
private import. The NAS retains its root-private working credential and queue.
The observer on the Mac only reads Gitea/SMB and verifies hashes; it has no
stage, plan or apply role in these automatic releases.
## Two consecutive main pushes
Both commits were pushed before the first release completed, without a manual
NAS plan/apply. Build runner1 has capacity1. The controller orders releases by
their durable run identity and invokes the canonical installer itself.
| Run | Device Core source | Artifact SHA-256 | Canonical result |
| --- | --- | --- | --- |
| 8 | `154f243cfde4c9407a28c4d0cb63d29b4cea7c4c` | `2d830958572509df220125a90251d1106abee50e5d891852140e83496ba325f6` | ledger387, success18:56:55Z |
| 9 | `e912e6ffaf7e142afa02254c6c48ac645eb2db63` | `5e678e69b316ceb547112c45ac51cc2294b2f301f2bdc380bcf4347e504739fb` | failed ledger79, clean rollback19:04:04Z |
Each artifact basename is
`nodedc-device-core-release-v1-r<RUN>-<FULL-SOURCE-SHA>.tgz`.
Run8 backup:
`device-core-release-device-core-release-v1-r8-154f243cfde4c9407a28c4d0cb63d29b4cea7c4c-20260929-215159`.
Its archive digest matches the independently retrieved Gitea receipt; the inbox
entry is absent, there is exactly one applied receipt and no failed receipt.
The lifecycle inspector classifies it as `terminal_success`; never replay it.
## Actual interruption and product checks
After staging run8, a subsequent Gitea request failed with `api_unavailable`
at18:51:05Z. The controller retained the candidate and automatically resumed;
its backup was created at18:51:59Z, followed by successful application at18:56:55Z.
No operator command, new commit, timeout expiry or re-enrollment was required.
This verifies one observed network-interruption recovery, not every outage case.
Only Core and Manager are rebuilt/recreated by the normal release domain.
Canonical acceptance checks selected generations/images, exact source and
runtime configuration, health, database/Gateway/backhaul preservation and other
Compose services. A green CI run alone is never treated as deployment.
After run8, the public Manager `/healthz` returned200 with `ok`, `authRequired`
and `deviceCoreConfigured` true. The authenticated browser rendered Device Core
as DC SUDO, opened Devices and retained DCTOUCH and
Robot2B — Moscow Trike Delivery in the owner/project selectors.
## Reproducible normal use and limits
Push to Device Core `main` from any computer. Read qualification in Gitea Actions;
read installation from the canonical applied journal and its archive/backup.
The controller's sanitized `runtime-status.json` is the last completed cycle;
it can still show that cycle while a new build/apply runs. `waiting` after a
release does not mean the installed release disappeared.
Main application updates need no SMB copy, SSH session or per-commit sudo.
Root-runner changes, schema/build foundation migrations, topology changes and
onboarding another repository remain separately registered infrastructure work.
The ordinary release domain intentionally cannot introduce those transitions.
Source tests cover failed/pending CI, duplicate/overlapping runs, changed
pagination, mismatched identities, crash reservation reconciliation and clean or
uncertain rollback. Run9 encountered a real Manager configuration mismatch and passed automatic
rollback. Production was not deliberately crashed for this acceptance. Fleet capacity, B2 auth and contour isolation
are not established by these deployment checks.
## Run9 incident
The canonical failure is `Device Core release runtime configuration drift:
device-manager`, failed ledger79, rollback `ok:device-core-release` at19:04:04Z.
The failed archive is the run9 basename with suffix `.20260929-215803`.
Its digest and backup are verified; it must never be replayed. Run8 remains the
accepted source. The old before snapshot retains only an aggregate configuration
hash, so the exact differing field was not retained before rollback removed the
failed container. Two-network NetworkMode selection is a hypothesis, not a
proven cause. Add per-field hash evidence without changing acceptance semantics
before attempting a forward fix.
The prepared instrumentation keeps fingerprint v2 unchanged and records only
per-field hashes plus the names of changed fields in the canonical failure
receipt. Eight focused evidence cases cover redaction, stable container identity,
mount-order equivalence versus option changes, network mismatch rejection and
legacy snapshots. An additional real apply/rollback dispatcher test confirms
that the diagnostic survives rollback in the failed journal.
Validation:75 Device Core release/bootstrap/recovery tests;75 registry tests
(1 historical skip);170 Device Core artifact tests (17 historical skips);
Python3.8 syntax and diff checks. Runner candidate SHA-256:
`3eefc75591bb08339d79c6a484912d7d6a8881fe8729e966b6f0bf32da21da80`.
Its installation is now confirmed by the operator's exact verify-install receipt.
## Remaining acceptance and handoff
- [x] Controller bootstrap accepted by the canonical installer.
- [x] Run8 passed CI and automatically reached an accepted production release.
- [x] An observed Gitea interruption recovered without operator intervention.
- [x] Run9 failed runtime acceptance and automatically restored accepted run8.
- [x] Candidate013 retains redacted field-level evidence and passed its source tests.
- [x] Install candidate013 through the separate root runner promotion gate.
- [ ] Obtain exact evidence for the Manager mismatch and qualify its correction.
- [x] Accept two ordered automatic application releases with the installed diagnostics (r11, r12).
Candidate013 source is Platform
`d1c5401f52f32cdc4bc4c6db5df8f8d5d6fc7045`, with staged candidate name
`nodedc-deploy.device-core-runtime-evidence-20260929-013`. Its byte count is
1785138 and its digest is recorded above. It preserves the installed runner's
acceptance and rollback rules; it is instrumentation, not a proven incident fix.
The next Device Core release was submitted only after this promotion was
confirmed. Neither the successful bootstrap/run8 nor terminal failed run9 is replayed.
At the 2026-09-30 documentation pass, the Mac's `/Volumes/docker` share was
disconnected. Historical receipts and artifact hashes remain available locally;
this report does not claim a new live NAS inspection at that time. Reconnect the
share, check for newer terminal receipts and verify the staged candidate before
giving the operator the prepared Synology promotion command. The share was then
reconnected: fresh lifecycle inspection confirmed the same387applied/79failed
receipts, run8/run9 archive hashes and backups, no warnings, and the staged
candidate digest. The operator subsequently completed promotion013.
Worker006 is not part of Device Core CI/CD. Its Windows installation and any
unverified Linux guest are irrelevant to this acceptance. A later isolated B2
fleet test is separate work and does not block finishing Synology deployment.
## Qualification continuation on 2026-09-30
Run10, source `893cb6490c1d37df1f9bca19d5c058c304091b87`, pinned the installed
Platform source. It failed in design-install at05:22:29Z with npm ECONNRESET,
before any deploy artifact was produced. Production remained on accepted run8.
This transport failure is distinct from the unexplained run9 Manager mismatch.
Source `70065fb74c449c16094dd4bc05356a8174ec4524` adds at most three frozen
dependency-install attempts for explicit ECONNRESET/ETIMEDOUT/EAI_AGAIN only.
Integrity/auth/lockfile/unclassified/mixed errors and build/test failures still
fail immediately.25local CI tests cover recovery, exhaustion, no false report,
and rejection of non-network failures.
Run11 passed265application/25CI/170artifact tests (17historical skips) and was
automatically accepted at2026-09-30T05:36:45Z, canonical applied ledger388.
Artifact SHA-256 is
`a1c9d201b2f129413b041fb56f2d35f0a05d3936f7ea46116b32929eab343418`;
backup is
`device-core-release-device-core-release-v1-r11-70065fb74c449c16094dd4bc05356a8174ec4524-20260930-083337`.
CI receipt, applied archive hash and backup were independently verified;
lifecycle is terminal_success with no warnings or failed receipt. Only
manifest/release metadata differ from r8's application payload. The new before
snapshot retained per-field hashes and Manager NetworkMode
`nodedc-device-plane-private`. The mismatch did not recur in this attempt.
Public health returned200 and the authenticated UI retained DC SUDO, DCTOUCH and
Robot2B — Moscow Trike Delivery. No user data was changed during the UI check.
Run12/source `b2660df9e26afe977bfa62efd35a8397eac4898b` is the subsequent
documentation push. Its dependency install really
encountered ECONNRESET at05:39:41Z, then retried after five seconds and recovered
without operator action; qualification proceeded to265application/25CI tests,
UI build and artifact contracts. This independently verifies the live transport
recovery path added after run10. It does not establish the cause of run9.
Run12 passed the same265application/25CI/170artifact checks and was automatically
accepted at2026-09-30T05:49:19Z, canonical ledger389. Artifact SHA-256:
`44c62036967c3ed26bd6c82f94e6f4103ccad06f45c383498210b43ad80c9d7c`.
Backup:
`device-core-release-device-core-release-v1-r12-b2660df9e26afe977bfa62efd35a8397eac4898b-20260930-084605`.
Its before snapshot identifies r11 as the predecessor. CI receipt, archive hash,
backup and unique journal row agree; lifecycle is terminal_success, with no
failed receipt or warnings. Public health returned200 with ok/authRequired/
deviceCoreConfigured true after the update. Neither r11 nor r12 needs any
operator replay. Current production source at this checkpoint is b2660df.
These two successful updates establish the automatic delivery path and observed
transport recovery. They do not prove the old intermittent Manager mismatch
fixed. Guards and rollback remain enabled; the installed diagnostics retain the
actual differing fields if it recurs. No topology/normalization workaround was
introduced based on the unproven NetworkMode hypothesis.
@@ -1,233 +0,0 @@
# Stable primary network for recurring Device Core releases
Status: root runner015 and metadata002 were accepted on 2026-09-30.
Two subsequent normal releases, r13 and r14, passed CI, automatic canonical
installation and separate UI/health acceptance. Both used the accepted override
with strict runtime fingerprint v2 and no manual NAS plan/apply.
DCPLATFORM-21 owns this exact registry addition; DCPLATFORM-37 tracks acceptance.
## Reproduced defect and evidence limits
Docker Compose 2.20.3 chooses `HostConfig.NetworkMode` from the first result of
`NetworksByPriority`. Its compose-go 1.18.1 dependency builds that result from a
Go map and sorts only by priority. Equal priorities have no deterministic tie
breaker. Reordering YAML keys is therefore insufficient.
Primary sources:
- [Compose 2.20.3 create.go](https://github.com/docker/compose/blob/v2.20.3/pkg/compose/create.go)
- [Compose dependency pin](https://github.com/docker/compose/blob/v2.20.3/go.mod)
- [compose-go network ordering](https://github.com/compose-spec/compose-go/blob/v1.18.1/types/types.go)
The official Darwin ARM64 Compose 2.20.3 binary was independently checksum
verified as `51cd66bf94923ec8668f1a78c8740abb6cfbe1189da5720a8051a97be527372b`.
Tests used local Docker Desktop Engine29.1.3 through API1.44, an existing pinned
Node image and isolated synthetic services. They used no NAS access, ports,
host mounts, credentials or production data. All test containers/networks were
removed by their exact project after each test; cleanup inventories are empty.
| Check | Result |
| --- | --- |
| Equal priorities, 32 fresh creates | Private primary28; secondary primary4 |
| Explicit private100 / secondary0, 32 fresh creates | Private primary32 |
| Exact candidate override, 16 Core+Manager recreations | All32 containers kept private primary and both attached networks |
| Original private-primary baseline to exact override, 8 Core+Manager recreations | All16 containers retained every canonical v2 configuration field digest |
Local reports and executable reproductions are retained under
`outputs/device-core-stability-20260930/compose-reproducer/` in the NODEDC
workspace: `result.json`, `rollout-result.json`, `fingerprint-result.json` and
their corresponding Python scripts. These are test evidence, never NAS payload.
The accepted NAS plan002 identified Compose `2.20.1-6047-g6817716`. The local Engine is newer
than NAS Docker24.0.2, so these checks do not replace NAS acceptance.
The old r9 receipt retained only an aggregate Manager configuration hash, and
rollback removed the rejected container. This reproduces a real defect capable
of causing that class of rejection; it does not prove which field differed in r9.
The existing r9 failure record remains unresolved historical evidence, not a
reason to replay r9 or waive configuration acceptance.
## Exact registered transition
Component: `device-core-network-priority`, type `app-overlay`, fixed identity
`device-core-network-priority-v1-20260930-002`. Both live and Compose roots are
`/volume1/docker/nodedc-device-plane`. The package permits exactly:
1. `docker-compose.device-release-network-priority.yml`
2. `deployment/device-core-network-priority-v1.json`
The existing base Compose files are unchanged. The new override specifies
private-network priority100 and secondary-network priority0 for Core and Manager.
It does not add/remove a network, change network properties, control the default
gateway or change endpoint settings. In particular, `priority` is not a
`gw_priority` substitute. The first installed primary must already be
`nodedc-device-plane-private` for both services.
This initial installation writes metadata only: no build, pull, restart,
recreation, database change, network creation or secret repair; services are
empty. No new ports, listeners or runtime dependencies are introduced.
Required predecessor is the exact accepted r12 source
`b2660df9e26afe977bfa62efd35a8397eac4898b`, release identity
`device-core-release-v1-r12-b2660df9e26afe977bfa62efd35a8397eac4898b`, archive SHA
`44c62036967c3ed26bd6c82f94e6f4103ccad06f45c383498210b43ad80c9d7c`.
Preflight proves journal/archive identity and every installed release file,
rejects unresolved rollback failures, requires both new paths absent, checks
health and existing secret/mount/network boundaries, then captures all five
Device Plane services and other persistent Compose services.
Canonical `docker compose config --format json` is read before and with the
candidate override. An in-memory comparison proves that ONLY the two primary
priority values change. Environment values and complete config never enter
logs or receipts. Only config hashes, version, file hashes and runtime evidence
are saved in `device-network-priority-before.json` with mode0600.
Runner014/plan001 uncovered a missing parser case: the real Compose2.20.3
`config --format json` output represents bare network attachments as `null`,
and explicit zero-priority attachments as `{}`. Earlier fixture-based config
proof tests used `{}` in both places; actual container tests exercised network
selection/fingerprints but did not call the new effective-config validator.
This was a test coverage gap, not a production topology change.
The corrected proof accepts null as an empty object only at the four known
service/network endpoints in its private comparison copies. Raw before/after
config hashes remain exact. Scalars, arrays, boolean/float/null priority values,
missing primary priority, added networks and changed endpoint properties are
still rejected. Other services and configuration sections are not normalized.
The complete generated config fixture and reproduction commands are committed
under `infra/deploy-runner/fixtures/device-core-network-priority-compose220`.
The fixture test fails on014 with the same message and passes on015.
001 remained staged with no applied/failed receipt or backup. It is superseded
and must not be applied;002 has a new immutable identity and archive digest.
015 rejects001 rather than silently giving that old identity new semantics.
Apply verifies the copied files, effective configuration, original Compose/source,
health and exactly unchanged container identities/images/configuration for all
five services and other Compose projects. It emits `deploy-ok` only after those
checks. Failure removes/restores only the two new metadata paths, verifies the
original config and runtime again, and records the rollback result. An uncertain
rollback blocks further application releases even when marker files are absent.
## Future normal releases and rollback
Only the recurring `device-core-release` domain appends this override to its
effective Compose files. Activation requires both exact files plus a unique
successful canonical receipt and its checked immutable archive; copying a marker
does not activate it. Generic/Engine executors and historical Device Plane
transitions are unchanged.
Normal release acceptance now hashes the complete effective Compose set,
including the accepted override. Build policy, service selection and
`--no-deps --no-build --pull never` remain unchanged. Normal activation and
automatic rollback call the same domain executor, so both receive the override.
Rollback still restores exact prior image IDs without rebuilding.
The runtime fingerprint stays v2: only complete uniquely addressed mount objects
are order-normalized. `HostConfig.NetworkMode`, all its other fields, environment,
mount options and attached network names remain strict. There is no retry-until-
accepted loop and no acceptance of a switched primary network.
## Reproducible qualification and operator sequence
Source checks:
```sh
python3 -m unittest discover -s infra/deploy-runner -p 'test_device_core_*.py'
python3 -m unittest discover -s infra/device-core-deploy -p 'test_*.py'
```
Also run the Platform/Device Plane registry suites and the Device Core
repository's artifact/real HTTP-health tests against this candidate runner.
Twenty focused network-priority tests cover exact payload, deterministic
packaging, configuration-diff boundaries, initial predecessor, secret redaction,
receipt/archive activation, actual release command construction, no-runtime
metadata application and rollback failure. Python3.8 syntax is required.
Promote the reviewed root runner through the separate atomic SHA-pinned gate,
then require its `verify-install`. Build with the committed canonical builder:
```sh
python3 infra/device-core-deploy/build_network_priority.py --output-dir /tmp/device-network-priority
```
Audit and stage the resulting immutable TGZ through SMB, inspect lifecycle,
then review a fresh NAS `plan`. Only the matching new plan authorizes the
already-requested `apply`. No raw Docker/diagnostic shell acceptance follows
`deploy-ok`: the runner owns that gate.
The completed acceptance sequence was: metadata002 → Device Core Platform pin
update in `33cd08c7ab4b1ee87e8c943fca4a30f38c782aae` → automatic r13 →
documentation commit `6ca6738bab22d0fdef714b90c68959363106ee5b` → automatic r14.
For each release, verify CI, canonical receipt/archive/backup, runtime evidence
and separate authenticated UI/public health. On another installation, never
advance main before its exact metadata predecessor transition is accepted.
## Production acceptance register
Installed root runner015 SHA:
`7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`,
Python3.8.15, exact operator `verify-install-ok`. Published source:
`50dc3b1a2cb1191484f5b90de2d2702b14127425` on
`fix/device-core-network-priority-20260930`; Device Core pins the full commit.
Metadata002 was accepted at2026-09-30T09:12:12Z, applied journal390,
archive SHA `5ee23f440ef4a5ef7593c5c35b27b17d93d556453df69e152caee1ddd41e8c7b`.
Backup:
`device-core-network-priority-device-core-network-priority-v1-20260930-002-20260930-121204`.
Independent SMB lifecycle inspection found one applied receipt, matching archive,
existing backup, no failed receipt/warnings and expected absence from inbox.
This proves the registered metadata acceptance; it is not an application release.
Do not restage/replay002 or the superseded001.
Live application acceptance below must follow CI → controller → canonical
archive/ledger/backup → authenticated Device Core UI/public GET health.
No manual NAS commands or shell acceptance are needed after `deploy-ok`.
First release after002: r13/source `33cd08c7ab4b1ee87e8c943fca4a30f38c782aae`.
CI passed265application/25CI/170artifact cases (17historical skips). Canonical
acceptance at09:25:33Z, ledger391, archive SHA
`5fa322be2619ddfe2ad91f9e7d2c9d2cd1b3f8d91d34b7a2e5650eb9b617fc98`, backup
`device-core-release-device-core-release-v1-r13-33cd08c7ab4b1ee87e8c943fca4a30f38c782aae-20260930-122207`.
The before snapshot identifies r12, both private primary networks and accepted
override SHA `01cd551b23ac56eee2577e60f9e1e4ecdcc252cd09c122d73583e3c39c9f2644`.
All77 regular artifact files were compared with r12: only manifest and release
descriptor differ. This qualifies delivery/recreation, not a schema migration.
Independent CI receipt, archive digest, unique canonical record and backup agree;
lifecycle terminal_success without warnings/failed record. Public GET health200,
all three health flags true; authenticated reload retained DC SUDO, DCTOUCH and
Robot2B — Moscow Trike Delivery, with no user/device-data mutation.
Second source `6ca6738bab22d0fdef714b90c68959363106ee5b` records r13 acceptance
and triggers r14 through the ordinary main push path. It changes only the
Device Core deployment documentation. No second root command is involved.
A Mac observation issue occurred after r13: the existing SMB read initially
returned465 zero bytes for the appended row although the controller reported
deployed. Read-only macOS F_NOCACHE/F_RDAHEAD returned the complete391st JSON
record, after which the canonical lifecycle inspector passed. The NAS journal
was not edited and the release was not replayed. The local observer now reads
journals without the client data cache and still rejects malformed rows. A
controller status alone must never substitute for journal/archive/backup proof.
Second release r14 was accepted at2026-09-30T09:38:00Z, ledger392, archive SHA
`385c2fec8fce300cb80a93edfbcb0d537e34755b0ccc35294c0102b3c4a7f724`, backup
`device-core-release-device-core-release-v1-r14-6ca6738bab22d0fdef714b90c68959363106ee5b-20260930-123508`.
CI passed the same265application/25CI/170artifact cases (17historical skips).
The independently downloaded CI receipt/archive agree with the unique canonical
record and existing backup. Lifecycle is terminal_success, with no failed
record/warnings. Its before snapshot identifies r13; effective Compose file
hashes and all diagnostic field hashes equal the r13 before snapshot, including
both private primary networks. Canonical acceptance also checks the recreated
services against those strict before fingerprints before reporting success.
Artifact payload comparison r13/r14 again differs only in manifest and release
descriptor. Public GET health200 and authenticated Devices UI retained DC SUDO,
DCTOUCH and Robot2B — Moscow Trike Delivery after reload.
The two-release gate is complete. No manual source staging, plan/apply, SSH
session or Mac-side deploy authority was used. Mac tools only observed Gitea/SMB
and product health/UI; the independent NAS controller performed installation.
This is measured acceptance of the Device Core delivery path and the reproduced
network-selection correction, not proof of the lost historical r9 field, fleet
load capacity, universal multi-repo onboarding or every possible outage.
Local evidence: `outputs/device-core-stability-20260930/automatic-acceptance/`
contains per-source CI receipts/packages, journal/archive lifecycle checks,
redacted runtime evidence, product checks and cross-release payload/field-digest
comparisons. Platform documentation is published separately from Device Core
main, so recording r14 does not cause an endless chain of documentation releases.
-256
View File
@@ -1,256 +0,0 @@
# Device Core recurring deployment
Status: 2026-09-30. Push-to-main qualification and automatic installation work on
Synology. The outbound controller bootstrap is recorded in ledger386.
Runs11 and12 were accepted automatically in sequence (ledgers388/389), followed
by runs13 and14 (ledgers391/392). Current accepted application source is
`6ca6738bab22d0fdef714b90c68959363106ee5b`. A real npm
ECONNRESET during run12 recovered through the bounded CI install retry.
Earlier run9 failed Manager runtime configuration acceptance and rolled back;
its exact cause remains unresolved. The installed runner retains per-field
diagnostics without weakening acceptance. See [the evidence report](ACCEPTANCE_20260929.md).
An independently reproduced equal-priority Compose network-selection defect now
has a tested correction. Runner014's first metadata plan exposed
a null-endpoint parser case. Corrected runner015 and metadata002 are now accepted;
two subsequent automatic application releases, r13 and r14, passed canonical
installation and separate authenticated UI/public-health acceptance.
See [the exact network-priority transition](NETWORK_PRIORITY_20260930.md).
DCPLATFORM-21 owns the deployment contract; DCPLATFORM-37 tracks acceptance.
## Release domain
The root-owned `infra/deploy-runner/nodedc-deploy` adds `device-core-release`.
Device Core's `infra/ci/package_release.py` creates the only accepted nine-entry,
data-only package. It binds repository 38, main, full source commit, CI run ID and
number, completed qualification, every source file, and the served UI digest.
The served digest uses lexically sorted relative POSIX paths, with 8-byte big-endian
path/data lengths; it excludes source maps independently of the full build digest.
The first deployment proves the exact applied sequence: Edge channel v4 (023),
Control Core v4 (047), Manager v13 (051). Later deployments prove the most recent
normal-release archive, journal and complete installed file map. Stale runs,
repeated source commits, source drift and unresolved rollback failures fail closed.
Historical transition rules are unchanged.
Only `device-control-core` and `device-manager` are built and recreated, using the
existing effective Compose project/files and `--no-deps --no-build --pull never`.
The database, Gateway, backhaul, volumes, existing ports, mounts, identities and
all other persistent Compose services remain unchanged. Migration files and build
recipes must match the installed foundation; changes need a separately reviewed
migration/topology transition. Build jobs never receive installation credentials.
Apply backs up the exact replaced source and old image IDs before writing. Failed
builds restore source and tags without restarting services. Failed activation
restores both old images without rebuilding, recreates only the selected services,
then verifies health, source, configuration and preservation before recording a
successful rollback. A failed rollback blocks further releases for reconciliation.
Successful apply requires new selected container generations, correct images,
healthy dependencies, unchanged topology and source hashes before `deploy-ok`.
## Durable queue foundation
`deployment_queue.py` supplies transactional SQLite ordering and restart recovery.
It has no network or runtime authority. It rejects mismatched run identity, waits
for earlier pending runs, records artifact reservation before installation, skips
duplicate/already superseded sources, and requires a canonical journal/archive
receipt after a crash. It does not discover API pages or prove Git ancestry.
## Outbound controller v1
`gitea_source.py` verifies complete stable API pagination, exact repository/run/job
identity and successful qualification steps. Commit-parent traversal proves
installed → candidate → current main. Downloads accept only the API origin and
Gitea's exact signed `/zip/raw?sig&expires` redirect for the same artifact ID;
the persistent Authorization token is removed from that redirected request.
ZIP entries, uncompressed bounds and release receipt are checked before the
canonical TGZ loader independently validates the release.
`controller.py` refreshes discovery, enforces queue order, stages and plans through
an injected canonical installer, rechecks qualification/ancestry, durably reserves,
then invokes apply. It reconciles canonical journal + archive digest + backup after
success, failure or restart. Missing/contradictory evidence stops further installs;
network errors before reservation preserve the ready queue. Failed CI is skipped,
pending CI retains its place, and completed releases are never installed twice.
`embed_library.py` deterministically places these pure modules inside the reviewed
standalone root runner as ordinary Python in a private lexical scope. There is no
runtime import from SMB, dynamic exec or script payload. Tests compare embedded
bytes against source modules.
The `device-core-autodeploy` bootstrap contains only
`deployment/device-core-autodeploy-v1.json`. Its fixed identity is
`device-core-autodeploy-v1-20260929-001`. The root installer creates exactly two
previously absent native units under `/usr/local/lib/systemd/system`:
`nodedc-device-autodeploy.service` and `.timer`. The timer starts 120s after boot
(or immediately when installed after that point), then 30s after each worker
completion. There is one worker, protected by flock, plus the existing canonical
deployment lock. It opens no listener and requires no Mac to remain online.
Commits from any computer qualify through the same Gitea main branch.
Native systemd, trusted Python/systemctl paths and absence of unit collisions are
preconditions, checked in plan before mutation. No unsupported CFS/Pids controls
or fallback schedulers are assumed. The service invokes only the internal fixed
`/usr/bin/python3 /usr/local/sbin/nodedc-deploy --device-core-autodeploy-tick` entry.
Its worker requires a successful canonical bootstrap receipt/archive before any
release installation, preventing an early timer firing from bypassing acceptance.
The dedicated `read:repository` token is imported from a bounded operator handoff
under `nodedc-deploy/runtime/device-core-autodeploy/enrollment.pending.json` into
`/var/lib/nodedc-device-autodeploy/gitea-read-token` (root:root 0600, directory0700).
It is absent from artifacts/build jobs/logs. The operator staging file is removed
only after private-copy verification. SQLite and private status live in the same
private directory. A sanitized `runtime-status.json` under the bootstrap descriptor
root gives SMB-readable operational status; it never authorizes installation.
Gitea's scope applies to repositories visible to that account; the controller's
API route allowlist is fixed to repository38.
Bootstrap preserves all existing containers and the accepted r7 application tree.
It verifies unit bytes, effective FragmentPath/no drop-ins, enabled/active timer,
private credential metadata, API qualification and health. Rollback removes only
its new units and descriptor; it retains private credentials/queue and all apps.
The activation floor is run8, so historical r5/r6 cannot enter automatic delivery.
The frozen generic `run_compose` function is byte-identical to the previous Engine
canon. Device Core uses its own exact Core+Manager Compose entry with unchanged
`--pull never --no-build --no-deps`, including rollback.
## Activation and acceptance
- Runner012 was promoted and verified as
`c1301d1072f3d5d39ba422a09847a05a5aad8a753c816d7fb6916d1f1cadd9c6`.
- Runner013 subsequently passed operator verify-install as
`3eefc75591bb08339d79c6a484912d7d6a8881fe8729e966b6f0bf32da21da80`.
- Current runner015 passed operator verify-install as
`7a213b7d086225ac9677f52e1bde99dd4b57d77da7c548aadb11793336911cf2`.
Metadata002 was accepted at2026-09-30T09:12:12Z, canonical journal390.
See the network-priority report for its immutable artifact and backup identity.
- The data-only bootstrap built by `build_autodeploy.py` passed fresh plan/apply;
artifact SHA is `fe9298baa5f41a35c2705ee9946b730ff2de7d5b5c9b2b8eb1b4cca0bc8ed12b`.
- NAS imported its root-private credential and removed enrollment staging. The
temporary Mac credential was removed after acceptance. Neither a Mac nor SMB
needs to remain connected for recurring delivery.
- Ordered automatic releases r11/r12 and then r13/r14 were verified against their CI receipts,
archive digests, unique canonical journal rows and backups. Failed-check and
crash/reconciliation tests are source qualification, not a claim that the NAS
was deliberately crashed during production acceptance.
No helper from this directory is executed on NAS or installed by an application
release. User-facing NAS deployment commands remain canonical plan/apply.
## Validation
Run9 was rejected for a Manager runtime configuration difference and rolled back
successfully to run8. Its failed archive must not be replayed. The initial
snapshots retained only an aggregate configuration hash, so the specific field
was not available after rollback removed the failed container.
Diagnostics introduced in runner013 add field hashes to new before snapshots.
Each observation is bound to the checked container/image/configuration identity.
On a mismatch, the canonical failed receipt retains changed field names and
their hashes before the failed generation is removed. Raw environment values,
inspect payloads and external exception text are not included. The v2 comparison,
network/mount semantics, selected services and rollback checks are unchanged.
Old snapshots still use their original aggregate hash. This instrumentation is
not by itself a fix for an as-yet-unidentified configuration difference.
See [live acceptance and the run9 incident](ACCEPTANCE_20260929.md).
```sh
python3 -m unittest discover -s infra/device-core-deploy -p 'test_*.py'
python3 -m unittest discover -s infra/deploy-runner -p test_device_core_release.py
python3 -m unittest discover -s infra/deploy-runner -p test_device_core_runtime_evidence.py
python3 -m unittest discover -s infra/gitea-ci -p 'test_*.py'
```
The Device Core repository's full `infra/deploy-runner` suite must also pass against
the changed canonical runner. Its historical skipped tests remain reported as
skipped, not as live acceptance.
## Initial r5 health-contract incident
The first normal release (run 5, source `67b2ae586399eb1eb7d3a6c074a292e0dbb7b406`)
failed acceptance and rollback acceptance because the new domain selected the old
generic disabled-foundation health expectations. The current preserved foundation
reports discovery and management enabled and `typed-service-ping-v1`. The release
now uses an explicit contract before build, after activation and during rollback.
Legacy transition contracts remain unchanged. Device Core's
`test_device_release_health_contract.py` runs the actual Core and Manager HTTP
handlers against the pinned installer; it fails on the original installer and
passes on this correction, including negative dependency/auth/capability cases.
`build_reconciliation.py` packages one fixed data descriptor for
`device-core-release-reconciliation`. Its plan and apply prove the exact failed
journal/archive, six backup digests, restored sources, old image IDs, runtime
configuration, Compose and preserved services. No build, restart, secret repair,
port or database action exists in this domain. Apply writes only a marker and a
separate canonical receipt; failure removes only that marker. It never rewrites
the original failed journal. Later releases require marker + applied archive +
receipt + original incident evidence. Other rollback failures remain blocked.
The r5 archive must never be replayed. Reconciliation does not install a release
or activate automatic deployment. Only after its live acceptance may a NEW
successful CI run become the next normal-release candidate.
## Read-only diagnosis after rejected reconciliation
Reconciliation001 stopped in plan on the saved Core runtime configuration hash.
No apply ran. The initial rejection alone did not prove harmless ordering or
actual drift. The original backup stores only an aggregate hash, and the legacy
snapshot retains HostConfig.Binds/Mounts order. The diagnostic kept acceptance
unchanged.
`build_drift_audit.py` creates a separate `device-core-release-drift-audit` bundle.
Its only entry is `deployment/device-core-release-r5-drift-audit-v1.json`.
Only canonical `plan` can execute this diagnostic; `apply` refuses before any
application/backup action. It proves original incident evidence and reports all
five service image/hash comparisons over three observations, source/Compose,
health, secret/mount/network boundaries and unrelated Compose preservation.
No raw inspect, environment values or secrets are printed.
The diagnostic searches at most 20,000 exact legacy hash candidates, changing only
the order of observed HostConfig.Binds/Mounts (up to eight each) and NetworkMode
among attached network names. It preserves every other value. A matching old
NetworkMode is reported as a difference, never accepted as harmless. Exhaustion,
changing samples or no match remains unresolved. No diagnostic result creates a
reconciliation marker or bypasses the original acceptance barriers. A subsequent
recovery decision requires the actual NAS report.
## Proven mount-order recovery and runtime fingerprint v2
The NAS audit on 2026-09-29 found an exact old hash preimage for Core and Manager
by reordering only `HostConfig.Mounts` (7 and 3 entries). All three observations
were stable; image IDs, source, topology, health, runtime boundaries and preserved
services matched. The audit output SHA is
`cf687c8bf550fa8c7d1125a3297e04c3d0d81a704b1d6ad17dbddc66470a1189`.
This evidence does not itself create a canonical recovery receipt.
The recurring release domain now records `runtimeFingerprintVersion: 2` in new
before snapshots. Version 2 sorts complete `HostConfig.Mounts` objects, requiring
unique absolute normalized Target paths, and preserves every value and option.
Binds and NetworkMode are unchanged. Old snapshots without a version retain the
legacy comparison; generic Compose and historical transition guards are unchanged.
Docker 24.0.2 registers mount points by unique destination, independently of this
input list order: <https://github.com/moby/moby/blob/v24.0.2/daemon/volumes.go>.
Build the NEW data-only recovery package with:
```sh
python3 infra/device-core-deploy/build_reconciliation.py --version 2 --output-dir /tmp/recovery-v2
```
The fixed identity is `device-core-release-r5-reconciliation-v2-20260929-002`, with
only `deployment/device-core-release-r5-reconciliation-v2.json`. Version 1 remains
strict and byte-identical. V2 proves the old digest with at most 5,041 candidates
per service by permuting only existing HostConfig.Mounts (at most seven); it never
uses the broader diagnostic probe. Three identical observations, old images and
exact preserved service rows are required. After proving equivalence it derives a
v2 baseline and rechecks every existing acceptance guard. Plan, locked preflight
and post-copy acceptance all repeat this proof. Conflicting v1/v2 markers fail.
Apply only writes the marker, backup and canonical journal. Original incident
files and the failed receipt remain unchanged. Marker plus unique applied receipt,
archive digest/identity and original evidence are required to acknowledge r5.
A failure removes only the marker. This package performs no application deployment
and does not activate automatic deployment. Live plan/apply are still required;
the old r5 artifact and the rejected v1 reconciliation must not be replayed.
@@ -1,21 +0,0 @@
{
"baselineArtifactSha256": "7510c7d12e209415970556321a005675d0af61c59497da4226df8ed353184917",
"baselineSourceCommit": "edf69068ec64e3d105d5324d39b8eaeface21215",
"branch": "main",
"firstRunNumber": 8,
"installer": "/usr/local/sbin/nodedc-deploy",
"intervalAfterCompletionSeconds": 30,
"publishedPorts": [],
"releaseComponent": "device-core-release",
"releaseId": "device-core-autodeploy-v1-20260929-001",
"repository": "SILVER/NODEDC_DEVICE_CORE",
"repositoryId": 38,
"scheduler": "native-systemd-timer",
"schemaVersion": "nodedc.device-core.autodeploy.v1",
"services": [
"device-control-core",
"device-manager"
],
"transport": "outbound-https",
"workflow": "ci.yml@refs/heads/main"
}
@@ -1,32 +0,0 @@
#!/usr/bin/env python3
"""Deterministic data-only controller bootstrap; executable policy is in the root runner."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT=Path(__file__).resolve().parent
ENTRY='deployment/device-core-autodeploy-v1.json'
def bundle():
data=(ROOT/'autodeploy-v1.json').read_bytes()
identity=json.loads(data)['releaseId']
members={'manifest.env':('id='+identity+'\ncomponent=device-core-autodeploy\ntype=app-overlay\n').encode(),
'files.txt':(ENTRY+'\n').encode(),'payload/'+ENTRY:data}
output=io.BytesIO()
with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as compressed:
with tarfile.open(fileobj=compressed,mode='w') as archive:
for name,value in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(value)
archive.addfile(info,io.BytesIO(value))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output-dir',required=True,type=Path)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps(dict(artifact=str(path),sha256=hashlib.sha256(data).hexdigest(),id=identity)))
@@ -1,38 +0,0 @@
#!/usr/bin/env python3
"""Build the exact plan-only r5 drift audit; apply is forbidden."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parent
ENTRY = 'deployment/device-core-release-r5-drift-audit-v1.json'
def bundle():
descriptor = (ROOT / 'r5-drift-audit-v1.json').read_bytes()
identity = json.loads(descriptor)['auditId']
members = {
'manifest.env': ('id='+identity+'\ncomponent=device-core-release-drift-audit\ntype=app-overlay\n').encode(),
'files.txt': (ENTRY+'\n').encode(),
'payload/'+ENTRY: descriptor,
}
output=io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for name,data in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(data)
archive.addfile(info,io.BytesIO(data))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-dir',required=True,type=Path)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle();path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps({'artifact':str(path),'sha256':hashlib.sha256(data).hexdigest(),'id':identity}))
@@ -1,45 +0,0 @@
#!/usr/bin/env python3
"""Build the exact data-only Device Core primary-network contract."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parent
ENTRIES = ('docker-compose.device-release-network-priority.yml',
'deployment/device-core-network-priority-v1.json')
def bundle():
descriptor = (ROOT / 'network-priority-v1.json').read_bytes()
identity = json.loads(descriptor)['releaseId']
members = {
'manifest.env': ('id=' + identity + '\ncomponent=device-core-network-priority\ntype=app-overlay\n').encode(),
'files.txt': ('\n'.join(ENTRIES) + '\n').encode(),
'payload/' + ENTRIES[0]: (ROOT / 'docker-compose.network-priority.yml').read_bytes(),
'payload/' + ENTRIES[1]: descriptor,
}
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for name, data in sorted(members.items()):
info = tarfile.TarInfo(name)
info.mode = 0o644
info.size = len(data)
archive.addfile(info, io.BytesIO(data))
return identity, output.getvalue()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-dir', required=True, type=Path)
args = parser.parse_args()
args.output_dir.mkdir(parents=True, exist_ok=True)
identity, data = bundle()
path = args.output_dir / ('nodedc-' + identity + '.tgz')
with path.open('xb') as stream:
stream.write(data)
print(json.dumps({'artifact': str(path), 'sha256': hashlib.sha256(data).hexdigest(), 'id': identity}))
@@ -1,42 +0,0 @@
#!/usr/bin/env python3
"""Build the exact evidence-only r5 reconciliation, never application code."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import tarfile
ROOT = Path(__file__).resolve().parent
ENTRY = 'deployment/device-core-release-r5-reconciliation-v1.json'
def bundle(version=1):
if version not in (1, 2):
raise ValueError("unsupported reconciliation version")
entry = ENTRY if version == 1 else ENTRY.replace("-v1.json", "-v2.json")
descriptor = (ROOT / ('r5-reconciliation-v'+str(version)+'.json')).read_bytes()
identity = json.loads(descriptor)['releaseId']
members = {
'manifest.env': ('id='+identity+'\ncomponent=device-core-release-reconciliation\ntype=app-overlay\n').encode(),
'files.txt': (entry+'\n').encode(),
'payload/'+entry: descriptor,
}
output=io.BytesIO()
with gzip.GzipFile(fileobj=output, mode='wb', mtime=0, filename='') as compressed:
with tarfile.open(fileobj=compressed, mode='w') as archive:
for name,data in sorted(members.items()):
info=tarfile.TarInfo(name);info.mode=0o644;info.size=len(data)
archive.addfile(info,io.BytesIO(data))
return identity,output.getvalue()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--version', type=int, choices=(1, 2), default=1)
parser.add_argument('--output-dir',required=True,type=Path)
args=parser.parse_args();args.output_dir.mkdir(parents=True,exist_ok=True)
identity,data=bundle(args.version);path=args.output_dir/('nodedc-'+identity+'.tgz')
with path.open('xb') as stream:stream.write(data)
print(json.dumps({'artifact':str(path),'sha256':hashlib.sha256(data).hexdigest(),'id':identity}))
-54
View File
@@ -1,54 +0,0 @@
"""One polling cycle with an injected canonical installer, no shell authority."""
from deployment_queue import REPOSITORY, REPOSITORY_ID, QueueError
class Controller:
def __init__(self, queue, source, installer):
self.queue, self.source, self.installer = queue, source, installer
def reconcile(self):
for row in self.queue.snapshot():
if row['phase'] != 'deploying':
continue
outcome, receipt = self.installer.receipt(row)
self.queue.reconcile(row['id'], digest=row['digest'], artifact=row['artifact'],
outcome=outcome, receipt=receipt)
def observe(self):
runs = self.source.discover()
# A disappeared pending run cannot be silently skipped. Keep its local
# reservation/order; a source error is actionable, never an expiry.
ids = {r['id'] for r in runs}
for row in self.queue.snapshot():
if row['phase'] in ('pending', 'ready') and row['id'] not in ids:
raise QueueError('observed_run_disappeared:' + str(row['id']))
self.queue.observe(runs, repository=REPOSITORY, repository_id=REPOSITORY_ID)
def tick(self):
self.reconcile()
self.observe()
row = self.queue.next_ready()
if row is None:
return {'status': 'waiting'}
run = self.source.successful_run(row)
baseline = self.installer.installed_source()
self.source.prove_lineage(baseline, row['sha'])
receipt, data = self.source.artifact(run)
# Staging validates the canonical payload and its relation to this run.
self.installer.stage(row, receipt, data)
self.installer.plan(receipt['artifact'])
# Recheck after potentially slow download/plan; a rerun/pending run may
# have appeared. Reserve still enforces the durable ordering atomically.
self.observe()
self.source.successful_run(row)
self.source.prove_lineage(baseline, row['sha'])
reserved = self.queue.reserve(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'])
try:
self.installer.apply(receipt['artifact'])
finally:
# Even a clean rollback is terminal for this exact artifact. Missing
# or conflicting evidence blocks subsequent installs after restart.
outcome, canonical_receipt = self.installer.receipt(reserved)
self.queue.reconcile(row['id'], digest=receipt['sha256'], artifact=receipt['artifact'],
outcome=outcome, receipt=canonical_receipt)
return {'status': outcome, 'run': row['id'], 'source': row['sha']}
@@ -1,178 +0,0 @@
"""Durable release ordering. Pure state policy; no network or runtime authority.
The canonical installer remains the only production executor. A controller may
reserve a verified artifact here, then must reconcile its canonical receipt
after any crash before admitting another deployment.
"""
import re
import sqlite3
REPOSITORY = "SILVER/NODEDC_DEVICE_CORE"
REPOSITORY_ID = 38
WORKFLOW = "ci.yml@refs/heads/main"
TERMINAL = {"deployed", "failed", "superseded", "blocked"}
SHA = re.compile(r"[0-9a-f]{40}")
DIGEST = re.compile(r"[0-9a-f]{64}")
class QueueError(ValueError):
pass
def positive(value):
return type(value) is int and 0 < value < 2**53
def normalize_run(run):
if not isinstance(run, dict):
raise QueueError("invalid_run")
if not all(positive(run.get(key)) for key in ("id", "run_number", "run_attempt")):
raise QueueError("invalid_run_identity")
if not isinstance(run.get("head_sha"), str) or not SHA.fullmatch(run["head_sha"]):
raise QueueError("invalid_source_sha")
status = run.get("status")
if status not in ("queued", "waiting", "in_progress", "completed"):
raise QueueError("unknown_run_status")
conclusion = run.get("conclusion")
if status == "completed" and conclusion not in (
"success", "failure", "cancelled", "skipped", "timed_out", "action_required", "neutral", "stale",
):
raise QueueError("unknown_run_conclusion")
relevant = (run.get("event") == "push" and run.get("head_branch") == "main"
and run.get("path") == WORKFLOW)
phase = "pending" if status != "completed" else "ready" if conclusion == "success" else "unqualified"
if not relevant:
phase = "ignored"
return (run["id"], run["run_number"], run["head_sha"], str(run.get("event", "")),
str(run.get("head_branch", "")), str(run.get("path", "")), run["run_attempt"], phase)
class DeploymentQueue:
def __init__(self, path, *, first_run_number):
if not positive(first_run_number):
raise QueueError("invalid_activation_floor")
self.db = sqlite3.connect(str(path), timeout=10, isolation_level=None)
self.db.row_factory = sqlite3.Row
self.db.execute("PRAGMA journal_mode=WAL")
self.db.execute("PRAGMA synchronous=FULL")
self.db.executescript("""
CREATE TABLE IF NOT EXISTS policy (
id INTEGER PRIMARY KEY CHECK(id=1),
repository TEXT NOT NULL, repository_id INTEGER NOT NULL,
first_run INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY, number INTEGER NOT NULL UNIQUE,
sha TEXT NOT NULL, event TEXT NOT NULL, branch TEXT NOT NULL,
workflow TEXT NOT NULL, attempt INTEGER NOT NULL, phase TEXT NOT NULL,
artifact TEXT, digest TEXT, receipt TEXT
);
CREATE INDEX IF NOT EXISTS runs_phase_number ON runs(phase,number);
CREATE INDEX IF NOT EXISTS runs_sha_phase ON runs(sha,phase);
""")
self.db.execute("INSERT OR IGNORE INTO policy VALUES(1,?,?,?)", (REPOSITORY, REPOSITORY_ID, first_run_number))
policy = self.db.execute("SELECT * FROM policy WHERE id=1").fetchone()
if (policy["repository"], policy["repository_id"], policy["first_run"]) != (REPOSITORY, REPOSITORY_ID, first_run_number):
self.db.close()
raise QueueError("queue_policy_changed")
self.first_run = first_run_number
def close(self):
self.db.close()
def transaction(self, operation):
self.db.execute("BEGIN IMMEDIATE")
try:
value = operation()
self.db.execute("COMMIT")
return value
except BaseException:
self.db.execute("ROLLBACK")
raise
def observe(self, runs, *, repository, repository_id):
if repository != REPOSITORY or type(repository_id) is not int or repository_id != REPOSITORY_ID:
raise QueueError("repository_identity_mismatch")
values = [normalize_run(run) for run in runs]
def apply():
for value in values:
identity, number, sha, event, branch, workflow, attempt, phase = value
if number < self.first_run:
continue
existing = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone()
if existing is None:
self.db.execute("INSERT INTO runs(id,number,sha,event,branch,workflow,attempt,phase) VALUES(?,?,?,?,?,?,?,?)", value)
continue
if tuple(existing[k] for k in ("number", "sha", "event", "branch", "workflow")) != (number, sha, event, branch, workflow):
raise QueueError("run_identity_changed")
if attempt < existing["attempt"]:
continue # A stale API page cannot rewind a rerun.
if existing["phase"] in TERMINAL or existing["phase"] == "deploying":
continue
if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase == "pending":
continue
if attempt == existing["attempt"] and existing["phase"] in ("ready", "unqualified") and phase != existing["phase"]:
raise QueueError("terminal_run_outcome_changed")
self.db.execute("UPDATE runs SET phase=?,attempt=? WHERE id=?", (phase, attempt, identity))
self.transaction(apply)
def _next(self):
blocked = self.db.execute("SELECT id,phase FROM runs WHERE phase IN ('deploying','blocked') ORDER BY number LIMIT 1").fetchone()
if blocked:
raise QueueError("canonical_reconciliation_required:" + str(blocked["id"]))
while True:
row = self.db.execute("SELECT * FROM runs WHERE phase IN ('pending','ready') ORDER BY number LIMIT 1").fetchone()
if row is None or row["phase"] != "ready":
return None
newer = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND number>=? LIMIT 1", (row["number"],)).fetchone()
duplicate = self.db.execute("SELECT id FROM runs WHERE phase='deployed' AND sha=? LIMIT 1", (row["sha"],)).fetchone()
if newer or duplicate:
self.db.execute("UPDATE runs SET phase='superseded' WHERE id=?", (row["id"],))
continue
return dict(row)
def next_ready(self):
return self.transaction(self._next)
def reserve(self, identity, *, digest, artifact):
if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
raise QueueError("invalid_artifact_digest")
def apply():
row = self._next()
if row is None or row["id"] != identity:
raise QueueError("deployment_order_mismatch")
expected = "nodedc-device-core-release-v1-r" + str(identity) + "-" + row["sha"] + ".tgz"
if artifact != expected:
raise QueueError("artifact_identity_mismatch")
self.db.execute("UPDATE runs SET phase='deploying',digest=?,artifact=? WHERE id=?", (digest, artifact, identity))
return {**row, "phase": "deploying", "digest": digest, "artifact": artifact}
return self.transaction(apply)
def reconcile(self, identity, *, digest, artifact, outcome, receipt):
"""Caller must prove the canonical applied/failed journal and archive.
No receipt or uncertain/failed rollback => blocked, never automatic retry.
A clean rollback may be followed by a new release, never this artifact.
"""
if outcome not in ("deployed", "rolled-back", "ambiguous"):
raise QueueError("invalid_canonical_outcome")
if not isinstance(receipt, str) or not receipt or len(receipt) > 240:
raise QueueError("canonical_receipt_required")
phase = {"deployed": "deployed", "rolled-back": "failed", "ambiguous": "blocked"}[outcome]
def apply():
row = self.db.execute("SELECT * FROM runs WHERE id=?", (identity,)).fetchone()
if row is None or (row["digest"], row["artifact"]) != (digest, artifact):
raise QueueError("canonical_artifact_mismatch")
if row["phase"] == phase and row["receipt"] == receipt:
return
if row["phase"] != "deploying":
raise QueueError("canonical_outcome_conflict")
self.db.execute("UPDATE runs SET phase=?,receipt=? WHERE id=?", (phase, receipt, identity))
self.transaction(apply)
def snapshot(self):
return [dict(row) for row in self.db.execute("SELECT * FROM runs ORDER BY number")]
@@ -1,13 +0,0 @@
services:
device-control-core:
networks:
device-plane-private:
priority: 100
device-plane-egress:
priority: 0
device-manager:
networks:
device-plane-private:
priority: 100
platform-edge:
priority: 0
-25
View File
@@ -1,25 +0,0 @@
#!/usr/bin/env python3
"""Embed reviewed pure Python into the standalone canonical runner; no runtime exec/import from SMB."""
from pathlib import Path
ROOT=Path(__file__).resolve().parent
RUNNER=ROOT.parent/'deploy-runner/nodedc-deploy'
START='# BEGIN GENERATED DEVICE CORE AUTODEPLOY LIBRARY\n'
END='# END GENERATED DEVICE CORE AUTODEPLOY LIBRARY\n'
def section():
output=START+'def device_autodeploy_library():\n'
for name in ('deployment_queue.py','gitea_source.py','controller.py'):
source=(ROOT/name).read_text()
lines=[line for line in source.splitlines() if not line.startswith('from deployment_queue import ')]
output+=' # Source: infra/device-core-deploy/'+name+'\n'
output+='\n'.join(' '+line if line else '' for line in lines)+'\n\n'
return output+' return DeploymentQueue, GiteaSource, Controller, (QueueError, SourceError)\n'+END
if __name__=='__main__':
current=RUNNER.read_text()
if START in current:
before,rest=current.split(START,1);_,after=rest.split(END,1)
current=before+section()+after
else:
current=current.replace('\ndef main(argv):','\n'+section()+'\n\ndef main(argv):',1)
RUNNER.write_text(current)
-259
View File
@@ -1,259 +0,0 @@
"""Read-only, bounded Gitea source verification. No production execution authority.
The privileged installer must independently validate the returned TGZ with its
canonical loader and reconcile its own journal. Nothing here accepts commands,
paths, origins, or credentials from a workflow artifact.
"""
import hashlib
import io
import json
import re
import stat
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW, SHA, normalize_run, positive
ORIGIN = "https://git.dcserve.ru"
PREFIX = "/api/v1/repos/" + REPOSITORY
PAGE_SIZE = 50
MAX_PAGES = 200
MAX_JSON = 8 * 1024 * 1024
MAX_ARCHIVE = 64 * 1024 * 1024
class SourceError(ValueError):
pass
def require(condition, code):
if not condition:
raise SourceError(code)
def strict_json(data):
def unique(pairs):
result = {}
for key, value in pairs:
require(key not in result, "duplicate_json_key")
result[key] = value
return result
try:
return json.loads(data, object_pairs_hook=unique)
except (UnicodeError, ValueError):
raise SourceError("invalid_json") from None
def signed_artifact_redirect(original, target):
origin, dest = urllib.parse.urlsplit(original), urllib.parse.urlsplit(target)
if (origin.scheme + "://" + origin.netloc != ORIGIN
or dest.scheme + "://" + dest.netloc != ORIGIN or origin.query or dest.fragment
or not re.fullmatch(re.escape(PREFIX) + r"/actions/artifacts/[1-9][0-9]*/zip", origin.path)
or dest.path != origin.path + "/raw"):
return False
pairs = urllib.parse.parse_qsl(dest.query, keep_blank_values=True)
params = dict(pairs)
return (len(pairs) == 2 and set(params) == {"sig", "expires"}
and re.fullmatch(r"[A-Za-z0-9_-]{32,128}", params["sig"]) is not None
and re.fullmatch(r"[0-9]{10,13}", params["expires"]) is not None)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Gitea 1.27 signs a same-origin /zip/raw URL. Only this exact route is
# allowed and the persistent token is deliberately NOT forwarded.
if (req is not None and req.get_method() == "GET" and code in (302, 303)
and signed_artifact_redirect(req.full_url, newurl)):
return urllib.request.Request(newurl, headers={"Accept": "application/octet-stream"})
raise SourceError("api_redirect_refused")
class GiteaSource:
def __init__(self, token):
require(isinstance(token, str) and re.fullmatch(r"[0-9a-f]{40}", token), "invalid_read_token")
self._token = token
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
def request(self, suffix, *, archive=False):
require(isinstance(suffix, str) and (suffix == "" or suffix.startswith("/")), "invalid_api_path")
require(not any(value in suffix for value in ("..", "\\", "#", "@", "\r", "\n", "%")), "invalid_api_path")
# Only methods below construct suffixes; this additional allowlist keeps
# even accidental future callers from reading other API resources.
require(re.fullmatch(
r"(?:|/branches/main|/git/commits/[a-f0-9]{40}"
r"|/actions/runs(?:/[1-9][0-9]*(?:/jobs|/artifacts)?)?"
r"|/actions/artifacts/[1-9][0-9]*/zip)(?:\?page=[1-9][0-9]*&limit=50)?", suffix),
"api_route_not_allowed")
require(archive == suffix.endswith("/zip"), "api_response_type_mismatch")
maximum = MAX_ARCHIVE if archive else MAX_JSON
request = urllib.request.Request(ORIGIN + PREFIX + suffix,
headers={"Authorization": "token " + self._token,
"Accept": "application/octet-stream" if archive else "application/json"})
try:
with self._opener.open(request, timeout=25) as response:
require(response.status == 200 and (response.geturl() == request.full_url or (archive and signed_artifact_redirect(request.full_url, response.geturl()))), "api_response_identity")
data = response.read(maximum + 1)
except urllib.error.HTTPError as error:
raise SourceError("api_http_" + str(error.code)) from None
except (OSError, urllib.error.URLError):
raise SourceError("api_unavailable") from None
require(len(data) <= maximum, "api_response_too_large")
return data if archive else strict_json(data)
def repository(self):
repo = self.request("")
require(isinstance(repo, dict) and type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
and repo.get("full_name") == REPOSITORY and repo.get("default_branch") == "main"
and repo.get("archived") is False and repo.get("mirror") is False,
"repository_identity_mismatch")
return repo
def pages(self, suffix, key):
rows, identities, total = [], set(), None
for page in range(1, MAX_PAGES + 1):
data = self.request(suffix + "?page=" + str(page) + "&limit=50")
require(isinstance(data, dict) and type(data.get("total_count")) is int
and 0 <= data["total_count"] <= PAGE_SIZE * MAX_PAGES, "pagination_total_invalid")
require(total is None or total == data["total_count"], "pagination_changed")
total = data["total_count"]
batch = data.get(key)
require(isinstance(batch, list) and len(batch) <= PAGE_SIZE, "pagination_batch_invalid")
for item in batch:
require(isinstance(item, dict) and positive(item.get("id")) and item["id"] not in identities,
"pagination_duplicate_or_invalid_id")
identities.add(item["id"])
rows.extend(batch)
require(len(rows) <= total, "pagination_overflow")
if len(rows) == total:
return rows
require(len(batch) == PAGE_SIZE, "pagination_incomplete")
raise SourceError("pagination_limit")
def run(self, identity):
require(positive(identity), "invalid_run_id")
run = self.request("/actions/runs/" + str(identity))
self.validate_run(run)
require(run["id"] == identity, "run_identity_mismatch")
return run
@staticmethod
def validate_run(run):
normalize_run(run)
# Gitea 1.27.2 leaves top-level repository_id=0. The nested repository
# and fixed repository endpoint carry the actual identity instead.
repo = run.get("repository") or {}
require(type(repo.get("id")) is int and repo["id"] == REPOSITORY_ID
and repo.get("full_name") == REPOSITORY, "run_repository_mismatch")
def discover(self):
self.repository()
runs = self.pages("/actions/runs", "workflow_runs")
for run in runs:
self.validate_run(run)
require(len({run["run_number"] for run in runs}) == len(runs), "duplicate_run_number")
# A push/deletion while pages were read must not silently hide an older
# pending run. Recheck identity/count, without requiring phases to stop.
check = self.pages("/actions/runs", "workflow_runs")
identity = lambda values: sorted((r["id"], r["run_number"], r["head_sha"], r["event"], r["head_branch"], r["path"]) for r in values)
for run in check:
self.validate_run(run)
require(identity(runs) == identity(check), "discovery_changed")
return check
def successful_run(self, row):
run = self.run(row["id"])
require((run["run_number"], run["head_sha"], run["run_attempt"]) ==
(row["number"], row["sha"], row["attempt"]), "qualified_run_changed")
require(run["path"] == WORKFLOW and run["event"] == "push" and run["head_branch"] == "main"
and run["status"] == "completed" and run["conclusion"] == "success", "run_not_qualified")
jobs = self.pages("/actions/runs/" + str(run["id"]) + "/jobs", "jobs")
require(len(jobs) == 1, "qualification_job_count")
job = jobs[0]
require(job.get("run_id") == run["id"] and job.get("head_sha") == run["head_sha"]
and job.get("head_branch") == "main" and job.get("run_attempt") == run["run_attempt"]
and job.get("name") == "qualify" and job.get("labels") == ["nodedc-node22-build"]
and job.get("runner_id") == 1 and job.get("status") == "completed"
and job.get("conclusion") == "success", "qualification_job_mismatch")
steps = job.get("steps")
require(isinstance(steps, list) and all(isinstance(s, dict) for s in steps) and [s.get("name") for s in steps] ==
["Check the exact pushed commit", "Retain the qualified release in this Gitea run"]
and all(s.get("status") == "completed" and s.get("conclusion") == "success" for s in steps),
"qualification_steps_mismatch")
return run
def main_commit(self):
branch = self.request("/branches/main")
require(isinstance(branch, dict) and branch.get("name") == "main", "main_branch_mismatch")
sha = (branch.get("commit") or {}).get("id")
require(isinstance(sha, str) and SHA.fullmatch(sha), "main_commit_invalid")
return sha
def ancestor(self, ancestor, descendant, *, limit=1024):
require(all(isinstance(s, str) and SHA.fullmatch(s) for s in (ancestor, descendant)), "ancestry_sha_invalid")
pending, seen = [descendant], set()
while pending:
sha = pending.pop()
if sha == ancestor:
return True
if sha in seen:
continue
require(len(seen) < limit, "ancestry_limit")
seen.add(sha)
commit = self.request("/git/commits/" + sha)
require(isinstance(commit, dict) and commit.get("sha") == sha, "commit_identity_mismatch")
parents = commit.get("parents")
require(isinstance(parents, list) and len(parents) <= 32, "commit_parents_invalid")
for parent in parents:
value = parent.get("sha") if isinstance(parent, dict) else None
require(isinstance(value, str) and SHA.fullmatch(value), "commit_parent_invalid")
pending.append(value)
return False
def prove_lineage(self, installed, candidate):
main = self.main_commit()
require(candidate != installed and self.ancestor(installed, candidate)
and self.ancestor(candidate, main), "non_forward_main_release")
require(self.main_commit() == main, "main_changed_during_proof")
return main
def artifact(self, run):
artifacts = self.pages("/actions/runs/" + str(run["id"]) + "/artifacts", "artifacts")
candidates = [a for a in artifacts if a.get("name") == "device-core-release"]
require(len(candidates) == 1, "qualified_artifact_count")
artifact = candidates[0]
owner = artifact.get("workflow_run") or {}
require(owner.get("id") == run["id"] and owner.get("repository_id") == REPOSITORY_ID
and owner.get("head_sha") == run["head_sha"] and artifact.get("expired") is False
and type(artifact.get("size_in_bytes")) is int and 0 < artifact["size_in_bytes"] <= MAX_ARCHIVE,
"artifact_owner_or_size_mismatch")
blob = self.request("/actions/artifacts/" + str(artifact["id"]) + "/zip", archive=True)
require(len(blob) == artifact["size_in_bytes"], "artifact_download_size_mismatch")
return unpack_artifact(blob, run)
def unpack_artifact(blob, run):
identity = "nodedc-device-core-release-v1-r" + str(run["id"]) + "-" + run["head_sha"] + ".tgz"
require(len(blob) <= MAX_ARCHIVE, "archive_too_large")
try:
with zipfile.ZipFile(io.BytesIO(blob)) as archive:
members = archive.infolist()
require(len(members) == 2 and set(archive.namelist()) == {identity, "release.json"}, "zip_entry_mismatch")
for member in members:
require(not member.is_dir() and stat.S_IFMT(member.external_attr >> 16) in (0, stat.S_IFREG)
and not member.flag_bits & 1 and 0 < member.file_size <= MAX_ARCHIVE,
"zip_member_invalid")
if member.filename == "release.json":
require(member.file_size <= 4096, "zip_receipt_too_large")
data = archive.read(identity)
receipt = strict_json(archive.read("release.json"))
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, OSError):
raise SourceError("archive_invalid") from None
expected = {"artifact": identity, "sourceCommit": run["head_sha"], "runId": run["id"],
"runNumber": run["run_number"], "deployed": False,
"sha256": hashlib.sha256(data).hexdigest()}
require(receipt == expected and type(receipt.get("runId")) is int
and type(receipt.get("runNumber")) is int and receipt.get("deployed") is False, "release_receipt_mismatch")
return receipt, data
@@ -1 +0,0 @@
{"schemaVersion":"nodedc.device-core.network-priority.v1","releaseId":"device-core-network-priority-v1-20260930-002","baselineReleaseId":"device-core-release-v1-r12-b2660df9e26afe977bfa62efd35a8397eac4898b","baselineSha256":"44c62036967c3ed26bd6c82f94e6f4103ccad06f45c383498210b43ad80c9d7c","mode":"metadata-only-existing-primary-network","primaryPriority":100,"secondaryPriority":0}
@@ -1,8 +0,0 @@
{
"schemaVersion": "nodedc.device-core.release-drift-audit.v1",
"failedReleaseId": "device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406",
"failedSha256": "b8dd1384f499d1173ce7d95dc1f2433a404290f443bd612816ad9136ccbf9347",
"backupId": "device-core-release-device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406-20260929-190019",
"mode": "read-only-plan;apply-forbidden",
"auditId": "device-core-release-r5-drift-audit-v1-20260929-001"
}
@@ -1,8 +0,0 @@
{
"schemaVersion": "nodedc.device-core.release-reconciliation.v1",
"releaseId": "device-core-release-r5-reconciliation-v1-20260929-001",
"failedReleaseId": "device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406",
"failedSha256": "b8dd1384f499d1173ce7d95dc1f2433a404290f443bd612816ad9136ccbf9347",
"backupId": "device-core-release-device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406-20260929-190019",
"mode": "prove-restored-baseline-only"
}
@@ -1,9 +0,0 @@
{
"backupId": "device-core-release-device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406-20260929-190019",
"failedReleaseId": "device-core-release-v1-r5-67b2ae586399eb1eb7d3a6c074a292e0dbb7b406",
"failedSha256": "b8dd1384f499d1173ce7d95dc1f2433a404290f443bd612816ad9136ccbf9347",
"mode": "prove-restored-baseline-mount-order-only",
"releaseId": "device-core-release-r5-reconciliation-v2-20260929-002",
"runtimeFingerprintVersion": 2,
"schemaVersion": "nodedc.device-core.release-reconciliation.v2"
}
@@ -1,74 +0,0 @@
import hashlib
from pathlib import Path
import tempfile
import unittest
from unittest import mock
from deployment_queue import DeploymentQueue, QueueError
from controller import Controller
from test_gitea_source import run,A,B,C
class ControllerTests(unittest.TestCase):
def setUp(self):
self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup)
self.path=Path(self.tmp.name)/'queue.db'
self.q=DeploymentQueue(self.path,first_run_number=8);self.addCleanup(self.q.close)
self.s=mock.Mock();self.i=mock.Mock()
self.i.installed_source.return_value=A
self.r=run();self.s.discover.return_value=[self.r];self.s.successful_run.return_value=self.r
self.data=b'archive';self.artifact='nodedc-device-core-release-v1-r8-'+B+'.tgz'
self.receipt={'artifact':self.artifact,'sha256':hashlib.sha256(self.data).hexdigest()}
self.s.artifact.return_value=(self.receipt,self.data)
self.i.receipt.return_value=('deployed','canonical:line1')
self.c=Controller(self.q,self.s,self.i)
def test_success_is_reserved_before_apply_and_never_repeated(self):
def apply(a):self.assertEqual(self.q.snapshot()[0]['phase'],'deploying')
self.i.apply.side_effect=apply
self.assertEqual(self.c.tick()['status'],'deployed')
self.assertEqual(self.c.tick()['status'],'waiting')
self.i.apply.assert_called_once_with(self.artifact)
def test_earlier_pending_blocks_newer_ready_but_failed_ci_does_not(self):
pending=run();pending.update(status='in_progress',conclusion=None)
self.s.discover.return_value=[run(9,C),pending]
self.assertEqual(self.c.tick()['status'],'waiting');self.i.apply.assert_not_called()
pending.update(status='completed',conclusion='failure');self.c.observe()
self.assertEqual(self.q.next_ready()['id'],9)
def test_failure_with_clean_rollback_is_terminal(self):
self.i.apply.side_effect=RuntimeError('failure');self.i.receipt.return_value=('rolled-back','failed:line1')
with self.assertRaises(RuntimeError):self.c.tick()
self.assertEqual(self.q.snapshot()[0]['phase'],'failed')
self.assertEqual(self.c.tick()['status'],'waiting');self.assertEqual(self.i.apply.call_count,1)
def test_missing_receipt_blocks_restart(self):
self.i.apply.side_effect=RuntimeError('crash');self.i.receipt.return_value=('ambiguous','missing-receipt')
with self.assertRaises(RuntimeError):self.c.tick()
with self.assertRaises(QueueError):self.c.tick()
self.assertEqual(self.i.apply.call_count,1)
def test_restart_reconciles_success_without_second_apply(self):
self.c.observe();self.q.reserve(8,digest=self.receipt['sha256'],artifact=self.artifact)
self.assertEqual(self.c.tick()['status'],'waiting')
self.i.apply.assert_not_called();self.assertEqual(self.q.snapshot()[0]['phase'],'deployed')
def test_network_or_plan_error_before_reservation_preserves_ready_queue(self):
self.i.plan.side_effect=RuntimeError('network')
with self.assertRaises(RuntimeError):self.c.tick()
self.assertEqual(self.q.snapshot()[0]['phase'],'ready');self.i.apply.assert_not_called()
def test_new_rerun_before_reservation_prevents_apply(self):
pending=run();pending.update(run_attempt=2,status='in_progress',conclusion=None)
self.s.discover.side_effect=[[run()],[pending]]
with self.assertRaises(QueueError):self.c.tick()
self.i.apply.assert_not_called()
def test_disappeared_pending_run_never_skipped(self):
pending=run();pending.update(status='in_progress',conclusion=None)
self.s.discover.return_value=[pending];self.c.observe()
self.s.discover.return_value=[run(9,C)]
with self.assertRaisesRegex(QueueError,'disappeared'):self.c.tick()
self.i.apply.assert_not_called()
if __name__=='__main__':unittest.main()
@@ -1,138 +0,0 @@
import tempfile
from pathlib import Path
import unittest
from deployment_queue import DeploymentQueue, QueueError, REPOSITORY, REPOSITORY_ID
def run(number, *, status="completed", conclusion="success", **updates):
return {"id": number + 100, "run_number": number, "run_attempt": 1,
"head_sha": format(number, "040x"), "event": "push", "head_branch": "main",
"path": "ci.yml@refs/heads/main", "status": status, "conclusion": conclusion, **updates}
class QueueTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.path = Path(self.temp.name) / "queue.db"
self.q = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(lambda: self.q.close())
def observe(self, *values):
self.q.observe(list(values), repository=REPOSITORY, repository_id=REPOSITORY_ID)
def reserve(self, number):
r = self.q.next_ready()
self.assertEqual(r["number"], number)
return self.q.reserve(r["id"], digest="a"*64,
artifact="nodedc-device-core-release-v1-r"+str(r["id"])+"-"+r["sha"]+".tgz")
def finish(self, row, outcome="deployed"):
self.q.reconcile(row["id"], digest=row["digest"], artifact=row["artifact"],
outcome=outcome, receipt="canonical-test-receipt-"+str(row["id"]))
def test_overlapping_pushes_wait_for_older_qualification(self):
self.observe(run(2), run(1, status="in_progress", conclusion=None))
self.assertIsNone(self.q.next_ready())
self.observe(run(1))
self.finish(self.reserve(1))
self.finish(self.reserve(2))
self.assertIsNone(self.q.next_ready())
def test_failed_tests_do_not_deploy_and_next_push_can_proceed(self):
self.observe(run(2), run(1, conclusion="failure"))
self.finish(self.reserve(2))
self.assertEqual(self.q.snapshot()[0]["phase"], "unqualified")
def test_duplicate_observations_and_receipts_are_idempotent(self):
self.observe(run(1), run(1))
row = self.reserve(1)
self.finish(row)
self.finish(row)
self.observe(run(1))
self.assertEqual(len(self.q.snapshot()), 1)
self.assertIsNone(self.q.next_ready())
def test_wrong_branch_event_and_workflow_never_deploy(self):
self.observe(run(1, head_branch="feature"), run(2, event="workflow_dispatch"), run(3, path="other.yml@refs/heads/main"))
self.assertIsNone(self.q.next_ready())
self.assertEqual({r["phase"] for r in self.q.snapshot()}, {"ignored"})
def test_wrong_repository_and_malformed_sha_rejected(self):
for repo, identity in [("other/Device", 38), (REPOSITORY, 39), (REPOSITORY, 38.0)]:
with self.assertRaises(QueueError): self.q.observe([run(1)], repository=repo, repository_id=identity)
with self.assertRaises(QueueError): self.observe(run(1, head_sha="main; execute"))
self.assertEqual(self.q.snapshot(), [])
def test_identity_conflict_rolls_back_entire_observation(self):
self.observe(run(1))
with self.assertRaises(QueueError): self.observe(run(2), run(1, head_sha="b"*40))
self.assertEqual(len(self.q.snapshot()), 1)
def test_restart_preserves_pending_and_requires_reconciliation_for_reserved(self):
self.observe(run(1), run(2))
row = self.reserve(1)
self.q.close()
self.q = DeploymentQueue(self.path, first_run_number=1)
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
self.finish(row)
self.assertEqual(self.q.next_ready()["number"], 2)
def test_ambiguous_or_failed_rollback_halts_following_deploys(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "ambiguous")
with self.assertRaisesRegex(QueueError, "reconciliation"): self.q.next_ready()
def test_clean_rollback_never_retries_same_artifact_but_allows_forward_fix(self):
self.observe(run(1), run(2))
self.finish(self.reserve(1), "rolled-back")
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 2)
def test_late_old_run_and_same_source_cannot_downgrade_installed_revision(self):
self.observe(run(5))
self.finish(self.reserve(5))
self.observe(run(4), run(6, head_sha=run(5)["head_sha"]))
self.assertIsNone(self.q.next_ready())
self.assertEqual([r["phase"] for r in self.q.snapshot()], ["superseded", "deployed", "superseded"])
def test_second_controller_cannot_reserve_another_deploy(self):
self.observe(run(1), run(2))
second = DeploymentQueue(self.path, first_run_number=1)
self.addCleanup(second.close)
self.reserve(1)
with self.assertRaises(QueueError): second.next_ready()
def test_wrong_receipt_cannot_close_crashed_deployment(self):
self.observe(run(1))
row = self.reserve(1)
with self.assertRaisesRegex(QueueError, "artifact_mismatch"):
self.q.reconcile(row["id"], digest="b"*64, artifact=row["artifact"], outcome="deployed", receipt="wrong")
with self.assertRaises(QueueError): self.q.next_ready()
def test_activation_floor_is_persistent_and_old_history_is_not_deployed(self):
self.q.close()
self.path = Path(self.temp.name) / "second.db"
self.q = DeploymentQueue(self.path, first_run_number=3)
self.observe(run(1), run(2), run(3))
self.assertEqual(self.q.next_ready()["number"], 3)
with self.assertRaisesRegex(QueueError, "policy_changed"):
DeploymentQueue(self.path, first_run_number=1)
def test_terminal_api_outcome_cannot_change_without_a_new_attempt(self):
self.observe(run(1, conclusion="failure"))
with self.assertRaisesRegex(QueueError, "outcome_changed"): self.observe(run(1))
self.observe(run(1, run_attempt=2))
self.assertEqual(self.q.next_ready()["number"], 1)
def test_large_backlog_of_duplicate_sources_is_iterative(self):
self.observe(run(1))
self.finish(self.reserve(1))
self.observe(*(run(n, head_sha=run(1)["head_sha"]) for n in range(2, 1200)))
self.assertIsNone(self.q.next_ready())
self.assertEqual(len(self.q.snapshot()), 1199)
if __name__ == "__main__":
unittest.main()
@@ -1,136 +0,0 @@
"""Untrusted API/ZIP boundaries and complete source lineage."""
import copy
import hashlib
import io
import json
import stat
import unittest
from unittest import mock
import zipfile
import urllib.request
from deployment_queue import REPOSITORY, REPOSITORY_ID, WORKFLOW
from gitea_source import GiteaSource, SourceError, NoRedirect, strict_json, unpack_artifact
A, B, C = 'a'*40, 'b'*40, 'c'*40
def run(number=8, sha=B):
return dict(id=number, run_number=number, run_attempt=1, head_sha=sha,
event='push', head_branch='main', path=WORKFLOW, status='completed', conclusion='success',
repository={'id':38, 'full_name':REPOSITORY})
def job(r):
return dict(id=8, run_id=r['id'], head_sha=r['head_sha'], head_branch='main', run_attempt=1,
name='qualify', labels=['nodedc-node22-build'], runner_id=1, status='completed', conclusion='success',
steps=[dict(name=n,status='completed',conclusion='success') for n in
('Check the exact pushed commit','Retain the qualified release in this Gitea run')])
def packed(r, mutate=None, names=None):
name='nodedc-device-core-release-v1-r'+str(r['id'])+'-'+r['head_sha']+'.tgz'
data=b'qualified tgz fixture'
receipt=dict(artifact=name,sourceCommit=r['head_sha'],runId=r['id'],runNumber=r['run_number'],
deployed=False,sha256=hashlib.sha256(data).hexdigest())
if mutate:mutate(receipt)
out=io.BytesIO()
with zipfile.ZipFile(out,'w') as z:
z.writestr(name,data)
z.writestr('release.json',json.dumps(receipt))
for n in names or []:z.writestr(n,b'extra')
return out.getvalue()
class SourceTests(unittest.TestCase):
def setUp(self):self.s=GiteaSource('a'*40)
def test_no_redirects_or_unapproved_routes(self):
with self.assertRaises(SourceError):NoRedirect().redirect_request(None,None,302,'',{},'https://other/')
for path in ['/../../user','/actions/runs?token=a','//user','/branches/other','/actions/artifacts/1/zip%3f']:
with self.subTest(path=path),self.assertRaises(SourceError):self.s.request(path)
def test_observed_signed_download_redirect_strips_persistent_token(self):
url='https://git.dcserve.ru/api/v1/repos/SILVER/NODEDC_DEVICE_CORE/actions/artifacts/6/zip'
target=url+'/raw?sig='+'a'*43+'&expires=1790708000'
req=urllib.request.Request(url,headers={'Authorization':'token '+'b'*40})
redirected=NoRedirect().redirect_request(req,None,302,'',{},target)
self.assertIsNone(redirected.get_header('Authorization'))
self.assertEqual(redirected.full_url,target)
for bad in [target.replace('git.dcserve.ru','example.com'),target.replace('/6/','/7/'),
target+'&extra=1',target+'&sig='+'c'*43,target.replace('https:','http:')]:
with self.subTest(url=bad),self.assertRaises(SourceError):NoRedirect().redirect_request(req,None,302,'',{},bad)
with self.assertRaises(SourceError):NoRedirect().redirect_request(redirected,None,302,'',{},target)
def test_duplicate_json_keys_and_token_format(self):
for value in [b'{"id":1,"id":2}',b'invalid',b'\xff']:
with self.assertRaises(SourceError):strict_json(value)
for token in ['', 'A'*40,'a'*40+'\n','secret']:
with self.assertRaises(SourceError):GiteaSource(token)
def test_paginated_complete_unique(self):
with mock.patch.object(self.s,'request',side_effect=[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=51,items=[dict(id=51)])]) as get:
self.assertEqual(len(self.s.pages('/actions/runs','items')),51)
self.assertEqual(get.call_args.args[0],'/actions/runs?page=2&limit=50')
def test_partial_changed_and_duplicate_pages_fail(self):
scenarios=[
[dict(total_count=2,items=[dict(id=1)])],
[dict(total_count=2,items=[dict(id=1),dict(id=1)])],
[dict(total_count=True,items=[])],
[dict(total_count=51,items=[dict(id=n) for n in range(1,51)]),dict(total_count=50,items=[])],
]
for pages in scenarios:
with self.subTest(pages=len(pages)),mock.patch.object(self.s,'request',side_effect=pages),self.assertRaises(SourceError):self.s.pages('/actions/runs','items')
def test_run_nested_repository_identity_not_broken_top_level_field(self):
r=run();r['repository_id']=0;self.s.validate_run(r)
r['repository']['id']=39
with self.assertRaises(SourceError):self.s.validate_run(r)
def test_discovery_rejects_change_between_complete_scans(self):
with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[run()],[run(),run(9,C)]]),self.assertRaises(SourceError):self.s.discover()
def test_discovery_allows_status_progress_without_loss(self):
pending=run();pending.update(status='in_progress',conclusion=None)
with mock.patch.object(self.s,'repository'),mock.patch.object(self.s,'pages',side_effect=[[pending],[run()]]):self.assertEqual(self.s.discover(),[run()])
def test_success_must_have_exact_job_and_steps(self):
r=run();row=dict(id=8,number=8,sha=B,attempt=1)
with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[job(r)]):self.assertEqual(self.s.successful_run(row),r)
for field,value in [('runner_id',2),('labels',['ubuntu-latest']),('steps',[]),('head_sha',A),('conclusion','failure')]:
j=job(r);j[field]=value
with mock.patch.object(self.s,'run',return_value=r),mock.patch.object(self.s,'pages',return_value=[j]),self.assertRaises(SourceError):self.s.successful_run(row)
def test_ancestry_proves_both_edges_and_stable_main(self):
graph={C:[B],B:[A],A:[]}
def get(path):
sha=path.rsplit('/',1)[1]
return dict(sha=sha,parents=[dict(sha=p) for p in graph[sha]])
with mock.patch.object(self.s,'request',side_effect=get),mock.patch.object(self.s,'main_commit',return_value=C):
self.assertEqual(self.s.prove_lineage(A,B),C)
with self.assertRaises(SourceError):self.s.prove_lineage(B,A)
with self.assertRaises(SourceError):self.s.prove_lineage(B,B)
with mock.patch.object(self.s,'ancestor',return_value=True),mock.patch.object(self.s,'main_commit',side_effect=[B,C]),self.assertRaises(SourceError):self.s.prove_lineage(A,B)
def test_ancestry_malformed_and_bound(self):
with mock.patch.object(self.s,'request',return_value=dict(sha=B,parents=[dict(sha=C)])),self.assertRaisesRegex(SourceError,'ancestry_limit'):self.s.ancestor(A,B,limit=1)
with mock.patch.object(self.s,'request',return_value=dict(sha=C,parents=[])),self.assertRaisesRegex(SourceError,'commit_identity'):self.s.ancestor(A,B)
def test_zip_requires_exact_receipt_and_only_two_files(self):
r=run();receipt,data=unpack_artifact(packed(r),r)
self.assertEqual(receipt['sha256'],hashlib.sha256(data).hexdigest())
for change in [lambda d:d.update(sourceCommit=A),lambda d:d.update(deployed=True),lambda d:d.update(sha256='f'*64),lambda d:d.update(extra='value')]:
with self.assertRaises(SourceError):unpack_artifact(packed(r,change),r)
for name in ['../../script','runtime/token','.DS_Store']:
with self.assertRaises(SourceError):unpack_artifact(packed(r,names=[name]),r)
with self.assertRaises(SourceError):unpack_artifact(b'bad zip',r)
def test_artifact_owner_download_digest_bound_to_run(self):
r=run();blob=packed(r)
a=dict(id=8,name='device-core-release',workflow_run=dict(id=8,repository_id=38,head_sha=B),expired=False,size_in_bytes=len(blob))
with mock.patch.object(self.s,'pages',return_value=[a]),mock.patch.object(self.s,'request',return_value=blob):self.assertEqual(self.s.artifact(r)[0]['sourceCommit'],B)
a['workflow_run']['repository_id']=39
with mock.patch.object(self.s,'pages',return_value=[a]),self.assertRaises(SourceError):self.s.artifact(r)
if __name__=='__main__':unittest.main()
-240
View File
@@ -1,240 +0,0 @@
# Synology CI foundation
This additive `gitea-ci` component creates only the Gitea build runner. It does
not activate automatic production apply, change Gitea itself, recreate Device
Core, open a port or modify application databases. Track activation in
DCPLATFORM-37; the canonical runner extension belongs to DCPLATFORM-21.
Initial policy: Device Core push to main automatically qualifies, then deploys
once the separate production controller and recurring release contract have
been accepted. Later repositories receive explicit registrations/policies.
## Reviewed contract
- Root: `/volume1/docker/nodedc-gitea-ci`.
- Compose project: `nodedc-gitea-ci`; selected service: `build-runner`.
- Three fixed data files: Compose, runner config, versioned descriptor.
- Runner and Node images use official Linux amd64 manifest digests (not mutable
tags), resolved from Docker Hub on 2026-09-29. The deploy runner pulls exactly
these two digests. No repository-provided image names or commands.
- Current Synology v4 profile: daemon and the single job share logical CPU7
through CPUSet. Their combined CPU ceiling is one logical CPU. Daemon:
CPU shares64, 512 MiB RAM+swap, readonly root filesystem. Job: CPU shares128,
2 GiB RAM+swap, no privileged mode, no host bind
mounts, no host execution label and no Docker socket in job containers.
- CPU shares also give low relative priority during contention. The NAS kernel
lacks a PIDs controller, so v4 does not set or claim a process-count limit.
V1/v2 retain their exact 0.5/1 NanoCPU quotas; v3 retains its shares-only/PIDs
profile. Historical configuration hashes are not changed.
- No published ports or host networking. Runner cache and metrics listeners
are disabled. Communication uses outbound HTTPS to the existing Gitea.
- Only the trusted runner daemon mounts the Docker socket. That daemon is
privileged infrastructure even with dropped Linux capabilities: access to
Docker is host authority. It is not passed to repository jobs.
- The first worker is registered for `SILVER/NODEDC_DEVICE_CORE`; sharing with
other repositories requires a reviewed enrollment/registry transition.
## Enrollment, separately from the artifact
Use the authenticated Gitea API to obtain the Device Core repository runner
registration token. Do not copy a personal Git token into the runner.
Stage `/volume1/docker/nodedc-deploy/runtime/gitea-ci/enrollment.pending.json`
through the operator's authenticated SMB session, containing only the exact
repository identity and its registration token. Never put this file in Git,
inbox, artifact payload, logs, Ops text or chat. This is a temporary handoff,
not the runtime secret. The NAS owner must be `dctouch` or root. The v2
preflight opens it with `O_NOFOLLOW`, rejects symlinks/hardlinks/special files,
limits the input to 2048 bytes, validates its schema and checks for concurrent
changes. Plan reports only safe filesystem metadata and does not change rights.
On 2026-09-29 the first v1 plan rejected this file's NAS metadata even though
the Mac SMB mount displayed 0700/regular/nlink1. A Mac `chmod 600` and a
successful Mac stat are not proof of the actual NAS permissions. V1's strict
private-file check is retained; use the explicit v2 import transition for SMB.
V2 apply creates the private file on NAS as root: `secrets/registration-token`
is 0600, its directory is 0700. Publication is atomic without overwriting an
existing identity, file and directory entries are fsynced, then the private
copy is revalidated. Only after that is the staging input removed. A mismatch
with an existing private copy is rejected. An interrupted apply can reuse the
same verified private copy after the canonical failure/retry review. Gitea
creates the persistent `/data/.runner` identity on first start. Neither private
file is part of the artifact, source backup, journal or diagnostic output.
The bootstrap accepts no existing installed CI descriptor or CI container.
Preflight reads Docker's actual resource capabilities before any runtime
mutation, and reports only allowlisted version/kernel/resource fields. V4
requires Linux amd64, CPUSet, CPU shares, memory/swap controls, at least eight
logical CPUs and CPU7 available in the installer's affinity. Acceptance also
verifies the actual daemon affinity is exactly CPU7. V3 requires a PIDs
controller; V1/v2 additionally require CFS period/quota. Missing or non-boolean
required capability values do not pass. Preflight also checks at least 8 GiB
free disk and 3 GiB currently available memory.
The v2 apply on 2026-09-29 imported the private token successfully and pulled
the pinned images, but Docker rejected `NanoCPUs`: this NAS kernel does not
provide the needed CFS bandwidth control. Canonical rollback completed with
`ok:gitea-ci-bootstrap`; the private enrollment is retained for v3 reuse.
Artifact `gitea-ci-bootstrap-v2-20260929-002` is terminal failed and must not be
restaged or retried. V3 uses separate reviewed `synology-v3/` configurations and
`bootstrap-v3.json`; historical payloads remain byte-for-byte reproducible.
The subsequent v3 plan established the actual host matrix: Docker24.0.2,
kernel4.4.302+, cgroupv1, x86_64, eight logical CPUs, MemTotal16743616512.
CPUSet/CPUShares/MemoryLimit/SwapLimit=true; CFS period/quota and PidsLimit=false.
It stopped before apply. V4 uses this verified matrix, with separate
`synology-v4/` templates and `bootstrap-v4.json`. The private token from the
rolled-back v2 attempt is reused. Neither v2 nor v3 is the next install target.
## Build and install
Before installing the runner, enable Actions at the **instance** level. On
2026-09-29, bootstrap v4 started correctly but could not register: the current
Gitea configuration explicitly contained `[actions] ENABLED=false`. The public
Actions Ping RPC returned 404 even though the REST registration-token endpoint
worked. The v4 attempt ended with `ok:gitea-ci-bootstrap` rollback; do not reuse
`gitea-ci-bootstrap-v4-20260929-004`. Increasing its registration deadline would
not enable the missing server routes.
The separate `gitea-actions-config` transition has exactly one data descriptor,
`deployment/actions-enable-v1.json`, built by `build_actions_artifact.py`. It
targets the existing `clean-gitea-20260820` container, using the verified
`/volume1/docker/gitea-clean-standalone-v1/compose.yaml` and `production.env`
context. The exact predecessor INI digest is registered in the root runner;
only the Actions boolean changes. Image, command, ports, bind mounts,
repositories, database and LFS remain in place. The existing Gitea container
restarts once, briefly interrupting Git web/SSH service. No Compose recreation,
image pull, new container, new listener or database rewrite occurs.
Plan verifies the effective source hashes, running container/mount/network/image
identity, healthy Gitea 1.27.2 and inactive Actions RPC. Apply keeps a root-only
configuration rollback copy under `nodedc-deploy/runtime/gitea-actions/<backup-id>`;
the shared source archive, artifact, Git, logs and Ops never receive its secrets.
The INI replacement preserves its owner and mode. Acceptance proves healthy
Gitea, the Actions Ping response, unchanged runtime configuration and the
unchanged identities/uptimes of every other container. Failure restores the
exact predecessor and restarts the same container; unrelated drift is rejected.
Install this transition first through runner promotion, fresh plan and apply.
Verify public Actions Ping after `deploy-ok`, then install a new CI bootstrap
patch on the unchanged v4 resource profile. CI preflight now requires the actual
public Actions Ping before runtime mutation. CI rollback records only fixed
startup-error categories/counts, never raw container logs or tokens.
```sh
python3 infra/gitea-ci/build_actions_artifact.py --patch-id gitea-actions-enable-v1-<unique-id> --source-commit <full-sha> --output-dir <output-dir>
```
### Recovery of Actions enable attempt 20260929-001
The first Actions apply stopped before replacing `app.ini` or restarting Gitea,
with `Gitea Actions runtime changed before mutation`. Its rollback repeated the
same fingerprint comparison and failed. Treat the failed archive, journal and
backup as evidence, not as permission to replay the artifact.
The legacy fingerprint compares `docker inspect` JSON including array order.
Docker 24.0.2 constructs
[mount points from a Go map](https://github.com/moby/moby/blob/v24.0.2/container/container_unix.go#L425-L440)
and [default ulimits from a map](https://github.com/moby/moby/blob/v24.0.2/daemon/oci_linux.go#L1012-L1026).
Their order can change without changing the container. Local tests reproduce the
false drift and preserve rejection of changed values, ordered command/env arrays,
image, ports and container identity. This explains a possible failure; the live
NAS must prove that it explains this specific attempt before another apply.
`actions-enable.v2` is a separate, bounded recovery for exactly that failed
attempt. Its read-only `plan` checks the failed journal, failed archive and saved
receipt digests, unchanged disabled config, leftover v1 descriptor, fixed Compose
context, same healthy Gitea and all other container identities/uptimes. For each
of the fresh inspections it must reconstruct the saved legacy fingerprint by
changing only Mounts and HostConfig.Ulimits order, retaining every field and value.
Duplicate mount destinations or limit names are rejected. Any unexplained
difference rejects the plan before mutation.
The initial v2 plan exposed a second algorithm defect: its up-front factorial
count exceeded 4096 before any matching was attempted. The corrected audit does
not enumerate permutations. It collects the actual orders returned by Docker,
their cyclic rotations, and rotations of canonical/reversed order. It tests
combinations of the two catalogs against the exact saved SHA-256; it never
assumes that an unobserved ordering is correct without that hash match. Each
fresh sample must have the same canonical fingerprint, so values from different
runtime configurations cannot be mixed into a proof. A direct legacy hash match
is also accepted without searching.
The audit collects at most 64 samples for the search and two further samples to
confirm a found proof. Each catalog has at most 256 orders, and at most 65536
distinct combinations are hashed; identical observations do not repeat the
search. These are bounds on read-only evidence collection, not on valid list
lengths via factorial size. An incomplete search fails closed with counts and
the last three fingerprint samples. The report never includes raw inspect data
or credentials. Regression tests cover 8 mounts/16 limits, a proof requiring
different observations for the two collections, changing values during sampling,
and exhaustion of the read-only search without mutation. This is an exact-match
search over a bounded candidate set, not an exhaustive solver for arbitrary
permutations; absence of a match is not itself proof of runtime drift.
Only after that plan has been reviewed can a separate apply repeat the audit
under the deploy lock and perform the same one-boolean transition. New comparison
and acceptance sort the two unordered collections. All other preservation checks
stay in force. A pre-mutation failure performs no Docker restart. A failure after
mutation restores the disabled config and removes only the v2 source descriptor;
the v1 marker and original failed evidence remain intact. The v2 backup records
the fingerprint version and reconciled attempt. Historical artifact bytes and
legacy Gitea recovery branches remain unchanged.
```sh
python3 infra/gitea-ci/build_actions_artifact.py --patch-id gitea-actions-enable-v2-<unique-id> --source-commit <full-sha> --output-dir <output-dir>
```
At preparation time, live order equivalence is still unverified and instance
Actions, build-runner registration and automatic production deployment remain
unfinished. Promote the reviewed root runner, run only a fresh read-only v2 plan,
review its three audit samples, and then decide the next registered action.
From a clean Platform commit:
```sh
python3 -m unittest discover -s infra/gitea-ci -p 'test_*.py'
python3 infra/gitea-ci/build_artifact.py --patch-id gitea-ci-bootstrap-v4-<unique-id> --source-commit <full-sha> --output-dir <output-dir>
```
The first use requires promotion of the reviewed root runner through the
separate atomic administrative gate and fresh `verify-install`. Stage the
immutable `.tgz` in the canonical inbox and inspect its lifecycle. Obtain a
fresh `nodedc-deploy plan`, review exact scope, then apply that artifact once.
`apply` snapshots the source partition and identities of all preexisting
containers. Acceptance checks the pinned image, Compose identity, mounts,
resource limits, privileges and absence of port publications. It requires
registration plus ten seconds of stable daemon operation and unchanged
preexisting container identities. All secrets and application data are outside
the artifact/backup source partition.
If startup or acceptance fails, rollback removes only `build-runner` and
restores only the three source paths. Runner registration and enrollment are
preserved for diagnosis. A failed attempt may leave an offline registration in
Gitea; do not create another token or delete persistent identity blindly.
The global failed-artifact replay rule remains in force.
After `deploy-ok`, verify online registration and a real qualification job via
Gitea API/UI. This is separate functional acceptance; do not ask an operator
to re-prove Docker/runtime checks with NAS shell commands. Do not describe the
runner bootstrap or a green build as a completed automatic production deploy.
## Validation baseline
Installed predecessor confirmed by the operator on 2026-09-29:
`f21936f131365bd3993e2d746e332538d628ba50ef62c1cce833161171ffde47`,
Python 3.8.15, `verify-install-ok`. This matches Platform commit
`11b73e64681f83aa2ebfd89ef266d3be2869f7e1`. The older SMB runner copy is not the
installed authority. Historical Gitea recovery guards remain unchanged.
Tests cover deterministic packaging, exact runtime/payload boundaries, secret
file handling, bootstrap reuse rejection, preserved container identity, real
synthetic-host apply receipts, and failed-health source rollback with runtime
registration retained. Existing Platform/Device/Gitea regression suites are
also required before promotion.
References: [official runner configuration](https://docs.gitea.com/runner/configuration/),
[Docker installation](https://docs.gitea.com/runner/installation/docker/),
[Docker resource constraints](https://docs.docker.com/engine/containers/resource_constraints/),
[Docker capabilities API](https://docs.docker.com/reference/api/engine/version/v1.40/).
-7
View File
@@ -1,7 +0,0 @@
{
"schemaVersion": "nodedc.gitea.actions-enable.v1",
"releaseId": "__PATCH_ID__",
"action": "enable-instance-actions",
"service": "gitea",
"productionDeployEnabled": false
}
-8
View File
@@ -1,8 +0,0 @@
{
"schemaVersion": "nodedc.gitea.actions-enable.v2",
"releaseId": "__PATCH_ID__",
"action": "enable-instance-actions",
"service": "gitea",
"productionDeployEnabled": false,
"reconcilesFailedAttempt": "gitea-actions-enable-v1-20260929-001"
}
-11
View File
@@ -1,11 +0,0 @@
{
"schemaVersion": "nodedc.gitea-ci.bootstrap.v1",
"releaseId": "__PATCH_ID__",
"action": "bootstrap-build-runner",
"repository": "SILVER/NODEDC_DEVICE_CORE",
"instance": "https://git.dcserve.ru",
"runnerName": "synology-device-core-build",
"productionDeployEnabled": false,
"publishedPorts": [],
"capacity": 1
}
-12
View File
@@ -1,12 +0,0 @@
{
"schemaVersion": "nodedc.gitea-ci.bootstrap.v2",
"releaseId": "__PATCH_ID__",
"action": "bootstrap-build-runner",
"repository": "SILVER/NODEDC_DEVICE_CORE",
"instance": "https://git.dcserve.ru",
"runnerName": "synology-device-core-build",
"productionDeployEnabled": false,
"publishedPorts": [],
"capacity": 1,
"enrollment": "import-dctouch-staging-to-root-private-runtime"
}
-13
View File
@@ -1,13 +0,0 @@
{
"schemaVersion": "nodedc.gitea-ci.bootstrap.v3",
"releaseId": "__PATCH_ID__",
"action": "bootstrap-build-runner",
"repository": "SILVER/NODEDC_DEVICE_CORE",
"instance": "https://git.dcserve.ru",
"runnerName": "synology-device-core-build",
"productionDeployEnabled": false,
"publishedPorts": [],
"capacity": 1,
"enrollment": "import-dctouch-staging-to-root-private-runtime",
"resourceProfile": "synology-cpu-shares-v1"
}
-13
View File
@@ -1,13 +0,0 @@
{
"schemaVersion": "nodedc.gitea-ci.bootstrap.v4",
"releaseId": "__PATCH_ID__",
"action": "bootstrap-build-runner",
"repository": "SILVER/NODEDC_DEVICE_CORE",
"instance": "https://git.dcserve.ru",
"runnerName": "synology-device-core-build",
"productionDeployEnabled": false,
"publishedPorts": [],
"capacity": 1,
"enrollment": "import-dctouch-staging-to-root-private-runtime",
"resourceProfile": "synology-cpuset-v1"
}
-65
View File
@@ -1,65 +0,0 @@
#!/usr/bin/env python3
"""Build the data-only, fixed Gitea Actions activation transition."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import re
import subprocess
import tarfile
ROOT = Path(__file__).resolve().parents[2]
SOURCE = Path(__file__).resolve().parent
ENTRY = "deployment/actions-enable-v1.json"
def descriptor_entry(patch_id):
match = re.fullmatch(r"gitea-actions-enable-(v[12])-[a-zA-Z0-9._-]{1,65}", patch_id)
if not match:
raise ValueError("invalid_actions_transition_identity")
return "deployment/actions-enable-" + match.group(1) + ".json"
def bundle(patch_id):
entry = descriptor_entry(patch_id)
descriptor = json.loads((SOURCE / Path(entry).name).read_text())
descriptor["releaseId"] = patch_id
files = {
"manifest.env": ("id=" + patch_id + "\ncomponent=gitea-actions-config\ntype=app-overlay\n").encode(),
"files.txt": (entry + "\n").encode(),
"payload/" + entry: (json.dumps(descriptor, indent=2) + "\n").encode(),
}
output = io.BytesIO()
with gzip.GzipFile(fileobj=output, mode="wb", filename="", mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as archive:
for name, data in sorted(files.items()):
info = tarfile.TarInfo(name)
info.size, info.mode, info.mtime = len(data), 0o644, 0
archive.addfile(info, io.BytesIO(data))
return output.getvalue()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--patch-id", required=True)
parser.add_argument("--source-commit", required=True)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args()
actual = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
if actual != args.source_commit or subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT, text=True).strip():
raise SystemExit("clean_matching_commit_required")
data = bundle(args.patch_id)
args.output_dir.mkdir(parents=True, exist_ok=True)
path = args.output_dir / ("nodedc-" + args.patch_id + ".tgz")
with path.open("xb") as stream:
stream.write(data)
print(json.dumps({"artifact": str(path.resolve()), "patchId": args.patch_id,
"component": "gitea-actions-config", "sourceCommit": actual,
"sha256": hashlib.sha256(data).hexdigest(), "entries": [descriptor_entry(args.patch_id)],
"services": ["gitea"], "newPorts": [], "productionDeployEnabled": False}))
if __name__ == "__main__":
main()
-86
View File
@@ -1,86 +0,0 @@
#!/usr/bin/env python3
"""Build the immutable, data-only Gitea CI bootstrap artifact from a clean commit."""
import argparse
import gzip
import hashlib
import io
import json
from pathlib import Path
import re
import subprocess
import tarfile
ROOT = Path(__file__).resolve().parents[2]
SOURCE = Path(__file__).resolve().parent
ENTRIES = ("docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v1.json")
V2_ENTRIES = ("docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v2.json")
V3_ENTRIES = ("docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v3.json")
V4_ENTRIES = ("docker-compose.gitea-ci.yml", "runner.yaml", "deployment/bootstrap-v4.json")
def entries_for(patch_id):
if not re.fullmatch(r"gitea-ci-bootstrap-v[1234]-[a-zA-Z0-9._-]{1,65}", patch_id):
raise ValueError("invalid_bootstrap_identity")
if patch_id.startswith("gitea-ci-bootstrap-v4-"):
return V4_ENTRIES
if patch_id.startswith("gitea-ci-bootstrap-v3-"):
return V3_ENTRIES
return V2_ENTRIES if patch_id.startswith("gitea-ci-bootstrap-v2-") else ENTRIES
def bundle(patch_id, source=SOURCE):
entries = entries_for(patch_id)
config_source = source / "synology-v4" if entries == V4_ENTRIES else source / "synology-v3" if entries == V3_ENTRIES else source
descriptor = json.loads((source / Path(entries[2]).name).read_text())
if descriptor["releaseId"] != "__PATCH_ID__":
raise ValueError("bootstrap_template_identity_mismatch")
descriptor["releaseId"] = patch_id
files = {
"manifest.env": ("id=" + patch_id + "\ncomponent=gitea-ci\ntype=app-overlay\n").encode(),
"files.txt": ("\n".join(entries) + "\n").encode(),
"payload/docker-compose.gitea-ci.yml": (config_source / ENTRIES[0]).read_bytes(),
"payload/runner.yaml": (config_source / ENTRIES[1]).read_bytes(),
"payload/" + entries[2]: (json.dumps(descriptor, indent=2) + "\n").encode(),
}
result = io.BytesIO()
with gzip.GzipFile(fileobj=result, mode="wb", filename="", mtime=0) as compressed:
with tarfile.open(fileobj=compressed, mode="w", format=tarfile.USTAR_FORMAT) as archive:
for name, content in sorted(files.items()):
info = tarfile.TarInfo(name)
info.size = len(content)
info.mode = 0o644
info.mtime = 0
archive.addfile(info, io.BytesIO(content))
return result.getvalue()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--patch-id", required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--source-commit", required=True)
args = parser.parse_args()
actual = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
if not re.fullmatch(r"[a-f0-9]{40}", args.source_commit) or actual != args.source_commit:
raise SystemExit("source_commit_mismatch")
dirty = subprocess.check_output(["git", "status", "--porcelain"], cwd=ROOT, text=True).strip()
if dirty:
raise SystemExit("clean_committed_source_required")
data = bundle(args.patch_id)
args.output_dir.mkdir(parents=True, exist_ok=True)
path = args.output_dir / ("nodedc-gitea-ci-" + args.patch_id + ".tgz")
with path.open("xb") as output:
output.write(data)
print(json.dumps({
"artifact": str(path.resolve()), "patchId": args.patch_id,
"component": "gitea-ci", "sourceCommit": actual,
"sha256": hashlib.sha256(data).hexdigest(),
"entries": entries_for(args.patch_id),
"services": ["build-runner"], "publishedPorts": [],
"productionDeployEnabled": False,
}))
if __name__ == "__main__":
main()
@@ -1,41 +0,0 @@
services:
build-runner:
image: docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14
platform: linux/amd64
pull_policy: never
restart: unless-stopped
read_only: true
cpus: 0.5
mem_limit: 512m
pids_limit: 128
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs:
- /tmp:rw,nosuid,nodev,size=134217728
environment:
HOME: /data
XDG_CACHE_HOME: /data/.cache
CONFIG_FILE: /config/runner.yaml
GITEA_INSTANCE_URL: https://git.dcserve.ru
GITEA_RUNNER_NAME: synology-device-core-build
GITEA_RUNNER_REGISTRATION_TOKEN_FILE: /run/secrets/registration-token
volumes:
- type: bind
source: /volume1/docker/nodedc-gitea-ci/runner.yaml
target: /config/runner.yaml
read_only: true
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/data
target: /data
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/secrets/registration-token
target: /run/secrets/registration-token
read_only: true
bind: {create_host_path: false}
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
bind: {create_host_path: false}
-26
View File
@@ -1,26 +0,0 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 1h
shutdown_timeout: 45m
insecure: false
fetch_interval: 5s
env_file: ""
envs:
NODE_OPTIONS: --max-old-space-size=1536
labels:
- nodedc-node22-build:docker://docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb
cache:
enabled: false
container:
network: ""
privileged: false
options: --cpus=1 --memory=2g --memory-swap=2g --pids-limit=256 --cap-drop=ALL --security-opt=no-new-privileges
valid_volumes: []
docker_host: "-"
force_pull: false
bind_workdir: false
metrics:
enabled: false
@@ -1,41 +0,0 @@
services:
build-runner:
image: docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14
platform: linux/amd64
pull_policy: never
restart: unless-stopped
read_only: true
cpu_shares: 64
mem_limit: 512m
pids_limit: 128
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs:
- /tmp:rw,nosuid,nodev,size=134217728
environment:
HOME: /data
XDG_CACHE_HOME: /data/.cache
CONFIG_FILE: /config/runner.yaml
GITEA_INSTANCE_URL: https://git.dcserve.ru
GITEA_RUNNER_NAME: synology-device-core-build
GITEA_RUNNER_REGISTRATION_TOKEN_FILE: /run/secrets/registration-token
volumes:
- type: bind
source: /volume1/docker/nodedc-gitea-ci/runner.yaml
target: /config/runner.yaml
read_only: true
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/data
target: /data
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/secrets/registration-token
target: /run/secrets/registration-token
read_only: true
bind: {create_host_path: false}
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
bind: {create_host_path: false}
-26
View File
@@ -1,26 +0,0 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 1h
shutdown_timeout: 45m
insecure: false
fetch_interval: 5s
env_file: ""
envs:
NODE_OPTIONS: --max-old-space-size=1536
labels:
- nodedc-node22-build:docker://docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb
cache:
enabled: false
container:
network: ""
privileged: false
options: --cpu-shares=128 --memory=2g --pids-limit=256 --cap-drop=ALL --security-opt=no-new-privileges
valid_volumes: []
docker_host: "-"
force_pull: false
bind_workdir: false
metrics:
enabled: false
@@ -1,42 +0,0 @@
services:
build-runner:
image: docker.io/gitea/runner@sha256:05e100d9c2268fb300f929cab014e9930591a2d66822454e175c1099d1464b14
platform: linux/amd64
pull_policy: never
restart: unless-stopped
read_only: true
cpu_shares: 64
cpuset: "7"
mem_limit: 512m
memswap_limit: 512m
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
tmpfs:
- /tmp:rw,nosuid,nodev,size=134217728
environment:
HOME: /data
XDG_CACHE_HOME: /data/.cache
CONFIG_FILE: /config/runner.yaml
GITEA_INSTANCE_URL: https://git.dcserve.ru
GITEA_RUNNER_NAME: synology-device-core-build
GITEA_RUNNER_REGISTRATION_TOKEN_FILE: /run/secrets/registration-token
volumes:
- type: bind
source: /volume1/docker/nodedc-gitea-ci/runner.yaml
target: /config/runner.yaml
read_only: true
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/data
target: /data
bind: {create_host_path: false}
- type: bind
source: /volume1/docker/nodedc-gitea-ci/secrets/registration-token
target: /run/secrets/registration-token
read_only: true
bind: {create_host_path: false}
- type: bind
source: /var/run/docker.sock
target: /var/run/docker.sock
read_only: true
bind: {create_host_path: false}
-26
View File
@@ -1,26 +0,0 @@
log:
level: info
runner:
file: /data/.runner
capacity: 1
timeout: 1h
shutdown_timeout: 45m
insecure: false
fetch_interval: 5s
env_file: ""
envs:
NODE_OPTIONS: --max-old-space-size=1536
labels:
- nodedc-node22-build:docker://docker.io/library/node@sha256:9887ee8a5e5aa4fb02e09f03cdf81ef1b52184665549836fe3943eb0c2eaefdb
cache:
enabled: false
container:
network: ""
privileged: false
options: --cpuset-cpus=7 --cpu-shares=128 --memory=2g --memory-swap=2g --cap-drop=ALL --security-opt=no-new-privileges
valid_volumes: []
docker_host: "-"
force_pull: false
bind_workdir: false
metrics:
enabled: false
-249
View File
@@ -1,249 +0,0 @@
import copy
from contextlib import ExitStack, redirect_stdout
import hashlib
import io
import json
import os
from pathlib import Path
import stat
import subprocess
import tempfile
from types import SimpleNamespace
import unittest
from unittest import mock
import build_actions_artifact
from test_bootstrap import RUNNER
class ActionsEnableTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
self.config = self.root / "instance/config/app.ini"
self.config.parent.mkdir(parents=True)
self.original = b"APP_NAME = Gitea\n[security]\nSECRET_KEY = fixture-keep-private\n[actions]\nENABLED = false\n[server]\nHTTP_PORT = 3000\n"
self.target = self.original.replace(b"ENABLED = false", b"ENABLED = true")
self.config.write_bytes(self.original)
self.config.chmod(0o640)
self.backup = self.root / "backup"
self.backup.mkdir()
self.metadata = self.config.stat()
self.stack = ExitStack()
self.addCleanup(self.stack.close)
for name, value in {"GITEA_ACTIONS_CONFIG": self.config,
"GITEA_ACTIONS_ROOT": self.root / "meta",
"RUNTIME_DIR": self.root / "runtime",
"GITEA_ACTIONS_BEFORE": hashlib.sha256(self.original).hexdigest(),
"GITEA_ACTIONS_AFTER": hashlib.sha256(self.target).hexdigest()}.items():
self.stack.enter_context(mock.patch.object(RUNNER, name, value))
self.info = {"Id": "verified-id", "Name": "/clean-gitea-20260820", "Image": "sha256:fixture",
"Config": {"Image": RUNNER.GITEA_ACTIONS_IMAGE,
"Cmd": ["web", "--config", "/etc/gitea/app.ini"],
"Env": ["HOME=/var/lib/gitea/git"],
"Labels": {"com.docker.compose.project": "clean-gitea", "com.docker.compose.service": "gitea"}},
"HostConfig": {"NetworkMode": "clean-gitea_clean_gitea", "PortBindings": {"3000/tcp": [{"HostIp": "172.22.0.222", "HostPort": "3000"}], "2222/tcp": [{"HostIp": "0.0.0.0", "HostPort": "4022"}]}},
"State": {"Running": True, "Health": {"Status": "healthy"}},
"Mounts": [{"Source": str(self.config), "Destination": "/etc/gitea/app.ini", "RW": False},
{"Source": str(self.config.parent.parent / "data"), "Destination": "/var/lib/gitea", "RW": True}],
"NetworkSettings": {"Networks": {"clean-gitea_clean_gitea": {"IPAddress": "172.22.27.2"}}}}
self.before = {"config": self.original, "metadata": self.metadata, "containerId": self.info["Id"],
"fingerprint": RUNNER.gitea_actions_fingerprint(self.info), "inventory": {"other": {"running": True}}}
def test_bundle_selects_one_service_and_only_data_descriptor(self):
patch = "gitea-actions-enable-v1-test-001"
artifact = self.root / "test.tgz"
artifact.write_bytes(build_actions_artifact.bundle(patch))
self.assertEqual(artifact.read_bytes(), build_actions_artifact.bundle(patch))
work = self.root / "work"
work.mkdir()
manifest, entries, payload = RUNNER.load_artifact(artifact, work)
self.assertEqual(manifest["component"], "gitea-actions-config")
self.assertEqual(entries, [RUNNER.GITEA_ACTIONS_ENTRY])
self.assertEqual(RUNNER.component_services(manifest["component"], entries), ("gitea",))
self.assertEqual(RUNNER.component_builds(manifest["component"], entries), ())
path = payload / entries[0]
value = json.loads(path.read_text())
value["service"] = "postgres"
path.write_text(json.dumps(value))
with self.assertRaisesRegex(RUNNER.DeployError, "descriptor mismatch"):
RUNNER.validate_gitea_actions_payload(payload, entries, patch)
for rel in ("app.ini", "secrets/token", "data/gitea.db", "compose.yaml"):
with self.subTest(rel=rel), self.assertRaises(RUNNER.DeployError):
RUNNER.allowed_payload_path(manifest["component"], rel)
def test_exact_boolean_change_and_unrelated_drift_rejection(self):
self.assertEqual(RUNNER.gitea_actions_transform(self.original), self.target)
with self.assertRaisesRegex(RUNNER.DeployError, "predecessor"):
RUNNER.gitea_actions_transform(self.original + b"# unrelated change\n")
with self.assertRaises(RUNNER.DeployError):
RUNNER.gitea_actions_transform(self.target)
def test_atomic_update_preserves_permissions_and_rejects_concurrent_edit(self):
RUNNER.gitea_actions_replace(RUNNER.GITEA_ACTIONS_BEFORE, self.target, self.metadata)
self.assertEqual(self.config.read_bytes(), self.target)
self.assertEqual(stat.S_IMODE(self.config.stat().st_mode), 0o640)
self.assertEqual(self.config.stat().st_uid, self.metadata.st_uid)
with self.assertRaisesRegex(RUNNER.DeployError, "changed before"):
RUNNER.gitea_actions_replace(RUNNER.GITEA_ACTIONS_BEFORE, self.target, self.metadata)
def test_runtime_rejects_wrong_identity_mounts_and_actions_env_override(self):
for field, value in (("Image", "other-image"), ("Cmd", ["other"]), ("Env", ["GITEA__actions__ENABLED=false"])):
info = copy.deepcopy(self.info)
info["Config"][field] = value
with mock.patch.object(RUNNER, "inspect_container", return_value=info):
with self.subTest(field=field), self.assertRaises(RUNNER.DeployError):
RUNNER.gitea_actions_container()
info = copy.deepcopy(self.info)
info["Mounts"][0]["RW"] = True
with mock.patch.object(RUNNER, "inspect_container", return_value=info):
with self.assertRaisesRegex(RUNNER.DeployError, "mounts"):
RUNNER.gitea_actions_container()
def test_config_links_are_rejected(self):
sibling = self.config.with_name('other.ini')
os.link(self.config, sibling)
with self.assertRaisesRegex(RUNNER.DeployError, "metadata"):
RUNNER.gitea_actions_read_config()
self.config.unlink()
self.config.symlink_to(sibling)
with self.assertRaises(OSError):
RUNNER.gitea_actions_read_config()
def test_preflight_binds_healthy_runtime_to_image_and_inactive_rpc(self):
sources = {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff",
"production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7"}
with mock.patch.object(RUNNER, "sha256_file", side_effect=lambda p:sources[p.name]), mock.patch.object(RUNNER, "inspect_container", return_value=self.info), mock.patch.object(RUNNER, "inspect_local_image", return_value=self.info["Image"]), mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (404,None)]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value={**self.before["inventory"],self.info["Id"]:{"running":True}}):
before = RUNNER.preflight_gitea_actions()
self.assertEqual(before["inventory"], self.before["inventory"])
self.assertEqual(before["config"], self.original)
self.assertEqual(before["fingerprint"], self.before["fingerprint"])
def test_preservation_acceptance_rejects_changed_container_configuration(self):
info = copy.deepcopy(self.info)
info["HostConfig"]["Memory"] = 123
with mock.patch.object(RUNNER, "gitea_actions_container", return_value=info), mock.patch.object(RUNNER.time, "monotonic", side_effect=[0,121]):
with self.assertRaisesRegex(RUNNER.DeployError, "runtime configuration drift"):
RUNNER.accept_gitea_actions(self.before)
def test_rpc_preflight_rejects_rest_only_instance(self):
with mock.patch.object(RUNNER, "gitea_actions_http", return_value=(404, None)):
with self.assertRaisesRegex(RUNNER.DeployError, "HTTP 404"):
RUNNER.require_gitea_actions_ping()
with mock.patch.object(RUNNER, "gitea_actions_http", return_value=(200, {"data": "Hello, nodedc-ci-probe!"})):
RUNNER.require_gitea_actions_ping()
with mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.root / "empty-ci"), mock.patch.object(RUNNER, "gitea_ci_host_capabilities"), mock.patch.object(RUNNER, "require_gitea_actions_ping", side_effect=RUNNER.DeployError("HTTP 404")), mock.patch.object(RUNNER, "gitea_ci_container_ids") as containers:
with self.assertRaisesRegex(RUNNER.DeployError, "HTTP 404"):
RUNNER.preflight_gitea_ci(RUNNER.GITEA_CI_V4_ENTRIES)
containers.assert_not_called()
def test_apply_private_snapshot_and_failed_restart_can_restore_stopped_container(self):
with mock.patch.object(RUNNER.os, "chown"), mock.patch.object(RUNNER.os, "fchown"), mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run", side_effect=subprocess.CalledProcessError(1, ["docker", "restart"])):
with self.assertRaises(subprocess.CalledProcessError):
RUNNER.apply_gitea_actions(self.before, self.backup)
self.assertEqual(self.config.read_bytes(), self.target)
private = RUNNER.RUNTIME_DIR / "gitea-actions" / self.backup.name / "app.ini.before"
self.assertEqual(private.read_bytes(), self.original)
self.assertEqual(stat.S_IMODE(private.stat().st_mode), 0o600)
self.assertNotIn("fixture-keep-private", (self.backup / "gitea-actions-before.json").read_text())
stopped = copy.deepcopy(self.info)
stopped["State"]["Running"] = False
stopped["NetworkSettings"]["Networks"]["clean-gitea_clean_gitea"]["IPAddress"] = ""
with mock.patch.object(RUNNER, "inspect_container", return_value=stopped), mock.patch.object(RUNNER.subprocess, "run") as restart, mock.patch.object(RUNNER, "accept_gitea_actions") as accept, mock.patch.object(RUNNER, "restore_overlay_source"):
RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_ENTRY], "stamp", self.before, True)
restart.assert_called_once()
accept.assert_called_once_with(self.before, enabled=False)
self.assertEqual(self.config.read_bytes(), self.original)
def test_rollback_refuses_to_overwrite_unrelated_changes(self):
self.config.write_bytes(self.target + b"# concurrent change")
with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run") as restart:
with self.assertRaisesRegex(RUNNER.DeployError, "unrelated config drift"):
RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_ENTRY], "stamp", self.before, True)
restart.assert_not_called()
def test_acceptance_proves_rpc_version_runtime_and_other_containers(self):
self.config.write_bytes(self.target)
with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (200,{"data":"Hello, nodedc-ci-probe!"})]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"]), redirect_stdout(io.StringIO()):
RUNNER.accept_gitea_actions(self.before)
def test_startup_diagnostics_never_save_raw_tokens_or_logs(self):
result = SimpleNamespace(stdout="runner registration token fixture-SECRET 404 not found", stderr="Authorization: another-secret")
with mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=["ci-container"]), mock.patch.object(RUNNER.subprocess, "run", return_value=result), redirect_stdout(io.StringIO()) as output:
RUNNER.capture_gitea_ci_diagnostics(self.backup)
data = (self.backup / "ci-startup-diagnostics.json").read_text()
for secret in ("fixture-SECRET", "another-secret", "Authorization"):
self.assertNotIn(secret, data + output.getvalue())
self.assertIn("actions-disabled-or-route", data)
def full_apply(self, fail_acceptance=False, version="v1"):
host = self.root / "host"
host.mkdir()
paths = {name: host / name.lower() for name in (
"INBOX", "APPLIED_DIR", "FAILED_DIR", "BACKUPS_DIR", "STATE_DIR", "TMP_DIR", "RUNTIME_DIR")}
for path in paths.values():
path.mkdir()
paths.update({"STATE_FILE": paths["STATE_DIR"] / "applied.jsonl",
"FAILED_STATE_FILE": paths["STATE_DIR"] / "failed.jsonl",
"LOCK_DIR": paths["STATE_DIR"] / "deploy.lock", "DOCKER": Path("/usr/bin/true")})
legacy = host / "legacy"
legacy.mkdir()
for name in ("compose.yaml", "production.env"):
(legacy / name).write_text("fixture")
root = host / "metadata"
registry = {**RUNNER.COMPONENTS["gitea-actions-config"], "payload_root": root,
"compose_root": legacy, "compose_files": (legacy / "compose.yaml",),
"compose_env_file": legacy / "production.env"}
artifact = paths["INBOX"] / "actions.tgz"
artifact.write_bytes(build_actions_artifact.bundle("gitea-actions-enable-" + version + "-full-test"))
if version == "v2":
(root / RUNNER.GITEA_ACTIONS_ENTRY).parent.mkdir(parents=True)
(root / RUNNER.GITEA_ACTIONS_ENTRY).write_bytes(b"preserved failed-attempt marker")
self.before.update({"fingerprint": RUNNER.gitea_actions_fingerprint_v2(self.info),
"fingerprintVersion": 2, "mutationStarted": False})
with ExitStack() as stack:
for name, value in paths.items():
stack.enter_context(mock.patch.object(RUNNER, name, value))
stack.enter_context(mock.patch.dict(RUNNER.COMPONENTS, {"gitea-actions-config": registry}))
stack.enter_context(mock.patch.object(RUNNER, "require_root"))
stack.enter_context(mock.patch.object(RUNNER.os, "chown"))
stack.enter_context(mock.patch.object(RUNNER.os, "fchown"))
stack.enter_context(mock.patch.object(RUNNER, "preflight_gitea_actions", return_value=self.before))
stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info))
stack.enter_context(mock.patch.object(RUNNER.subprocess, "run"))
if fail_acceptance:
accept = stack.enter_context(mock.patch.object(RUNNER, "accept_gitea_actions", side_effect=[RUNNER.DeployError("synthetic RPC failure"), None]))
else:
stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}), (200,{"data":"Hello, nodedc-ci-probe!"})]))
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"]))
with redirect_stdout(io.StringIO()):
if fail_acceptance:
with self.assertRaisesRegex(RUNNER.DeployError, "synthetic RPC"):
RUNNER.apply_artifact(artifact)
self.assertEqual(accept.call_count, 2)
else:
RUNNER.apply_artifact(artifact)
return paths, root
def test_full_apply_receipt_only_after_success_and_no_secrets_in_source_backup(self):
paths, root = self.full_apply()
row = json.loads(paths["STATE_FILE"].read_text())
self.assertEqual(row["status"], "ok")
self.assertEqual(self.config.read_bytes(), self.target)
self.assertTrue((root / RUNNER.GITEA_ACTIONS_ENTRY).is_file())
for file in (paths["BACKUPS_DIR"] / row["backup_id"]).iterdir():
if file.is_file():
self.assertNotIn(b"fixture-keep-private", file.read_bytes())
def test_full_failed_acceptance_restores_flag_and_descriptor_and_records_rollback(self):
paths, root = self.full_apply(fail_acceptance=True)
row = json.loads(paths["FAILED_STATE_FILE"].read_text())
self.assertEqual(row["rollback_status"], "ok:gitea-actions-config")
self.assertEqual(self.config.read_bytes(), self.original)
self.assertFalse((root / RUNNER.GITEA_ACTIONS_ENTRY).exists())
self.assertFalse(paths["STATE_FILE"].exists())
if __name__ == "__main__":
unittest.main()
-327
View File
@@ -1,327 +0,0 @@
import copy
from contextlib import redirect_stdout
import hashlib
import io
import json
from pathlib import Path
import unittest
from unittest import mock
import build_actions_artifact
import test_actions_enable as base
from test_bootstrap import RUNNER
class ActionsRecoveryTests(unittest.TestCase):
setUp = base.ActionsEnableTests.setUp
full_apply = base.ActionsEnableTests.full_apply
def with_limits(self):
value = copy.deepcopy(self.info)
value["HostConfig"]["Ulimits"] = [
{"Name": "nofile", "Soft": 1024, "Hard": 4096},
{"Name": "nproc", "Soft": 1024, "Hard": 2048}]
return value
def test_mount_and_ulimit_order_is_the_only_difference_allowed(self):
old = self.with_limits()
changed = copy.deepcopy(old)
changed["Mounts"].reverse()
changed["HostConfig"]["Ulimits"].reverse()
snapshot = copy.deepcopy(changed)
self.assertNotEqual(RUNNER.gitea_actions_fingerprint(old), RUNNER.gitea_actions_fingerprint(changed))
self.assertEqual(RUNNER.gitea_actions_fingerprint_v2(old), RUNNER.gitea_actions_fingerprint_v2(changed))
self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(changed, RUNNER.gitea_actions_fingerprint(old)))
self.assertEqual(changed, snapshot, "normalization must not mutate the inspected object")
def test_order_proof_rejects_all_real_configuration_changes(self):
old = self.with_limits()
old["Config"]["Env"].append("USER=gitea")
mutations = [lambda x: x.update(Id="other"), lambda x: x.update(Image="other"),
lambda x: x["Mounts"][0].update(Source="/other"),
lambda x: x["Mounts"][0].update(RW=True),
lambda x: x["HostConfig"]["Ulimits"][0].update(Hard=999),
lambda x: x["HostConfig"].update(Memory=123),
lambda x: x["HostConfig"]["PortBindings"]["3000/tcp"][0].update(HostPort="3001"),
lambda x: x["Config"]["Env"].reverse(),
lambda x: x["Config"]["Cmd"].reverse(),
lambda x: x["NetworkSettings"]["Networks"].update(other={})]
fingerprint = RUNNER.gitea_actions_fingerprint(old)
for i, mutate in enumerate(mutations):
changed = copy.deepcopy(old)
mutate(changed)
with self.subTest(mutation=i):
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(changed, fingerprint))
self.assertNotEqual(RUNNER.gitea_actions_fingerprint_v2(old), RUNNER.gitea_actions_fingerprint_v2(changed))
def test_duplicate_and_malformed_runtime_fields_rejected(self):
duplicate = self.with_limits()
duplicate["Mounts"].append(copy.deepcopy(duplicate["Mounts"][0]))
with self.assertRaisesRegex(RUNNER.DeployError, "duplicate"):
RUNNER.gitea_actions_fingerprint_v2(duplicate)
malformed = copy.deepcopy(self.info)
malformed["HostConfig"] = None
with self.assertRaisesRegex(RUNNER.DeployError, "malformed"):
RUNNER.gitea_actions_fingerprint_v2(malformed)
for value in (None, []):
info = copy.deepcopy(self.info)
info["HostConfig"]["Ulimits"] = value
self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(info, RUNNER.gitea_actions_fingerprint(info)))
def many_fields(self):
value = copy.deepcopy(self.info)
value["Mounts"].extend({"Destination": "/mount" + str(i), "Source": "/data" + str(i), "RW": False} for i in range(6))
value["HostConfig"]["Ulimits"] = [{"Name": "limit%02d" % i, "Soft": 1024, "Hard": 4096} for i in range(16)]
return value
def cross_sample_orders(self):
target = self.many_fields()
for values in (target["Mounts"], target["HostConfig"]["Ulimits"]):
values[:] = values[::2] + values[1::2]
a, b = copy.deepcopy(target), copy.deepcopy(target)
a["HostConfig"]["Ulimits"].sort(key=lambda x: x["Name"])
b["Mounts"].sort(key=lambda x: x["Destination"])
return target, a, b
def test_large_lists_direct_match_does_not_require_factorial_search(self):
info = self.many_fields()
evidence = {}
self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(info, RUNNER.gitea_actions_fingerprint(info), evidence))
self.assertEqual(evidence["mountCount"], 8)
self.assertEqual(evidence["ulimitCount"], 16)
self.assertEqual(len(evidence.get("tested", set())), 0)
def test_cross_sample_proof_recovers_exact_hash_with_large_lists(self):
target, a, b = self.cross_sample_orders()
expected = RUNNER.gitea_actions_fingerprint(target)
evidence = {}
self.assertNotEqual(RUNNER.gitea_actions_fingerprint(a), expected)
self.assertNotEqual(RUNNER.gitea_actions_fingerprint(b), expected)
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(a, expected, evidence))
self.assertTrue(RUNNER.gitea_actions_prove_legacy_order(b, expected, evidence))
self.assertLessEqual(len(evidence["tested"]), 65536)
# A cached proof is not transferable to changed values.
b["HostConfig"]["Ulimits"][0]["Hard"] += 1
with self.assertRaisesRegex(RUNNER.DeployError, "runtime changed"):
RUNNER.gitea_actions_prove_legacy_order(b, expected, evidence)
def test_repeated_observations_do_not_repeat_hash_search(self):
info = self.many_fields()
evidence = {}
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(info, "0" * 64, evidence))
attempts = len(evidence["tested"])
for _ in range(64):
self.assertFalse(RUNNER.gitea_actions_prove_legacy_order(info, "0" * 64, evidence))
self.assertEqual(len(evidence["tested"]), attempts)
self.assertLessEqual(attempts, 65536)
def test_v1_archive_unchanged_and_v2_has_one_data_descriptor(self):
self.assertEqual(hashlib.sha256(build_actions_artifact.bundle(RUNNER.GITEA_ACTIONS_FAILED_ID)).hexdigest(),
"2ae874cfc6015378246e0bb7b24d4594a749e4136fbd82dbe9db0b57356d2162")
patch = "gitea-actions-enable-v2-test-001"
data = build_actions_artifact.bundle(patch)
self.assertEqual(data, build_actions_artifact.bundle(patch))
artifact = self.root / "recovery.tgz"
artifact.write_bytes(data)
work = self.root / "work"
work.mkdir()
manifest, entries, payload = RUNNER.load_artifact(artifact, work)
self.assertEqual(entries, [RUNNER.GITEA_ACTIONS_V2_ENTRY])
self.assertEqual(RUNNER.component_services(manifest["component"], entries), ("gitea",))
self.assertEqual(RUNNER.component_builds(manifest["component"], entries), ())
path = payload / entries[0]
descriptor = json.loads(path.read_text())
descriptor["reconcilesFailedAttempt"] = "another-failure"
path.write_text(json.dumps(descriptor))
with self.assertRaisesRegex(RUNNER.DeployError, "descriptor"):
RUNNER.validate_gitea_actions_payload(payload, entries, patch)
def recovery_fixture(self):
backups = self.root / "backups"
backup = backups / RUNNER.GITEA_ACTIONS_FAILED_BACKUP
backup.mkdir(parents=True)
failed = self.root / "failed"
failed.mkdir()
ledger = self.root / "failed.jsonl"
row = {"id": RUNNER.GITEA_ACTIONS_FAILED_ID, "component": "gitea-actions-config",
"artifact": "nodedc-gitea-actions-enable-v1-20260929-001.tgz.20260929-160304",
"status": "failed", "sha256": "2ae874cfc6015378246e0bb7b24d4594a749e4136fbd82dbe9db0b57356d2162",
"backup_id": RUNNER.GITEA_ACTIONS_FAILED_BACKUP, "rollback_status": "failed:DeployError",
"message": "Gitea Actions runtime changed before mutation", "started_apply": True}
ledger.write_text(json.dumps(row) + "\n")
(failed / row["artifact"]).write_bytes(build_actions_artifact.bundle(RUNNER.GITEA_ACTIONS_FAILED_ID))
self.old = self.with_limits()
self.reordered = copy.deepcopy(self.old)
self.reordered["Mounts"].reverse()
self.reordered["HostConfig"]["Ulimits"].reverse()
receipt = {"containerId": self.old["Id"], "fingerprint": RUNNER.gitea_actions_fingerprint(self.old),
"configBeforeSha256": RUNNER.GITEA_ACTIONS_BEFORE,
"configAfterSha256": RUNNER.GITEA_ACTIONS_AFTER, "inventory": self.before["inventory"]}
(backup / "gitea-actions-before.json").write_text(json.dumps(receipt))
marker = RUNNER.GITEA_ACTIONS_ROOT / RUNNER.GITEA_ACTIONS_ENTRY
marker.parent.mkdir(parents=True)
marker.write_bytes(b"fixture")
for key, val in {"BACKUPS_DIR": backups, "FAILED_DIR": failed, "FAILED_STATE_FILE": ledger}.items():
self.stack.enter_context(mock.patch.object(RUNNER, key, val))
hashes = {"compose.yaml": "c21ef87833f87623f8352477d2b541d0a0f48769d8f9f79251d58033e90197ff",
"production.env": "9ebbf8638e035dddca25fd455b2ac4d4b6db306e1a6a4debd973b133fdeb5bb7",
"actions-enable-v1.json": "4bc516559ac7a3b62c8d90d8ebc1423ec2039e14591be62eb81fde76bb6751be",
"gitea-actions-before.json": "7b45f822d5afb165f49f0fd4575d92c930ed079cf286a685350f75c61364e0fe"}
real_sha = RUNNER.sha256_file
self.stack.enter_context(mock.patch.object(RUNNER, "sha256_file", side_effect=lambda p: hashes[p.name] if p.name in hashes else real_sha(p)))
self.inspect = self.stack.enter_context(mock.patch.object(RUNNER, "inspect_container", side_effect=[self.reordered,self.old,self.reordered]))
self.stack.enter_context(mock.patch.object(RUNNER, "inspect_local_image", return_value=self.info["Image"]))
self.stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}),(404,None)]))
self.inventory = self.stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=copy.deepcopy(self.before["inventory"])))
self.mutation = self.stack.enter_context(mock.patch.object(RUNNER, "gitea_actions_replace"))
self.restart = self.stack.enter_context(mock.patch.object(RUNNER.subprocess, "run"))
return ledger, row
def test_readonly_reconciliation_proves_saved_hash_for_three_order_variations(self):
self.recovery_fixture()
with redirect_stdout(io.StringIO()) as output:
result = RUNNER.preflight_gitea_actions([RUNNER.GITEA_ACTIONS_V2_ENTRY])
self.assertEqual(self.inspect.call_count, 3)
self.assertEqual(result["fingerprintVersion"], 2)
self.assertFalse(result["mutationStarted"])
self.assertEqual(result["config"], self.original)
self.assertIn('"matchesSavedStateByOrderOnly": true', output.getvalue())
self.assertNotIn("fixture-keep-private", output.getvalue())
self.mutation.assert_not_called()
self.restart.assert_not_called()
def test_readonly_reconciliation_rejects_drift_without_mutation(self):
self.recovery_fixture()
self.reordered["HostConfig"]["Memory"] = 123
with redirect_stdout(io.StringIO()), self.assertRaisesRegex(RUNNER.DeployError, "runtime changed"):
RUNNER.preflight_gitea_actions_recovery()
self.mutation.assert_not_called()
self.restart.assert_not_called()
def test_readonly_reconciliation_handles_cross_sample_proof_and_two_confirmations(self):
self.recovery_fixture()
target, a, b = self.cross_sample_orders()
receipt_path = RUNNER.BACKUPS_DIR / RUNNER.GITEA_ACTIONS_FAILED_BACKUP / "gitea-actions-before.json"
receipt = json.loads(receipt_path.read_text())
receipt["fingerprint"] = RUNNER.gitea_actions_fingerprint(target)
receipt_path.write_text(json.dumps(receipt))
self.inspect.side_effect = [a,b,a,b]
with redirect_stdout(io.StringIO()) as output:
before = RUNNER.preflight_gitea_actions_recovery()
self.assertEqual(self.inspect.call_count, 4)
self.assertFalse(before["mutationStarted"])
report = json.loads(output.getvalue().split("gitea_actions_readonly_audit=")[1])
self.assertTrue(report["exactLegacyProof"])
self.assertEqual(report["sampleCount"], 4)
self.assertEqual(report["ulimitCount"], 16)
self.assertTrue(all(s["matchesSavedStateByOrderOnly"] for s in report["samples"]))
self.mutation.assert_not_called()
self.restart.assert_not_called()
def test_unproven_stable_drift_exhausts_readonly_samples_without_mutation(self):
self.recovery_fixture()
self.reordered["HostConfig"]["Memory"] = 123
self.inspect.side_effect = None
self.inspect.return_value = self.reordered
with redirect_stdout(io.StringIO()) as output, self.assertRaisesRegex(RUNNER.DeployError, "cannot prove order-only"):
RUNNER.preflight_gitea_actions_recovery()
self.assertEqual(self.inspect.call_count, 64)
report = json.loads(output.getvalue().split("gitea_actions_readonly_audit=")[1])
self.assertFalse(report["exactLegacyProof"])
self.assertFalse(report["mutation"])
self.assertEqual(report["sampleCount"], 64)
self.assertNotIn("fixture-keep-private", output.getvalue())
self.mutation.assert_not_called()
self.restart.assert_not_called()
def test_proof_on_last_search_sample_still_requires_two_fresh_confirmations(self):
self.recovery_fixture()
target, a, b = self.cross_sample_orders()
receipt_path = RUNNER.BACKUPS_DIR / RUNNER.GITEA_ACTIONS_FAILED_BACKUP / "gitea-actions-before.json"
receipt = json.loads(receipt_path.read_text())
receipt["fingerprint"] = RUNNER.gitea_actions_fingerprint(target)
receipt_path.write_text(json.dumps(receipt))
self.inspect.side_effect = [a] * 63 + [b,a,b]
with redirect_stdout(io.StringIO()) as output:
RUNNER.preflight_gitea_actions_recovery()
self.assertEqual(self.inspect.call_count, 66)
report = json.loads(output.getvalue().split("gitea_actions_readonly_audit=")[1])
self.assertTrue(report["exactLegacyProof"])
self.assertEqual(report["sampleCount"], 66)
self.mutation.assert_not_called()
self.restart.assert_not_called()
def test_reconciliation_rejects_wrong_ledger_before_inspection(self):
ledger, row = self.recovery_fixture()
row["rollback_status"] = "ok:gitea-actions-config"
ledger.write_text(json.dumps(row) + "\n")
with self.assertRaisesRegex(RUNNER.DeployError, "failed-attempt evidence"):
RUNNER.preflight_gitea_actions_recovery()
self.inspect.assert_not_called()
self.restart.assert_not_called()
def test_reconciliation_rejects_changed_config_and_other_containers(self):
self.recovery_fixture()
self.config.write_bytes(self.original + b"# drift")
with self.assertRaisesRegex(RUNNER.DeployError, "predecessor"):
RUNNER.preflight_gitea_actions_recovery()
self.inspect.assert_not_called()
self.config.write_bytes(self.original)
self.inventory.return_value = {"other": {"running": False}}
with self.assertRaisesRegex(RUNNER.DeployError, "preserved inventory"):
RUNNER.preflight_gitea_actions_recovery()
self.restart.assert_not_called()
def test_pre_mutation_failure_restores_only_source_without_restart(self):
self.before.update({"fingerprint": RUNNER.gitea_actions_fingerprint_v2(self.info),
"fingerprintVersion": 2, "mutationStarted": False})
with mock.patch.object(RUNNER, "gitea_actions_container", return_value=self.info), mock.patch.object(RUNNER.subprocess, "run") as restart, mock.patch.object(RUNNER, "accept_gitea_actions") as accept, mock.patch.object(RUNNER, "restore_overlay_source") as restore:
RUNNER.rollback_gitea_actions(self.root, self.backup, [RUNNER.GITEA_ACTIONS_V2_ENTRY], "stamp", self.before, True)
restart.assert_not_called()
accept.assert_called_once_with(self.before, enabled=False)
restore.assert_called_once()
self.assertEqual(self.config.read_bytes(), self.original)
def test_apply_and_accept_keep_working_when_inspect_array_order_changes(self):
old = self.with_limits()
reordered = copy.deepcopy(old)
reordered["Mounts"].reverse()
reordered["HostConfig"]["Ulimits"].reverse()
self.before.update({"fingerprint": RUNNER.gitea_actions_fingerprint_v2(old),
"fingerprintVersion": 2, "mutationStarted": False})
with mock.patch.object(RUNNER.os, "chown"), mock.patch.object(RUNNER.os, "fchown"), mock.patch.object(RUNNER, "gitea_actions_container", side_effect=[reordered,old]), mock.patch.object(RUNNER.subprocess, "run") as restart, mock.patch.object(RUNNER, "gitea_actions_http", side_effect=[(200,{"version":"1.27.2"}),(200,{"data":"Hello, nodedc-ci-probe!"})]), mock.patch.object(RUNNER, "gitea_ci_inventory", return_value=self.before["inventory"]), redirect_stdout(io.StringIO()):
RUNNER.apply_gitea_actions(self.before, self.backup)
RUNNER.accept_gitea_actions(self.before)
restart.assert_called_once()
self.assertEqual(self.config.read_bytes(), self.target)
def test_reconciliation_rejects_changed_failed_archive_before_inspection(self):
_, row = self.recovery_fixture()
(RUNNER.FAILED_DIR / row["artifact"]).write_bytes(b"changed")
with self.assertRaisesRegex(RUNNER.DeployError, "archived evidence"):
RUNNER.preflight_gitea_actions_recovery()
self.inspect.assert_not_called()
self.restart.assert_not_called()
def test_full_v2_apply_preserves_v1_marker_and_records_fingerprint_version(self):
paths, root = self.full_apply(version="v2")
row = json.loads(paths["STATE_FILE"].read_text())
self.assertEqual(row["status"], "ok")
self.assertEqual(self.config.read_bytes(), self.target)
self.assertTrue((root / RUNNER.GITEA_ACTIONS_V2_ENTRY).is_file())
self.assertEqual((root / RUNNER.GITEA_ACTIONS_ENTRY).read_bytes(), b"preserved failed-attempt marker")
receipt = json.loads((paths["BACKUPS_DIR"] / row["backup_id"] / "gitea-actions-before.json").read_text())
self.assertEqual(receipt["fingerprintVersion"], 2)
def test_full_v2_failed_acceptance_restores_disabled_config_and_keeps_v1_marker(self):
paths, root = self.full_apply(fail_acceptance=True, version="v2")
row = json.loads(paths["FAILED_STATE_FILE"].read_text())
self.assertEqual(row["rollback_status"], "ok:gitea-actions-config")
self.assertEqual(self.config.read_bytes(), self.original)
self.assertFalse((root / RUNNER.GITEA_ACTIONS_V2_ENTRY).exists())
self.assertEqual((root / RUNNER.GITEA_ACTIONS_ENTRY).read_bytes(), b"preserved failed-attempt marker")
self.assertFalse(paths["STATE_FILE"].exists())
if __name__ == "__main__":
unittest.main()
-273
View File
@@ -1,273 +0,0 @@
import copy
from contextlib import ExitStack, redirect_stdout, redirect_stderr
import io
import importlib.machinery
import importlib.util
import json
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest import mock
import build_artifact
SOURCE = Path(__file__).resolve().parent
loader = importlib.machinery.SourceFileLoader("gitea_ci_runner_test", str(SOURCE.parent / "deploy-runner/nodedc-deploy"))
spec = importlib.util.spec_from_loader(loader.name, loader)
RUNNER = importlib.util.module_from_spec(spec)
loader.exec_module(RUNNER)
def container_info():
return {
"Config": {"Image": RUNNER.GITEA_CI_IMAGE, "Labels": {
"com.docker.compose.project": "nodedc-gitea-ci",
"com.docker.compose.service": "build-runner",
}},
"State": {"Running": True},
"HostConfig": {
"PortBindings": {}, "NetworkMode": "nodedc-gitea-ci_default",
"ReadonlyRootfs": True, "Memory": 512 * 1024 ** 2,
"NanoCpus": 500000000, "PidsLimit": 128,
"CapDrop": ["ALL"], "SecurityOpt": ["no-new-privileges:true"],
},
"NetworkSettings": {"Ports": {}},
"Mounts": [{"Destination": dest, "Source": source, "RW": rw, "Type": "bind"}
for dest, source, rw in [
("/config/runner.yaml", str(RUNNER.GITEA_CI_ROOT / "runner.yaml"), False),
("/data", str(RUNNER.GITEA_CI_ROOT / "data"), True),
("/run/secrets/registration-token", str(RUNNER.GITEA_CI_ROOT / "secrets/registration-token"), False),
("/var/run/docker.sock", "/var/run/docker.sock", False),
]],
}
class BootstrapTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
self.patch = "gitea-ci-bootstrap-v1-test-001"
self.artifact = self.root / "bootstrap.tgz"
self.artifact.write_bytes(build_artifact.bundle(self.patch))
self.extracted = self.root / "extracted"
self.extracted.mkdir()
def load(self):
return RUNNER.load_artifact(self.artifact, self.extracted)
def test_deterministic_data_bundle_accepted_by_canonical_runner(self):
self.assertEqual(self.artifact.read_bytes(), build_artifact.bundle(self.patch))
manifest, entries, _ = self.load()
self.assertEqual(manifest["component"], "gitea-ci")
self.assertEqual(tuple(entries), RUNNER.GITEA_CI_ENTRIES)
self.assertEqual(RUNNER.component_services("gitea-ci", entries), ("build-runner",))
self.assertEqual(RUNNER.component_builds("gitea-ci", entries), ())
self.assertTrue(RUNNER.component_compose_no_deps("gitea-ci", entries))
with tarfile.open(self.artifact) as archive:
self.assertEqual(len(archive.getmembers()), 5)
self.assertTrue(all(m.isfile() and m.mode == 0o644 for m in archive))
def test_changed_ports_or_privileges_in_source_are_rejected(self):
_, entries, payload = self.load()
compose = payload / RUNNER.GITEA_CI_ENTRIES[0]
compose.write_text(compose.read_text() + ' ports: ["9999:9999"]\n')
with self.assertRaisesRegex(RUNNER.DeployError, "immutable configuration"):
RUNNER.validate_gitea_ci_payload(payload, entries, self.patch)
def test_partial_update_and_production_activation_are_rejected(self):
_, entries, payload = self.load()
with self.assertRaisesRegex(RUNNER.DeployError, "entry set"):
RUNNER.validate_gitea_ci_payload(payload, entries[:1], self.patch)
descriptor_path = payload / RUNNER.GITEA_CI_ENTRIES[2]
descriptor = json.loads(descriptor_path.read_text())
descriptor["productionDeployEnabled"] = True
descriptor_path.write_text(json.dumps(descriptor))
with self.assertRaisesRegex(RUNNER.DeployError, "descriptor mismatch"):
RUNNER.validate_gitea_ci_payload(payload, entries, self.patch)
def test_credentials_hooks_and_extra_services_are_not_payload_paths(self):
for path in ("secrets/token", "data/.runner", "install.sh", "other.yml", "controller.py"):
with self.subTest(path=path), self.assertRaises(RUNNER.DeployError):
RUNNER.allowed_payload_path("gitea-ci", path)
def test_runtime_accepts_exact_isolated_daemon(self):
RUNNER.accept_gitea_ci_container(container_info())
def test_runtime_rejects_port_privilege_unbounded_memory_or_wrong_service(self):
for field, value in (
("PortBindings", {"8080/tcp": [{"HostPort": "8080"}]}),
("PublishAllPorts", True), ("NetworkMode", "host"),
("Privileged", True), ("Memory", 0), ("NanoCpus", 0),
("PidsLimit", 0), ("CapAdd", ["SYS_ADMIN"]),
("CapDrop", []), ("SecurityOpt", []),
):
info = container_info()
info["HostConfig"][field] = value
with self.subTest(field=field), self.assertRaises(RUNNER.DeployError):
RUNNER.accept_gitea_ci_container(info)
def test_runtime_rejects_production_volume_mount(self):
info = container_info()
info["Mounts"].append({"Destination": "/production", "Source": "/volume1/docker/nodedc-device-plane", "RW": True, "Type": "bind"})
with self.assertRaisesRegex(RUNNER.DeployError, "mount boundary"):
RUNNER.accept_gitea_ci_container(info)
def test_enrollment_must_be_private_and_is_not_logged_in_error(self):
pending = self.root / "enrollment.json"
pending.write_text(json.dumps({"repository": "SILVER/NODEDC_DEVICE_CORE", "token": "sensitive" * 6}))
with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", pending):
pending.chmod(0o644)
with self.assertRaisesRegex(RUNNER.DeployError, "private regular"):
RUNNER.read_gitea_ci_enrollment()
pending.chmod(0o600)
self.assertEqual(RUNNER.read_gitea_ci_enrollment(), "sensitive" * 6)
pending.write_text('{"token":"sensitive", malformed')
with self.assertRaises(RUNNER.DeployError) as error:
RUNNER.read_gitea_ci_enrollment()
self.assertNotIn("sensitive", str(error.exception))
def test_symlink_enrollment_rejected(self):
actual = self.root / "actual"
actual.write_text("secret")
link = self.root / "link"
link.symlink_to(actual)
with mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", link):
with self.assertRaises(RUNNER.DeployError):
RUNNER.read_gitea_ci_enrollment()
def test_preflight_rejects_reusing_bootstrap_for_an_installed_release(self):
(self.root / RUNNER.GITEA_CI_ENTRIES[0]).write_text("installed")
with mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.root):
with self.assertRaisesRegex(RUNNER.DeployError, "versioned upgrade"):
RUNNER.preflight_gitea_ci()
def test_inventory_preserves_only_non_ci_container_identities(self):
old = {"Image": "old", "State": {"Running": True, "StartedAt": "before"}, "Config": {"Labels": {}}}
own = copy.deepcopy(old)
own["Config"]["Labels"]["com.docker.compose.project"] = "nodedc-gitea-ci"
with mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=["old", "own"]), mock.patch.object(RUNNER, "inspect_container", side_effect=[old, own]):
self.assertEqual(RUNNER.gitea_ci_inventory(), {"old": {"image": "old", "startedAt": "before", "running": True}})
def test_rollback_removes_only_ci_service_and_restores_only_source(self):
with mock.patch.object(RUNNER, "stop_and_remove_compose_services") as stop, mock.patch.object(RUNNER, "restore_overlay_source") as restore, mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[]):
RUNNER.rollback_gitea_ci(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp", True)
stop.assert_called_once_with("gitea-ci", ("build-runner",))
restore.assert_called_once_with(self.root, self.root / "backup", RUNNER.GITEA_CI_ENTRIES, "stamp")
def apply_in_synthetic_host(self, fail_health=False, version="v1"):
expected_entries = RUNNER.GITEA_CI_ENTRIES
if version in ("v2", "v3", "v4"):
expected_entries = getattr(RUNNER, "GITEA_CI_" + version.upper() + "_ENTRIES")
self.artifact.write_bytes(build_artifact.bundle("gitea-ci-bootstrap-" + version + "-test-001"))
host = self.root / "host"
host.mkdir()
names = {name: host / name.lower() for name in (
"INBOX", "APPLIED_DIR", "FAILED_DIR", "BACKUPS_DIR", "STATE_DIR", "TMP_DIR", "RUNTIME_DIR",
)}
for directory in names.values():
directory.mkdir()
names.update({
"STATE_FILE": names["STATE_DIR"] / "applied.jsonl",
"FAILED_STATE_FILE": names["STATE_DIR"] / "failed.jsonl",
"LOCK_DIR": names["STATE_DIR"] / "deploy.lock",
"DOCKER": Path("/usr/bin/true"),
})
app = host / "gitea-ci"
registry = {**RUNNER.COMPONENTS["gitea-ci"], "payload_root": app,
"compose_root": app, "compose_files": (app / "docker-compose.gitea-ci.yml",)}
candidate = names["INBOX"] / "candidate.tgz"
candidate.write_bytes(self.artifact.read_bytes())
def start_runtime(*args):
self.assertEqual(args, ("gitea-ci", list(expected_entries), ("build-runner",)))
(app / "data").mkdir()
(app / "data" / "registration-marker").write_text("preserve-on-rollback")
with ExitStack() as stack:
for name, value in names.items():
stack.enter_context(mock.patch.object(RUNNER, name, value))
stack.enter_context(mock.patch.dict(RUNNER.COMPONENTS, {"gitea-ci": registry}))
stack.enter_context(mock.patch.object(RUNNER, "require_root"))
stack.enter_context(mock.patch.object(RUNNER.os, "chown"))
stack.enter_context(mock.patch.object(RUNNER, "preflight_gitea_ci", return_value={}))
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_inventory", return_value={}))
stack.enter_context(mock.patch.object(RUNNER, "gitea_ci_container_ids", return_value=[]))
stack.enter_context(mock.patch.object(RUNNER, "run_component_runtime", side_effect=start_runtime))
stop = stack.enter_context(mock.patch.object(RUNNER, "stop_and_remove_compose_services"))
stack.enter_context(mock.patch.object(RUNNER, "accept_gitea_ci",
side_effect=RUNNER.DeployError("synthetic health failure") if fail_health else None))
output = stack.enter_context(redirect_stdout(io.StringIO()))
stack.enter_context(redirect_stderr(io.StringIO()))
if fail_health:
with self.assertRaisesRegex(RUNNER.DeployError, "synthetic health failure"):
RUNNER.apply_artifact(candidate)
stop.assert_called_once_with("gitea-ci", ("build-runner",))
else:
RUNNER.apply_artifact(candidate)
stop.assert_not_called()
return names, app, candidate, output.getvalue()
def test_apply_records_commit_independent_artifact_receipt_only_after_acceptance(self):
paths, app, candidate, output = self.apply_in_synthetic_host()
self.assertFalse(candidate.exists())
row = json.loads(paths["STATE_FILE"].read_text())
self.assertEqual(row["status"], "ok")
self.assertEqual(row["component"], "gitea-ci")
self.assertTrue((paths["APPLIED_DIR"] / candidate.name).is_file())
self.assertTrue((paths["BACKUPS_DIR"] / row["backup_id"] / "ci-runtime-before.json").is_file())
self.assertIn("deploy-ok", output)
self.assertTrue((app / "runner.yaml").is_file())
def test_failed_health_restores_source_preserves_registration_and_archives_failure(self):
paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True)
self.assertFalse(paths["STATE_FILE"].exists())
row = json.loads(paths["FAILED_STATE_FILE"].read_text())
self.assertEqual(row["rollback_status"], "ok:gitea-ci-bootstrap")
self.assertTrue((paths["FAILED_DIR"] / row["artifact"]).is_file())
self.assertFalse((app / "runner.yaml").exists())
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
self.assertNotIn("deploy-ok", output)
def test_v2_apply_records_distinct_descriptor_and_receipt(self):
paths, app, candidate, output = self.apply_in_synthetic_host(version="v2")
self.assertTrue((app / "deployment/bootstrap-v2.json").is_file())
self.assertFalse((app / "deployment/bootstrap-v1.json").exists())
self.assertEqual(json.loads(paths["STATE_FILE"].read_text())["status"], "ok")
self.assertIn("deploy-ok patch=gitea-ci-bootstrap-v2-test-001", output)
def test_v2_failed_health_preserves_identity_and_rolls_back_source(self):
paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True, version="v2")
self.assertFalse((app / "deployment/bootstrap-v2.json").exists())
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
self.assertEqual(json.loads(paths["FAILED_STATE_FILE"].read_text())["rollback_status"], "ok:gitea-ci-bootstrap")
def test_v3_apply_and_receipt(self):
paths, app, candidate, output = self.apply_in_synthetic_host(version="v3")
self.assertTrue((app / "deployment/bootstrap-v3.json").is_file())
self.assertEqual(json.loads(paths["STATE_FILE"].read_text())["status"], "ok")
self.assertIn("deploy-ok patch=gitea-ci-bootstrap-v3-test-001", output)
def test_v3_rollback_preserves_identity(self):
paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True, version="v3")
self.assertFalse((app / "deployment/bootstrap-v3.json").exists())
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
self.assertEqual(json.loads(paths["FAILED_STATE_FILE"].read_text())["rollback_status"], "ok:gitea-ci-bootstrap")
def test_v4_apply_and_receipt(self):
paths, app, candidate, output = self.apply_in_synthetic_host(version="v4")
self.assertTrue((app / "deployment/bootstrap-v4.json").is_file())
self.assertEqual(json.loads(paths["STATE_FILE"].read_text())["status"], "ok")
self.assertIn("deploy-ok patch=gitea-ci-bootstrap-v4-test-001", output)
def test_v4_rollback_preserves_identity(self):
paths, app, candidate, output = self.apply_in_synthetic_host(fail_health=True, version="v4")
self.assertFalse((app / "deployment/bootstrap-v4.json").exists())
self.assertEqual((app / "data/registration-marker").read_text(), "preserve-on-rollback")
self.assertEqual(json.loads(paths["FAILED_STATE_FILE"].read_text())["rollback_status"], "ok:gitea-ci-bootstrap")
if __name__ == "__main__":
unittest.main()
-164
View File
@@ -1,164 +0,0 @@
import io
import json
import os
from contextlib import ExitStack, redirect_stdout
from pathlib import Path
import stat
import tempfile
from types import SimpleNamespace
import unittest
from unittest import mock
import build_artifact
from test_bootstrap import RUNNER
class EnrollmentV2Tests(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name).resolve()
self.app = self.root / "ci"
self.pending = self.root / "enrollment.pending.json"
self.token = "fixture-not-a-real-token-1234567890"
self.pending.write_text(json.dumps({
"repository": "SILVER/NODEDC_DEVICE_CORE", "token": self.token,
}))
self.pending.chmod(0o666) # Simulate NAS permissions hidden by SMB's 0700 view.
self.stack = ExitStack()
self.addCleanup(self.stack.close)
self.stack.enter_context(mock.patch.object(RUNNER, "GITEA_CI_ROOT", self.app))
self.stack.enter_context(mock.patch.object(RUNNER, "GITEA_CI_ENROLLMENT", self.pending))
self.stack.enter_context(mock.patch.object(RUNNER.pwd, "getpwnam", return_value=SimpleNamespace(pw_uid=os.getuid())))
def emulate_root_ownership(self):
fstat = os.fstat
def root_stat(fd):
original = fstat(fd)
fields = {key: getattr(original, key) for key in dir(original) if key.startswith("st_")}
fields["st_uid"] = 0
return SimpleNamespace(**fields)
self.stack.enter_context(mock.patch.object(RUNNER.os, "fstat", side_effect=root_stat))
chown = self.stack.enter_context(mock.patch.object(RUNNER.os, "chown"))
fchown = self.stack.enter_context(mock.patch.object(RUNNER.os, "fchown"))
return chown, fchown
def test_v1_private_guard_still_rejects_shared_staging(self):
with self.assertRaisesRegex(RUNNER.DeployError, "private regular"):
RUNNER.read_gitea_ci_enrollment()
def test_v2_preflight_reports_metadata_without_mutation_or_secret(self):
before = self.pending.stat()
result = RUNNER.preflight_gitea_ci_v2_enrollment()
self.assertIn("mode=0666", result)
self.assertNotIn(self.token, result)
self.assertEqual(self.pending.stat(), before)
self.assertFalse(self.app.exists())
def test_v2_import_is_private_atomic_and_retryable_without_staging(self):
chown, fchown = self.emulate_root_ownership()
output = io.StringIO()
with redirect_stdout(output):
self.assertEqual(RUNNER.import_gitea_ci_v2_enrollment(), self.token)
private = self.app / "secrets" / "registration-token"
self.assertEqual(private.read_text(), self.token + "\n")
self.assertEqual(stat.S_IMODE(private.stat().st_mode), 0o600)
self.assertEqual(stat.S_IMODE(private.parent.stat().st_mode), 0o700)
self.assertEqual(private.stat().st_nlink, 1)
self.assertFalse(self.pending.exists())
self.assertEqual(list(private.parent.iterdir()), [private])
chown.assert_called_with(str(private.parent), 0, 0)
self.assertEqual(fchown.call_args.args[1:], (0, 0))
self.assertNotIn(self.token, output.getvalue())
original_inode = private.stat().st_ino
self.assertEqual(RUNNER.preflight_gitea_ci_v2_enrollment(), "reuse-root-private-runtime")
with redirect_stdout(output):
RUNNER.import_gitea_ci_v2_enrollment()
self.assertEqual(private.stat().st_ino, original_inode)
def test_durability_failure_keeps_staging_for_recovery(self):
self.emulate_root_ownership()
# First fsync persists file bytes; the second publishes its directory entry.
with mock.patch.object(RUNNER.os, "fsync", side_effect=[None, OSError("disk")]):
with self.assertRaises(OSError):
RUNNER.import_gitea_ci_v2_enrollment()
self.assertTrue(self.pending.exists())
self.assertEqual((self.app / "secrets/registration-token").read_text(), self.token + "\n")
with redirect_stdout(io.StringIO()):
RUNNER.import_gitea_ci_v2_enrollment()
self.assertFalse(self.pending.exists())
def test_different_private_identity_is_never_overwritten(self):
self.emulate_root_ownership()
private = self.app / "secrets/registration-token"
private.parent.mkdir(parents=True)
private.write_text("different-fixture-token-1234567890\n")
private.chmod(0o600)
with self.assertRaisesRegex(RUNNER.DeployError, "differs"):
RUNNER.import_gitea_ci_v2_enrollment()
self.assertTrue(self.pending.exists())
self.assertEqual(private.read_text(), "different-fixture-token-1234567890\n")
def test_wrong_operator_owner_rejected(self):
with mock.patch.object(RUNNER.pwd, "getpwnam", return_value=SimpleNamespace(pw_uid=os.getuid() + 1)):
with self.assertRaisesRegex(RUNNER.DeployError, "metadata rejected"):
RUNNER.read_gitea_ci_v2_input()
def test_symlink_and_hardlink_rejected(self):
actual = self.root / "actual"
self.pending.rename(actual)
self.pending.symlink_to(actual)
with self.assertRaises(RUNNER.DeployError):
RUNNER.read_gitea_ci_v2_input()
self.pending.unlink()
os.link(actual, self.pending)
with self.assertRaisesRegex(RUNNER.DeployError, "nlink=2"):
RUNNER.read_gitea_ci_v2_input()
def test_special_and_oversized_files_rejected_without_blocking(self):
self.pending.unlink()
os.mkfifo(self.pending)
with self.assertRaises(RUNNER.DeployError):
RUNNER.read_gitea_ci_v2_input()
self.pending.unlink()
self.pending.write_text("x" * 2049)
with self.assertRaisesRegex(RUNNER.DeployError, "metadata rejected"):
RUNNER.read_gitea_ci_v2_input()
def test_runtime_copy_requires_root_and_exact_private_mode(self):
self.emulate_root_ownership()
private = self.app / "secrets/registration-token"
private.parent.mkdir(parents=True)
private.write_text(self.token)
private.chmod(0o644)
with self.assertRaisesRegex(RUNNER.DeployError, "runtime=True;mode=0644"):
RUNNER.read_gitea_ci_v2_input(runtime=True)
def test_wrong_repository_and_malformed_json_never_echo_secret(self):
for value in [self.token + "!", json.dumps({"repository": "other", "token": self.token})]:
self.pending.write_text(value)
with self.assertRaises(RUNNER.DeployError) as error:
RUNNER.read_gitea_ci_v2_input()
self.assertNotIn(self.token, str(error.exception))
def test_v2_artifact_has_own_identity_and_no_secret_paths(self):
patch = "gitea-ci-bootstrap-v2-test-001"
data = build_artifact.bundle(patch)
self.assertEqual(data, build_artifact.bundle(patch))
artifact = self.root / "v2.tgz"
artifact.write_bytes(data)
extracted = self.root / "extracted"
extracted.mkdir()
manifest, entries, payload = RUNNER.load_artifact(artifact, extracted)
self.assertEqual(tuple(entries), RUNNER.GITEA_CI_V2_ENTRIES)
self.assertEqual(RUNNER.component_services("gitea-ci", entries), ("build-runner",))
with self.assertRaisesRegex(RUNNER.DeployError, "release identity"):
RUNNER.validate_gitea_ci_payload(payload, entries, patch.replace("v2", "v1"))
with self.assertRaisesRegex(RUNNER.DeployError, "entry set"):
RUNNER.validate_gitea_ci_payload(payload, list(entries) + [RUNNER.GITEA_CI_ENTRIES[2]], patch)
if __name__ == "__main__":
unittest.main()
-111
View File
@@ -1,111 +0,0 @@
import copy
import hashlib
import io
import json
from contextlib import redirect_stdout
from pathlib import Path
import tempfile
from types import SimpleNamespace
import unittest
from unittest import mock
import build_artifact
from test_bootstrap import RUNNER, container_info
def capabilities():
return {"OSType": "linux", "Architecture": "x86_64", "NCPU": 8,
"MemoryLimit": True, "SwapLimit": False, "PidsLimit": True,
"CPUShares": True, "CPUSet": True, "CpuCfsQuota": False,
"CpuCfsPeriod": False, "KernelVersion": "fixture-kernel",
"RegistryConfig": {"do-not-log": "fixture-secret"},
"HttpProxy": "fixture-private-proxy"}
class SynologyV3Tests(unittest.TestCase):
def query(self, info, entries=RUNNER.GITEA_CI_V3_ENTRIES):
result = SimpleNamespace(stdout=json.dumps(info))
output = io.StringIO()
with mock.patch.object(RUNNER.subprocess, "run", return_value=result) as run:
with redirect_stdout(output):
report = RUNNER.gitea_ci_host_capabilities(entries)
run.assert_called_once_with([str(RUNNER.DOCKER), "info", "--format", "{{json .}}"],
capture_output=True, text=True, check=True, timeout=30)
return report, output.getvalue()
def test_v3_supports_no_cfs_no_swap_without_claiming_cpu_quota(self):
report, output = self.query(capabilities())
self.assertFalse(report["CpuCfsQuota"])
self.assertTrue(report["CPUShares"])
self.assertNotIn("fixture-secret", output)
self.assertNotIn("fixture-private-proxy", output)
def test_missing_memory_pids_or_shares_is_rejected_before_container_creation(self):
for key in ("MemoryLimit", "PidsLimit", "CPUShares"):
for value in (False, None, "true"):
info = capabilities()
info[key] = value
with self.subTest(key=key, value=value), self.assertRaisesRegex(RUNNER.DeployError, key):
self.query(info)
def test_cfs_profile_remains_rejected_on_incompatible_kernel(self):
for entries in (RUNNER.GITEA_CI_ENTRIES, RUNNER.GITEA_CI_V2_ENTRIES):
with self.assertRaisesRegex(RUNNER.DeployError, "CpuCfsPeriod,CpuCfsQuota,SwapLimit"):
self.query(capabilities(), entries)
def test_wrong_architecture_is_rejected(self):
info = capabilities()
info["Architecture"] = "aarch64"
with self.assertRaisesRegex(RUNNER.DeployError, "Linux amd64"):
self.query(info)
def test_runtime_accepts_only_exact_cpu_shares_profile(self):
info = container_info()
info["HostConfig"].update({"NanoCpus": 0, "CpuShares": 64, "CpuQuota": 0, "CpuPeriod": 0})
RUNNER.accept_gitea_ci_container(info, RUNNER.GITEA_CI_V3_ENTRIES)
for field, value in (("CpuShares", 0), ("CpuShares", 1024), ("NanoCpus", 500000000),
("CpuQuota", 50000), ("Memory", 0), ("PidsLimit", 0)):
candidate = copy.deepcopy(info)
candidate["HostConfig"][field] = value
with self.subTest(field=field), self.assertRaisesRegex(RUNNER.DeployError, "resource limit"):
RUNNER.accept_gitea_ci_container(candidate, RUNNER.GITEA_CI_V3_ENTRIES)
with self.assertRaisesRegex(RUNNER.DeployError, "resource limit"):
RUNNER.accept_gitea_ci_container(info, RUNNER.GITEA_CI_V2_ENTRIES)
def test_v3_artifact_pins_both_daemon_and_job_configuration(self):
patch = "gitea-ci-bootstrap-v3-test-001"
data = build_artifact.bundle(patch)
self.assertEqual(data, build_artifact.bundle(patch))
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
artifact = root / "test.tgz"
artifact.write_bytes(data)
target = root / "unpacked"
target.mkdir()
_, entries, payload = RUNNER.load_artifact(artifact, target)
self.assertEqual(tuple(entries), RUNNER.GITEA_CI_V3_ENTRIES)
self.assertEqual(RUNNER.component_services("gitea-ci", entries), ("build-runner",))
compose = (payload / "docker-compose.gitea-ci.yml").read_text()
runner = (payload / "runner.yaml").read_text()
self.assertIn("cpu_shares: 64", compose)
self.assertNotIn("cpus:", compose)
self.assertIn("--cpu-shares=128", runner)
self.assertNotIn("--cpus=", runner)
self.assertNotIn("--memory-swap", runner)
self.assertIn("--memory=2g --pids-limit=256", runner)
(payload / "runner.yaml").write_text(runner.replace("--cpu-shares=128", "--cpu-shares=1024"))
with self.assertRaisesRegex(RUNNER.DeployError, "immutable configuration"):
RUNNER.validate_gitea_ci_payload(payload, entries, patch)
def test_historical_artifact_bytes_remain_reproducible(self):
for patch, sha in (
("gitea-ci-bootstrap-v1-20260929-001", "ba942839c5815d09ac8f3c8dc23acdcf53ad9ef098a74c26b14c8b81afcf6a20"),
("gitea-ci-bootstrap-v2-20260929-002", "f9381e1ca59372f75277b6a6207ac9e35acaf29fd8ffa5dcf6afafa2daf80630"),
("gitea-ci-bootstrap-v3-20260929-003", "9df6c741e2432c0cac9fe2f2c7d90348a61d75b28098146018467050ef21ab9a"),
("gitea-ci-bootstrap-v4-20260929-004", "866771bd94c82bee6d8143574fd7cc6292b0a516a2c4f082a4565bc13ccf2fb8"),
):
self.assertEqual(hashlib.sha256(build_artifact.bundle(patch)).hexdigest(), sha)
if __name__ == "__main__":
unittest.main()
-106
View File
@@ -1,106 +0,0 @@
import io
import json
from contextlib import redirect_stdout
from pathlib import Path
import tempfile
from types import SimpleNamespace
import unittest
from unittest import mock
import build_artifact
from test_bootstrap import RUNNER, container_info
def nas_capabilities():
return {"Architecture": "x86_64", "CPUSet": True, "CPUShares": True,
"CgroupVersion": "1", "CpuCfsPeriod": False, "CpuCfsQuota": False,
"KernelVersion": "4.4.302+", "MemTotal": 16743616512,
"MemoryLimit": True, "NCPU": 8, "OSType": "linux",
"PidsLimit": False, "ServerVersion": "24.0.2", "SwapLimit": True}
def v4_container():
info = container_info()
info["State"]["Pid"] = 1234
info["HostConfig"].update({"NanoCpus": 0, "CpuShares": 64, "CpusetCpus": "7",
"PidsLimit": None, "MemorySwap": 512 * 1024 ** 2})
return info
class SynologyV4Tests(unittest.TestCase):
def query(self, info, affinity=None):
with mock.patch.object(RUNNER.subprocess, "run", return_value=SimpleNamespace(stdout=json.dumps(info))):
with mock.patch.object(RUNNER.os, "sched_getaffinity", create=True, return_value=set(range(8)) if affinity is None else affinity):
with redirect_stdout(io.StringIO()):
return RUNNER.gitea_ci_host_capabilities(RUNNER.GITEA_CI_V4_ENTRIES)
def test_actual_nas_capability_matrix_passes_without_cfs_or_pids(self):
report = self.query(nas_capabilities())
self.assertFalse(report["PidsLimit"])
self.assertFalse(report["CpuCfsQuota"])
self.assertTrue(report["CPUSet"])
def test_required_supported_controls_are_not_optional(self):
for key in ("CPUSet", "CPUShares", "MemoryLimit", "SwapLimit"):
info = nas_capabilities()
info[key] = False
with self.subTest(key=key), self.assertRaisesRegex(RUNNER.DeployError, key):
self.query(info)
def test_cpu7_must_exist_and_be_available(self):
info = nas_capabilities()
info["NCPU"] = 4
with self.assertRaisesRegex(RUNNER.DeployError, "eight logical"):
self.query(info)
with self.assertRaisesRegex(RUNNER.DeployError, "CPU7 affinity"):
self.query(nas_capabilities(), affinity={0, 1})
def test_exact_runtime_cpu_affinity_memory_swap_and_no_pids_contract(self):
with mock.patch.object(RUNNER.os, "sched_getaffinity", create=True, return_value={7}) as affinity:
RUNNER.accept_gitea_ci_container(v4_container(), RUNNER.GITEA_CI_V4_ENTRIES)
affinity.assert_called_once_with(1234)
def test_broad_affinity_unbounded_swap_or_reintroduced_unsupported_limit_rejected(self):
for field, value in (("CpusetCpus", "0-7"), ("MemorySwap", -1), ("Memory", 0),
("NanoCpus", 500000000), ("PidsLimit", 128), ("CpuShares", 0)):
info = v4_container()
info["HostConfig"][field] = value
with mock.patch.object(RUNNER.os, "sched_getaffinity", create=True, return_value={7}):
with self.subTest(field=field), self.assertRaises(RUNNER.DeployError):
RUNNER.accept_gitea_ci_container(info, RUNNER.GITEA_CI_V4_ENTRIES)
with mock.patch.object(RUNNER.os, "sched_getaffinity", create=True, return_value={0, 7}):
with self.assertRaisesRegex(RUNNER.DeployError, "CPU7 affinity"):
RUNNER.accept_gitea_ci_container(v4_container(), RUNNER.GITEA_CI_V4_ENTRIES)
def test_affinity_requires_a_positive_numeric_runtime_pid(self):
for pid in (None, 0, -1, True, "1234"):
with self.subTest(pid=pid), self.assertRaisesRegex(RUNNER.DeployError, "process identity"):
RUNNER.gitea_ci_check_affinity(pid, exact=True)
def test_v4_bundle_pins_same_single_cpu_for_daemon_and_job(self):
patch = "gitea-ci-bootstrap-v4-test-001"
data = build_artifact.bundle(patch)
self.assertEqual(data, build_artifact.bundle(patch))
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
artifact = root / "test.tgz"
artifact.write_bytes(data)
target = root / "unpacked"
target.mkdir()
_, entries, payload = RUNNER.load_artifact(artifact, target)
self.assertEqual(tuple(entries), RUNNER.GITEA_CI_V4_ENTRIES)
compose = (payload / "docker-compose.gitea-ci.yml").read_text()
runner = (payload / "runner.yaml").read_text()
self.assertIn('cpuset: "7"', compose)
self.assertIn('memswap_limit: 512m', compose)
self.assertNotIn('pids_limit:', compose)
self.assertIn('--cpuset-cpus=7', runner)
self.assertIn('--memory=2g --memory-swap=2g', runner)
self.assertNotIn('--pids-limit', runner)
(payload / "runner.yaml").write_text(runner.replace('--cpuset-cpus=7', '--cpuset-cpus=0-7'))
with self.assertRaisesRegex(RUNNER.DeployError, "immutable configuration"):
RUNNER.validate_gitea_ci_payload(payload, entries, patch)
if __name__ == "__main__":
unittest.main()
-39
View File
@@ -1,39 +0,0 @@
# Optional delegated Core egress
Prepared 17 November 2026; **not deployed on NAS**. The legacy AMD path remains
active when no delegation is supplied. McHost's relay is installed, but Cesium
country-blocks its public egress IP; Mission Core has therefore not selected it.
`src/egress.mjs` admits a request-scoped `nodedc.map-egress/v1` binding only with a
separate HMAC signature over schema, method, path and payload. A browser or trusted
subject header alone cannot set the route. The key is derived from Gateway's
existing administrative secret with the domain `nodedc.map-egress.core/v1`; Core
would receive only the derived key in private `services/cesium-ion/egress-signing.key`
(64 hexadecimal characters). No key has been provisioned in this rollout. Keep
the key, binding and provider credentials out of logs, responses and Git.
The binding expires within 30 seconds and supplies a pinned relay endpoint,
credential and Cesium profile. TLS 1.3 certificate verification by exact fingerprint
precedes HTTP credentials. Destination checks forbid private addresses and arbitrary
provider hosts. The relay allows only GET/HEAD; range and conditional headers are
forwarded. Cancellation closes the stream. Concurrent relay requests are bounded
at 16; handshake and body idle timeouts are 8 and 30 seconds.
Cache lookup is unchanged and occurs before external fetch. Delegation affects
only a miss/refresh fetch: it does not change canonical URLs, object keys, index
format, credential scoping, atomic fills or the physical cache root. Warm hits
need neither AMD nor VPS. Do not rebuild, copy, clear or reindex tiles for this
transport change. The health contract advertises `egressContract` after deployment;
Core requires this contract and its signing key before admitting a cached route.
Three delegation tests passed, including real TLS pin/header/cancellation cases.
Existing smoke checks passed for no-browser-credentials, live-cache-fallback and
streaming-cache-fill (unchanged warm-hit writes, conditional responses, bounded
singleflight and partial-object privacy). These are local checks, not proof of a
deployed Gateway or live NAS-to-VPS acceptance.
Before activation: qualify a reachable provider exit; build and deploy only with
the canonical NODE.DC artifact/runner plan/apply workflow; provision the derived
private key; verify bounded warm hits, cold fills and NAS outage/recovery. Preserve
the existing AMD route as rollback. No NAS deployment artifact was staged during
the blocked McHost qualification.
-103
View File
@@ -1,103 +0,0 @@
// Delegated Core egress is authenticated separately from map-read admission.
// A browser/trusted-subject header alone cannot redirect provider credentials.
import {AsyncLocalStorage} from 'node:async_hooks';
import {createHash, createHmac, timingSafeEqual} from 'node:crypto';
import {lookup} from 'node:dns/promises';
import {Agent, request as httpRequest} from 'node:http';
import {isIP} from 'node:net';
import {Readable} from 'node:stream';
import {connect} from 'node:tls';
export const egressContext = new AsyncLocalStorage();
const contract = 'nodedc.map-egress/v1';
const hosts = new Set(['api.cesium.com', 'assets.ion.cesium.com', 'assets.cesium.com',
'dev.virtualearth.net', 'ecn.tiles.virtualearth.net',
...[0,1,2,3].map(n=>`ecn.t${n}.tiles.virtualearth.net`)]);
function denied(code='map_egress_request_rejected', statusCode=403) {
return Object.assign(new Error(code), {statusCode});
}
export function signingKey(adminSecret) {
return createHmac('sha256', adminSecret).update('nodedc.map-egress.core/v1').digest();
}
export function authorizeEgress(request, adminSecret, path, now=Date.now()) {
const payload=request.headers['x-nodedc-map-egress'];
const signature=request.headers['x-nodedc-map-egress-signature'];
if (!payload && !signature) return null;
if (!adminSecret || typeof payload!=='string' || payload.length>4096 || !/^[A-Za-z0-9_-]+$/.test(payload)
|| typeof signature!=='string' || !/^[a-f0-9]{64}$/.test(signature)) throw denied();
const expected=createHmac('sha256',signingKey(adminSecret))
.update(`${contract}\n${request.method}\n${path}\n${payload}`).digest();
if (!timingSafeEqual(expected,Buffer.from(signature,'hex'))) throw denied();
let value;
try {value=JSON.parse(Buffer.from(payload,'base64url'));} catch {throw denied();}
if (!value || Object.keys(value).sort().join(',')!=='endpoint,fingerprint,profile,schema,timestamp,token'
|| value.schema!==contract || value.profile!=='cesium' || !Number.isSafeInteger(value.timestamp)
|| Math.abs(now/1000-value.timestamp)>30 || !/^[a-f0-9]{64}$/.test(value.fingerprint)
|| !/^[A-Za-z0-9_-]{43}$/.test(value.token)) throw denied();
validateEndpoint(value.endpoint);
return value;
}
export function publicIPv4(address) {
if(isIP(address)!==4) return false;
const [a,b,c]=address.split('.').map(Number);
return !(a===0||a===10||a===127||a>=224||(a===100&&b>=64&&b<=127)
||(a===169&&b===254)||(a===172&&b>=16&&b<=31)||(a===192&&(b===168||b===0||b===2))
||(a===198&&(b===18||b===19||(b===51&&c===100)))||(a===203&&b===0&&c===113));
}
function validateEndpoint(endpoint) {
let url;
try {url=new URL(endpoint);} catch {throw denied();}
if(url.protocol!=='https:'||url.username||url.password||url.search||url.hash||url.pathname!=='/'
|| !url.port || Number(url.port)<1024 || Number(url.port)>65535) throw denied();
return url;
}
let active=0;
export async function relayFetch(binding,target,options={},dependencies={}) {
const provider=new URL(target);
if(provider.protocol!=='https:'||!hosts.has(provider.hostname)||provider.username||provider.password
||provider.hash||(provider.port&&provider.port!=='443')||!['GET','HEAD'].includes(options.method||'GET')) throw denied();
const endpoint=validateEndpoint(binding.endpoint);
if(active>=16) throw denied('map_egress_capacity_reached',503);
active++;
let socket,agent,released=false;
const release=()=>{if(!released){released=true;active--;agent?.destroy();socket?.destroy();}};
try {
const addresses=await (dependencies.lookup||lookup)(endpoint.hostname,{all:true,family:4});
if(!addresses.length||addresses.some(item=>!publicIPv4(item.address))) throw denied();
options.signal?.throwIfAborted();
socket=await new Promise((resolve,reject)=>{
const candidate=(dependencies.connect||connect)({host:addresses[0].address,port:Number(endpoint.port),servername:isIP(endpoint.hostname)?undefined:endpoint.hostname,
rejectUnauthorized:false,minVersion:'TLSv1.3'});
const timer=setTimeout(()=>candidate.destroy(new Error('relay_timeout')),8000);
const abort=()=>candidate.destroy(new Error('relay_cancelled'));
options.signal?.addEventListener('abort',abort,{once:true});
candidate.once('error',error=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);reject(error);});
candidate.once('secureConnect',()=>{
clearTimeout(timer);options.signal?.removeEventListener('abort',abort);
const actual=createHash('sha256').update(candidate.getPeerCertificate().raw||Buffer.alloc(0)).digest('hex');
if(actual!==binding.fingerprint){candidate.destroy();reject(denied('map_egress_identity_changed',502));}
else resolve(candidate); // No HTTP bytes/credentials sent before this point.
});
});
const input=new Headers(options.headers||{}), headers={Authorization:`Bearer ${binding.token}`};
for(const name of ['accept','range','if-none-match','if-modified-since']) if(input.has(name)) headers[name]=input.get(name);
if(input.has('authorization')) headers['X-Nodedc-Upstream-Authorization']=input.get('authorization');
if(input.has('referer')) headers['X-Nodedc-Upstream-Referer']=input.get('referer');
agent=new Agent({keepAlive:false});
agent.createConnection=()=>socket;
const response=await new Promise((resolve,reject)=>{
const req=httpRequest({host:endpoint.hostname,port:Number(endpoint.port),agent,method:options.method||'GET',
path:'/v1/fetch/cesium?'+new URLSearchParams({url:provider.href}),headers,signal:options.signal},resolve);
req.setTimeout(30000,()=>req.destroy(new Error('relay_timeout')));
req.once('error',reject);req.end();
});
response.once('close',release);
const responseHeaders=new Headers();
for(const [key,value] of Object.entries(response.headers)) if(value!==undefined&&!['transfer-encoding','connection','set-cookie'].includes(key))
responseHeaders.set(key,Array.isArray(value)?value.join(', '):value);
if(options.method==='HEAD'||[204,205,304].includes(response.statusCode)) {
response.resume();return new Response(null,{status:response.statusCode,headers:responseHeaders});
}
return new Response(Readable.toWeb(response),{status:response.statusCode,headers:responseHeaders});
} catch(error) {release();throw error?.statusCode?error:denied('map_egress_unavailable',502);}
}
+6 -16
View File
@@ -12,7 +12,6 @@ import {
TRANSPORT_STATION_PROFILE_ID,
createReferenceStationSource,
} from "./reference-station-source.mjs";
import {authorizeEgress, egressContext, relayFetch} from "./egress.mjs";
import { loadZoneSourceProfile } from "./zone-source-snapshot.mjs";
const canonicalCesiumAssetIds = ["1", "2", "96188"];
@@ -22,8 +21,6 @@ const cesiumVerificationTransportVersion = 4;
const canonicalCesiumEgressHosts = new Set([
"api.cesium.com",
"assets.ion.cesium.com",
"assets.cesium.com",
"ecn.tiles.virtualearth.net",
"dev.virtualearth.net",
"ecn.t0.tiles.virtualearth.net",
"ecn.t1.tiles.virtualearth.net",
@@ -66,7 +63,7 @@ let activeCesiumIonToken = (await readStoredCesiumIonToken()) || config.bootstra
let ionTokenWriteQueue = Promise.resolve();
let ionTokenGeneration = 0;
const server = createServer((request, response) => egressContext.run(null, async () => {
const server = createServer(async (request, response) => {
applyCors(request, response);
if (request.method === "OPTIONS") return response.writeHead(204).end();
let requestPath = "unknown";
@@ -85,7 +82,6 @@ const server = createServer((request, response) => egressContext.run(null, async
return serveZoneSourceGeneration(request, response);
}
if (!isAllowedRequest(request)) return writeJson(response, 401, { ok: false, error: "map_gateway_auth_required" });
egressContext.enterWith(authorizeEgress(request, config.mapGatewayAdminSecret, requestUrl.pathname));
if (requestUrl.pathname === `/api/map/reference-sources/v1/profiles/${TRANSPORT_STATION_PROFILE_ID}/current`
&& ["GET", "HEAD"].includes(request.method || "")) {
@@ -100,7 +96,6 @@ const server = createServer((request, response) => egressContext.run(null, async
return writeJson(response, 200, {
ok: true,
service: "nodedc-map-gateway",
egressContract: "nodedc.map-egress/v1",
cache: await cacheStats(liveCache),
offlineSnapshot: offlineSnapshot ? await cacheStats(offlineSnapshot) : null,
diagnostics: gatewayDiagnostics.status(),
@@ -149,7 +144,7 @@ const server = createServer((request, response) => egressContext.run(null, async
error: errorCode,
});
}
}));
});
server.listen(config.port, "0.0.0.0", () => {
console.log(`NODE.DC Map Gateway listening on http://0.0.0.0:${config.port}`);
@@ -1361,20 +1356,16 @@ function throughCesiumEgress(target, options = {}) {
async function fetchWithTimeout(target, options = {}, diagnostic = {}) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), config.upstreamTimeoutMs);
const binding = egressContext.getStore();
const viaRelay = Boolean(binding && canonicalCesiumEgressHosts.has(new URL(String(target)).hostname));
const viaEgress = viaRelay || shouldUseCesiumEgress(target);
const viaEgress = shouldUseCesiumEgress(target);
const provider = safeProviderName(target);
const operation = safeProviderOperation(diagnostic.operation);
const assetId = /^\d{1,20}$/.test(String(diagnostic.assetId || "")) ? String(diagnostic.assetId) : undefined;
const request = viaEgress && !viaRelay
const request = viaEgress
? throughCesiumEgress(target, options)
: { target, options };
const startedAt = Date.now();
try {
const response = viaRelay
? await relayFetch(binding, target, {...options, signal: controller.signal})
: await fetch(request.target, { ...request.options, signal: controller.signal, redirect: "follow" });
const response = await fetch(request.target, { ...request.options, signal: controller.signal, redirect: "follow" });
const egressError = safeEgressErrorCode(response.headers.get("x-nodedc-egress-error"));
// The restricted egress emits a short code instead of a target URL or a
// secret. Preserve it through Map Gateway so the operator can distinguish
@@ -1507,8 +1498,7 @@ function createGatewayDiagnostics(slowUpstreamMs) {
function safeEgressErrorCode(value) {
const code = String(value || "").trim();
const relay = new Set(["upstream_region_denied", "upstream_unavailable", "capacity_reached", "access_rejected", "request_rejected"]);
return /^amd_[a-z0-9_.:-]{1,100}$/.test(code) || relay.has(code) ? code : "";
return /^amd_[a-z0-9_.:-]{1,100}$/.test(code) ? code : "";
}
function safeDiagnosticCode(value) {
-60
View File
@@ -1,60 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {createHash,createHmac,X509Certificate} from 'node:crypto';
import {createServer} from 'node:https';
import {connect} from 'node:tls';
import {execFileSync} from 'node:child_process';
import {mkdtemp,readFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {authorizeEgress,publicIPv4,relayFetch,signingKey} from '../src/egress.mjs';
const secret='a'.repeat(64);
function signed(overrides={}) {
const value={schema:'nodedc.map-egress/v1',timestamp:1000,profile:'cesium',
endpoint:'https://1.1.1.1:19446',fingerprint:'b'.repeat(64),token:'c'.repeat(43),...overrides};
const payload=Buffer.from(JSON.stringify(value)).toString('base64url');
const signature=createHmac('sha256',signingKey(secret)).update(`nodedc.map-egress/v1\nGET\n/api/map/cache\n${payload}`).digest('hex');
return {method:'GET',headers:{'x-nodedc-map-egress':payload,'x-nodedc-map-egress-signature':signature}};
}
test('signed admission rejects tampering, expiry and a subject without delegation',()=>{
assert.equal(authorizeEgress(signed(),secret,'/api/map/cache',1000000).profile,'cesium');
assert.throws(()=>authorizeEgress(signed(),secret,'/api/map/ion',1000000));
assert.throws(()=>authorizeEgress(signed(),secret,'/api/map/cache',1031000));
assert.throws(()=>authorizeEgress(signed(),'wrong','/api/map/cache',1000000));
assert.throws(()=>authorizeEgress(signed({profile:'arbitrary'}),secret,'/api/map/cache',1000000));
assert.equal(authorizeEgress({headers:{'x-nodedc-user-id':'operator'}},secret,'/api/map/cache'),null);
});
test('public relay destination excludes private and special address ranges',()=>{
for(const address of ['127.0.0.1','0.0.0.0','10.1.1.1','100.64.0.1','169.254.169.254','172.22.0.1','192.168.1.2','198.18.0.1','203.0.113.1','224.0.0.1','::1']) assert.equal(publicIPv4(address),false,address);
assert.equal(publicIPv4('1.1.1.1'),true);
});
test('TLS pin checked before secrets; range and cancellation preserve transport boundaries',async()=>{
const folder=await mkdtemp(join(tmpdir(),'egress-test-'));
let server;
try {
execFileSync('openssl',['req','-x509','-newkey','ed25519','-nodes','-days','1','-subj','/CN=test','-keyout',join(folder,'key'),'-out',join(folder,'cert')],{stdio:'ignore'});
const cert=await readFile(join(folder,'cert')),key=await readFile(join(folder,'key'));
const fingerprint=createHash('sha256').update(new X509Certificate(cert).raw).digest('hex');
const received=[];
server=createServer({cert,key,minVersion:'TLSv1.3'},(req,res)=>{
received.push({url:req.url,headers:req.headers});
res.writeHead(206,{'content-type':'application/octet-stream','content-range':'bytes 1-3/4','set-cookie':'secret'});res.end('abc');
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const dependencies={lookup:async()=>[{address:'1.1.1.1'}],connect:options=>connect({...options,host:'127.0.0.1',port:server.address().port})};
const binding={endpoint:'https://1.1.1.1:19446',token:'c'.repeat(43),fingerprint};
await assert.rejects(relayFetch({...binding,fingerprint:'0'.repeat(64)},'https://assets.ion.cesium.com/a',{},dependencies),/identity_changed/);
assert.equal(received.length,0);
const response=await relayFetch(binding,'https://assets.ion.cesium.com/a',{headers:{authorization:'Bearer provider-secret',range:'bytes=1-3',cookie:'no'}},dependencies);
assert.equal(response.status,206);assert.equal(await response.text(),'abc');
assert.equal(response.headers.get('content-range'),'bytes 1-3/4');assert.equal(response.headers.get('set-cookie'),null);
assert.equal(received[0].headers.authorization,'Bearer '+binding.token);
assert.equal(received[0].headers['x-nodedc-upstream-authorization'],'Bearer provider-secret');
assert.equal(received[0].headers.cookie,undefined);
const cancelled=new AbortController();cancelled.abort();
await assert.rejects(relayFetch(binding,'https://assets.ion.cesium.com/a',{signal:cancelled.signal},dependencies));
assert.equal(received.length,1,'A cancelled request must not send credentials');
await assert.rejects(relayFetch(binding,'https://private.example/',{},dependencies));
} finally {if(server)await new Promise(resolve=>server.close(resolve));await rm(folder,{recursive:true,force:true});}
});
-5
View File
@@ -167,11 +167,6 @@ Current package:
- `seo` - NDC SEO mod domain ontology for site scans, project ontology instances, scope contracts, semantic analysis, market evidence, optimization planning, validation, changesets, and future app-owned SEO assistant actions.
- `map` - provider-neutral NDC Module Studio map ontology for spatial subjects, layers, routes, zones, shared labels, visibility rules, selection, and replaceable renderer adapters.
- `gelios` - provider-neutral Gelios fleet and telemetry ontology, bound to map.moving_object, map.zone and map.place_target without exposing provider credentials or renderer objects.
- `party` - provider-neutral people, organizations, accounts, access subjects, contacts and temporal operational roles.
- `asset` - stable business assets, external references, assignments and lifecycle evidence independent of tracker or provider identity.
- `device` - Device Core direct onboarding, adapter, enrollment, temporal Asset binding, Edge route, session, configuration, typed command and audit ontology.
- `infrastructure` - provider-neutral Host, Endpoint, Deployment, Service Instance and privileged management-session topology for VPS and Edge infrastructure.
- `observation` - time-qualified property, source, freshness, health and position evidence for Assets, Devices and infrastructure.
The package loader merges domain packages into the base catalog before validation. Domain packages extend core meanings; they do not own app data or execute mutations.
@@ -1,13 +0,0 @@
{
"version": "0.1.0",
"updatedAt": "2026-08-22",
"aliases": [
{ "alias": "business asset", "canonicalId": "asset.asset" },
{ "alias": "бизнес-актив", "canonicalId": "asset.asset" },
{ "alias": "трайк как актив", "canonicalId": "asset.asset" },
{ "alias": "тип актива", "canonicalId": "asset.asset_type" },
{ "alias": "внешняя ссылка актива", "canonicalId": "asset.external_reference" },
{ "alias": "назначение актива", "canonicalId": "asset.assignment" },
{ "alias": "событие жизненного цикла актива", "canonicalId": "asset.lifecycle_event" }
]
}
@@ -1,11 +0,0 @@
{
"version": "0.1.0",
"updatedAt": "2026-08-22",
"entities": [
{ "id": "asset.asset", "name": "Asset", "surface": "domain", "status": ["product-required"], "authority": "Owning business domain", "summary": "Stable business or operational object such as a trike, vehicle, machine or facility whose identity survives device, provider and renderer changes." },
{ "id": "asset.asset_type", "name": "Asset Type", "surface": "domain", "status": ["product-required"], "authority": "Owning business domain + Ontology Core", "summary": "Versioned semantic classification of an asset without forcing a rigid inheritance hierarchy." },
{ "id": "asset.external_reference", "name": "Asset External Reference", "surface": "domain", "status": ["product-required"], "authority": "Owning business domain", "summary": "Namespaced reference linking an asset to a source-system record without replacing the NODE.DC asset identity." },
{ "id": "asset.assignment", "name": "Asset Assignment", "surface": "domain", "status": ["product-required"], "authority": "Owning operations domain", "summary": "Time-qualified relationship connecting an asset to a party, role, project or other operational context with provenance and validity interval." },
{ "id": "asset.lifecycle_event", "name": "Asset Lifecycle Event", "surface": "domain", "status": ["product-required"], "authority": "Owning business domain", "summary": "Immutable evidence of an asset lifecycle transition such as commissioning, activation, suspension, retirement or transfer." }
]
}
@@ -1,18 +0,0 @@
{
"version": "0.1.0",
"updatedAt": "2026-08-22",
"sourceRoots": [
{ "surface": "device-core", "path": "/Users/dcconstructions/Downloads/mnt/NODEDC/NODEDC_DEVICE_CORE", "mode": "Read-only device, project, binding, direct lifecycle and restricted-identifier source inspection" },
{ "surface": "foundry", "path": "foundry://application/1c7dcdbb-6e50-4272-b1bc-aa5ece77ae99", "mode": "Robot2B Data Product composition and moving-object projection inspection" },
{ "surface": "ops-decision", "path": "DCPLATFORM-70", "mode": "Accepted direct B2, trike Asset and temporal attachment decision" }
],
"ledgers": [
{ "id": "ledger.asset_domain_v0", "path": "docs/PARTY_ASSET_DOMAIN_ONTOLOGY.md", "entityIds": ["asset.asset", "asset.asset_type", "asset.external_reference", "asset.assignment", "asset.lifecycle_event"] }
],
"baselineDocs": ["docs/PARTY_ASSET_DOMAIN_ONTOLOGY.md"],
"restrictions": [
"Do not use IMEI, provider unit ID, current tracker or renderer ID as the Asset identity.",
"Do not hide reassignment history by mutating one current owner, driver or device field.",
"Do not publish an Asset to a map without a declared spatial observation and Data Product semantic binding."
]
}
@@ -1,38 +0,0 @@
{
"version": "0.1.0",
"updatedAt": "2026-08-22",
"rules": [
{
"id": "guardrail.asset.identity_survives_device_changes",
"severity": "error",
"summary": "Asset identity must not be derived from IMEI, tracker, provider unit, current driver, project or renderer object; those are separate graph subjects and assignments.",
"entityIds": ["asset.asset", "device.tracking_device", "device.restricted_identifier", "gelios.unit", "party.driver_role", "map.moving_object"]
},
{
"id": "guardrail.asset.assignments_are_temporal",
"severity": "error",
"summary": "Asset-to-party, driver, project and device composition requires explicit provenance and valid_from/valid_to semantics; overwriting the current label is not history.",
"entityIds": ["asset.asset", "asset.assignment", "party.driver_role", "device.asset_binding"]
},
{
"id": "guardrail.asset.map_projection_requires_spatial_evidence",
"severity": "error",
"summary": "Foundry may render an asset as a moving object only through a declared Data Product binding backed by a time-qualified spatial observation.",
"entityIds": ["asset.asset", "map.moving_object", "observation.position_observation"]
},
{
"id": "guardrail.asset.ontology_not_asset_store",
"severity": "error",
"summary": "Ontology Core defines Asset meaning and relations; it must not store runtime asset rows, assignments, live positions or lifecycle logs.",
"entityIds": ["asset.asset", "asset.assignment", "asset.lifecycle_event"]
}
],
"blockedConflations": [
["asset.asset", "device.device"],
["asset.asset", "device.tracking_device"],
["asset.asset", "device.restricted_identifier"],
["asset.asset", "gelios.unit"],
["asset.asset", "map.moving_object"],
["asset.assignment", "asset.lifecycle_event"]
]
}
@@ -1,7 +0,0 @@
{
"id": "asset",
"version": "0.1.0",
"updatedAt": "2026-08-22",
"status": "product-required/source-evidenced",
"summary": "Stable business assets, classifications, external references, temporal assignments and lifecycle evidence independent of a tracker, provider or renderer."
}
@@ -1,12 +0,0 @@
{
"version": "0.1.0",
"updatedAt": "2026-08-22",
"relations": [
{ "id": "asset.asset.classified_by_type", "from": ["asset.asset"], "to": ["asset.asset_type"], "status": "product-required", "summary": "An asset uses a versioned semantic type while remaining a stable shallow graph subject." },
{ "id": "asset.asset.has_external_reference", "from": ["asset.asset"], "to": ["asset.external_reference"], "status": "product-required", "summary": "An asset may have multiple namespaced provider or source-system references." },
{ "id": "asset.asset.has_assignment", "from": ["asset.asset"], "to": ["asset.assignment"], "status": "product-required", "summary": "Operational composition is represented by explicit assignments with provenance and validity intervals." },
{ "id": "asset.assignment.assigns_party", "from": ["asset.assignment"], "to": ["party.party", "party.driver_role"], "status": "product-required", "summary": "An assignment connects the asset to a party or operational role for a bounded interval." },
{ "id": "asset.asset.has_lifecycle_event", "from": ["asset.asset"], "to": ["asset.lifecycle_event"], "status": "product-required", "summary": "Lifecycle transitions are preserved as evidence rather than overwritten status labels." },
{ "id": "asset.asset.is_map_moving_object", "from": ["asset.asset"], "to": ["map.moving_object"], "status": "product-required", "summary": "An asset with spatial evidence can be projected into Foundry through the provider-neutral moving-object contract without adopting renderer identity." }
]
}

Some files were not shown because too many files have changed in this diff Show More