diff --git a/Docs/Codex/Deployment.md b/Docs/Codex/Deployment.md index 646012f1..b22bc96d 100644 --- a/Docs/Codex/Deployment.md +++ b/Docs/Codex/Deployment.md @@ -1,110 +1,177 @@ # PlotDirector Development Deployment -The authoritative release/package and migration-history contract is now -[Production deployment standard](../Deployment/Production.md), implemented under -`Tools/Deployment`. The environment details below describe the existing Development -layout; conversion of its physical `current` directory is an explicit provisioning -operation. Use the same manifest, checksums, SQL worker, history and health gates -for Development/Test; do not return to untracked manual SQL on later deployments. -The root activation entry point has a production target profile and must not be -pointed at Development by replacing credentials alone. +Development uses the installed Atlas-only manifest activation profile in +`Tools/Deployment/development.py`. Production uses a separate helper on web1. +Do not repoint either helper, copy Production credentials, or use Production access +for a Development release. -Read this document only when deployment or detailed development-service operation is part of the task. +## Targets and trust boundaries -## Current Production +| Setting | Development on Atlas | +|---|---| +| Application root | `/opt/plotdirector-dev` | +| Current application | `/opt/plotdirector-dev/current` (atomic symlink) | +| Immutable releases | `/opt/plotdirector-dev/releases//app` | +| Service / runtime user | `plotdirector-dev.service` / `plotdirector` | +| Runtime environment | `/etc/plotdirector/plotdirector.env` | +| Deployment configuration | `/etc/plotdirector-development/target.json` | +| Database worker configuration | `/etc/plotdirector-development/database.json` | +| Database / SQL endpoint | `PlotDirector_Development` / `192.168.10.10,1433` | +| Installed helper | `/usr/local/sbin/deploy-plotdirector-development` | +| Installed implementation | `/usr/local/lib/plotdirector-dev-deployment` | +| Migration OS identity | `plotdirector-dev-migrate` | +| Deployment group / sudo rule | `plotdirector-dev-deploy` / `/etc/sudoers.d/plotdirector-development` | +| Submission inbox | `/var/lib/plotdirector-dev-deployment/incoming` | +| Approved code-only baseline | `/var/lib/plotdirector-dev-deployment/baseline` | +| Evidence / receipts | `/opt/plotdirector-dev/deployment-evidence`, `/opt/plotdirector-dev/deployment-receipts` | +| SQL backup (host / container) | `/sql/mssql/backup` / `/var/opt/mssql/backup` | +| Local / public URL | `http://127.0.0.1:5050` / `https://dev.plotdirector.com/` | -Production is live on web1 (`85.190.124.132`) at https://plotdirector.com/. -Use the restricted manifest-driven helper, never the legacy www helper. See -[the operational standard](../Deployment/Production.md) and -[actual installation/acceptance and worker holds](../Deployment/Phase2-20261125.md). -www is an inactive recovery fallback. +The fixed Development profile rejects any change to host, database, service, +configuration paths, trust anchor or endpoints. Its signing key is independent of +Production. The privileged command clears the environment and imports only its +root-owned installed modules. Operators submit untrusted packages; the helper +snapshots them and verifies signatures, manifests, file checksums, qualification, +schema fingerprints and the complete immutable migration ledger before admission. -## Environment +`/srv/apps/plotdirector-dev/current` is the retained legacy application directory, +not the active service target. Existing uploads, logs and data-protection storage +remain at their original Development paths. Root-owned bindings and configuration +links under `/opt/plotdirector-dev/shared` preserve those paths across releases. +Runtime appsettings and the environment file are not taken from release packages. +The Development systemd drop-in explicitly retains +`DataProtection__KeysPath=/srv/apps/plotdirector-dev/App_Data/DataProtectionKeys` +and `DataProtection__ApplicationName=/srv/apps/plotdirector-dev/current/`. The latter +is the measured legacy ASP.NET application discriminator, including its trailing +slash. Both values are enforced by admission, so release-directory changes do not +rotate the cookie purpose or key ring. +Do not delete the legacy directory: some persistent bindings still reference it. -- Development host: Atlas. -- Repository: `/srv/repos/PlotDirector`. -- Development files: `/srv/apps/plotdirector-dev/current`. -- Release archive: `/srv/apps/plotdirector-dev/releases/`. -- Service: `plotdirector-dev`. -- Service user: `plotdirector:plotdirector`. -- Environment file: `/etc/plotdirector/plotdirector.env`. -- Persistent uploads: `/srv/apps/plotdirector-dev/uploads`. -- Default deployed data-protection keys: `/srv/apps/plotdirector-dev/App_Data/DataProtectionKeys`. -- Local endpoint: `http://127.0.0.1:5050`. -- Public development endpoint: `https://dev.plotdirector.com/`. +## Routine code-only deployment -`current` is a physical directory, not a symlink. +Use a clean committed checkout. Preserve unrelated work by building from a separate +clean worktree when necessary. The caller must be a member of +`plotdirector-dev-deploy`; membership takes effect on the next login (or use +`sg plotdirector-dev-deploy -c 'COMMAND'` for the current session). -Use `sudo -n` for protected service/configuration paths where appropriate. +Run the repository's current orchestration tool, supplying the intended clean +application checkout and a new private output directory: -## Before Deployment +```bash +python3 Tools/Deployment/development_release.py \ + --source /absolute/clean/checkout \ + --output /home/nick/.local/share/plotdirector-development/releases/UNIQUE-ID \ + --activate +``` -Confirm the intended commit: +This publishes the exact commit, runs the executable regression harness serially, +checks that SQL has not changed from the approved Development baseline, prepares +and signs the standard manifest package, submits it, validates it, then activates +it. The signing key is +`~/.local/share/plotdirector-development/signing/private.pem` (mode 0600, parent +0700). It never reads a Production signing key or invokes SSH. Without `--activate` +it stops after preactivation validation; there is no service stop or database write. - git status --short --branch - git log -1 --oneline +Activation checks queued/running work and holds the database deployment session +lock. It makes and verifies a COPY_ONLY/CHECKSUM backup, checks idle state again +before and after stopping the service, verifies/skips recorded migrations, installs +immutable files, switches `current`, starts the service, verifies application and +database identity, and records successful release history only after health passes. +Active import, Story Intelligence, synthesis, enrichment or other checked jobs +block deployment. Do not interrupt them without explicit acceptance. -If the change involves database migration, qualify an explicit manifest and let the worker back up, verify and apply it before activating dependent code; do not bypass migration history with manual SQL. +For a previously submitted bundle: -Before stopping the service, confirm there is no active import, Story Intelligence run, synthesis or character enrichment work. Check queued and processing work as well as core imports. +```bash +sudo -n /usr/local/sbin/deploy-plotdirector-development --validate RELEASE-ID +sudo -n /usr/local/sbin/deploy-plotdirector-development --activate RELEASE-ID +sudo -n /usr/local/sbin/deploy-plotdirector-development --receipt DEPLOYMENT-ID +``` -Do not deploy while such work is active unless interruption has explicitly been accepted. +No administrator intervention or Production access is needed for these routine +commands after provisioning. A failed operation retains a sanitised receipt and +protected evidence. After a failure involving a service stop, investigate the +receipt before taking further action; the helper does not blindly roll back SQL. -## Publish +## SQL changes and recovery -Use a fresh temporary publish directory. Set fail-fast shell behaviour and derive a release name from the short commit SHA and UTC timestamp. +The routine command deliberately rejects changed SQL. A schema release needs an +explicit reviewed plan qualified against Development's schema, using the standard +`release.py` package contract and `DatabaseWorker`. Read +[database operations](Database.md) and the [manifest/history contract](../Deployment/Production.md). +Never replay all SQL files, infer history from a migration number, or adopt a +Production baseline. Update the approved Development code-only baseline only after +successful schema qualification and activation. -Publish with: - - dotnet publish PlotLine/PlotLine.csproj -c Release -o "$publish_dir" - -The standard paths are: - - release_dir="/srv/apps/plotdirector-dev/releases/$release" - backup_dir="/srv/apps/plotdirector-dev/current-before-$release" - -## Install - -Copy the fresh publish into the release archive and ensure ownership is `plotdirector:plotdirector`. - -Stop `plotdirector-dev` before replacing the physical live directory. - -Back up the existing `current` directory to the timestamped `current-before` path. - -Use `rsync -a --delete` from the release directory into `current`, preserving: - -- `appsettings*.json` -- `.env*` -- `App_Data/` -- `wwwroot/uploads/` -- `uploads/` -- `logs/` -- `Logs/` - -Restore `plotdirector:plotdirector` ownership and start `plotdirector-dev`. - -If installation or startup fails, stop and diagnose. Do not continue blindly or claim successful deployment. - -An application rollback does not undo SQL migrations and must remain compatible with the migrated schema. +An application rollback needs a signed package with a new release identifier and +compatible schema. `--rollback` requires all migration history already present; +it never undoes database changes. The previous release remains in `releases`. ## Verification -Verify: +Check service status, recent warning/error logs, local health identity and normal +TLS public GETs. Compare the installed DLL checksum and changed static assets with +the signed manifest. Confirm the running health endpoint reports the intended full +commit, `Development` and `PlotDirector_Development`. Verify affected authenticated +routes through normal login with an isolated Development fixture when applicable. +Never print credentials or record login screenshots, browser storage or traces. -- `systemctl is-active plotdirector-dev` -- service status and recent warning/error logs; -- local GET to `http://127.0.0.1:5050/`; -- public HTTPS GET to `https://dev.plotdirector.com/`; -- deployed `PlotLine.dll` metadata; -- SHA-256 of published and deployed `PlotLine.dll`; -- the changed authenticated route when applicable. +## One-time provisioning and infrastructure updates -Timestamps alone do not prove the intended build is running. +`Tools/Deployment/provision/development.py` is an administrator-only provisioning +operation. It accepts a previously signed **Development** package matching the +running DLL and a complete verified Development ledger; it refuses an existing +target. It installs an independent worker/profile/key/sudo rule, preserves runtime +configuration and persistent paths, seeds the previous release and reloads the +Development service drop-in without restarting the process. It does not contact +Production or change database state. Its worker input is a full published directory, +including nested `runtimes/` dependencies. -Use a real GET for public smoke testing. HEAD may return 405. +The actual 2026-11-25 provisioning command was: -Normal verification must validate TLS. Use `-k` only for certificate diagnosis. +```bash +sudo -n python3 Tools/Deployment/provision/development.py \ + --deployment-user nick \ + --database-config /home/nick/plotdirector-phase1-20261125/worker-development.private.json \ + --worker /tmp/pd-dev-deploy-ops/worker \ + --previous-package /home/nick/otp-refine-20261125/signed-bundle \ + --previous-public-key /home/nick/plotdirector-phase1-20261125/release-signing/phase1-candidate.pub.pem \ + --public-key /home/nick/.local/share/plotdirector-development/signing/public.pem +``` -Review configuration changes separately because deployment preserves deployed appsettings files. +Those inputs describe the historical bootstrap, not routine deployment dependencies. +Subsequent releases use only the installed profile, approved baseline and independent +Development signing key. Installed privileged modules do not update themselves +from a checkout. Changes to the trusted helper require separate administrator +review/install and the focused Python regression suite; they do not require any +Production access. -Keep the release directory and `current-before` backup named with the deployed short SHA and UTC timestamp for traceability. +## Why the 2026-11-25 blocker occurred + +`05a689c2` changed this guide to mandate manifest/history activation, but supplied +only a Production-specific installed target. `793de563` retained that restriction. +The last successful Development deployment (`9b1770d9`, 19:48 UTC) used a one-off +private Development driver, with a signed package, verified backup, 321-entry +ledger and post-health release record. That driver was not installed or documented +as the reusable Development entry point. The later `ff6369e9` task therefore found +no supported configured Development target. The running application and ledger +were healthy; the regression was the incomplete operational handover. + +## Acceptance of the restored mechanism + +Commit `ff6369e9766b37fba38b9c327c0c170076236870` was deployed twice through the +routine command, with the final activation retaining the legacy data-protection +identity. Both used signed manifests, verified backups and complete 321-entry +history; zero migrations executed. A group-only temporary OS identity successfully +validated a release while general sudo, migration credentials and the private +signing key remained inaccessible. All 77 deployment tests and the complete +application regression harness passed. Authenticated Scan Manuscript and actual +theme-picker checks passed in light/dark modes; served stylesheet hashes match. + +See the [activation receipt](../Deployment/Evidence/Development-20261125/activation-receipt.json), +[verification](../Deployment/Evidence/Development-20261125/verification.json), and +[permission checks](../Deployment/Evidence/Development-20261125/permission-check.json). +The legacy HTTPS-port warning behind the reverse proxy remains; public TLS checks +pass. A separate existing account-deletion foreign-key defect was observed while +removing the browser fixture; the fixture was fully removed, and no schema change +was made. Neither observation blocks Development deployments. diff --git a/Docs/Deployment/Evidence/Development-20261125/activation-receipt.json b/Docs/Deployment/Evidence/Development-20261125/activation-receipt.json new file mode 100644 index 00000000..d930526c --- /dev/null +++ b/Docs/Deployment/Evidence/Development-20261125/activation-receipt.json @@ -0,0 +1,291 @@ +{ + "availability": { + "confirmed_inactive_to_health_ready_seconds": 7.380294495989801, + "definition": "Monotonic intervals include stop/start commands; observed public outage measured separately on Atlas.", + "service_stop_to_start_seconds": 2.005145545990672, + "stop_request_to_health_ready_seconds": 7.524218160993769, + "stop_request_to_start_command_complete_seconds": 2.1490729079960147 + }, + "checks": { + "activation": true, + "application": { + "database": "PlotDirector_Development", + "environment": "Development", + "healthy": true, + "sourceCommit": "ff6369e9766b37fba38b9c327c0c170076236870", + "version": "1.0.0" + }, + "binary_identity": true, + "database": { + "complete_history": true, + "healthy": true, + "history": { + "baselined": 317, + "executed": 4, + "expected": 321, + "latest_successful_release": { + "activated_utc": "2026-11-25T21:03:35.9983834Z", + "activation_kind": "Deploy", + "application_version": "1.0.0", + "deployment_identifier": "20261125T210308Z-b72117527063", + "manifest_sha256": "e9af01e8060a1e8fce81db625a79215e903efef4ff7db76aee9a60d972179fbb", + "package_sha256": "ddfc29ef614ec4ff108535d21dbe40726e9097ebb1b3f1b05cad6cf06aef0142", + "recorded": true, + "release_identifier": "development-ff6369e9766b-20261125T210110Z", + "source_commit": "ff6369e9766b37fba38b9c327c0c170076236870" + }, + "recorded": 321, + "successful_release_count": 3 + }, + "history_verification_seconds": 0.1163479 + }, + "http_login": true, + "http_root": true + }, + "completed_utc": "2026-11-25T21:11:09.056+00:00", + "database_backup": { + "options": [ + "COPY_ONLY", + "CHECKSUM", + "VERIFYONLY" + ], + "path": "/sql/mssql/backup/PlotDirector_Development-predeploy-20261125T211042Z-2d66c5c3fa11.bak", + "verified": true + }, + "deployment_id": "20261125T211042Z-2d66c5c3fa11", + "failures": [], + "format": 1, + "migration_history": { + "complete": true, + "database_bytes": 2097152000, + "history": { + "baselined": 317, + "executed": 4, + "expected": 321, + "latest_successful_release": { + "activated_utc": "2026-11-25T21:03:35.9983834Z", + "activation_kind": "Deploy", + "application_version": "1.0.0", + "deployment_identifier": "20261125T210308Z-b72117527063", + "manifest_sha256": "e9af01e8060a1e8fce81db625a79215e903efef4ff7db76aee9a60d972179fbb", + "package_sha256": "ddfc29ef614ec4ff108535d21dbe40726e9097ebb1b3f1b05cad6cf06aef0142", + "recorded": true, + "release_identifier": "development-ff6369e9766b-20261125T210110Z", + "source_commit": "ff6369e9766b37fba38b9c327c0c170076236870" + }, + "recorded": 321, + "successful_release_count": 3 + }, + "history_verification_seconds": 0.3024553, + "schema": "432931e506b7f02570952bc098b952fcc82228c9f1dbca0fef1619ff869763c7" + }, + "migrations": { + "baselined": 0, + "committed": [], + "committed_list_truncated": false, + "executed": 0, + "schema": "432931e506b7f02570952bc098b952fcc82228c9f1dbca0fef1619ff869763c7" + }, + "operation": "activate", + "origin": "web1", + "phases": [ + { + "completed_utc": "2026-11-25T21:10:43.800+00:00", + "exclusive_seconds": 0.737653, + "name": "package_validation", + "outcome": "passed", + "parent": null, + "seconds": 0.737653, + "started_utc": "2026-11-25T21:10:43.062+00:00" + }, + { + "completed_utc": "2026-11-25T21:10:45.265+00:00", + "exclusive_seconds": 1.46513, + "name": "package_validation", + "outcome": "passed", + "parent": null, + "seconds": 1.46513, + "started_utc": "2026-11-25T21:10:43.800+00:00" + }, + { + "completed_utc": "2026-11-25T21:10:47.600+00:00", + "exclusive_seconds": 0.696416, + "name": "database_state_verification", + "outcome": "passed", + "parent": null, + "seconds": 0.998871, + "started_utc": "2026-11-25T21:10:46.601+00:00" + }, + { + "clock": "SQL worker Stopwatch; measured duration, UTC endpoints unavailable", + "completed_utc": null, + "exclusive_seconds": 0.302455, + "name": "migration_history_verification", + "outcome": "passed", + "parent": "database_state_verification", + "seconds": 0.302455, + "started_utc": null + }, + { + "completed_utc": "2026-11-25T21:11:01.296+00:00", + "exclusive_seconds": 13.675311, + "name": "database_backup", + "outcome": "passed", + "parent": null, + "seconds": 13.675311, + "started_utc": "2026-11-25T21:10:47.620+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:01.474+00:00", + "exclusive_seconds": 0.143827, + "name": "service_stop", + "outcome": "passed", + "parent": null, + "seconds": 0.143827, + "started_utc": "2026-11-25T21:11:01.331+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:02.645+00:00", + "exclusive_seconds": 1.140531, + "name": "migration_execution", + "outcome": "passed", + "parent": null, + "seconds": 1.140531, + "started_utc": "2026-11-25T21:11:01.504+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:03.209+00:00", + "exclusive_seconds": 0.55612, + "name": "release_installation", + "outcome": "passed", + "parent": null, + "seconds": 0.55612, + "started_utc": "2026-11-25T21:11:02.653+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:03.460+00:00", + "exclusive_seconds": 0.091703, + "name": "release_activation", + "outcome": "passed", + "parent": null, + "seconds": 0.091703, + "started_utc": "2026-11-25T21:11:03.368+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:03.480+00:00", + "exclusive_seconds": 0.019743, + "name": "service_start", + "outcome": "passed", + "parent": null, + "seconds": 0.019743, + "started_utc": "2026-11-25T21:11:03.460+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:08.855+00:00", + "exclusive_seconds": 0.538483, + "name": "postactivation_verification", + "outcome": "passed", + "parent": "application_health_readiness", + "seconds": 0.654831, + "started_utc": "2026-11-25T21:11:08.200+00:00" + }, + { + "clock": "SQL worker Stopwatch; measured duration, UTC endpoints unavailable", + "completed_utc": null, + "exclusive_seconds": 0.116348, + "name": "migration_history_verification", + "outcome": "passed", + "parent": "postactivation_verification", + "seconds": 0.116348, + "started_utc": null + }, + { + "completed_utc": "2026-11-25T21:11:08.855+00:00", + "exclusive_seconds": 4.72025, + "name": "application_health_readiness", + "outcome": "passed", + "parent": null, + "seconds": 5.375081, + "started_utc": "2026-11-25T21:11:03.480+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:08.887+00:00", + "exclusive_seconds": 0.024546, + "name": "postactivation_verification", + "outcome": "passed", + "parent": null, + "seconds": 0.024546, + "started_utc": "2026-11-25T21:11:08.863+00:00" + }, + { + "completed_utc": "2026-11-25T21:11:09.056+00:00", + "exclusive_seconds": 0.015857, + "name": "receipt_generation", + "outcome": "passed", + "parent": null, + "seconds": 0.015857, + "started_utc": "2026-11-25T21:11:09.040+00:00" + } + ], + "previous_release": { + "deployment": "20261125T210308Z-b72117527063", + "package_sha256": "ddfc29ef614ec4ff108535d21dbe40726e9097ebb1b3f1b05cad6cf06aef0142", + "release": "development-ff6369e9766b-20261125T210110Z", + "source_commit": "ff6369e9766b37fba38b9c327c0c170076236870", + "version": "1.0.0" + }, + "protected_evidence_reference": "/opt/plotdirector-dev/deployment-evidence/20261125T211042Z-2d66c5c3fa11.jsonl", + "recovery": "No automatic database restore or application rollback. Review protected attempt evidence on failure.", + "release": { + "application_sha256": "a6306640483b7366aa39b0ca16971fd9ef4d9732084fc69c2077b1e8b9a48147", + "dll_sha256": "a6b0edd9494e360aebbdfc2f51053d430ba0e056122e6f9f91e1dc9bdc80a805", + "id": "development-ff6369e9766b-20261125T210842Z", + "manifest_sha256": "0ead2269363a3a1322674952af6c4fac4b64cb46eb9ba185d7c1ea2a2b8106aa", + "package_sha256": "35274650d8ec098a7313483321e4949ac75489c81345e5b58bac6993ebbfe777", + "source_commit": "ff6369e9766b37fba38b9c327c0c170076236870", + "version": "1.0.0" + }, + "release_history": { + "activated_utc": "2026-11-25T21:11:08.8683394Z", + "activation_kind": "Deploy", + "application_version": "1.0.0", + "deployment_identifier": "20261125T211042Z-2d66c5c3fa11", + "manifest_sha256": "0ead2269363a3a1322674952af6c4fac4b64cb46eb9ba185d7c1ea2a2b8106aa", + "package_sha256": "35274650d8ec098a7313483321e4949ac75489c81345e5b58bac6993ebbfe777", + "recorded": true, + "release_identifier": "development-ff6369e9766b-20261125T210842Z", + "source_commit": "ff6369e9766b37fba38b9c327c0c170076236870" + }, + "started_utc": "2026-11-25T21:10:42.984+00:00", + "status": "activated", + "timing": { + "clock": "monotonic; UTC timestamps for correlation only", + "measured_top_level_seconds": 24.244373, + "total_seconds": 26.071247, + "unattributed_seconds": 1.826874 + }, + "transport": { + "compression_ratio": 1.0, + "method": "none", + "original_bytes": 554301440, + "original_sha256": "35274650d8ec098a7313483321e4949ac75489c81345e5b58bac6993ebbfe777", + "transferred_bytes": 554301440, + "transferred_sha256": "35274650d8ec098a7313483321e4949ac75489c81345e5b58bac6993ebbfe777" + }, + "unperformed_phases": [ + "release_preparation", + "production_validation", + "remote_activation", + "receipt_retrieval", + "scope_verification", + "build", + "packaging_signing", + "compression", + "transfer", + "decompression", + "public_acceptance" + ], + "warnings": [ + "upload-metrics-unavailable; sender receipt may provide transfer measurements" + ] +} diff --git a/Docs/Deployment/Evidence/Development-20261125/permission-check.json b/Docs/Deployment/Evidence/Development-20261125/permission-check.json new file mode 100644 index 00000000..16c019d4 --- /dev/null +++ b/Docs/Deployment/Evidence/Development-20261125/permission-check.json @@ -0,0 +1,7 @@ +{ + "group_only_validation": true, + "general_sudo_denied": true, + "migration_credentials_unreadable": true, + "private_signing_key_unreadable": true, + "production_access": false +} diff --git a/Docs/Deployment/Evidence/Development-20261125/verification.json b/Docs/Deployment/Evidence/Development-20261125/verification.json new file mode 100644 index 00000000..d467e770 --- /dev/null +++ b/Docs/Deployment/Evidence/Development-20261125/verification.json @@ -0,0 +1,41 @@ +{ + "status": "passed", + "source_commit": "ff6369e9766b37fba38b9c327c0c170076236870", + "environment": "Development", + "database": "PlotDirector_Development", + "release_id": "development-ff6369e9766b-20261125T210842Z", + "deployment_id": "20261125T211042Z-2d66c5c3fa11", + "installed_dll_sha256": "a6b0edd9494e360aebbdfc2f51053d430ba0e056122e6f9f91e1dc9bdc80a805", + "public_https": { + "https://dev.plotdirector.com/": 200, + "https://dev.plotdirector.com/Account/Login": 200 + }, + "served_stylesheets": { + "onboarding.css": "56044b4480832870ca92de79b894dbbe71a10a162c731258da1fdd2dba2e549b", + "story-intelligence-global-progress.css": "a5315dadbd5374eb08af5e124f20d0c6b37f610078f18369071c903b406851f5" + }, + "installed_modules": { + "activate.py": "a4d9ffb3745555f08db5b3433f66c79eedbe52f94328286a7133bb594fe19271", + "release.py": "10bff1f1c1579b5f8a3d4df8bf9c4ef8891d576f5c329fba5c169dfb77dcb8dd", + "receipt.py": "d92324e00862f773ef663332dedc0e061bb0561b5397e83728e05ce42c142d21", + "transport.py": "66c5adf1eeaf28fa050d188e9c7607234116fa6bb5f289301a79ca58e3a3e601", + "development.py": "43d671ef3758da701299b08f375b5674c695d1857c4e36022dbc8e73bd993e84" + }, + "full_regression_harness": "passed", + "deployment_python_tests": { + "passed": 77 + }, + "authenticated_scan_route": "passed using isolated synthetic account; actual theme picker warm-dark/warm-light", + "continuation_banner": "verified as display-only synthetic state on authenticated running page; no import started", + "fixture_cleanup": "completed; no fixture account remains", + "persistence": { + "legacyDiscriminator": "/srv/apps/plotdirector-dev/current/", + "stableKeyDirectory": "/srv/apps/plotdirector-dev/App_Data/DataProtectionKeys", + "legacyProtectionCompatibility": true + }, + "production_access": false, + "remaining_observations": [ + "Existing account deletion procedure conflicts with FK_UserOnboardingState_AppUser for an account that has entered onboarding. Only the synthetic fixture row was removed before normal account cleanup; no application/schema fix was included.", + "The HTTPS-port redirect warning was present before and after deployment behind the reverse proxy; normal public TLS GETs pass. No postactivation failure markers were logged by the final process." + ] +} diff --git a/Tools/Deployment/README.md b/Tools/Deployment/README.md index e742e4fe..3dfe94ba 100644 --- a/Tools/Deployment/README.md +++ b/Tools/Deployment/README.md @@ -1,6 +1,10 @@ -# Production deployment tooling +# Manifest deployment tooling -Phase 1 implementation and qualification live here. Do not install on a production +For routine Atlas Development releases, use `development_release.py` and the independent +`deploy-plotdirector-development` profile; see [Development operations](../../Docs/Codex/Deployment.md). +Never repoint the Production entry point. + +Production Phase 1 implementation and qualification live here. Do not install on a production host until the qualification report says READY and Phase 2 has been authorised. See `Docs/Deployment/Production.md` for the trust model and operational procedure. diff --git a/Tools/Deployment/activate.py b/Tools/Deployment/activate.py index 598c54fe..268f09e5 100644 --- a/Tools/Deployment/activate.py +++ b/Tools/Deployment/activate.py @@ -180,7 +180,7 @@ def health(cfg, destination, manifest, worker, meter=None): for attempt in range(20): try: status = command(['/usr/bin/curl', '--silent', '--show-error', '--noproxy', '*', - '--header', 'Host: plotdirector.com', '--header', 'X-Forwarded-Proto: https', '--connect-timeout', '2', + '--header', 'Host: ' + cfg.get('health_host', 'plotdirector.com'), '--header', 'X-Forwarded-Proto: https', '--connect-timeout', '2', '--max-time', '5', '--output', '/dev/null', '--write-out', '%{http_code}', cfg['health_base'] + path], account=cfg['runtime_account'], timeout=10) if status in ('200', '301', '302', '307', '308'): break @@ -192,7 +192,7 @@ def health(cfg, destination, manifest, worker, meter=None): require((Path(cfg['root']) / 'current').resolve(strict=True) == destination / 'app', 'Active release identity mismatch') require(file_digest(destination / 'app/PlotLine.dll') == manifest['files']['app/PlotLine.dll'], 'Installed DLL checksum mismatch') identity = json.loads(command(['/usr/bin/curl', '--silent', '--show-error', '--fail', '--noproxy', '*', - '--header', 'Host: plotdirector.com', '--header', 'X-Forwarded-Proto: https', + '--header', 'Host: ' + cfg.get('health_host', 'plotdirector.com'), '--header', 'X-Forwarded-Proto: https', '--connect-timeout', '2', '--max-time', '10', cfg['health_base'] + '/_deployment/health'], account=cfg['runtime_account'], timeout=15)) require(identity.get('healthy') is True and identity.get('version') == manifest['version'] @@ -210,7 +210,7 @@ def health(cfg, destination, manifest, worker, meter=None): def persist_receipt(cfg, meter): directory=Path(cfg['root'])/'deployment-receipts' protected(directory,directory=True) - gid=grp.getgrnam('plotdirector-deploy').gr_gid + gid=grp.getgrnam(cfg.get('deployment_group', '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) @@ -252,13 +252,13 @@ def import_upload_metrics(source, work, meter): meter.data['warnings'].append('upload-metrics-unavailable; sender receipt may provide transfer measurements') -def activate(package_id, validate=False, rollback=False): +def activate(package_id, validate=False, rollback=False, profile=None): 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: - cfg=configuration();root=Path(cfg['root']) + cfg=profile.configuration() if profile else 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) @@ -285,7 +285,7 @@ def activate(package_id, validate=False, rollback=False): 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) + worker=profile.worker(cfg) if profile else 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 @@ -304,14 +304,14 @@ def activate(package_id, validate=False, rollback=False): event('validation-only');status='validated' print('VALIDATED '+package_id+'; no backup, migrations or service operations performed') return - backup=Path(cfg['backup'])/('PlotLine-predeploy-'+deployment+'.bak') + backup=Path(cfg['backup'])/(cfg['database']+'-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') with meter.phase('database_backup'): - backup_result=worker.call('backup',path=str(backup)) + backup_result=worker.call('backup',path=str(Path(cfg.get('database_backup_directory',cfg['backup']))/backup.name)) 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') @@ -325,7 +325,9 @@ def activate(package_id, validate=False, rollback=False): meter.data['migrations']=migration if isinstance(migration,dict) else {} event('migration-complete') destination=root/'releases'/package_id - with meter.phase('release_installation'):install(payload,destination,cfg['runtime_account']) + with meter.phase('release_installation'): + if profile:profile.install(payload,destination,cfg['runtime_account']) + else: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) @@ -359,8 +361,10 @@ def activate(package_id, validate=False, rollback=False): 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) + + if cfg is not None:persist_receipt(cfg,meter) + meter.finish(status) + if cfg is not None:persist_receipt(cfg,meter) print('RECEIPT '+deployment) diff --git a/Tools/Deployment/deploy-plotdirector-development b/Tools/Deployment/deploy-plotdirector-development new file mode 100644 index 00000000..1ac7ea9c --- /dev/null +++ b/Tools/Deployment/deploy-plotdirector-development @@ -0,0 +1,13 @@ +#!/bin/sh +# Independent Atlas-only launcher; no Production import path, config or sudo rule. +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-dev-deployment") +from development import main +from activate import public_error +try: + main() +except Exception as error: + print("DEVELOPMENT DEPLOYMENT REFUSED: " + public_error(error)) + sys.exit(1) +' "$@" diff --git a/Tools/Deployment/development.py b/Tools/Deployment/development.py new file mode 100644 index 00000000..342d222a --- /dev/null +++ b/Tools/Deployment/development.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Atlas-only activation profile. Production entry point/configuration is never used.""" +import grp +import os +from pathlib import Path +import pwd +import signal +import shlex +import socket +import subprocess +import sys + +import activate as core +from release import load, keys, require, safe_name, canonical + +CONFIG = Path('/etc/plotdirector-development/target.json') +ROOT = '/opt/plotdirector-dev' +PERSISTENCE_ENV = { + 'DataProtection__KeysPath=/srv/apps/plotdirector-dev/App_Data/DataProtectionKeys', + 'DataProtection__ApplicationName=/srv/apps/plotdirector-dev/current/', +} +FIXED = { + 'format': 1, 'host': 'atlas', 'environment': 'Development', + 'database': 'PlotDirector_Development', 'root': ROOT, + 'inbox': '/var/lib/plotdirector-dev-deployment/incoming', + 'evidence': ROOT + '/deployment-evidence', 'backup': '/sql/mssql/backup', + 'database_backup_directory': '/var/opt/mssql/backup', + 'service': 'plotdirector-dev.service', 'runtime_account': 'plotdirector', + 'migration_account': 'plotdirector-dev-migrate', + 'deployment_group': 'plotdirector-dev-deploy', + 'worker': '/usr/local/lib/plotdirector-dev-deployment/database/DatabaseWorker.dll', + 'database_config': '/etc/plotdirector-development/database.json', + 'public_key': '/etc/plotdirector-development/release-signing-public.pem', + 'runtime_config': '/etc/plotdirector/plotdirector.env', + 'health_base': 'http://127.0.0.1:5050', 'health_host': 'dev.plotdirector.com', + 'minimum_free_bytes': 2147483648, +} + + +def validate_target(cfg): + keys(cfg, FIXED) + require(cfg == FIXED and socket.gethostname() == 'atlas', 'Wrong Development target') + + +class DevelopmentWorker(core.Worker): + def __init__(self, cfg): + validate_target(cfg) + core.protected(cfg['database_config'], secret=True) + data = load(cfg['database_config']) + require(data['database'] == 'PlotDirector_Development' and + data['expected_server'] == '192.168.10.10,1433' and + data['expected_host'] == 'atlas', 'Wrong Development SQL target') + user = pwd.getpwnam(cfg['migration_account']) + self.process = subprocess.Popen(['/usr/bin/dotnet', cfg['worker'], cfg['database_config']], + env=core.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() + + +class Development: + worker = DevelopmentWorker + + def configuration(self): + require(os.geteuid() == 0, 'Restricted sudo invocation required') + core.protected(CONFIG, secret=True) + cfg = load(CONFIG) + validate_target(cfg) + for name in ('root', 'evidence'): + core.protected(cfg[name], directory=True) + core.protected(Path(cfg['inbox']).parent, directory=True) + for name in ('releases', 'shared', 'deployment-receipts'): + core.protected(Path(ROOT) / name, directory=True) + for name in ('public_key', 'database_config', 'runtime_config', 'worker'): + core.protected(cfg[name], secret=name.endswith('config')) + for entry in Path(cfg['worker']).parent.rglob('*'): + core.protected(entry, directory=entry.is_dir()) + require(core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'User', '--value']) == cfg['runtime_account'], 'Development service user mismatch') + require(core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'WorkingDirectory', '--value']) == ROOT + '/current', 'Development service directory mismatch') + executable = core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'ExecStart', '--value']) + require('path=/usr/bin/dotnet ;' in executable and 'argv[]=/usr/bin/dotnet ' + ROOT + '/current/PlotLine.dll' in executable, 'Development executable mismatch') + require(core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'EnvironmentFiles', '--value']).split()[0] == cfg['runtime_config'], 'Development environment mismatch') + environment = core.command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'Environment', '--value']) + require(PERSISTENCE_ENV <= set(shlex.split(environment)), 'Development data-protection identity must remain stable') + return cfg + + def install(self, payload, destination, runtime_group): + core.install(payload, destination, runtime_group) + app = destination / 'app' + shared = Path(ROOT) / 'shared' + bindings = load(shared / 'bindings.json') + require(set(bindings) == {'App_Data', 'wwwroot/uploads', 'uploads', 'logs', 'Logs'}, 'Invalid persistent bindings') + for name, target in bindings.items(): + require(target.startswith('/srv/apps/plotdirector-dev/') or target == str(shared / name), 'Persistent path outside Development') + location = app / name + require(not location.exists() and not location.is_symlink(), 'Persistent path in package') + location.parent.mkdir(parents=True, exist_ok=True) + location.symlink_to(target, target_is_directory=True) + for config in sorted((shared / 'config').glob('appsettings*.json')): + core.protected(config, secret=True) + (app / config.name).symlink_to(config) + + +def main(): + os.umask(0o077) + signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(core.Refused('Development deployment timeout'))) + signal.alarm(7200) + args = sys.argv[1:] + if len(args) == 2 and args[0] == '--receipt': + require(os.geteuid() == 0, 'Restricted sudo invocation required') + identifier = safe_name(args[1]) + target = Path(ROOT) / 'deployment-receipts' / (identifier + '.json') + core.protected(target, secret=True) + print(canonical(load(target)).decode(), end='') + return + require(len(args) == 2 and args[0] in ('--validate', '--activate', '--rollback'), + 'Usage: deploy-plotdirector-development --validate|--activate|--rollback ') + core.activate(args[1], validate=args[0] == '--validate', rollback=args[0] == '--rollback', profile=Development()) + + +if __name__ == '__main__': + try: + main() + except Exception as error: + print('DEVELOPMENT DEPLOYMENT REFUSED: ' + core.public_error(error)) + sys.exit(1) diff --git a/Tools/Deployment/development_release.py b/Tools/Deployment/development_release.py new file mode 100644 index 00000000..86f615a0 --- /dev/null +++ b/Tools/Deployment/development_release.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Prepare, sign and admit code-only Development releases on Atlas; no Production access.""" +import argparse +import json +import os +from pathlib import Path +import shutil +import socket +import subprocess +import tempfile +from types import SimpleNamespace + +from release import require, load, file_digest, canonical, prepare + +BASELINE = Path('/var/lib/plotdirector-dev-deployment/baseline') +INBOX = Path('/var/lib/plotdirector-dev-deployment/incoming') +HELPER = '/usr/local/sbin/deploy-plotdirector-development' + + +def run(args, log): + with Path(log).open('w') as stream: + result = subprocess.run(args, stdout=stream, stderr=subprocess.STDOUT) + require(result.returncode == 0, 'Release check failed; see '+str(log)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', required=True) + parser.add_argument('--output', required=True) + parser.add_argument('--activate', action='store_true') + args = parser.parse_args() + require(socket.gethostname() == 'atlas' and os.geteuid() != 0, 'Run as the Atlas Development deployer') + os.umask(0o077) + source = Path(args.source).resolve() + output = Path(args.output).resolve() + require(not output.exists(), 'Use a fresh output directory') + commit = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip() + require(not subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip(), 'Clean committed source required') + baseline = load(BASELINE/'manifest.json') + changed_sql = subprocess.check_output(['git', '-C', str(source), 'diff', '--name-only', baseline['source_commit'], commit, '--', 'PlotLine/Sql'], text=True).strip() + require(not changed_sql, 'Schema changes require a separately reviewed/qualified migration plan') + require(baseline['starting_schema_sha256'] == baseline['resulting_schema_sha256'], 'Code-only Development baseline required') + output.mkdir(parents=True, mode=0o700) + release_id = 'development-'+commit[:12]+'-'+__import__('time').strftime('%Y%m%dT%H%M%SZ', __import__('time').gmtime()) + # Source SQL must still match every approved immutable historical script. + for step in baseline['migrations']: + candidate = source/'PlotLine/Sql'/step['file'] + if candidate.exists():require(file_digest(candidate) == step['sha256'], 'Historical SQL changed: '+step['file']) + signing = Path.home()/'.local/share/plotdirector-development/signing/private.pem' + require(signing.is_file() and signing.stat().st_mode & 0o077 == 0, 'Private Development signing key missing or exposed') + with tempfile.TemporaryDirectory(prefix='build-', dir=output) as work: + work = Path(work) + publish = work/'publish' + run(['dotnet', 'publish', str(source/'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId='+commit], output/'qualification-build.log') + run(['dotnet', 'run', '--project', str(source/'PlotLine.Tests/PlotLine.Tests.csproj')], output/'regression.log') + evidence = work/'evidence' + shutil.copytree(BASELINE/'evidence', evidence) + plan = {k:baseline[k] for k in ('starting_schema_sha256', 'resulting_schema_sha256', 'migrations', 'omitted_migrations', 'prerequisites', 'postconditions', 'qualification')} + plan['qualification'] = {'status':'passed', 'evidence':'evidence/development-code-only.json'} + (evidence/'development-code-only.json').write_bytes(canonical({ + 'status':'passed', 'source_commit':commit, 'application_dll_sha256':file_digest(publish/'PlotLine.dll'), + 'starting_schema_sha256':plan['starting_schema_sha256'], 'resulting_schema_sha256':plan['resulting_schema_sha256'], + 'checks':['clean-committed-source', 'unchanged-reviewed-sql', 'release-publish', 'full-regression-harness'], + 'target':'Development on Atlas only', 'production_access':False, + })) + plan_file = output/'plan.json' + plan_file.write_bytes(canonical(plan)) + prepare(SimpleNamespace(source=str(source), plan=str(plan_file), sql=str(BASELINE/'sql'), evidence=str(evidence), + output=str(output/'bundle'), release_id=release_id, signing_key=str(signing), compression='none', scope_base=baseline['source_commit'])) + # Unprivileged submission; privileged helper snapshots and verifies it again. + destination = INBOX/release_id + require(not destination.exists(), 'Release identifier already submitted') + shutil.copytree(output/'bundle', destination) + result = subprocess.run(['sudo', '-n', HELPER, '--validate', release_id]) + require(result.returncode == 0, 'Development validation refused') + if args.activate: + result = subprocess.run(['sudo', '-n', HELPER, '--activate', release_id]) + require(result.returncode == 0, 'Development activation refused; inspect protected receipt') + (output/'submission.json').write_bytes(canonical({'release_id':release_id, 'source_commit':commit, 'operation':'activate' if args.activate else 'validate', 'target':'Development'})) + print(json.dumps({'release_id':release_id, 'source_commit':commit, 'status':'activated' if args.activate else 'validated'})) + + +if __name__ == '__main__': + try:main() + except Exception as error: + from activate import public_error + print('Development release refused: '+public_error(error));raise SystemExit(1) diff --git a/Tools/Deployment/provision/development.py b/Tools/Deployment/provision/development.py new file mode 100644 index 00000000..74f67353 --- /dev/null +++ b/Tools/Deployment/provision/development.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""One-time Atlas provisioning, using the last verified Development package. Never contacts Production.""" +import argparse +import grp +import json +import os +from pathlib import Path +import pwd +import shutil +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import activate as core +import development as dev +from release import require, load, verify_bundle, canonical, file_digest + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('deployment-user', 'database-config', 'worker', 'previous-package', 'previous-public-key', 'public-key'): + parser.add_argument('--'+name, required=True) + args = parser.parse_args() + require(os.geteuid() == 0 and __import__('socket').gethostname() == 'atlas', 'Atlas administrator required') + os.umask(0o077) + require(not dev.CONFIG.exists() and not Path(dev.ROOT).exists(), 'Already provisioned; refuses overwrite') + db = load(args.database_config) + require(db['database'] == 'PlotDirector_Development' and db['expected_server'] == '192.168.10.10,1433' and db['expected_host'] == 'atlas', 'Wrong Development database') + operator = pwd.getpwnam(args.deployment_user) + require(operator.pw_uid != 0, 'Non-root deployment user required') + for group in ('plotdirector-dev-deploy', 'plotdirector-dev-migrate'): + if not any(g.gr_name == group for g in grp.getgrall()): + subprocess.run(['/usr/sbin/groupadd', '--system', group], check=True) + if not any(p.pw_name == 'plotdirector-dev-migrate' for p in pwd.getpwall()): + subprocess.run(['/usr/sbin/useradd', '--system', '--gid', 'plotdirector-dev-migrate', '--no-create-home', '--shell', '/usr/sbin/nologin', 'plotdirector-dev-migrate'], check=True) + subprocess.run(['/usr/sbin/usermod', '-aG', 'plotdirector-dev-deploy', args.deployment_user], check=True) + deploy_gid = grp.getgrnam('plotdirector-dev-deploy').gr_gid + migrate_gid = grp.getgrnam('plotdirector-dev-migrate').gr_gid + runtime_gid = grp.getgrnam('plotdirector').gr_gid + + def directory(path, group=0, mode=0o750): + path = Path(path);path.mkdir(parents=True, exist_ok=True) + os.chown(path, 0, group);path.chmod(mode) + return path + + def write(path, data, group=0, mode=0o640): + path = Path(path);path.write_bytes(data);os.chown(path, 0, group);path.chmod(mode) + + directory('/etc/plotdirector-development', mode=0o755) + write(dev.CONFIG, canonical(dev.FIXED), mode=0o600) + write(dev.FIXED['database_config'], canonical(db), migrate_gid) + write(dev.FIXED['public_key'], Path(args.public_key).read_bytes(), mode=0o644) + lib = directory('/usr/local/lib/plotdirector-dev-deployment', mode=0o755) + tools = Path(__file__).resolve().parents[1] + for name in ('activate.py', 'release.py', 'receipt.py', 'transport.py', 'development.py'): + write(lib/name, (tools/name).read_bytes(), mode=0o644) + worker = directory(lib/'database', mode=0o755) + for source in Path(args.worker).rglob('*'): + require(not source.is_symlink(), 'Worker symlink refused') + target = worker/source.relative_to(args.worker) + if source.is_dir():directory(target, mode=0o755) + else:write(target, source.read_bytes(), mode=0o644) + write('/usr/local/sbin/deploy-plotdirector-development', (tools/'deploy-plotdirector-development').read_bytes(), mode=0o755) + rule = b'%plotdirector-dev-deploy ALL=(root) NOPASSWD: /usr/local/sbin/deploy-plotdirector-development *\n' + staged = Path('/etc/sudoers.d/.plotdirector-development.pending') + write(staged, rule, mode=0o440) + subprocess.run(['/usr/sbin/visudo', '-cf', str(staged)], check=True, stdout=subprocess.DEVNULL) + staged.rename('/etc/sudoers.d/plotdirector-development') + root = directory(dev.ROOT, runtime_gid, 0o751) + directory(root/'releases', runtime_gid) + directory(root/'deployment-evidence') + directory(root/'deployment-receipts', deploy_gid) + write(root/'deployment.lock', b'', mode=0o600) + state = directory('/var/lib/plotdirector-dev-deployment', deploy_gid, 0o751) + directory(state/'incoming', deploy_gid, 0o2770) + shared = directory(root/'shared', runtime_gid) + config = directory(shared/'config', runtime_gid) + old = Path('/srv/apps/plotdirector-dev/current') + require(old.is_dir() and not old.is_symlink(), 'Unexpected legacy Development layout') + for source in old.glob('appsettings*.json'): + write(config/source.name, source.read_bytes(), runtime_gid) + require(list(config.glob('appsettings*.json')), 'Development application configuration missing') + bindings = {} + for name in ('App_Data', 'wwwroot/uploads', 'uploads', 'logs', 'Logs'): + source = old/name + if source.is_dir():bindings[name] = str(source.resolve()) + else: + path = shared/name + path.mkdir(parents=True, exist_ok=True) + os.chown(path, pwd.getpwnam('plotdirector').pw_uid, runtime_gid);path.chmod(0o750) + bindings[name] = str(path) + write(shared/'bindings.json', canonical(bindings), runtime_gid) + # Verify the previous signed Development package and its real database history + # before deriving the initial current link or any reusable admission plan. + with tempfile.TemporaryDirectory(prefix='.provision-', dir=root) as work: + os.chmod(work, 0o750);os.chown(work, 0, migrate_gid) + manifest, auth, payload = verify_bundle(args.previous_package, work, args.previous_public_key) + require(file_digest(old/'PlotLine.dll') == manifest['files']['app/PlotLine.dll'], 'Previous package does not match running Development') + for entry in (payload, *payload.rglob('*')): + os.chown(entry, 0, migrate_gid);entry.chmod(0o750 if entry.is_dir() else 0o640) + session = dev.DevelopmentWorker(dev.FIXED) + try: + begin = session.call('begin', package_root=str(payload), deployment_id='dev-provision-validation', package_sha256=auth['package_sha256']) + require(begin['complete'], 'Incomplete Development history') + previous = begin['history']['latest_successful_release'] + require(previous['source_commit'] == manifest['source_commit'], 'Previous Development release identity mismatch') + destination = root/'releases'/manifest['release_id'] + dev.Development().install(payload, destination, 'plotdirector') + core.switch(root, destination/'app', 'provision') + write(root/'active-deployment.json', canonical({'deployment': previous['deployment_identifier'], 'release': manifest['release_id'], 'package_sha256':auth['package_sha256']})) + baseline = directory(state/'baseline', deploy_gid) + # The package was verified above. Copy only immutable reviewed plan data. + for area in ('sql', 'evidence'): + target = baseline/area + shutil.copytree(payload/area, target) + write(baseline/'manifest.json', (payload/'manifest.json').read_bytes(), deploy_gid) + for entry in baseline.rglob('*'): + os.chown(entry, 0, deploy_gid);entry.chmod(0o750 if entry.is_dir() else 0o640) + finally:session.close() + # Reload changes the configured target, but does not restart the running app. + directory('/etc/systemd/system/plotdirector-dev.service.d', mode=0o755) + write('/etc/systemd/system/plotdirector-dev.service.d/manifest-target.conf', + ('[Service]\nWorkingDirectory='+dev.ROOT+'/current\nExecStart=\nExecStart=/usr/bin/dotnet '+dev.ROOT+'/current/PlotLine.dll\n'+''.join('Environment='+value+'\n' for value in sorted(dev.PERSISTENCE_ENV))).encode(), mode=0o644) + subprocess.run(['/usr/bin/systemctl', 'daemon-reload'], check=True) + print('Development profile provisioned; running service untouched. Validate and activate a signed Development release next.') + + +if __name__ == '__main__': + try:main() + except Exception as error: + print('Development provisioning refused: '+core.public_error(error));sys.exit(1) diff --git a/Tools/Deployment/test_development.py b/Tools/Deployment/test_development.py new file mode 100644 index 00000000..a27ba4df --- /dev/null +++ b/Tools/Deployment/test_development.py @@ -0,0 +1,87 @@ +import copy +import unittest +from unittest.mock import patch + +import activate +import development +from release import Refused + + +class DevelopmentBoundaryTests(unittest.TestCase): + def test_atlas_target_is_fixed(self): + with patch.object(development.socket, 'gethostname', return_value='atlas'): + development.validate_target(copy.deepcopy(development.FIXED)) + + def test_every_target_field_is_enforced(self): + with patch.object(development.socket, 'gethostname', return_value='atlas'): + for key in development.FIXED: + wrong = copy.deepcopy(development.FIXED) + wrong[key] = 'unexpected' + with self.subTest(key=key), self.assertRaises(Refused): + development.validate_target(wrong) + + def test_refuses_production_host(self): + with patch.object(development.socket, 'gethostname', return_value='web1'): + with self.assertRaises(Refused): + development.validate_target(development.FIXED) + + def test_missing_and_extra_configuration_refused(self): + for cfg in ({}, {**development.FIXED, 'hook': '/bin/sh'}): + with self.assertRaises(Refused): + development.validate_target(cfg) + + def test_sql_target_mismatch_never_launches_worker(self): + with patch.object(development.socket, 'gethostname', return_value='atlas'), \ + patch.object(activate, 'protected'), \ + patch.object(development, 'load', return_value={'database': 'PlotLine', 'expected_server': '127.0.0.1,1433', 'expected_host': 'web1'}), \ + patch.object(development.subprocess, 'Popen') as process: + with self.assertRaises(Refused): + development.DevelopmentWorker(development.FIXED) + process.assert_not_called() + + def test_explicit_development_activation_dispatch(self): + for operation in ('validate', 'activate', 'rollback'): + with self.subTest(operation=operation), \ + patch.object(development.sys, 'argv', ['helper', '--'+operation, 'fixture']), \ + patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \ + patch.object(development.signal, 'alarm'), patch.object(activate, 'activate') as run: + development.main() + self.assertEqual(run.call_args.args, ('fixture',)) + self.assertIsInstance(run.call_args.kwargs['profile'], development.Development) + self.assertEqual(run.call_args.kwargs['validate'], operation == 'validate') + self.assertEqual(run.call_args.kwargs['rollback'], operation == 'rollback') + + def test_implicit_activation_is_refused(self): + with patch.object(development.sys, 'argv', ['helper', 'fixture']), \ + patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \ + patch.object(development.signal, 'alarm'), patch.object(activate, 'activate') as run: + with self.assertRaises(Refused): + development.main() + run.assert_not_called() + + def test_service_must_preserve_existing_cookie_identity(self): + def command(args, **kwargs): + prop = args[args.index('-p')+1] + return {'User':'plotdirector', 'WorkingDirectory':development.ROOT+'/current', + 'ExecStart':'path=/usr/bin/dotnet ; argv[]=/usr/bin/dotnet '+development.ROOT+'/current/PlotLine.dll', + 'EnvironmentFiles':development.FIXED['runtime_config']+' (ignore_errors=no)', + 'Environment':self.environment}[prop] + with patch.object(development.socket, 'gethostname', return_value='atlas'), \ + patch.object(development.os, 'geteuid', return_value=0), \ + patch.object(activate, 'protected'), patch.object(activate, 'command', side_effect=command), \ + patch.object(development, 'load', return_value=development.FIXED): + for missing in development.PERSISTENCE_ENV: + self.environment = ' '.join(development.PERSISTENCE_ENV-{missing}) + with self.subTest(missing=missing), self.assertRaises(Refused): + development.Development().configuration() + self.environment = ' '.join(development.PERSISTENCE_ENV) + self.assertEqual(development.Development().configuration(), development.FIXED) + + def test_production_configuration_path_is_unchanged(self): + self.assertEqual(str(activate.CONFIG), '/etc/plotdirector-deployment/target.json') + self.assertNotEqual(development.CONFIG, activate.CONFIG) + self.assertNotEqual(development.FIXED['root'], '/srv/plotdirector') + + +if __name__ == '__main__': + unittest.main()