Introduce manifest-driven release activation and transactional deployment history

This commit is contained in:
Nick Beckley 2026-11-25 14:04:51 +00:00
parent 643f28c4f9
commit 05a689c202
33 changed files with 16683 additions and 1 deletions

View File

@ -1,5 +1,11 @@
# PlotDirector Database Operations
Deployable SQL now uses the [manifest/history standard](../Deployment/Production.md)
and `Tools/Deployment/DatabaseWorker`, shared by Development, Test and Production.
Do not bypass successful migration history with ad-hoc sqlcmd execution. Adopt an
existing database only through a verified current-state baseline; historical
execution is not inferred. See the [reviewed recovered-Production plan](../Deployment/ProductionUpgrade-20261125.plan.json).
Read this document only when the current task requires database inspection, SQL migration, schema work or direct development-database access.
## Environment

View File

@ -1,5 +1,14 @@
# 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.
Read this document only when deployment or detailed development-service operation is part of the task.
## Environment

View File

@ -0,0 +1,160 @@
# Production migration Phase 1 — 25 November 2026
Status at the implementation commit: **qualification in progress; no Production
deployment authorised**. Final evidence is recorded separately after clean-commit
qualification. Do not treat a draft plan or prototype rehearsal as release approval.
## Source and installed Development baseline
Repository HEAD at discovery was `643f28c4f99c72056b5a66a54398a0c7edd4847b`,
an evidence-only descendant of implementation
`f3c3683bc24674914b5d52499efa9b8e743615a5`. Current Development DLL and archive
`character-overview-f3c3683b-20261123T223506Z` both hash to
`0659e7aa4988516e3955ba33b120330cb039cdd154c2413a059fd6cab5195e27`.
No newer installed build was found. Historical regression evidence reports 816
application checks, authenticated browser acceptance and provenance preservation.
Implementation is on an isolated worktree/branch so the pre-existing untracked
canonical-manuscript assessment and Context workspace audit are preserved. The
qualified candidate must include this phase's tooling, migrations 318/319 and
deployment-only application changes, built from its own clean commit.
## Independently verified web1 inventory
Strict SSH used the supplied dedicated identity and recorded ED25519 fingerprint.
Administrator currently has passwordless administrative sudo. No remote changes
were made. OS is Ubuntu 24.04.5 LTS. Both .NET/ASP.NET Core runtimes are 10.0.15;
no SDK is listed. Approximately 21 GiB RAM was available, with 4 GiB swap and
555 GiB free on the root volume at inspection.
Native SQL Server reports 17.0.5065.9, Express Edition. It binds loopback 1433;
configuration limits memory to 4096 MiB, disables SQL Agent and sets backup directory
`/srv/backups/sql`. PlotLine is ONLINE, compatibility 170, SIMPLE recovery, owned by
sa; data/log allocations are 200/264 MiB. The backup service's SQL principal has
db_backupoperator. Its metadata visibility is limited: a complete live login/user
and permissions inventory still requires a SQL security administrator or appropriate
VIEW DEFINITION/server-security visibility. Do not infer absence of an application
login/user from that restricted view. The recovered backup contains PlotLineApp as
an orphaned user on Atlas, as expected for a restore to another server.
The hourly `sql-backup.timer` invokes a root-owned 0750 script with a root-protected
credentials file; it backs up both PlotLine and CatherineLynwood with CHECKSUM to
new timestamped 0600 files. It is not changed by the new deployment tooling.
Existing backups, including the original recovered media, were not overwritten.
`catherinelynwood.service`, Nginx, SQL Server and Fail2ban were active. Catherine
runs as catherinelynwood from `/srv/catherinelynwood/current` on 127.0.0.1:5002 with
its own environment file, enabled virtual host and certificate. Ports 5001/5003
were free. UFW allows SSH/HTTP/HTTPS; SQL is not publicly listening. PlotDirector
has no enabled virtual host, certificate or loaded application service yet.
Fontconfig, FreeType, ICU 74 and libstdc++ are present; final native-library loading
on web1 remains a Phase 2 smoke check.
Existing PlotDirector layout differs from the protected target: root/release
directories are administrator-owned; shared uploads and key directories exist;
logs are currently top-level; `/etc/plotdirector` is empty. The runtime account
exists; deployment/migration accounts do not. The planned helper deliberately
refuses this unprovisioned state. No ownership, accounts or services were changed.
Recovered private archives in `/home/administrator` contain uploads and the old
environment file, service definition and two Data Protection key files. The config
archive does not include appsettings.json. Shared configuration must be reconciled
with the old effective configuration during provisioning. `/srv/backups/{websites,
configuration}` existed but contained no files at inspection.
Atlas's default SSH include `/etc/ssh/ssh_config.d/20-systemd-ssh-proxy.conf` is
root-owned mode 0777, causing OpenSSH's ownership/permissions refusal. `-F /dev/null`
avoids it. No system-wide SSH configuration was modified.
## Old Production and recovered baseline
www remains inactive and unchanged. Installed helper and DLL still match the
November archived hashes; release commit is
`5d2e080539c10c3a2c6aed5c18c169abc8a55e77`. The installed November helper, not the
September README, informed preservation, active-work, backup, failure and SQL rules.
Original recovered media: `web1:/srv/backups/sql/PlotLine-20261124.bak`, 198261248
bytes, SHA-256
`6cf9e6d4d340a222a48c43265582e45a0150b132ae6eeb2bb6cd112f97cb743c`.
It was read over SSH into mode-0700 private Atlas storage, with matching source and
local checksums. It passed VERIFYONLY and actual isolated restores to the existing
Atlas SQL Server 2025 container (17.0.4006.2 Developer Edition). Production data was
never used as a live migration test target.
There is no existing migration/release ledger in the restored copy. The original
schema has 163 tables and 659 modules. Historical comparison found 642 literal
module matches, eight comment-only differences, one migration-160 dynamic patch
and one trigger deliberately removed by 125. Eight additional modules are SSMS
diagram support, retained without inventing PlotDirector migration identities.
The stored active Problem Solver graph exactly matches the archived non-numeric
publication script's UTF-16 SHA-256. Historical scripts before 208 are unchanged
between 5d2e080 and the selected source baseline.
[Baseline evidence](ProductionBaseline-20261125.json) distinguishes a verified
cumulative final-state baseline from proof that an individual historical script
executed. Baseline UTC is the actual verification time. [The explicit ordered
plan](ProductionUpgrade-20261125.plan.json) records individual identities/checksums,
dependencies, baseline evidence, prerequisites and postconditions.
Important ordering/classification decisions:
- 253 → **255 → 254** → 256, as documented in the geography implementation report.
The first exploratory numeric rehearsal demonstrated the 254 truncation and a
complete rollback of that script/history record. No automatic retry was made.
- 301/302/303 are superseded by the standalone complete 304 definition; 302 also
contains a known syntax error. Their files are preserved, never rewritten.
- 286 refreshes Development reset procedures and is inapplicable to Production.
Old reset definitions remain untouched; no reset procedure is executed.
- 318 bootstraps history before recording historical baselines; 319 supplies the
local application's stored-procedure health probe. Neither changes business rows.
- SQL performance/inline-SQL improvements are carried by 283–285, 287–289 and later
included migrations. No blanket index maintenance or speculative tuning is added.
## Architecture and qualification evidence
See [the operational standard](Production.md) and `Tools/Deployment` for release
preparation, Ed25519 authorisation, restricted transfer, root-owned activation,
transactional history, versioned installation, atomic switching, health, evidence
and rollback. Provisioning examples are prepared but not installed on web1.
Exploratory fresh-copy upgrades established the migration sequence, exact original
business-data preservation and reproducible schema. Those rehearsals are not the
final clean-commit qualification. Private data fingerprints cover all original
columns, IDs, content, revision/synchronisation metadata and asset references in
all 163 tables (139554 rows). New columns are excluded from old-column comparison
so defaults cannot hide a change to existing data. No row content is published.
Actual SQL failure checks verify replay prevention, changed historical checksum,
incorrect baseline, missing prerequisite and competing-session lock rejection.
Filesystem/service-boundary tests cover package/signature/path/link integrity,
space, backup verification, migration failure, installation permissions, HTTP
failure and failed history recording. Service operations in these failure tests
are mocked; they do not qualify web1's uninstalled service or Nginx configuration.
The final test-only host requires an isolated SQL database/login, a private request
token and loopback binding; it verifies the actual application DLL hash. All app
background services and external HTTP clients are disabled. Real SMTP, Stripe and
OpenAI credentials are absent. Clone-only test authentication is in the test tool,
not the deployed web application. Read-only clone requests supplement existing
authentication/browser regression evidence; they are not a claim of physical Word
or external-payment/email acceptance.
Application changes are limited to stable configurable Data Protection identity,
trusted-loopback forwarded headers and the loopback deployment health endpoint.
The health endpoint returns only binary/database identity and fails closed without
leaking connection/SQL diagnostics. Existing Writer/Context/Companion functionality
is retained. Synthetic key-ring tests establish the content-root discriminator and
cross-root explicit identity behaviour; no real historical cookie is claimed valid.
## Remaining gates before Production
Final readiness requires a clean-commit signed package, two complete fresh-copy
upgrades using the final worker, regression/HTTP/failure results and a matching
qualified DLL/evidence identity. Phase 2 then provisions accounts, trust, ownership,
SQL permissions/mappings, shared data/secrets, service and independent TLS/vhost,
verifies the live starting fingerprint, and obtains explicit activation authority.
Actual web1 login permissions, its initial service, certificate, public HTTPS,
Catherine coexistence after later configuration changes, physical Windows Word
behaviour and real-cookie continuity remain deployment/cutover checks. Production
configuration, databases, files, services, firewall and DNS remain unchanged.

View File

@ -0,0 +1,263 @@
# PlotDirector production deployment standard
This procedure separates Atlas preparation, immutable transfer and restricted
activation. Phase 1 does not authorise installing it or activating PlotDirector on
web1. Consult [Phase 1 qualification](Phase1-20261125.md) before Phase 2.
## Trust and environment boundaries
- Build only on Atlas, from a clean, committed worktree. Keep source, SDKs and
development tooling off web1. Use framework-dependent .NET 10 releases.
- `administrator` provisions the server; `plotdirector-deploy` transfers approved
releases and invokes one fixed activation command; `plotdirector` runs the app.
- A separate `plotdirector-migrate` system identity reads the migration connection
configuration. The runtime and transfer accounts must not read it.
- The root-owned helper, Python modules, database-worker binaries/dependencies,
target configuration and release-verification public key are outside releases.
Neither runtime nor transfer identities may write any ancestor of these files.
- Release signing is independent of deployment SSH. Keep the signing private key
on Atlas under an approved secret-management process, mode 0600 inside a 0700
directory. Do not place it on web1 or share it with the transfer account.
- The manifest cannot select shell hooks, executables, service names, destinations
or health URLs. Target paths/service/endpoint come from protected configuration.
- Administrator access in this phase is temporary. Remove the specific temporary
authorised key only after restricted deployment access has passed verification.
Production: `web1`, `85.190.124.132`, SQL `PlotLine`, Kestrel loopback 5001.
Catherine Lynwood remains on 5002; 5003 remains reserved. No default Nginx site,
Catherine service/configuration, SQL database or firewall change is part of a
PlotDirector release.
Atlas SSH must use `-F /dev/null -o IdentitiesOnly=yes -o HostKeyAlgorithms=ssh-ed25519
-o StrictHostKeyChecking=yes -o UpdateHostKeys=no` with the dedicated identity.
Verified host fingerprint: `SHA256:4X54DW85/3J/iGU7ECfRkbMn0n13gVPbpRnvtcZfn/0`.
The bypass is required because Atlas's system SSH include is mode 0777. Repair of
that system-wide configuration is separate work, not part of this migration.
## Release preparation and approval
Tool location: `Tools/Deployment`. Publish the database worker separately during
initial provisioning; the privileged helper never executes package binaries.
1. Select a full source SHA and create a clean worktree. Preserve unrelated work.
2. Review the database state and explicit ordered plan. Do not infer history from
a numeric maximum or replay the SQL directory. Retain script hashes forever.
3. Restore the recovered backup into uniquely named isolated SQL databases.
Qualify the complete plan twice from fresh copies. Keep original backups.
4. Verify business fingerprints, integrity, SQL contracts, real app startup and
feature evidence. Disable all background workers and substitute credentials
before starting a clone application. Never load a production connection string.
5. Save a sanitised evidence directory and a plan with qualification status passed.
It must identify the actual source/build hashes and the two fresh-copy results.
6. Prepare and sign on Atlas:
```bash
python3 Tools/Deployment/release.py prepare \
--source /absolute/clean/worktree \
--plan /absolute/reviewed-plan.json \
--sql /absolute/reviewed-sql-input \
--evidence /absolute/sanitised-evidence \
--output /absolute/new-release-bundle \
--release-id FULLY-QUALIFIED-UNIQUE-ID \
--signing-key /absolute/private/release-signing.pem
python3 Tools/Deployment/release.py verify /absolute/new-release-bundle \
--public-key /absolute/trusted-release-signing-public.pem
```
`authorization.json` binds the source SHA, release ID, complete uncompressed tar
SHA-256 and manifest SHA-256. Its Ed25519 signature is verified against the
administrator-installed trust anchor. The manifest indexes every application,
SQL and sanitised evidence file. The application checksum covers its canonical
file index. Package version must match `PlotLine.deps.json`.
Preparation excludes appsettings, environment files, persistent directories and
local tools configuration. Secrets must be provisioned separately. Evidence must
never contain recovered rows, connection strings, key files or diagnostic dumps.
Private qualification artifacts stay outside Git, under restricted Atlas storage.
## Migration and release history
Migration 318 introduces `dbo.DatabaseMigrationHistory` and
`dbo.ApplicationReleaseHistory`. There is no administration UI.
- Identity is a unique script identity, including historical non-numeric scripts.
Filenames, SHA-256, current recorded UTC, deployment ID and execution duration
are stored. `Baselined` rows contain an evidence reference and no duration.
Baseline time means verification/recording time, never an invented execution time.
- A historical final-state baseline does not assert that every original script
executed. Superseded effects must be explained in its evidence. Unknown effects
remain unresolved and block approval; do not label them applied.
- A checksum mismatch against history blocks before backup or shutdown. Recorded
scripts are skipped; dependencies must be explicit and ordered. An unknown
recorded identity blocks a plan that does not account for it.
- One SQL session holds `sp_getapplock` through migration, startup, health and
release recording. A protected filesystem lock additionally prevents concurrent
activation on the same host. A disconnected SQL session releases its lock.
- Each transactional script, its postconditions and its successful history insert
commit together. Error rolls back the current script and its history row. Earlier
committed scripts remain. No automatic retry or database rollback is attempted.
- This version refuses non-transactional scripts. Such a change requires an
explicitly reviewed manual execution/recovery procedure before release approval;
it must not be disguised as transactional or silently retried.
- A completed plan is accepted again only with the exact final schema and all
matching history. It does not reapply completed SQL. Code-only releases retain
the full known history and have no unrecorded execute steps; they still receive
an activation history row after health checks.
- Successful activation history contains a new deployment ID, release/version,
source SHA, package hash, manifest hash, server UTC and evidence reference.
`ActivationKind` distinguishes Deploy/Rollback and links the preceding successful
deployment. Failure attempts belong in protected JSONL evidence, never successful
activation history.
`ApplicationReleaseHistory` is an append-only account of successful activations,
not a promise that its last row is currently running. Determine current state by
checking the service, resolved `current` symlink, installed hashes, root-owned
`active-deployment.json`, SQL history and attempt evidence together. A crash between
SQL recording and the filesystem marker requires operator reconciliation.
The same manifest, history schema, database worker and qualification rules apply
to Development and Test. A different environment gets its own explicit schema
baseline, SQL identity and protected target configuration; never copy a production
connection string. Adoption in Development must back up/verify its own database,
check active work and baseline its actual current state. Do not run the legacy
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
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.
After independent Phase 2 authorisation:
```bash
python3 Tools/Deployment/transfer.py /absolute/bundle \
--identity /home/nick/.ssh/plotdirector-production
```
Use the verified SSH options above with `plotdirector-deploy@85.190.124.132` and
remote command `validate RELEASE-ID`, then `activate RELEASE-ID`.
Validation takes private snapshots, checks signature/archive/index/version,
target identity, exact schema, history, prerequisites and active work. It creates
protected validation evidence and takes locks; it does not back up, migrate or
operate the service. Archive members must be regular files, bounded in size/count,
with no traversal, duplicate paths, links, special files or extra content.
Activation reserves space, creates a unique COPY_ONLY/CHECKSUM backup, executes
RESTORE VERIFYONLY before stopping the service, rechecks active work, stops and
requires inactive state, then runs SQL. It installs a new root-owned release and
atomically replaces `current`. It starts the service and checks local root/login
HTTP, binary identity and database postconditions before recording success.
Backups are not overwritten. VERIFYONLY is useful but is not a restore rehearsal;
the isolated restore qualifications provide separate evidence. The existing hourly
backup timer continues independently and is not a substitute for pre-deploy backup.
Any migration/install/startup/health/history error leaves or requests the service
stopped, retains artifacts and records the failure phase. The symlink may point at
a failed candidate after activation begins; never assume it still identifies the
last successful release. A root process kill or machine failure can interrupt this
sequence: inspect evidence and ledger before any recovery action.
For application rollback, qualify old binaries against the **current** database,
issue a new signed release ID with no outstanding SQL, and request `rollback ID`.
The helper refuses rollback if any migration is unrecorded. Health must pass before
a new Rollback history row is inserted. A SQL rollback is a separately authorised
restore/recovery operation; never replace a database automatically.
## Phase 2 initial provisioning (administrator only; not executed in Phase 1)
Review existing files and take uniquely named configuration backups first. Keep
Catherine's service, virtual host, certificate, data and database unchanged.
1. Verify OS/runtime/native dependencies, trusted SSH fingerprint, free ports and
backup health again. Confirm web1's live schema matches the qualified starting
fingerprint; additional changes require fresh qualification.
2. Provision `plotdirector-deploy` with `/bin/sh` and a locked password; provision
`plotdirector-migrate` as a system account with `/usr/sbin/nologin`. Reuse the
existing `plotdirector` runtime account. Do not grant either new account access
to Catherine's groups or add them to sudo/adm/docker groups.
3. Create protected directories with these exact ownership/mode requirements:
| Path | Owner | Mode |
| --- | --- | --- |
| `/srv/plotdirector` | root:root | 0755 |
| `/srv/plotdirector/releases` | root:root | 0755 |
| `/srv/plotdirector/incoming` | root:plotdirector-deploy | 0730 |
| `/srv/plotdirector/deployment-evidence` | root:root | 0700 |
| `/srv/plotdirector/deployment.lock` (empty regular file) | root:root | 0600 |
| `/srv/plotdirector/shared/{uploads,logs}` | plotdirector:plotdirector | 0750 |
| `/srv/plotdirector/shared/.aspnet/DataProtection-Keys` | plotdirector:plotdirector | 0700 |
| `/etc/plotdirector` | root:plotdirector | 0750 |
| `/etc/plotdirector/plotdirector.env` | root:plotdirector | 0640 |
| `/etc/plotdirector-deployment` | root:plotdirector-migrate | 0750 |
| `/etc/plotdirector-deployment/database.json` | root:plotdirector-migrate | 0640 |
| target JSON and public verification key | root:root | 0600 / 0644 |
Do not recursively change existing shared data or `/srv/backups`. Preserve the
recovered archives. Migrate any existing top-level logs into shared storage
without replacing existing files. No deployed release directory may be writable
by runtime or transfer identities. New release files are root:plotdirector 0440,
directories 0750. Application files execute only through the unprivileged service.
4. Publish `DatabaseWorker.csproj` on Atlas. Administrator installs the entire
framework-dependent output under `/usr/local/lib/plotdirector-deployment/database`
root:root, directories 0755/files 0644. Install `activate.py`, `release.py` and
`ssh_dispatch.py` in the parent root-owned directory (0755; dispatcher executable).
Install `deploy-plotdirector` as `/usr/local/sbin/deploy-plotdirector`, root 0755.
Review every installed file/hash; no source repository or SDK is needed on web1.
5. Copy reviewed `provision/target.example.json` to the target JSON location.
Provision the independent approved signing public key. Create `database.json`
privately with `database`, `connection`, `expected_host` and `expected_server`
properties, using database PlotLine, host web1, server `127.0.0.1,1433` and a
dedicated migration SQL login targeting local native SQL Server.
Use a secure prompt/secret manager; never put its connection string in commands,
reports, Git or a package.
6. A SQL administrator must create/reconcile server logins and restored user SIDs.
Runtime login: PlotLine-only user, required EXECUTE on reviewed application
procedures, metadata visibility on the two history tables for the fixed health probe, no server role, no db_owner or direct migration/history-write rights.
Migration login: db_owner **only in PlotLine** for reviewed DDL/backup work;
direct CREATE ANY DATABASE permission is needed by SQL Server for VERIFYONLY ([Microsoft permission reference](https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-verifyonly-transact-sql?view=sql-server-ver17)).
Do not use dbcreator (which grants broader powers), sysadmin, the hourly backup
credential or the application credential for migration. It must have no user or
elevated permissions in CatherineLynwood. Review existing PUBLIC/cross-database
permissions. A future certificate-signed fixed verification procedure can narrow
the server permission further; that is not silently assumed installed.
7. Recover uploads and keys separately, validating archive paths/link types before
copying, preserving originals and checking file hashes. Configure absolute
`Storage__UploadsRoot` and `DataProtection__KeysPath` to shared directories.
Provision SMTP/Stripe/OpenAI settings and other qualified-build settings outside
releases. The recovered configuration archive does not contain appsettings.json;
reconcile the old effective settings explicitly, including Site/Admin and feature
flags, rather than assuming environment-only recovery is complete.
8. Data Protection's default application identity depends on the content root.
A versioned release changes that root unless pinned. The application now supports
`DataProtection__ApplicationName`; choose an explicitly reviewed stable identity
and keep it unchanged across releases. Historical root was `/var/www/plotdirector`.
Test old key purposes/discriminator before claiming cookie or encrypted-payload
continuity. Copying XML keys alone does not establish compatibility. Phase 1 does
not claim a real historical authentication cookie was successfully replayed.
9. Install the reviewed service template; do not start it. Run systemd verification
and check its account, environment path, content root, writable paths and loopback
endpoint. Install the reviewed sudoers fragment only after `visudo -cf` passes;
validate the whole sudo configuration. Install the forced-command SSH Match block
only after `sshd -t` passes. Keep an administrator session open during SSH reload.
10. Put the dedicated deployment public key in the root-owned authorised-keys file
named by the Match block, with `restrict` and an appropriate verified Atlas
source-address restriction where operationally stable. Verify upload/validate,
shell and SFTP refusal, forwarding refusal, no general sudo, helper/config
non-writability and no access to Catherine. Then remove **only** the temporary
Atlas administrator key authorisation. Do not remove other administration access.
11. Provision PlotDirector's own certificate and reviewed virtual host/map templates.
Existing DNS still targeting www will affect certificate issuance; select an
explicitly authorised challenge/certificate-transfer approach. Run `nginx -t`;
verify Catherine before and after any later reload. Preserve ports 5002/5003.
Test HTTPS using `--resolve` and normal certificate validation before DNS cutover.
12. Activate only after Phase 2 approval and a verified starting-state/backup check.
Run authenticated feature, upload, image, Word/SignalR and account checks before
separately authorised DNS changes. Keep www inactive and unchanged as fallback.
No provisioning, remote transfer, production migration, service start, Nginx reload
or DNS change in this document is authorised merely by completing Phase 1.

View File

@ -0,0 +1,47 @@
{
"historical_application_commit": "5d2e080539c10c3a2c6aed5c18c169abc8a55e77",
"recovered_backup_sha256": "6cf9e6d4d340a222a48c43265582e45a0150b132ae6eeb2bb6cd112f97cb743c",
"starting_schema_sha256": "1eaa17d39bfdc2542743d6e911659141466f0bdf4efbeb62fb76b958ddd03c21",
"semantics": "Baselined at current verification time against cumulative final schema/data state. Individual historical execution is not asserted. No fabricated original timestamps. Module checks use preserved final definitions, including documented supersession.",
"literal_modules_reviewed": 652,
"literal_matches_initial": 642,
"differences_explained_by_comments": 8,
"dynamic_patch": "160_Phase25E_ProjectHardDeleteDependencyCleanup.sql updates ProjectHardDelete_ForOwner",
"removed_trigger": "125_Phase20AE_RemoveDefaultScenePlaceholder.sql removes TR_Chapters_CreateDefaultScene",
"additional_modules": "Eight retained SSMS diagram support modules; no PlotDirector migration identity assigned.",
"publication_graph_utf16_sha256": "b341f299e0704490a57bbada6f3dd06a5b952c3a451f14506b811545e4d4cc3f",
"original_business_tables": 163,
"original_business_rows": 139554,
"original_business_fingerprint_artifact_sha256": "759c6d23b59ac17d4447d33bf692029b88d180f20e4abcb3d4fe795b54def450",
"historical_baseline_entries": 210,
"executed_steps_in_plan": 108,
"ordering_exception": "253 -> 255 -> 254 -> 256; Docs/Geography/GeographicalPositioning.md",
"omitted_migrations": [
{
"id": "286_DevelopmentResetProcedures",
"sha256": "ed1de0660ed11ad36799b4449adb8c502a792e34c3b238482039ebdf4d6a5b3e",
"reason": "Development-only reset procedure refresh; no Production execution; current runtime guards require separate review.",
"evidence": "evidence/baseline.json"
},
{
"id": "301_CharacterLifeStatus",
"sha256": "2ce923ff04ab7648790521d68f8aeea5d4e56b6c36ea884a73fdb212f17043e0",
"reason": "Superseded by standalone migration 304, which explicitly replaces partial 301 and failed 302; 303 is the intermediate projection repair covered by 304.",
"evidence": "evidence/baseline.json"
},
{
"id": "302_CharacterLifeStatusProjections",
"sha256": "b50f5bb1616bf5eff5a02ccba92cf6348e8da663941c1242fd578b3f315b62e7",
"reason": "Superseded by standalone migration 304, which explicitly replaces partial 301 and failed 302; 303 is the intermediate projection repair covered by 304.",
"evidence": "evidence/baseline.json"
},
{
"id": "303_CharacterLifeStatusProjectionRepair",
"sha256": "947d276060e33a8a07c8e6413d97c36ce6b41540a80efb14386e16015108e21f",
"reason": "Superseded by standalone migration 304, which explicitly replaces partial 301 and failed 302; 303 is the intermediate projection repair covered by 304.",
"evidence": "evidence/baseline.json"
}
],
"unresolved": "No unresolved module-definition discrepancy after documented patch, removal and SSMS-support classification. Historical per-script execution remains unknown; baselines represent verified current final state.",
"resulting_schema_sha256": "6d26db0814ae38254957a5b27b44591e959e0408cab98e6701b25cfee7827fe1"
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,76 @@
using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Controllers;
using PlotLine.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
internal static class DeploymentOperationsTests
{
public static void Run()
{
foreach(var address in new[]{"203.0.113.1","192.168.10.8"})
{
var repository=new Probe();var controller=Controller(address,repository);
if(controller.Read(default).GetAwaiter().GetResult() is not NotFoundResult || repository.Calls!=0)
throw new Exception("External health request reached the database");
}
foreach(var address in new[]{"127.0.0.1","::1"})
{
var repository=new Probe();var controller=Controller(address,repository);
if(controller.Read(default).GetAwaiter().GetResult() is not JsonResult || repository.Calls!=1)
throw new Exception("Loopback health request did not verify the database");
}
var unready=new Probe{Ready=false};
if(Controller("127.0.0.1",unready).Read(default).GetAwaiter().GetResult() is not ObjectResult {StatusCode:503})
throw new Exception("Uninitialised ledger passed health");
var failed=new Probe{Fail=true};
if(Controller("127.0.0.1",failed).Read(default).GetAwaiter().GetResult() is not ObjectResult {StatusCode:503})
throw new Exception("Database failure passed health");
DataProtectionIdentity();
}
private static void DataProtectionIdentity()
{
var temporary=Directory.CreateTempSubdirectory("pd-protection-test-").FullName;
try
{
var oldRoot=Path.Combine(temporary,"old");var newRoot=Path.Combine(temporary,"new");var keys=Path.Combine(temporary,"keys");
Directory.CreateDirectory(oldRoot);Directory.CreateDirectory(newRoot);Directory.CreateDirectory(keys);
ServiceProvider Services(string root,string? applicationName=null)
{
var builder=WebApplication.CreateBuilder(new WebApplicationOptions{ContentRootPath=root,EnvironmentName="Qualification"});
var protection=builder.Services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(keys));
if(applicationName is not null)protection.SetApplicationName(applicationName);
return builder.Services.BuildServiceProvider();
}
using var original=Services(oldRoot);
var identity=original.GetRequiredService<IOptions<DataProtectionOptions>>().Value.ApplicationDiscriminator;
if(identity!=oldRoot+Path.DirectorySeparatorChar)throw new Exception("Hosting content-root identity differs from the reviewed assumption");
var purpose=new[]{"Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware","Cookies","v2"};
var protectedValue=original.GetRequiredService<IDataProtectionProvider>().CreateProtector(purpose).Protect("synthetic compatibility probe");
using var moved=Services(newRoot);
var failed=false;
try{moved.GetRequiredService<IDataProtectionProvider>().CreateProtector(purpose).Unprotect(protectedValue);}
catch(System.Security.Cryptography.CryptographicException){failed=true;}
if(!failed)throw new Exception("Different default roots unexpectedly shared an application identity");
using var pinned=Services(newRoot,identity);
if(pinned.GetRequiredService<IDataProtectionProvider>().CreateProtector(purpose).Unprotect(protectedValue)!="synthetic compatibility probe")
throw new Exception("Explicit stable Data Protection identity did not preserve the synthetic payload");
}
finally{Directory.Delete(temporary,true);}
}
private static DeploymentHealthController Controller(string address,Probe repository)
{
var http=new DefaultHttpContext();http.Connection.RemoteIpAddress=IPAddress.Parse(address);
return new DeploymentHealthController(repository){ControllerContext=new ControllerContext{HttpContext=http}};
}
private sealed class Probe:IDeploymentHealthRepository
{
public int Calls;public bool Ready=true;public bool Fail;
public Task<DeploymentDatabaseHealth> ReadAsync(CancellationToken cancellationToken)
{Calls++;if(Fail)throw new InvalidOperationException("Private diagnostic must not reach HTTP");return Task.FromResult(new DeploymentDatabaseHealth("Isolated",Ready));}
}
}

View File

@ -199,6 +199,7 @@ if(args.Contains("--focus-diagnostics")){SharedFocusDiagnosticsTests.Run();retur
var tests = new (string Name, Action Test)[]
{
("Deployment health is loopback-only, database-backed and fails closed",DeploymentOperationsTests.Run),
("Main Character workspace lazy reads and safe management",()=>CharacterWorkspaceTests.Run().GetAwaiter().GetResult()),
("Scene family identification and branch exploration",ContextFamilyTests.Run),
("Context Family/Story projection and bounded reads",()=>ContextRelationshipLensTests.Run().GetAwaiter().GetResult()),

View File

@ -0,0 +1,37 @@
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PlotLine.Data;
namespace PlotLine.Controllers;
[AllowAnonymous]
[ApiExplorerSettings(IgnoreApi=true)]
public sealed class DeploymentHealthController(IDeploymentHealthRepository database) : Controller
{
[HttpGet("/_deployment/health")]
[ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
public async Task<IActionResult> Read(CancellationToken cancellationToken)
{
// Forwarded headers have already restored the external client's address.
// This endpoint is for the local activation helper, never the public proxy.
if(HttpContext.Connection.RemoteIpAddress is not { } ip || !IPAddress.IsLoopback(ip))
return NotFound();
try
{
var state=await database.ReadAsync(cancellationToken);
if(!state.LedgerReady)return StatusCode(503,new {healthy=false});
var info=typeof(Program).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion??"";
var sha=Regex.Match(info,@"\+([a-f0-9]{40})").Groups[1].Value;
if(sha.Length!=40)return StatusCode(503,new {healthy=false});
return Json(new {healthy=true,version=info.Split('+')[0],sourceCommit=sha,database=state.DatabaseName});
}
catch(Exception) when(!cancellationToken.IsCancellationRequested)
{
// Never return SQL diagnostics or connection information to HTTP clients.
return StatusCode(503,new {healthy=false});
}
}
}

View File

@ -0,0 +1,22 @@
using System.Data;
using Dapper;
namespace PlotLine.Data;
public sealed record DeploymentDatabaseHealth(string DatabaseName, bool LedgerReady);
public interface IDeploymentHealthRepository
{
Task<DeploymentDatabaseHealth> ReadAsync(CancellationToken cancellationToken);
}
public sealed class DeploymentHealthRepository(ISqlConnectionFactory connections) : IDeploymentHealthRepository
{
public async Task<DeploymentDatabaseHealth> ReadAsync(CancellationToken cancellationToken)
{
using var connection=connections.CreateConnection();
return await connection.QuerySingleAsync<DeploymentDatabaseHealth>(new CommandDefinition(
"dbo.Deployment_Health",commandType:CommandType.StoredProcedure,
cancellationToken:cancellationToken,commandTimeout:5));
}
}

View File

@ -6,6 +6,8 @@ using PlotLine.Models;
using PlotLine.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using System.Net;
using Microsoft.Extensions.FileProviders;
using PlotLine.Hubs;
@ -24,6 +26,15 @@ public class Program
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.ForwardLimit = 1;
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
options.KnownProxies.Add(IPAddress.Loopback);
options.KnownProxies.Add(IPAddress.IPv6Loopback);
});
builder.Services.AddControllersWithViews(options =>
{
@ -59,8 +70,14 @@ public class Program
builder.Environment.ContentRootPath,
builder.Configuration["DataProtection:KeysPath"]);
Directory.CreateDirectory(dataProtectionKeyPath);
builder.Services.AddDataProtection()
var dataProtection = builder.Services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(dataProtectionKeyPath));
// Releases live in versioned directories. A separately provisioned stable
// identity prevents a path change from silently changing the key purpose.
// Leave the existing default intact unless operations explicitly configure it.
var dataProtectionApplicationName = builder.Configuration["DataProtection:ApplicationName"];
if (!string.IsNullOrWhiteSpace(dataProtectionApplicationName))
dataProtection.SetApplicationName(dataProtectionApplicationName);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
@ -143,6 +160,7 @@ public class Program
});
});
builder.Services.AddSingleton<ISqlConnectionFactory, SqlConnectionFactory>();
builder.Services.AddScoped<IDeploymentHealthRepository, DeploymentHealthRepository>();
builder.Services.AddSingleton<DevelopmentSqlDiagnostics>();
builder.Services.AddHostedService(services => services.GetRequiredService<DevelopmentSqlDiagnostics>());
builder.Services.AddScoped<IUserRepository, UserRepository>();
@ -384,6 +402,8 @@ public class Program
configure?.Invoke(builder);
var app = builder.Build();
app.UseForwardedHeaders();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");

View File

@ -0,0 +1,48 @@
-- Authoritative forward migration/release history. No historical execution is inferred.
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
IF OBJECT_ID(N'dbo.DatabaseMigrationHistory', N'U') IS NULL
BEGIN
CREATE TABLE dbo.DatabaseMigrationHistory
(
MigrationIdentity nvarchar(200) NOT NULL CONSTRAINT PK_DatabaseMigrationHistory PRIMARY KEY,
ScriptFilename nvarchar(260) NOT NULL,
ScriptSha256 char(64) NOT NULL,
RecordedUtc datetime2(7) NOT NULL CONSTRAINT DF_DatabaseMigrationHistory_RecordedUtc DEFAULT SYSUTCDATETIME(),
DeploymentIdentifier varchar(100) NOT NULL,
DurationMilliseconds bigint NULL,
RecordingKind varchar(10) NOT NULL,
BaselineEvidenceReference nvarchar(500) NULL,
CONSTRAINT CK_DatabaseMigrationHistory_Kind CHECK
((RecordingKind='Executed' AND DurationMilliseconds IS NOT NULL AND DurationMilliseconds>=0 AND BaselineEvidenceReference IS NULL)
OR (RecordingKind='Baselined' AND DurationMilliseconds IS NULL AND LEN(BaselineEvidenceReference)>0)),
CONSTRAINT CK_DatabaseMigrationHistory_Hash CHECK
(LEN(ScriptSha256)=64 AND ScriptSha256 COLLATE Latin1_General_100_BIN2 NOT LIKE '%[^0-9a-f]%')
);
END;
GO
IF OBJECT_ID(N'dbo.ApplicationReleaseHistory', N'U') IS NULL
BEGIN
CREATE TABLE dbo.ApplicationReleaseHistory
(
DeploymentIdentifier varchar(100) NOT NULL CONSTRAINT PK_ApplicationReleaseHistory PRIMARY KEY,
ReleaseIdentifier varchar(100) NOT NULL,
ApplicationVersion varchar(100) NOT NULL,
SourceCommit char(40) NOT NULL,
PackageSha256 char(64) NOT NULL,
MigrationManifestSha256 char(64) NOT NULL,
ActivatedUtc datetime2(7) NOT NULL CONSTRAINT DF_ApplicationReleaseHistory_ActivatedUtc DEFAULT SYSUTCDATETIME(),
EvidenceReference nvarchar(500) NOT NULL,
ActivationKind varchar(10) NOT NULL,
PreviousDeploymentIdentifier varchar(100) NULL,
CONSTRAINT FK_ApplicationReleaseHistory_Previous FOREIGN KEY (PreviousDeploymentIdentifier)
REFERENCES dbo.ApplicationReleaseHistory(DeploymentIdentifier),
CONSTRAINT CK_ApplicationReleaseHistory_Kind CHECK (ActivationKind IN ('Deploy','Rollback')),
CONSTRAINT CK_ApplicationReleaseHistory_Hashes CHECK
(LEN(SourceCommit)=40 AND SourceCommit COLLATE Latin1_General_100_BIN2 NOT LIKE '%[^0-9a-f]%'
AND LEN(PackageSha256)=64 AND PackageSha256 COLLATE Latin1_General_100_BIN2 NOT LIKE '%[^0-9a-f]%'
AND LEN(MigrationManifestSha256)=64 AND MigrationManifestSha256 COLLATE Latin1_General_100_BIN2 NOT LIKE '%[^0-9a-f]%')
);
END;
GO

View File

@ -0,0 +1,12 @@
SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO
CREATE OR ALTER PROCEDURE dbo.Deployment_Health
AS
BEGIN
SET NOCOUNT ON;
SELECT DB_NAME() AS DatabaseName,
CONVERT(bit,CASE WHEN OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U') IS NOT NULL
AND OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U') IS NOT NULL THEN 1 ELSE 0 END) AS LedgerReady;
END;
GO

3
Tools/Deployment/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
__pycache__/
bin/
obj/

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.1" />
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="9.0.21" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,364 @@
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Microsoft.Data.SqlClient;
// Root-owned, separately provisioned worker. JSON-lines protocol; never emits SQL,
// connection strings, exception messages or business data. Holds the SQL session
// lock across backup, migrations, application activation and health checks.
internal static class Program
{
private static SqlConnection? connection;
private static string database = "";
private static bool locked;
private static JsonObject? manifest;
private static string packageRoot = "";
private static string deployment = "";
private static string packageHash = "";
private static string? currentMigration;
private static int currentBatch;
public static async Task<int> Main(string[] args)
{
if (args.Length != 1) return 2;
try
{
var config = JsonNode.Parse(await File.ReadAllTextAsync(args[0]))!.AsObject();
database = S(config, "database");
var builder = new SqlConnectionStringBuilder(S(config, "connection"));
if (builder.DataSource!=S(config,"expected_server") || Environment.MachineName!=S(config,"expected_host"))
throw new InvalidOperationException("server-identity");
if (builder.InitialCatalog != database || !Regex.IsMatch(database, "^[A-Za-z][A-Za-z0-9_]{0,100}$"))
throw new InvalidOperationException("target");
builder.ApplicationName = "PlotDirector deployment worker";
builder.ConnectTimeout = 10;
connection = new SqlConnection(builder.ConnectionString);
await connection.OpenAsync();
if ((string?)await Scalar("SELECT DB_NAME()") != database) throw new InvalidOperationException("target");
Console.WriteLine("{\"ok\":true,\"ready\":true}");
while (await Console.In.ReadLineAsync() is { } line)
{
try
{
var request = JsonNode.Parse(line)!.AsObject();
var answer = await Execute(request);
Console.WriteLine(JsonSerializer.Serialize(new { ok = true, result = answer }));
}
catch (Exception e)
{
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 }));
// A failed command poisons the session. Never proceed to activation.
return 1;
}
}
return 0;
}
catch (Exception e)
{
Console.WriteLine(JsonSerializer.Serialize(new { ok = false,
error = e is SqlException se ? "SQL_" + se.Number : e.GetType().Name }));
return 1;
}
finally { if (connection is not null) await connection.DisposeAsync(); }
}
private static string S(JsonObject o, string key) => o[key]!.GetValue<string>();
private static string Hash(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
private static SqlCommand Command(string sql, SqlTransaction? transaction = null)
=> new(sql, connection, transaction) { CommandTimeout = 1800 };
private static async Task<object?> Scalar(string sql, SqlTransaction? t = null)
{ using var c = Command(sql, t); return await c.ExecuteScalarAsync(); }
private static async Task Run(string sql, SqlTransaction? t = null)
{ using var c = Command(sql, t); await c.ExecuteNonQueryAsync(); }
private static async Task<object> Execute(JsonObject request)
{
var op = S(request, "op");
if (op == "inspect") return new { schema = await Schema(), database };
if(op is "fingerprint" or "integrity")
{
if(!database.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal))
throw new InvalidOperationException("qualification-only");
if(op=="fingerprint")return await Fingerprints(request["original"]?.AsObject());
await Run("DBCC CHECKDB WITH NO_INFOMSGS,ALL_ERRORMSGS;");
var violations=Convert.ToInt64(await Scalar("CREATE TABLE #violations([Table] nvarchar(512),[Constraint] nvarchar(512),[Where] nvarchar(max)); INSERT #violations EXEC('DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS,NO_INFOMSGS'); SELECT COUNT_BIG(*) FROM #violations; DROP TABLE #violations;"));
if(violations!=0)throw new InvalidOperationException("referential-integrity");
return new { integrity=true, constraint_violations=violations };
}
if (op == "begin")
{
if (locked) throw new InvalidOperationException("already-begun");
var result = Convert.ToInt32(await Scalar("DECLARE @r int; EXEC @r=sys.sp_getapplock @Resource=N'PlotDirector.Deployment',@LockMode='Exclusive',@LockOwner='Session',@LockTimeout=0; SELECT @r;"));
if (result < 0) throw new InvalidOperationException("concurrent-deployment");
locked = true;
packageRoot = Path.GetFullPath(S(request, "package_root"));
manifest = JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(packageRoot, "manifest.json")))!.AsObject();
deployment = S(request, "deployment_id");
packageHash = S(request, "package_sha256");
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 complete = await ValidateHistory();
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());
return new { schema = actual, complete };
}
if (!locked || manifest is null) throw new InvalidOperationException("not-begun");
if (op == "idle") { await Idle(); return new { idle = true }; }
if (op == "backup")
{
// Path comes only from the root-owned target configuration, not a release.
var path = S(request, "path");
if (!Regex.IsMatch(path, @"^/[A-Za-z0-9_./-]+\.bak$") || path.Split('/').Contains(".."))
throw new InvalidOperationException("backup-path");
using var backup = Command("BACKUP DATABASE " + Quote(database) + " TO DISK=@p WITH COPY_ONLY,CHECKSUM,NOINIT; RESTORE VERIFYONLY FROM DISK=@p WITH CHECKSUM;");
backup.Parameters.AddWithValue("@p", path);
await backup.ExecuteNonQueryAsync();
return new { verified = true };
}
if (op == "migrate")
{
await Idle();
foreach (var node in manifest["migrations"]!.AsArray()) await Migration(node!.AsObject());
var schema = await Schema();
if (schema != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("resulting-schema");
await Conditions(manifest["postconditions"]!.AsArray());
return new { schema };
}
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 };
}
if (op == "activated")
{
// Caller must pass health checks BEFORE this operation. Failed activation
// remains in protected filesystem evidence, never in successful history.
await Conditions(manifest["postconditions"]!.AsArray());
using var cmd = Command("INSERT dbo.ApplicationReleaseHistory(DeploymentIdentifier,ReleaseIdentifier,ApplicationVersion,SourceCommit,PackageSha256,MigrationManifestSha256,EvidenceReference,ActivationKind,PreviousDeploymentIdentifier) VALUES(@id,@release,@version,@commit,@package,@manifest,@evidence,@kind,@previous)");
foreach (var (key, value) in new Dictionary<string,object> {
["@id"]=deployment,["@release"]=S(manifest,"release_id"),["@version"]=S(manifest,"version"),
["@commit"]=S(manifest,"source_commit"),["@package"]=packageHash,
["@manifest"]=Hash(await File.ReadAllBytesAsync(Path.Combine(packageRoot,"manifest.json"))),
["@evidence"]=S(request,"evidence"),["@kind"]=S(request,"kind"),
["@previous"]=request["previous_deployment"]?.GetValue<string>() is { } previous ? previous : DBNull.Value })
cmd.Parameters.AddWithValue(key,value);
await cmd.ExecuteNonQueryAsync();
return new { recorded = true };
}
throw new InvalidOperationException("operation");
}
private static string Quote(string name) => "[" + name.Replace("]", "]]") + "]";
private static async Task<object> Fingerprints(JsonObject? original)
{
var tables=new Dictionary<string,List<string>>();
using(var cmd=Command("SELECT s.name,t.name,c.name FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.columns c ON c.object_id=t.object_id WHERE t.name NOT IN ('DatabaseMigrationHistory','ApplicationReleaseHistory') ORDER BY s.name,t.name,c.column_id"))
using(var reader=await cmd.ExecuteReaderAsync())
while(await reader.ReadAsync())
{
var key=reader.GetString(0)+"."+reader.GetString(1);
if(!tables.ContainsKey(key))tables[key]=[];
tables[key].Add(reader.GetString(2));
}
var answer=new Dictionary<string,object>();
var targets=original is null?tables.Keys.ToList():original.Select(x=>x.Key).ToList();
foreach(var name in targets)
{
if(!tables.TryGetValue(name,out var available))throw new InvalidOperationException("lost-business-table");
var columns=original is null?available:original[name]!["columns"]!.AsArray().Select(x=>x!.GetValue<string>()).ToList();
if(!columns.All(available.Contains))throw new InvalidOperationException("lost-business-column");
var parts=name.Split('.');
if(parts.Length!=2)throw new InvalidOperationException("table-name");
var projection=string.Join(',',columns.Select(x=>"t."+Quote(x)));
using var cmd=Command($"SELECT COUNT_BIG(*),LOWER(CONVERT(varchar(64),HASHBYTES('SHA2_256',COALESCE(STRING_AGG(CONVERT(varchar(max),RowHash),'') WITHIN GROUP(ORDER BY RowHash),'')),2)) FROM {Quote(parts[0])}.{Quote(parts[1])} t CROSS APPLY (SELECT CONVERT(varchar(64),HASHBYTES('SHA2_256',(SELECT {projection} FOR JSON PATH,WITHOUT_ARRAY_WRAPPER,INCLUDE_NULL_VALUES)),2) AS RowHash) h");
using var reader=await cmd.ExecuteReaderAsync();await reader.ReadAsync();
answer[name]=new { columns, rows=reader.GetInt64(0),sha256=reader.GetString(1) };
}
return answer;
}
private static async Task Idle()
{
foreach (var table in new[] { "StoryIntelligenceRuns", "StoryIntelligenceJobs", "WholeBookPlotSynthesisRuns", "CharacterEnrichmentRuns", "OnboardingManuscriptBuilds", "GeographicLookupJob", "NativeChapterReviews" })
{
var sql = $"IF OBJECT_ID(N'dbo.{table}',N'U') IS NOT NULL AND COL_LENGTH(N'dbo.{table}',N'Status') IS NOT NULL EXEC(N'IF EXISTS(SELECT 1 FROM dbo.{table} WHERE Status IN (N''Pending'',N''Queued'',N''Running'',N''Processing'',N''InProgress'',N''CancelRequested'')) THROW 51000,''Active background work'',1;');";
await Run(sql);
}
}
private static async Task<bool> ValidateHistory()
{
if (await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull)
{
if (manifest!["migrations"]!.AsArray().Count==0) throw new InvalidOperationException("code-only-without-ledger");
return false;
}
var complete = true;
var identities = new HashSet<string>();
foreach (var node in manifest!["migrations"]!.AsArray())
{
var m = node!.AsObject();
identities.Add(S(m,"id"));
using var cmd = Command("SELECT ScriptSha256 FROM dbo.DatabaseMigrationHistory WHERE MigrationIdentity=@id");
cmd.Parameters.AddWithValue("@id",S(m,"id"));
if (await cmd.ExecuteScalarAsync() is string checksum)
{ if(checksum!=S(m,"sha256"))throw new InvalidOperationException("immutable-migration-checksum"); }
else complete=false;
}
// Code-only plans retain their full immutable historical entries. A ledger
// identity absent from the approved plan is an unknown database state.
using var all = Command("SELECT MigrationIdentity FROM dbo.DatabaseMigrationHistory");
using var reader = await all.ExecuteReaderAsync();
while(await reader.ReadAsync()) if(!identities.Contains(reader.GetString(0)))throw new InvalidOperationException("unrecognised-history");
return complete;
}
private static async Task Migration(JsonObject migration)
{
var identity = S(migration,"id");
currentMigration = identity;
currentBatch = 0;
var expected = S(migration,"sha256");
var filename = S(migration,"file");
if (Path.GetFileName(filename) != filename) throw new InvalidOperationException("migration-path");
var bytes = await File.ReadAllBytesAsync(Path.Combine(packageRoot,"sql",filename));
if (Hash(bytes) != expected) throw new InvalidOperationException("migration-checksum");
var historyExists = await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is not DBNull;
if (historyExists)
{
using var existing = Command("SELECT ScriptSha256 FROM dbo.DatabaseMigrationHistory WHERE MigrationIdentity=@id");
existing.Parameters.AddWithValue("@id",identity);
if (await existing.ExecuteScalarAsync() is string prior)
{
if (prior != expected) throw new InvalidOperationException("immutable-migration-checksum");
return;
}
}
await Conditions(migration["prerequisites"]!.AsArray());
foreach(var prerequisite in migration["requires"]!.AsArray())
{
using var check=Command("SELECT COUNT(*) FROM dbo.DatabaseMigrationHistory WHERE MigrationIdentity=@id");
check.Parameters.AddWithValue("@id",prerequisite!.GetValue<string>());
if(Convert.ToInt32(await check.ExecuteScalarAsync())!=1)throw new InvalidOperationException("migration-dependency");
}
if (S(migration,"mode") is not ("execute" or "baseline"))
throw new InvalidOperationException("nontransactional-migration-requires-reviewed-recovery");
var stopwatch = Stopwatch.StartNew();
await using var transaction = (SqlTransaction)await connection!.BeginTransactionAsync();
try
{
if (S(migration,"mode") == "execute")
{
await Run("SET XACT_ABORT ON; SET ANSI_NULLS ON; SET QUOTED_IDENTIFIER ON;",transaction);
foreach (var batch in Batches(Encoding.UTF8.GetString(bytes).TrimStart('\ufeff')))
{
currentBatch++;
await Run(batch,transaction);
if ((string?)await Scalar("SELECT DB_NAME()",transaction) != database || Convert.ToInt32(await Scalar("SELECT @@TRANCOUNT",transaction)) != 1)
throw new InvalidOperationException("migration-session-changed");
}
}
await Conditions(migration["postconditions"]!.AsArray(), transaction);
using var insert = Command("INSERT dbo.DatabaseMigrationHistory(MigrationIdentity,ScriptFilename,ScriptSha256,DeploymentIdentifier,DurationMilliseconds,RecordingKind,BaselineEvidenceReference) VALUES(@id,@file,@hash,@deployment,@duration,@kind,@evidence)",transaction);
insert.Parameters.AddWithValue("@id",identity);
insert.Parameters.AddWithValue("@file",filename);
insert.Parameters.AddWithValue("@hash",expected);
insert.Parameters.AddWithValue("@deployment",deployment);
var baseline = S(migration,"mode")=="baseline";
insert.Parameters.AddWithValue("@duration",baseline ? DBNull.Value : stopwatch.ElapsedMilliseconds);
insert.Parameters.AddWithValue("@kind",baseline ? "Baselined" : "Executed");
insert.Parameters.AddWithValue("@evidence",baseline ? S(migration,"evidence") : DBNull.Value);
await insert.ExecuteNonQueryAsync();
await transaction.CommitAsync();
currentMigration=null;
currentBatch=0;
}
catch { try { await transaction.RollbackAsync(); } catch { } throw; }
}
private static async Task Conditions(JsonArray conditions, SqlTransaction? transaction = null)
{
foreach (var node in conditions)
{
var c = node!.AsObject();
string sql = S(c,"kind") switch {
"object" => "SELECT CASE WHEN OBJECT_ID(@name,@type) IS NOT NULL THEN 1 ELSE 0 END",
"column" => "SELECT CASE WHEN COL_LENGTH(@name,@column) IS NOT NULL THEN 1 ELSE 0 END",
"module_sha256" => "SELECT LOWER(CONVERT(varchar(64),HASHBYTES('SHA2_256',CONVERT(varbinary(max),OBJECT_DEFINITION(OBJECT_ID(@name)))),2))",
"solver_graph" => "SELECT CASE WHEN COUNT(*)=1 THEN MIN(LOWER(CONVERT(varchar(64),HASHBYTES('SHA2_256',CONVERT(varbinary(max),GraphJson)),2))) ELSE NULL END FROM dbo.WritingSolverVersions WHERE Active=1 AND Version=@version",
_ => throw new InvalidOperationException("condition-kind")
};
using var cmd = Command(sql,transaction);
if(c["name"] is not null)cmd.Parameters.AddWithValue("@name",S(c,"name"));
if(c["version"] is not null)cmd.Parameters.AddWithValue("@version",S(c,"version"));
if (c["type"] is not null) cmd.Parameters.AddWithValue("@type",S(c,"type"));
if (c["column"] is not null) cmd.Parameters.AddWithValue("@column",S(c,"column"));
var actual = await cmd.ExecuteScalarAsync();
if (S(c,"kind") is "module_sha256" or "solver_graph" ? actual is not string hash || hash!=S(c,"sha256") : Convert.ToInt32(actual)!=1)
throw new InvalidOperationException("condition-failed");
}
}
private static async Task<string> Schema()
{
// Object-name ordered, independent of restore-assigned object IDs and data.
// History is excluded so records do not change the application's schema ID.
const string filter = "t.name NOT IN ('DatabaseMigrationHistory','ApplicationReleaseHistory')";
var queries = new[] {
$"SELECT s.name AS [schema],t.name,c.name AS [column],c.column_id,TYPE_NAME(c.user_type_id) AS [type],c.max_length,c.precision,c.scale,c.is_nullable,c.is_identity,c.is_computed,OBJECT_DEFINITION(c.default_object_id) AS [default],cc.definition AS computed FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.columns c ON c.object_id=t.object_id LEFT JOIN sys.computed_columns cc ON cc.object_id=c.object_id AND cc.column_id=c.column_id WHERE {filter} ORDER BY s.name,t.name,c.column_id FOR JSON PATH,INCLUDE_NULL_VALUES",
"SELECT OBJECT_SCHEMA_NAME(m.object_id) AS [schema],o.name,o.type,REPLACE(m.definition,CHAR(13),'') AS definition,m.uses_ansi_nulls,m.uses_quoted_identifier FROM sys.sql_modules m JOIN sys.objects o ON o.object_id=m.object_id ORDER BY OBJECT_SCHEMA_NAME(m.object_id),o.name FOR JSON PATH,INCLUDE_NULL_VALUES",
$"SELECT s.name AS [schema],t.name,CASE WHEN EXISTS(SELECT 1 FROM sys.key_constraints k WHERE k.parent_object_id=i.object_id AND k.unique_index_id=i.index_id AND k.is_system_named=1) THEN NULL ELSE i.name END AS [index],i.type,i.is_unique,i.is_primary_key,i.is_disabled,i.has_filter,i.filter_definition,c.name AS [column],ic.key_ordinal,ic.is_descending_key,ic.is_included_column FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.indexes i ON i.object_id=t.object_id JOIN sys.index_columns ic ON ic.object_id=i.object_id AND ic.index_id=i.index_id JOIN sys.columns c ON c.object_id=ic.object_id AND c.column_id=ic.column_id WHERE {filter} ORDER BY s.name,t.name,i.index_id,ic.index_column_id FOR JSON PATH,INCLUDE_NULL_VALUES",
$"SELECT s.name AS [schema],t.name AS [table],CASE WHEN COALESCE(f.is_system_named,ck.is_system_named,dc.is_system_named,kc.is_system_named,0)=1 THEN NULL ELSE o.name END AS [constraint],o.type,OBJECT_DEFINITION(o.object_id) AS definition,f.is_disabled AS fk_disabled,f.is_not_trusted AS fk_untrusted,ck.is_disabled AS check_disabled,ck.is_not_trusted AS check_untrusted,(SELECT pc.name AS parent_column,OBJECT_SCHEMA_NAME(fc.referenced_object_id) AS referenced_schema,OBJECT_NAME(fc.referenced_object_id) AS referenced_table,rc.name AS referenced_column FROM sys.foreign_key_columns fc JOIN sys.columns pc ON pc.object_id=fc.parent_object_id AND pc.column_id=fc.parent_column_id JOIN sys.columns rc ON rc.object_id=fc.referenced_object_id AND rc.column_id=fc.referenced_column_id WHERE fc.constraint_object_id=o.object_id ORDER BY fc.constraint_column_id FOR JSON PATH) AS foreign_key_columns FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id JOIN sys.objects o ON o.parent_object_id=t.object_id LEFT JOIN sys.foreign_keys f ON f.object_id=o.object_id LEFT JOIN sys.check_constraints ck ON ck.object_id=o.object_id LEFT JOIN sys.default_constraints dc ON dc.object_id=o.object_id LEFT JOIN sys.key_constraints kc ON kc.object_id=o.object_id WHERE {filter} AND o.type IN ('C','D','F','PK','UQ') ORDER BY s.name,t.name,o.type,CASE WHEN COALESCE(f.is_system_named,ck.is_system_named,dc.is_system_named,kc.is_system_named,0)=0 THEN o.name END,o.object_id FOR JSON PATH,INCLUDE_NULL_VALUES"
};
var values = new List<string>();
foreach (var sql in queries)
{
using var cmd = Command(sql);
using var reader = await cmd.ExecuteReaderAsync();
var text = new StringBuilder();
while (await reader.ReadAsync()) text.Append(reader.GetString(0));
values.Add(text.ToString());
}
return Hash(Encoding.UTF8.GetBytes(string.Join("\n",values)));
}
internal static IEnumerable<string> Batches(string script)
{
var buffer = new StringBuilder();
int commentDepth=0;
char quote='\0';
foreach (var line in script.Replace("\r\n","\n").Split('\n'))
{
if (commentDepth==0 && quote=='\0' && Regex.IsMatch(line,@"^\s*GO\s*(?:--.*)?$",RegexOptions.IgnoreCase))
{ if (!string.IsNullOrWhiteSpace(buffer.ToString())) yield return buffer.ToString(); buffer.Clear(); continue; }
if (commentDepth==0 && quote=='\0' && Regex.IsMatch(line,@"^\s*(?:GO\s+\d|:|!!)",RegexOptions.IgnoreCase))
throw new InvalidOperationException("sqlcmd-directive");
buffer.AppendLine(line);
for(int i=0;i<line.Length;i++)
{
var ch=line[i]; var next=i+1<line.Length?line[i+1]:'\0';
if(commentDepth>0)
{ if(ch=='/'&&next=='*'){commentDepth++;i++;} else if(ch=='*'&&next=='/'){commentDepth--;i++;} continue; }
if(quote!='\0')
{ if(ch==quote){if(next==quote)i++;else quote='\0';} continue; }
if(ch=='-'&&next=='-')break;
if(ch=='/'&&next=='*'){commentDepth++;i++;}
else if(ch=='\''||ch=='"')quote=ch;
else if(ch=='[')quote=']';
}
}
if(quote!='\0'||commentDepth!=0)throw new InvalidOperationException("unclosed-sql-token");
if(!string.IsNullOrWhiteSpace(buffer.ToString()))yield return buffer.ToString();
}
}

View File

@ -0,0 +1,96 @@
using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.Infrastructure;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using System.Text.Encodings.Web;
// Test-only host. Same PlotLine assembly/controllers/Razor; no email, payment,
// OpenAI credentials or application background services. Never installed on web1.
var configPath = Environment.GetEnvironmentVariable("PD_QUALIFICATION_CONFIG")
?? throw new InvalidOperationException("Private qualification configuration required");
using var configDoc=JsonDocument.Parse(File.ReadAllText(configPath));
var c=configDoc.RootElement;
var cs=new SqlConnectionStringBuilder(c.GetProperty("connection").GetString());
if(cs.DataSource!="192.168.10.10,1433" || !cs.InitialCatalog.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal)
|| !cs.UserID.StartsWith("PDQualification_",StringComparison.Ordinal))
throw new InvalidOperationException("Not an isolated qualification identity");
var owners=c.GetProperty("owner_ids").EnumerateArray().Select(x=>x.GetInt32()).ToHashSet();
var requestToken=c.GetProperty("request_token").GetString()!;
if(requestToken.Length<40)throw new InvalidOperationException("Private request token required");
using(var connection=new SqlConnection(cs.ConnectionString))
{
connection.Open();
using var command=new SqlCommand("SELECT DB_NAME()",connection);
if((string?)command.ExecuteScalar()!=cs.InitialCatalog)throw new InvalidOperationException("Database identity mismatch");
}
var contentRoot=c.GetProperty("content_root").GetString()!;
var dll=Path.Combine(contentRoot,"PlotLine.dll");
var expected=c.GetProperty("dll_sha256").GetString();
if(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(dll)))!=expected
|| Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(typeof(PlotLine.Program).Assembly.Location)))!=expected)
throw new InvalidOperationException("Application assembly differs from qualified payload");
var keys=c.GetProperty("keys_path").GetString()!;
var url=c.GetProperty("url").GetString()!;
if(!url.StartsWith("http://127.0.0.1:",StringComparison.Ordinal))throw new InvalidOperationException("Loopback binding required");
var values=new Dictionary<string,string?> {
["ConnectionStrings:DefaultConnection"]=cs.ConnectionString,
["Storage:UploadsRoot"]=c.GetProperty("uploads_path").GetString(),
["DataProtection:KeysPath"]=keys,
["Site:PublicBaseUrl"]=url,
["EmailSettings:SmtpServer"]="127.0.0.1",["EmailSettings:Port"]="1",
["EmailSettings:Username"]="",["EmailSettings:Password"]="",
["EmailSettings:FromAddress"]="qualification@example.invalid",
["Stripe:PublishableKey"]="",["Stripe:SecretKey"]="",["Stripe:WebhookSecret"]="",
["OpenAI:ApiKey"]="",["Geography:Enabled"]="false",
["StoryIntelligence:WorkersEnabled"]="false",["Illustrations:GenerationWorkerEnabled"]="false",
["WritingSolver:EnableIndexing"]="false",
["Features:ParagraphManuscripts"]="true"
};
var app=PlotLine.Program.BuildApplication(["--applicationName=PlotLine","--environment=Qualification",
"--contentRoot="+contentRoot,"--urls="+url,"--DataProtection:KeysPath="+keys],builder=>{
builder.Configuration.Sources.Clear();
builder.Configuration.AddInMemoryCollection(values);
// Removes retention, email, geocoding, native expiry, AI, presence and notification
// workers. The web host is registered when Build() completes.
builder.Services.RemoveAll<IHostedService>();
builder.Services.ConfigureHttpClientDefaults(http=>http.ConfigurePrimaryHttpMessageHandler(()=>new NoExternalRequests()));
builder.Services.AddSingleton(owners);
builder.Services.AddSingleton(new QualificationToken(requestToken));
builder.Services.AddAuthentication(options=>{
options.DefaultAuthenticateScheme="Qualification"; options.DefaultChallengeScheme="Qualification";
}).AddScheme<AuthenticationSchemeOptions,QualificationAuthentication>("Qualification",_=>{});
});
app.Urls.Clear();app.Urls.Add(url);
app.MapGet("/qualification/transport",(HttpContext context)=>Results.Json(new {scheme=context.Request.Scheme}));
Console.WriteLine("QUALIFICATION_HOST isolated database identity and binary checksum verified; all application workers disabled.");
await app.RunAsync();
internal sealed class NoExternalRequests:HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
=> throw new InvalidOperationException("Outbound HTTP disabled in qualification");
}
// Explicit clone-only test authentication, absent from PlotLine/production binaries.
// Loopback binding and SQL identity guards above are mandatory before registration.
internal sealed record QualificationToken(string Value);
internal sealed class QualificationAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,UrlEncoder encoder,HashSet<int> owners,QualificationToken token)
:AuthenticationHandler<AuthenticationSchemeOptions>(options,logger,encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var supplied=System.Text.Encoding.UTF8.GetBytes(Request.Headers["X-Qualification-Token"].ToString());
if(!CryptographicOperations.FixedTimeEquals(supplied,System.Text.Encoding.UTF8.GetBytes(token.Value))
|| !int.TryParse(Request.Headers["X-Qualification-Author"],out var owner)||!owners.Contains(owner))
return Task.FromResult(AuthenticateResult.NoResult());
var identity=new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,owner.ToString()),
new Claim(ClaimTypes.Name,"Isolated qualification")],Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),Scheme.Name)));
}
}

View File

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../../PlotLine/PlotLine.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,10 @@
# Production deployment tooling
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.
The release package is data, never a privileged executable. Atlas prepares it from
a clean Git commit. An administrator installs the helper, database worker, target
configuration and independent release-verification public key. The transfer account
can submit signed packages but cannot change the helper, trust anchor or target.

View File

@ -0,0 +1,299 @@
#!/usr/bin/python3 -I
"""Restricted activation entry point; install with release.py in a root-owned directory."""
import fcntl
import grp
import json
import os
from pathlib import Path
import pwd
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import time
import uuid
from release import Refused, canonical, file_digest, keys, load, require, safe_name, verify_bundle
CONFIG = Path('/etc/plotdirector-deployment/target.json')
SAFE_ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LANG': 'C.UTF-8', 'HOME': '/nonexistent', 'DOTNET_NOLOGO': '1'}
def protected(path, directory=False, secret=False):
path = Path(path)
require(path.is_absolute(), 'Absolute protected path required')
for parent in reversed(path.parents):
info = parent.lstat()
require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022, 'Untrusted protected path ancestor')
info = path.lstat()
require(info.st_uid == 0 and not info.st_mode & 0o022 and info.st_nlink == 1 if not directory else info.st_uid == 0 and not info.st_mode & 0o022, 'Protected path ownership/permissions invalid')
require(stat.S_ISDIR(info.st_mode) if directory else stat.S_ISREG(info.st_mode), 'Protected path type invalid')
if secret:
require(not info.st_mode & 0o007, 'Secret readable by other users')
def command(args, *, account=None, timeout=120):
options = {}
if account:
user = pwd.getpwnam(account)
options = {'user': user.pw_uid, 'group': user.pw_gid, 'extra_groups': []}
result = subprocess.run(args, env=SAFE_ENV, cwd='/', capture_output=True, timeout=timeout, **options)
require(result.returncode == 0, Path(args[0]).name + ' failed; diagnostic values suppressed')
return result.stdout.decode().strip()
class Worker:
def __init__(self, config):
protected(config['worker'])
protected(config['database_config'], secret=True)
database_config = load(config['database_config'])
require(database_config['database'] == config['database'], 'Database configuration target mismatch')
require(database_config['expected_host'] == config['host'] and database_config['expected_server'] == '127.0.0.1,1433', 'SQL server identity mismatch')
user = pwd.getpwnam(config['migration_account'])
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.read()
def read(self):
# poll/read timeout is enforced at the subprocess level by an alarm below;
# SQL operations additionally have finite command timeouts in the worker.
line = self.process.stdout.readline(65537)
require(bool(line) and len(line) <= 65536, 'Database worker unavailable')
answer = json.loads(line)
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)
def call(self, op, **values):
self.process.stdin.write(json.dumps({'op': op, **values}) + '\n')
self.process.stdin.flush()
return self.read()
def close(self):
if self.process.poll() is None:
self.process.stdin.close()
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
def configuration():
require(os.geteuid() == 0, 'Restricted sudo invocation required')
protected(CONFIG, secret=True)
cfg = load(CONFIG)
keys(cfg, ('format', 'host', 'environment', 'database', 'root', 'inbox', 'evidence', 'backup',
'service', 'runtime_account', 'migration_account', 'worker', 'database_config',
'public_key', 'minimum_free_bytes', 'health_base', 'runtime_config'))
require(cfg['format'] == 1 and cfg['host'] == socket.gethostname(), 'Wrong deployment host')
require(cfg['environment'] in ('Production', 'Test', 'Development'), 'Invalid environment')
require(cfg['root'] == '/srv/plotdirector' and cfg['inbox'] == '/srv/plotdirector/incoming'
and cfg['evidence'] == '/srv/plotdirector/deployment-evidence'
and cfg['service'] == 'plotdirector.service' and cfg['runtime_account'] == 'plotdirector'
and cfg['migration_account'] == 'plotdirector-migrate'
and cfg['database'] == 'PlotLine' and cfg['backup'] == '/srv/backups/sql'
and cfg['runtime_config'] == '/etc/plotdirector/plotdirector.env'
and cfg['health_base'] == 'http://127.0.0.1:5001', 'Unexpected target layout')
require(cfg['environment'] == 'Production', 'This installed entry point is production-specific; use the same core in the isolated qualification driver')
for p in (cfg['root'], cfg['root'] + '/releases', cfg['evidence']):
protected(p, directory=True)
for p in (cfg['public_key'], cfg['worker']):
protected(p)
protected(cfg['runtime_config'], secret=True)
for p in ('/usr/bin/dotnet', '/usr/bin/openssl', '/usr/bin/systemctl', '/usr/bin/curl'):
require(os.access(p, os.X_OK), 'Required executable unavailable')
require(isinstance(cfg['minimum_free_bytes'], int) and cfg['minimum_free_bytes'] >= 1024**3, 'Invalid disk-space floor')
require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'User', '--value']) == cfg['runtime_account'], 'Runtime identity mismatch')
require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'WorkingDirectory', '--value']) == cfg['root'] + '/current', 'Service content root mismatch')
executable = command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'ExecStart', '--value'])
require('path=/usr/bin/dotnet ;' in executable and
'argv[]=/usr/bin/dotnet ' + cfg['root'] + '/current/PlotLine.dll' in executable,
'Service executable mismatch')
require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'EnvironmentFiles', '--value']).split()[0] == cfg['runtime_config'], 'Service environment file mismatch')
protected(cfg['database_config'], secret=True)
database_config = load(cfg['database_config'])
require(database_config['database'] == cfg['database'], 'Database configuration target mismatch')
for base in (cfg['root'], cfg['backup']):
require(shutil.disk_usage(base).free >= cfg['minimum_free_bytes'], 'Insufficient free space')
return cfg
def install(payload, destination, runtime_group):
require(not destination.exists() and not destination.is_symlink(), 'Release already installed; use a new release identifier')
gid = grp.getgrnam(runtime_group).gr_gid
destination.mkdir(mode=0o750)
for source in sorted(payload.rglob('*')):
relative = source.relative_to(payload)
target = destination / relative
if source.is_dir():
target.mkdir(mode=0o750)
else:
require(source.is_file() and not source.is_symlink(), 'Invalid payload entry')
with source.open('rb') as src, target.open('xb') as out:
shutil.copyfileobj(src, out)
target.chmod(0o440)
os.chown(target, 0, gid)
os.chown(destination, 0, gid)
def switch(root, target, deployment):
current = root / 'current'
if current.exists() or current.is_symlink():
require(current.is_symlink(), 'current must be a symlink; initial provisioning is separate')
old = current.resolve(strict=True)
require(old.is_relative_to(root / 'releases') and old.name == 'app', 'Unsafe previous release')
pending = root / ('.current-' + deployment)
os.symlink(str(target), pending)
os.replace(pending, current)
fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
def health(cfg, destination, manifest, worker):
require(command(['/usr/bin/systemctl', 'is-active', cfg['service']]) == 'active', 'Service inactive')
for path in ('/', '/Account/Login'):
for attempt in range(20):
try:
status = command(['/usr/bin/curl', '--silent', '--show-error', '--noproxy', '*', '--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
except Refused:
pass
time.sleep(1)
else:
raise Refused('Application HTTP health check failed')
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', '*',
'--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']
and identity.get('sourceCommit') == manifest['source_commit'] and identity.get('database') == cfg['database'],
'Running application/database identity mismatch')
worker.call('health')
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
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):
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')
if validate:
event('validation-only')
print('VALIDATED ' + package_id + '; no backup, migrations or service operations performed')
return
backup_name = 'PlotLine-predeploy-' + deployment + '.bak'
backup = Path(cfg['backup']) / backup_name
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')
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)
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))
except Exception as error:
if stopped:
try:
command(['/usr/bin/systemctl', 'stop', cfg['service']])
except Exception:
pass
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())
raise
finally:
if worker is not None:
worker.close()
os.close(lock_fd)
def main():
os.umask(0o077)
# Ignore inherited Python/environment search paths; installed launcher uses -I.
import signal
signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(Refused('Deployment timeout')))
signal.alarm(7200)
args = sys.argv[1:]
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>')
activate(args[-1], validate, rollback)
if __name__ == '__main__':
try:
main()
except Exception as error:
print('DEPLOYMENT REFUSED: ' + (str(error) if isinstance(error, Refused) else type(error).__name__))
sys.exit(1)

View File

@ -0,0 +1,12 @@
#!/bin/sh
# Install root:root 0755. Fixed import path under a root-owned, non-writable tree.
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
try:
main()
except Exception as error:
print("DEPLOYMENT REFUSED: " + (str(error) if isinstance(error, Refused) else type(error).__name__))
sys.exit(1)
' "$@"

View File

@ -0,0 +1,5 @@
# Phase 2: /etc/nginx/conf.d/plotdirector-websocket-map.conf (http context).
map $http_upgrade $plotdirector_connection_upgrade {
default upgrade;
'' close;
}

View File

@ -0,0 +1,35 @@
# Phase 2: /etc/nginx/sites-available/plotdirector (no default_server).
# Certificate must already be valid for both hostnames. Do not edit Catherine's vhost.
server {
listen 80;
listen [::]:80;
server_name plotdirector.com www.plotdirector.com;
return 301 https://plotdirector.com$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name www.plotdirector.com;
ssl_certificate /etc/letsencrypt/live/plotdirector.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/plotdirector.com/privkey.pem;
return 301 https://plotdirector.com$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name plotdirector.com;
ssl_certificate /etc/letsencrypt/live/plotdirector.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/plotdirector.com/privkey.pem;
client_max_body_size 110m;
location / {
proxy_pass http://127.0.0.1:5001;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $plotdirector_connection_upgrade;
proxy_read_timeout 3600s;
proxy_buffering off;
}
}

View File

@ -0,0 +1,2 @@
Defaults:plotdirector-deploy env_reset, !setenv
plotdirector-deploy ALL=(root) NOSETENV: NOPASSWD: /usr/local/sbin/deploy-plotdirector

View File

@ -0,0 +1,34 @@
[Unit]
Description=PlotDirector production application
After=network.target mssql-server.service
Requires=mssql-server.service
[Service]
Type=simple
User=plotdirector
Group=plotdirector
WorkingDirectory=/srv/plotdirector/current
ExecStart=/usr/bin/dotnet /srv/plotdirector/current/PlotLine.dll --contentRoot=/srv/plotdirector/current
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=ASPNETCORE_URLS=http://127.0.0.1:5001
Environment=DOTNET_NOLOGO=1
EnvironmentFile=/etc/plotdirector/plotdirector.env
Restart=on-failure
RestartSec=10
UMask=0027
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectControlGroups=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
ReadWritePaths=/srv/plotdirector/shared
InaccessiblePaths=-/srv/catherinelynwood -/etc/catherinelynwood -/srv/backups -/etc/sql-backup
StandardOutput=journal
StandardError=journal
SyslogIdentifier=plotdirector
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,11 @@
# Phase 2 only. Validate sshd -t and keep administrator session open before reload.
Match User plotdirector-deploy
AuthorizedKeysFile /etc/ssh/authorized_keys/plotdirector-deploy
AuthenticationMethods publickey
PasswordAuthentication no
KbdInteractiveAuthentication no
ForceCommand /usr/local/lib/plotdirector-deployment/ssh_dispatch.py
PermitTTY no
DisableForwarding yes
PermitUserRC no
Match all

View File

@ -0,0 +1,19 @@
{
"format": 1,
"host": "web1",
"environment": "Production",
"database": "PlotLine",
"root": "/srv/plotdirector",
"inbox": "/srv/plotdirector/incoming",
"evidence": "/srv/plotdirector/deployment-evidence",
"backup": "/srv/backups/sql",
"service": "plotdirector.service",
"runtime_account": "plotdirector",
"migration_account": "plotdirector-migrate",
"worker": "/usr/local/lib/plotdirector-deployment/database/DatabaseWorker.dll",
"database_config": "/etc/plotdirector-deployment/database.json",
"public_key": "/etc/plotdirector-deployment/release-signing-public.pem",
"minimum_free_bytes": 2147483648,
"health_base": "http://127.0.0.1:5001",
"runtime_config": "/etc/plotdirector/plotdirector.env"
}

129
Tools/Deployment/qualify.py Normal file
View File

@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Repeat the reviewed SQL upgrade on two fresh Atlas-only database copies.
Recovered backups/configurations and all outputs must be private, outside Git.
No Production connection strings, Docker hosts or database names are accepted.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import uuid
from release import Refused, canonical, file_digest, load, require
DOCKER=['docker','--host','unix:///var/run/docker.sock']
CONTAINER='atlas-sql-server'
ENDPOINT='192.168.10.10,1433'
class Session:
def __init__(self,worker,config):
self.process=subprocess.Popen(['dotnet',str(worker),str(config)],stdin=subprocess.PIPE,
stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True)
self.read()
def read(self):
line=self.process.stdout.readline()
require(bool(line),'Database worker exited')
value=json.loads(line)
require(value.get('ok'),'Qualification blocked: '+str(value.get('error'))+' migration='+str(value.get('migration'))+' batch='+str(value.get('batch')))
return value.get('result',value)
def call(self,op,**data):
self.process.stdin.write(json.dumps({'op':op,**data})+'\n');self.process.stdin.flush()
return self.read()
def close(self):
if self.process.poll() is None:
self.process.stdin.close()
try:self.process.wait(timeout=15)
except subprocess.TimeoutExpired:self.process.kill();self.process.wait()
def main():
parser=argparse.ArgumentParser(description=__doc__)
for option in ('backup','backup-sha256','source','package','worker','output','database-prefix'):
parser.add_argument('--'+option,required=True)
args=parser.parse_args();os.umask(0o077)
require(re.fullmatch(r'PlotDirector_Qualification_[A-Za-z0-9_]{1,65}',args.database_prefix),'Qualification database prefix required')
require(re.fullmatch(r'[a-f0-9]{64}',args.backup_sha256),'Backup checksum required')
source=Path(args.source).resolve();output=Path(args.output).resolve();package=Path(args.package).resolve()
require(not output.exists(),'Qualification output already exists; refuses overwrite')
require(file_digest(args.backup)==args.backup_sha256,'Backup checksum mismatch')
require(not subprocess.check_output(['git','-C',str(source),'status','--porcelain'],text=True).strip(),'Source is not clean')
commit=subprocess.check_output(['git','-C',str(source),'rev-parse','HEAD'],text=True).strip()
manifest=load(package/'manifest.json')
require(manifest['source_commit']==commit,'Plan source differs from clean source')
require(commit.encode() in Path(args.worker).read_bytes(),'Worker was not built from the clean source commit')
metadata=json.loads(subprocess.check_output(DOCKER+['inspect',CONTAINER]))[0]
ports=metadata['HostConfig']['PortBindings'].get('1433/tcp')
require(ports==[{'HostIp':'192.168.10.10','HostPort':'1433'}],'Unexpected Atlas SQL endpoint')
require(any(m['Source']=='/sql/mssql' and m['Destination']=='/var/opt/mssql' for m in metadata['Mounts']),'Unexpected SQL storage mapping')
values=dict(x.split('=',1) for x in metadata['Config']['Env'] if '=' in x)
password=values.get('MSSQL_SA_PASSWORD',values.get('SA_PASSWORD'))
require(bool(password),'Atlas qualification administrator unavailable')
output.mkdir(parents=True,mode=0o700)
unique=uuid.uuid4().hex
media='/var/opt/mssql/backup/qualification-original-'+unique+'.bak'
host_media=Path('/sql/mssql/backup')/Path(media).name
# docker cp never overwrites an existing media path. UUID collision is refused.
require(subprocess.run(DOCKER+['exec',CONTAINER,'test','-e',media]).returncode!=0,'Media destination already exists')
subprocess.run(DOCKER+['cp',str(Path(args.backup).resolve()),CONTAINER+':'+media],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
subprocess.run(DOCKER+['exec','-u','0',CONTAINER,'chown','mssql:mssql',media],check=True)
subprocess.run(DOCKER+['exec','-u','0',CONTAINER,'chmod','600',media],check=True)
def sql(text):
r=subprocess.run(DOCKER+['exec','-i','-e','SQLCMDPASSWORD',CONTAINER,'/opt/mssql-tools18/bin/sqlcmd',
'-S','localhost','-U','sa','-C','-I','-b','-l','10','-t','1800','-y','0'],input=text,text=True,capture_output=True,
env={**os.environ,'SQLCMDPASSWORD':password})
(output/'private-sql-diagnostic.txt').write_text(r.stdout+r.stderr)
require(r.returncode==0,'SQL restore/inspection failed; diagnostic retained privately')
return r.stdout
sql(f"RESTORE VERIFYONLY FROM DISK=N'{media}' WITH CHECKSUM;")
listing=sql(f"RESTORE FILELISTONLY FROM DISK=N'{media}';")
# Restored PlotLine backup has these independently verified logical file names.
# Other media must be reviewed rather than guessed or restored with REPLACE.
require('PlotLine ' in listing and 'PlotLine_log ' in listing,'Unexpected logical backup file names')
results=[]
try:
for ordinal in (1,2):
database=args.database_prefix+'_'+str(ordinal)
sql(f"IF DB_ID(N'{database}') IS NOT NULL THROW 51000,'Refusing existing qualification database',1; RESTORE DATABASE [{database}] FROM DISK=N'{media}' WITH MOVE N'PlotLine' TO N'/var/opt/mssql/data/{database}.mdf',MOVE N'PlotLine_log' TO N'/var/opt/mssql/data/{database}_log.ldf',RECOVERY,CHECKSUM; ALTER AUTHORIZATION ON DATABASE::[{database}] TO [sa]; ALTER DATABASE [{database}] SET TRUSTWORTHY OFF; ALTER DATABASE [{database}] SET DB_CHAINING OFF;")
escaped=password.replace('"','""')
config={'database':database,'expected_host':'atlas','expected_server':ENDPOINT,'connection':f'Server={ENDPOINT};Database={database};User ID=sa;Password="{escaped}";Encrypt=True;TrustServerCertificate=True;'}
config_path=output/(database+'.private.json');config_path.write_bytes(canonical(config))
worker=Session(args.worker,config_path)
try:
before=worker.call('fingerprint')
start=worker.call('inspect');require(start['schema']==manifest['starting_schema_sha256'],'Restored baseline mismatch')
deployment='qualification-'+unique+'-'+str(ordinal)
worker.call('begin',package_root=str(package),deployment_id=deployment,package_sha256='0'*64)
backup='/var/opt/mssql/backup/'+deployment+'-preupgrade.bak'
require(subprocess.run(DOCKER+['exec',CONTAINER,'test','-e',backup]).returncode!=0,'Preupgrade backup exists')
worker.call('backup',path=backup)
migrated=worker.call('migrate');worker.call('health')
after=worker.call('fingerprint',original=before)
changes=[name for name in before if before[name]!=after.get(name)]
require(not changes,'Unexplained business-data changes: '+','.join(changes))
integrity=worker.call('integrity')
(output/(database+'-fingerprints.json')).write_bytes(canonical({'before':before,'after':after}))
results.append({'database':database,'starting_schema_sha256':start['schema'],
'resulting_schema_sha256':migrated['schema'],'original_tables':len(before),
'original_rows':sum(t['rows'] for t in before.values()),'all_original_fingerprints_equal':True,
'fingerprint_sha256':hashlib.sha256(canonical(before)).hexdigest(),'integrity':integrity})
finally:worker.close()
print('QUALIFIED '+database+'; original business data unchanged')
require(results[0]['resulting_schema_sha256']==results[1]['resulting_schema_sha256'],'Non-reproducible resulting schema')
(output/'database-qualification.json').write_bytes(canonical({'status':'passed','source_commit':commit,
'worker_sha256':file_digest(args.worker),'backup_sha256':args.backup_sha256,'runs':results}))
except Exception:
(output/'qualification-status.json').write_bytes(canonical({'status':'blocked','completed_runs':results,
'recovery':'Original backups/databases retained. Do not retry partial state or modify production.'}))
raise
if __name__=='__main__':
try:main()
except Exception as error:
print(str(error) if isinstance(error,Refused) else 'QUALIFICATION FAILED: '+type(error).__name__)
sys.exit(1)

343
Tools/Deployment/release.py Normal file
View File

@ -0,0 +1,343 @@
#!/usr/bin/env python3
"""Immutable release preparation and validation. Standard library + OpenSSL only."""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import stat
import subprocess
import tarfile
import tempfile
LIMIT_BYTES = 4 * 1024**3
LIMIT_FILES = 100000
ID = re.compile(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\Z')
HASH = re.compile(r'[a-f0-9]{64}\Z')
COMMIT = re.compile(r'[a-f0-9]{40}\Z')
class Refused(Exception):
pass
def require(condition, message):
if not condition:
raise Refused(message)
def digest(data):
return hashlib.sha256(data).hexdigest()
def file_digest(path):
with Path(path).open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def canonical(value):
return (json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True) + '\n').encode()
def load(path):
def unique(items):
result = {}
for key, value in items:
require(key not in result, 'Duplicate JSON key')
result[key] = value
return result
require(Path(path).stat().st_size <= 16 * 1024**2, 'Oversized JSON')
return json.loads(Path(path).read_text(), object_pairs_hook=unique)
def keys(value, required, optional=()):
require(isinstance(value, dict) and set(required) <= set(value) <= set(required) | set(optional), 'Invalid fields')
def safe_name(value):
require(isinstance(value, str) and ID.fullmatch(value) and value not in ('.', '..'), 'Invalid identifier')
return value
def safe_path(value):
require(isinstance(value, str) and value and '\\' not in value and not any(ord(c) < 32 or ord(c) == 127 for c in value), 'Invalid path')
p = PurePosixPath(value)
require(not p.is_absolute() and '..' not in p.parts and str(p) == value and value != '.', 'Unsafe path')
return p
def sha(value):
require(isinstance(value, str) and HASH.fullmatch(value), 'Invalid SHA256')
def conditions(items):
require(isinstance(items, list) and len(items) <= 10000, 'Invalid conditions')
for c in items:
require(isinstance(c, dict), 'Invalid condition')
kind = c.get('kind')
required = {'object': ('kind', 'name', 'type'), 'column': ('kind', 'name', 'column'), 'module_sha256': ('kind', 'name', 'sha256'), 'solver_graph': ('kind', 'version', 'sha256')}.get(kind)
require(required is not None, 'Unsupported condition')
keys(c, required)
if kind == 'solver_graph':
require(re.fullmatch(r'[A-Za-z0-9_.-]{1,100}', c['version']), 'Invalid solver version')
sha(c['sha256'])
continue
require(re.fullmatch(r'dbo\.[A-Za-z_][A-Za-z0-9_]{0,127}', c['name']), 'Invalid object name')
if kind == 'object':
require(c['type'] in ('U', 'P', 'FN', 'IF', 'TF', 'V', 'TR'), 'Invalid object type')
if kind == 'column':
require(re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]{0,127}', c['column']), 'Invalid column')
if kind == 'module_sha256':
sha(c['sha256'])
def validate_manifest(m):
keys(m, ('format', 'release_id', 'source_commit', 'version', 'files', 'application_sha256',
'starting_schema_sha256', 'resulting_schema_sha256', 'migrations', 'omitted_migrations',
'prerequisites', 'postconditions', 'health', 'qualification'))
require(m['format'] == 1, 'Unsupported manifest format')
safe_name(m['release_id'])
require(COMMIT.fullmatch(m['source_commit']), 'Full source commit required')
require(isinstance(m['version'], str) and re.fullmatch(r'[A-Za-z0-9.+_-]{1,100}', m['version']), 'Invalid application version')
for field in ('application_sha256', 'starting_schema_sha256', 'resulting_schema_sha256'):
sha(m[field])
require(isinstance(m['files'], dict) and 3 <= len(m['files']) <= LIMIT_FILES, 'Invalid file index')
for name, checksum in m['files'].items():
p = safe_path(name)
require(p.parts[0] in ('app', 'sql', 'evidence'), 'Invalid package area')
require(not any(x.startswith('.') or x in ('App_Data', 'uploads', 'logs', 'Logs') for x in p.parts), 'Persistent/config path in package')
require(not (p.name.startswith('appsettings') and p.suffix == '.json') and p.name not in ('web.config', 'dotnet-tools.json'), 'Configuration in package')
sha(checksum)
for name in ('PlotLine.dll', 'PlotLine.deps.json', 'PlotLine.runtimeconfig.json'):
require('app/' + name in m['files'], 'Incomplete framework-dependent application')
app_index = {k: v for k, v in m['files'].items() if k.startswith('app/')}
require(digest(canonical(app_index)) == m['application_sha256'], 'Application index checksum mismatch')
conditions(m['prerequisites'])
conditions(m['postconditions'])
require(bool(m['postconditions']), 'Release database health checks required')
require(isinstance(m['migrations'], list), 'Invalid migrations')
known = set()
sql_files = set()
for step in m['migrations']:
keys(step, ('id', 'file', 'sha256', 'requires', 'mode', 'prerequisites', 'postconditions'), ('evidence',))
identity = step['id']
require(isinstance(identity, str) and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,199}', identity), 'Invalid migration identity')
require(identity not in known, 'Duplicate migration identity')
require(isinstance(step['requires'], list) and len(set(step['requires'])) == len(step['requires']) and set(step['requires']) <= known, 'Missing or out-of-order migration dependency')
safe_path(step['file'])
require('/' not in step['file'] and step['file'].endswith('.sql') and step['file'] not in sql_files, 'Invalid migration filename')
sql_files.add(step['file'])
sha(step['sha256'])
require(m['files'].get('sql/' + step['file']) == step['sha256'], 'Migration absent from index or checksum mismatch')
require(step['mode'] in ('execute', 'baseline'), 'Non-transactional migration requires a separately reviewed recovery procedure')
if step['mode'] == 'baseline':
require(isinstance(step.get('evidence'), str) and step['evidence'].startswith('evidence/') and step['evidence'] in m['files'], 'Historical baseline evidence required')
else:
require('evidence' not in step, 'Execution cannot claim historical baseline evidence')
conditions(step['prerequisites'])
conditions(step['postconditions'])
require(bool(step['postconditions']), 'Migration postconditions required')
known.add(identity)
require({n[4:] for n in m['files'] if n.startswith('sql/')} == sql_files, 'Unapproved SQL file')
require(isinstance(m['omitted_migrations'], list), 'Invalid omitted migrations')
for omitted in m['omitted_migrations']:
keys(omitted, ('id', 'sha256', 'reason', 'evidence'))
require(omitted['id'] not in known and isinstance(omitted['reason'], str) and len(omitted['reason']) > 10, 'Invalid omitted migration')
sha(omitted['sha256'])
require(omitted['evidence'] in m['files'] and omitted['evidence'].startswith('evidence/'), 'Omission evidence missing')
known.add(omitted['id'])
require(m['health'] == ['http-root', 'http-login', 'http-deployment-identity', 'database-postconditions', 'binary-identity'], 'Unsupported health checks')
require(isinstance(m['qualification'], dict) and m['qualification'].get('status') == 'passed', 'Release is not qualified')
keys(m['qualification'], ('status', 'evidence'))
require(m['qualification']['evidence'] in m['files'] and m['qualification']['evidence'].startswith('evidence/'), 'Qualification evidence absent')
def qualification_identity(m, evidence):
require(evidence.get('status') == 'passed' and evidence.get('source_commit') == m['source_commit'], 'Qualification source identity mismatch')
require(evidence.get('application_dll_sha256') == m['files']['app/PlotLine.dll'], 'Qualification binary identity mismatch')
require(evidence.get('starting_schema_sha256') == m['starting_schema_sha256']
and evidence.get('resulting_schema_sha256') == m['resulting_schema_sha256'], 'Qualification database identity mismatch')
def extract(archive, destination):
"""Only called on a private, verified snapshot; never uses extractall."""
destination = Path(destination)
total = 0
names = set()
with tarfile.open(archive, 'r:') as tar:
for member in tar:
name = str(safe_path(member.name))
require(member.isfile() and not member.pax_headers and not member.linkname, 'Archive must contain plain regular files only')
require(name not in names and len(names) < LIMIT_FILES, 'Duplicate or excessive archive entries')
names.add(name)
total += member.size
require(0 <= member.size and total <= LIMIT_BYTES, 'Archive exceeds size limit')
require(name == 'manifest.json' or PurePosixPath(name).parts[0] in ('app', 'sql', 'evidence'), 'Unexpected archive path')
out = destination / name
out.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
with out.open('xb') as target, tar.extractfile(member) as source:
while block := source.read(1024**2):
target.write(block)
out.chmod(0o600)
require('manifest.json' in names, 'Missing manifest')
m = load(destination / 'manifest.json')
validate_manifest(m)
require(names == set(m['files']) | {'manifest.json'}, 'Package files differ from manifest')
for name, checksum in m['files'].items():
require(file_digest(destination / name) == checksum, 'File checksum mismatch')
runtime = load(destination / 'app/PlotLine.runtimeconfig.json')
require(runtime.get('runtimeOptions', {}).get('tfm') == 'net10.0', 'Unexpected application runtime')
deps = load(destination / 'app/PlotLine.deps.json')
require('PlotLine/' + m['version'] in deps.get('libraries', {}), 'Application package version mismatch')
require((m['version'] + '+' + m['source_commit']).encode() in (destination / 'app/PlotLine.dll').read_bytes(), 'Assembly source commit mismatch')
qualification_identity(m, load(destination / m['qualification']['evidence']))
return m
def snapshot(path, destination, max_bytes):
"""Descriptor-relative, no-follow input. A changing source cannot bypass signature."""
path = Path(path)
require(path.is_absolute(), 'Absolute source path required')
fd = os.open('/', os.O_RDONLY | os.O_DIRECTORY)
try:
for part in path.parts[1:-1]:
next_fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
os.close(fd)
fd = next_fd
source_fd = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=fd)
with os.fdopen(source_fd, 'rb') as source, Path(destination).open('xb') as out:
info = os.fstat(source.fileno())
require(stat.S_ISREG(info.st_mode) and info.st_nlink == 1 and info.st_size <= max_bytes, 'Unsafe input file')
count = 0
while data := source.read(1024**2):
count += len(data)
require(count <= max_bytes, 'Input size exceeded')
out.write(data)
finally:
os.close(fd)
def verify_bundle(source, work, public_key):
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',
'-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')
return manifest, authorization, payload
def prepare(args):
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')
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.
keys(plan, ('starting_schema_sha256', 'resulting_schema_sha256', 'migrations', 'omitted_migrations', 'prerequisites', 'postconditions', 'qualification'))
output = Path(args.output).resolve()
require(not output.exists(), 'Release destination already exists')
output.mkdir(mode=0o700, parents=True)
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),
'-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)
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)
print(json.dumps(authorization, sort_keys=True))
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
p = sub.add_parser('prepare')
for field in ('source', 'plan', 'sql', 'evidence', 'output', 'release-id', 'signing-key'):
p.add_argument('--' + field, required=True)
v = sub.add_parser('verify')
v.add_argument('bundle')
v.add_argument('--public-key', required=True)
args = parser.parse_args()
os.umask(0o077)
try:
if args.command == 'prepare':
prepare(args)
else:
with tempfile.TemporaryDirectory(prefix='pd-verify-') as work:
m, a, _ = verify_bundle(Path(args.bundle).resolve(), work, args.public_key)
print(json.dumps({'verified': True, 'release_id': m['release_id'], 'package_sha256': a['package_sha256']}))
except (Refused, ValueError, OSError, subprocess.CalledProcessError) as error:
print('RELEASE REFUSED: ' + (str(error) if isinstance(error, Refused) else type(error).__name__))
raise SystemExit(1)
if __name__ == '__main__':
main()

View File

@ -0,0 +1,53 @@
#!/usr/bin/python3 -I
"""Forced SSH command for plotdirector-deploy; no shell, SFTP or arbitrary paths."""
import os
from pathlib import Path
import re
import subprocess
import sys
import tarfile
INBOX=Path('/srv/plotdirector/incoming')
LIMIT=4*1024**3
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)
if not match or match[2] in ('.','..'):
raise ValueError('Unsupported deployment operation')
operation,release=match.groups()
if operation!='upload':
args=['/usr/bin/sudo','-n','/usr/local/sbin/deploy-plotdirector']
if operation=='validate':args.append('--validate')
if operation=='rollback':args.append('--rollback')
args.append(release)
raise SystemExit(subprocess.run(args,env={'PATH':'/usr/sbin:/usr/bin:/sbin:/bin','LANG':'C.UTF-8'},cwd='/').returncode)
destination=INBOX/release
destination.mkdir(mode=0o700) # Refuses replacement, including symlinks.
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:
raise ValueError('Invalid transfer member')
received.add(member.name)
limit=LIMIT if member.name=='package.tar' 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')
with tar.extractfile(member) as source,(destination/member.name).open('xb') as target:
while block:=source.read(1024**2):target.write(block)
target.flush();os.fsync(target.fileno())
if received!={'package.tar','authorization.json','authorization.sig'}:
raise ValueError('Incomplete transfer; administrator must remove the incomplete incoming directory before retry')
print('UPLOADED '+release+'; activation has not been performed')
if __name__=='__main__':
try:main()
except Exception:
print('DEPLOYMENT REQUEST REFUSED; no command was shell-evaluated',file=sys.stderr)
sys.exit(1)

View File

@ -0,0 +1,128 @@
import hashlib
import json
from pathlib import Path
import tempfile
import unittest
import fcntl
from unittest.mock import patch
from types import SimpleNamespace
import activate
from release import Refused,canonical
class ActivationFailureTests(unittest.TestCase):
def setUp(self):
self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name)
for name in ('releases','inbox/new-release','evidence','backup','old/app'):(self.root/name).mkdir(parents=True)
(self.root/'inbox/new-release/package.tar').write_bytes(b'fixture')
(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.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'}
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')
def call(self,op,**values):
outer.calls.append(op)
if outer.failure==op:raise Refused('Injected '+op+' failure')
if op=='backup':Path(values['path']).write_bytes(b'verified-fixture')
if op=='begin':return {'complete':outer.complete}
if op=='activated':outer.activations.append(values)
return {}
def close(self):outer.calls.append('worker-close')
self.FakeWorker=FakeWorker
def tearDown(self):self.temp.cleanup()
def bundle(self,source,work,key):
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
def command(self,args,**kwargs):
if args[0].endswith('systemctl'):
action=args[1];self.calls.append('service-'+action)
if action=='stop':self.state='inactive'
if action=='start':self.state='active'
return self.state
if args[0].endswith('curl'):
self.calls.append('http')
return self.status if '--output' in args else json.dumps({'healthy':True,'version':'1.0.0','sourceCommit':'a'*40,'database':'PlotLine'})
raise AssertionError('Unexpected executable')
def run_activation(self,validate=False,free=10**12,rollback=False):
# Root-only OS operations are mocked; archive validation and actual SQL
# transactions/concurrency are independently exercised by their test suites.
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.time,'sleep'),patch.object(activate.shutil,'disk_usage',return_value=SimpleNamespace(free=free)):
activate.activate('new-release',validate,rollback)
def test_validation_does_not_backup_migrate_or_stop_service(self):
self.run_activation(validate=True)
self.assertNotIn('backup',self.calls);self.assertNotIn('migrate',self.calls);self.assertNotIn('service-stop',self.calls)
def test_backup_verification_failure_prevents_shutdown(self):
self.failure='backup'
with self.assertRaises(Refused):self.run_activation()
self.assertNotIn('service-stop',self.calls);self.assertNotIn('migrate',self.calls)
def test_migration_failure_keeps_old_target_and_service_stopped(self):
self.failure='migrate'
with self.assertRaises(Refused):self.run_activation()
self.assertEqual((self.root/'current').resolve(),self.root/'releases/old-release/app')
self.assertEqual(self.state,'inactive');self.assertNotIn('activated',self.calls)
def test_failed_application_health_never_records_success(self):
self.status='500'
with self.assertRaises(Refused):self.run_activation()
self.assertEqual(self.state,'inactive');self.assertNotIn('activated',self.calls)
self.assertEqual(json.loads((self.root/'active-deployment.json').read_text())['deployment'],'previous-success')
def test_success_is_recorded_after_http_and_database_health(self):
self.run_activation()
self.assertLess(self.calls.index('http'),self.calls.index('health'))
self.assertLess(self.calls.index('health'),self.calls.index('activated'))
self.assertEqual((self.root/'current').resolve(),self.root/'releases/new-release/app')
self.assertEqual(self.state,'active')
def test_insufficient_space_prevents_any_database_or_service_operations(self):
with self.assertRaises(Refused):self.run_activation(free=0)
self.assertEqual(self.calls,[])
def test_install_permission_failure_leaves_service_stopped(self):
with patch.object(activate,'install',side_effect=PermissionError('injected')):
with self.assertRaises(PermissionError):self.run_activation()
self.assertEqual(self.state,'inactive');self.assertNotIn('activated',self.calls)
def test_failed_release_history_write_stops_application(self):
self.failure='activated'
with self.assertRaises(Refused):self.run_activation()
self.assertEqual(self.state,'inactive')
self.assertEqual(json.loads((self.root/'active-deployment.json').read_text())['deployment'],'previous-success')
def test_competing_filesystem_activation_is_rejected(self):
with (self.root/'deployment.lock').open('r+') as held:
fcntl.flock(held,fcntl.LOCK_EX|fcntl.LOCK_NB)
with self.assertRaises(Refused):self.run_activation()
self.assertEqual(self.calls,[])
def test_rollback_refuses_outstanding_sql(self):
with self.assertRaises(Refused):self.run_activation(rollback=True)
self.assertNotIn('backup',self.calls);self.assertNotIn('migrate',self.calls)
def test_rollback_records_new_success_only_after_health(self):
self.complete=True;self.run_activation(rollback=True)
self.assertEqual(self.activations[0]['kind'],'Rollback')
self.assertEqual(self.activations[0]['previous_deployment'],'previous-success')
if __name__=='__main__':unittest.main()

View File

@ -0,0 +1,173 @@
import copy
import io
import json
import os
from pathlib import Path
import subprocess
import tarfile
import tempfile
import unittest
import release
class ReleaseBoundaryTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.root = Path(self.temp.name)
self.commit = 'a' * 40
self.files = {
'app/PlotLine.dll': ('1.0.0+'+self.commit).encode(),
'app/PlotLine.deps.json': b'{"libraries":{"PlotLine/1.0.0":{"type":"project"}}}',
'app/PlotLine.runtimeconfig.json': b'{"runtimeOptions":{"tfm":"net10.0"}}',
'evidence/qualified.json': b'{"status":"passed"}',
}
index = {p: release.digest(b) for p, b in self.files.items()}
self.manifest = {
'format': 1, 'release_id': 'fixture-release', 'source_commit': self.commit, 'version': '1.0.0',
'files': index, 'application_sha256': release.digest(release.canonical({k:v for k,v in index.items() if k.startswith('app/')})),
'starting_schema_sha256': 'b'*64, 'resulting_schema_sha256': 'c'*64,
'migrations': [], 'omitted_migrations': [], 'prerequisites': [],
'postconditions': [{'kind':'object','name':'dbo.Books','type':'U'}],
'health': ['http-root','http-login','http-deployment-identity','database-postconditions','binary-identity'],
'qualification': {'status':'passed','evidence':'evidence/qualified.json'},
}
self.files['evidence/qualified.json']=release.canonical({'status':'passed','source_commit':self.commit,
'application_dll_sha256':self.manifest['files']['app/PlotLine.dll'],
'starting_schema_sha256':'b'*64,'resulting_schema_sha256':'c'*64})
self.manifest['files']['evidence/qualified.json']=release.digest(self.files['evidence/qualified.json'])
def tearDown(self):
self.temp.cleanup()
def archive(self, extras=(), manifest=None):
archive = self.root / 'test.tar'
with tarfile.open(archive, 'w', format=tarfile.USTAR_FORMAT) as tar:
for name, data in [*self.files.items(), ('manifest.json', release.canonical(manifest or self.manifest)), *extras]:
entry = tarfile.TarInfo(name)
entry.size = len(data)
tar.addfile(entry, io.BytesIO(data))
return archive
def output(self):
dest = self.root / 'output'
dest.mkdir()
return dest
def test_valid_package_extracts_exact_index(self):
self.assertEqual(release.extract(self.archive(), self.output()), self.manifest)
def test_path_traversal_is_rejected(self):
with self.assertRaises(release.Refused):
release.extract(self.archive([('../escaped',b'x')]),self.output())
self.assertFalse((self.root.parent / 'escaped').exists())
def test_duplicate_member_is_rejected(self):
with self.assertRaises(release.Refused):
release.extract(self.archive([('app/PlotLine.dll',b'replaced')]),self.output())
def test_unindexed_files_are_rejected(self):
with self.assertRaises(release.Refused):
release.extract(self.archive([('app/unreviewed.dll',b'x')]),self.output())
def test_application_configuration_is_rejected(self):
m=copy.deepcopy(self.manifest)
m['files']['app/appsettings.Production.json']='a'*64
with self.assertRaises(release.Refused): release.validate_manifest(m)
def test_file_integrity_is_enforced(self):
self.files['app/PlotLine.dll']=b'changed'
with self.assertRaises(release.Refused): release.extract(self.archive(),self.output())
def test_symlinks_hardlinks_and_special_members_are_rejected(self):
for kind in (tarfile.SYMTYPE,tarfile.LNKTYPE,tarfile.FIFOTYPE,tarfile.CHRTYPE):
with self.subTest(kind=kind):
archive=self.root/'special.tar'
with tarfile.open(archive,'w') as tar:
item=tarfile.TarInfo('app/link');item.type=kind;item.linkname='/etc/shadow';tar.addfile(item)
dest=self.root/('out-'+str(kind));dest.mkdir()
with self.assertRaises(release.Refused):release.extract(archive,dest)
def test_duplicate_json_keys_are_rejected(self):
path=self.root/'duplicate.json';path.write_text('{"format":1,"format":2}')
with self.assertRaises(release.Refused):release.load(path)
def test_unqualified_release_is_rejected(self):
self.manifest['qualification']['status']='pending'
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
def test_stale_qualification_identity_is_rejected(self):
evidence=json.loads(self.files['evidence/qualified.json']);evidence['source_commit']='f'*40
with self.assertRaises(release.Refused):release.qualification_identity(self.manifest,evidence)
evidence['source_commit']=self.commit;evidence['application_dll_sha256']='f'*64
with self.assertRaises(release.Refused):release.qualification_identity(self.manifest,evidence)
def migration(self, identity='318_DeploymentHistory', requires=()):
filename=identity+'.sql';data=b'SELECT 1;'
self.files['sql/'+filename]=data
self.manifest['files']['sql/'+filename]=release.digest(data)
return {'id':identity,'file':filename,'sha256':release.digest(data),'requires':list(requires),
'mode':'execute','prerequisites':[], 'postconditions':[{'kind':'object','name':'dbo.Books','type':'U'}]}
def test_missing_and_out_of_order_dependencies_block(self):
self.manifest['migrations']=[self.migration(requires=['unknown'])]
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
def test_duplicate_migration_id_blocks(self):
step=self.migration();self.manifest['migrations']=[step,copy.deepcopy(step)]
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
def test_modified_migration_checksum_blocks(self):
step=self.migration();step['sha256']='a'*64;self.manifest['migrations']=[step]
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
def test_baseline_requires_evidence_and_never_claims_execution(self):
step=self.migration();step['mode']='baseline';self.manifest['migrations']=[step]
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
step['evidence']='evidence/qualified.json';release.validate_manifest(self.manifest)
def test_nontransactional_migration_is_explicitly_refused(self):
step=self.migration();step['mode']='nontransactional';self.manifest['migrations']=[step]
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
def test_arbitrary_shell_health_hook_is_rejected(self):
self.manifest['health'].append('sh -c anything')
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
def test_manifest_cannot_select_service_or_destination(self):
self.manifest['service']='catherinelynwood.service'
with self.assertRaises(release.Refused):release.validate_manifest(self.manifest)
def test_input_snapshot_refuses_symlink_and_hardlink(self):
source=self.root/'source';source.write_bytes(b'fixture')
link=self.root/'link';link.symlink_to(source)
with self.assertRaises(OSError):release.snapshot(link,self.root/'copy',100)
link.unlink();os.link(source,link)
with self.assertRaises(release.Refused):release.snapshot(link,self.root/'copy2',100)
def test_input_snapshot_is_independent(self):
source=self.root/'source';source.write_bytes(b'original');dest=self.root/'copy'
release.snapshot(source,dest,100);source.write_bytes(b'changed')
self.assertEqual(dest.read_bytes(),b'original')
def test_signature_and_envelope_integrity(self):
private=self.root/'key.pem';public=self.root/'public.pem'
subprocess.run(['openssl','genpkey','-algorithm','ED25519','-out',str(private)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
subprocess.run(['openssl','pkey','-in',str(private),'-pubout','-out',str(public)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
bundle=self.root/'bundle';bundle.mkdir()
self.archive().rename(bundle/'package.tar')
authorization={'format':1,'release_id':self.manifest['release_id'],'source_commit':self.commit,
'package_sha256':release.file_digest(bundle/'package.tar'), 'manifest_sha256':release.digest(release.canonical(self.manifest))}
(bundle/'authorization.json').write_bytes(release.canonical(authorization))
subprocess.run(['openssl','pkeyutl','-sign','-inkey',str(private),'-rawin','-in',str(bundle/'authorization.json'),'-out',str(bundle/'authorization.sig')],check=True)
work=self.root/'verify';work.mkdir();release.verify_bundle(bundle,work,public)
(bundle/'package.tar').write_bytes(b'modified')
work2=self.root/'verify2';work2.mkdir()
with self.assertRaises(release.Refused):release.verify_bundle(bundle,work2,public)
(bundle/'authorization.json').write_bytes(b'{}')
work3=self.root/'verify3';work3.mkdir()
with self.assertRaises(release.Refused):release.verify_bundle(bundle,work3,public)
if __name__=='__main__':
unittest.main()

View File

@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Atlas-side immutable transfer. Upload only; activation is a separate operation."""
import argparse
import os
from pathlib import Path
import subprocess
import tarfile
from release import load, safe_name, require
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()