PlotDirector/Docs/Deployment/Production.md

265 lines
18 KiB
Markdown

# 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`. Migration 319 adds the local SQL health probe; 322 makes the actual runtime identity/permissions a health gate. Standalone migration 321 defines the runtime permission contract; isolated predecessor 320 is superseded and is not deployed to a new environment. 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. Development has adopted 318/319/321/322 and the restricted runtime role, with its existing application process preserved. 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 reconciles the fixed runtime permission policy (not a manifest hook) and 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/incoming-upload.lock` (empty regular file) | root:plotdirector-deploy | 0660 |
| `/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 in `PlotDirectorRuntime`, no server role or db_owner. The role permits business DML and procedure execution; explicit denials protect migration/release history and the permission-policy procedure. The login receives no direct table/schema DDL or database-backup permission. The reviewed project-restore procedure alone uses owner context for its bounded restore operations, with TRUSTWORTHY and database/server cross-database chaining disabled. Validate these flags before migration. The history role is verified using a non-authenticatable database probe principal.
After 321, map the runtime user to `PlotDirectorRuntime` and remove legacy db_owner membership; verify database ownership/server roles separately. Do not reduce privileges on an existing environment until the actual export/restore path has passed in an isolated clone.
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.
Explicitly provision `Features__ParagraphManuscripts=true`, the production `Site__PublicBaseUrl`, the intended worker/indexing flags and allowed-host/admin settings; these must not silently inherit the historical release defaults. 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.