Add signed Zstandard transport and measured sanitized deployment receipts

This commit is contained in:
Nick Beckley 2026-11-25 17:33:37 +00:00
parent ec0bdf4f39
commit 15a9f96f79
23 changed files with 3221 additions and 204 deletions

View File

@ -0,0 +1,149 @@
{
"fixture": "/home/nick/plotdirector-routine-20261125/bundle/package.tar",
"original_bytes": 554260480,
"original_sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7",
"baseline_mib_per_second": 1.888,
"results": [
{
"method": "uncompressed",
"bytes": 554260480,
"compression_seconds": 0,
"decompression_seconds": 0,
"estimated_transfer_seconds": 279.97033070709745,
"combined_seconds": 279.97033070709745,
"sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7"
},
{
"method": "gzip-1",
"bytes": 201854349,
"compression_seconds": 5.7469,
"decompression_seconds": 2.0668,
"estimated_transfer_seconds": 101.9615,
"combined_seconds": 109.7751,
"compression_cpu_user_seconds": 5.63,
"compression_cpu_system_seconds": 0.11,
"compression_peak_rss_kib": 7908,
"integrity": "original SHA256 matched"
},
{
"method": "gzip-6",
"bytes": 181826954,
"compression_seconds": 17.9912,
"decompression_seconds": 1.845,
"estimated_transfer_seconds": 91.8452,
"combined_seconds": 111.6814,
"compression_cpu_user_seconds": 17.87,
"compression_cpu_system_seconds": 0.11,
"compression_peak_rss_kib": 7892,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-1-T1",
"bytes": 189037362,
"compression_seconds": 1.6523,
"decompression_seconds": 0.623,
"estimated_transfer_seconds": 95.4873,
"combined_seconds": 97.7626,
"compression_cpu_user_seconds": 1.78,
"compression_cpu_system_seconds": 0.31,
"compression_peak_rss_kib": 18084,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-1-T4",
"bytes": 189037362,
"compression_seconds": 0.4813,
"decompression_seconds": 0.6185,
"estimated_transfer_seconds": 95.4873,
"combined_seconds": 96.5872,
"compression_cpu_user_seconds": 1.85,
"compression_cpu_system_seconds": 0.35,
"compression_peak_rss_kib": 31492,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-1-T8",
"bytes": 189037362,
"compression_seconds": 0.4085,
"decompression_seconds": 0.6559,
"estimated_transfer_seconds": 95.4873,
"combined_seconds": 96.5517,
"compression_cpu_user_seconds": 2.65,
"compression_cpu_system_seconds": 0.43,
"compression_peak_rss_kib": 47560,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-3-T1",
"bytes": 174970395,
"compression_seconds": 2.4469,
"decompression_seconds": 0.6677,
"estimated_transfer_seconds": 88.3818,
"combined_seconds": 91.4963,
"compression_cpu_user_seconds": 2.55,
"compression_cpu_system_seconds": 0.41,
"compression_peak_rss_kib": 52144,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-3-T4",
"bytes": 174970395,
"compression_seconds": 0.7884,
"decompression_seconds": 0.6596,
"estimated_transfer_seconds": 88.3818,
"combined_seconds": 89.8298,
"compression_cpu_user_seconds": 2.91,
"compression_cpu_system_seconds": 0.38,
"compression_peak_rss_kib": 93328,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-3-T8",
"bytes": 174970395,
"compression_seconds": 0.7352,
"decompression_seconds": 0.6704,
"estimated_transfer_seconds": 88.3818,
"combined_seconds": 89.7874,
"compression_cpu_user_seconds": 4.68,
"compression_cpu_system_seconds": 0.43,
"compression_peak_rss_kib": 146288,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-6-T1",
"bytes": 165585450,
"compression_seconds": 6.6843,
"decompression_seconds": 0.6449,
"estimated_transfer_seconds": 83.6412,
"combined_seconds": 90.9705,
"compression_cpu_user_seconds": 6.73,
"compression_cpu_system_seconds": 0.43,
"compression_peak_rss_kib": 53576,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-6-T4",
"bytes": 165585450,
"compression_seconds": 2.027,
"decompression_seconds": 0.6607,
"estimated_transfer_seconds": 83.6412,
"combined_seconds": 86.3288,
"compression_cpu_user_seconds": 7.87,
"compression_cpu_system_seconds": 0.46,
"compression_peak_rss_kib": 97704,
"integrity": "original SHA256 matched"
},
{
"method": "zstd-6-T8",
"bytes": 165585450,
"compression_seconds": 1.6271,
"decompression_seconds": 0.6714,
"estimated_transfer_seconds": 83.6412,
"combined_seconds": 85.9397,
"compression_cpu_user_seconds": 11.92,
"compression_cpu_system_seconds": 0.45,
"compression_peak_rss_kib": 158668,
"integrity": "original SHA256 matched"
}
]
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,17 @@
{
"status": "public-unchanged",
"application_release": "eadda6f6",
"application_action_taken": false,
"tooling_installation": "pending temporary administrator authorisation",
"sites": {
"plotdirector": {
"https_status": 200,
"tls_verified": true
},
"catherine": {
"https_status": 200,
"tls_verified": true
}
},
"production_css_matches_eadda6f6": true
}

View File

@ -0,0 +1,13 @@
{
"status": "qualified-on-atlas-installation-pending",
"deployment_regression_tests": 67,
"retained_compressed_release_all_checksums_and_signatures": "passed",
"legacy_signed_release_compatibility": "passed",
"real_root_filesystem_receipt_boundaries": "passed",
"isolated_sql_worker_counters_replay_and_failure_rollback": "passed",
"application_rebuilt": false,
"production_application_activated": false,
"production_tooling_installed": false,
"web1_decompression_measured": false,
"blocker": "Existing dedicated Atlas key needs temporary administrator authorisation for reviewed root-owned tooling maintenance; no SQL admin credentials needed."
}

View File

@ -0,0 +1,99 @@
{
"format": 1,
"origin": "atlas-retained-package-qualification",
"started_utc": "2026-11-25T17:23:21.718+00:00",
"completed_utc": "2026-11-25T17:23:24.373+00:00",
"status": "validated-package-only",
"phases": [
{
"name": "package_validation",
"started_utc": "2026-11-25T17:23:21.718+00:00",
"parent": null,
"outcome": "passed",
"completed_utc": "2026-11-25T17:23:21.904+00:00",
"seconds": 0.185414,
"exclusive_seconds": 0.185414
},
{
"name": "decompression",
"started_utc": "2026-11-25T17:23:21.904+00:00",
"parent": null,
"outcome": "passed",
"completed_utc": "2026-11-25T17:23:22.927+00:00",
"seconds": 1.022908,
"exclusive_seconds": 1.022908
},
{
"name": "package_validation",
"started_utc": "2026-11-25T17:23:22.927+00:00",
"parent": null,
"outcome": "passed",
"completed_utc": "2026-11-25T17:23:24.356+00:00",
"seconds": 1.428878,
"exclusive_seconds": 1.428878
}
],
"warnings": [],
"failures": [],
"checks": {
"unchanged_original_signature": true,
"transport_signature": true,
"original_tar_sha256": true,
"all_application_and_sql_checksums": true,
"exact_qualified_dll": true
},
"migrations": {
"executed": null,
"baselined": null
},
"recovery": "No automatic database restore or application rollback. Review protected attempt evidence on failure.",
"transport": {
"method": "zstd",
"original_bytes": 554260480,
"transferred_bytes": 165585450,
"original_sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7",
"transferred_sha256": "f0786b505d5f1b1a43ff28283ca730b0e045f19a395432d85013c998292d85a1",
"compression_ratio": 0.29875,
"compression_seconds_atlas": 2.0684954689932056,
"settings": {
"level": 6,
"threads": 4
}
},
"release": {
"id": "plotdirector-production-eadda6f6-20261125-r1",
"version": "1.0.0",
"source_commit": "eadda6f674ac456e8ae6014e2c5781088d408f8f",
"package_sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7",
"application_sha256": "238850639212d9f39bc6e208f0799dd1fb42c7f6a3d903386ccdf406baa6cb22"
},
"timing": {
"total_seconds": 2.654963,
"measured_top_level_seconds": 2.6372,
"unattributed_seconds": 0.017763,
"clock": "monotonic; UTC timestamps for correlation only"
},
"unperformed_phases": [
"release_preparation",
"production_validation",
"remote_activation",
"receipt_retrieval",
"scope_verification",
"build",
"packaging_signing",
"compression",
"transfer",
"database_state_verification",
"migration_history_verification",
"database_backup",
"migration_execution",
"service_stop",
"release_installation",
"release_activation",
"service_start",
"application_health_readiness",
"postactivation_verification",
"public_acceptance",
"receipt_generation"
]
}

View File

@ -0,0 +1,13 @@
{
"status": "passed",
"isolated_database": "PlotDirector_Qualification_Transport_20261125",
"executed": 2,
"baselined": 1,
"replay_executed": 0,
"failed_transaction_rolled_back": true,
"failed_success_history_absent": true,
"readback_existing_activation_record": "passed",
"existing_retained_history_rows": 320,
"no_production_connection": true,
"fixture_database_removed": true
}

View File

@ -7,6 +7,10 @@ future changes still require environment-specific authorisation and qualificatio
Latest routine release: `eadda6f6`, version `1.0.0`; see [deployment and timings](Routine-20261125-eadda6f6.md).
**Tooling update:** compressed transport/receipts are qualified on Atlas but await
the authorised web1 maintenance installation; see [qualification and status](Transport-20261125.md).
Use raw packages until that installation is verified.
## Trust and environment boundaries
- Build only on Atlas, from a clean, committed worktree. Keep source, SDKs and
@ -128,7 +132,7 @@ manual SQL procedure alongside this ledger after adoption.
## Activation and failure behaviour
`transfer.py` sends only the three immutable bundle files over strict SSH. The
forced SSH dispatcher supports upload, validate, activate and rollback with one
forced SSH dispatcher supports upload, validate, activate, rollback and sanitized receipt retrieval with one
validated release ID; it rejects shells, SFTP and other commands. Transfer alone
does not activate anything. An incomplete upload requires administrator review;
it is not overwritten automatically.
@ -316,3 +320,140 @@ RENEWED_LINEAGE is `/etc/letsencrypt/live/plotdirector.com`, then runs `nginx -t
and reloads Nginx. The targeted dry run passed. Never replace Catherine's files.
The supplied vhost template requires the PlotDirector map and maintenance snippet;
initial provisioning starts with 503, while the live snippet contains only a comment.
## Compressed transport and standard routine receipt
Selected transport: **Zstandard level 6, four workers, frame checksum**. Preparation
now defaults to this codec; `--compression none` retains the original tar format.
The original USTAR `package.tar`, authorization.json and Ed25519 authorization.sig
remain the integrity/recovery basis. Compression does not change manifest bytes,
application/SQL contents or the original signature. A new transport.json/signature
binds compressed bytes/hash/size, original tar hash/size and original authorization
hash. The compressed bundle contains exactly these transfer members:
```
authorization.json
authorization.sig
transport.json
transport.sig
package.tar.zst
```
Original three-file raw bundles remain valid. To wrap a retained raw release,
without any application rebuild or modification of that original bundle:
```bash
python3 Tools/Deployment/release.py compress \
--bundle /absolute/original-signed-bundle \
--output /absolute/new-compressed-bundle \
--signing-key /absolute/private/release-signing.pem \
--public-key /absolute/trusted/release-signing-public.pem
```
Both signatures and compressed integrity are checked before decoding. The decoder
uses signed exact output size, a 4 GiB global input/output ceiling, 128 MB window
limit and CPU/wall limits. Reconstructed bytes must match the original signed tar
SHA, then all original safe extraction, manifest, SQL and application checks run.
No unsigned patches, incremental updates or active-directory modification occurs.
Allow space for compressed snapshot + original tar + extracted payload + new
release, as well as existing backups/releases and the configured free-space floor.
Failed transfer/decompression affects only incoming/private temporary storage.
Upload and deployment locks remain independent and mandatory.
For new release preparation, continue the qualified-source/evidence process above,
add `--scope-base FULL_CURRENT_APPLICATION_COMMIT`, and use the default compression.
For measured end-to-end orchestration, `deploy.py` can prepare from clean source
(`--source`, `--scope-base`, `--plan`, `--sql`, `--evidence`, `--output`,
`--release-id`, `--signing-key`) or use an existing qualified `--bundle` instead:
```bash
python3 Tools/Deployment/deploy.py \
--bundle /absolute/qualified-compressed-bundle \
--identity /home/nick/.ssh/plotdirector-production \
--public-key /absolute/trusted/release-signing-public.pem \
--receipt /absolute/private/new-operation-receipt.json \
--public-acceptance
```
This defaults to **non-activating validation**. Add `--activate` only with explicit
application-release authorisation. Unexpected pending history blocks activation;
`--allow-migrations` requires a separately reviewed/qualified and authorised SQL
upgrade. The application source/qualification process is unchanged. Scope timing
captures clean-commit checks and Git differences, not a claim of automatic semantic
review. Human scope/release approval remains necessary before signing/activation.
No long bespoke Markdown report is needed for an ordinary success. The command
writes a structured JSON receipt plus a concise text summary from the same data.
Keep detailed protected diagnostics for failures or exceptional timings. Receipts
carry release/version/source, package/application/DLL checksums, compressed/original
sizes and ratio, measured transfer/throughput, previous/new identity, backup result,
actual history counts and executed/baselined migrations, read-back activation row,
health, optional public acceptance, warnings/recovery and phase measurements.
Failed server receipts are retrieved too; failed public acceptance remains a failed
pipeline outcome even if the nested server record correctly shows an active release.
No automatic retry, database restore or unqualified rollback is introduced.
Server receipts: `/srv/plotdirector/deployment-receipts/DEPLOYMENT-ID.json` and
`.txt`, root:plotdirector-deploy 0640 in root:plotdirector-deploy 0750 directory.
Retrieve JSON using the existing strict SSH options and command `receipt ID`.
This reads only bounded root-owned regular sanitized receipt files, never arbitrary
paths, protected attempt logs, configuration or credentials. The forced dispatcher
and fixed sudo helper remain the only entry points; no general sudo/shell or
additional database privilege is granted. The root-protected detailed JSONL attempt
evidence remains separate. Receiver transfer metrics are explicitly unprivileged
telemetry, not authorisation; Atlas sender throughput is measured independently.
Timing uses monotonic clocks. Parent phase durations include child phases;
exclusive durations and unattributed overhead prevent double counting. UTC values
are for correlation, not elapsed-time arithmetic. SQL history verification is timed
in the worker with Stopwatch; if child UTC endpoints are unavailable they are null,
not reconstructed. Missing/unperformed phases are explicit, never measured zero.
Service confirmed-inactive-to-start-command-complete and inactive-to-health-ready
are separate from stop-request-inclusive intervals and independently sampled public
outage. Source preparation and web1 operations have distinct clocks/provenance.
The combined pipeline measures its own total including otherwise unattributed work;
using an already prepared bundle does not pretend to measure an earlier build.
Standard target: **3–5 minutes** for a routine release where achievable; **10 minutes**
is the normal upper target subject to essential backup, integrity and health checks.
Investigate exceptional times. Reuse valid qualification; do not repeat full app,
Companion or recovered-database exercises on ordinary releases. Postactivation
checks and history/row readback now occur inside the helper, so a further complete
package extraction solely for status/reporting is unnecessary. Pre-activation
validation and activation still independently verify immutable package integrity.
## Tooling-only administrative maintenance
Tooling installation is separate from an application release. If Atlas's temporary
administrator authorisation has been removed, a desktop/laptop administrator must
briefly re-authorise only the existing dedicated Atlas public key, fingerprint
`SHA256:2Iw3JYNS8TgPARowjnp+7wNC6cmWf1EV7Cy1Mg1ig3w`. Use strict pinned SSH and
remove that one authorisation after maintenance; preserve all other admin keys.
The deployment account must never replace its own helper or read migration secrets.
1. Record the live current link, DLL/source identity, application PID and configuration
hashes, and Catherine HTTPS. Confirm `/usr/bin/zstd` availability. Stop if a
prerequisite is missing; do not change application or unrelated infrastructure.
2. Publish only DatabaseWorker on Atlas from the reviewed tooling source. Stage
reviewed hashes/files privately. No SDK, repository or Codex is installed on web1.
3. Take the existing `/srv/plotdirector/deployment.lock` exclusively. Preserve the
previous helper/modules and entire worker output under a new protected
`/srv/backups/configuration/plotdirector-tooling-before-TIMESTAMP/` directory.
4. Install receipt.py/transport.py first, then release.py and the new worker, then
activate.py/dispatcher/launcher, all root-owned and non-writable by runtime/deploy.
Worker directory/files remain 0755/0644; dispatcher and launcher 0755. Create the
receipt directory with explicit root:plotdirector-deploy 0750 permissions. Keep
target/configuration, credentials, service, SSH/sudo and web server settings intact.
5. For the retained signed package transport test, preserve the existing incoming
directory under a new protected transport-test archive before using the same
release ID; never overwrite it or alter signed tar/manifest bytes. Upload the
compressed wrapper through the restricted account, use `validate` only and
retrieve its sanitized receipt. Test the raw package separately with the verifier.
Do not invoke activate/rollback/migrate, backup/restore, or service stop/start.
6. Confirm decoder measurements on web1, original tar/DLL checksums, receipt read
restrictions, unchanged current link/PID/configuration hashes, history counts and
successful-release count, and continued normal HTTPS for both sites. Remove only
temporary maintenance files/authorisation; retain recovery and diagnostic evidence.
No Production application activation is authorised by a tooling-maintenance task.

View File

@ -0,0 +1,124 @@
# Signed transport and receipt qualification — 25 November 2026
**Atlas implementation qualified; web1 tooling installation is pending temporary
administrator authorisation.** No Production application release was activated.
The active application remains eadda6f6; public HTTPS and Catherine HTTPS return
200, and Production CSS still exactly matches eadda6f6.
The retained successful routine package is an uncompressed USTAR archive:
554260480 bytes / 528.58 MiB, SHA-256
`e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7`.
The application was not rebuilt. Each candidate was compressed, decompressed to
a real temporary file and checked against that original SHA-256. Source/signature
and manifest/file/DLL identity were separately verified using the full retained
signed release. No application dependencies or other package contents were removed.
## Compression benchmark
Compression/decompression durations, sizes and encoder peak RSS below were
**measured on Atlas**, sequentially at nice 10. Transfer durations are **estimates**
using the prior observed 1.888 MiB/s file-payload throughput. Combined time is
compression + estimated transfer + measured Atlas decompression. SHA verification
was performed separately from the benchmark decoder timer. These are single warm
fixture trials, not statistically significant comparisons of subsecond differences.
| Method | Compression s | MiB | Estimated transfer s | Atlas decode s | Combined s | Peak encoder MiB |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| uncompressed | 0.000 | 528.58 | 279.97 | 0.000 | 279.97 | 0.0 |
| gzip-1 | 5.747 | 192.50 | 101.96 | 2.067 | 109.78 | 7.7 |
| gzip-6 | 17.991 | 173.40 | 91.85 | 1.845 | 111.68 | 7.7 |
| zstd-1-T1 | 1.652 | 180.28 | 95.49 | 0.623 | 97.76 | 17.7 |
| zstd-1-T4 | 0.481 | 180.28 | 95.49 | 0.619 | 96.59 | 30.8 |
| zstd-1-T8 | 0.408 | 180.28 | 95.49 | 0.656 | 96.55 | 46.4 |
| zstd-3-T1 | 2.447 | 166.86 | 88.38 | 0.668 | 91.50 | 50.9 |
| zstd-3-T4 | 0.788 | 166.86 | 88.38 | 0.660 | 89.83 | 91.1 |
| zstd-3-T8 | 0.735 | 166.86 | 88.38 | 0.670 | 89.79 | 142.9 |
| zstd-6-T1 | 6.684 | 157.91 | 83.64 | 0.645 | 90.97 | 52.3 |
| zstd-6-T4 | 2.027 | 157.91 | 83.64 | 0.661 | 86.33 | 95.4 |
| zstd-6-T8 | 1.627 | 157.91 | 83.64 | 0.671 | 85.94 | 154.9 |
Select **Zstandard level 6, four workers, frame checksum enabled**. It produces
165585450 bytes / 157.91 MiB (29.87% of original, approximately 70.1% smaller).
Measured compression 2.027s, Atlas decompression 0.661s, estimated transfer 83.64s;
combined 86.33s versus the 280s uncompressed transfer baseline. Estimated transfer
savings are about 196s. Eight workers saved only approximately 0.4s, while increasing
CPU consumption from 8.33 to 12.37 CPU seconds and peak RSS from 95.4 to 155.0 MiB.
Level 3 compresses faster, but its larger output adds more transfer time overall.
Gzip also helps substantially, but is slower overall than the selected Zstandard.
Representative web1 decoder timing is **not yet measured**: the existing restricted
account intentionally cannot run arbitrary benchmark commands or install helpers,
and Atlas's temporary administrator key was removed at Phase 2 completion. No
attempt was made to circumvent this boundary. A retained staged compressed package
and installation procedure are ready for the authorised maintenance window.
Keeping other baseline timings unchanged, replacing transfer and bespoke reporting
suggests approximately **4.3 minutes** overall. The automated pipeline can reduce
orchestration further; a **3–5 minute target is an estimate**, not a measured genuine
release. Ten minutes remains the normal upper target, subject to essential safety.
The next genuine application release is the definitive end-to-end benchmark.
## Implementation and focused qualification
- Original authorization/manifest signatures remain byte-identical. A separately
signed transport envelope binds original authorization hash, original tar hash
and size, compressed hash and size, release/source identity and codec settings.
Corrupt compressed bytes are rejected before the decoder is launched. Decoded
bytes must match both the original signature and complete manifest/file index.
- Original raw packages remain supported. Decoder output is capped to the signed
size and 4 GiB global maximum, with a 128 MB decoder window limit and CPU/wall
limits. Existing regular-file-only archive extraction, no-follow snapshots,
traversal/link/special-member/duplicate checks and count/size limits remain.
Space checks include reconstructed archive, extraction and installation.
- Upload remains unprivileged, fixed-member, bounded and serialised. Upload and
validation never stop a service. Failed/incomplete staging is retained for review.
Backup, transaction, history immutability, deployment lock, activation and
qualified rollback safeguards remain. No incremental/unsigned active-file patching.
- Root creates sanitized JSON/text receipts; the fixed `receipt ID` SSH operation
reads only those receipts. It cannot read protected logs/configuration. The
directory is root:plotdirector-deploy 0750, files 0640; the account gains no write
or general sudo/shell privilege. Credential-like fields/values are defensively
redacted; raw exceptions and command arguments are not copied into receipts.
- Receipts contain actual before/after release identity, package/application/DLL
checksums, transport sizes/ratio, transfer provenance/throughput, backup result,
measured migration counts, read-back activation row, health, failures/recovery,
monotonic timing and otherwise unattributed overhead. Service inactive-to-start,
inactive-to-readiness and independently observed public outage are distinct.
SQL worker history durations are measured with Stopwatch; UTC child endpoints
are null when unavailable, never estimated. Unperformed phases remain explicit.
- `deploy.py` is the measured Atlas workflow. It defaults to validate only; activation
is explicit, and pending history requires a separately authorised allow-migrations
run. It retrieves failed server receipts too. Its JSON/text summary replaces
lengthy bespoke routine reports. Postactivation history checks happen inside the
worker and its successful activation record is read back, avoiding another full
package extraction solely to obtain these facts.
Focused qualification: **67 deployment regression tests passed**, including all
previous tests and compression/signature/checksum/corruption/truncation/expansion,
unsafe archive, lock, upload failure, timing, receipt/redaction, activation/backup/
rollback and permission cases. A real root-owned Atlas filesystem fixture proved
intended-group read-only access, other-user denial, symlink and foreign-owner
rejection. A new tiny isolated SQL fixture proved 2 executed / 1 baselined count,
zero-execution replay and failed transaction/history rollback, then was removed.
The common C# activation-record reader was checked against retained Test history.
No full application/Companion suite, recovered-database restore or Production
migration was repeated. Only DatabaseWorker was published on Atlas.
## Pending installation and remaining opportunities
Temporary administrator authorisation for the existing dedicated Atlas key is
required solely to replace root-owned tooling/worker files and create the receipt
directory. The restricted account correctly cannot do this. Use the established
strict-host-key administrative maintenance procedure, keep other admin keys, and
remove only the temporary Atlas key after qualified installation/non-activating
checks. No permanent Atlas administrator access or expanded deployment sudo is
needed. See the standard's maintenance procedure. Do not stop/start the app, invoke
migrate/activate, or alter SQL/Nginx/SSH/Certbot/configuration during this installation.
Further reduction opportunity: Windows runtime directories alone occupy about
276 MiB. Other RIDs and native variants also contribute. A future qualified
framework-dependent linux-x64 publish may exclude unnecessary platform assets;
no files were removed here, and download/Companion dependencies must be reviewed
before such a change. The full immutable package remains the unit of deployment.
[Machine-readable measurements](Evidence/Transport-20261125/compression-benchmark.json).

View File

@ -20,6 +20,9 @@ internal static class Program
private static string packageHash = "";
private static string? currentMigration;
private static int currentBatch;
private static int executed;
private static int baselined;
private static readonly List<string> committed = [];
public static async Task<int> Main(string[] args)
{
@ -55,7 +58,7 @@ internal static class Program
{
Console.WriteLine(JsonSerializer.Serialize(new { ok = false,
error = e is SqlException se ? "SQL_" + se.Number : e.Message is "baseline" or "concurrent-deployment" or "immutable-migration-checksum" ? e.Message : e.GetType().Name,
migration = currentMigration, batch = currentBatch }));
migration = currentMigration, batch = currentBatch, executed, baselined, committed = committed.Take(256) }));
// A failed command poisons the session. Never proceed to activation.
return 1;
}
@ -107,13 +110,16 @@ internal static class Program
if (!Regex.IsMatch(deployment, "^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$") || !Regex.IsMatch(packageHash,"^[a-f0-9]{64}$"))
throw new InvalidOperationException("identity");
var actual = await Schema();
var historyTimer=Stopwatch.StartNew();
var complete = await ValidateHistory();
var historySeconds=historyTimer.Elapsed.TotalSeconds;
var history=await HistoryStatus();
if (actual != S(manifest, "starting_schema_sha256") && !(complete && actual == S(manifest,"resulting_schema_sha256")))
throw new InvalidOperationException("baseline");
await Idle();
await Conditions(manifest["prerequisites"]!.AsArray());
var databaseBytes=Convert.ToInt64(await Scalar("SELECT SUM(CONVERT(bigint,size))*8192 FROM sys.database_files"));
return new { schema = actual, complete, database_bytes=databaseBytes };
return new { schema = actual, complete, database_bytes=databaseBytes, history, history_verification_seconds=historySeconds };
}
if (!locked || manifest is null) throw new InvalidOperationException("not-begun");
if (op == "idle") { await Idle(); return new { idle = true }; }
@ -139,14 +145,18 @@ internal static class Program
var schema = await Schema();
if (schema != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("resulting-schema");
await Conditions(manifest["postconditions"]!.AsArray());
return new { schema };
return new { schema, executed, baselined, committed=committed.Take(256), committed_list_truncated=committed.Count>256 };
}
if (op == "health")
{
if ((string?)await Scalar("SELECT DB_NAME()") != database) throw new InvalidOperationException("target");
if (await Schema() != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("schema");
await Conditions(manifest["postconditions"]!.AsArray());
return new { healthy = true };
var timer=Stopwatch.StartNew();
var complete=await ValidateHistory();
if(!complete)throw new InvalidOperationException("migration-history-incomplete");
var seconds=timer.Elapsed.TotalSeconds;
return new { healthy = true, complete_history=complete, history=await HistoryStatus(), history_verification_seconds=seconds };
}
if (op == "activated")
{
@ -162,7 +172,9 @@ internal static class Program
["@previous"]=request["previous_deployment"]?.GetValue<string>() is { } previous ? previous : DBNull.Value })
cmd.Parameters.AddWithValue(key,value);
await cmd.ExecuteNonQueryAsync();
return new { recorded = true };
var record=await ReleaseRecord(deployment);
if(record is null)throw new InvalidOperationException("activation-record-missing");
return record;
}
throw new InvalidOperationException("operation");
}
@ -206,6 +218,33 @@ internal static class Program
}
}
private static async Task<JsonObject?> ReleaseRecord(string? identifier=null)
{
if(await Scalar("SELECT OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U')") is DBNull)return null;
using var read=Command("SELECT TOP(1) DeploymentIdentifier,ReleaseIdentifier,ApplicationVersion,SourceCommit,PackageSha256,MigrationManifestSha256,ActivatedUtc,ActivationKind FROM dbo.ApplicationReleaseHistory WHERE (@id IS NULL OR DeploymentIdentifier=@id) ORDER BY ActivatedUtc DESC");
read.Parameters.Add("@id",System.Data.SqlDbType.VarChar,100).Value=identifier is null?DBNull.Value:identifier;
using var reader=await read.ExecuteReaderAsync();
if(!await reader.ReadAsync())return null;
return new JsonObject { ["recorded"]=true,["deployment_identifier"]=reader.GetString(0),["release_identifier"]=reader.GetString(1),
["application_version"]=reader.GetString(2),["source_commit"]=reader.GetString(3),["package_sha256"]=reader.GetString(4),
["manifest_sha256"]=reader.GetString(5),["activated_utc"]=DateTime.SpecifyKind(reader.GetDateTime(6),DateTimeKind.Utc).ToString("O"),
["activation_kind"]=reader.GetString(7)};
}
private static async Task<object> HistoryStatus()
{
var expected=manifest!["migrations"]!.AsArray().Count;
if(await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull)
return new {expected,recorded=0,baselined=0,executed=0};
int recorded,baselineCount,executedCount;
using(var command=Command("SELECT COUNT(*),COALESCE(SUM(CASE WHEN RecordingKind='Baselined' THEN 1 ELSE 0 END),0),COALESCE(SUM(CASE WHEN RecordingKind='Executed' THEN 1 ELSE 0 END),0) FROM dbo.DatabaseMigrationHistory"))
using(var reader=await command.ExecuteReaderAsync())
{await reader.ReadAsync();recorded=reader.GetInt32(0);baselineCount=reader.GetInt32(1);executedCount=reader.GetInt32(2);}
var latest=await ReleaseRecord();
var releaseCount=await Scalar("IF OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U') IS NOT NULL SELECT COUNT(*) FROM dbo.ApplicationReleaseHistory ELSE SELECT 0");
return new {expected,recorded,baselined=baselineCount,executed=executedCount,successful_release_count=Convert.ToInt32(releaseCount),latest_successful_release=latest};
}
private static async Task<bool> ValidateHistory()
{
if (await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull)
@ -290,6 +329,8 @@ internal static class Program
insert.Parameters.AddWithValue("@evidence",baseline ? S(migration,"evidence") : DBNull.Value);
await insert.ExecuteNonQueryAsync();
await transaction.CommitAsync();
if(baseline)baselined++;else executed++;
committed.Add(identity);
currentMigration=null;
currentBatch=0;
}

View File

@ -44,3 +44,13 @@ On a disposable isolated clone only, a separately recorded short-lived entitleme
fixture may enable that test. Remove it in finally, never change original entitlement
rows, and compare all original business-column fingerprints afterwards. Do not
disable the subscription trigger or use a Production database as the fixture.
Compressed transport and machine receipts are implemented in transport.py,
receipt.py and deploy.py. See Docs/Deployment/Transport-20261125.md for measured
qualification and installation status, and Production.md for the operational
protocol. deploy.py defaults to validate-only; --activate is an explicit separately
authorised action. Existing raw signed releases remain supported. New compression
and receipt operations require the matching qualified server tooling; do not send
a compressed bundle to an old dispatcher. No routine bespoke Markdown report is
required: report the JSON/text receipt summary and any exceptional failures.

View File

@ -14,10 +14,15 @@ import sys
import tempfile
import time
import uuid
import math
import re
from contextlib import nullcontext
from receipt import Receipt, summary, sanitized
from release import Refused, canonical, file_digest, keys, load, require, safe_name, verify_bundle
CONFIG = Path('/etc/plotdirector-deployment/target.json')
RECEIPT_DIRECTORY = Path('/srv/plotdirector/deployment-receipts')
SAFE_ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LANG': 'C.UTF-8', 'HOME': '/nonexistent', 'DOTNET_NOLOGO': '1'}
@ -58,6 +63,7 @@ class Worker:
self.process = subprocess.Popen(['/usr/bin/dotnet', config['worker'], config['database_config']],
env=SAFE_ENV, cwd='/', user=user.pw_uid, group=user.pw_gid, extra_groups=[],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
self.last_error = None
self.read()
def read(self):
@ -66,6 +72,13 @@ class Worker:
line = self.process.stdout.readline(65537)
require(bool(line) and len(line) <= 65536, 'Database worker unavailable')
answer = json.loads(line)
if not answer.get('ok'):
# SQL workers emit codes, never exception text. Reject accidental secret-bearing diagnostics.
if not isinstance(answer.get('error'),str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,80}',answer['error']):
answer={'ok':False,'error':'invalid-worker-error','migration':None,'batch':0}
if answer.get('migration') is not None and not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,199}',str(answer['migration'])):
answer['migration']=None
self.last_error = answer
require(answer.get('ok'), 'Database operation refused: ' + str(answer.get('error', 'unknown'))
+ ' migration=' + str(answer.get('migration', 'none')) + ' batch=' + str(answer.get('batch', 0)))
return answer.get('result', answer)
@ -161,7 +174,7 @@ def switch(root, target, deployment):
os.close(fd)
def health(cfg, destination, manifest, worker):
def health(cfg, destination, manifest, worker, meter=None):
require(command(['/usr/bin/systemctl', 'is-active', cfg['service']]) == 'active', 'Service inactive')
for path in ('/', '/Account/Login'):
for attempt in range(20):
@ -186,108 +199,173 @@ def health(cfg, destination, manifest, worker):
and identity.get('sourceCommit') == manifest['source_commit'] and identity.get('database') == cfg['database'],
'Running application/database identity mismatch')
require(identity.get('environment') == cfg['environment'], 'Running application environment mismatch')
worker.call('health')
with meter.phase('postactivation_verification') if meter else nullcontext():
database = worker.call('health')
if meter and isinstance(database,dict) and 'history_verification_seconds' in database:
meter.component('migration_history_verification',database['history_verification_seconds'],'postactivation_verification')
application={k:identity[k] for k in ('healthy','version','sourceCommit','database','environment')}
return {'application':application,'database':database,'http_root':True,'http_login':True,'binary_identity':True}
def persist_receipt(cfg, meter):
directory=Path(cfg['root'])/'deployment-receipts'
protected(directory,directory=True)
gid=grp.getgrnam('plotdirector-deploy').gr_gid
require(directory.stat().st_gid==gid and not directory.stat().st_mode&0o007,'Unsafe receipt directory')
identifier=safe_name(meter.data['deployment_id'])
clean=sanitized(meter.data)
data=canonical(clean);require(len(data)<=1024**2,'Receipt exceeds safe size limit')
pending=directory/('.receipt-'+uuid.uuid4().hex)
with pending.open('xb') as stream:stream.write(data);stream.flush();os.fsync(stream.fileno())
os.chown(pending,0,gid);pending.chmod(0o640)
os.replace(pending,directory/(identifier+'.json'))
pending=directory/('.summary-'+uuid.uuid4().hex)
with pending.open('xb') as stream:stream.write((summary(clean)+'\n').encode());stream.flush();os.fsync(stream.fileno())
os.chown(pending,0,gid);pending.chmod(0o640);os.replace(pending,directory/(identifier+'.txt'))
def read_receipt(identifier):
require(os.geteuid()==0,'Restricted sudo invocation required')
identifier=safe_name(identifier)
directory=RECEIPT_DIRECTORY;protected(directory,directory=True)
path=directory/(identifier+'.json');protected(path,secret=True)
require(path.stat().st_size<=1024**2,'Oversized receipt')
value=load(path);require(value.get('format')==1 and value.get('deployment_id')==identifier,'Receipt identity mismatch')
print(canonical(value).decode(),end='')
def import_upload_metrics(source, work, meter):
try:
from release import snapshot
target=Path(work)/'upload-metrics.json'
snapshot(Path(source)/'transfer-metrics.json',target,16384)
data=load(target)
keys(data,('source','started_utc','completed_utc','bytes','seconds','mib_per_second'))
require(data['source']=='ssh-receiver-unprivileged','Unknown transfer provenance')
require(type(data['seconds']) in (int,float) and math.isfinite(data['seconds']) and 0<data['seconds']<7200,'Invalid upload timing')
require(type(data['bytes']) is int and 0<data['bytes']<=4*1024**3+65536,'Invalid upload byte count')
require(math.isfinite(data['bytes']/data['seconds']/1024**2),'Invalid throughput measurement')
# Receiver metrics are unprivileged telemetry, never authorisation inputs.
meter.data['transfer']={'source':data['source'],'bytes':data['bytes'],'seconds':data['seconds'],
'mib_per_second':data['bytes']/data['seconds']/1024**2}
except (OSError,ValueError,Refused,TypeError):
meter.data['warnings'].append('upload-metrics-unavailable; sender receipt may provide transfer measurements')
def activate(package_id, validate=False, rollback=False):
cfg = configuration()
root = Path(cfg['root'])
# A precreated protected lock file cannot be redirected by the transfer account.
lock_path = root / 'deployment.lock'
protected(lock_path, secret=True)
lock_fd = os.open(lock_path, os.O_RDWR | os.O_NOFOLLOW)
worker = None
evidence = None
stopped = False
safe_name(package_id)
meter=Receipt();deployment=time.strftime('%Y%m%dT%H%M%SZ',time.gmtime())+'-'+uuid.uuid4().hex[:12]
meter.data.update(deployment_id=deployment,operation='validate' if validate else 'rollback' if rollback else 'activate')
cfg=None;lock_fd=None;worker=None;evidence=None;stopped=False;status='failed';stop_started=None
try:
try:
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise Refused('Concurrent deployment')
safe_name(package_id)
incoming = Path(cfg['inbox']) / package_id / 'package.tar'
incoming_info = incoming.lstat()
require(stat.S_ISREG(incoming_info.st_mode) and incoming_info.st_nlink == 1, 'Unsafe incoming package')
require(shutil.disk_usage(root).free >= cfg['minimum_free_bytes'] + 4 * incoming_info.st_size,
'Insufficient snapshot/extraction/installation space')
with tempfile.TemporaryDirectory(prefix='.deployment-', dir=str(root)) as work:
os.chmod(work, 0o750)
os.chown(work, 0, grp.getgrnam(cfg['migration_account']).gr_gid)
manifest, authorization, payload = verify_bundle(Path(cfg['inbox']) / package_id, work, cfg['public_key'])
require(manifest['release_id'] == package_id, 'Package identifier mismatch')
size = sum(x.stat().st_size for x in payload.rglob('*') if x.is_file())
require(shutil.disk_usage(root).free >= cfg['minimum_free_bytes'] + 2 * size, 'Insufficient release/snapshot space')
for path in [payload, *payload.rglob('*')]:
os.chown(path, 0, grp.getgrnam(cfg['migration_account']).gr_gid)
path.chmod(0o750 if path.is_dir() else 0o640)
deployment = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '-' + uuid.uuid4().hex[:12]
evidence = Path(cfg['evidence']) / (deployment + '.jsonl')
def event(phase, **data):
cfg=configuration();root=Path(cfg['root'])
lock_path=root/'deployment.lock';protected(lock_path,secret=True)
lock_fd=os.open(lock_path,os.O_RDWR|os.O_NOFOLLOW)
try:fcntl.flock(lock_fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
except BlockingIOError:raise Refused('Concurrent deployment')
source=Path(cfg['inbox'])/package_id
incoming=source/('package.tar.zst' if (source/'transport.json').exists() else 'package.tar')
info=incoming.lstat();require(stat.S_ISREG(info.st_mode) and info.st_nlink==1,'Unsafe incoming package')
require(shutil.disk_usage(root).free>=cfg['minimum_free_bytes']+4*info.st_size,'Insufficient snapshot/extraction/installation space')
with tempfile.TemporaryDirectory(prefix='.deployment-',dir=str(root)) as work:
os.chmod(work,0o750);os.chown(work,0,grp.getgrnam(cfg['migration_account']).gr_gid)
manifest,authorization,payload=verify_bundle(source,work,cfg['public_key'],meter=meter)
require(manifest['release_id']==package_id,'Package identifier mismatch')
meter.data['release']={'id':package_id,'version':manifest['version'],'source_commit':manifest['source_commit'],
'package_sha256':authorization['package_sha256'],'manifest_sha256':authorization['manifest_sha256'],
'application_sha256':manifest['application_sha256'],'dll_sha256':manifest['files']['app/PlotLine.dll']}
import_upload_metrics(source,work,meter)
size=sum(x.stat().st_size for x in payload.rglob('*') if x.is_file())
require(shutil.disk_usage(root).free>=cfg['minimum_free_bytes']+2*size,'Insufficient release/snapshot space')
for path in [payload,*payload.rglob('*')]:
os.chown(path,0,grp.getgrnam(cfg['migration_account']).gr_gid);path.chmod(0o750 if path.is_dir() else 0o640)
evidence=Path(cfg['evidence'])/(deployment+'.jsonl')
meter.data['protected_evidence_reference']=str(evidence)
def event(phase,**data):
with evidence.open('a') as stream:
stream.write(canonical({'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'deployment': deployment, 'release': package_id, 'phase': phase, **data}).decode())
stream.flush()
os.fsync(stream.fileno())
event('validated', package_sha256=authorization['package_sha256'])
worker = Worker(cfg)
beginning = worker.call('begin', package_root=str(payload), deployment_id=deployment, package_sha256=authorization['package_sha256'])
if rollback:
require(beginning.get('complete') is True, 'Rollback requires all migration history already present; SQL changes are forbidden')
stream.write(canonical({'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'deployment':deployment,'release':package_id,'phase':phase,**data}).decode());stream.flush();os.fsync(stream.fileno())
event('validated',package_sha256=authorization['package_sha256'])
worker=Worker(cfg)
with meter.phase('database_state_verification'):
beginning=worker.call('begin',package_root=str(payload),deployment_id=deployment,package_sha256=authorization['package_sha256'])
meter.data['migration_history']=beginning
if 'history_verification_seconds' in beginning:
meter.component('migration_history_verification',beginning['history_verification_seconds'],'database_state_verification')
if rollback:require(beginning.get('complete') is True,'Rollback requires all migration history already present; SQL changes are forbidden')
active_file=root/'active-deployment.json'
marker=load(active_file) if active_file.exists() else None
if marker:
prior=safe_name(marker['release']);prior_manifest=root/'releases'/prior/'manifest.json'
meter.data['previous_release']={k:marker[k] for k in ('deployment','release','package_sha256') if k in marker}
if prior_manifest.exists():
pm=load(prior_manifest);meter.data['previous_release'].update(version=pm['version'],source_commit=pm['source_commit'])
else:meter.data['previous_release']=None
if validate:
event('validation-only')
print('VALIDATED ' + package_id + '; no backup, migrations or service operations performed')
event('validation-only');status='validated'
print('VALIDATED '+package_id+'; no backup, migrations or service operations performed')
return
backup_name = 'PlotLine-predeploy-' + deployment + '.bak'
backup = Path(cfg['backup']) / backup_name
database_bytes = beginning.get('database_bytes')
require(isinstance(database_bytes, int) and database_bytes > 0, 'Database size unavailable for backup-space check')
require(shutil.disk_usage(cfg['backup']).free >= cfg['minimum_free_bytes'] + 2 * database_bytes,
'Insufficient verified database-backup space')
require(not backup.exists() and not backup.is_symlink(), 'Backup path already exists')
backup=Path(cfg['backup'])/('PlotLine-predeploy-'+deployment+'.bak')
database_bytes=beginning.get('database_bytes')
require(isinstance(database_bytes,int) and database_bytes>0,'Database size unavailable for backup-space check')
require(shutil.disk_usage(cfg['backup']).free>=cfg['minimum_free_bytes']+2*database_bytes,'Insufficient verified database-backup space')
require(not backup.exists() and not backup.is_symlink(),'Backup path already exists')
event('backup-start')
worker.call('backup', path=str(backup))
require(backup.is_file() and backup.stat().st_size > 0, 'Verified backup file unavailable')
event('backup-verified', path=str(backup))
worker.call('idle')
command(['/usr/bin/systemctl', 'stop', cfg['service']])
stopped = True
require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'ActiveState', '--value']) == 'inactive', 'Service did not stop')
worker.call('idle')
event('migration-start')
worker.call('migrate')
with meter.phase('database_backup'):
backup_result=worker.call('backup',path=str(backup))
require(backup.is_file() and backup.stat().st_size>0,'Verified backup file unavailable')
meter.data['database_backup']={'path':str(backup),'verified':True,'options':['COPY_ONLY','CHECKSUM','VERIFYONLY']}
event('backup-verified',path=str(backup));worker.call('idle')
stop_started=time.monotonic()
with meter.phase('service_stop'):
command(['/usr/bin/systemctl','stop',cfg['service']]);stopped=True
require(command(['/usr/bin/systemctl','show',cfg['service'],'-p','ActiveState','--value'])=='inactive','Service did not stop')
stop_complete=time.monotonic()
worker.call('idle');event('migration-start')
with meter.phase('migration_execution'):migration=worker.call('migrate')
meter.data['migrations']=migration if isinstance(migration,dict) else {}
event('migration-complete')
destination = root / 'releases' / package_id
install(payload, destination, cfg['runtime_account'])
# Successful release history contains the predecessor SUCCESS, not merely
# the symlink target left by a failed activation.
active_file = root / 'active-deployment.json'
previous = load(active_file)['deployment'] if active_file.exists() else None
event('activation-start', previous_deployment=previous)
switch(root, destination / 'app', deployment)
command(['/usr/bin/systemctl', 'start', cfg['service']])
health(cfg, destination, manifest, worker)
destination=root/'releases'/package_id
with meter.phase('release_installation'):install(payload,destination,cfg['runtime_account'])
previous=marker['deployment'] if marker else None
event('activation-start',previous_deployment=previous)
with meter.phase('release_activation'):switch(root,destination/'app',deployment)
with meter.phase('service_start'):command(['/usr/bin/systemctl','start',cfg['service']])
meter.data['availability']={'service_stop_to_start_seconds':time.monotonic()-stop_complete,
'stop_request_to_start_command_complete_seconds':time.monotonic()-stop_started,
'definition':'Monotonic intervals include stop/start commands; observed public outage measured separately on Atlas.'}
with meter.phase('application_health_readiness'):checks=health(cfg,destination,manifest,worker,meter)
meter.data['checks']=checks;meter.data['availability']['stop_request_to_health_ready_seconds']=time.monotonic()-stop_started
meter.data['availability']['confirmed_inactive_to_health_ready_seconds']=time.monotonic()-stop_complete
event('health-passed')
worker.call('activated', evidence=str(evidence), kind='Rollback' if rollback else 'Deploy', previous_deployment=previous)
pending = root / ('.active-' + deployment)
pending.write_bytes(canonical({'deployment': deployment, 'release': package_id, 'package_sha256': authorization['package_sha256']}))
os.replace(pending, active_file)
event('successful')
stopped = False
print('ACTIVATED ' + package_id + ' deployment=' + deployment + ' evidence=' + str(evidence))
with meter.phase('postactivation_verification'):
record=worker.call('activated',evidence=str(evidence),kind='Rollback' if rollback else 'Deploy',previous_deployment=previous)
pending=root/('.active-'+deployment);pending.write_bytes(canonical({'deployment':deployment,'release':package_id,'package_sha256':authorization['package_sha256']}));os.replace(pending,active_file)
meter.data['release_history']=record;meter.data['checks']['activation']=True
event('successful');stopped=False;status='activated'
print('ACTIVATED '+package_id+' deployment='+deployment+' evidence='+str(evidence))
except Exception as error:
if stopped:
try:
command(['/usr/bin/systemctl', 'stop', cfg['service']])
except Exception:
pass
try:command(['/usr/bin/systemctl','stop',cfg['service']])
except Exception:pass
meter.data['failures'].append({'code':type(error).__name__,'service_stop_requested':stopped})
if worker is not None and getattr(worker,'last_error',None):
safe=worker.last_error
meter.data['worker_failure']={k:safe[k] for k in ('error','migration','batch','executed','baselined') if k in safe}
if evidence is not None:
with evidence.open('a') as stream:
stream.write(canonical({'phase': 'failed', 'error': str(error) if isinstance(error, Refused) else type(error).__name__,
'service_stop_requested': stopped, 'recovery': 'Operator review required; no automatic database rollback.'}).decode())
with evidence.open('a') as stream:stream.write(canonical({'phase':'failed','error':type(error).__name__,'service_stop_requested':stopped,'recovery':'Operator review required; no automatic database rollback.'}).decode())
raise
finally:
if worker is not None:
worker.close()
os.close(lock_fd)
if worker is not None:worker.close()
if lock_fd is not None:os.close(lock_fd)
with meter.phase('receipt_generation'):
meter.finish(status)
persist_receipt(cfg or {'root':'/srv/plotdirector'},meter)
meter.finish(status);persist_receipt(cfg or {'root':'/srv/plotdirector'},meter)
print('RECEIPT '+deployment)
def public_error(error):
return sanitized(str(error)) if isinstance(error,Refused) else type(error).__name__
def main():
@ -297,6 +375,8 @@ def main():
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(Refused('Deployment timeout')))
signal.alarm(7200)
args = sys.argv[1:]
if len(args)==2 and args[0]=='--receipt':
read_receipt(args[1]);return
validate = len(args) == 2 and args[0] == '--validate'
rollback = len(args) == 2 and args[0] == '--rollback'
require(len(args) == 1 or validate or rollback, 'Usage: deploy-plotdirector [--validate|--rollback] <release-id>')
@ -307,5 +387,5 @@ if __name__ == '__main__':
try:
main()
except Exception as error:
print('DEPLOYMENT REFUSED: ' + (str(error) if isinstance(error, Refused) else type(error).__name__))
print('DEPLOYMENT REFUSED: ' + public_error(error))
sys.exit(1)

View File

@ -3,10 +3,10 @@
exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 /usr/bin/python3 -I -c '
import sys
sys.path.insert(0, "/usr/local/lib/plotdirector-deployment")
from activate import main, Refused
from activate import main, public_error
try:
main()
except Exception as error:
print("DEPLOYMENT REFUSED: " + (str(error) if isinstance(error, Refused) else type(error).__name__))
print("DEPLOYMENT REFUSED: " + public_error(error))
sys.exit(1)
' "$@"

131
Tools/Deployment/deploy.py Normal file
View File

@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Measured Atlas release pipeline. Defaults to validation only; no general SSH commands."""
import argparse
from contextlib import nullcontext
import json
from pathlib import Path
import re
import subprocess
import threading
import time
import urllib.request
import urllib.error
import tempfile
from receipt import Receipt, summary, write_local
from release import Refused, require, load, verify_bundle
from transfer import transfer, ssh
def remote(identity, operation, release, meter):
phase='production_validation' if operation=='validate' else 'remote_activation'
with meter.phase(phase):
p=subprocess.run(ssh(identity,operation+' '+release),capture_output=True,text=True,timeout=7200)
# No raw stderr/SQL/configuration is copied into public receipts.
return_code=p.returncode
identifier=re.search(r'^RECEIPT ([A-Za-z0-9][A-Za-z0-9_.-]{0,99})$',p.stdout,re.M)
require(identifier is not None,'Server did not return a sanitized receipt; compatible tooling required')
with meter.phase('receipt_retrieval'):
p=subprocess.run(ssh(identity,'receipt '+identifier[1]),capture_output=True,text=True,timeout=30)
require(p.returncode==0 and len(p.stdout.encode())<=1024**2,'Receipt retrieval failed')
data=json.loads(p.stdout)
require(data.get('format')==1 and data.get('deployment_id')==identifier[1],'Receipt identity mismatch')
if return_code!=0 or data.get('status')!=('validated' if operation=='validate' else 'activated'):
meter.data['failed_server_operation']=data
raise Refused('Restricted operation failed; sanitized server receipt retained')
return data
def public_acceptance(meter):
with meter.phase('public_acceptance'):
result={}
for name,url in [('plotdirector','https://plotdirector.com/'),('catherine','https://catherinelynwood.com/')]:
with urllib.request.urlopen(url,timeout=20) as response:
require(response.status==200,'Public HTTPS acceptance failed');response.read()
result[name]={'status':200,'tls_verified':True}
return result
def run(args):
meter=Receipt('atlas-pipeline');receipt_path=Path(args.receipt).resolve()
receipt_path.parent.mkdir(parents=True,exist_ok=True,mode=0o700)
require(not receipt_path.exists() and not receipt_path.is_symlink(),'Receipt destination already exists')
done=threading.Event();observations=[];poller=None;status='failed'
try:
if args.source:
from release import prepare
require(all(getattr(args,k,None) for k in ['plan','sql','evidence','output','release_id','signing_key','scope_base']), 'Complete release preparation arguments required')
preparation_meter=Receipt('atlas-preparation')
with meter.phase('release_preparation'):
try:
args.compression='zstd';prepare(args,meter=preparation_meter)
finally:
meter.data['preparation']=preparation_meter.data
bundle=Path(args.output).resolve()
# Import only known typed timing rows from this actual preparation.
meter.data['preparation']=preparation_meter.data
else:bundle=Path(args.bundle).resolve()
with tempfile.TemporaryDirectory(prefix='pd-pipeline-check-',dir=receipt_path.parent) as work:
manifest,authorization,_=verify_bundle(bundle,work,args.public_key,meter=meter)
release=manifest['release_id']
meter.data['release']={'id':release,'source_commit':manifest['source_commit'],'version':manifest['version'],
'package_sha256':authorization['package_sha256'],'application_sha256':manifest['application_sha256'],
'dll_sha256':manifest['files']['app/PlotLine.dll']}
transfer(bundle,args.identity,meter=meter)
validated=remote(args.identity,'validate',release,meter)
require(validated['release']['package_sha256']==authorization['package_sha256'],'Server validated another package')
meter.data['server_validation']=validated
meter.data['previous_release']=validated.get('previous_release')
meter.data['migration_history']=validated.get('migration_history')
require(not args.activate or validated.get('migration_history',{}).get('complete') is True or args.allow_migrations,
'Pending migration history requires an explicitly approved --allow-migrations run')
if args.activate:
def poll():
while not done.is_set():
start=time.monotonic()
try:
with urllib.request.urlopen('https://plotdirector.com/Account/Login',timeout=4) as response:ok=response.status==200;response.read()
except Exception:ok=False
observations.append((start,ok));done.wait(.5)
poller=threading.Thread(target=poll,daemon=True);poller.start()
try:activated=remote(args.identity,'activate',release,meter)
finally:done.set();poller.join(timeout=5)
require(activated['release']['package_sha256']==authorization['package_sha256'],'Server activated another package')
meter.data['server_activation']=activated
for key in ['deployment_id','release_history','migrations','database_backup','checks','availability','previous_release']:
if key in activated:meter.data[key]=activated[key]
failed=[i for i,x in enumerate(observations) if not x[1]]
if failed:
recovered=next((x[0] for x in observations[failed[-1]+1:] if x[1]),None)
meter.data['observed_public_outage']={'seconds':None if recovered is None else recovered-observations[failed[0]][0],
'definition':'Measured failed HTTPS GET to next successful GET; 0.5s sampling plus request latency','recovery_observed':recovered is not None}
else:meter.data['observed_public_outage']={'seconds':None,'failed_samples':0,'definition':'No failed sample observed; zero downtime is not asserted'}
status='activated'
else:status='validated';meter.data['warnings'].append('Validation only; no activation, backup or migration performed')
if args.public_acceptance:meter.data['public_https']=public_acceptance(meter)
except Exception as error:
status='failed'
meter.data['failures'].append({'code':type(error).__name__,'recovery':'Review local receipt and protected server attempt evidence; no automatic retry/rollback'})
raise
finally:
done.set()
if poller:poller.join(timeout=5)
with meter.phase('receipt_generation'):
meter.finish(status);write_local(receipt_path,meter.data)
meter.finish(status);write_local(receipt_path,meter.data)
print(summary(meter.data))
return meter.data
def main():
parser=argparse.ArgumentParser(description=__doc__)
group=parser.add_mutually_exclusive_group(required=True)
group.add_argument('--bundle');group.add_argument('--source')
for field in ['identity','public-key','receipt']:parser.add_argument('--'+field,required=True)
for field in ['plan','sql','evidence','output','release-id','signing-key','scope-base']:parser.add_argument('--'+field)
parser.add_argument('--activate',action='store_true');parser.add_argument('--allow-migrations',action='store_true')
parser.add_argument('--public-acceptance',action='store_true');args=parser.parse_args()
try:run(args)
except (Refused,ValueError,OSError,subprocess.SubprocessError):raise SystemExit('Deployment pipeline refused; sanitized receipt retained')
if __name__=='__main__':main()

114
Tools/Deployment/receipt.py Normal file
View File

@ -0,0 +1,114 @@
"""Bounded, secret-free deployment receipts and monotonic phase accounting."""
from contextlib import contextmanager
from datetime import datetime, timezone
import json
import os
import tempfile
import re
from pathlib import Path
import time
FORMAT = 1
PHASES = ('release_preparation','production_validation','remote_activation','receipt_retrieval','scope_verification','build','packaging_signing','compression','transfer','decompression',
'package_validation','database_state_verification','migration_history_verification',
'database_backup','migration_execution','service_stop','release_installation','release_activation',
'service_start','application_health_readiness','postactivation_verification','public_acceptance','receipt_generation')
def utc():
return datetime.now(timezone.utc).isoformat(timespec='milliseconds')
class Receipt:
def __init__(self, origin='web1'):
self.started = time.monotonic()
self.stack = []
self.data = {'format':FORMAT,'origin':origin,'started_utc':utc(),'completed_utc':None,
'status':'in-progress','phases':[],'warnings':[],'failures':[],
'checks':{},'migrations':{'executed':None,'baselined':None},
'recovery':'No automatic database restore or application rollback. Review protected attempt evidence on failure.'}
@contextmanager
def phase(self, name):
if name not in PHASES:
raise ValueError('Unknown measured phase')
row={'name':name,'started_utc':utc(),'parent':self.stack[-1]['name'] if self.stack else None}
start=time.monotonic(); state={'name':name,'children':0.0}
self.stack.append(state)
try:
yield
row['outcome']='passed'
except BaseException:
row['outcome']='failed'
raise
finally:
self.stack.pop(); elapsed=time.monotonic()-start
row.update(completed_utc=utc(),seconds=round(elapsed,6),exclusive_seconds=round(max(0,elapsed-state['children']),6))
self.data['phases'].append(row)
if self.stack:self.stack[-1]['children']+=elapsed
def component(self, name, seconds, parent):
"""Import a measured child duration; do not invent cross-process timestamps."""
import math
if name not in PHASES or type(seconds) not in (float,int) or not math.isfinite(seconds):
raise ValueError('Invalid measured component')
row=next((x for x in reversed(self.data['phases']) if x['name']==parent),None)
if row is None or not 0<=seconds<=row['seconds']+.001:
raise ValueError('Component lies outside its measured parent')
self.data['phases'].append({'name':name,'parent':parent,'seconds':round(seconds,6),
'exclusive_seconds':round(seconds,6),'started_utc':None,'completed_utc':None,
'clock':'SQL worker Stopwatch; measured duration, UTC endpoints unavailable','outcome':'passed'})
row['exclusive_seconds']=round(max(0,row['exclusive_seconds']-seconds),6)
def finish(self, status):
self.data['status']=status
self.data['completed_utc']=utc()
total=time.monotonic()-self.started
accounted=sum(x['seconds'] for x in self.data['phases'] if x['parent'] is None)
self.data['timing']={'total_seconds':round(total,6),'measured_top_level_seconds':round(accounted,6),
'unattributed_seconds':round(max(0,total-accounted),6),
'clock':'monotonic; UTC timestamps for correlation only'}
performed={x['name'] for x in self.data['phases']}
for key in ('preparation','server_validation','server_activation','failed_server_operation'):
nested=self.data.get(key,{})
performed.update(x['name'] for x in nested.get('phases',[]))
self.data['unperformed_phases']=[n for n in PHASES if n not in performed]
return self.data
def sanitized(value):
"""Defence in depth; callers still collect only explicitly selected facts."""
if isinstance(value,dict):
return {k:sanitized(v) for k,v in value.items() if not re.search(
r'password|connection.?string|private.?key|api.?key|access.?token|refresh.?token|credential',k,re.I)}
if isinstance(value,list):return [sanitized(x) for x in value]
if isinstance(value,str) and re.search(r'(?:Password|Pwd|Server|Data Source|User ID|Initial Catalog)\s*=|Bearer\s+|-----BEGIN.*PRIVATE KEY|sk_(?:live|test)_|sk-proj-|whsec_',value,re.I):
return '[redacted]'
return value
def summary(data):
"""Render only known safe fields; never include diagnostics/configuration blobs."""
data=sanitized(data)
seconds=data.get('timing',{}).get('total_seconds',0)
release=data.get('release',{})
public=data.get('public_https')
public_result='passed' if public and all(x.get('status')==200 and x.get('tls_verified') for x in public.values()) else 'not-performed'
if any(x['name']=='public_acceptance' and x.get('outcome')=='failed' for x in data.get('phases',[])):public_result='failed'
return ('{status}: {release} v{version} source={source} total={seconds:.2f}s; '
'backup={backup}; migrations-executed={migrations}; public-https={public}; receipt={receipt}').format(
status=data.get('status','unknown'),release=release.get('id','unavailable'),version=release.get('version','unknown'),
source=release.get('source_commit','unavailable')[:12],seconds=seconds,
backup=data.get('database_backup',{}).get('verified','not-performed'),
migrations=data.get('migrations',{}).get('executed','not-performed'),public=public_result,
receipt=data.get('deployment_id','local'))
def write_local(path, data):
path=Path(path)
data=sanitized(data)
for target,body in [(path,json.dumps(data,indent=2)+'\n'),(path.with_suffix('.txt'),summary(data)+'\n')]:
with tempfile.NamedTemporaryFile(mode='w',dir=target.parent,prefix='.receipt-',delete=False) as stream:
temporary=Path(stream.name);stream.write(body);stream.flush();os.fsync(stream.fileno())
temporary.chmod(0o600);os.replace(temporary,target)

View File

@ -10,6 +10,11 @@ import stat
import subprocess
import tarfile
import tempfile
import sys
from contextlib import nullcontext
if __name__ == '__main__':
sys.modules.setdefault('release', sys.modules[__name__])
LIMIT_BYTES = 4 * 1024**3
LIMIT_FILES = 100000
@ -218,33 +223,67 @@ def snapshot(path, destination, max_bytes):
os.close(fd)
def verify_bundle(source, work, public_key):
def verify_bundle(source, work, public_key, meter=None):
source, work = Path(source), Path(work)
for name, limit in (('authorization.json', 16384), ('authorization.sig', 16384), ('package.tar', LIMIT_BYTES)):
snapshot(source / name, work / name, limit)
result = subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', str(public_key), '-rawin',
phase = meter.phase if meter else lambda name: nullcontext()
with phase('package_validation'):
for name in ('authorization.json', 'authorization.sig'):
snapshot(source / name, work / name, 16384)
result = subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', str(public_key), '-rawin',
'-in', str(work / 'authorization.json'), '-sigfile', str(work / 'authorization.sig')],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
require(result.returncode == 0, 'Release signature invalid')
authorization = load(work / 'authorization.json')
keys(authorization, ('format', 'release_id', 'source_commit', 'package_sha256', 'manifest_sha256'))
require(authorization['format'] == 1, 'Invalid authorization format')
safe_name(authorization['release_id'])
sha(authorization['package_sha256'])
sha(authorization['manifest_sha256'])
require(file_digest(work / 'package.tar') == authorization['package_sha256'], 'Package checksum mismatch')
payload = work / 'payload'
payload.mkdir(mode=0o700)
manifest = extract(work / 'package.tar', payload)
require(file_digest(payload / 'manifest.json') == authorization['manifest_sha256'], 'Manifest checksum mismatch')
require(manifest['release_id'] == authorization['release_id'] and manifest['source_commit'] == authorization['source_commit'], 'Authorization identity mismatch')
require(result.returncode == 0, 'Release signature invalid')
authorization = load(work / 'authorization.json')
keys(authorization, ('format', 'release_id', 'source_commit', 'package_sha256', 'manifest_sha256'))
require(authorization['format'] == 1, 'Invalid authorization format')
safe_name(authorization['release_id'])
sha(authorization['package_sha256'])
sha(authorization['manifest_sha256'])
compressed = (source / 'transport.json').exists() or (source / 'package.tar.zst').exists()
if compressed:
from transport import envelope
require(not (source / 'package.tar').exists(), 'Ambiguous raw/compressed bundle')
t = envelope(source, work, public_key)
require(t['original_sha256'] == authorization['package_sha256'] and
t['release_id'] == authorization['release_id'] and
t['source_commit'] == authorization['source_commit'], 'Transport identity mismatch')
else:
snapshot(source / 'package.tar', work / 'package.tar', LIMIT_BYTES)
size = (work / 'package.tar').stat().st_size
t = {'method':'none','original_bytes':size,'transferred_bytes':size,
'original_sha256':authorization['package_sha256'],'transferred_sha256':authorization['package_sha256']}
if meter:
meter.data['transport'] = {k:t[k] for k in ('method','original_bytes','transferred_bytes','original_sha256','transferred_sha256')}
meter.data['transport']['compression_ratio'] = round(t['transferred_bytes']/t['original_bytes'],6)
if compressed:
meter.data['transport']['compression_seconds_atlas'] = t['compression_seconds']
meter.data['transport']['settings'] = {'level':t['level'],'threads':t['threads']}
if compressed:
from transport import decompress
with phase('decompression'):
decompress(work,t)
with phase('package_validation'):
require(file_digest(work / 'package.tar') == authorization['package_sha256'], 'Package checksum mismatch')
payload = work / 'payload'
payload.mkdir(mode=0o700)
manifest = extract(work / 'package.tar', payload)
require(file_digest(payload / 'manifest.json') == authorization['manifest_sha256'], 'Manifest checksum mismatch')
require(manifest['release_id'] == authorization['release_id'] and manifest['source_commit'] == authorization['source_commit'], 'Authorization identity mismatch')
return manifest, authorization, payload
def prepare(args):
def prepare(args, meter=None):
from receipt import Receipt, write_local
meter = meter or Receipt('atlas-preparation')
repo = Path(args.source).resolve()
commit = subprocess.check_output(['git', '-C', str(repo), 'rev-parse', 'HEAD'], text=True).strip()
require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Source must be a clean Git commit')
with meter.phase('scope_verification'):
commit = subprocess.check_output(['git', '-C', str(repo), 'rev-parse', 'HEAD'], text=True).strip()
require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Source must be a clean Git commit')
if getattr(args, 'scope_base', None):
base = subprocess.check_output(['git','-C',str(repo),'rev-parse','--verify','--end-of-options',args.scope_base+'^{commit}'],text=True).strip()
require(COMMIT.fullmatch(base), 'Invalid scope baseline')
meter.data['scope'] = {'base':base,'source':commit,'changed_paths':subprocess.check_output(
['git','-C',str(repo),'diff','--name-only',base,commit],text=True).splitlines()}
require(COMMIT.fullmatch(commit), 'Invalid source commit')
plan = load(args.plan)
# The plan is reviewed data; paths are only read on Atlas, never trusted as remote targets.
@ -255,64 +294,80 @@ def prepare(args):
with tempfile.TemporaryDirectory(prefix='pd-release-', dir=str(output.parent)) as directory:
work = Path(directory)
publish = work / 'publish'
subprocess.run(['dotnet', 'publish', str(repo / 'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish),
with meter.phase('build'):
subprocess.run(['dotnet', 'publish', str(repo / 'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish),
'-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId=' + commit], check=True,
stdout=(output / 'publish.log').open('w'), stderr=subprocess.STDOUT)
require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Build changed tracked source')
files = {}
sources = {}
for path in sorted(publish.rglob('*')):
require(not path.is_symlink(), 'Publish contains symlink')
if not path.is_file():
continue
rel = path.relative_to(publish)
if any(p.startswith('.') or p in ('App_Data', 'uploads', 'logs', 'Logs') for p in rel.parts):
continue
if (path.name.startswith('appsettings') and path.suffix == '.json') or path.name in ('web.config', 'dotnet-tools.json'):
continue
name = 'app/' + rel.as_posix()
files[name] = file_digest(path)
sources[name] = path
for migration in plan['migrations']:
filename = str(safe_path(migration['file']))
require('/' not in filename, 'Invalid SQL source name')
# Historical non-numeric release SQL may be staged separately in the reviewed SQL input directory.
path = Path(args.sql) / filename
require(path.is_file() and not path.is_symlink() and file_digest(path) == migration['sha256'], 'SQL source differs from reviewed plan')
name = 'sql/' + filename
files[name] = migration['sha256']
sources[name] = path
for path in sorted(Path(args.evidence).rglob('*')):
require(not path.is_symlink(), 'Evidence symlink')
if path.is_file():
name = 'evidence/' + path.relative_to(args.evidence).as_posix()
safe_path(name)
with meter.phase('packaging_signing'):
require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Build changed tracked source')
files = {}
sources = {}
for path in sorted(publish.rglob('*')):
require(not path.is_symlink(), 'Publish contains symlink')
if not path.is_file():
continue
rel = path.relative_to(publish)
if any(p.startswith('.') or p in ('App_Data', 'uploads', 'logs', 'Logs') for p in rel.parts):
continue
if (path.name.startswith('appsettings') and path.suffix == '.json') or path.name in ('web.config', 'dotnet-tools.json'):
continue
name = 'app/' + rel.as_posix()
files[name] = file_digest(path)
sources[name] = path
deps = load(publish / 'PlotLine.deps.json')
versions = [x[9:] for x in deps['libraries'] if x.startswith('PlotLine/')]
require(len(versions) == 1, 'Application identity unavailable')
manifest = {'format': 1, 'release_id': safe_name(args.release_id), 'source_commit': commit, 'version': versions[0],
'files': files, 'application_sha256': digest(canonical({k:v for k,v in files.items() if k.startswith('app/')})),
'health': ['http-root', 'http-login', 'http-deployment-identity', 'database-postconditions', 'binary-identity'], **plan}
validate_manifest(manifest)
qualification_identity(manifest, load(Path(args.evidence) / PurePosixPath(plan['qualification']['evidence']).relative_to('evidence')))
manifest_bytes = canonical(manifest)
(work / 'manifest.json').write_bytes(manifest_bytes)
sources['manifest.json'] = work / 'manifest.json'
with tarfile.open(output / 'package.tar', 'w', format=tarfile.USTAR_FORMAT) as tar:
for name, path in sorted(sources.items()):
entry = tarfile.TarInfo(name)
entry.size = path.stat().st_size
entry.mode = 0o644
with path.open('rb') as stream:
tar.addfile(entry, stream)
authorization = {'format': 1, 'release_id': args.release_id, 'source_commit': commit,
'package_sha256': file_digest(output / 'package.tar'), 'manifest_sha256': digest(manifest_bytes)}
(output / 'authorization.json').write_bytes(canonical(authorization))
subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-sign', '-inkey', args.signing_key, '-rawin',
'-in', str(output / 'authorization.json'), '-out', str(output / 'authorization.sig')], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for migration in plan['migrations']:
filename = str(safe_path(migration['file']))
require('/' not in filename, 'Invalid SQL source name')
# Historical non-numeric release SQL may be staged separately in the reviewed SQL input directory.
path = Path(args.sql) / filename
require(path.is_file() and not path.is_symlink() and file_digest(path) == migration['sha256'], 'SQL source differs from reviewed plan')
name = 'sql/' + filename
files[name] = migration['sha256']
sources[name] = path
for path in sorted(Path(args.evidence).rglob('*')):
require(not path.is_symlink(), 'Evidence symlink')
if path.is_file():
name = 'evidence/' + path.relative_to(args.evidence).as_posix()
safe_path(name)
files[name] = file_digest(path)
sources[name] = path
deps = load(publish / 'PlotLine.deps.json')
versions = [x[9:] for x in deps['libraries'] if x.startswith('PlotLine/')]
require(len(versions) == 1, 'Application identity unavailable')
manifest = {'format': 1, 'release_id': safe_name(args.release_id), 'source_commit': commit, 'version': versions[0],
'files': files, 'application_sha256': digest(canonical({k:v for k,v in files.items() if k.startswith('app/')})),
'health': ['http-root', 'http-login', 'http-deployment-identity', 'database-postconditions', 'binary-identity'], **plan}
validate_manifest(manifest)
qualification_identity(manifest, load(Path(args.evidence) / PurePosixPath(plan['qualification']['evidence']).relative_to('evidence')))
manifest_bytes = canonical(manifest)
(work / 'manifest.json').write_bytes(manifest_bytes)
sources['manifest.json'] = work / 'manifest.json'
with tarfile.open(output / 'package.tar', 'w', format=tarfile.USTAR_FORMAT) as tar:
for name, path in sorted(sources.items()):
entry = tarfile.TarInfo(name)
entry.size = path.stat().st_size
entry.mode = 0o644
with path.open('rb') as stream:
tar.addfile(entry, stream)
authorization = {'format': 1, 'release_id': args.release_id, 'source_commit': commit,
'package_sha256': file_digest(output / 'package.tar'), 'manifest_sha256': digest(manifest_bytes)}
(output / 'authorization.json').write_bytes(canonical(authorization))
subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-sign', '-inkey', args.signing_key, '-rawin',
'-in', str(output / 'authorization.json'), '-out', str(output / 'authorization.sig')], check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
meter.data['release'] = {'id':args.release_id,'source_commit':commit,'version':manifest['version'],
'package_sha256':authorization['package_sha256'],'application_sha256':manifest['application_sha256']}
if getattr(args, 'compression', 'none') == 'zstd':
from transport import compress_bundle
with meter.phase('compression'):
transport = compress_bundle(output,work/'transport',args.signing_key,None,verified=True)
for name in ('transport.json','transport.sig','package.tar.zst'):
(work/'transport'/name).rename(output/name)
(output/'package.tar').unlink() # Only this operation's newly built temporary tar.
meter.data['transport'] = transport
with meter.phase('receipt_generation'):
meter.finish('prepared')
write_local(output/'preparation-receipt.json',meter.data)
meter.finish('prepared');write_local(output/'preparation-receipt.json',meter.data)
print(json.dumps(authorization, sort_keys=True))
@ -322,6 +377,10 @@ def main():
p = sub.add_parser('prepare')
for field in ('source', 'plan', 'sql', 'evidence', 'output', 'release-id', 'signing-key'):
p.add_argument('--' + field, required=True)
p.add_argument('--compression',choices=('zstd','none'),default='zstd')
p.add_argument('--scope-base')
c = sub.add_parser('compress',help='Wrap an unchanged existing signed tar; no application build')
for field in ('bundle','output','signing-key','public-key'):c.add_argument('--'+field,required=True)
v = sub.add_parser('verify')
v.add_argument('bundle')
v.add_argument('--public-key', required=True)
@ -330,6 +389,9 @@ def main():
try:
if args.command == 'prepare':
prepare(args)
elif args.command == 'compress':
from transport import compress_bundle
print(json.dumps(compress_bundle(args.bundle,args.output,args.signing_key,args.public_key),sort_keys=True))
else:
with tempfile.TemporaryDirectory(prefix='pd-verify-') as work:
m, a, _ = verify_bundle(Path(args.bundle).resolve(), work, args.public_key)

View File

@ -11,6 +11,9 @@ import resource
import signal
import shutil
import stat
import time
import json
from datetime import datetime, timezone
INBOX=Path('/srv/plotdirector/incoming')
LIMIT=4*1024**3
@ -22,7 +25,7 @@ def main():
os.umask(0o077)
# sshd ForceCommand passes the requested text as data, never to a shell here.
original=os.environ.get('SSH_ORIGINAL_COMMAND','')
match=re.fullmatch(r'(upload|validate|activate|rollback) ([A-Za-z0-9][A-Za-z0-9_.-]{0,99})',original)
match=re.fullmatch(r'(upload|validate|activate|rollback|receipt) ([A-Za-z0-9][A-Za-z0-9_.-]{0,99})',original)
if not match or match[2] in ('.','..'):
raise ValueError('Unsupported deployment operation')
operation,release=match.groups()
@ -30,6 +33,7 @@ def main():
args=['/usr/bin/sudo','-n','/usr/local/sbin/deploy-plotdirector']
if operation=='validate':args.append('--validate')
if operation=='rollback':args.append('--rollback')
if operation=='receipt':args.append('--receipt')
args.append(release)
raise SystemExit(subprocess.run(args,env={'PATH':'/usr/sbin:/usr/bin:/sbin:/bin','LANG':'C.UTF-8'},cwd='/').returncode)
# These limits apply only to unprivileged transfer, never to the activation
@ -46,24 +50,30 @@ def main():
if shutil.disk_usage(INBOX).free<FREE_FLOOR+LIMIT:raise ValueError('Insufficient staging space')
destination=INBOX/release
destination.mkdir(mode=0o700) # Refuses replacement, including symlinks.
started=time.monotonic()
started_utc=datetime.now(timezone.utc).isoformat()
received=set()
total=0
with tarfile.open(fileobj=sys.stdin.buffer,mode='r|') as tar:
for member in tar:
if member.name not in ('package.tar','authorization.json','authorization.sig') or member.name in received or not member.isfile() or member.linkname or member.pax_headers:
if member.name not in ('package.tar','package.tar.zst','authorization.json','authorization.sig','transport.json','transport.sig') or member.name in received or not member.isfile() or member.linkname or member.pax_headers:
raise ValueError('Invalid transfer member')
received.add(member.name)
limit=LIMIT if member.name=='package.tar' else 16384
if member.name in ('package.tar','package.tar.zst') and received & ({'package.tar','package.tar.zst'}-{member.name}):
raise ValueError('Ambiguous transport')
limit=LIMIT if member.name in ('package.tar','package.tar.zst') else 16384
if not 0<=member.size<=limit:raise ValueError('Transfer size exceeded')
total+=member.size
if total>LIMIT+32768:raise ValueError('Transfer size exceeded')
if total>LIMIT+65536:raise ValueError('Transfer size exceeded')
with tar.extractfile(member) as source,(destination/member.name).open('xb') as target:
while block:=source.read(1024**2):
if shutil.disk_usage(INBOX).free<FREE_FLOOR+len(block):raise ValueError('Staging space floor reached')
target.write(block)
target.flush();os.fsync(target.fileno())
if received!={'package.tar','authorization.json','authorization.sig'}:
if received not in ({'package.tar','authorization.json','authorization.sig'},{'package.tar.zst','authorization.json','authorization.sig','transport.json','transport.sig'}):
raise ValueError('Incomplete transfer; administrator must remove the incomplete incoming directory before retry')
elapsed=time.monotonic()-started
(destination/'transfer-metrics.json').write_text(json.dumps({'source':'ssh-receiver-unprivileged','started_utc':started_utc,'completed_utc':datetime.now(timezone.utc).isoformat(),'bytes':total,'seconds':elapsed,'mib_per_second':total/elapsed/1024**2}))
print('UPLOADED '+release+'; activation has not been performed')

View File

@ -1,5 +1,6 @@
import hashlib
import os
import copy
import json
from pathlib import Path
import tempfile
@ -36,12 +37,12 @@ class ActivationFailureTests(unittest.TestCase):
(self.root/'deployment.lock').write_bytes(b'')
(self.root/'current').symlink_to(self.root/'releases/old-release/app')
(self.root/'releases/old-release/app').mkdir(parents=True)
(self.root/'active-deployment.json').write_text('{"deployment":"previous-success"}')
(self.root/'active-deployment.json').write_text('{"deployment":"previous-success","release":"old-release","package_sha256":"'+('b'*64)+'"}')
self.cfg={'root':str(self.root),'inbox':str(self.root/'inbox'),'evidence':str(self.root/'evidence'),
'backup':str(self.root/'backup'),'runtime_account':'root','migration_account':'root',
'public_key':'not-used','minimum_free_bytes':1,'service':'plotdirector-qualification.service',
'health_base':'http://127.0.0.1:5999','database':'PlotLine','environment':'Production'}
self.calls=[];self.state='active';self.failure=None;self.status='200';self.complete=False;self.activations=[]
self.receipts=[];self.calls=[];self.state='active';self.failure=None;self.status='200';self.complete=False;self.activations=[]
outer=self
class FakeWorker:
def __init__(self,cfg):outer.calls.append('worker-open')
@ -51,17 +52,18 @@ class ActivationFailureTests(unittest.TestCase):
if op=='backup':Path(values['path']).write_bytes(b'verified-fixture')
if op=='begin':return {'complete':outer.complete,'database_bytes':1024}
if op=='activated':outer.activations.append(values)
if op=='migrate':return {'executed':0,'baselined':0,'committed':[]}
return {}
def close(self):outer.calls.append('worker-close')
self.FakeWorker=FakeWorker
def tearDown(self):self.temp.cleanup()
def bundle(self,source,work,key):
def bundle(self,source,work,key,meter=None):
payload=Path(work)/'payload';(payload/'app').mkdir(parents=True)
(payload/'app/PlotLine.dll').write_bytes(b'qualified-fixture')
(payload/'manifest.json').write_bytes(b'{}')
return {'release_id':'new-release','version':'1.0.0','source_commit':'a'*40,'files':{'app/PlotLine.dll':hashlib.sha256(b'qualified-fixture').hexdigest()}}, {'package_sha256':'a'*64},payload
return {'application_sha256':'c'*64,'release_id':'new-release','version':'1.0.0','source_commit':'a'*40,'files':{'app/PlotLine.dll':hashlib.sha256(b'qualified-fixture').hexdigest()}}, {'package_sha256':'a'*64,'manifest_sha256':'d'*64},payload
def command(self,args,**kwargs):
if args[0].endswith('systemctl'):
@ -80,6 +82,7 @@ class ActivationFailureTests(unittest.TestCase):
with patch.object(activate,'configuration',return_value=self.cfg),patch.object(activate,'protected'),\
patch.object(activate,'verify_bundle',side_effect=self.bundle),patch.object(activate,'Worker',self.FakeWorker),\
patch.object(activate,'command',side_effect=self.command),patch.object(activate.os,'chown'),\
patch.object(activate,'persist_receipt',side_effect=lambda cfg,meter:self.receipts.append(copy.deepcopy(meter.data))),\
patch.object(activate.time,'sleep'),patch.object(activate.shutil,'disk_usage',return_value=SimpleNamespace(free=free)):
activate.activate('new-release',validate,rollback)

View File

@ -0,0 +1,81 @@
import argparse
import copy
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import deploy
import test_transport
from release import Refused
class PipelineTests(unittest.TestCase):
def setUp(self):
self.fixture=test_transport.CompressedTransportTests();self.fixture.setUp();self.root=self.fixture.root
self.args=argparse.Namespace(bundle=str(self.fixture.compressed),source=None,identity='test-key',public_key=str(self.fixture.pub),
receipt=str(self.root/'operation.json'),activate=False,allow_migrations=False,public_acceptance=False)
self.calls=[];self.complete=True
def tearDown(self):self.fixture.tearDown()
def remote(self,identity,operation,release,meter):
self.calls.append(operation)
with meter.phase('production_validation' if operation=='validate' else 'remote_activation'):pass
a=json.loads((self.fixture.bundle/'authorization.json').read_text())
return {'format':1,'status':'validated' if operation=='validate' else 'activated','deployment_id':'test-attempt',
'release':{'id':release,'source_commit':'a'*40,'package_sha256':a['package_sha256']},
'migration_history':{'complete':self.complete},'migrations':{'executed':0},'checks':{'activation':operation!='validate'}}
def execute(self,**patches):
class Response:
status=200
def __enter__(self):return self
def __exit__(self,*x):pass
def read(self):return b''
with patch.object(deploy,'transfer',**({'side_effect':patches['transfer_error']} if 'transfer_error' in patches else {'return_value':{'seconds':1}})),\
patch.object(deploy,'remote',side_effect=self.remote),patch.object(deploy.urllib.request,'urlopen',return_value=Response()):
return deploy.run(self.args)
def test_default_validation_does_not_activate(self):
d=self.execute();self.assertEqual(self.calls,['validate']);self.assertEqual(d['status'],'validated')
self.assertNotIn('server_activation',d)
self.assertTrue(Path(self.args.receipt).with_suffix('.txt').exists())
def test_pending_history_requires_explicit_authorised_migration_flag(self):
self.complete=False;self.args.activate=True
with self.assertRaises(Refused):self.execute()
self.assertEqual(self.calls,['validate'])
self.assertEqual(json.loads(Path(self.args.receipt).read_text())['status'],'failed')
def test_activation_receipt_contains_actual_server_result(self):
self.args.activate=True;d=self.execute()
self.assertEqual(self.calls,['validate','activate']);self.assertEqual(d['status'],'activated')
self.assertEqual(d['migrations']['executed'],0)
self.assertTrue(d['server_activation']['checks']['activation'])
def test_failed_transfer_never_calls_server_and_redacts_exception(self):
with self.assertRaises(ValueError):self.execute(transfer_error=ValueError('Password=do-not-record'))
self.assertEqual(self.calls,[]);s=Path(self.args.receipt).read_text()
self.assertNotIn('do-not-record',s);self.assertEqual(json.loads(s)['status'],'failed')
def test_public_failure_does_not_claim_success_or_rollback_activated_app(self):
self.args.activate=True;self.args.public_acceptance=True
with patch.object(deploy,'public_acceptance',side_effect=ValueError('Bearer secret-never-copy')):
with self.assertRaises(ValueError):self.execute()
d=json.loads(Path(self.args.receipt).read_text());self.assertEqual(d['status'],'failed')
self.assertEqual(d['server_activation']['status'],'activated');self.assertNotIn('secret-never-copy',json.dumps(d))
self.assertEqual(self.calls,['validate','activate'])
def test_failed_remote_receipt_is_retrieved_without_exposing_raw_output(self):
meter=deploy.Receipt()
failed={'format':1,'status':'failed','deployment_id':'failed-1','failures':[{'code':'Refused'}]}
responses=[type('P',(),{'returncode':1,'stdout':'RECEIPT failed-1\n','stderr':'Password=never-echo'})(),
type('P',(),{'returncode':0,'stdout':json.dumps(failed),'stderr':''})()]
with patch.object(deploy.subprocess,'run',side_effect=responses):
with self.assertRaises(Refused):deploy.remote('key','activate','fixture-release',meter)
self.assertEqual(meter.data['failed_server_operation']['status'],'failed')
self.assertNotIn('never-echo',json.dumps(meter.data))
if __name__=='__main__':unittest.main()

View File

@ -0,0 +1,95 @@
import copy
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import activate
import receipt
from release import Refused
import test_activation
class TimingTests(unittest.TestCase):
def test_nested_monotonic_timing_and_overhead_account_for_total(self):
with patch.object(receipt.time,'monotonic',side_effect=[0,1,2,4,6,7]):
meter=receipt.Receipt('test')
with meter.phase('application_health_readiness'):
with meter.phase('postactivation_verification'):pass
d=meter.finish('validated')
self.assertEqual(d['timing']['total_seconds'],7)
self.assertEqual(d['timing']['measured_top_level_seconds'],5)
self.assertEqual(d['timing']['unattributed_seconds'],2)
outer=next(x for x in d['phases'] if x['name']=='application_health_readiness')
self.assertEqual(outer['exclusive_seconds'],3)
self.assertEqual(outer['seconds'],5)
def test_failed_phase_is_recorded_without_secret_exception_text(self):
m=receipt.Receipt()
with self.assertRaises(RuntimeError):
with m.phase('decompression'):raise RuntimeError('Password=never-copy-this; Server=private')
d=m.finish('failed');self.assertEqual(d['phases'][0]['outcome'],'failed')
self.assertNotIn('never-copy-this',json.dumps(d))
def test_summary_and_json_are_generated_from_same_safe_data(self):
m=receipt.Receipt();m.data.update(release={'id':'safe-release','source_commit':'a'*40},deployment_id='attempt-1')
d=m.finish('validated')
with tempfile.TemporaryDirectory() as directory:
p=Path(directory)/'receipt.json';receipt.write_local(p,d)
self.assertEqual(json.loads(p.read_text()),d)
self.assertEqual(p.with_suffix('.txt').read_text().strip(),receipt.summary(d))
self.assertEqual(p.stat().st_mode&0o777,0o600)
def test_defence_in_depth_redacts_accidental_secret_fields_and_values(self):
data={'status':'failed','password':'hidden','connectionString':'Server=private;Password=hidden',
'diagnostic':'Bearer hidden-token','nested':{'private_key':'hidden','count':3}}
clean=receipt.sanitized(data)
self.assertNotIn('hidden',json.dumps(clean));self.assertEqual(clean['nested']['count'],3)
self.assertEqual(clean['diagnostic'],'[redacted]')
def test_worker_component_is_measured_not_timestamp_estimated(self):
meter=receipt.Receipt()
meter.data['phases']=[{'name':'database_state_verification','parent':None,'seconds':4,'exclusive_seconds':4}]
meter.component('migration_history_verification',1.25,'database_state_verification')
self.assertEqual(meter.data['phases'][0]['exclusive_seconds'],2.75)
self.assertIsNone(meter.data['phases'][1]['started_utc'])
with self.assertRaises(ValueError):meter.component('migration_history_verification',9,'database_state_verification')
class ReceiptActivationTests(unittest.TestCase):
def setUp(self):self.fixture=test_activation.ActivationFailureTests();self.fixture.setUp()
def tearDown(self):self.fixture.tearDown()
def test_validation_receipt_cannot_claim_activation_backup_or_migrations(self):
self.fixture.run_activation(validate=True);d=self.fixture.receipts[-1]
self.assertEqual(d['status'],'validated');self.assertNotIn('database_backup',d)
self.assertNotIn('activation',d['checks']);self.assertIsNone(d['migrations']['executed'])
def test_success_has_backup_health_phase_and_zero_code_only_migrations(self):
self.fixture.run_activation();d=self.fixture.receipts[-1]
self.assertEqual(d['status'],'activated');self.assertTrue(d['database_backup']['verified'])
self.assertTrue(d['checks']['activation']);self.assertEqual(d['migrations']['executed'],0)
names={x['name'] for x in d['phases']}
for n in ['database_backup','migration_execution','service_stop','release_activation','service_start','application_health_readiness','postactivation_verification','receipt_generation']:self.assertIn(n,names)
self.assertGreaterEqual(d['availability']['confirmed_inactive_to_health_ready_seconds'],d['availability']['service_stop_to_start_seconds'])
def test_failed_migration_keeps_failure_receipt_and_no_activation_record(self):
self.fixture.failure='migrate'
with self.assertRaises(Refused):self.fixture.run_activation()
d=self.fixture.receipts[-1];self.assertEqual(d['status'],'failed')
self.assertEqual(self.fixture.state,'inactive');self.assertFalse(self.fixture.activations)
def test_secret_error_is_not_written_into_receipt_or_protected_attempt_log(self):
with patch.object(activate,'install',side_effect=Refused('Password=secret-example')):
with self.assertRaises(Refused):self.fixture.run_activation()
self.assertNotIn('secret-example',json.dumps(self.fixture.receipts[-1]))
for p in (self.fixture.root/'evidence').glob('*.jsonl'):self.assertNotIn('secret-example',p.read_text())
def test_receipt_read_rejects_paths_before_file_access(self):
for name in ['../target','/etc/passwd','..','valid/other','x; id']:
with patch.object(activate.os,'geteuid',return_value=0):
with self.assertRaises(Refused):activate.read_receipt(name)
if __name__=='__main__':unittest.main()

View File

@ -0,0 +1,109 @@
import copy
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from unittest.mock import patch
import release
import transport
from receipt import Receipt
import test_release
class CompressedTransportTests(unittest.TestCase):
def setUp(self):
self.fixture=test_release.ReleaseBoundaryTests();self.fixture.setUp();self.root=self.fixture.root
self.bundle=self.root/'legacy';self.bundle.mkdir()
shutil.copyfile(self.fixture.archive(),self.bundle/'package.tar')
self.key=self.root/'key.pem';self.pub=self.root/'pub.pem'
subprocess.run(['openssl','genpkey','-algorithm','ED25519','-out',str(self.key)],check=True,capture_output=True)
subprocess.run(['openssl','pkey','-in',str(self.key),'-pubout','-out',str(self.pub)],check=True,capture_output=True)
auth={'format':1,'release_id':'fixture-release','source_commit':self.fixture.commit,
'package_sha256':release.file_digest(self.bundle/'package.tar'),
'manifest_sha256':release.digest(release.canonical(self.fixture.manifest))}
(self.bundle/'authorization.json').write_bytes(release.canonical(auth));self.sign(self.bundle/'authorization.json',self.bundle/'authorization.sig')
self.compressed=self.root/'compressed'
transport.compress_bundle(self.bundle,self.compressed,self.key,self.pub)
def tearDown(self):self.fixture.tearDown()
def sign(self,path,signature):
subprocess.run(['openssl','pkeyutl','-sign','-inkey',str(self.key),'-rawin','-in',str(path),'-out',str(signature)],check=True,capture_output=True)
def verify(self,bundle=None):
with tempfile.TemporaryDirectory(dir=self.root) as d:
meter=Receipt('test')
return release.verify_bundle(bundle or self.compressed,d,self.pub,meter=meter),meter
def edit_transport(self,change):
p=self.compressed/'transport.json';data=json.loads(p.read_text());change(data);p.write_bytes(release.canonical(data));self.sign(p,self.compressed/'transport.sig')
def test_compressed_and_legacy_reconstruct_same_signed_manifest(self):
compressed,meter=self.verify();legacy,_=self.verify(self.bundle)
self.assertEqual(compressed[0],legacy[0]);self.assertEqual(compressed[1],legacy[1])
self.assertEqual(meter.data['transport']['method'],'zstd')
self.assertTrue(any(p['name']=='decompression' for p in meter.data['phases']))
self.assertEqual(release.file_digest(self.bundle/'package.tar'),compressed[1]['package_sha256'])
def test_corrupt_or_truncated_compressed_bytes_rejected_before_decoder(self):
file=self.compressed/'package.tar.zst';original=file.read_bytes()
for data in [original[:-4],b'changed'+original[7:]]:
file.write_bytes(data)
with patch.object(transport,'decompress') as decoder:
with self.assertRaises(release.Refused):self.verify()
decoder.assert_not_called()
file.write_bytes(original)
def test_invalid_original_signature_cannot_be_reauthorised_by_transport(self):
(self.compressed/'authorization.sig').write_bytes(b'invalid')
with self.assertRaises(release.Refused):self.verify()
def test_invalid_transport_signature_rejected(self):
(self.compressed/'transport.sig').write_bytes(b'invalid')
with self.assertRaises(release.Refused):self.verify()
def test_wrong_original_authorization_binding_rejected(self):
self.edit_transport(lambda t:t.update(authorization_sha256='0'*64))
with self.assertRaises(release.Refused):self.verify()
def test_signed_size_and_global_expansion_limits_enforced(self):
self.edit_transport(lambda t:t.update(original_bytes=release.LIMIT_BYTES+1))
with self.assertRaises(release.Refused):self.verify()
def test_output_beyond_signed_size_killed_and_partial_output_removed(self):
self.edit_transport(lambda t:t.update(original_bytes=512))
with tempfile.TemporaryDirectory(dir=self.root) as d:
with self.assertRaises(release.Refused):release.verify_bundle(self.compressed,d,self.pub)
self.assertFalse((Path(d)/'package.tar').exists())
def test_decoder_failure_on_signed_truncated_frame_is_not_accepted(self):
path=self.compressed/'package.tar.zst';path.write_bytes(path.read_bytes()[:-12])
self.edit_transport(lambda t:t.update(transferred_bytes=path.stat().st_size,transferred_sha256=release.file_digest(path)))
with self.assertRaises(release.Refused):self.verify()
def test_ambiguous_mixed_transport_rejected(self):
shutil.copyfile(self.bundle/'package.tar',self.compressed/'package.tar')
with self.assertRaises(release.Refused):self.verify()
def test_compressed_input_symlink_rejected(self):
p=self.compressed/'package.tar.zst';p.rename(self.root/'real.zst');p.symlink_to(self.root/'real.zst')
with self.assertRaises(OSError):self.verify()
def test_low_disk_space_prevents_decompression(self):
with patch.object(transport.shutil,'disk_usage',return_value=type('Space',(),{'free':1})()):
with self.assertRaises(release.Refused):self.verify()
def test_archive_traversal_still_rejected_after_valid_compression(self):
# Independently authorised malicious tar: extraction rules remain the gate.
shutil.copyfile(self.fixture.archive([('../escape',b'x')]),self.bundle/'package.tar')
auth=release.load(self.bundle/'authorization.json');auth['package_sha256']=release.file_digest(self.bundle/'package.tar')
(self.bundle/'authorization.json').write_bytes(release.canonical(auth));self.sign(self.bundle/'authorization.json',self.bundle/'authorization.sig')
evil=self.root/'evil';transport.compress_bundle(self.bundle,evil,self.key,self.pub,verified=True)
with self.assertRaises(release.Refused):self.verify(evil)
self.assertFalse((self.root/'escape').exists())
if __name__=='__main__':unittest.main()

View File

@ -0,0 +1,70 @@
import io
import json
from pathlib import Path
import subprocess
import sys
import tarfile
import tempfile
import unittest
import fcntl
class UploadTests(unittest.TestCase):
def setUp(self):
self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name);self.inbox=self.root/'inbox';self.inbox.mkdir()
self.lock=self.root/'lock';self.lock.touch();self.lock.chmod(0o660)
self.marker=self.root/'active-app';self.marker.write_bytes(b'active unchanged')
def tearDown(self):self.temp.cleanup()
def archive(self,names):
b=io.BytesIO()
with tarfile.open(fileobj=b,mode='w',format=tarfile.USTAR_FORMAT) as tar:
for name in names:
data=b'x'*8192 if name.startswith('package.') else b'{}'
m=tarfile.TarInfo(name);m.size=len(data);tar.addfile(m,io.BytesIO(data))
return b.getvalue()
def upload(self,data):
# Only root ownership is simulated in this unprivileged isolated child;
# all archive/stream/locking/resource limits run as production code.
code="""import os,sys
from pathlib import Path
sys.path.insert(0,sys.argv[1]);import ssh_dispatch as d
d.INBOX=Path(sys.argv[2]);d.UPLOAD_LOCK=Path(sys.argv[3])
f=os.fstat
def root_lock(fd):
s=list(f(fd));s[4]=0;return os.stat_result(s)
os.fstat=root_lock
os.environ['SSH_ORIGINAL_COMMAND']='upload fixture'
try:d.main()
except Exception:raise SystemExit(1)
"""
return subprocess.run([sys.executable,'-c',code,str(Path(__file__).parent),str(self.inbox),str(self.lock)],input=data,capture_output=True)
def test_compressed_upload_receives_only_fixed_members_and_metrics(self):
p=self.upload(self.archive(['authorization.json','authorization.sig','transport.json','transport.sig','package.tar.zst']))
self.assertEqual(p.returncode,0,p.stderr.decode());d=json.loads((self.inbox/'fixture/transfer-metrics.json').read_text())
self.assertGreater(d['bytes'],8192);self.assertGreater(d['seconds'],0)
self.assertEqual(self.marker.read_bytes(),b'active unchanged')
def test_legacy_upload_remains_supported(self):
p=self.upload(self.archive(['authorization.json','authorization.sig','package.tar']));self.assertEqual(p.returncode,0)
def test_truncated_upload_retained_for_review_never_activates(self):
data=self.archive(['authorization.json','authorization.sig','transport.json','transport.sig','package.tar.zst'])
p=self.upload(data[:6000]);self.assertNotEqual(p.returncode,0)
self.assertFalse((self.inbox/'fixture/transfer-metrics.json').exists());self.assertEqual(self.marker.read_bytes(),b'active unchanged')
def test_unsafe_member_and_mixed_transports_are_rejected(self):
for names in [['../outside'],['package.tar','package.tar.zst']]:
with self.subTest(names=names):
p=self.upload(self.archive(names));self.assertNotEqual(p.returncode,0)
self.assertEqual(self.marker.read_bytes(),b'active unchanged')
def test_competing_upload_is_rejected_before_staging_creation(self):
with self.lock.open('r+') as stream:
fcntl.flock(stream,fcntl.LOCK_EX|fcntl.LOCK_NB)
self.assertNotEqual(self.upload(self.archive(['package.tar'])).returncode,0)
self.assertFalse((self.inbox/'fixture').exists())
if __name__=='__main__':unittest.main()

View File

@ -1,31 +1,48 @@
#!/usr/bin/env python3
"""Atlas-side immutable transfer. Upload only; activation is a separate operation."""
"""Atlas immutable transfer. No activation; strict existing SSH identity/host policy."""
import argparse
import os
from contextlib import nullcontext
from pathlib import Path
import subprocess
import tarfile
import time
from release import load, safe_name, require
from transport import TRANSPORT_FILES, LEGACY_FILES
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('bundle')
parser.add_argument('--identity',required=True)
parser.add_argument('--host',default='85.190.124.132')
args=parser.parse_args()
require(args.host=='85.190.124.132','Production transfer host must be web1')
bundle=Path(args.bundle).resolve()
release=safe_name(load(bundle/'authorization.json')['release_id'])
command=['ssh','-F','/dev/null','-i',args.identity,'-o','IdentitiesOnly=yes','-o','HostKeyAlgorithms=ssh-ed25519',
'-o','StrictHostKeyChecking=yes','-o','UpdateHostKeys=no','plotdirector-deploy@'+args.host,'upload '+release]
process=subprocess.Popen(command,stdin=subprocess.PIPE)
try:
with tarfile.open(fileobj=process.stdin,mode='w|',format=tarfile.USTAR_FORMAT) as tar:
for name in ('authorization.json','authorization.sig','package.tar'):
path=bundle/name
require(path.is_file() and not path.is_symlink(),'Invalid transfer input')
entry=tarfile.TarInfo(name);entry.size=path.stat().st_size;entry.mode=0o600
with path.open('rb') as stream:tar.addfile(entry,stream)
process.stdin.close()
raise SystemExit(process.wait())
finally:
if process.poll() is None:process.kill();process.wait()
def ssh(identity, command, host='85.190.124.132'):
require(host=='85.190.124.132','Production transfer host must be web1')
return ['ssh','-F','/dev/null','-i',identity,'-o','IdentitiesOnly=yes','-o','HostKeyAlgorithms=ssh-ed25519',
'-o','StrictHostKeyChecking=yes','-o','UpdateHostKeys=no','plotdirector-deploy@'+host,command]
def transfer(bundle, identity, host='85.190.124.132', meter=None):
bundle=Path(bundle).resolve();release=safe_name(load(bundle/'authorization.json')['release_id'])
names=TRANSPORT_FILES if (bundle/'transport.json').exists() else LEGACY_FILES
start=time.monotonic();total=0
with meter.phase('transfer') if meter else nullcontext():
process=subprocess.Popen(ssh(identity,'upload '+release,host),stdin=subprocess.PIPE)
try:
with tarfile.open(fileobj=process.stdin,mode='w|',format=tarfile.USTAR_FORMAT) as tar:
for name in names:
path=bundle/name
require(path.is_file() and not path.is_symlink(),'Invalid transfer input')
entry=tarfile.TarInfo(name);entry.size=path.stat().st_size;entry.mode=0o600;total+=entry.size
with path.open('rb') as stream:tar.addfile(entry,stream)
process.stdin.close()
require(process.wait()==0,'Restricted upload failed; incomplete staging retained for review')
finally:
if process.poll() is None:process.kill();process.wait()
elapsed=time.monotonic()-start
result={'source':'atlas-sender','bytes':total,'seconds':elapsed,'mib_per_second':total/elapsed/1024**2}
if meter:meter.data['transfer']=result
return result
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('bundle');parser.add_argument('--identity',required=True)
parser.add_argument('--host',default='85.190.124.132');args=parser.parse_args()
transfer(args.bundle,args.identity,args.host)
if __name__=='__main__':main()

View File

@ -0,0 +1,88 @@
"""Signed Zstandard envelope around an unchanged, previously signed tar package."""
import os
from pathlib import Path
import shutil
import subprocess
import time
from release import LIMIT_BYTES, Refused, canonical, file_digest, keys, load, require, safe_name, sha, snapshot
TRANSPORT_FILES=('authorization.json','authorization.sig','transport.json','transport.sig','package.tar.zst')
LEGACY_FILES=('authorization.json','authorization.sig','package.tar')
MAX_WINDOW_MIB=128
def signed_json(path, signature, public_key):
p=subprocess.run(['/usr/bin/openssl','pkeyutl','-verify','-pubin','-inkey',str(public_key),'-rawin',
'-in',str(path),'-sigfile',str(signature)],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
require(p.returncode==0,'Transport signature invalid')
return load(path)
def envelope(source, work, public_key):
"""Private snapshots only. Verify compressed bytes BEFORE invoking the decoder."""
for name,limit in [('transport.json',16384),('transport.sig',16384),('package.tar.zst',LIMIT_BYTES)]:
snapshot(source/name,work/name,limit)
t=signed_json(work/'transport.json',work/'transport.sig',public_key)
keys(t,('format','method','level','threads','release_id','source_commit','authorization_sha256',
'original_sha256','original_bytes','transferred_sha256','transferred_bytes','compression_seconds'))
require(t['format']==1 and t['method']=='zstd','Unsupported transport')
safe_name(t['release_id'])
require(isinstance(t['source_commit'],str) and len(t['source_commit'])==40,'Invalid transport source')
for k in ['authorization_sha256','original_sha256','transferred_sha256']:sha(t[k])
for k in ['original_bytes','transferred_bytes']:
require(type(t[k]) is int and 0<t[k]<=LIMIT_BYTES,'Transport size exceeds limit')
require(type(t['level']) is int and t['level'] in (1,3,6) and type(t['threads']) is int and 1<=t['threads']<=8,'Unsupported compressor settings')
require(type(t['compression_seconds']) in (float,int) and 0<=t['compression_seconds']<=86400,'Invalid compression measurement')
require((work/'package.tar.zst').stat().st_size==t['transferred_bytes'] and file_digest(work/'package.tar.zst')==t['transferred_sha256'],'Compressed transport checksum/size mismatch')
require(file_digest(work/'authorization.json')==t['authorization_sha256'],'Transport authorization mismatch')
require(shutil.disk_usage(work).free>=1024**3+3*t['original_bytes'],'Insufficient decompression/extraction/installation space')
return t
def decompress(work, t):
"""Bound output, decoder memory, CPU and wall time; never invoke a shell."""
import resource
import signal
def limits():
resource.setrlimit(resource.RLIMIT_FSIZE,(t['original_bytes'],t['original_bytes']))
resource.setrlimit(resource.RLIMIT_CPU,(120,120))
signal.alarm(120)
output=work/'package.tar'
try:
with output.open('xb') as stream:
p=subprocess.run(['/usr/bin/zstd','--quiet','--decompress','--stdout',f'--memory={MAX_WINDOW_MIB}MB','--',str(work/'package.tar.zst')],
stdout=stream,stderr=subprocess.DEVNULL,timeout=125,preexec_fn=limits)
require(p.returncode==0 and output.stat().st_size==t['original_bytes'],'Decompression failed or size mismatch')
require(file_digest(output)==t['original_sha256'],'Reconstructed package checksum mismatch')
except BaseException:
output.unlink(missing_ok=True)
raise
def compress_bundle(source, output, signing_key, public_key, *, level=6, threads=4, meter=None, verified=False):
source,output=Path(source).resolve(),Path(output).resolve()
require(not output.exists(),'Transport destination already exists')
require(level in (1,3,6) and 1<=threads<=8,'Unsupported compression settings')
if not verified:
import tempfile
from release import verify_bundle
with tempfile.TemporaryDirectory(prefix='pd-source-check-',dir=output.parent) as directory:
verify_bundle(source,Path(directory),public_key)
output.mkdir(mode=0o700)
for name in ['authorization.json','authorization.sig']:
snapshot(source/name,output/name,16384)
a=load(output/'authorization.json');require(file_digest(source/'package.tar')==a['package_sha256'],'Original signed package differs')
start=time.monotonic()
with (output/'package.tar.zst').open('xb') as stream:
p=subprocess.run(['/usr/bin/zstd','--quiet',f'-{level}',f'-T{threads}','--check','--stdout','--',str(source/'package.tar')],stdout=stream,stderr=subprocess.DEVNULL,timeout=180)
require(p.returncode==0,'Compression failed')
elapsed=time.monotonic()-start
size=(source/'package.tar').stat().st_size
require(0<size<=LIMIT_BYTES and (output/'package.tar.zst').stat().st_size<=LIMIT_BYTES,'Transport exceeds size limit')
t={'format':1,'method':'zstd','level':level,'threads':threads,'release_id':a['release_id'],'source_commit':a['source_commit'],
'authorization_sha256':file_digest(output/'authorization.json'),'original_sha256':a['package_sha256'],'original_bytes':size,
'transferred_sha256':file_digest(output/'package.tar.zst'),'transferred_bytes':(output/'package.tar.zst').stat().st_size,'compression_seconds':elapsed}
(output/'transport.json').write_bytes(canonical(t))
subprocess.run(['/usr/bin/openssl','pkeyutl','-sign','-inkey',str(signing_key),'-rawin','-in',str(output/'transport.json'),'-out',str(output/'transport.sig')],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
return t