From 15a9f96f790c543cd24bff8a11e190cb4d59f9d4 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Wed, 25 Nov 2026 17:33:37 +0000 Subject: [PATCH] Add signed Zstandard transport and measured sanitized deployment receipts --- .../compression-benchmark.json | 149 ++ .../Transport-20261125/package-inventory.json | 1550 +++++++++++++++++ .../production-unchanged.json | 17 + .../Transport-20261125/qualification.json | 13 + .../retained-package-receipt.json | 99 ++ .../worker-qualification.json | 13 + Docs/Deployment/Production.md | 143 +- Docs/Deployment/Transport-20261125.md | 124 ++ Tools/Deployment/DatabaseWorker/Program.cs | 51 +- Tools/Deployment/README.md | 10 + Tools/Deployment/activate.py | 258 ++- Tools/Deployment/deploy-plotdirector | 4 +- Tools/Deployment/deploy.py | 131 ++ Tools/Deployment/receipt.py | 114 ++ Tools/Deployment/release.py | 210 ++- Tools/Deployment/ssh_dispatch.py | 20 +- Tools/Deployment/test_activation.py | 11 +- Tools/Deployment/test_pipeline.py | 81 + Tools/Deployment/test_receipt.py | 95 + Tools/Deployment/test_transport.py | 109 ++ Tools/Deployment/test_upload.py | 70 + Tools/Deployment/transfer.py | 65 +- Tools/Deployment/transport.py | 88 + 23 files changed, 3221 insertions(+), 204 deletions(-) create mode 100644 Docs/Deployment/Evidence/Transport-20261125/compression-benchmark.json create mode 100644 Docs/Deployment/Evidence/Transport-20261125/package-inventory.json create mode 100644 Docs/Deployment/Evidence/Transport-20261125/production-unchanged.json create mode 100644 Docs/Deployment/Evidence/Transport-20261125/qualification.json create mode 100644 Docs/Deployment/Evidence/Transport-20261125/retained-package-receipt.json create mode 100644 Docs/Deployment/Evidence/Transport-20261125/worker-qualification.json create mode 100644 Docs/Deployment/Transport-20261125.md create mode 100644 Tools/Deployment/deploy.py create mode 100644 Tools/Deployment/receipt.py create mode 100644 Tools/Deployment/test_pipeline.py create mode 100644 Tools/Deployment/test_receipt.py create mode 100644 Tools/Deployment/test_transport.py create mode 100644 Tools/Deployment/test_upload.py create mode 100644 Tools/Deployment/transport.py diff --git a/Docs/Deployment/Evidence/Transport-20261125/compression-benchmark.json b/Docs/Deployment/Evidence/Transport-20261125/compression-benchmark.json new file mode 100644 index 00000000..9f58491d --- /dev/null +++ b/Docs/Deployment/Evidence/Transport-20261125/compression-benchmark.json @@ -0,0 +1,149 @@ +{ + "fixture": "/home/nick/plotdirector-routine-20261125/bundle/package.tar", + "original_bytes": 554260480, + "original_sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7", + "baseline_mib_per_second": 1.888, + "results": [ + { + "method": "uncompressed", + "bytes": 554260480, + "compression_seconds": 0, + "decompression_seconds": 0, + "estimated_transfer_seconds": 279.97033070709745, + "combined_seconds": 279.97033070709745, + "sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7" + }, + { + "method": "gzip-1", + "bytes": 201854349, + "compression_seconds": 5.7469, + "decompression_seconds": 2.0668, + "estimated_transfer_seconds": 101.9615, + "combined_seconds": 109.7751, + "compression_cpu_user_seconds": 5.63, + "compression_cpu_system_seconds": 0.11, + "compression_peak_rss_kib": 7908, + "integrity": "original SHA256 matched" + }, + { + "method": "gzip-6", + "bytes": 181826954, + "compression_seconds": 17.9912, + "decompression_seconds": 1.845, + "estimated_transfer_seconds": 91.8452, + "combined_seconds": 111.6814, + "compression_cpu_user_seconds": 17.87, + "compression_cpu_system_seconds": 0.11, + "compression_peak_rss_kib": 7892, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-1-T1", + "bytes": 189037362, + "compression_seconds": 1.6523, + "decompression_seconds": 0.623, + "estimated_transfer_seconds": 95.4873, + "combined_seconds": 97.7626, + "compression_cpu_user_seconds": 1.78, + "compression_cpu_system_seconds": 0.31, + "compression_peak_rss_kib": 18084, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-1-T4", + "bytes": 189037362, + "compression_seconds": 0.4813, + "decompression_seconds": 0.6185, + "estimated_transfer_seconds": 95.4873, + "combined_seconds": 96.5872, + "compression_cpu_user_seconds": 1.85, + "compression_cpu_system_seconds": 0.35, + "compression_peak_rss_kib": 31492, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-1-T8", + "bytes": 189037362, + "compression_seconds": 0.4085, + "decompression_seconds": 0.6559, + "estimated_transfer_seconds": 95.4873, + "combined_seconds": 96.5517, + "compression_cpu_user_seconds": 2.65, + "compression_cpu_system_seconds": 0.43, + "compression_peak_rss_kib": 47560, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-3-T1", + "bytes": 174970395, + "compression_seconds": 2.4469, + "decompression_seconds": 0.6677, + "estimated_transfer_seconds": 88.3818, + "combined_seconds": 91.4963, + "compression_cpu_user_seconds": 2.55, + "compression_cpu_system_seconds": 0.41, + "compression_peak_rss_kib": 52144, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-3-T4", + "bytes": 174970395, + "compression_seconds": 0.7884, + "decompression_seconds": 0.6596, + "estimated_transfer_seconds": 88.3818, + "combined_seconds": 89.8298, + "compression_cpu_user_seconds": 2.91, + "compression_cpu_system_seconds": 0.38, + "compression_peak_rss_kib": 93328, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-3-T8", + "bytes": 174970395, + "compression_seconds": 0.7352, + "decompression_seconds": 0.6704, + "estimated_transfer_seconds": 88.3818, + "combined_seconds": 89.7874, + "compression_cpu_user_seconds": 4.68, + "compression_cpu_system_seconds": 0.43, + "compression_peak_rss_kib": 146288, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-6-T1", + "bytes": 165585450, + "compression_seconds": 6.6843, + "decompression_seconds": 0.6449, + "estimated_transfer_seconds": 83.6412, + "combined_seconds": 90.9705, + "compression_cpu_user_seconds": 6.73, + "compression_cpu_system_seconds": 0.43, + "compression_peak_rss_kib": 53576, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-6-T4", + "bytes": 165585450, + "compression_seconds": 2.027, + "decompression_seconds": 0.6607, + "estimated_transfer_seconds": 83.6412, + "combined_seconds": 86.3288, + "compression_cpu_user_seconds": 7.87, + "compression_cpu_system_seconds": 0.46, + "compression_peak_rss_kib": 97704, + "integrity": "original SHA256 matched" + }, + { + "method": "zstd-6-T8", + "bytes": 165585450, + "compression_seconds": 1.6271, + "decompression_seconds": 0.6714, + "estimated_transfer_seconds": 83.6412, + "combined_seconds": 85.9397, + "compression_cpu_user_seconds": 11.92, + "compression_cpu_system_seconds": 0.45, + "compression_peak_rss_kib": 158668, + "integrity": "original SHA256 matched" + } + ] +} diff --git a/Docs/Deployment/Evidence/Transport-20261125/package-inventory.json b/Docs/Deployment/Evidence/Transport-20261125/package-inventory.json new file mode 100644 index 00000000..1b1314f5 --- /dev/null +++ b/Docs/Deployment/Evidence/Transport-20261125/package-inventory.json @@ -0,0 +1,1550 @@ +[ + [ + "app/runtimes/win-x86", + 97363336 + ], + [ + "app/runtimes/win-x64", + 96229264 + ], + [ + "app/runtimes/win-arm64", + 95902088 + ], + [ + "app/wwwroot", + 30717352 + ], + [ + "app/runtimes/linux-musl-arm64", + 18533064 + ], + [ + "app/runtimes/linux-musl-x64", + 18440296 + ], + [ + "app/PlotLine.dll", + 17358336 + ], + [ + "app/Data", + 16560582 + ], + [ + "app/runtimes/osx", + 15201456 + ], + [ + "app/runtimes/linux-musl-arm", + 14656372 + ], + [ + "app/runtimes/linux-musl-loongarch64", + 11896256 + ], + [ + "app/runtimes/linux-bionic-arm64", + 11319400 + ], + [ + "app/runtimes/linux-x64", + 11155176 + ], + [ + "app/runtimes/linux-bionic-x64", + 11068032 + ], + [ + "app/runtimes/linux-arm64", + 10832888 + ], + [ + "app/runtimes/linux-loongarch64", + 10480264 + ], + [ + "app/runtimes/linux-x86", + 10340080 + ], + [ + "app/runtimes/linux-musl-riscv64", + 9966152 + ], + [ + "app/runtimes/linux-riscv64", + 8612584 + ], + [ + "app/runtimes/linux-arm", + 7994064 + ], + [ + "app/Stripe.net.dll", + 4704256 + ], + [ + "app/PlotLine.pdb", + 3826916 + ], + [ + "app/Content", + 1942217 + ], + [ + "app/runtimes/win", + 1849752 + ], + [ + "app/runtimes/unix", + 1799616 + ], + [ + "app/PlotLine.staticwebassets.endpoints.json", + 1681050 + ], + [ + "app/Newtonsoft.Json.dll", + 712464 + ], + [ + "app/Microsoft.Data.SqlClient.dll", + 643512 + ], + [ + "app/Help", + 518051 + ], + [ + "app/SkiaSharp.dll", + 489824 + ], + [ + "manifest.json", + 489394 + ], + [ + "app/System.Configuration.ConfigurationManager.dll", + 443192 + ], + [ + "app/Microsoft.IdentityModel.Tokens.dll", + 391200 + ], + [ + "sql/release_InitialProblemSolverPublication.sql", + 380551 + ], + [ + "app/ru", + 348568 + ], + [ + "app/ja", + 292760 + ], + [ + "app/fr", + 271296 + ], + [ + "app/ko", + 270744 + ], + [ + "app/de", + 270232 + ], + [ + "app/pl", + 269720 + ], + [ + "app/it", + 263104 + ], + [ + "app/es", + 262040 + ], + [ + "app/cs", + 259992 + ], + [ + "app/pt-BR", + 257944 + ], + [ + "app/tr", + 253336 + ], + [ + "app/Dapper.dll", + 247808 + ], + [ + "app/zh-Hant", + 231824 + ], + [ + "app/zh-Hans", + 228248 + ], + [ + "app/Microsoft.IdentityModel.JsonWebTokens.dll", + 173088 + ], + [ + "app/QRCoder.dll", + 144384 + ], + [ + "app/Microsoft.IdentityModel.Protocols.OpenIdConnect.dll", + 137248 + ], + [ + "app/Docs", + 113822 + ], + [ + "app/PlotDirector.Companion.Protocol.dll", + 106496 + ], + [ + "app/System.IdentityModel.Tokens.Jwt.dll", + 92232 + ], + [ + "app/PlotLine", + 78872 + ], + [ + "sql/229_ProjectBackupIllustrationHistory.sql", + 71194 + ], + [ + "sql/228_ProjectBackupNarrativeHistory.sql", + 66857 + ], + [ + "sql/214_ProjectBackupPersistentSourceState.sql", + 64892 + ], + [ + "sql/227_ProjectBackupCharacterEnrichment.sql", + 62778 + ], + [ + "sql/068_BookDisplayTitles.sql", + 61239 + ], + [ + "sql/225_ProjectBackupEntityReviews.sql", + 59192 + ], + [ + "sql/084_ProjectBackupFloorPlansAndVisualIdentity.sql", + 58239 + ], + [ + "sql/224_ProjectBackupStoryMemory.sql", + 56216 + ], + [ + "sql/053_Phase6A_PlotLineDataModel.sql", + 55839 + ], + [ + "app/Microsoft.Data.SqlClient.Internal.Logging.dll", + 53880 + ], + [ + "app/Microsoft.IdentityModel.Protocols.dll", + 53280 + ], + [ + "sql/226_ProjectRestoreAccountReferences.sql", + 51982 + ], + [ + "sql/223_ProjectBackupAnalysisAudit.sql", + 44495 + ], + [ + "sql/008_Phase1G_ContinuityWarnings.sql", + 41835 + ], + [ + "app/PlotDirector.Companion.Protocol.pdb", + 40952 + ], + [ + "sql/215_ProjectBackupMapStoredMetadata.sql", + 39346 + ], + [ + "sql/222_ProjectBackupCoreLocationReview.sql", + 39282 + ], + [ + "sql/006_Phase1E_Characters.sql", + 39155 + ], + [ + "app/System.Security.Cryptography.ProtectedData.dll", + 38672 + ], + [ + "app/Microsoft.IdentityModel.Logging.dll", + 38432 + ], + [ + "sql/007_Phase1F_Locations.sql", + 37842 + ], + [ + "sql/240_ParagraphManuscripts.sql", + 36707 + ], + [ + "sql/221_ProjectBackupSceneReviewState.sql", + 36093 + ], + [ + "sql/048_Phase5G_ProjectExportArchiving.sql", + 36075 + ], + [ + "sql/174_Phase27_WholeBookPlotIntelligence.sql", + 35676 + ], + [ + "sql/212_MapAppearanceReferences.sql", + 34535 + ], + [ + "sql/241_ParagraphRecovery.sql", + 33383 + ], + [ + "sql/005_Phase1D_StoryAssets.sql", + 32486 + ], + [ + "sql/220_ProjectBackupCoreBuildProvenance.sql", + 32446 + ], + [ + "sql/028_GenreMetricPresets.sql", + 32388 + ], + [ + "sql/034_ProjectBackupExport.sql", + 31345 + ], + [ + "sql/210_MapStoryMode.sql", + 31132 + ], + [ + "sql/036_ProjectRestoreApply.sql", + 30377 + ], + [ + "sql/015_Phase1P_WriterWorkspace.sql", + 29679 + ], + [ + "sql/217_ProjectBackupUploadedFiles.sql", + 29427 + ], + [ + "sql/216_ProjectBackupCompanionSceneLinks.sql", + 28203 + ], + [ + "sql/123_Phase20Z_CommitReadinessAndArchiveHardDelete.sql", + 27975 + ], + [ + "sql/004_Phase1C_PlotThreads.sql", + 26596 + ], + [ + "sql/148_Phase23_NameIntelligence.sql", + 25903 + ], + [ + "sql/014_Phase1O_StoryBible.sql", + 25235 + ], + [ + "sql/020_Phase1T_ArchiveRestore.sql", + 25161 + ], + [ + "sql/001_Phase1A_Core.sql", + 24153 + ], + [ + "sql/165_Phase26A_PovAndCharacterIdentityFoundation.sql", + 24000 + ], + [ + "app/Microsoft.SqlServer.Server.dll", + 23976 + ], + [ + "app/Microsoft.Data.SqlClient.Extensions.Abstractions.dll", + 23672 + ], + [ + "sql/019_Phase1S_Scenarios.sql", + 23557 + ], + [ + "sql/057_Phase10A_WordCompanionApiFoundation.sql", + 23242 + ], + [ + "sql/236_BookRecovery.sql", + 22898 + ], + [ + "sql/134_Phase20AV_ArchivedBookProjectPermanentDeletion.sql", + 22525 + ], + [ + "sql/201_SubscriptionEntitlementEnforcement.sql", + 22225 + ], + [ + "app/PlotLine.deps.json", + 21846 + ], + [ + "sql/093_Phase16A_BaseIdentityAndSceneFoundation.sql", + 21590 + ], + [ + "sql/088_InlineSqlStoredProcedureRefactor.sql", + 21419 + ], + [ + "sql/250_SelectiveChapterShiftedSourceBounds.sql", + 21283 + ], + [ + "sql/162_Phase25G_CoreImportSceneTitles.sql", + 20767 + ], + [ + "sql/089_TimelineLoadPerformance.sql", + 20733 + ], + [ + "sql/285_StoredProcedureCompoundWrites.sql", + 20678 + ], + [ + "sql/018_Phase1R_Dynamics.sql", + 20348 + ], + [ + "sql/249_SelectiveChapterProjections.sql", + 19910 + ], + [ + "sql/211_MapJourneyArchivedSceneRestore.sql", + 19773 + ], + [ + "sql/188_Phase27O_CharacterEnrichmentStructuredFacts.sql", + 19686 + ], + [ + "sql/124_Phase20Z2_StoryIntelligenceCommitAndProjectHardDelete.sql", + 19538 + ], + [ + "app/Microsoft.IdentityModel.Abstractions.dll", + 19528 + ], + [ + "sql/183_Phase27J_CharacterEnrichmentRuns.sql", + 19361 + ], + [ + "sql/209_StoryMapsBackupRestore.sql", + 19148 + ], + [ + "sql/243_ParagraphChapterBoundaries.sql", + 18963 + ], + [ + "sql/032_Phase2C_RelationshipCategories.sql", + 18556 + ], + [ + "sql/027_DragDropQuickAddBar.sql", + 18275 + ], + [ + "sql/046_Phase5E_AuditActivity.sql", + 18172 + ], + [ + "sql/113_Phase20F_OnboardingManuscriptBuild.sql", + 17874 + ], + [ + "sql/147_Phase22C_SafeIllustrationGenerationPolicy.sql", + 17575 + ], + [ + "sql/071_LocationFloorPlans.sql", + 17374 + ], + [ + "sql/095_Phase16C_WordCompanionFirstRunImport.sql", + 17311 + ], + [ + "sql/029_ProjectSceneMetricsManagement.sql", + 16814 + ], + [ + "sql/284_PlotWorkspaceCandidateAssociations.sql", + 16755 + ], + [ + "app/Microsoft.Bcl.Cryptography.dll", + 16648 + ], + [ + "sql/010_Phase1I_Analytics.sql", + 16378 + ], + [ + "sql/200_StoryIntelligenceExceptionReview.sql", + 16352 + ], + [ + "sql/204_PlotLineWorkspaceV1.sql", + 16145 + ], + [ + "sql/094_Phase16B_ManuscriptBindingLinkedStructures.sql", + 15735 + ], + [ + "sql/193_LocationAndAssetMerge.sql", + 15620 + ], + [ + "sql/262_WriterWorkSessions.sql", + 15594 + ], + [ + "sql/142_Phase21S_DurableStoryMemory.sql", + 15502 + ], + [ + "sql/085_ProjectHardDeletionFloorPlansAndImages.sql", + 15271 + ], + [ + "sql/050_Phase5I_StripePaymentIntegration.sql", + 15068 + ], + [ + "sql/042_Phase5A_ProjectUserAccess.sql", + 15001 + ], + [ + "sql/289_ChapterSyncMaterializedIntervals.sql", + 14492 + ], + [ + "sql/181_Phase27H_CoreImportBasicLocationReview.sql", + 14423 + ], + [ + "sql/017_Phase1Q_Exports.sql", + 14387 + ], + [ + "sql/157_Phase25B_OnboardingBuildFirstSceneInsert.sql", + 14345 + ], + [ + "sql/248_ChapterAcceptanceSetBasedAdoption.sql", + 13984 + ], + [ + "sql/080_SceneFloorPlanOccupancy.sql", + 13767 + ], + [ + "sql/177_Phase27D_StoryIntelligencePersistedReviewCandidates.sql", + 13692 + ], + [ + "sql/245_ChapterSynchronisation.sql", + 13325 + ], + [ + "sql/306_CharacterWorkspaceReads.sql", + 13179 + ], + [ + "sql/185_Phase27L_ManualCharacterEnrichment.sql", + 13165 + ], + [ + "sql/135_Phase21C_IllustrationLibrary.sql", + 13121 + ], + [ + "sql/247_ChapterAdoptionSnapshotDigest.sql", + 12983 + ], + [ + "sql/054_ProjectHardDeletion.sql", + 12876 + ], + [ + "sql/219_WordManuscriptImportCurrentSceneModel.sql", + 12841 + ], + [ + "sql/115_Phase20I_StoryIntelligenceResultPersistence.sql", + 12793 + ], + [ + "sql/246_ChapterReviewInvalidatesLivePositions.sql", + 12684 + ], + [ + "sql/026_TimelineConfigurationSettings.sql", + 12335 + ], + [ + "sql/114_Phase20H_StoryIntelligenceFramework.sql", + 12287 + ], + [ + "sql/009_Phase1H_SceneDependenciesAndMoves.sql", + 12233 + ], + [ + "sql/260_WriterActivitySummary.sql", + 11920 + ], + [ + "sql/092_Phase15C_FeatureRequestNotificationsRoadmap.sql", + 11864 + ], + [ + "sql/117_Phase20K_PersistedStoryIntelligenceRunner.sql", + 11621 + ], + [ + "sql/030_Phase2A_RelationshipFoundations.sql", + 11322 + ], + [ + "sql/180_Phase27G_EntityPreferredNameAliases.sql", + 11258 + ], + [ + "sql/037_Phase4A_BespokeAuthFoundation.sql", + 11248 + ], + [ + "sql/002_Phase1B_WorkspaceMetrics.sql", + 11171 + ], + [ + "sql/136_Phase21D_IllustrationLibraryGenerationStudio.sql", + 10972 + ], + [ + "sql/175_Phase27B_StoryIntelligenceIndependentReviewState.sql", + 10884 + ], + [ + "sql/184_Phase27K_ProjectHardDeleteReviewCentreCleanup.sql", + 10606 + ], + [ + "sql/192_LocationNarrativeSignificance.sql", + 10599 + ], + [ + "sql/087_Phase14B_CharacterRelationshipsIdentity.sql", + 10550 + ], + [ + "sql/056_Phase9B_WritingScheduleFoundation.sql", + 10531 + ], + [ + "sql/208_StoryMaps.sql", + 10249 + ], + [ + "sql/253_LocationGeography.sql", + 10242 + ], + [ + "sql/155_Phase25_StoryIntelligenceNarrativeReview.sql", + 10218 + ], + [ + "sql/160_Phase25E_ProjectHardDeleteDependencyCleanup.sql", + 10113 + ], + [ + "sql/291_InvestigationDeletionIdentityLock.sql", + 9961 + ], + [ + "sql/122_Phase20Y_DefaultPlaceholderCommit.sql", + 9910 + ], + [ + "sql/304_CharacterLifeStatusCanonical.sql", + 9844 + ], + [ + "sql/292_NarrativeFocus.sql", + 9813 + ], + [ + "sql/186_Phase27M_AuthoritativeGlobalProgressCompletedScenes.sql", + 9658 + ], + [ + "sql/232_NativeApprovedImport.sql", + 9637 + ], + [ + "sql/252_ChapterReuseStrictPositionRows.sql", + 9538 + ], + [ + "sql/090_Phase15A_FeatureRequests.sql", + 9492 + ], + [ + "sql/290_InvestigationDeletion.sql", + 9425 + ], + [ + "sql/100_Phase16I_WordCompanionCharacterSuggestionReview.sql", + 9397 + ], + [ + "sql/300_ContextRelationshipLenses.sql", + 9226 + ], + [ + "sql/109_DropdownListOrderingConsistency.sql", + 9201 + ], + [ + "sql/254_GeographyAuthorHierarchyBatches.sql", + 9045 + ], + [ + "sql/251_ChapterCheckpointReuse.sql", + 9023 + ], + [ + "sql/118_Phase20L_StoryIntelligenceExistingChapterSource.sql", + 8934 + ], + [ + "sql/259_WritingActivityFoundation.sql", + 8795 + ], + [ + "sql/081_FloorPlanFloorDescriptionAndOccupancyWarnings.sql", + 8764 + ], + [ + "sql/127_Phase20AJ_StoryIntelligencePipelineState.sql", + 8531 + ], + [ + "sql/045_Phase5D_CollaborationFoundation.sql", + 8425 + ], + [ + "sql/168_Phase26D_NarrativeCandidateHierarchy.sql", + 8275 + ], + [ + "sql/179_Phase27F_ReviewCentreCandidateLifecycleSummary.sql", + 8245 + ], + [ + "sql/021_Phase1U_AcceptanceChecklist.sql", + 8182 + ], + [ + "sql/299_ContextNamesUsageScope.sql", + 8180 + ], + [ + "sql/263_WriterPlanningActivities.sql", + 8169 + ], + [ + "sql/061_Phase10H2_WordCompanionSceneLinksRealSceneData.sql", + 8114 + ], + [ + "sql/171_Phase26G_StoryIntelligenceAuthoritativeGlobalProgress.sql", + 8113 + ], + [ + "sql/072_FloorPlanLocationLinks.sql", + 8069 + ], + [ + "sql/317_SharedFocusChapterBoundaries.sql", + 7939 + ], + [ + "sql/265_WriterInlineAuthoring.sql", + 7915 + ], + [ + "sql/078_FloorPlanEditorPerformanceAndReciprocalStairs.sql", + 7802 + ], + [ + "sql/086_Phase14A_CharacterGalleriesAvatars.sql", + 7789 + ], + [ + "sql/043_Phase5B_SubscriptionInfrastructure.sql", + 7776 + ], + [ + "sql/307_CharacterWorkspaceManagement.sql", + 7696 + ], + [ + "sql/154_Phase24C_CoreImportCharacterMappingAndSummaries.sql", + 7580 + ], + [ + "sql/172_Phase26H_StoryIntelligenceSceneAnalysisCompletionBarrier.sql", + 7566 + ], + [ + "sql/163_Phase25H_BookContextAndLeanImportFlow.sql", + 7409 + ], + [ + "sql/103_Phase16K_WordCompanionAssetSuggestions.sql", + 7324 + ], + [ + "sql/116_Phase20J_StoryIntelligenceRunAuditFields.sql", + 7269 + ], + [ + "sql/098_Phase16H_WordCompanionCharacterSuggestions.sql", + 7265 + ], + [ + "sql/025_AssetTimelinePerformance.sql", + 7241 + ], + [ + "sql/079_VisualIdentityCharacterAssetImages.sql", + 7183 + ], + [ + "sql/197_SceneRelationshipDevelopments.sql", + 7072 + ], + [ + "sql/294_NarrativeFocusChapterBoundaries.sql", + 6977 + ], + [ + "sql/272_WriterReviewObservations.sql", + 6974 + ], + [ + "sql/024_CharacterTimelinePerformance.sql", + 6940 + ], + [ + "sql/112_Phase20B_OnboardingProjectBook.sql", + 6919 + ], + [ + "sql/281_WriterActivities.sql", + 6903 + ], + [ + "sql/074_FloorPlanFloorBackgroundImages.sql", + 6778 + ], + [ + "sql/283_DataAccessAuditReads.sql", + 6727 + ], + [ + "sql/167_Phase26C_CanonicalStoryIntelligenceContext.sql", + 6695 + ], + [ + "sql/314_UnifiedManuscriptFocus.sql", + 6693 + ], + [ + "sql/075_FloorPlanTransitions.sql", + 6634 + ], + [ + "sql/169_Phase26E_StoryIntelligenceConcurrentExecution.sql", + 6608 + ], + [ + "sql/310_CharacterRelationshipQuickEdit.sql", + 6562 + ], + [ + "sql/066_Phase13A_BookMetadataBackend.sql", + 6555 + ], + [ + "sql/104_Phase16L_WordCompanionAssetSuggestionReview.sql", + 6546 + ], + [ + "sql/107_Phase16O_WordCompanionLocationSuggestionReview.sql", + 6427 + ], + [ + "sql/105_Phase16M_LocationDetectionMetadata.sql", + 6403 + ], + [ + "sql/238_NativeInstallationAuthorisation.sql", + 6292 + ], + [ + "sql/091_Phase15B_FeatureRequestWorkflow.sql", + 6048 + ], + [ + "sql/052_RevisionStatusWriterWorkflow.sql", + 6021 + ], + [ + "sql/111_Phase20A_StoryIntelligenceOnboarding.sql", + 6002 + ], + [ + "sql/315_SharedFocusCanonicalRead.sql", + 5953 + ], + [ + "sql/106_Phase16N_WordCompanionLocationSuggestions.sql", + 5924 + ], + [ + "sql/121_Phase20V_StoryIntelligenceImportCommit.sql", + 5909 + ], + [ + "sql/023_TimelinePerformanceIndexes.sql", + 5829 + ], + [ + "sql/150_Phase24B_SceneManuscriptSources.sql", + 5797 + ], + [ + "sql/152_NameLibraryAllLocalesDefault.sql", + 5775 + ], + [ + "sql/039_Phase4D_EmailQueue.sql", + 5757 + ], + [ + "sql/267_WriterInlineLongTextValidation.sql", + 5690 + ], + [ + "sql/266_WriterInlineOptionalValues.sql", + 5659 + ], + [ + "sql/321_DeploymentRuntimePermissionContract.sql", + 5603 + ], + [ + "sql/270_WriterAuthoringCanonicalTextLengths.sql", + 5550 + ], + [ + "sql/273_WriterInvestigations.sql", + 5434 + ], + [ + "sql/257_GeographyRequiredLookupAccounting.sql", + 5424 + ], + [ + "sql/126_Phase20AH_ChapterPurposeAndStoryIntelligenceCharacters.sql", + 5386 + ], + [ + "sql/143_Phase21U_DevelopmentStoryIntelligenceReset.sql", + 5337 + ], + [ + "sql/282_WriterEditorialAnnotations.sql", + 5275 + ], + [ + "sql/065_Phase12F_ContinuityWarningAcknowledgements.sql", + 5256 + ], + [ + "sql/170_Phase26F_StoryIntelligenceWholeRunProgress.sql", + 5230 + ], + [ + "sql/033_Phase2D_RelationshipMap.sql", + 5179 + ], + [ + "sql/022_CharacterImportance.sql", + 5130 + ], + [ + "sql/178_Phase27E_ReviewCentreMetricSummary.sql", + 5102 + ], + [ + "sql/176_Phase27C_StoryIntelligenceReviewCentreSummary.sql", + 5000 + ], + [ + "sql/041_Phase4F_SecurityHardening.sql", + 4967 + ], + [ + "sql/055_AccountHardDeletion.sql", + 4965 + ], + [ + "sql/137_Phase21H_BookLevelStoryIntelligenceImportSessions.sql", + 4964 + ], + [ + "sql/198_FixDevelopmentAccountResetObsoleteIllustrationAssignmentReference.sql", + 4900 + ], + [ + "sql/077_FloorPlanStairTransitionPlacement.sql", + 4722 + ], + [ + "sql/264_WriterFoundationQueues.sql", + 4696 + ], + [ + "sql/164_Phase25I_SceneTextStatistics.sql", + 4669 + ], + [ + "sql/305_ContextFamilyExploration.sql", + 4650 + ], + [ + "sql/051_SubscriptionLevelDisplayPricing.sql", + 4604 + ], + [ + "sql/047_Phase5F_StorageManagement.sql", + 4559 + ], + [ + "sql/149_Phase24_StructuralImportMarkerSync.sql", + 4530 + ], + [ + "sql/060_Phase10H1_WordCompanionSceneLinksEmptySelections.sql", + 4467 + ], + [ + "sql/313_CharacterRelationshipLensFilters.sql", + 4375 + ], + [ + "sql/287_ControlledKnownCharacterQueueContracts.sql", + 4166 + ], + [ + "sql/146_Phase22B_StoryIntelligenceKnownCharactersContext.sql", + 4089 + ], + [ + "sql/035_ProjectRestorePoints.sql", + 4045 + ], + [ + "sql/312_CharacterRelationshipGroupBounds.sql", + 4003 + ], + [ + "sql/138_Phase21I_IntelligentIllustrationMatching.sql", + 3980 + ], + [ + "sql/158_Phase25C_OnboardingMarkerSaveStates.sql", + 3969 + ], + [ + "sql/145_Phase22_CharacterIntelligenceProfiles.sql", + 3953 + ], + [ + "sql/191_StoryPointHistory.sql", + 3933 + ], + [ + "sql/309_CharacterRelationshipGroups.sql", + 3806 + ], + [ + "sql/063_Phase10J_UnmatchedSceneChapterDiagnostics.sql", + 3804 + ], + [ + "sql/067_Phase13B_BookCoverUpload.sql", + 3781 + ], + [ + "sql/149_Phase24_LeanImportCompletionNotifications.sql", + 3749 + ], + [ + "sql/277_InvestigationGuidanceBookScope.sql", + 3746 + ], + [ + "sql/276_InvestigationGuidanceProcedure.sql", + 3673 + ], + [ + "evidence/baseline.json", + 3642 + ], + [ + "sql/141_Phase21K_IllustrationAssignmentAuditFields.sql", + 3625 + ], + [ + "sql/031_Phase2B_RelationshipTimeline.sql", + 3593 + ], + [ + "sql/237_DurableManuscriptCapture.sql", + 3584 + ], + [ + "sql/011_Phase1L_TimelineViewPresets.sql", + 3563 + ], + [ + "sql/258_GeographyBoundedContextFallback.sql", + 3554 + ], + [ + "sql/040_Phase4E_TwoFactorAuthentication.sql", + 3546 + ], + [ + "sql/308_CharacterWorkspaceConnectionSummaries.sql", + 3538 + ], + [ + "sql/058_Phase10E2_WordCompanionResolveSceneMatching.sql", + 3501 + ], + [ + "sql/196_RelationshipReviewChronologyAndTypes.sql", + 3447 + ], + [ + "sql/189_Phase27P_BackfillDateOfBirthFromAgeEvidence.sql", + 3445 + ], + [ + "sql/233_NativeImportedPositions.sql", + 3420 + ], + [ + "sql/096_Phase16D_WordCompanionCharacterDiscovery.sql", + 3392 + ], + [ + "sql/120_Phase20R_DeterministicChapterParagraphs.sql", + 3234 + ], + [ + "sql/231_NativeChapterReview.sql", + 3204 + ], + [ + "sql/049_Phase5H_SubscriptionManagementUI.sql", + 3162 + ], + [ + "sql/173_Phase26I_StoryIntelligenceModernMaterialisation.sql", + 3131 + ], + [ + "sql/234_NativeImportedSessionGuard.sql", + 3121 + ], + [ + "sql/195_LocationReparent.sql", + 3033 + ], + [ + "sql/269_WriterAuthoringEmptyCollectionTokens.sql", + 2964 + ], + [ + "sql/268_WriterAuthoringFieldConcurrency.sql", + 2923 + ], + [ + "sql/293_NarrativeFocusCanonicalOrder.sql", + 2916 + ], + [ + "sql/261_WriterWorkingObjective.sql", + 2821 + ], + [ + "sql/311_RelationshipEvolutionRefinement.sql", + 2771 + ], + [ + "sql/153_SelfHealingProjectMetricDefaults.sql", + 2709 + ], + [ + "sql/318_DeploymentHistory.sql", + 2671 + ], + [ + "sql/062_Phase10J_WordCompanionSceneCreateLink.sql", + 2619 + ], + [ + "sql/235_WritingIntentAssessment.sql", + 2561 + ], + [ + "sql/280_WriterFocusIntention.sql", + 2500 + ], + [ + "sql/064_Phase10K_WordCompanionChapterCreateLink.sql", + 2498 + ], + [ + "sql/139_Phase21J2_IllustrationMetadataBackfill.sql", + 2478 + ], + [ + "sql/132_Phase20AT_RelationshipTypeTaxonomy.sql", + 2463 + ], + [ + "sql/070_TimelineDefaultSceneFocusedView.sql", + 2457 + ], + [ + "sql/097_Phase16F_WordCompanionRuntimeSceneWordCountSync.sql", + 2288 + ], + [ + "sql/166_Phase26B_StructuralPovAudit.sql", + 2288 + ], + [ + "sql/159_Phase25D_ManuscriptSourceHardDeleteCascades.sql", + 2287 + ], + [ + "sql/242_CoreImportCompletion.sql", + 2266 + ], + [ + "sql/016_FixCharacterTimelineAppearanceLabels.sql", + 2184 + ], + [ + "sql/230_WordMarkerAcknowledgementOwnership.sql", + 2150 + ], + [ + "sql/099_FixSceneCharacterSaveQuotedIdentifier.sql", + 2122 + ], + [ + "sql/316_SharedFocusWordPositions.sql", + 2115 + ], + [ + "sql/108_Phase16Q_ManuscriptUnlink.sql", + 2072 + ], + [ + "sql/012_SceneCharacterEditing.sql", + 2070 + ], + [ + "sql/218_ImportSharedAssetStateLookups.sql", + 2062 + ], + [ + "sql/083_FloorPlanEditorOccupancyIndexes.sql", + 1976 + ], + [ + "sql/239_ManuscriptAnalysisCheckpoints.sql", + 1938 + ], + [ + "sql/044_Phase5C_SubscriptionLimitUsage.sql", + 1915 + ], + [ + "sql/082_FloorPlanOccupancySceneOrdering.sql", + 1842 + ], + [ + "sql/206_WritingProblemSolver.sql", + 1837 + ], + [ + "sql/013_Phase1N_DragDrop.sql", + 1758 + ], + [ + "sql/296_WriterChapterVerification.sql", + 1710 + ], + [ + "sql/161_Phase25F_CanonicalSceneSourceStoryIntelligence.sql", + 1642 + ], + [ + "sql/199_FixCharacterEnrichmentClaimNextQuotedIdentifier.sql", + 1547 + ], + [ + "sql/102_Phase16J_FixFollowSceneEditUrl.sql", + 1545 + ], + [ + "sql/059_Phase10F_WordCompanionSceneProgressSync.sql", + 1540 + ], + [ + "sql/133_Phase20AU_KnowledgeReviewPipelineStages.sql", + 1531 + ], + [ + "sql/190_Phase27Q_CharacterEnrichmentClaimIsolation.sql", + 1495 + ], + [ + "sql/322_DeploymentRuntimeHealth.sql", + 1491 + ], + [ + "sql/119_Phase20R_FullChapterTestHarness.sql", + 1454 + ], + [ + "sql/274_WriterEditorialCatalogues.sql", + 1412 + ], + [ + "sql/128_Phase20AL_SceneListImportTracking.sql", + 1346 + ], + [ + "sql/244_WritingContextRecordedMetrics.sql", + 1335 + ], + [ + "sql/140_Phase21J3_DemandIllustrationStyleMarkers.sql", + 1256 + ], + [ + "sql/279_InvestigationSavedActivity.sql", + 1241 + ], + [ + "sql/151_BackfillDefaultSceneMetricValues.sql", + 1222 + ], + [ + "sql/202_UserApplicationAppearance.sql", + 1200 + ], + [ + "sql/156_Phase25A_NarrativeReviewPipelineConstraint.sql", + 1179 + ], + [ + "sql/076_FloorPlanFloorLevels.sql", + 1116 + ], + [ + "sql/278_InvestigationSavedSummaries.sql", + 1087 + ], + [ + "sql/131_Phase20AS_RelationshipReviewPipelineStages.sql", + 1051 + ], + [ + "sql/203_UserApplicationBarPreferences.sql", + 1038 + ], + [ + "sql/271_WriterWordStatus.sql", + 993 + ], + [ + "sql/130_Phase20AP_AssetReviewPipelineStages.sql", + 981 + ], + [ + "sql/201_UserToolbarPreferences.sql", + 976 + ], + [ + "sql/297_ContextCharacterImportDefault.sql", + 963 + ], + [ + "sql/295_UserToastPosition.sql", + 956 + ], + [ + "sql/129_Phase20AN_LocationReviewPipelineStages.sql", + 925 + ], + [ + "sql/194_ProjectActivityMergeType.sql", + 923 + ], + [ + "sql/069_CharacterAttributeEventsByScene.sql", + 914 + ], + [ + "sql/125_Phase20AE_RemoveDefaultScenePlaceholder.sql", + 875 + ], + [ + "sql/275_InvestigationGuidance.sql", + 847 + ], + [ + "sql/288_ManuscriptReaderNavigation.sql", + 754 + ], + [ + "sql/110_LocationLeafNameListOrdering.sql", + 739 + ], + [ + "sql/003_FixScenePurposeSave.sql", + 726 + ], + [ + "evidence/qualification.json", + 670 + ], + [ + "sql/207_PlotDirectorApplicationTheme.sql", + 641 + ], + [ + "sql/298_ContextCharacterAliases.sql", + 635 + ], + [ + "sql/073_FloorPlanDeleteProcedureSettings.sql", + 614 + ], + [ + "sql/213_ProjectBackupBookContext.sql", + 549 + ], + [ + "sql/205_UserApplicationAppearanceThemes.sql", + 544 + ], + [ + "sql/256_GeographyQueueIndex.sql", + 528 + ], + [ + "sql/144_Phase21V_StoryMemoryImportContext.sql", + 497 + ], + [ + "sql/038_Phase4B_RegisterLoginLogout.sql", + 488 + ], + [ + "app/PlotLine.runtimeconfig.json", + 472 + ], + [ + "sql/319_DeploymentHealth.sql", + 367 + ], + [ + "sql/182_Phase27I_CoreImportBasicLocationDevReset.sql", + 323 + ], + [ + "sql/255_GeographyHierarchyStateWidth.sql", + 313 + ], + [ + "sql/187_Phase27N_CharacterEnrichmentEvidenceValueLength.sql", + 253 + ], + [ + "sql/150_Phase24B_RemoveVisualisationIllustrationAssignments.sql", + 222 + ] +] diff --git a/Docs/Deployment/Evidence/Transport-20261125/production-unchanged.json b/Docs/Deployment/Evidence/Transport-20261125/production-unchanged.json new file mode 100644 index 00000000..2bfd395b --- /dev/null +++ b/Docs/Deployment/Evidence/Transport-20261125/production-unchanged.json @@ -0,0 +1,17 @@ +{ + "status": "public-unchanged", + "application_release": "eadda6f6", + "application_action_taken": false, + "tooling_installation": "pending temporary administrator authorisation", + "sites": { + "plotdirector": { + "https_status": 200, + "tls_verified": true + }, + "catherine": { + "https_status": 200, + "tls_verified": true + } + }, + "production_css_matches_eadda6f6": true +} diff --git a/Docs/Deployment/Evidence/Transport-20261125/qualification.json b/Docs/Deployment/Evidence/Transport-20261125/qualification.json new file mode 100644 index 00000000..5a4a5267 --- /dev/null +++ b/Docs/Deployment/Evidence/Transport-20261125/qualification.json @@ -0,0 +1,13 @@ +{ + "status": "qualified-on-atlas-installation-pending", + "deployment_regression_tests": 67, + "retained_compressed_release_all_checksums_and_signatures": "passed", + "legacy_signed_release_compatibility": "passed", + "real_root_filesystem_receipt_boundaries": "passed", + "isolated_sql_worker_counters_replay_and_failure_rollback": "passed", + "application_rebuilt": false, + "production_application_activated": false, + "production_tooling_installed": false, + "web1_decompression_measured": false, + "blocker": "Existing dedicated Atlas key needs temporary administrator authorisation for reviewed root-owned tooling maintenance; no SQL admin credentials needed." +} diff --git a/Docs/Deployment/Evidence/Transport-20261125/retained-package-receipt.json b/Docs/Deployment/Evidence/Transport-20261125/retained-package-receipt.json new file mode 100644 index 00000000..0d4e7dbb --- /dev/null +++ b/Docs/Deployment/Evidence/Transport-20261125/retained-package-receipt.json @@ -0,0 +1,99 @@ +{ + "format": 1, + "origin": "atlas-retained-package-qualification", + "started_utc": "2026-11-25T17:23:21.718+00:00", + "completed_utc": "2026-11-25T17:23:24.373+00:00", + "status": "validated-package-only", + "phases": [ + { + "name": "package_validation", + "started_utc": "2026-11-25T17:23:21.718+00:00", + "parent": null, + "outcome": "passed", + "completed_utc": "2026-11-25T17:23:21.904+00:00", + "seconds": 0.185414, + "exclusive_seconds": 0.185414 + }, + { + "name": "decompression", + "started_utc": "2026-11-25T17:23:21.904+00:00", + "parent": null, + "outcome": "passed", + "completed_utc": "2026-11-25T17:23:22.927+00:00", + "seconds": 1.022908, + "exclusive_seconds": 1.022908 + }, + { + "name": "package_validation", + "started_utc": "2026-11-25T17:23:22.927+00:00", + "parent": null, + "outcome": "passed", + "completed_utc": "2026-11-25T17:23:24.356+00:00", + "seconds": 1.428878, + "exclusive_seconds": 1.428878 + } + ], + "warnings": [], + "failures": [], + "checks": { + "unchanged_original_signature": true, + "transport_signature": true, + "original_tar_sha256": true, + "all_application_and_sql_checksums": true, + "exact_qualified_dll": true + }, + "migrations": { + "executed": null, + "baselined": null + }, + "recovery": "No automatic database restore or application rollback. Review protected attempt evidence on failure.", + "transport": { + "method": "zstd", + "original_bytes": 554260480, + "transferred_bytes": 165585450, + "original_sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7", + "transferred_sha256": "f0786b505d5f1b1a43ff28283ca730b0e045f19a395432d85013c998292d85a1", + "compression_ratio": 0.29875, + "compression_seconds_atlas": 2.0684954689932056, + "settings": { + "level": 6, + "threads": 4 + } + }, + "release": { + "id": "plotdirector-production-eadda6f6-20261125-r1", + "version": "1.0.0", + "source_commit": "eadda6f674ac456e8ae6014e2c5781088d408f8f", + "package_sha256": "e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7", + "application_sha256": "238850639212d9f39bc6e208f0799dd1fb42c7f6a3d903386ccdf406baa6cb22" + }, + "timing": { + "total_seconds": 2.654963, + "measured_top_level_seconds": 2.6372, + "unattributed_seconds": 0.017763, + "clock": "monotonic; UTC timestamps for correlation only" + }, + "unperformed_phases": [ + "release_preparation", + "production_validation", + "remote_activation", + "receipt_retrieval", + "scope_verification", + "build", + "packaging_signing", + "compression", + "transfer", + "database_state_verification", + "migration_history_verification", + "database_backup", + "migration_execution", + "service_stop", + "release_installation", + "release_activation", + "service_start", + "application_health_readiness", + "postactivation_verification", + "public_acceptance", + "receipt_generation" + ] +} diff --git a/Docs/Deployment/Evidence/Transport-20261125/worker-qualification.json b/Docs/Deployment/Evidence/Transport-20261125/worker-qualification.json new file mode 100644 index 00000000..7adcc005 --- /dev/null +++ b/Docs/Deployment/Evidence/Transport-20261125/worker-qualification.json @@ -0,0 +1,13 @@ +{ + "status": "passed", + "isolated_database": "PlotDirector_Qualification_Transport_20261125", + "executed": 2, + "baselined": 1, + "replay_executed": 0, + "failed_transaction_rolled_back": true, + "failed_success_history_absent": true, + "readback_existing_activation_record": "passed", + "existing_retained_history_rows": 320, + "no_production_connection": true, + "fixture_database_removed": true +} diff --git a/Docs/Deployment/Production.md b/Docs/Deployment/Production.md index fcc2c723..b8db08e5 100644 --- a/Docs/Deployment/Production.md +++ b/Docs/Deployment/Production.md @@ -7,6 +7,10 @@ future changes still require environment-specific authorisation and qualificatio Latest routine release: `eadda6f6`, version `1.0.0`; see [deployment and timings](Routine-20261125-eadda6f6.md). +**Tooling update:** compressed transport/receipts are qualified on Atlas but await +the authorised web1 maintenance installation; see [qualification and status](Transport-20261125.md). +Use raw packages until that installation is verified. + ## Trust and environment boundaries - Build only on Atlas, from a clean, committed worktree. Keep source, SDKs and @@ -128,7 +132,7 @@ manual SQL procedure alongside this ledger after adoption. ## Activation and failure behaviour `transfer.py` sends only the three immutable bundle files over strict SSH. The -forced SSH dispatcher supports upload, validate, activate and rollback with one +forced SSH dispatcher supports upload, validate, activate, rollback and sanitized receipt retrieval with one validated release ID; it rejects shells, SFTP and other commands. Transfer alone does not activate anything. An incomplete upload requires administrator review; it is not overwritten automatically. @@ -316,3 +320,140 @@ RENEWED_LINEAGE is `/etc/letsencrypt/live/plotdirector.com`, then runs `nginx -t and reloads Nginx. The targeted dry run passed. Never replace Catherine's files. The supplied vhost template requires the PlotDirector map and maintenance snippet; initial provisioning starts with 503, while the live snippet contains only a comment. + + +## Compressed transport and standard routine receipt + +Selected transport: **Zstandard level 6, four workers, frame checksum**. Preparation +now defaults to this codec; `--compression none` retains the original tar format. +The original USTAR `package.tar`, authorization.json and Ed25519 authorization.sig +remain the integrity/recovery basis. Compression does not change manifest bytes, +application/SQL contents or the original signature. A new transport.json/signature +binds compressed bytes/hash/size, original tar hash/size and original authorization +hash. The compressed bundle contains exactly these transfer members: + +``` +authorization.json +authorization.sig +transport.json +transport.sig +package.tar.zst +``` + +Original three-file raw bundles remain valid. To wrap a retained raw release, +without any application rebuild or modification of that original bundle: + +```bash +python3 Tools/Deployment/release.py compress \ + --bundle /absolute/original-signed-bundle \ + --output /absolute/new-compressed-bundle \ + --signing-key /absolute/private/release-signing.pem \ + --public-key /absolute/trusted/release-signing-public.pem +``` + +Both signatures and compressed integrity are checked before decoding. The decoder +uses signed exact output size, a 4 GiB global input/output ceiling, 128 MB window +limit and CPU/wall limits. Reconstructed bytes must match the original signed tar +SHA, then all original safe extraction, manifest, SQL and application checks run. +No unsigned patches, incremental updates or active-directory modification occurs. +Allow space for compressed snapshot + original tar + extracted payload + new +release, as well as existing backups/releases and the configured free-space floor. +Failed transfer/decompression affects only incoming/private temporary storage. +Upload and deployment locks remain independent and mandatory. + +For new release preparation, continue the qualified-source/evidence process above, +add `--scope-base FULL_CURRENT_APPLICATION_COMMIT`, and use the default compression. +For measured end-to-end orchestration, `deploy.py` can prepare from clean source +(`--source`, `--scope-base`, `--plan`, `--sql`, `--evidence`, `--output`, +`--release-id`, `--signing-key`) or use an existing qualified `--bundle` instead: + +```bash +python3 Tools/Deployment/deploy.py \ + --bundle /absolute/qualified-compressed-bundle \ + --identity /home/nick/.ssh/plotdirector-production \ + --public-key /absolute/trusted/release-signing-public.pem \ + --receipt /absolute/private/new-operation-receipt.json \ + --public-acceptance +``` + +This defaults to **non-activating validation**. Add `--activate` only with explicit +application-release authorisation. Unexpected pending history blocks activation; +`--allow-migrations` requires a separately reviewed/qualified and authorised SQL +upgrade. The application source/qualification process is unchanged. Scope timing +captures clean-commit checks and Git differences, not a claim of automatic semantic +review. Human scope/release approval remains necessary before signing/activation. + +No long bespoke Markdown report is needed for an ordinary success. The command +writes a structured JSON receipt plus a concise text summary from the same data. +Keep detailed protected diagnostics for failures or exceptional timings. Receipts +carry release/version/source, package/application/DLL checksums, compressed/original +sizes and ratio, measured transfer/throughput, previous/new identity, backup result, +actual history counts and executed/baselined migrations, read-back activation row, +health, optional public acceptance, warnings/recovery and phase measurements. +Failed server receipts are retrieved too; failed public acceptance remains a failed +pipeline outcome even if the nested server record correctly shows an active release. +No automatic retry, database restore or unqualified rollback is introduced. + +Server receipts: `/srv/plotdirector/deployment-receipts/DEPLOYMENT-ID.json` and +`.txt`, root:plotdirector-deploy 0640 in root:plotdirector-deploy 0750 directory. +Retrieve JSON using the existing strict SSH options and command `receipt ID`. +This reads only bounded root-owned regular sanitized receipt files, never arbitrary +paths, protected attempt logs, configuration or credentials. The forced dispatcher +and fixed sudo helper remain the only entry points; no general sudo/shell or +additional database privilege is granted. The root-protected detailed JSONL attempt +evidence remains separate. Receiver transfer metrics are explicitly unprivileged +telemetry, not authorisation; Atlas sender throughput is measured independently. + +Timing uses monotonic clocks. Parent phase durations include child phases; +exclusive durations and unattributed overhead prevent double counting. UTC values +are for correlation, not elapsed-time arithmetic. SQL history verification is timed +in the worker with Stopwatch; if child UTC endpoints are unavailable they are null, +not reconstructed. Missing/unperformed phases are explicit, never measured zero. +Service confirmed-inactive-to-start-command-complete and inactive-to-health-ready +are separate from stop-request-inclusive intervals and independently sampled public +outage. Source preparation and web1 operations have distinct clocks/provenance. +The combined pipeline measures its own total including otherwise unattributed work; +using an already prepared bundle does not pretend to measure an earlier build. + +Standard target: **3–5 minutes** for a routine release where achievable; **10 minutes** +is the normal upper target subject to essential backup, integrity and health checks. +Investigate exceptional times. Reuse valid qualification; do not repeat full app, +Companion or recovered-database exercises on ordinary releases. Postactivation +checks and history/row readback now occur inside the helper, so a further complete +package extraction solely for status/reporting is unnecessary. Pre-activation +validation and activation still independently verify immutable package integrity. + +## Tooling-only administrative maintenance + +Tooling installation is separate from an application release. If Atlas's temporary +administrator authorisation has been removed, a desktop/laptop administrator must +briefly re-authorise only the existing dedicated Atlas public key, fingerprint +`SHA256:2Iw3JYNS8TgPARowjnp+7wNC6cmWf1EV7Cy1Mg1ig3w`. Use strict pinned SSH and +remove that one authorisation after maintenance; preserve all other admin keys. +The deployment account must never replace its own helper or read migration secrets. + +1. Record the live current link, DLL/source identity, application PID and configuration + hashes, and Catherine HTTPS. Confirm `/usr/bin/zstd` availability. Stop if a + prerequisite is missing; do not change application or unrelated infrastructure. +2. Publish only DatabaseWorker on Atlas from the reviewed tooling source. Stage + reviewed hashes/files privately. No SDK, repository or Codex is installed on web1. +3. Take the existing `/srv/plotdirector/deployment.lock` exclusively. Preserve the + previous helper/modules and entire worker output under a new protected + `/srv/backups/configuration/plotdirector-tooling-before-TIMESTAMP/` directory. +4. Install receipt.py/transport.py first, then release.py and the new worker, then + activate.py/dispatcher/launcher, all root-owned and non-writable by runtime/deploy. + Worker directory/files remain 0755/0644; dispatcher and launcher 0755. Create the + receipt directory with explicit root:plotdirector-deploy 0750 permissions. Keep + target/configuration, credentials, service, SSH/sudo and web server settings intact. +5. For the retained signed package transport test, preserve the existing incoming + directory under a new protected transport-test archive before using the same + release ID; never overwrite it or alter signed tar/manifest bytes. Upload the + compressed wrapper through the restricted account, use `validate` only and + retrieve its sanitized receipt. Test the raw package separately with the verifier. + Do not invoke activate/rollback/migrate, backup/restore, or service stop/start. +6. Confirm decoder measurements on web1, original tar/DLL checksums, receipt read + restrictions, unchanged current link/PID/configuration hashes, history counts and + successful-release count, and continued normal HTTPS for both sites. Remove only + temporary maintenance files/authorisation; retain recovery and diagnostic evidence. + +No Production application activation is authorised by a tooling-maintenance task. diff --git a/Docs/Deployment/Transport-20261125.md b/Docs/Deployment/Transport-20261125.md new file mode 100644 index 00000000..ee29ff0e --- /dev/null +++ b/Docs/Deployment/Transport-20261125.md @@ -0,0 +1,124 @@ +# Signed transport and receipt qualification — 25 November 2026 + +**Atlas implementation qualified; web1 tooling installation is pending temporary +administrator authorisation.** No Production application release was activated. +The active application remains eadda6f6; public HTTPS and Catherine HTTPS return +200, and Production CSS still exactly matches eadda6f6. + +The retained successful routine package is an uncompressed USTAR archive: +554260480 bytes / 528.58 MiB, SHA-256 +`e4990e90c3d32084e87af5bb149c5aff393b61e7e0c03f8e3c5120771686a4d7`. +The application was not rebuilt. Each candidate was compressed, decompressed to +a real temporary file and checked against that original SHA-256. Source/signature +and manifest/file/DLL identity were separately verified using the full retained +signed release. No application dependencies or other package contents were removed. + +## Compression benchmark + +Compression/decompression durations, sizes and encoder peak RSS below were +**measured on Atlas**, sequentially at nice 10. Transfer durations are **estimates** +using the prior observed 1.888 MiB/s file-payload throughput. Combined time is +compression + estimated transfer + measured Atlas decompression. SHA verification +was performed separately from the benchmark decoder timer. These are single warm +fixture trials, not statistically significant comparisons of subsecond differences. + +| Method | Compression s | MiB | Estimated transfer s | Atlas decode s | Combined s | Peak encoder MiB | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| uncompressed | 0.000 | 528.58 | 279.97 | 0.000 | 279.97 | 0.0 | +| gzip-1 | 5.747 | 192.50 | 101.96 | 2.067 | 109.78 | 7.7 | +| gzip-6 | 17.991 | 173.40 | 91.85 | 1.845 | 111.68 | 7.7 | +| zstd-1-T1 | 1.652 | 180.28 | 95.49 | 0.623 | 97.76 | 17.7 | +| zstd-1-T4 | 0.481 | 180.28 | 95.49 | 0.619 | 96.59 | 30.8 | +| zstd-1-T8 | 0.408 | 180.28 | 95.49 | 0.656 | 96.55 | 46.4 | +| zstd-3-T1 | 2.447 | 166.86 | 88.38 | 0.668 | 91.50 | 50.9 | +| zstd-3-T4 | 0.788 | 166.86 | 88.38 | 0.660 | 89.83 | 91.1 | +| zstd-3-T8 | 0.735 | 166.86 | 88.38 | 0.670 | 89.79 | 142.9 | +| zstd-6-T1 | 6.684 | 157.91 | 83.64 | 0.645 | 90.97 | 52.3 | +| zstd-6-T4 | 2.027 | 157.91 | 83.64 | 0.661 | 86.33 | 95.4 | +| zstd-6-T8 | 1.627 | 157.91 | 83.64 | 0.671 | 85.94 | 154.9 | + +Select **Zstandard level 6, four workers, frame checksum enabled**. It produces +165585450 bytes / 157.91 MiB (29.87% of original, approximately 70.1% smaller). +Measured compression 2.027s, Atlas decompression 0.661s, estimated transfer 83.64s; +combined 86.33s versus the 280s uncompressed transfer baseline. Estimated transfer +savings are about 196s. Eight workers saved only approximately 0.4s, while increasing +CPU consumption from 8.33 to 12.37 CPU seconds and peak RSS from 95.4 to 155.0 MiB. +Level 3 compresses faster, but its larger output adds more transfer time overall. +Gzip also helps substantially, but is slower overall than the selected Zstandard. + +Representative web1 decoder timing is **not yet measured**: the existing restricted +account intentionally cannot run arbitrary benchmark commands or install helpers, +and Atlas's temporary administrator key was removed at Phase 2 completion. No +attempt was made to circumvent this boundary. A retained staged compressed package +and installation procedure are ready for the authorised maintenance window. + +Keeping other baseline timings unchanged, replacing transfer and bespoke reporting +suggests approximately **4.3 minutes** overall. The automated pipeline can reduce +orchestration further; a **3–5 minute target is an estimate**, not a measured genuine +release. Ten minutes remains the normal upper target, subject to essential safety. +The next genuine application release is the definitive end-to-end benchmark. + +## Implementation and focused qualification + +- Original authorization/manifest signatures remain byte-identical. A separately + signed transport envelope binds original authorization hash, original tar hash + and size, compressed hash and size, release/source identity and codec settings. + Corrupt compressed bytes are rejected before the decoder is launched. Decoded + bytes must match both the original signature and complete manifest/file index. +- Original raw packages remain supported. Decoder output is capped to the signed + size and 4 GiB global maximum, with a 128 MB decoder window limit and CPU/wall + limits. Existing regular-file-only archive extraction, no-follow snapshots, + traversal/link/special-member/duplicate checks and count/size limits remain. + Space checks include reconstructed archive, extraction and installation. +- Upload remains unprivileged, fixed-member, bounded and serialised. Upload and + validation never stop a service. Failed/incomplete staging is retained for review. + Backup, transaction, history immutability, deployment lock, activation and + qualified rollback safeguards remain. No incremental/unsigned active-file patching. +- Root creates sanitized JSON/text receipts; the fixed `receipt ID` SSH operation + reads only those receipts. It cannot read protected logs/configuration. The + directory is root:plotdirector-deploy 0750, files 0640; the account gains no write + or general sudo/shell privilege. Credential-like fields/values are defensively + redacted; raw exceptions and command arguments are not copied into receipts. +- Receipts contain actual before/after release identity, package/application/DLL + checksums, transport sizes/ratio, transfer provenance/throughput, backup result, + measured migration counts, read-back activation row, health, failures/recovery, + monotonic timing and otherwise unattributed overhead. Service inactive-to-start, + inactive-to-readiness and independently observed public outage are distinct. + SQL worker history durations are measured with Stopwatch; UTC child endpoints + are null when unavailable, never estimated. Unperformed phases remain explicit. +- `deploy.py` is the measured Atlas workflow. It defaults to validate only; activation + is explicit, and pending history requires a separately authorised allow-migrations + run. It retrieves failed server receipts too. Its JSON/text summary replaces + lengthy bespoke routine reports. Postactivation history checks happen inside the + worker and its successful activation record is read back, avoiding another full + package extraction solely to obtain these facts. + +Focused qualification: **67 deployment regression tests passed**, including all +previous tests and compression/signature/checksum/corruption/truncation/expansion, +unsafe archive, lock, upload failure, timing, receipt/redaction, activation/backup/ +rollback and permission cases. A real root-owned Atlas filesystem fixture proved +intended-group read-only access, other-user denial, symlink and foreign-owner +rejection. A new tiny isolated SQL fixture proved 2 executed / 1 baselined count, +zero-execution replay and failed transaction/history rollback, then was removed. +The common C# activation-record reader was checked against retained Test history. +No full application/Companion suite, recovered-database restore or Production +migration was repeated. Only DatabaseWorker was published on Atlas. + +## Pending installation and remaining opportunities + +Temporary administrator authorisation for the existing dedicated Atlas key is +required solely to replace root-owned tooling/worker files and create the receipt +directory. The restricted account correctly cannot do this. Use the established +strict-host-key administrative maintenance procedure, keep other admin keys, and +remove only the temporary Atlas key after qualified installation/non-activating +checks. No permanent Atlas administrator access or expanded deployment sudo is +needed. See the standard's maintenance procedure. Do not stop/start the app, invoke +migrate/activate, or alter SQL/Nginx/SSH/Certbot/configuration during this installation. + +Further reduction opportunity: Windows runtime directories alone occupy about +276 MiB. Other RIDs and native variants also contribute. A future qualified +framework-dependent linux-x64 publish may exclude unnecessary platform assets; +no files were removed here, and download/Companion dependencies must be reviewed +before such a change. The full immutable package remains the unit of deployment. + +[Machine-readable measurements](Evidence/Transport-20261125/compression-benchmark.json). diff --git a/Tools/Deployment/DatabaseWorker/Program.cs b/Tools/Deployment/DatabaseWorker/Program.cs index f663c0d1..68024a8d 100644 --- a/Tools/Deployment/DatabaseWorker/Program.cs +++ b/Tools/Deployment/DatabaseWorker/Program.cs @@ -20,6 +20,9 @@ internal static class Program private static string packageHash = ""; private static string? currentMigration; private static int currentBatch; + private static int executed; + private static int baselined; + private static readonly List committed = []; public static async Task Main(string[] args) { @@ -55,7 +58,7 @@ internal static class Program { Console.WriteLine(JsonSerializer.Serialize(new { ok = false, error = e is SqlException se ? "SQL_" + se.Number : e.Message is "baseline" or "concurrent-deployment" or "immutable-migration-checksum" ? e.Message : e.GetType().Name, - migration = currentMigration, batch = currentBatch })); + migration = currentMigration, batch = currentBatch, executed, baselined, committed = committed.Take(256) })); // A failed command poisons the session. Never proceed to activation. return 1; } @@ -107,13 +110,16 @@ internal static class Program if (!Regex.IsMatch(deployment, "^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$") || !Regex.IsMatch(packageHash,"^[a-f0-9]{64}$")) throw new InvalidOperationException("identity"); var actual = await Schema(); + var historyTimer=Stopwatch.StartNew(); var complete = await ValidateHistory(); + var historySeconds=historyTimer.Elapsed.TotalSeconds; + var history=await HistoryStatus(); if (actual != S(manifest, "starting_schema_sha256") && !(complete && actual == S(manifest,"resulting_schema_sha256"))) throw new InvalidOperationException("baseline"); await Idle(); await Conditions(manifest["prerequisites"]!.AsArray()); var databaseBytes=Convert.ToInt64(await Scalar("SELECT SUM(CONVERT(bigint,size))*8192 FROM sys.database_files")); - return new { schema = actual, complete, database_bytes=databaseBytes }; + return new { schema = actual, complete, database_bytes=databaseBytes, history, history_verification_seconds=historySeconds }; } if (!locked || manifest is null) throw new InvalidOperationException("not-begun"); if (op == "idle") { await Idle(); return new { idle = true }; } @@ -139,14 +145,18 @@ internal static class Program var schema = await Schema(); if (schema != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("resulting-schema"); await Conditions(manifest["postconditions"]!.AsArray()); - return new { schema }; + return new { schema, executed, baselined, committed=committed.Take(256), committed_list_truncated=committed.Count>256 }; } if (op == "health") { if ((string?)await Scalar("SELECT DB_NAME()") != database) throw new InvalidOperationException("target"); if (await Schema() != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("schema"); await Conditions(manifest["postconditions"]!.AsArray()); - return new { healthy = true }; + var timer=Stopwatch.StartNew(); + var complete=await ValidateHistory(); + if(!complete)throw new InvalidOperationException("migration-history-incomplete"); + var seconds=timer.Elapsed.TotalSeconds; + return new { healthy = true, complete_history=complete, history=await HistoryStatus(), history_verification_seconds=seconds }; } if (op == "activated") { @@ -162,7 +172,9 @@ internal static class Program ["@previous"]=request["previous_deployment"]?.GetValue() is { } previous ? previous : DBNull.Value }) cmd.Parameters.AddWithValue(key,value); await cmd.ExecuteNonQueryAsync(); - return new { recorded = true }; + var record=await ReleaseRecord(deployment); + if(record is null)throw new InvalidOperationException("activation-record-missing"); + return record; } throw new InvalidOperationException("operation"); } @@ -206,6 +218,33 @@ internal static class Program } } + private static async Task ReleaseRecord(string? identifier=null) + { + if(await Scalar("SELECT OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U')") is DBNull)return null; + using var read=Command("SELECT TOP(1) DeploymentIdentifier,ReleaseIdentifier,ApplicationVersion,SourceCommit,PackageSha256,MigrationManifestSha256,ActivatedUtc,ActivationKind FROM dbo.ApplicationReleaseHistory WHERE (@id IS NULL OR DeploymentIdentifier=@id) ORDER BY ActivatedUtc DESC"); + read.Parameters.Add("@id",System.Data.SqlDbType.VarChar,100).Value=identifier is null?DBNull.Value:identifier; + using var reader=await read.ExecuteReaderAsync(); + if(!await reader.ReadAsync())return null; + return new JsonObject { ["recorded"]=true,["deployment_identifier"]=reader.GetString(0),["release_identifier"]=reader.GetString(1), + ["application_version"]=reader.GetString(2),["source_commit"]=reader.GetString(3),["package_sha256"]=reader.GetString(4), + ["manifest_sha256"]=reader.GetString(5),["activated_utc"]=DateTime.SpecifyKind(reader.GetDateTime(6),DateTimeKind.Utc).ToString("O"), + ["activation_kind"]=reader.GetString(7)}; + } + + private static async Task HistoryStatus() + { + var expected=manifest!["migrations"]!.AsArray().Count; + if(await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull) + return new {expected,recorded=0,baselined=0,executed=0}; + int recorded,baselineCount,executedCount; + using(var command=Command("SELECT COUNT(*),COALESCE(SUM(CASE WHEN RecordingKind='Baselined' THEN 1 ELSE 0 END),0),COALESCE(SUM(CASE WHEN RecordingKind='Executed' THEN 1 ELSE 0 END),0) FROM dbo.DatabaseMigrationHistory")) + using(var reader=await command.ExecuteReaderAsync()) + {await reader.ReadAsync();recorded=reader.GetInt32(0);baselineCount=reader.GetInt32(1);executedCount=reader.GetInt32(2);} + var latest=await ReleaseRecord(); + var releaseCount=await Scalar("IF OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U') IS NOT NULL SELECT COUNT(*) FROM dbo.ApplicationReleaseHistory ELSE SELECT 0"); + return new {expected,recorded,baselined=baselineCount,executed=executedCount,successful_release_count=Convert.ToInt32(releaseCount),latest_successful_release=latest}; + } + private static async Task ValidateHistory() { if (await Scalar("SELECT OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U')") is DBNull) @@ -290,6 +329,8 @@ internal static class Program insert.Parameters.AddWithValue("@evidence",baseline ? S(migration,"evidence") : DBNull.Value); await insert.ExecuteNonQueryAsync(); await transaction.CommitAsync(); + if(baseline)baselined++;else executed++; + committed.Add(identity); currentMigration=null; currentBatch=0; } diff --git a/Tools/Deployment/README.md b/Tools/Deployment/README.md index 28ab74c6..e742e4fe 100644 --- a/Tools/Deployment/README.md +++ b/Tools/Deployment/README.md @@ -44,3 +44,13 @@ On a disposable isolated clone only, a separately recorded short-lived entitleme fixture may enable that test. Remove it in finally, never change original entitlement rows, and compare all original business-column fingerprints afterwards. Do not disable the subscription trigger or use a Production database as the fixture. + + +Compressed transport and machine receipts are implemented in transport.py, +receipt.py and deploy.py. See Docs/Deployment/Transport-20261125.md for measured +qualification and installation status, and Production.md for the operational +protocol. deploy.py defaults to validate-only; --activate is an explicit separately +authorised action. Existing raw signed releases remain supported. New compression +and receipt operations require the matching qualified server tooling; do not send +a compressed bundle to an old dispatcher. No routine bespoke Markdown report is +required: report the JSON/text receipt summary and any exceptional failures. diff --git a/Tools/Deployment/activate.py b/Tools/Deployment/activate.py index 569776bd..598c54fe 100644 --- a/Tools/Deployment/activate.py +++ b/Tools/Deployment/activate.py @@ -14,10 +14,15 @@ import sys import tempfile import time import uuid +import math +import re +from contextlib import nullcontext +from receipt import Receipt, summary, sanitized from release import Refused, canonical, file_digest, keys, load, require, safe_name, verify_bundle CONFIG = Path('/etc/plotdirector-deployment/target.json') +RECEIPT_DIRECTORY = Path('/srv/plotdirector/deployment-receipts') SAFE_ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LANG': 'C.UTF-8', 'HOME': '/nonexistent', 'DOTNET_NOLOGO': '1'} @@ -58,6 +63,7 @@ class Worker: self.process = subprocess.Popen(['/usr/bin/dotnet', config['worker'], config['database_config']], env=SAFE_ENV, cwd='/', user=user.pw_uid, group=user.pw_gid, extra_groups=[], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + self.last_error = None self.read() def read(self): @@ -66,6 +72,13 @@ class Worker: line = self.process.stdout.readline(65537) require(bool(line) and len(line) <= 65536, 'Database worker unavailable') answer = json.loads(line) + if not answer.get('ok'): + # SQL workers emit codes, never exception text. Reject accidental secret-bearing diagnostics. + if not isinstance(answer.get('error'),str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_-]{0,80}',answer['error']): + answer={'ok':False,'error':'invalid-worker-error','migration':None,'batch':0} + if answer.get('migration') is not None and not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,199}',str(answer['migration'])): + answer['migration']=None + self.last_error = answer require(answer.get('ok'), 'Database operation refused: ' + str(answer.get('error', 'unknown')) + ' migration=' + str(answer.get('migration', 'none')) + ' batch=' + str(answer.get('batch', 0))) return answer.get('result', answer) @@ -161,7 +174,7 @@ def switch(root, target, deployment): os.close(fd) -def health(cfg, destination, manifest, worker): +def health(cfg, destination, manifest, worker, meter=None): require(command(['/usr/bin/systemctl', 'is-active', cfg['service']]) == 'active', 'Service inactive') for path in ('/', '/Account/Login'): for attempt in range(20): @@ -186,108 +199,173 @@ def health(cfg, destination, manifest, worker): and identity.get('sourceCommit') == manifest['source_commit'] and identity.get('database') == cfg['database'], 'Running application/database identity mismatch') require(identity.get('environment') == cfg['environment'], 'Running application environment mismatch') - worker.call('health') + with meter.phase('postactivation_verification') if meter else nullcontext(): + database = worker.call('health') + if meter and isinstance(database,dict) and 'history_verification_seconds' in database: + meter.component('migration_history_verification',database['history_verification_seconds'],'postactivation_verification') + application={k:identity[k] for k in ('healthy','version','sourceCommit','database','environment')} + return {'application':application,'database':database,'http_root':True,'http_login':True,'binary_identity':True} + + +def persist_receipt(cfg, meter): + directory=Path(cfg['root'])/'deployment-receipts' + protected(directory,directory=True) + gid=grp.getgrnam('plotdirector-deploy').gr_gid + require(directory.stat().st_gid==gid and not directory.stat().st_mode&0o007,'Unsafe receipt directory') + identifier=safe_name(meter.data['deployment_id']) + clean=sanitized(meter.data) + data=canonical(clean);require(len(data)<=1024**2,'Receipt exceeds safe size limit') + pending=directory/('.receipt-'+uuid.uuid4().hex) + with pending.open('xb') as stream:stream.write(data);stream.flush();os.fsync(stream.fileno()) + os.chown(pending,0,gid);pending.chmod(0o640) + os.replace(pending,directory/(identifier+'.json')) + pending=directory/('.summary-'+uuid.uuid4().hex) + with pending.open('xb') as stream:stream.write((summary(clean)+'\n').encode());stream.flush();os.fsync(stream.fileno()) + os.chown(pending,0,gid);pending.chmod(0o640);os.replace(pending,directory/(identifier+'.txt')) + + +def read_receipt(identifier): + require(os.geteuid()==0,'Restricted sudo invocation required') + identifier=safe_name(identifier) + directory=RECEIPT_DIRECTORY;protected(directory,directory=True) + path=directory/(identifier+'.json');protected(path,secret=True) + require(path.stat().st_size<=1024**2,'Oversized receipt') + value=load(path);require(value.get('format')==1 and value.get('deployment_id')==identifier,'Receipt identity mismatch') + print(canonical(value).decode(),end='') + + +def import_upload_metrics(source, work, meter): + try: + from release import snapshot + target=Path(work)/'upload-metrics.json' + snapshot(Path(source)/'transfer-metrics.json',target,16384) + data=load(target) + keys(data,('source','started_utc','completed_utc','bytes','seconds','mib_per_second')) + require(data['source']=='ssh-receiver-unprivileged','Unknown transfer provenance') + require(type(data['seconds']) in (int,float) and math.isfinite(data['seconds']) and 0= cfg['minimum_free_bytes'] + 4 * incoming_info.st_size, - 'Insufficient snapshot/extraction/installation space') - with tempfile.TemporaryDirectory(prefix='.deployment-', dir=str(root)) as work: - os.chmod(work, 0o750) - os.chown(work, 0, grp.getgrnam(cfg['migration_account']).gr_gid) - manifest, authorization, payload = verify_bundle(Path(cfg['inbox']) / package_id, work, cfg['public_key']) - require(manifest['release_id'] == package_id, 'Package identifier mismatch') - size = sum(x.stat().st_size for x in payload.rglob('*') if x.is_file()) - require(shutil.disk_usage(root).free >= cfg['minimum_free_bytes'] + 2 * size, 'Insufficient release/snapshot space') - for path in [payload, *payload.rglob('*')]: - os.chown(path, 0, grp.getgrnam(cfg['migration_account']).gr_gid) - path.chmod(0o750 if path.is_dir() else 0o640) - deployment = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '-' + uuid.uuid4().hex[:12] - evidence = Path(cfg['evidence']) / (deployment + '.jsonl') - def event(phase, **data): + cfg=configuration();root=Path(cfg['root']) + lock_path=root/'deployment.lock';protected(lock_path,secret=True) + lock_fd=os.open(lock_path,os.O_RDWR|os.O_NOFOLLOW) + try:fcntl.flock(lock_fd,fcntl.LOCK_EX|fcntl.LOCK_NB) + except BlockingIOError:raise Refused('Concurrent deployment') + source=Path(cfg['inbox'])/package_id + incoming=source/('package.tar.zst' if (source/'transport.json').exists() else 'package.tar') + info=incoming.lstat();require(stat.S_ISREG(info.st_mode) and info.st_nlink==1,'Unsafe incoming package') + require(shutil.disk_usage(root).free>=cfg['minimum_free_bytes']+4*info.st_size,'Insufficient snapshot/extraction/installation space') + with tempfile.TemporaryDirectory(prefix='.deployment-',dir=str(root)) as work: + os.chmod(work,0o750);os.chown(work,0,grp.getgrnam(cfg['migration_account']).gr_gid) + manifest,authorization,payload=verify_bundle(source,work,cfg['public_key'],meter=meter) + require(manifest['release_id']==package_id,'Package identifier mismatch') + meter.data['release']={'id':package_id,'version':manifest['version'],'source_commit':manifest['source_commit'], + 'package_sha256':authorization['package_sha256'],'manifest_sha256':authorization['manifest_sha256'], + 'application_sha256':manifest['application_sha256'],'dll_sha256':manifest['files']['app/PlotLine.dll']} + import_upload_metrics(source,work,meter) + size=sum(x.stat().st_size for x in payload.rglob('*') if x.is_file()) + require(shutil.disk_usage(root).free>=cfg['minimum_free_bytes']+2*size,'Insufficient release/snapshot space') + for path in [payload,*payload.rglob('*')]: + os.chown(path,0,grp.getgrnam(cfg['migration_account']).gr_gid);path.chmod(0o750 if path.is_dir() else 0o640) + evidence=Path(cfg['evidence'])/(deployment+'.jsonl') + meter.data['protected_evidence_reference']=str(evidence) + def event(phase,**data): with evidence.open('a') as stream: - stream.write(canonical({'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'deployment': deployment, 'release': package_id, 'phase': phase, **data}).decode()) - stream.flush() - os.fsync(stream.fileno()) - event('validated', package_sha256=authorization['package_sha256']) - worker = Worker(cfg) - beginning = worker.call('begin', package_root=str(payload), deployment_id=deployment, package_sha256=authorization['package_sha256']) - if rollback: - require(beginning.get('complete') is True, 'Rollback requires all migration history already present; SQL changes are forbidden') + stream.write(canonical({'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'deployment':deployment,'release':package_id,'phase':phase,**data}).decode());stream.flush();os.fsync(stream.fileno()) + event('validated',package_sha256=authorization['package_sha256']) + worker=Worker(cfg) + with meter.phase('database_state_verification'): + beginning=worker.call('begin',package_root=str(payload),deployment_id=deployment,package_sha256=authorization['package_sha256']) + meter.data['migration_history']=beginning + if 'history_verification_seconds' in beginning: + meter.component('migration_history_verification',beginning['history_verification_seconds'],'database_state_verification') + if rollback:require(beginning.get('complete') is True,'Rollback requires all migration history already present; SQL changes are forbidden') + active_file=root/'active-deployment.json' + marker=load(active_file) if active_file.exists() else None + if marker: + prior=safe_name(marker['release']);prior_manifest=root/'releases'/prior/'manifest.json' + meter.data['previous_release']={k:marker[k] for k in ('deployment','release','package_sha256') if k in marker} + if prior_manifest.exists(): + pm=load(prior_manifest);meter.data['previous_release'].update(version=pm['version'],source_commit=pm['source_commit']) + else:meter.data['previous_release']=None if validate: - event('validation-only') - print('VALIDATED ' + package_id + '; no backup, migrations or service operations performed') + event('validation-only');status='validated' + print('VALIDATED '+package_id+'; no backup, migrations or service operations performed') return - backup_name = 'PlotLine-predeploy-' + deployment + '.bak' - backup = Path(cfg['backup']) / backup_name - database_bytes = beginning.get('database_bytes') - require(isinstance(database_bytes, int) and database_bytes > 0, 'Database size unavailable for backup-space check') - require(shutil.disk_usage(cfg['backup']).free >= cfg['minimum_free_bytes'] + 2 * database_bytes, - 'Insufficient verified database-backup space') - require(not backup.exists() and not backup.is_symlink(), 'Backup path already exists') + backup=Path(cfg['backup'])/('PlotLine-predeploy-'+deployment+'.bak') + database_bytes=beginning.get('database_bytes') + require(isinstance(database_bytes,int) and database_bytes>0,'Database size unavailable for backup-space check') + require(shutil.disk_usage(cfg['backup']).free>=cfg['minimum_free_bytes']+2*database_bytes,'Insufficient verified database-backup space') + require(not backup.exists() and not backup.is_symlink(),'Backup path already exists') event('backup-start') - worker.call('backup', path=str(backup)) - require(backup.is_file() and backup.stat().st_size > 0, 'Verified backup file unavailable') - event('backup-verified', path=str(backup)) - worker.call('idle') - command(['/usr/bin/systemctl', 'stop', cfg['service']]) - stopped = True - require(command(['/usr/bin/systemctl', 'show', cfg['service'], '-p', 'ActiveState', '--value']) == 'inactive', 'Service did not stop') - worker.call('idle') - event('migration-start') - worker.call('migrate') + with meter.phase('database_backup'): + backup_result=worker.call('backup',path=str(backup)) + require(backup.is_file() and backup.stat().st_size>0,'Verified backup file unavailable') + meter.data['database_backup']={'path':str(backup),'verified':True,'options':['COPY_ONLY','CHECKSUM','VERIFYONLY']} + event('backup-verified',path=str(backup));worker.call('idle') + stop_started=time.monotonic() + with meter.phase('service_stop'): + command(['/usr/bin/systemctl','stop',cfg['service']]);stopped=True + require(command(['/usr/bin/systemctl','show',cfg['service'],'-p','ActiveState','--value'])=='inactive','Service did not stop') + stop_complete=time.monotonic() + worker.call('idle');event('migration-start') + with meter.phase('migration_execution'):migration=worker.call('migrate') + meter.data['migrations']=migration if isinstance(migration,dict) else {} event('migration-complete') - destination = root / 'releases' / package_id - install(payload, destination, cfg['runtime_account']) - # Successful release history contains the predecessor SUCCESS, not merely - # the symlink target left by a failed activation. - active_file = root / 'active-deployment.json' - previous = load(active_file)['deployment'] if active_file.exists() else None - event('activation-start', previous_deployment=previous) - switch(root, destination / 'app', deployment) - command(['/usr/bin/systemctl', 'start', cfg['service']]) - health(cfg, destination, manifest, worker) + destination=root/'releases'/package_id + with meter.phase('release_installation'):install(payload,destination,cfg['runtime_account']) + previous=marker['deployment'] if marker else None + event('activation-start',previous_deployment=previous) + with meter.phase('release_activation'):switch(root,destination/'app',deployment) + with meter.phase('service_start'):command(['/usr/bin/systemctl','start',cfg['service']]) + meter.data['availability']={'service_stop_to_start_seconds':time.monotonic()-stop_complete, + 'stop_request_to_start_command_complete_seconds':time.monotonic()-stop_started, + 'definition':'Monotonic intervals include stop/start commands; observed public outage measured separately on Atlas.'} + with meter.phase('application_health_readiness'):checks=health(cfg,destination,manifest,worker,meter) + meter.data['checks']=checks;meter.data['availability']['stop_request_to_health_ready_seconds']=time.monotonic()-stop_started + meter.data['availability']['confirmed_inactive_to_health_ready_seconds']=time.monotonic()-stop_complete event('health-passed') - worker.call('activated', evidence=str(evidence), kind='Rollback' if rollback else 'Deploy', previous_deployment=previous) - pending = root / ('.active-' + deployment) - pending.write_bytes(canonical({'deployment': deployment, 'release': package_id, 'package_sha256': authorization['package_sha256']})) - os.replace(pending, active_file) - event('successful') - stopped = False - print('ACTIVATED ' + package_id + ' deployment=' + deployment + ' evidence=' + str(evidence)) + with meter.phase('postactivation_verification'): + record=worker.call('activated',evidence=str(evidence),kind='Rollback' if rollback else 'Deploy',previous_deployment=previous) + pending=root/('.active-'+deployment);pending.write_bytes(canonical({'deployment':deployment,'release':package_id,'package_sha256':authorization['package_sha256']}));os.replace(pending,active_file) + meter.data['release_history']=record;meter.data['checks']['activation']=True + event('successful');stopped=False;status='activated' + print('ACTIVATED '+package_id+' deployment='+deployment+' evidence='+str(evidence)) except Exception as error: if stopped: - try: - command(['/usr/bin/systemctl', 'stop', cfg['service']]) - except Exception: - pass + try:command(['/usr/bin/systemctl','stop',cfg['service']]) + except Exception:pass + meter.data['failures'].append({'code':type(error).__name__,'service_stop_requested':stopped}) + if worker is not None and getattr(worker,'last_error',None): + safe=worker.last_error + meter.data['worker_failure']={k:safe[k] for k in ('error','migration','batch','executed','baselined') if k in safe} if evidence is not None: - with evidence.open('a') as stream: - stream.write(canonical({'phase': 'failed', 'error': str(error) if isinstance(error, Refused) else type(error).__name__, - 'service_stop_requested': stopped, 'recovery': 'Operator review required; no automatic database rollback.'}).decode()) + with evidence.open('a') as stream:stream.write(canonical({'phase':'failed','error':type(error).__name__,'service_stop_requested':stopped,'recovery':'Operator review required; no automatic database rollback.'}).decode()) raise finally: - if worker is not None: - worker.close() - os.close(lock_fd) + if worker is not None:worker.close() + if lock_fd is not None:os.close(lock_fd) + with meter.phase('receipt_generation'): + meter.finish(status) + persist_receipt(cfg or {'root':'/srv/plotdirector'},meter) + meter.finish(status);persist_receipt(cfg or {'root':'/srv/plotdirector'},meter) + print('RECEIPT '+deployment) + + +def public_error(error): + return sanitized(str(error)) if isinstance(error,Refused) else type(error).__name__ def main(): @@ -297,6 +375,8 @@ def main(): signal.signal(signal.SIGALRM, lambda *_: (_ for _ in ()).throw(Refused('Deployment timeout'))) signal.alarm(7200) args = sys.argv[1:] + if len(args)==2 and args[0]=='--receipt': + read_receipt(args[1]);return validate = len(args) == 2 and args[0] == '--validate' rollback = len(args) == 2 and args[0] == '--rollback' require(len(args) == 1 or validate or rollback, 'Usage: deploy-plotdirector [--validate|--rollback] ') @@ -307,5 +387,5 @@ if __name__ == '__main__': try: main() except Exception as error: - print('DEPLOYMENT REFUSED: ' + (str(error) if isinstance(error, Refused) else type(error).__name__)) + print('DEPLOYMENT REFUSED: ' + public_error(error)) sys.exit(1) diff --git a/Tools/Deployment/deploy-plotdirector b/Tools/Deployment/deploy-plotdirector index 940ca3f7..77e9130c 100644 --- a/Tools/Deployment/deploy-plotdirector +++ b/Tools/Deployment/deploy-plotdirector @@ -3,10 +3,10 @@ exec /usr/bin/env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin LANG=C.UTF-8 /usr/bin/python3 -I -c ' import sys sys.path.insert(0, "/usr/local/lib/plotdirector-deployment") -from activate import main, Refused +from activate import main, public_error try: main() except Exception as error: - print("DEPLOYMENT REFUSED: " + (str(error) if isinstance(error, Refused) else type(error).__name__)) + print("DEPLOYMENT REFUSED: " + public_error(error)) sys.exit(1) ' "$@" diff --git a/Tools/Deployment/deploy.py b/Tools/Deployment/deploy.py new file mode 100644 index 00000000..71bc9863 --- /dev/null +++ b/Tools/Deployment/deploy.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +"""Measured Atlas release pipeline. Defaults to validation only; no general SSH commands.""" +import argparse +from contextlib import nullcontext +import json +from pathlib import Path +import re +import subprocess +import threading +import time +import urllib.request +import urllib.error +import tempfile + +from receipt import Receipt, summary, write_local +from release import Refused, require, load, verify_bundle +from transfer import transfer, ssh + + +def remote(identity, operation, release, meter): + phase='production_validation' if operation=='validate' else 'remote_activation' + with meter.phase(phase): + p=subprocess.run(ssh(identity,operation+' '+release),capture_output=True,text=True,timeout=7200) + # No raw stderr/SQL/configuration is copied into public receipts. + return_code=p.returncode + identifier=re.search(r'^RECEIPT ([A-Za-z0-9][A-Za-z0-9_.-]{0,99})$',p.stdout,re.M) + require(identifier is not None,'Server did not return a sanitized receipt; compatible tooling required') + with meter.phase('receipt_retrieval'): + p=subprocess.run(ssh(identity,'receipt '+identifier[1]),capture_output=True,text=True,timeout=30) + require(p.returncode==0 and len(p.stdout.encode())<=1024**2,'Receipt retrieval failed') + data=json.loads(p.stdout) + require(data.get('format')==1 and data.get('deployment_id')==identifier[1],'Receipt identity mismatch') + if return_code!=0 or data.get('status')!=('validated' if operation=='validate' else 'activated'): + meter.data['failed_server_operation']=data + raise Refused('Restricted operation failed; sanitized server receipt retained') + return data + + +def public_acceptance(meter): + with meter.phase('public_acceptance'): + result={} + for name,url in [('plotdirector','https://plotdirector.com/'),('catherine','https://catherinelynwood.com/')]: + with urllib.request.urlopen(url,timeout=20) as response: + require(response.status==200,'Public HTTPS acceptance failed');response.read() + result[name]={'status':200,'tls_verified':True} + return result + + +def run(args): + meter=Receipt('atlas-pipeline');receipt_path=Path(args.receipt).resolve() + receipt_path.parent.mkdir(parents=True,exist_ok=True,mode=0o700) + require(not receipt_path.exists() and not receipt_path.is_symlink(),'Receipt destination already exists') + done=threading.Event();observations=[];poller=None;status='failed' + try: + if args.source: + from release import prepare + require(all(getattr(args,k,None) for k in ['plan','sql','evidence','output','release_id','signing_key','scope_base']), 'Complete release preparation arguments required') + preparation_meter=Receipt('atlas-preparation') + with meter.phase('release_preparation'): + try: + args.compression='zstd';prepare(args,meter=preparation_meter) + finally: + meter.data['preparation']=preparation_meter.data + bundle=Path(args.output).resolve() + # Import only known typed timing rows from this actual preparation. + meter.data['preparation']=preparation_meter.data + else:bundle=Path(args.bundle).resolve() + with tempfile.TemporaryDirectory(prefix='pd-pipeline-check-',dir=receipt_path.parent) as work: + manifest,authorization,_=verify_bundle(bundle,work,args.public_key,meter=meter) + release=manifest['release_id'] + meter.data['release']={'id':release,'source_commit':manifest['source_commit'],'version':manifest['version'], + 'package_sha256':authorization['package_sha256'],'application_sha256':manifest['application_sha256'], + 'dll_sha256':manifest['files']['app/PlotLine.dll']} + transfer(bundle,args.identity,meter=meter) + validated=remote(args.identity,'validate',release,meter) + require(validated['release']['package_sha256']==authorization['package_sha256'],'Server validated another package') + meter.data['server_validation']=validated + meter.data['previous_release']=validated.get('previous_release') + meter.data['migration_history']=validated.get('migration_history') + require(not args.activate or validated.get('migration_history',{}).get('complete') is True or args.allow_migrations, + 'Pending migration history requires an explicitly approved --allow-migrations run') + if args.activate: + def poll(): + while not done.is_set(): + start=time.monotonic() + try: + with urllib.request.urlopen('https://plotdirector.com/Account/Login',timeout=4) as response:ok=response.status==200;response.read() + except Exception:ok=False + observations.append((start,ok));done.wait(.5) + poller=threading.Thread(target=poll,daemon=True);poller.start() + try:activated=remote(args.identity,'activate',release,meter) + finally:done.set();poller.join(timeout=5) + require(activated['release']['package_sha256']==authorization['package_sha256'],'Server activated another package') + meter.data['server_activation']=activated + for key in ['deployment_id','release_history','migrations','database_backup','checks','availability','previous_release']: + if key in activated:meter.data[key]=activated[key] + failed=[i for i,x in enumerate(observations) if not x[1]] + if failed: + recovered=next((x[0] for x in observations[failed[-1]+1:] if x[1]),None) + meter.data['observed_public_outage']={'seconds':None if recovered is None else recovered-observations[failed[0]][0], + 'definition':'Measured failed HTTPS GET to next successful GET; 0.5s sampling plus request latency','recovery_observed':recovered is not None} + else:meter.data['observed_public_outage']={'seconds':None,'failed_samples':0,'definition':'No failed sample observed; zero downtime is not asserted'} + status='activated' + else:status='validated';meter.data['warnings'].append('Validation only; no activation, backup or migration performed') + if args.public_acceptance:meter.data['public_https']=public_acceptance(meter) + except Exception as error: + status='failed' + meter.data['failures'].append({'code':type(error).__name__,'recovery':'Review local receipt and protected server attempt evidence; no automatic retry/rollback'}) + raise + finally: + done.set() + if poller:poller.join(timeout=5) + with meter.phase('receipt_generation'): + meter.finish(status);write_local(receipt_path,meter.data) + meter.finish(status);write_local(receipt_path,meter.data) + print(summary(meter.data)) + return meter.data + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + group=parser.add_mutually_exclusive_group(required=True) + group.add_argument('--bundle');group.add_argument('--source') + for field in ['identity','public-key','receipt']:parser.add_argument('--'+field,required=True) + for field in ['plan','sql','evidence','output','release-id','signing-key','scope-base']:parser.add_argument('--'+field) + parser.add_argument('--activate',action='store_true');parser.add_argument('--allow-migrations',action='store_true') + parser.add_argument('--public-acceptance',action='store_true');args=parser.parse_args() + try:run(args) + except (Refused,ValueError,OSError,subprocess.SubprocessError):raise SystemExit('Deployment pipeline refused; sanitized receipt retained') + +if __name__=='__main__':main() diff --git a/Tools/Deployment/receipt.py b/Tools/Deployment/receipt.py new file mode 100644 index 00000000..9ab8b815 --- /dev/null +++ b/Tools/Deployment/receipt.py @@ -0,0 +1,114 @@ +"""Bounded, secret-free deployment receipts and monotonic phase accounting.""" +from contextlib import contextmanager +from datetime import datetime, timezone +import json +import os +import tempfile +import re +from pathlib import Path +import time + +FORMAT = 1 +PHASES = ('release_preparation','production_validation','remote_activation','receipt_retrieval','scope_verification','build','packaging_signing','compression','transfer','decompression', + 'package_validation','database_state_verification','migration_history_verification', + 'database_backup','migration_execution','service_stop','release_installation','release_activation', + 'service_start','application_health_readiness','postactivation_verification','public_acceptance','receipt_generation') + + +def utc(): + return datetime.now(timezone.utc).isoformat(timespec='milliseconds') + + +class Receipt: + def __init__(self, origin='web1'): + self.started = time.monotonic() + self.stack = [] + self.data = {'format':FORMAT,'origin':origin,'started_utc':utc(),'completed_utc':None, + 'status':'in-progress','phases':[],'warnings':[],'failures':[], + 'checks':{},'migrations':{'executed':None,'baselined':None}, + 'recovery':'No automatic database restore or application rollback. Review protected attempt evidence on failure.'} + + @contextmanager + def phase(self, name): + if name not in PHASES: + raise ValueError('Unknown measured phase') + row={'name':name,'started_utc':utc(),'parent':self.stack[-1]['name'] if self.stack else None} + start=time.monotonic(); state={'name':name,'children':0.0} + self.stack.append(state) + try: + yield + row['outcome']='passed' + except BaseException: + row['outcome']='failed' + raise + finally: + self.stack.pop(); elapsed=time.monotonic()-start + row.update(completed_utc=utc(),seconds=round(elapsed,6),exclusive_seconds=round(max(0,elapsed-state['children']),6)) + self.data['phases'].append(row) + if self.stack:self.stack[-1]['children']+=elapsed + + def component(self, name, seconds, parent): + """Import a measured child duration; do not invent cross-process timestamps.""" + import math + if name not in PHASES or type(seconds) not in (float,int) or not math.isfinite(seconds): + raise ValueError('Invalid measured component') + row=next((x for x in reversed(self.data['phases']) if x['name']==parent),None) + if row is None or not 0<=seconds<=row['seconds']+.001: + raise ValueError('Component lies outside its measured parent') + self.data['phases'].append({'name':name,'parent':parent,'seconds':round(seconds,6), + 'exclusive_seconds':round(seconds,6),'started_utc':None,'completed_utc':None, + 'clock':'SQL worker Stopwatch; measured duration, UTC endpoints unavailable','outcome':'passed'}) + row['exclusive_seconds']=round(max(0,row['exclusive_seconds']-seconds),6) + + def finish(self, status): + self.data['status']=status + self.data['completed_utc']=utc() + total=time.monotonic()-self.started + accounted=sum(x['seconds'] for x in self.data['phases'] if x['parent'] is None) + self.data['timing']={'total_seconds':round(total,6),'measured_top_level_seconds':round(accounted,6), + 'unattributed_seconds':round(max(0,total-accounted),6), + 'clock':'monotonic; UTC timestamps for correlation only'} + performed={x['name'] for x in self.data['phases']} + for key in ('preparation','server_validation','server_activation','failed_server_operation'): + nested=self.data.get(key,{}) + performed.update(x['name'] for x in nested.get('phases',[])) + self.data['unperformed_phases']=[n for n in PHASES if n not in performed] + return self.data + + +def sanitized(value): + """Defence in depth; callers still collect only explicitly selected facts.""" + if isinstance(value,dict): + return {k:sanitized(v) for k,v in value.items() if not re.search( + r'password|connection.?string|private.?key|api.?key|access.?token|refresh.?token|credential',k,re.I)} + if isinstance(value,list):return [sanitized(x) for x in value] + if isinstance(value,str) and re.search(r'(?:Password|Pwd|Server|Data Source|User ID|Initial Catalog)\s*=|Bearer\s+|-----BEGIN.*PRIVATE KEY|sk_(?:live|test)_|sk-proj-|whsec_',value,re.I): + return '[redacted]' + return value + + +def summary(data): + """Render only known safe fields; never include diagnostics/configuration blobs.""" + data=sanitized(data) + seconds=data.get('timing',{}).get('total_seconds',0) + release=data.get('release',{}) + public=data.get('public_https') + public_result='passed' if public and all(x.get('status')==200 and x.get('tls_verified') for x in public.values()) else 'not-performed' + if any(x['name']=='public_acceptance' and x.get('outcome')=='failed' for x in data.get('phases',[])):public_result='failed' + return ('{status}: {release} v{version} source={source} total={seconds:.2f}s; ' + 'backup={backup}; migrations-executed={migrations}; public-https={public}; receipt={receipt}').format( + status=data.get('status','unknown'),release=release.get('id','unavailable'),version=release.get('version','unknown'), + source=release.get('source_commit','unavailable')[:12],seconds=seconds, + backup=data.get('database_backup',{}).get('verified','not-performed'), + migrations=data.get('migrations',{}).get('executed','not-performed'),public=public_result, + receipt=data.get('deployment_id','local')) + + + +def write_local(path, data): + path=Path(path) + data=sanitized(data) + for target,body in [(path,json.dumps(data,indent=2)+'\n'),(path.with_suffix('.txt'),summary(data)+'\n')]: + with tempfile.NamedTemporaryFile(mode='w',dir=target.parent,prefix='.receipt-',delete=False) as stream: + temporary=Path(stream.name);stream.write(body);stream.flush();os.fsync(stream.fileno()) + temporary.chmod(0o600);os.replace(temporary,target) diff --git a/Tools/Deployment/release.py b/Tools/Deployment/release.py index f94751a1..b43a5e35 100644 --- a/Tools/Deployment/release.py +++ b/Tools/Deployment/release.py @@ -10,6 +10,11 @@ import stat import subprocess import tarfile import tempfile +import sys +from contextlib import nullcontext + +if __name__ == '__main__': + sys.modules.setdefault('release', sys.modules[__name__]) LIMIT_BYTES = 4 * 1024**3 LIMIT_FILES = 100000 @@ -218,33 +223,67 @@ def snapshot(path, destination, max_bytes): os.close(fd) -def verify_bundle(source, work, public_key): +def verify_bundle(source, work, public_key, meter=None): source, work = Path(source), Path(work) - for name, limit in (('authorization.json', 16384), ('authorization.sig', 16384), ('package.tar', LIMIT_BYTES)): - snapshot(source / name, work / name, limit) - result = subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', str(public_key), '-rawin', + phase = meter.phase if meter else lambda name: nullcontext() + with phase('package_validation'): + for name in ('authorization.json', 'authorization.sig'): + snapshot(source / name, work / name, 16384) + result = subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', str(public_key), '-rawin', '-in', str(work / 'authorization.json'), '-sigfile', str(work / 'authorization.sig')], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - require(result.returncode == 0, 'Release signature invalid') - authorization = load(work / 'authorization.json') - keys(authorization, ('format', 'release_id', 'source_commit', 'package_sha256', 'manifest_sha256')) - require(authorization['format'] == 1, 'Invalid authorization format') - safe_name(authorization['release_id']) - sha(authorization['package_sha256']) - sha(authorization['manifest_sha256']) - require(file_digest(work / 'package.tar') == authorization['package_sha256'], 'Package checksum mismatch') - payload = work / 'payload' - payload.mkdir(mode=0o700) - manifest = extract(work / 'package.tar', payload) - require(file_digest(payload / 'manifest.json') == authorization['manifest_sha256'], 'Manifest checksum mismatch') - require(manifest['release_id'] == authorization['release_id'] and manifest['source_commit'] == authorization['source_commit'], 'Authorization identity mismatch') + require(result.returncode == 0, 'Release signature invalid') + authorization = load(work / 'authorization.json') + keys(authorization, ('format', 'release_id', 'source_commit', 'package_sha256', 'manifest_sha256')) + require(authorization['format'] == 1, 'Invalid authorization format') + safe_name(authorization['release_id']) + sha(authorization['package_sha256']) + sha(authorization['manifest_sha256']) + compressed = (source / 'transport.json').exists() or (source / 'package.tar.zst').exists() + if compressed: + from transport import envelope + require(not (source / 'package.tar').exists(), 'Ambiguous raw/compressed bundle') + t = envelope(source, work, public_key) + require(t['original_sha256'] == authorization['package_sha256'] and + t['release_id'] == authorization['release_id'] and + t['source_commit'] == authorization['source_commit'], 'Transport identity mismatch') + else: + snapshot(source / 'package.tar', work / 'package.tar', LIMIT_BYTES) + size = (work / 'package.tar').stat().st_size + t = {'method':'none','original_bytes':size,'transferred_bytes':size, + 'original_sha256':authorization['package_sha256'],'transferred_sha256':authorization['package_sha256']} + if meter: + meter.data['transport'] = {k:t[k] for k in ('method','original_bytes','transferred_bytes','original_sha256','transferred_sha256')} + meter.data['transport']['compression_ratio'] = round(t['transferred_bytes']/t['original_bytes'],6) + if compressed: + meter.data['transport']['compression_seconds_atlas'] = t['compression_seconds'] + meter.data['transport']['settings'] = {'level':t['level'],'threads':t['threads']} + if compressed: + from transport import decompress + with phase('decompression'): + decompress(work,t) + with phase('package_validation'): + require(file_digest(work / 'package.tar') == authorization['package_sha256'], 'Package checksum mismatch') + payload = work / 'payload' + payload.mkdir(mode=0o700) + manifest = extract(work / 'package.tar', payload) + require(file_digest(payload / 'manifest.json') == authorization['manifest_sha256'], 'Manifest checksum mismatch') + require(manifest['release_id'] == authorization['release_id'] and manifest['source_commit'] == authorization['source_commit'], 'Authorization identity mismatch') return manifest, authorization, payload -def prepare(args): +def prepare(args, meter=None): + from receipt import Receipt, write_local + meter = meter or Receipt('atlas-preparation') repo = Path(args.source).resolve() - commit = subprocess.check_output(['git', '-C', str(repo), 'rev-parse', 'HEAD'], text=True).strip() - require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Source must be a clean Git commit') + with meter.phase('scope_verification'): + commit = subprocess.check_output(['git', '-C', str(repo), 'rev-parse', 'HEAD'], text=True).strip() + require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Source must be a clean Git commit') + if getattr(args, 'scope_base', None): + base = subprocess.check_output(['git','-C',str(repo),'rev-parse','--verify','--end-of-options',args.scope_base+'^{commit}'],text=True).strip() + require(COMMIT.fullmatch(base), 'Invalid scope baseline') + meter.data['scope'] = {'base':base,'source':commit,'changed_paths':subprocess.check_output( + ['git','-C',str(repo),'diff','--name-only',base,commit],text=True).splitlines()} require(COMMIT.fullmatch(commit), 'Invalid source commit') plan = load(args.plan) # The plan is reviewed data; paths are only read on Atlas, never trusted as remote targets. @@ -255,64 +294,80 @@ def prepare(args): with tempfile.TemporaryDirectory(prefix='pd-release-', dir=str(output.parent)) as directory: work = Path(directory) publish = work / 'publish' - subprocess.run(['dotnet', 'publish', str(repo / 'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), + with meter.phase('build'): + subprocess.run(['dotnet', 'publish', str(repo / 'PlotLine/PlotLine.csproj'), '-c', 'Release', '-o', str(publish), '-p:ContinuousIntegrationBuild=true', '-p:SourceRevisionId=' + commit], check=True, stdout=(output / 'publish.log').open('w'), stderr=subprocess.STDOUT) - require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Build changed tracked source') - files = {} - sources = {} - for path in sorted(publish.rglob('*')): - require(not path.is_symlink(), 'Publish contains symlink') - if not path.is_file(): - continue - rel = path.relative_to(publish) - if any(p.startswith('.') or p in ('App_Data', 'uploads', 'logs', 'Logs') for p in rel.parts): - continue - if (path.name.startswith('appsettings') and path.suffix == '.json') or path.name in ('web.config', 'dotnet-tools.json'): - continue - name = 'app/' + rel.as_posix() - files[name] = file_digest(path) - sources[name] = path - for migration in plan['migrations']: - filename = str(safe_path(migration['file'])) - require('/' not in filename, 'Invalid SQL source name') - # Historical non-numeric release SQL may be staged separately in the reviewed SQL input directory. - path = Path(args.sql) / filename - require(path.is_file() and not path.is_symlink() and file_digest(path) == migration['sha256'], 'SQL source differs from reviewed plan') - name = 'sql/' + filename - files[name] = migration['sha256'] - sources[name] = path - for path in sorted(Path(args.evidence).rglob('*')): - require(not path.is_symlink(), 'Evidence symlink') - if path.is_file(): - name = 'evidence/' + path.relative_to(args.evidence).as_posix() - safe_path(name) + with meter.phase('packaging_signing'): + require(not subprocess.check_output(['git', '-C', str(repo), 'status', '--porcelain'], text=True).strip(), 'Build changed tracked source') + files = {} + sources = {} + for path in sorted(publish.rglob('*')): + require(not path.is_symlink(), 'Publish contains symlink') + if not path.is_file(): + continue + rel = path.relative_to(publish) + if any(p.startswith('.') or p in ('App_Data', 'uploads', 'logs', 'Logs') for p in rel.parts): + continue + if (path.name.startswith('appsettings') and path.suffix == '.json') or path.name in ('web.config', 'dotnet-tools.json'): + continue + name = 'app/' + rel.as_posix() files[name] = file_digest(path) sources[name] = path - deps = load(publish / 'PlotLine.deps.json') - versions = [x[9:] for x in deps['libraries'] if x.startswith('PlotLine/')] - require(len(versions) == 1, 'Application identity unavailable') - manifest = {'format': 1, 'release_id': safe_name(args.release_id), 'source_commit': commit, 'version': versions[0], - 'files': files, 'application_sha256': digest(canonical({k:v for k,v in files.items() if k.startswith('app/')})), - 'health': ['http-root', 'http-login', 'http-deployment-identity', 'database-postconditions', 'binary-identity'], **plan} - validate_manifest(manifest) - qualification_identity(manifest, load(Path(args.evidence) / PurePosixPath(plan['qualification']['evidence']).relative_to('evidence'))) - manifest_bytes = canonical(manifest) - (work / 'manifest.json').write_bytes(manifest_bytes) - sources['manifest.json'] = work / 'manifest.json' - with tarfile.open(output / 'package.tar', 'w', format=tarfile.USTAR_FORMAT) as tar: - for name, path in sorted(sources.items()): - entry = tarfile.TarInfo(name) - entry.size = path.stat().st_size - entry.mode = 0o644 - with path.open('rb') as stream: - tar.addfile(entry, stream) - authorization = {'format': 1, 'release_id': args.release_id, 'source_commit': commit, - 'package_sha256': file_digest(output / 'package.tar'), 'manifest_sha256': digest(manifest_bytes)} - (output / 'authorization.json').write_bytes(canonical(authorization)) - subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-sign', '-inkey', args.signing_key, '-rawin', - '-in', str(output / 'authorization.json'), '-out', str(output / 'authorization.sig')], check=True, - stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for migration in plan['migrations']: + filename = str(safe_path(migration['file'])) + require('/' not in filename, 'Invalid SQL source name') + # Historical non-numeric release SQL may be staged separately in the reviewed SQL input directory. + path = Path(args.sql) / filename + require(path.is_file() and not path.is_symlink() and file_digest(path) == migration['sha256'], 'SQL source differs from reviewed plan') + name = 'sql/' + filename + files[name] = migration['sha256'] + sources[name] = path + for path in sorted(Path(args.evidence).rglob('*')): + require(not path.is_symlink(), 'Evidence symlink') + if path.is_file(): + name = 'evidence/' + path.relative_to(args.evidence).as_posix() + safe_path(name) + files[name] = file_digest(path) + sources[name] = path + deps = load(publish / 'PlotLine.deps.json') + versions = [x[9:] for x in deps['libraries'] if x.startswith('PlotLine/')] + require(len(versions) == 1, 'Application identity unavailable') + manifest = {'format': 1, 'release_id': safe_name(args.release_id), 'source_commit': commit, 'version': versions[0], + 'files': files, 'application_sha256': digest(canonical({k:v for k,v in files.items() if k.startswith('app/')})), + 'health': ['http-root', 'http-login', 'http-deployment-identity', 'database-postconditions', 'binary-identity'], **plan} + validate_manifest(manifest) + qualification_identity(manifest, load(Path(args.evidence) / PurePosixPath(plan['qualification']['evidence']).relative_to('evidence'))) + manifest_bytes = canonical(manifest) + (work / 'manifest.json').write_bytes(manifest_bytes) + sources['manifest.json'] = work / 'manifest.json' + with tarfile.open(output / 'package.tar', 'w', format=tarfile.USTAR_FORMAT) as tar: + for name, path in sorted(sources.items()): + entry = tarfile.TarInfo(name) + entry.size = path.stat().st_size + entry.mode = 0o644 + with path.open('rb') as stream: + tar.addfile(entry, stream) + authorization = {'format': 1, 'release_id': args.release_id, 'source_commit': commit, + 'package_sha256': file_digest(output / 'package.tar'), 'manifest_sha256': digest(manifest_bytes)} + (output / 'authorization.json').write_bytes(canonical(authorization)) + subprocess.run(['/usr/bin/openssl', 'pkeyutl', '-sign', '-inkey', args.signing_key, '-rawin', + '-in', str(output / 'authorization.json'), '-out', str(output / 'authorization.sig')], check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + meter.data['release'] = {'id':args.release_id,'source_commit':commit,'version':manifest['version'], + 'package_sha256':authorization['package_sha256'],'application_sha256':manifest['application_sha256']} + if getattr(args, 'compression', 'none') == 'zstd': + from transport import compress_bundle + with meter.phase('compression'): + transport = compress_bundle(output,work/'transport',args.signing_key,None,verified=True) + for name in ('transport.json','transport.sig','package.tar.zst'): + (work/'transport'/name).rename(output/name) + (output/'package.tar').unlink() # Only this operation's newly built temporary tar. + meter.data['transport'] = transport + with meter.phase('receipt_generation'): + meter.finish('prepared') + write_local(output/'preparation-receipt.json',meter.data) + meter.finish('prepared');write_local(output/'preparation-receipt.json',meter.data) print(json.dumps(authorization, sort_keys=True)) @@ -322,6 +377,10 @@ def main(): p = sub.add_parser('prepare') for field in ('source', 'plan', 'sql', 'evidence', 'output', 'release-id', 'signing-key'): p.add_argument('--' + field, required=True) + p.add_argument('--compression',choices=('zstd','none'),default='zstd') + p.add_argument('--scope-base') + c = sub.add_parser('compress',help='Wrap an unchanged existing signed tar; no application build') + for field in ('bundle','output','signing-key','public-key'):c.add_argument('--'+field,required=True) v = sub.add_parser('verify') v.add_argument('bundle') v.add_argument('--public-key', required=True) @@ -330,6 +389,9 @@ def main(): try: if args.command == 'prepare': prepare(args) + elif args.command == 'compress': + from transport import compress_bundle + print(json.dumps(compress_bundle(args.bundle,args.output,args.signing_key,args.public_key),sort_keys=True)) else: with tempfile.TemporaryDirectory(prefix='pd-verify-') as work: m, a, _ = verify_bundle(Path(args.bundle).resolve(), work, args.public_key) diff --git a/Tools/Deployment/ssh_dispatch.py b/Tools/Deployment/ssh_dispatch.py index d08851d7..dc40c538 100644 --- a/Tools/Deployment/ssh_dispatch.py +++ b/Tools/Deployment/ssh_dispatch.py @@ -11,6 +11,9 @@ import resource import signal import shutil import stat +import time +import json +from datetime import datetime, timezone INBOX=Path('/srv/plotdirector/incoming') LIMIT=4*1024**3 @@ -22,7 +25,7 @@ def main(): os.umask(0o077) # sshd ForceCommand passes the requested text as data, never to a shell here. original=os.environ.get('SSH_ORIGINAL_COMMAND','') - match=re.fullmatch(r'(upload|validate|activate|rollback) ([A-Za-z0-9][A-Za-z0-9_.-]{0,99})',original) + match=re.fullmatch(r'(upload|validate|activate|rollback|receipt) ([A-Za-z0-9][A-Za-z0-9_.-]{0,99})',original) if not match or match[2] in ('.','..'): raise ValueError('Unsupported deployment operation') operation,release=match.groups() @@ -30,6 +33,7 @@ def main(): args=['/usr/bin/sudo','-n','/usr/local/sbin/deploy-plotdirector'] if operation=='validate':args.append('--validate') if operation=='rollback':args.append('--rollback') + if operation=='receipt':args.append('--receipt') args.append(release) raise SystemExit(subprocess.run(args,env={'PATH':'/usr/sbin:/usr/bin:/sbin:/bin','LANG':'C.UTF-8'},cwd='/').returncode) # These limits apply only to unprivileged transfer, never to the activation @@ -46,24 +50,30 @@ def main(): if shutil.disk_usage(INBOX).freeLIMIT+32768:raise ValueError('Transfer size exceeded') + if total>LIMIT+65536:raise ValueError('Transfer size exceeded') with tar.extractfile(member) as source,(destination/member.name).open('xb') as target: while block:=source.read(1024**2): if shutil.disk_usage(INBOX).free=1024**3+3*t['original_bytes'],'Insufficient decompression/extraction/installation space') + return t + + +def decompress(work, t): + """Bound output, decoder memory, CPU and wall time; never invoke a shell.""" + import resource + import signal + def limits(): + resource.setrlimit(resource.RLIMIT_FSIZE,(t['original_bytes'],t['original_bytes'])) + resource.setrlimit(resource.RLIMIT_CPU,(120,120)) + signal.alarm(120) + output=work/'package.tar' + try: + with output.open('xb') as stream: + p=subprocess.run(['/usr/bin/zstd','--quiet','--decompress','--stdout',f'--memory={MAX_WINDOW_MIB}MB','--',str(work/'package.tar.zst')], + stdout=stream,stderr=subprocess.DEVNULL,timeout=125,preexec_fn=limits) + require(p.returncode==0 and output.stat().st_size==t['original_bytes'],'Decompression failed or size mismatch') + require(file_digest(output)==t['original_sha256'],'Reconstructed package checksum mismatch') + except BaseException: + output.unlink(missing_ok=True) + raise + + +def compress_bundle(source, output, signing_key, public_key, *, level=6, threads=4, meter=None, verified=False): + source,output=Path(source).resolve(),Path(output).resolve() + require(not output.exists(),'Transport destination already exists') + require(level in (1,3,6) and 1<=threads<=8,'Unsupported compression settings') + if not verified: + import tempfile + from release import verify_bundle + with tempfile.TemporaryDirectory(prefix='pd-source-check-',dir=output.parent) as directory: + verify_bundle(source,Path(directory),public_key) + output.mkdir(mode=0o700) + for name in ['authorization.json','authorization.sig']: + snapshot(source/name,output/name,16384) + a=load(output/'authorization.json');require(file_digest(source/'package.tar')==a['package_sha256'],'Original signed package differs') + start=time.monotonic() + with (output/'package.tar.zst').open('xb') as stream: + p=subprocess.run(['/usr/bin/zstd','--quiet',f'-{level}',f'-T{threads}','--check','--stdout','--',str(source/'package.tar')],stdout=stream,stderr=subprocess.DEVNULL,timeout=180) + require(p.returncode==0,'Compression failed') + elapsed=time.monotonic()-start + size=(source/'package.tar').stat().st_size + require(0