From e6b2a6d239e4c8d16213f5a9baf1cd87b827ac64 Mon Sep 17 00:00:00 2001 From: Atlas Development Worker Date: Wed, 2 Dec 2026 20:08:05 +0000 Subject: [PATCH] Enable automatic Development SQL qualification and transactional releases --- AGENTS.md | 11 + Docs/Codex/Database.md | 2 +- Docs/Codex/Deployment.md | 32 ++- Docs/Deployment/AutomaticDevelopment.md | 68 ++++++ Tools/Deployment/DatabaseWorker/Program.cs | 12 +- .../DatabaseWorker/packages.lock.json | 181 +++++++++++++++ Tools/Deployment/activate.py | 31 +-- Tools/Deployment/development.py | 27 +++ Tools/Deployment/development_plan.py | 82 +++++++ Tools/Deployment/development_qualification.py | 218 ++++++++++++++++++ Tools/Deployment/development_release.py | 106 ++++++--- .../provision/install-unattended-release.sh | 2 +- Tools/Deployment/sandbox_build.py | 4 +- Tools/Deployment/test_activation.py | 21 +- Tools/Deployment/test_development.py | 6 +- Tools/Deployment/test_development_plan.py | 61 +++++ 16 files changed, 792 insertions(+), 72 deletions(-) create mode 100644 Docs/Deployment/AutomaticDevelopment.md create mode 100644 Tools/Deployment/DatabaseWorker/packages.lock.json create mode 100644 Tools/Deployment/development_plan.py create mode 100644 Tools/Deployment/development_qualification.py create mode 100644 Tools/Deployment/test_development_plan.py diff --git a/AGENTS.md b/AGENTS.md index fac7a184..d2a6a80a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -215,3 +215,14 @@ print credentials, record login traces/storageState, target Production or use SQ sudo for routine browser fixtures. Preserve pending run journals and use documented resume cleanup on failure. Report deployed commit, URLs, actual checks, cleanup and limitations in CYJ; task-specific acceptance must still be performed by its worker. + +## Standing automatic Development authority (2 December 2026) + +Routine Development .NET, stored procedure/function, schema and data migrations are +automatically authorised, including multiple corrective deployments in one controller +execution. Use the installed controller-mediated mechanism documented in +`Docs/Deployment/AutomaticDevelopment.md`. No individual operator SQL approval or new +worker execution is required. `failed_safe` results permit correction/new request; +uncertain live effects require reconciliation. Preserve applied hashes and migration +ordering. Functional owner acceptance remains separate. Production always needs +explicit owner approval and is unavailable through this Development path. diff --git a/Docs/Codex/Database.md b/Docs/Codex/Database.md index f368bbbf..977aec56 100644 --- a/Docs/Codex/Database.md +++ b/Docs/Codex/Database.md @@ -69,7 +69,7 @@ Before schema or data changes: 1. Verify the development database. 2. Back up development using a unique SQL Server backup filename. 3. Verify the backup command succeeded and the backup exists. -4. Execute only the approved manifest through its deployment worker, in explicit dependency order. +4. Execute the automatically qualified Development manifest through its deployment worker, in explicit dependency order. Routine Development schema/data changes have standing owner approval; do not request individual SQL approval. Production remains separately authorised. Apply scripts separately with `SET ANSI_NULLS ON` and `SET QUOTED_IDENTIFIER ON`. diff --git a/Docs/Codex/Deployment.md b/Docs/Codex/Deployment.md index cf63c776..010be294 100644 --- a/Docs/Codex/Deployment.md +++ b/Docs/Codex/Deployment.md @@ -95,13 +95,31 @@ receipt before taking further action; the helper does not blindly roll back SQL. ## SQL changes and recovery -The routine command deliberately rejects changed SQL. A schema release needs an -explicit reviewed plan qualified against Development's schema, using the standard -`release.py` package contract and `DatabaseWorker`. Read -[database operations](Database.md) and the [manifest/history contract](../Deployment/Production.md). -Never replay all SQL files, infer history from a migration number, or adopt a -Production baseline. Update the approved Development code-only baseline only after -successful schema qualification and activation. +Owner standing policy (2 December 2026) automatically authorises routine Development +.NET, procedure/function, schema and data releases, including successive corrective +releases in one execution. There is no per-release human SQL approval. Production +still requires explicit owner approval; Development deployment and functional owner +acceptance are separate activities. + +The installed adapter appends new numbered migrations to the actual successful +Development manifest, preserves all historical hashes and ordering, and automatically +qualifies pending SQL on one disposable copy restored from a verified Development +backup. Candidate SQL runs as a temporary login restricted to that copy; fixed +maintenance statements alone use administrative credentials. The normal signed +manifest/history worker then checks live schema/history, takes verified recovery, +stops the application, applies transactional scripts and activates/health-checks the +application. Unchanged schema skips qualification, SQL backup and migration execution. +The successful manifest becomes the next baseline automatically. + +Use the existing controller `deployment-request` / `deployment-result` commands. +Results include phase, safe build errors, migration error code/script/batch/line, +committed script counts, actual deployed identity and history. `failed_safe` means +no live database/application change: correct the cause and submit a fresh request +key within the same execution. An uncertain activation or partial live migration +remains `recovery_required`; inspect the receipt before proceeding. Never blindly +replay an uncertain release. The installed helper's `--status` provides read-only +identity/schema/history without exposing credentials. Never replay the SQL directory +or use a Production baseline. See [automatic Development operations](../Deployment/AutomaticDevelopment.md). An application rollback needs a signed package with a new release identifier and compatible schema. `--rollback` requires all migration history already present; diff --git a/Docs/Deployment/AutomaticDevelopment.md b/Docs/Deployment/AutomaticDevelopment.md new file mode 100644 index 00000000..49f937ec --- /dev/null +++ b/Docs/Deployment/AutomaticDevelopment.md @@ -0,0 +1,68 @@ +# Automatic PlotDirector Development deployment + +Owner policy, 2 December 2026: application, SQL-only, combined schema/data and +corrective Development releases are automatically authorised. Production deployment +is not authorised by this policy. Feature acceptance remains the feature worker’s +responsibility. + +## Worker operation + +Commit tested source, then use the existing `deployment-request` command for +`application-development` and poll `deployment-result`. Use one unique key per +intent. The controller rechecks the current task, dependencies, assignment, claim, +full commit and root-owned Development-only policy at every admission. + +New SQL uses the next free numbered filename under `PlotLine/Sql`. Applied scripts +are immutable; procedure/function revisions are new forward migrations. The installed +planner preserves the complete ledger, appends new scripts in order, and refuses +number collisions. Data-only migrations are supported transactionally. Qualification +and live postconditions plus the measured resulting schema detect structural errors. +Use task-specific smoke/persistence checks for functional correctness; no routine +full application regression is imposed by the deployment adapter. + +Pending SQL is tested on a disposable restored copy. Its temporary login has rights +only in that copy and never receives the live migrator credentials. The independent +installed DatabaseWorker executes SQL under that identity. A fixed maintenance broker +backs up/restores/drops generated copies; it never executes release SQL as administrator. +Recovery backups are retained. Application-only changes skip all this SQL work. + +The existing deployment lock, SQL application lock, verified backup, migration history, +transaction per script, fixed target, immutable signed package, service stop, health +and full binary/source identity checks remain. Successful activation refreshes the +root-controlled baseline. Root/code/service/secret permissions are not delegated +to workers. Production tooling, configuration, signatures and approval policy are +unchanged. + +## Diagnostics and correction + +`failed_safe` identifies a known failure before live activation. Results include +phase, actionable build diagnostics or SQL code/script/batch/line, applied counts, +current deployed commit and migration history. Fix and submit another key in the +same execution. Durable linked attempt records preserve every failed attempt and +block replay after an uncertain/crashed attempt. Worker-written mailbox results are +never authoritative. + +`recovery_required` means the external effect is uncertain or live activation failed. +Do not replay it. Inspect the original protected receipt and actual state. Partial +migration failure may have committed earlier scripts; keep the service stopped and +recover or make an explicitly reconciled forward correction. Never restart an old +application against an incompatible schema. Read-only installed helper `--status` +reports actual binary, service, database schema/history and last successful marker. +The controller returns those facts without granting worker sudo or credentials. + +## Infrastructure maintenance + +Drain the controller, let current executions finish, then stop it. Preserve branches, +working changes, receipts and request stores. Review exact source/diff, run focused +contained tests, and data-copy a protected snapshot with hashes. Build only the +reviewed independent DatabaseWorker through `atlas-worker-exec tooling-build` with +locked dependencies. Snapshot the existing installed files before replacing them. +Never run a repository installer with administrative authority. Install only reviewed +code and independently built tooling; no change to sudo rules is needed. The +unprivileged adapter needs `development_plan.py`; the existing Development helper +needs `development_qualification.py`, `development_plan.py` and the reviewed worker. +The Production installation is deliberately untouched. + +Commission using real Development activations: application-only, SQL-only, combined, +successive correction and controlled copy/build failure. Check receipts and actual +identity/history, then restore the controller and normal queue polling. diff --git a/Tools/Deployment/DatabaseWorker/Program.cs b/Tools/Deployment/DatabaseWorker/Program.cs index 68024a8d..377182e7 100644 --- a/Tools/Deployment/DatabaseWorker/Program.cs +++ b/Tools/Deployment/DatabaseWorker/Program.cs @@ -58,7 +58,7 @@ internal static class Program { Console.WriteLine(JsonSerializer.Serialize(new { ok = false, error = e is SqlException se ? "SQL_" + se.Number : e.Message is "baseline" or "concurrent-deployment" or "immutable-migration-checksum" ? e.Message : e.GetType().Name, - migration = currentMigration, batch = currentBatch, executed, baselined, committed = committed.Take(256) })); + migration = currentMigration, batch = currentBatch, sql_line = e is SqlException sqlError ? sqlError.LineNumber : 0, executed, baselined, committed = committed.Take(256) })); // A failed command poisons the session. Never proceed to activation. return 1; } @@ -86,7 +86,7 @@ internal static class Program private static async Task Execute(JsonObject request) { var op = S(request, "op"); - if (op == "inspect") return new { schema = await Schema(), database }; + if (op == "inspect") return new { schema = await Schema(), database, history = await HistoryStatus() }; if(op is "fingerprint" or "integrity") { if(!database.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal)) @@ -134,8 +134,10 @@ internal static class Program await backup.ExecuteNonQueryAsync(); return new { verified = true }; } - if (op == "migrate") + if (op is "migrate" or "qualify-migrate") { + if(op == "qualify-migrate" && !database.StartsWith("PlotDirector_Qualification_", StringComparison.Ordinal)) + throw new InvalidOperationException("qualification-only"); await Idle(); foreach (var node in manifest["migrations"]!.AsArray()) await Migration(node!.AsObject()); // Fixed policy, never an executable hook supplied by a manifest. New @@ -143,7 +145,7 @@ internal static class Program if(await Scalar("SELECT OBJECT_ID(N'dbo.Deployment_ApplyRuntimePermissions',N'P')") is not DBNull) await Run("EXEC dbo.Deployment_ApplyRuntimePermissions;"); var schema = await Schema(); - if (schema != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("resulting-schema"); + if (op != "qualify-migrate" && schema != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("resulting-schema"); await Conditions(manifest["postconditions"]!.AsArray()); return new { schema, executed, baselined, committed=committed.Take(256), committed_list_truncated=committed.Count>256 }; } @@ -233,7 +235,7 @@ internal static class Program private static async Task HistoryStatus() { - var expected=manifest!["migrations"]!.AsArray().Count; + var expected=manifest?["migrations"]?.AsArray().Count ?? 0; if(await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull) return new {expected,recorded=0,baselined=0,executed=0}; int recorded,baselineCount,executedCount; diff --git a/Tools/Deployment/DatabaseWorker/packages.lock.json b/Tools/Deployment/DatabaseWorker/packages.lock.json new file mode 100644 index 00000000..b16c064a --- /dev/null +++ b/Tools/Deployment/DatabaseWorker/packages.lock.json @@ -0,0 +1,181 @@ +{ + "version": 1, + "dependencies": { + "net10.0": { + "Microsoft.Data.SqlClient": { + "type": "Direct", + "requested": "[7.0.1, )", + "resolved": "7.0.1", + "contentHash": "9jZFXAJ2ThNYK7lhj2RhH7klXVNaWSvZpQncq3bPIOjmHBrdjwgeO4c8wucUVxQwFT8rAA13Z2F2jzoYR7ICDw==", + "dependencies": { + "Microsoft.Bcl.Cryptography": "9.0.13", + "Microsoft.Data.SqlClient.Extensions.Abstractions": "1.0.0", + "Microsoft.Data.SqlClient.Internal.Logging": "1.0.0", + "Microsoft.Data.SqlClient.SNI.runtime": "6.0.2", + "Microsoft.Extensions.Caching.Memory": "9.0.13", + "Microsoft.IdentityModel.JsonWebTokens": "8.16.0", + "Microsoft.IdentityModel.Protocols.OpenIdConnect": "8.16.0", + "Microsoft.SqlServer.Server": "1.0.0", + "System.Configuration.ConfigurationManager": "9.0.13", + "System.Security.Cryptography.Pkcs": "9.0.13" + } + }, + "System.Security.Cryptography.Pkcs": { + "type": "Direct", + "requested": "[9.0.21, )", + "resolved": "9.0.21", + "contentHash": "KD+oHoYIxwNCajjVe58WVwq9cRpum+Pg3tRveDRtkcaw6w3oc7sNBoMRtb5P5OehI3bgv1ucMpgjf8lpj5J96A==" + }, + "Microsoft.Bcl.Cryptography": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "5T+bH3Lb1nEe8Hf/ixMxLmhlrx5wRi53wv7OhVwG2F1ZviW1ejFRS1NHur3uqPpJRGtkQwUchtY6zhVK2R+v+w==" + }, + "Microsoft.Data.SqlClient.Extensions.Abstractions": { + "type": "Transitive", + "resolved": "1.0.0", + "contentHash": "rlnxc0KfwDSbE8ZHntFnl8SCgOa9QtJZblMv2zXLhRwl1Je7fsdsVzxSjzzC4JMsfAK+jXJWyezRB8SxUY4BdA==", + "dependencies": { + "Microsoft.Data.SqlClient.Internal.Logging": "1.0.0" + } + }, + "Microsoft.Data.SqlClient.Internal.Logging": { + "type": "Transitive", + "resolved": "1.0.0", + "contentHash": "Kue/7CF8KNT9zozfr30C94dMZVZml3atqWZvQemSXvTau76tRdypzeKiBKXadqgbOME0UiQIyVTNo5WxCRNVNg==" + }, + "Microsoft.Data.SqlClient.SNI.runtime": { + "type": "Transitive", + "resolved": "6.0.2", + "contentHash": "f+pRODTWX7Y67jXO3T5S2dIPZ9qMJNySjlZT/TKmWVNWe19N8jcWmHaqHnnchaq3gxEKv1SWVY5EFzOD06l41w==" + }, + "Microsoft.Extensions.Caching.Abstractions": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "nTT90JYIpcXEy6fcU8LPVycONkO6wipROgP9pyC4uxBif4fazu2rDzlWSntqtzr5p8GbQL2EopsYuTZR3yoeag==", + "dependencies": { + "Microsoft.Extensions.Primitives": "9.0.13" + } + }, + "Microsoft.Extensions.Caching.Memory": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "OdQmN8LYcUEu20Fxii9mk68nHJGL+JPXF3w0+hxenf0oDDdDBA+ZV/S92FmIgAWAElowIiFA/g0x+8YB1g80Hg==", + "dependencies": { + "Microsoft.Extensions.Caching.Abstractions": "9.0.13", + "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.13", + "Microsoft.Extensions.Logging.Abstractions": "9.0.13", + "Microsoft.Extensions.Options": "9.0.13", + "Microsoft.Extensions.Primitives": "9.0.13" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "10.0.0", + "contentHash": "L3AdmZ1WOK4XXT5YFPEwyt0ep6l8lGIPs7F5OOBZc77Zqeo01Of7XXICy47628sdVl0v/owxYJTe86DTgFwKCA==" + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "10.0.0", + "contentHash": "FU/IfjDfwaMuKr414SSQNTIti/69bHEMb+QKrskRb26oVqpx3lNFXMjs/RC9ZUuhBhcwDM2BwOgoMw+PZ+beqQ==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "10.0.0" + } + }, + "Microsoft.Extensions.Options": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "MJ0afZ8YTPr+TQ0qN+vp4U1yqgj3ccIhq/sFkznMX/V/sPadIQuQJRNK9gWXUoJ03AQmAt31TXtSMuRX3IvaUw==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "9.0.13", + "Microsoft.Extensions.Primitives": "9.0.13" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "cqzLFZ6rIEX/N1mJAGN8HLqWhlks2G3eYO+9pCShMLqxeBLN7ndS+MbmxiuQiQ0Tj/Q3tVHRWx91n17yLczjmg==" + }, + "Microsoft.IdentityModel.Abstractions": { + "type": "Transitive", + "resolved": "8.16.0", + "contentHash": "gSxKLWRZzBpIsEoeUPkxfywNCCvRvl7hkq146XHPk5vOQc9izSf1I+uL1vh4y2U19QPxd9Z8K/8AdWyxYz2lSg==" + }, + "Microsoft.IdentityModel.JsonWebTokens": { + "type": "Transitive", + "resolved": "8.16.0", + "contentHash": "prBU72cIP4V8E9fhN+o/YdskTsLeIcnKPbhZf0X6mD7fdxoZqnS/NdEkSr+9Zp+2q7OZBOMfNBKGbTbhXODO4w==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.16.0" + } + }, + "Microsoft.IdentityModel.Logging": { + "type": "Transitive", + "resolved": "8.16.0", + "contentHash": "MTzXmETkNQPACR7/XCXM1OGM6oU9RkyibqeJRtO9Ndew2LnGjMf9Atqj2VSf4XC27X0FQycUAlzxxEgQMWn2xQ==", + "dependencies": { + "Microsoft.IdentityModel.Abstractions": "8.16.0" + } + }, + "Microsoft.IdentityModel.Protocols": { + "type": "Transitive", + "resolved": "8.16.0", + "contentHash": "UFrU7d46UTsPQTa2HIEIpB9H1uJe1BW9FLw5uhEJ2ZuKdur8bcUA/bO5caq5dlBt5gNJeRIB3QQXYNs5fCQCZA==", + "dependencies": { + "Microsoft.IdentityModel.Tokens": "8.16.0" + } + }, + "Microsoft.IdentityModel.Protocols.OpenIdConnect": { + "type": "Transitive", + "resolved": "8.16.0", + "contentHash": "h4yVXyJsEBBX5lg2G5ftMsi5JzcNEGAzrNphA6DQ6eOd8P0s+cDCOyPwVTYLePZvJL5unbPvYIvzrbTXzFjXnQ==", + "dependencies": { + "Microsoft.IdentityModel.Protocols": "8.16.0", + "System.IdentityModel.Tokens.Jwt": "8.16.0" + } + }, + "Microsoft.IdentityModel.Tokens": { + "type": "Transitive", + "resolved": "8.16.0", + "contentHash": "rtViGJcGsN7WcfUNErwNeQgjuU5cJNl6FDQsfi9TncwO+Epzn0FTfBsg3YuFW1Q0Ch/KPxaVdjLw3/+5Z5ceFQ==", + "dependencies": { + "Microsoft.Extensions.Logging.Abstractions": "10.0.0", + "Microsoft.IdentityModel.Logging": "8.16.0" + } + }, + "Microsoft.SqlServer.Server": { + "type": "Transitive", + "resolved": "1.0.0", + "contentHash": "N4KeF3cpcm1PUHym1RmakkzfkEv3GRMyofVv40uXsQhCQeglr2OHNcUk2WOG51AKpGO8ynGpo9M/kFXSzghwug==" + }, + "System.Configuration.ConfigurationManager": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "GbBrJq9S/gYpHzm7Pxx6Y5tDyfSfyxW6tlP5oiKJV38uf19Wp+GIIAnWfyL1zmNiz1+EjwVapw2WkBFvvqKQzg==", + "dependencies": { + "System.Diagnostics.EventLog": "9.0.13", + "System.Security.Cryptography.ProtectedData": "9.0.13" + } + }, + "System.Diagnostics.EventLog": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "675Rk4RwaVrWo09wrR2rpDVKixtgtnhd5NhPrn6O21uj92JvE61KTGupn76M2N6Ff/xJjY3SHSfSg0MIanEzGw==" + }, + "System.IdentityModel.Tokens.Jwt": { + "type": "Transitive", + "resolved": "8.16.0", + "contentHash": "rrs2u7DRMXQG2yh0oVyF/vLwosfRv20Ld2iEpYcKwQWXHjfV+gFXNQsQ9p008kR9Ou4pxBs68Q6/9zC8Gi1wjg==", + "dependencies": { + "Microsoft.IdentityModel.JsonWebTokens": "8.16.0", + "Microsoft.IdentityModel.Tokens": "8.16.0" + } + }, + "System.Security.Cryptography.ProtectedData": { + "type": "Transitive", + "resolved": "9.0.13", + "contentHash": "t8S9IDpjJKsLpLkeBdW8cWtcPyYqrGu93Dej1RO6WwuL/lkFSqWlan3rMJfortqz1mRIh+sys2AFsSA6jWJ3Jg==" + } + } + } +} \ No newline at end of file diff --git a/Tools/Deployment/activate.py b/Tools/Deployment/activate.py index 268f09e5..f383bd52 100644 --- a/Tools/Deployment/activate.py +++ b/Tools/Deployment/activate.py @@ -304,24 +304,29 @@ def activate(package_id, validate=False, rollback=False, profile=None): event('validation-only');status='validated' print('VALIDATED '+package_id+'; no backup, migrations or service operations performed') return - backup=Path(cfg['backup'])/(cfg['database']+'-predeploy-'+deployment+'.bak') - database_bytes=beginning.get('database_bytes') - require(isinstance(database_bytes,int) and database_bytes>0,'Database size unavailable for backup-space check') - require(shutil.disk_usage(cfg['backup']).free>=cfg['minimum_free_bytes']+2*database_bytes,'Insufficient verified database-backup space') - require(not backup.exists() and not backup.is_symlink(),'Backup path already exists') - event('backup-start') - with meter.phase('database_backup'): - backup_result=worker.call('backup',path=str(Path(cfg.get('database_backup_directory',cfg['backup']))/backup.name)) - require(backup.is_file() and backup.stat().st_size>0,'Verified backup file unavailable') - meter.data['database_backup']={'path':str(backup),'verified':True,'options':['COPY_ONLY','CHECKSUM','VERIFYONLY']} - event('backup-verified',path=str(backup));worker.call('idle') + unchanged = bool(profile and getattr(profile, 'skip_unchanged_migrations', False) and beginning.get('complete')) + if not unchanged: + backup=Path(cfg['backup'])/(cfg['database']+'-predeploy-'+deployment+'.bak') + database_bytes=beginning.get('database_bytes') + require(isinstance(database_bytes,int) and database_bytes>0,'Database size unavailable for backup-space check') + require(shutil.disk_usage(cfg['backup']).free>=cfg['minimum_free_bytes']+2*database_bytes,'Insufficient verified database-backup space') + require(not backup.exists() and not backup.is_symlink(),'Backup path already exists') + event('backup-start') + with meter.phase('database_backup'): + backup_result=worker.call('backup',path=str(Path(cfg.get('database_backup_directory',cfg['backup']))/backup.name)) + require(backup.is_file() and backup.stat().st_size>0,'Verified backup file unavailable') + meter.data['database_backup']={'path':str(backup),'verified':True,'options':['COPY_ONLY','CHECKSUM','VERIFYONLY']} + event('backup-verified',path=str(backup));worker.call('idle') + else: + meter.data['database_backup'] = {'skipped':True,'reason':'No pending migrations'} stop_started=time.monotonic() with meter.phase('service_stop'): command(['/usr/bin/systemctl','stop',cfg['service']]);stopped=True require(command(['/usr/bin/systemctl','show',cfg['service'],'-p','ActiveState','--value'])=='inactive','Service did not stop') stop_complete=time.monotonic() worker.call('idle');event('migration-start') - with meter.phase('migration_execution'):migration=worker.call('migrate') + with meter.phase('migration_execution'): + migration = {'executed':0,'baselined':0,'committed':[],'skipped':True,'schema':beginning['schema']} if unchanged else worker.call('migrate') meter.data['migrations']=migration if isinstance(migration,dict) else {} event('migration-complete') destination=root/'releases'/package_id @@ -352,7 +357,7 @@ def activate(package_id, validate=False, rollback=False, profile=None): meter.data['failures'].append({'code':type(error).__name__,'service_stop_requested':stopped}) if worker is not None and getattr(worker,'last_error',None): safe=worker.last_error - meter.data['worker_failure']={k:safe[k] for k in ('error','migration','batch','executed','baselined') if k in safe} + meter.data['worker_failure']={k:safe[k] for k in ('error','migration','batch','sql_line','executed','baselined','committed') if k in safe} if evidence is not None: with evidence.open('a') as stream:stream.write(canonical({'phase':'failed','error':type(error).__name__,'service_stop_requested':stopped,'recovery':'Operator review required; no automatic database rollback.'}).decode()) raise diff --git a/Tools/Deployment/development.py b/Tools/Deployment/development.py index fa8cb0fb..767e1990 100644 --- a/Tools/Deployment/development.py +++ b/Tools/Deployment/development.py @@ -60,6 +60,7 @@ class DevelopmentWorker(core.Worker): class Development: worker = DevelopmentWorker + skip_unchanged_migrations = True def configuration(self): require(os.geteuid() == 0, 'Restricted sudo invocation required') @@ -106,6 +107,26 @@ def main(): signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(core.Refused('Development deployment timeout'))) signal.alarm(7200) args = sys.argv[1:] + if args == ['--status']: + Development().configuration() + import fcntl + from release import file_digest + lock = os.open(Path(ROOT)/'deployment.lock',os.O_RDWR|os.O_NOFOLLOW) + worker = None + try: + fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB) + marker = load(Path(ROOT)/'active-deployment.json') + active = (Path(ROOT)/'current').resolve().parent + manifest = load(active/'manifest.json') + require(file_digest(active/'app/PlotLine.dll') == manifest['files']['app/PlotLine.dll'], 'Active binary mismatch') + worker = DevelopmentWorker(FIXED) + print(canonical({'source_commit':manifest['source_commit'],'release_id':manifest['release_id'], + 'last_successful_activation':marker,'database':worker.call('inspect'), + 'service_state':core.command(['/usr/bin/systemctl','show',FIXED['service'],'-p','ActiveState','--value'])}).decode(),end='') + finally: + if worker: worker.close() + os.close(lock) + return if len(args) == 2 and args[0] == '--receipt': require(os.geteuid() == 0, 'Restricted sudo invocation required') identifier = safe_name(args[1]) @@ -113,12 +134,18 @@ def main(): core.protected(target, secret=True) print(canonical(load(target)).decode(), end='') return + if len(args) == 2 and args[0] == '--qualify': + from development_qualification import qualify + qualify(args[1]) + return require(len(args) == 2 and args[0] in ('--validate', '--activate', '--rollback'), 'Usage: deploy-plotdirector-development --validate|--activate|--rollback ') import retention retention.preflight() core.activate(args[1], validate=args[0] == '--validate', rollback=args[0] == '--rollback', profile=Development()) if args[0] != '--validate': + from development_qualification import sync_baseline + sync_baseline() # Activation has completed and released its lock. Housekeeping reacquires the # same lock and rechecks current; a competing deployment causes a safe skip. try: diff --git a/Tools/Deployment/development_plan.py b/Tools/Deployment/development_plan.py new file mode 100644 index 00000000..e5138485 --- /dev/null +++ b/Tools/Deployment/development_plan.py @@ -0,0 +1,82 @@ +"""Development-only, data-only migration planning shared by the installed brokers.""" +import copy +import re +from pathlib import Path + +from release import canonical, conditions, file_digest, require + +PLAN_FIELDS = ('starting_schema_sha256', 'resulting_schema_sha256', 'migrations', + 'omitted_migrations', 'prerequisites', 'postconditions', 'qualification') + + +def plan_source(source, baseline, sql): + """Keep every recorded hash; append new numbered migrations in filename order.""" + import shutil + sql = Path(sql) + sql.mkdir() + plan = {k: copy.deepcopy(baseline[k]) for k in PLAN_FIELDS} + plan['starting_schema_sha256'] = baseline['resulting_schema_sha256'] + known = {m['file']: m for m in baseline['migrations']} + omitted = {m['id']: m for m in baseline['omitted_migrations']} + pending = [] + for candidate in sorted((Path(source)/'PlotLine/Sql').glob('*.sql')): + require(not candidate.is_symlink(), 'SQL symlink refused') + name = candidate.name + if name in known: + require(file_digest(candidate) == known[name]['sha256'], 'Historical SQL changed: '+name) + elif candidate.stem in omitted or name in omitted: + item = omitted.get(candidate.stem, omitted.get(name)) + require(file_digest(candidate) == item['sha256'], 'Omitted historical SQL changed: '+name) + elif re.fullmatch(r'[0-9]{3,}_[A-Za-z0-9_.-]+\.sql', name): + pending.append(candidate) + previous = plan['migrations'][-1]['id'] + highest = max(int(m['file'].split('_')[0]) for m in baseline['migrations'] + if re.match(r'^\d+_', m['file'])) + numbers = set() + for candidate in pending: + number = int(candidate.name.split('_')[0]) + require(number > highest and number not in numbers, + 'New migration number collides with recorded history: '+candidate.name) + numbers.add(number) + # These checks are structural smoke checks; the complete resulting schema + # is measured on a disposable database and verified again at activation. + text = candidate.read_text(encoding='utf-8-sig') + objects = re.findall(r'\bCREATE\s+(?:OR\s+ALTER\s+)?(TABLE|PROCEDURE|PROC|FUNCTION|VIEW)\s+\[?dbo\]?\.\[?([A-Za-z_][A-Za-z0-9_]*)\]?', text, re.I) + types = {'TABLE':'U', 'PROCEDURE':'P', 'PROC':'P', 'VIEW':'V'} + checks = [{'kind':'object','name':'dbo.'+name,'type':types[kind.upper()]} + for kind, name in objects if kind.upper() in types] + checks = list({canonical(c): c for c in checks}.values()) + if not checks: + checks = [{'kind':'object','name':'dbo.DatabaseMigrationHistory','type':'U'}] + step = dict(id=candidate.stem, file=candidate.name, sha256=file_digest(candidate), + requires=[previous], mode='execute', prerequisites=[], postconditions=checks) + plan['migrations'].append(step) + previous = step['id'] + shutil.copyfile(candidate, sql/candidate.name) + return plan, pending + + +def validate_extension(plan, baseline): + require(set(plan) == set(PLAN_FIELDS), 'Unexpected migration plan fields') + old = baseline['migrations'] + require(plan['migrations'][:len(old)] == old, 'Historical migration plan changed') + require(plan['omitted_migrations'] == baseline['omitted_migrations'], 'Historical omissions changed') + require(plan['starting_schema_sha256'] == baseline['resulting_schema_sha256'], 'Stale Development baseline') + require(plan['prerequisites'] == baseline['prerequisites'] and + plan['postconditions'] == baseline['postconditions'], 'Baseline conditions changed') + seen = {m['id'] for m in old} + numbers = [int(m['file'].split('_')[0]) for m in old if re.match(r'^\d+_', m['file'])] + highest = max(numbers) + previous = old[-1]['id'] + for step in plan['migrations'][len(old):]: + require(set(step) == {'id','file','sha256','requires','mode','prerequisites','postconditions'}, 'Invalid new migration') + require(re.fullmatch(r'[0-9]{3,}_[A-Za-z0-9_.-]+\.sql', step['file']), 'Invalid SQL filename') + number = int(step['file'].split('_')[0]) + require(number > highest, 'Migration order collision') + highest = number + require(step['id'] == Path(step['file']).stem and step['id'] not in seen and + step['requires'] == [previous] and step['mode'] == 'execute', 'Invalid migration ordering') + require(re.fullmatch(r'[a-f0-9]{64}', step['sha256']), 'Invalid SQL checksum') + conditions(step['prerequisites']); conditions(step['postconditions']) + require(bool(step['postconditions']), 'Migration health check required') + previous = step['id']; seen.add(previous) diff --git a/Tools/Deployment/development_qualification.py b/Tools/Deployment/development_qualification.py new file mode 100644 index 00000000..3207dd87 --- /dev/null +++ b/Tools/Deployment/development_qualification.py @@ -0,0 +1,218 @@ +"""Fixed Atlas Development qualification broker. Candidate SQL never uses SA/root. + +Invoked only by the existing installed Development helper. The administrative +connection executes fixed backup/restore/drop statements against generated names. +All candidate SQL executes as the existing database migration identity on a copy. +""" +import fcntl +import grp +import json +import os +from pathlib import Path +import pwd +import re +import shutil +import subprocess +import tempfile +import uuid + +import activate as core +from development import Development, DevelopmentWorker, FIXED, ROOT +from development_plan import PLAN_FIELDS, validate_extension +from release import canonical, file_digest, load, require, safe_name, snapshot + +STATE = Path('/var/lib/plotdirector-dev-deployment') + + +def refresh_baseline(): + """Called with the deployment lock held; only successfully recorded releases.""" + marker = load(Path(ROOT)/'active-deployment.json') + release = Path(ROOT)/'releases'/safe_name(marker['release']) + receipt = load(Path(ROOT)/'deployment-receipts'/(safe_name(marker['deployment'])+'.json')) + require(receipt['status'] == 'activated' and receipt['release']['id'] == marker['release'], + 'Current release lacks successful receipt') + manifest = load(release/'manifest.json') + baseline = STATE/'baseline' + gid = grp.getgrnam(FIXED['deployment_group']).gr_gid + for area in ('sql', 'evidence'): + for source in (release/area).rglob('*'): + require(not source.is_symlink(), 'Installed baseline symlink refused') + target = baseline/area/source.relative_to(release/area) + if source.is_dir(): + target.mkdir(exist_ok=True, parents=True) + os.chown(target, 0, gid); target.chmod(0o750) + else: + target.parent.mkdir(exist_ok=True, parents=True) + shutil.copyfile(source, target) + os.chown(target, 0, gid); target.chmod(0o640) + pending = baseline/'.manifest.pending' + pending.write_bytes(canonical(manifest)) + os.chown(pending, 0, gid); pending.chmod(0o640) + os.replace(pending, baseline/'manifest.json') + return manifest + + +class CopyWorker(core.Worker): + def __init__(self, config): + user = pwd.getpwnam(FIXED['migration_account']) + self.process = subprocess.Popen(['/usr/bin/dotnet', FIXED['worker'], str(config)], + env=core.SAFE_ENV, cwd='/', user=user.pw_uid, group=user.pw_gid, extra_groups=[], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + self.last_error = None + self.read() + + +class Maintenance: + def __init__(self): + # No candidate values, SQL or scripts are passed to docker/SA. + data = json.loads(subprocess.check_output(['/usr/bin/docker','inspect','atlas-sql-server'], + env=core.SAFE_ENV))[0] + require(data['HostConfig']['PortBindings']['1433/tcp'] == + [{'HostIp':'192.168.10.10','HostPort':'1433'}], 'Wrong Atlas SQL endpoint') + require(any(m['Source']=='/sql/mssql' and m['Destination']=='/var/opt/mssql' + for m in data['Mounts']), 'Wrong Atlas SQL storage') + env = dict(v.split('=',1) for v in data['Config']['Env'] if '=' in v) + self.password = env.get('MSSQL_SA_PASSWORD', env.get('SA_PASSWORD')) + require(bool(self.password), 'Maintenance authentication unavailable') + + def sql(self, statement): + result = subprocess.run(['/usr/bin/docker','exec','-i','-e','SQLCMDPASSWORD', + 'atlas-sql-server','/opt/mssql-tools18/bin/sqlcmd','-S','localhost','-U','sa', + '-C','-I','-b','-l','10','-t','1800','-y','0'], + input='SET NOCOUNT ON;\n'+statement, text=True, capture_output=True, + env={**core.SAFE_ENV,'SQLCMDPASSWORD':self.password}, timeout=1900) + require(result.returncode == 0, 'Fixed Development backup/restore operation failed') + return result.stdout.strip() + + def restore(self, database, media): + require(re.fullmatch(r'PlotDirector_Qualification_[a-f0-9]{32}', database), 'Invalid copy name') + files = json.loads(self.sql("SELECT name,type FROM sys.master_files WHERE database_id=DB_ID(N'PlotDirector_Development') ORDER BY file_id FOR JSON PATH;")) + require(len(files) == 2 and {f['type'] for f in files} == {0,1}, 'Unexpected Development files') + moves = [] + for f in files: + require(re.fullmatch(r'[A-Za-z0-9_]+', f['name']), 'Unexpected logical file name') + suffix = '.mdf' if f['type']==0 else '_log.ldf' + moves.append("MOVE N'"+f['name']+"' TO N'/var/opt/mssql/data/"+database+suffix+"'") + self.sql(f"IF DB_ID(N'{database}') IS NOT NULL THROW 51000,'Copy already exists',1; RESTORE DATABASE [{database}] FROM DISK=N'{media}' WITH "+','.join(moves)+",RECOVERY,CHECKSUM; "+f"ALTER DATABASE [{database}] SET TRUSTWORTHY OFF; ALTER DATABASE [{database}] SET DB_CHAINING OFF;") + + def copy_identity(self, database): + require(re.fullmatch(r'PlotDirector_Qualification_[a-f0-9]{32}', database), 'Invalid copy name') + login = 'pd_qualification_'+database.rsplit('_',1)[1] + password = uuid.uuid4().hex+uuid.uuid4().hex+'Aa9!' + self.sql(f"CREATE LOGIN [{login}] WITH PASSWORD=N'{password}',CHECK_POLICY=ON; USE [{database}]; CREATE USER [{login}] FOR LOGIN [{login}]; ALTER ROLE db_owner ADD MEMBER [{login}];") + return {'database':database,'expected_host':'atlas','expected_server':'192.168.10.10,1433', + 'connection':f'Server=192.168.10.10,1433;Database={database};User ID={login};Password={password};Encrypt=True;TrustServerCertificate=True;'} + + def drop(self, database): + require(re.fullmatch(r'PlotDirector_Qualification_[a-f0-9]{32}', database), 'Invalid copy name') + self.sql(f"IF DB_ID(N'{database}') IS NOT NULL BEGIN ALTER DATABASE [{database}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{database}]; END;") + login = 'pd_qualification_'+database.rsplit('_',1)[1] + self.sql(f"IF EXISTS(SELECT 1 FROM sys.server_principals WHERE name=N'{login}') DROP LOGIN [{login}];") + + +def qualify(identifier): + identifier = safe_name(identifier) + Development().configuration() # fixed service, host, accounts and protected code + lock = os.open(Path(ROOT)/'deployment.lock', os.O_RDWR|os.O_NOFOLLOW) + try: + fcntl.flock(lock, fcntl.LOCK_EX|fcntl.LOCK_NB) + baseline = refresh_baseline() + destination = STATE/'qualified'/identifier + require(not destination.exists(), 'Qualification identifier already exists') + gid = grp.getgrnam(FIXED['deployment_group']).gr_gid + destination.mkdir(mode=0o750, parents=True) + os.chown(destination, 0, gid) + result = {'status':'failed','phase':'plan-validation','database_changes_applied':False, + 'application_activated':False,'corrective_deployment_safe':True} + try: + with tempfile.TemporaryDirectory(prefix='.qualification-', dir=ROOT) as temporary: + work = Path(temporary) + migrate_gid = pwd.getpwnam(FIXED['migration_account']).pw_gid + os.chown(work,0,migrate_gid); work.chmod(0o750) + request = STATE/'incoming'/identifier/'qualification' + snapshot(request/'plan.json', work/'manifest.json', 8*1024*1024) + plan = load(work/'manifest.json') + validate_extension(plan, baseline) + require(len(plan['migrations']) > len(baseline['migrations']), 'No new SQL to qualify') + (work/'sql').mkdir() + total = 0 + for step in plan['migrations']: + target = work/'sql'/step['file'] + if step in baseline['migrations']: + shutil.copyfile(STATE/'baseline/sql'/step['file'],target) + else: + snapshot(request/'sql'/step['file'],target,8*1024*1024) + require(file_digest(target) == step['sha256'], 'SQL checksum differs from plan') + total += target.stat().st_size + require(total <= 128*1024*1024, 'SQL input limit exceeded') + for path in (work/'manifest.json',work/'sql',*(work/'sql').iterdir()): + os.chown(path,0,migrate_gid); path.chmod(0o750 if path.is_dir() else 0o640) + # Validate the actual live ledger before copying it. No live SQL runs. + live = DevelopmentWorker(FIXED) + try: + result['phase'] = 'live-history-verification' + begin = live.call('begin', package_root=str(work), deployment_id='qualification-'+uuid.uuid4().hex, + package_sha256='0'*64) + result['migration_history'] = begin + require(begin['schema'] == plan['starting_schema_sha256'], 'Live Development schema drift') + result['phase'] = 'verified-backup' + unique = uuid.uuid4().hex + backup = 'PlotDirector_Development-qualification-'+unique+'.bak' + require(shutil.disk_usage(FIXED['backup']).free > FIXED['minimum_free_bytes']+2*begin['database_bytes'], 'Insufficient recovery space') + require(not (Path(FIXED['backup'])/backup).exists(), 'Backup identifier collision') + live.call('backup',path=FIXED['database_backup_directory']+'/'+backup) + require((Path(FIXED['backup'])/backup).stat().st_size > 0, 'Backup unavailable') + result['backup'] = {'file':backup,'verified':True} + finally: + live.close() + result['phase'] = 'disposable-copy-restore' + admin = Maintenance() + database = 'PlotDirector_Qualification_'+unique + restored = False + try: + admin.restore(database, FIXED['database_backup_directory']+'/'+backup) + restored = True + config = admin.copy_identity(database) + config_path = work/'copy.private.json' + config_path.write_bytes(canonical(config)); os.chown(config_path,0,migrate_gid); config_path.chmod(0o640) + copy = CopyWorker(config_path) + try: + copy.call('begin',package_root=str(work),deployment_id='qualification-'+unique,package_sha256='0'*64) + result['phase'] = 'migration-on-copy' + migrated = copy.call('qualify-migrate') + plan['resulting_schema_sha256'] = migrated['schema'] + result.update(status='passed', phase='qualified', migrations=migrated, + source_starting_schema_sha256=plan['starting_schema_sha256'], + resulting_schema_sha256=migrated['schema']) + except Exception: + result['worker_failure'] = copy.last_error + raise + finally: + copy.close() + finally: + # Never drop or restore the Development database. Failure to + # clean up a generated copy is reported for maintenance. + try: admin.drop(database) + except Exception: + result['copy_cleanup_required'] = database + if not restored: raise + (destination/'plan.json').write_bytes(canonical(plan)) + except Exception as error: + result['error'] = core.public_error(error) + raise + finally: + (destination/'result.json').write_bytes(canonical(result)) + for path in destination.iterdir(): + os.chown(path,0,gid); path.chmod(0o640) + print(canonical(result).decode(),end='') + finally: + os.close(lock) + + +def sync_baseline(): + lock = os.open(Path(ROOT)/'deployment.lock',os.O_RDWR|os.O_NOFOLLOW) + try: + fcntl.flock(lock,fcntl.LOCK_EX) + refresh_baseline() + finally: + os.close(lock) diff --git a/Tools/Deployment/development_release.py b/Tools/Deployment/development_release.py index 2c91d59f..b057c813 100644 --- a/Tools/Deployment/development_release.py +++ b/Tools/Deployment/development_release.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Prepare, sign and admit code-only Development releases on Atlas; no Production access.""" +"""Prepare, qualify, sign and admit application/SQL Development releases on Atlas; no Production access.""" import argparse import json import os @@ -21,6 +21,8 @@ from release import require, load, file_digest, canonical, prepare BASELINE = Path('/var/lib/plotdirector-dev-deployment/baseline') INBOX = Path('/var/lib/plotdirector-dev-deployment/incoming') HELPER = '/usr/local/sbin/deploy-plotdirector-development' +RESULT = {'phase':'source-verification','database_changes_applied':False,'application_activated':False,'corrective_deployment_safe':True} +OUTPUT = None def run(args, log): @@ -49,6 +51,8 @@ def main(): parser.add_argument('--activate', action='store_true') parser.add_argument('--isolate-build', action='store_true', help='Run all repository build code without host secrets using Bubblewrap') args = parser.parse_args() + global OUTPUT + OUTPUT = Path(args.output).resolve() require(socket.gethostname() == 'atlas' and os.geteuid() != 0, 'Run as the Atlas Development deployer') os.umask(0o077) for storage_path in ('/srv', '/opt/plotdirector-dev'): @@ -60,54 +64,72 @@ def main(): source = Path(args.source).resolve() output = Path(args.output).resolve() require(not output.exists(), 'Use a fresh output directory') - commit = subprocess.check_output(['git', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip() - require(not subprocess.check_output(['git', '-C', str(source), 'status', '--porcelain'], text=True).strip(), 'Clean committed source required') + commit = subprocess.check_output(['/usr/local/sbin/atlas-git-inspect', '-C', str(source), 'rev-parse', 'HEAD'], text=True).strip() + require(not subprocess.check_output(['/usr/local/sbin/atlas-git-inspect', '-C', str(source), 'status', '--porcelain'], text=True).strip(), 'Clean committed source required') baseline = load(BASELINE/'manifest.json') def build(command, log, writable): - if args.isolate_build: - from sandbox_build import run_build - run_build(command, source, writable, log) - else: - run(command, log) - changed_sql = subprocess.check_output(['git', '-C', str(source), 'diff', '--name-only', baseline['source_commit'], commit, '--', 'PlotLine/Sql'], text=True).strip() - require(not changed_sql, 'Schema changes require a separately reviewed/qualified migration plan') - require(baseline['starting_schema_sha256'] == baseline['resulting_schema_sha256'], 'Code-only Development baseline required') + RESULT['phase'] = 'contained-publish' + from sandbox_build import run_build + run_build(command, source, writable, log) + proof = output/'evidence/development-automatic.json' + if proof.exists() and command[1] == 'publish': + data = load(proof) + published = Path(command[command.index('-o')+1]) + require(not published.is_symlink() and not (published/'PlotLine.dll').is_symlink(), 'Unsafe published binary') + data['application_dll_sha256'] = file_digest(published/'PlotLine.dll') + proof.write_bytes(canonical(data)) output.mkdir(parents=True, mode=0o700) - release_id = 'development-'+commit[:12]+'-'+__import__('time').strftime('%Y%m%dT%H%M%SZ', __import__('time').gmtime()) - # Source SQL must still match every approved immutable historical script. + release_id = 'development-'+commit[:12]+'-'+__import__('time').strftime('%Y%m%dT%H%M%SZ', __import__('time').gmtime())+'-'+__import__('uuid').uuid4().hex[:8] + from development_plan import plan_source + evidence = output/'evidence' + shutil.copytree(BASELINE/'evidence', evidence) + sql = output/'sql' + plan, pending = plan_source(source, baseline, sql) for step in baseline['migrations']: - candidate = source/'PlotLine/Sql'/step['file'] - if candidate.exists():require(file_digest(candidate) == step['sha256'], 'Historical SQL changed: '+step['file']) + shutil.copyfile(BASELINE/'sql'/step['file'], sql/step['file']) + qualification = None + if pending: + request = INBOX/release_id/'qualification' + request.mkdir(parents=True) + shutil.copytree(sql, request/'sql') + (request/'plan.json').write_bytes(canonical(plan)) + RESULT['phase'] = 'sql-qualification' + result = subprocess.run(['sudo','-n',HELPER,'--qualify',release_id], capture_output=True, text=True) + qualified = INBOX.parent/'qualified'/release_id + if (qualified/'result.json').is_file(): + qualification = load(qualified/'result.json') + RESULT['qualification'] = qualification + (output/'qualification-result.json').write_bytes(canonical(qualification)) + require(result.returncode == 0 and qualification and qualification['status']=='passed', + 'Development SQL qualification failed; inspect qualification-result.json') + plan = load(qualified/'plan.json') + plan['qualification'] = {'status':'passed','evidence':'evidence/development-automatic.json'} + (evidence/'development-automatic.json').write_bytes(canonical({ + 'status':'passed','source_commit':commit, + 'starting_schema_sha256':plan['starting_schema_sha256'], + 'resulting_schema_sha256':plan['resulting_schema_sha256'], + 'checks':['immutable-history','contained-release-publish','migration-on-disposable-copy' if pending else 'unchanged-schema'], + 'database_qualification':qualification, 'target':'Development on Atlas only','production_access':False, + })) signing = Path.home()/'.local/share/plotdirector-development/signing/private.pem' require(signing.is_file() and signing.stat().st_mode & 0o077 == 0, 'Private Development signing key missing or exposed') - with tempfile.TemporaryDirectory(prefix='build-', dir=output) as work: - work = Path(work) - publish = work/'publish' - build(['dotnet', 'publish', str(source/'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId='+commit], output/'qualification-build.log', work) - build(['dotnet', 'run', '--project', str(source/'PlotLine.Tests/PlotLine.Tests.csproj')], output/'regression.log', work) - evidence = work/'evidence' - shutil.copytree(BASELINE/'evidence', evidence) - plan = {k:baseline[k] for k in ('starting_schema_sha256', 'resulting_schema_sha256', 'migrations', 'omitted_migrations', 'prerequisites', 'postconditions', 'qualification')} - plan['qualification'] = {'status':'passed', 'evidence':'evidence/development-code-only.json'} - (evidence/'development-code-only.json').write_bytes(canonical({ - 'status':'passed', 'source_commit':commit, 'application_dll_sha256':file_digest(publish/'PlotLine.dll'), - 'starting_schema_sha256':plan['starting_schema_sha256'], 'resulting_schema_sha256':plan['resulting_schema_sha256'], - 'checks':['clean-committed-source', 'unchanged-reviewed-sql', 'release-publish', 'full-regression-harness'], - 'target':'Development on Atlas only', 'production_access':False, - })) - plan_file = output/'plan.json' - plan_file.write_bytes(canonical(plan)) - prepare(SimpleNamespace(source=str(source), plan=str(plan_file), sql=str(BASELINE/'sql'), evidence=str(evidence), - output=str(output/'bundle'), release_id=release_id, signing_key=str(signing), compression='none', scope_base=baseline['source_commit']), - publish_runner=build if args.isolate_build else None) + plan_file = output/'plan.json' + plan_file.write_bytes(canonical(plan)) + prepare(SimpleNamespace(source=str(source),plan=str(plan_file),sql=str(sql),evidence=str(evidence), + output=str(output/'bundle'),release_id=release_id,signing_key=str(signing),compression='none',scope_base=None), + publish_runner=build) # Unprivileged submission; privileged helper snapshots and verifies it again. destination = INBOX/release_id - require(not destination.exists(), 'Release identifier already submitted') - shutil.copytree(output/'bundle', destination) - result = subprocess.run(['sudo', '-n', HELPER, '--validate', release_id]) + destination.mkdir(exist_ok=True) + shutil.copytree(output/'bundle', destination, dirs_exist_ok=True) + RESULT['phase'] = 'validation' + result = subprocess.run(['sudo', '-n', HELPER, '--validate', release_id], capture_output=True, text=True) + print(result.stdout, end='') + capture_activation_receipt(output, result.stdout) require(result.returncode == 0, 'Development validation refused') activation_receipt = None if args.activate: + RESULT.update(phase='activation',corrective_deployment_safe=False,database_changes_applied='unknown',application_activated='unknown') result = subprocess.run(['sudo', '-n', HELPER, '--activate', release_id], capture_output=True, text=True) print(result.stdout, end='') activation_receipt = capture_activation_receipt(output, result.stdout) @@ -120,4 +142,12 @@ if __name__ == '__main__': try:main() except Exception as error: from activate import public_error + RESULT['error'] = public_error(error) + state = subprocess.run(['sudo','-n',HELPER,'--status'],capture_output=True,text=True) + if state.returncode == 0: + RESULT['current_deployment'] = json.loads(state.stdout) + else: + RESULT['current_deployment'] = {'status':'unavailable','reconciliation_required':True} + if OUTPUT is not None and OUTPUT.is_dir(): + (OUTPUT/'deployment-result.json').write_bytes(canonical(RESULT)) print('Development release refused: '+public_error(error));raise SystemExit(1) diff --git a/Tools/Deployment/provision/install-unattended-release.sh b/Tools/Deployment/provision/install-unattended-release.sh index c9dd11b9..ced6a073 100755 --- a/Tools/Deployment/provision/install-unattended-release.sh +++ b/Tools/Deployment/provision/install-unattended-release.sh @@ -5,7 +5,7 @@ set -eu source_dir=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) target=/usr/local/lib/plotdirector-dev-release install -d -o root -g root -m 755 "$target" -for name in development_release.py sandbox_build.py release.py transport.py receipt.py activate.py; do +for name in development_release.py development_plan.py sandbox_build.py release.py transport.py receipt.py activate.py; do install -o root -g root -m 644 "$source_dir/$name" "$target/$name" done printf '%s\n' 'Installed unprivileged Development release orchestration. Activation helper, sudo rules and Production are unchanged.' diff --git a/Tools/Deployment/sandbox_build.py b/Tools/Deployment/sandbox_build.py index 8848e56a..aa88b99c 100644 --- a/Tools/Deployment/sandbox_build.py +++ b/Tools/Deployment/sandbox_build.py @@ -40,11 +40,13 @@ def build_command(command, source, writable, home): packages = Path.home() / '.nuget/packages' if packages.is_dir(): args += ['--ro-bind', str(packages), '/nuget/packages', - '--setenv', 'NUGET_PACKAGES', '/nuget/packages'] + '--setenv', 'RestoreFallbackFolders', '/nuget/packages', '--setenv', 'NUGET_PACKAGES', '/build-home/packages'] return args + ['--', *command] def run_build(command, source, writable, log): + if __import__('os').geteuid() == 0: + raise ValueError('Never compile as root') # A fresh home per invocation has no NuGet credentials or host configuration. with tempfile.TemporaryDirectory(prefix='pd-build-home-') as home: args = build_command(command, source, writable, home) diff --git a/Tools/Deployment/test_activation.py b/Tools/Deployment/test_activation.py index 60c5c59b..e494a1f8 100644 --- a/Tools/Deployment/test_activation.py +++ b/Tools/Deployment/test_activation.py @@ -50,7 +50,7 @@ class ActivationFailureTests(unittest.TestCase): 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,'database_bytes':1024} + if op=='begin':return {'complete':outer.complete,'database_bytes':1024,'schema':'a'*64} if op=='activated':outer.activations.append(values) if op=='migrate':return {'executed':0,'baselined':0,'committed':[]} return {} @@ -76,7 +76,7 @@ class ActivationFailureTests(unittest.TestCase): return self.status if '--output' in args else json.dumps({'healthy':True,'version':'1.0.0','sourceCommit':'a'*40,'database':'PlotLine','environment':'Production'}) raise AssertionError('Unexpected executable') - def run_activation(self,validate=False,free=10**12,rollback=False): + def run_activation(self,validate=False,free=10**12,rollback=False,development=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'),\ @@ -84,7 +84,22 @@ class ActivationFailureTests(unittest.TestCase): patch.object(activate,'command',side_effect=self.command),patch.object(activate.os,'chown'),\ patch.object(activate,'persist_receipt',side_effect=lambda cfg,meter:self.receipts.append(copy.deepcopy(meter.data))),\ patch.object(activate.time,'sleep'),patch.object(activate.shutil,'disk_usage',return_value=SimpleNamespace(free=free)): - activate.activate('new-release',validate,rollback) + profile = SimpleNamespace(configuration=lambda:self.cfg,worker=self.FakeWorker,install=activate.install,skip_unchanged_migrations=True) if development else None + activate.activate('new-release',validate,rollback,profile=profile) + + def test_development_unchanged_schema_skips_backup_and_migration(self): + self.complete=True + self.run_activation(development=True) + self.assertNotIn('backup',self.calls) + self.assertNotIn('migrate',self.calls) + self.assertIn('service-start',self.calls) + self.assertEqual(self.receipts[-1]['status'],'activated') + self.assertTrue(self.receipts[-1]['database_backup']['skipped']) + + def test_development_pending_schema_keeps_verified_backup_and_migration(self): + self.run_activation(development=True) + self.assertLess(self.calls.index('backup'),self.calls.index('migrate')) + self.assertTrue(self.receipts[-1]['database_backup']['verified']) def test_validation_does_not_backup_migrate_or_stop_service(self): self.run_activation(validate=True) diff --git a/Tools/Deployment/test_development.py b/Tools/Deployment/test_development.py index 517405e2..c3832922 100644 --- a/Tools/Deployment/test_development.py +++ b/Tools/Deployment/test_development.py @@ -45,7 +45,7 @@ class DevelopmentBoundaryTests(unittest.TestCase): with self.subTest(operation=operation), \ patch.object(development.sys, 'argv', ['helper', '--'+operation, 'fixture']), \ patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \ - patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), \ + patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), patch('development_qualification.sync_baseline'), \ patch.object(retention, 'run') as prune, patch.object(activate, 'activate') as run: development.main() if operation == 'validate':prune.assert_not_called() @@ -58,7 +58,7 @@ class DevelopmentBoundaryTests(unittest.TestCase): def test_failed_activation_never_prunes(self): with patch.object(development.sys, 'argv', ['helper', '--activate', 'fixture']), \ patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \ - patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), \ + patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), patch('development_qualification.sync_baseline'), \ patch.object(retention, 'run') as prune, patch.object(activate, 'activate', side_effect=Refused('fixture')): with self.assertRaises(Refused):development.main() prune.assert_not_called() @@ -66,7 +66,7 @@ class DevelopmentBoundaryTests(unittest.TestCase): def test_cleanup_failure_does_not_reclassify_successful_activation(self): with patch.object(development.sys, 'argv', ['helper', '--activate', 'fixture']), \ patch.object(development.os, 'umask'), patch.object(development.signal, 'signal'), \ - patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), \ + patch.object(development.signal, 'alarm'), patch.object(retention, 'preflight'), patch('development_qualification.sync_baseline'), \ patch.object(retention, 'run', side_effect=BlockingIOError()), \ patch.object(activate, 'activate') as run, patch('builtins.print') as report: development.main() diff --git a/Tools/Deployment/test_development_plan.py b/Tools/Deployment/test_development_plan.py new file mode 100644 index 00000000..d272ca39 --- /dev/null +++ b/Tools/Deployment/test_development_plan.py @@ -0,0 +1,61 @@ +import copy +from pathlib import Path +import tempfile +import unittest + +from development_plan import plan_source, validate_extension +from release import Refused, file_digest + + +class PlanTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.source = self.root/'source' + (self.source/'PlotLine/Sql').mkdir(parents=True) + self.old = self.source/'PlotLine/Sql/339_Existing.sql' + self.old.write_text('CREATE TABLE dbo.Existing(Id int);') + step = dict(id='339_Existing',file=self.old.name,sha256=file_digest(self.old), + requires=[],mode='execute',prerequisites=[],postconditions=[dict(kind='object',name='dbo.Existing',type='U')]) + self.baseline = dict(starting_schema_sha256='a'*64,resulting_schema_sha256='b'*64, + migrations=[step],omitted_migrations=[],prerequisites=[],postconditions=step['postconditions'], + qualification=dict(status='passed',evidence='evidence/old.json')) + + def tearDown(self): + self.temp.cleanup() + + def test_code_only_reuses_resulting_schema_without_qualification(self): + plan, pending = plan_source(self.source,self.baseline,self.root/'sql') + self.assertFalse(pending) + self.assertEqual(plan['starting_schema_sha256'],'b'*64) + validate_extension(plan,self.baseline) + + def test_procedure_schema_function_and_data_migrations_append_in_order(self): + for name,sql in [('340_Procedure.sql','CREATE OR ALTER PROCEDURE dbo.ReadNew AS SELECT 1;'), + ('341_Table.sql','CREATE TABLE [dbo].[NewTable](Id int);'), + ('342_Data.sql','UPDATE dbo.Existing SET Id=Id+1;'), + ('343_Function.sql','CREATE OR ALTER FUNCTION dbo.ReadValue() RETURNS int AS BEGIN RETURN 1 END;')]: + (self.old.parent/name).write_text(sql) + plan,pending = plan_source(self.source,self.baseline,self.root/'sql') + self.assertEqual(len(pending),4) + self.assertEqual(plan['migrations'][1]['requires'],['339_Existing']) + self.assertEqual(plan['migrations'][2]['requires'],['340_Procedure']) + validate_extension(plan,self.baseline) + + def test_changed_historical_sql_and_number_collisions_refused(self): + self.old.write_text('ALTER TABLE dbo.Existing ADD Surprise int;') + with self.assertRaises(Refused): plan_source(self.source,self.baseline,self.root/'sql') + self.old.write_text('CREATE TABLE dbo.Existing(Id int);') + (self.old.parent/'339_Collision.sql').write_text('SELECT 1;') + with self.assertRaises(Refused): plan_source(self.source,self.baseline,self.root/'sql2') + + def test_broker_rejects_history_changes_and_path_substitution(self): + for field,value in [('mode','baseline'),('file','../outside.sql'),('requires',[])]: + plan=copy.deepcopy(self.baseline) + plan['starting_schema_sha256']='b'*64 + plan['migrations'].append(dict(plan['migrations'][0],id='340_New',file='340_New.sql',requires=['339_Existing'])) + plan['migrations'][-1][field]=value + with self.subTest(field=field),self.assertRaises(Refused):validate_extension(plan,self.baseline) + + +if __name__ == '__main__': unittest.main()