Qualify restricted runtime permissions and enforce runtime deployment health
This commit is contained in:
parent
05a689c202
commit
190c074d52
@ -16,7 +16,7 @@ application checks, authenticated browser acceptance and provenance preservation
|
||||
|
||||
Implementation is on an isolated worktree/branch so the pre-existing untracked
|
||||
canonical-manuscript assessment and Context workspace audit are preserved. The
|
||||
qualified candidate must include this phase's tooling, migrations 318/319 and
|
||||
qualified candidate must include this phase's tooling, migrations 318/319/321/322 and
|
||||
deployment-only application changes, built from its own clean commit.
|
||||
|
||||
## Independently verified web1 inventory
|
||||
@ -105,8 +105,7 @@ Important ordering/classification decisions:
|
||||
contains a known syntax error. Their files are preserved, never rewritten.
|
||||
- 286 refreshes Development reset procedures and is inapplicable to Production.
|
||||
Old reset definitions remain untouched; no reset procedure is executed.
|
||||
- 318 bootstraps history before recording historical baselines; 319 supplies the
|
||||
local application's stored-procedure health probe. Neither changes business rows.
|
||||
- 318 bootstraps history; 319 supplies local SQL health and 322 verifies the actual runtime permissions. Standalone 321 supplies the scoped runtime role, a bounded owner-context restore operation, and effective permission assertions. Isolated prototype 320 is retained but superseded because its DENY CONTROL also denied required EXECUTE/metadata. None changes business rows.
|
||||
- SQL performance/inline-SQL improvements are carried by 283–285, 287–289 and later
|
||||
included migrations. No blanket index maintenance or speculative tuning is added.
|
||||
|
||||
@ -158,3 +157,5 @@ Actual web1 login permissions, its initial service, certificate, public HTTPS,
|
||||
Catherine coexistence after later configuration changes, physical Windows Word
|
||||
behaviour and real-cookie continuity remain deployment/cutover checks. Production
|
||||
configuration, databases, files, services, firewall and DNS remain unchanged.
|
||||
|
||||
Development adoption adds the same history mechanism after a verified backup and an isolated clone rehearsal. Historical entries are final-state baselines, not invented original executions. The installed f3c3683b application is preserved; successful historical activation rows are not fabricated. Runtime permission deprivileging passed the actual export/restore round-trip (rolled back) and was adopted atomically. Development remains active at PID 7065 with its original f3c3683b DLL; local/public GETs returned 200, and runtime SQL health reports ledger-ready/restricted. No historical successful-activation row was fabricated.
|
||||
|
||||
@ -78,7 +78,7 @@ Private qualification artifacts stay outside Git, under restricted Atlas storage
|
||||
## Migration and release history
|
||||
|
||||
Migration 318 introduces `dbo.DatabaseMigrationHistory` and
|
||||
`dbo.ApplicationReleaseHistory`. There is no administration UI.
|
||||
`dbo.ApplicationReleaseHistory`. Migration 319 adds the local SQL health probe; 322 makes the actual runtime identity/permissions a health gate. Standalone migration 321 defines the runtime permission contract; isolated predecessor 320 is superseded and is not deployed to a new environment. There is no administration UI.
|
||||
|
||||
- Identity is a unique script identity, including historical non-numeric scripts.
|
||||
Filenames, SHA-256, current recorded UTC, deployment ID and execution duration
|
||||
@ -116,7 +116,7 @@ checking the service, resolved `current` symlink, installed hashes, root-owned
|
||||
SQL recording and the filesystem marker requires operator reconciliation.
|
||||
|
||||
The same manifest, history schema, database worker and qualification rules apply
|
||||
to Development and Test. A different environment gets its own explicit schema
|
||||
to Development and Test. Development has adopted 318/319/321/322 and the restricted runtime role, with its existing application process preserved. A different environment gets its own explicit schema
|
||||
baseline, SQL identity and protected target configuration; never copy a production
|
||||
connection string. Adoption in Development must back up/verify its own database,
|
||||
check active work and baseline its actual current state. Do not run the legacy
|
||||
@ -148,7 +148,7 @@ with no traversal, duplicate paths, links, special files or extra content.
|
||||
|
||||
Activation reserves space, creates a unique COPY_ONLY/CHECKSUM backup, executes
|
||||
RESTORE VERIFYONLY before stopping the service, rechecks active work, stops and
|
||||
requires inactive state, then runs SQL. It installs a new root-owned release and
|
||||
requires inactive state, then runs SQL. It reconciles the fixed runtime permission policy (not a manifest hook) and installs a new root-owned release and
|
||||
atomically replaces `current`. It starts the service and checks local root/login
|
||||
HTTP, binary identity and database postconditions before recording success.
|
||||
|
||||
@ -189,6 +189,7 @@ Catherine's service, virtual host, certificate, data and database unchanged.
|
||||
| `/srv/plotdirector/incoming` | root:plotdirector-deploy | 0730 |
|
||||
| `/srv/plotdirector/deployment-evidence` | root:root | 0700 |
|
||||
| `/srv/plotdirector/deployment.lock` (empty regular file) | root:root | 0600 |
|
||||
| `/srv/plotdirector/incoming-upload.lock` (empty regular file) | root:plotdirector-deploy | 0660 |
|
||||
| `/srv/plotdirector/shared/{uploads,logs}` | plotdirector:plotdirector | 0750 |
|
||||
| `/srv/plotdirector/shared/.aspnet/DataProtection-Keys` | plotdirector:plotdirector | 0700 |
|
||||
| `/etc/plotdirector` | root:plotdirector | 0750 |
|
||||
@ -216,8 +217,8 @@ Catherine's service, virtual host, certificate, data and database unchanged.
|
||||
Use a secure prompt/secret manager; never put its connection string in commands,
|
||||
reports, Git or a package.
|
||||
6. A SQL administrator must create/reconcile server logins and restored user SIDs.
|
||||
Runtime login: PlotLine-only user, required EXECUTE on reviewed application
|
||||
procedures, metadata visibility on the two history tables for the fixed health probe, no server role, no db_owner or direct migration/history-write rights.
|
||||
Runtime login: PlotLine-only user in `PlotDirectorRuntime`, no server role or db_owner. The role permits business DML and procedure execution; explicit denials protect migration/release history and the permission-policy procedure. The login receives no direct table/schema DDL or database-backup permission. The reviewed project-restore procedure alone uses owner context for its bounded restore operations, with TRUSTWORTHY and database/server cross-database chaining disabled. Validate these flags before migration. The history role is verified using a non-authenticatable database probe principal.
|
||||
After 321, map the runtime user to `PlotDirectorRuntime` and remove legacy db_owner membership; verify database ownership/server roles separately. Do not reduce privileges on an existing environment until the actual export/restore path has passed in an isolated clone.
|
||||
Migration login: db_owner **only in PlotLine** for reviewed DDL/backup work;
|
||||
direct CREATE ANY DATABASE permission is needed by SQL Server for VERIFYONLY ([Microsoft permission reference](https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-verifyonly-transact-sql?view=sql-server-ver17)).
|
||||
Do not use dbcreator (which grants broader powers), sysadmin, the hourly backup
|
||||
@ -228,7 +229,7 @@ Catherine's service, virtual host, certificate, data and database unchanged.
|
||||
7. Recover uploads and keys separately, validating archive paths/link types before
|
||||
copying, preserving originals and checking file hashes. Configure absolute
|
||||
`Storage__UploadsRoot` and `DataProtection__KeysPath` to shared directories.
|
||||
Provision SMTP/Stripe/OpenAI settings and other qualified-build settings outside
|
||||
Explicitly provision `Features__ParagraphManuscripts=true`, the production `Site__PublicBaseUrl`, the intended worker/indexing flags and allowed-host/admin settings; these must not silently inherit the historical release defaults. Provision SMTP/Stripe/OpenAI settings and other qualified-build settings outside
|
||||
releases. The recovered configuration archive does not contain appsettings.json;
|
||||
reconcile the old effective settings explicitly, including Site/Admin and feature
|
||||
flags, rather than assuming environment-only recovery is complete.
|
||||
|
||||
@ -14,7 +14,7 @@
|
||||
"original_business_rows": 139554,
|
||||
"original_business_fingerprint_artifact_sha256": "759c6d23b59ac17d4447d33bf692029b88d180f20e4abcb3d4fe795b54def450",
|
||||
"historical_baseline_entries": 210,
|
||||
"executed_steps_in_plan": 108,
|
||||
"executed_steps_in_plan": 110,
|
||||
"ordering_exception": "253 -> 255 -> 254 -> 256; Docs/Geography/GeographicalPositioning.md",
|
||||
"omitted_migrations": [
|
||||
{
|
||||
@ -40,8 +40,14 @@
|
||||
"sha256": "947d276060e33a8a07c8e6413d97c36ce6b41540a80efb14386e16015108e21f",
|
||||
"reason": "Superseded by standalone migration 304, which explicitly replaces partial 301 and failed 302; 303 is the intermediate projection repair covered by 304.",
|
||||
"evidence": "evidence/baseline.json"
|
||||
},
|
||||
{
|
||||
"id": "320_DeploymentRuntimePermissions",
|
||||
"sha256": "be2abc358df50c44ee61ff22e25e8a88aff7f3b5cf07435bd7f6363fb4425ac7",
|
||||
"reason": "Superseded isolated permission prototype: DENY CONTROL also denied required runtime EXECUTE and metadata. Standalone 321 supplies corrected denials and an effective-role assertion before commit. Never deploy 320 to a new environment.",
|
||||
"evidence": "evidence/baseline.json"
|
||||
}
|
||||
],
|
||||
"unresolved": "No unresolved module-definition discrepancy after documented patch, removal and SSMS-support classification. Historical per-script execution remains unknown; baselines represent verified current final state.",
|
||||
"resulting_schema_sha256": "6d26db0814ae38254957a5b27b44591e959e0408cab98e6701b25cfee7827fe1"
|
||||
"resulting_schema_sha256": "b17db2bbdc583cb7bd3c856fb4db5cf6fc470e87fbaee5dc1dbbe99b6878beb7"
|
||||
}
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"starting_schema_sha256": "1eaa17d39bfdc2542743d6e911659141466f0bdf4efbeb62fb76b958ddd03c21",
|
||||
"resulting_schema_sha256": "6d26db0814ae38254957a5b27b44591e959e0408cab98e6701b25cfee7827fe1",
|
||||
"resulting_schema_sha256": "b17db2bbdc583cb7bd3c856fb4db5cf6fc470e87fbaee5dc1dbbe99b6878beb7",
|
||||
"migrations": [
|
||||
{
|
||||
"id": "318_DeploymentHistory",
|
||||
@ -14123,6 +14123,52 @@
|
||||
"type": "P"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "321_DeploymentRuntimePermissionContract",
|
||||
"file": "321_DeploymentRuntimePermissionContract.sql",
|
||||
"sha256": "9ac9f6437f78e90b1ad38a5dfcf9c317889d8fa72ee77881e25b79dd173ff43d",
|
||||
"requires": [
|
||||
"319_DeploymentHealth"
|
||||
],
|
||||
"mode": "execute",
|
||||
"prerequisites": [
|
||||
{
|
||||
"kind": "object",
|
||||
"name": "dbo.ProjectRestore_ApplyFromJson",
|
||||
"type": "P"
|
||||
}
|
||||
],
|
||||
"postconditions": [
|
||||
{
|
||||
"kind": "object",
|
||||
"name": "dbo.Deployment_ApplyRuntimePermissions",
|
||||
"type": "P"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "322_DeploymentRuntimeHealth",
|
||||
"file": "322_DeploymentRuntimeHealth.sql",
|
||||
"sha256": "14e24721d8dee3bcbd059b1057342bf4ce4e5ac1ce0076b120d584b5e07d9f17",
|
||||
"requires": [
|
||||
"321_DeploymentRuntimePermissionContract"
|
||||
],
|
||||
"mode": "execute",
|
||||
"prerequisites": [
|
||||
{
|
||||
"kind": "object",
|
||||
"name": "dbo.Deployment_ApplyRuntimePermissions",
|
||||
"type": "P"
|
||||
}
|
||||
],
|
||||
"postconditions": [
|
||||
{
|
||||
"kind": "object",
|
||||
"name": "dbo.Deployment_Health",
|
||||
"type": "P"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"omitted_migrations": [
|
||||
@ -14149,6 +14195,12 @@
|
||||
"sha256": "947d276060e33a8a07c8e6413d97c36ce6b41540a80efb14386e16015108e21f",
|
||||
"reason": "Superseded by standalone migration 304, which explicitly replaces partial 301 and failed 302; 303 is the intermediate projection repair covered by 304.",
|
||||
"evidence": "evidence/baseline.json"
|
||||
},
|
||||
{
|
||||
"id": "320_DeploymentRuntimePermissions",
|
||||
"sha256": "be2abc358df50c44ee61ff22e25e8a88aff7f3b5cf07435bd7f6363fb4425ac7",
|
||||
"reason": "Superseded isolated permission prototype: DENY CONTROL also denied required runtime EXECUTE and metadata. Standalone 321 supplies corrected denials and an effective-role assertion before commit. Never deploy 320 to a new environment.",
|
||||
"evidence": "evidence/baseline.json"
|
||||
}
|
||||
],
|
||||
"prerequisites": [
|
||||
@ -14203,6 +14255,11 @@
|
||||
"kind": "object",
|
||||
"name": "dbo.Deployment_Health",
|
||||
"type": "P"
|
||||
},
|
||||
{
|
||||
"kind": "object",
|
||||
"name": "dbo.Deployment_ApplyRuntimePermissions",
|
||||
"type": "P"
|
||||
}
|
||||
],
|
||||
"qualification": {
|
||||
|
||||
@ -27,6 +27,8 @@ internal static class DeploymentOperationsTests
|
||||
var unready=new Probe{Ready=false};
|
||||
if(Controller("127.0.0.1",unready).Read(default).GetAwaiter().GetResult() is not ObjectResult {StatusCode:503})
|
||||
throw new Exception("Uninitialised ledger passed health");
|
||||
if(Controller("127.0.0.1",new Probe{Restricted=false}).Read(default).GetAwaiter().GetResult() is not ObjectResult {StatusCode:503})
|
||||
throw new Exception("Privileged runtime credentials passed deployment health");
|
||||
var failed=new Probe{Fail=true};
|
||||
if(Controller("127.0.0.1",failed).Read(default).GetAwaiter().GetResult() is not ObjectResult {StatusCode:503})
|
||||
throw new Exception("Database failure passed health");
|
||||
@ -65,12 +67,21 @@ internal static class DeploymentOperationsTests
|
||||
private static DeploymentHealthController Controller(string address,Probe repository)
|
||||
{
|
||||
var http=new DefaultHttpContext();http.Connection.RemoteIpAddress=IPAddress.Parse(address);
|
||||
return new DeploymentHealthController(repository){ControllerContext=new ControllerContext{HttpContext=http}};
|
||||
return new DeploymentHealthController(repository,new TestEnvironment()){ControllerContext=new ControllerContext{HttpContext=http}};
|
||||
}
|
||||
private sealed class TestEnvironment:Microsoft.AspNetCore.Hosting.IWebHostEnvironment
|
||||
{
|
||||
public string EnvironmentName {get;set;}="Production";
|
||||
public string ApplicationName {get;set;}="PlotLine";
|
||||
public string ContentRootPath {get;set;}="/unused";
|
||||
public string WebRootPath {get;set;}="/unused/wwwroot";
|
||||
public Microsoft.Extensions.FileProviders.IFileProvider ContentRootFileProvider {get;set;}=new Microsoft.Extensions.FileProviders.NullFileProvider();
|
||||
public Microsoft.Extensions.FileProviders.IFileProvider WebRootFileProvider {get;set;}=new Microsoft.Extensions.FileProviders.NullFileProvider();
|
||||
}
|
||||
private sealed class Probe:IDeploymentHealthRepository
|
||||
{
|
||||
public int Calls;public bool Ready=true;public bool Fail;
|
||||
public int Calls;public bool Ready=true;public bool Restricted=true;public bool Fail;
|
||||
public Task<DeploymentDatabaseHealth> ReadAsync(CancellationToken cancellationToken)
|
||||
{Calls++;if(Fail)throw new InvalidOperationException("Private diagnostic must not reach HTTP");return Task.FromResult(new DeploymentDatabaseHealth("Isolated",Ready));}
|
||||
{Calls++;if(Fail)throw new InvalidOperationException("Private diagnostic must not reach HTTP");return Task.FromResult(new DeploymentDatabaseHealth("Isolated",Ready,Restricted));}
|
||||
}
|
||||
}
|
||||
|
||||
@ -9,7 +9,7 @@ namespace PlotLine.Controllers;
|
||||
|
||||
[AllowAnonymous]
|
||||
[ApiExplorerSettings(IgnoreApi=true)]
|
||||
public sealed class DeploymentHealthController(IDeploymentHealthRepository database) : Controller
|
||||
public sealed class DeploymentHealthController(IDeploymentHealthRepository database,IWebHostEnvironment environment) : Controller
|
||||
{
|
||||
[HttpGet("/_deployment/health")]
|
||||
[ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)]
|
||||
@ -22,11 +22,11 @@ public sealed class DeploymentHealthController(IDeploymentHealthRepository datab
|
||||
try
|
||||
{
|
||||
var state=await database.ReadAsync(cancellationToken);
|
||||
if(!state.LedgerReady)return StatusCode(503,new {healthy=false});
|
||||
if(!state.LedgerReady||!state.RuntimeRestricted)return StatusCode(503,new {healthy=false});
|
||||
var info=typeof(Program).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion??"";
|
||||
var sha=Regex.Match(info,@"\+([a-f0-9]{40})").Groups[1].Value;
|
||||
if(sha.Length!=40)return StatusCode(503,new {healthy=false});
|
||||
return Json(new {healthy=true,version=info.Split('+')[0],sourceCommit=sha,database=state.DatabaseName});
|
||||
return Json(new {healthy=true,version=info.Split('+')[0],sourceCommit=sha,database=state.DatabaseName,environment=environment.EnvironmentName});
|
||||
}
|
||||
catch(Exception) when(!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
|
||||
@ -3,7 +3,7 @@ using Dapper;
|
||||
|
||||
namespace PlotLine.Data;
|
||||
|
||||
public sealed record DeploymentDatabaseHealth(string DatabaseName, bool LedgerReady);
|
||||
public sealed record DeploymentDatabaseHealth(string DatabaseName, bool LedgerReady, bool RuntimeRestricted = true);
|
||||
|
||||
public interface IDeploymentHealthRepository
|
||||
{
|
||||
|
||||
44
PlotLine/Sql/320_DeploymentRuntimePermissions.sql
Normal file
44
PlotLine/Sql/320_DeploymentRuntimePermissions.sql
Normal file
@ -0,0 +1,44 @@
|
||||
-- Runtime business-data access is separate from schema deployment/history/backup.
|
||||
-- Dynamic project restore needs a narrowly scoped owner execution context for
|
||||
-- IDENTITY_INSERT/constraints. The login itself receives no table/schema DDL.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF DATABASE_PRINCIPAL_ID(N'PlotDirectorRuntime') IS NULL
|
||||
EXEC(N'CREATE ROLE [PlotDirectorRuntime] AUTHORIZATION [dbo];');
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Deployment_ApplyRuntimePermissions
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF IS_MEMBER(N'db_owner')<>1 AND USER_NAME()<>N'dbo'
|
||||
THROW 51000,'Only the migration principal may reconcile runtime permissions.',1;
|
||||
GRANT EXECUTE ON SCHEMA::dbo TO [PlotDirectorRuntime];
|
||||
GRANT SELECT,INSERT,UPDATE,DELETE ON SCHEMA::dbo TO [PlotDirectorRuntime];
|
||||
-- Direct ledger mutation/DDL is always denied even though the role can access
|
||||
-- business tables. Runtime is never a db_owner or schema-owner principal.
|
||||
DENY INSERT,UPDATE,DELETE,ALTER,CONTROL,TAKE OWNERSHIP ON OBJECT::dbo.DatabaseMigrationHistory TO [PlotDirectorRuntime];
|
||||
DENY INSERT,UPDATE,DELETE,ALTER,CONTROL,TAKE OWNERSHIP ON OBJECT::dbo.ApplicationReleaseHistory TO [PlotDirectorRuntime];
|
||||
DENY EXECUTE,ALTER,CONTROL,TAKE OWNERSHIP ON OBJECT::dbo.Deployment_ApplyRuntimePermissions TO [PlotDirectorRuntime];
|
||||
-- Only this reviewed, bounded project-restore procedure receives owner context.
|
||||
-- Runtime cannot alter it or this policy. Do not grant ALTER TABLE to the login.
|
||||
DECLARE @Definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectRestore_ApplyFromJson',N'P'));
|
||||
IF @Definition IS NULL THROW 51000,'Project restore prerequisite is missing.',1;
|
||||
IF @Definition NOT LIKE N'%WITH EXECUTE AS OWNER%'
|
||||
BEGIN
|
||||
SET @Definition=REPLACE(@Definition,CHAR(13),N'');
|
||||
DECLARE @Procedure int=CHARINDEX(N'PROCEDURE dbo.ProjectRestore_ApplyFromJson',@Definition);
|
||||
DECLARE @Body int=CHARINDEX(CHAR(10)+N'AS'+CHAR(10),@Definition);
|
||||
IF @Procedure=0 OR @Body=0 OR @Body>2000 OR @Body<@Procedure
|
||||
THROW 51000,'Unrecognised project restore header; permission change refused.',1;
|
||||
SET @Definition=STUFF(@Definition,@Body+1,0,N'WITH EXECUTE AS OWNER'+CHAR(10));
|
||||
SET @Definition=N'ALTER '+SUBSTRING(@Definition,@Procedure,LEN(@Definition));
|
||||
EXEC sys.sp_executesql @Definition;
|
||||
END;
|
||||
DENY ALTER,CONTROL,TAKE OWNERSHIP ON OBJECT::dbo.ProjectRestore_ApplyFromJson TO [PlotDirectorRuntime];
|
||||
IF DB_NAME()=N'PlotLine' AND OBJECT_ID(N'dbo.StoryIntelligence_DevelopmentAccountReset',N'P') IS NOT NULL
|
||||
DENY EXECUTE ON OBJECT::dbo.StoryIntelligence_DevelopmentAccountReset TO [PlotDirectorRuntime];
|
||||
END;
|
||||
GO
|
||||
EXEC dbo.Deployment_ApplyRuntimePermissions;
|
||||
GO
|
||||
87
PlotLine/Sql/321_DeploymentRuntimePermissionContract.sql
Normal file
87
PlotLine/Sql/321_DeploymentRuntimePermissionContract.sql
Normal file
@ -0,0 +1,87 @@
|
||||
-- Standalone forward correction: DENY CONTROL also denied required EXECUTE/metadata.
|
||||
-- Supersedes the isolated 320 qualification attempt; new environments apply 321 only.
|
||||
-- Runtime business-data access is separate from schema deployment/history/backup.
|
||||
-- Dynamic project restore needs a narrowly scoped owner execution context for
|
||||
-- IDENTITY_INSERT/constraints. The login itself receives no table/schema DDL.
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
IF DATABASE_PRINCIPAL_ID(N'PlotDirectorRuntime') IS NULL
|
||||
EXEC(N'CREATE ROLE [PlotDirectorRuntime] AUTHORIZATION [dbo];');
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Deployment_ApplyRuntimePermissions
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
IF IS_MEMBER(N'db_owner')<>1 AND USER_NAME()<>N'dbo'
|
||||
THROW 51000,'Only the migration principal may reconcile runtime permissions.',1;
|
||||
-- Remove only the overly broad isolated predecessor denials, if present.
|
||||
REVOKE CONTROL ON OBJECT::dbo.DatabaseMigrationHistory FROM [PlotDirectorRuntime];
|
||||
REVOKE CONTROL ON OBJECT::dbo.ApplicationReleaseHistory FROM [PlotDirectorRuntime];
|
||||
REVOKE CONTROL ON OBJECT::dbo.Deployment_ApplyRuntimePermissions FROM [PlotDirectorRuntime];
|
||||
REVOKE CONTROL ON OBJECT::dbo.ProjectRestore_ApplyFromJson FROM [PlotDirectorRuntime];
|
||||
GRANT EXECUTE ON SCHEMA::dbo TO [PlotDirectorRuntime];
|
||||
GRANT SELECT,INSERT,UPDATE,DELETE ON SCHEMA::dbo TO [PlotDirectorRuntime];
|
||||
-- Direct ledger mutation/DDL is always denied even though the role can access
|
||||
-- business tables. Runtime is never a db_owner or schema-owner principal.
|
||||
DENY INSERT,UPDATE,DELETE,ALTER,TAKE OWNERSHIP ON OBJECT::dbo.DatabaseMigrationHistory TO [PlotDirectorRuntime];
|
||||
DENY INSERT,UPDATE,DELETE,ALTER,TAKE OWNERSHIP ON OBJECT::dbo.ApplicationReleaseHistory TO [PlotDirectorRuntime];
|
||||
DENY EXECUTE,ALTER,TAKE OWNERSHIP ON OBJECT::dbo.Deployment_ApplyRuntimePermissions TO [PlotDirectorRuntime];
|
||||
-- Only this reviewed, bounded project-restore procedure receives owner context.
|
||||
-- Runtime cannot alter it or this policy. Do not grant ALTER TABLE to the login.
|
||||
DECLARE @Definition nvarchar(max)=OBJECT_DEFINITION(OBJECT_ID(N'dbo.ProjectRestore_ApplyFromJson',N'P'));
|
||||
IF @Definition IS NULL THROW 51000,'Project restore prerequisite is missing.',1;
|
||||
IF @Definition NOT LIKE N'%WITH EXECUTE AS OWNER%'
|
||||
BEGIN
|
||||
SET @Definition=REPLACE(@Definition,CHAR(13),N'');
|
||||
DECLARE @Procedure int=CHARINDEX(N'PROCEDURE dbo.ProjectRestore_ApplyFromJson',@Definition);
|
||||
DECLARE @Body int=CHARINDEX(CHAR(10)+N'AS'+CHAR(10),@Definition);
|
||||
IF @Procedure=0 OR @Body=0 OR @Body>2000 OR @Body<@Procedure
|
||||
THROW 51000,'Unrecognised project restore header; permission change refused.',1;
|
||||
SET @Definition=STUFF(@Definition,@Body+1,0,N'WITH EXECUTE AS OWNER'+CHAR(10));
|
||||
SET @Definition=N'ALTER '+SUBSTRING(@Definition,@Procedure,LEN(@Definition));
|
||||
EXEC sys.sp_executesql @Definition;
|
||||
END;
|
||||
DENY ALTER,TAKE OWNERSHIP ON OBJECT::dbo.ProjectRestore_ApplyFromJson TO [PlotDirectorRuntime];
|
||||
-- A non-authenticatable principal verifies the effective role, not just grants.
|
||||
IF DATABASE_PRINCIPAL_ID(N'PlotDirectorRuntimeProbe') IS NULL
|
||||
CREATE USER [PlotDirectorRuntimeProbe] WITHOUT LOGIN;
|
||||
IF NOT EXISTS(SELECT 1 FROM sys.database_principals WHERE name=N'PlotDirectorRuntimeProbe'
|
||||
AND type='S' AND authentication_type=0)
|
||||
THROW 51000,'Runtime probe principal conflicts with an existing identity.',1;
|
||||
IF IS_ROLEMEMBER(N'PlotDirectorRuntime',N'PlotDirectorRuntimeProbe')<>1
|
||||
ALTER ROLE [PlotDirectorRuntime] ADD MEMBER [PlotDirectorRuntimeProbe];
|
||||
DECLARE @Valid bit=0;
|
||||
BEGIN TRY
|
||||
EXECUTE AS USER=N'PlotDirectorRuntimeProbe';
|
||||
SET @Valid=CASE WHEN IS_MEMBER(N'db_owner')=0
|
||||
AND HAS_PERMS_BY_NAME(DB_NAME(),'DATABASE','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(DB_NAME(),'DATABASE','CREATE TABLE')=0
|
||||
AND HAS_PERMS_BY_NAME(DB_NAME(),'DATABASE','BACKUP DATABASE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','SELECT')=1
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','INSERT')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','UPDATE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','DELETE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','INSERT')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','UPDATE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','DELETE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.Projects','OBJECT','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ProjectRestore_ApplyFromJson','OBJECT','EXECUTE')=1
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ProjectRestore_ApplyFromJson','OBJECT','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.Deployment_ApplyRuntimePermissions','OBJECT','EXECUTE')=0
|
||||
THEN 1 ELSE 0 END;
|
||||
REVERT;
|
||||
END TRY
|
||||
BEGIN CATCH
|
||||
IF USER_NAME()=N'PlotDirectorRuntimeProbe' REVERT;
|
||||
THROW;
|
||||
END CATCH;
|
||||
IF @Valid<>1 THROW 51000,'Runtime role permission contract failed.',1;
|
||||
IF DB_NAME()=N'PlotLine' AND OBJECT_ID(N'dbo.StoryIntelligence_DevelopmentAccountReset',N'P') IS NOT NULL
|
||||
DENY EXECUTE ON OBJECT::dbo.StoryIntelligence_DevelopmentAccountReset TO [PlotDirectorRuntime];
|
||||
END;
|
||||
GO
|
||||
EXEC dbo.Deployment_ApplyRuntimePermissions;
|
||||
GO
|
||||
26
PlotLine/Sql/322_DeploymentRuntimeHealth.sql
Normal file
26
PlotLine/Sql/322_DeploymentRuntimeHealth.sql
Normal file
@ -0,0 +1,26 @@
|
||||
SET ANSI_NULLS ON;
|
||||
SET QUOTED_IDENTIFIER ON;
|
||||
GO
|
||||
CREATE OR ALTER PROCEDURE dbo.Deployment_Health
|
||||
AS
|
||||
BEGIN
|
||||
SET NOCOUNT ON;
|
||||
SELECT DB_NAME() AS DatabaseName,
|
||||
CONVERT(bit,CASE WHEN OBJECT_ID(N'dbo.DatabaseMigrationHistory',N'U') IS NOT NULL
|
||||
AND OBJECT_ID(N'dbo.ApplicationReleaseHistory',N'U') IS NOT NULL THEN 1 ELSE 0 END) AS LedgerReady,
|
||||
CONVERT(bit,CASE WHEN IS_ROLEMEMBER(N'db_owner')=0 AND IS_SRVROLEMEMBER(N'sysadmin')=0
|
||||
AND HAS_PERMS_BY_NAME(DB_NAME(),'DATABASE','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(DB_NAME(),'DATABASE','BACKUP DATABASE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','INSERT')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','UPDATE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','DELETE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.DatabaseMigrationHistory','OBJECT','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','INSERT')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','UPDATE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','DELETE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ApplicationReleaseHistory','OBJECT','ALTER')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.Deployment_ApplyRuntimePermissions','OBJECT','EXECUTE')=0
|
||||
AND HAS_PERMS_BY_NAME(N'dbo.ProjectRestore_ApplyFromJson','OBJECT','EXECUTE')=1
|
||||
THEN 1 ELSE 0 END) AS RuntimeRestricted;
|
||||
END;
|
||||
GO
|
||||
@ -38,6 +38,10 @@ internal static class Program
|
||||
connection = new SqlConnection(builder.ConnectionString);
|
||||
await connection.OpenAsync();
|
||||
if ((string?)await Scalar("SELECT DB_NAME()") != database) throw new InvalidOperationException("target");
|
||||
if(Convert.ToInt32(await Scalar("SELECT CONVERT(int,is_trustworthy_on)+CONVERT(int,is_db_chaining_on) FROM sys.databases WHERE name=DB_NAME()"))!=0)
|
||||
throw new InvalidOperationException("cross-database-security-boundary");
|
||||
if(Convert.ToInt32(await Scalar("SELECT value_in_use FROM sys.configurations WHERE name=N'cross db ownership chaining'"))!=0)
|
||||
throw new InvalidOperationException("server-cross-database-chaining");
|
||||
Console.WriteLine("{\"ok\":true,\"ready\":true}");
|
||||
while (await Console.In.ReadLineAsync() is { } line)
|
||||
{
|
||||
@ -108,7 +112,8 @@ internal static class Program
|
||||
throw new InvalidOperationException("baseline");
|
||||
await Idle();
|
||||
await Conditions(manifest["prerequisites"]!.AsArray());
|
||||
return new { schema = actual, complete };
|
||||
var databaseBytes=Convert.ToInt64(await Scalar("SELECT SUM(CONVERT(bigint,size))*8192 FROM sys.database_files"));
|
||||
return new { schema = actual, complete, database_bytes=databaseBytes };
|
||||
}
|
||||
if (!locked || manifest is null) throw new InvalidOperationException("not-begun");
|
||||
if (op == "idle") { await Idle(); return new { idle = true }; }
|
||||
@ -127,6 +132,10 @@ internal static class Program
|
||||
{
|
||||
await Idle();
|
||||
foreach (var node in manifest["migrations"]!.AsArray()) await Migration(node!.AsObject());
|
||||
// Fixed policy, never an executable hook supplied by a manifest. New
|
||||
// business tables receive the reviewed runtime permissions on release.
|
||||
if(await Scalar("SELECT OBJECT_ID(N'dbo.Deployment_ApplyRuntimePermissions',N'P')") is not DBNull)
|
||||
await Run("EXEC dbo.Deployment_ApplyRuntimePermissions;");
|
||||
var schema = await Schema();
|
||||
if (schema != S(manifest, "resulting_schema_sha256")) throw new InvalidOperationException("resulting-schema");
|
||||
await Conditions(manifest["postconditions"]!.AsArray());
|
||||
|
||||
@ -34,6 +34,35 @@ var expected=c.GetProperty("dll_sha256").GetString();
|
||||
if(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(dll)))!=expected
|
||||
|| Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(typeof(PlotLine.Program).Assembly.Location)))!=expected)
|
||||
throw new InvalidOperationException("Application assembly differs from qualified payload");
|
||||
if(args.Contains("--restore-contract"))
|
||||
{
|
||||
// Actual application export/encoding, followed by the actual SQL restore,
|
||||
// under the runtime role. The disposable clone's transaction always rolls back.
|
||||
using var db=new SqlConnection(cs.ConnectionString);db.Open();
|
||||
using var choose=db.CreateCommand();
|
||||
choose.CommandText="SELECT IS_MEMBER('db_owner')+HAS_PERMS_BY_NAME(DB_NAME(),'DATABASE','ALTER')+HAS_PERMS_BY_NAME('dbo.Projects','OBJECT','ALTER')";
|
||||
if(Convert.ToInt32(choose.ExecuteScalar())!=0)throw new InvalidOperationException("Unprivileged runtime principal required");
|
||||
choose.CommandText="SELECT TOP(1) p.ProjectID FROM dbo.Projects p JOIN dbo.Books b ON b.ProjectID=p.ProjectID JOIN dbo.Chapters c ON c.BookID=b.BookID JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID WHERE p.IsArchived=0 AND b.IsArchived=0 AND NOT EXISTS(SELECT 1 FROM dbo.NativeChapterReviews n JOIN dbo.Books k ON k.BookID=n.BookID WHERE k.ProjectID=p.ProjectID) AND NOT EXISTS(SELECT 1 FROM dbo.BookParagraphManuscripts m JOIN dbo.Books k ON k.BookID=m.BookID WHERE k.ProjectID=p.ProjectID) GROUP BY p.ProjectID ORDER BY COUNT_BIG(*),p.ProjectID";
|
||||
var project=Convert.ToInt32(choose.ExecuteScalar());
|
||||
if(project<=0)throw new InvalidOperationException("Eligible clone restore fixture unavailable");
|
||||
var repository=new PlotLine.Data.ProjectBackupRepository(new QualificationConnections(cs.ConnectionString));
|
||||
var exported=await repository.GetProjectBackupAsync(project)??throw new InvalidOperationException("Project export failed");
|
||||
var payload=PlotLine.Data.BookRecoveryRepository.Encode(exported,null);
|
||||
using var transaction=db.BeginTransaction();
|
||||
try
|
||||
{
|
||||
using var restore=new SqlCommand("dbo.ProjectRestore_ApplyFromJson",db,transaction){CommandType=System.Data.CommandType.StoredProcedure,CommandTimeout=180};
|
||||
restore.Parameters.AddWithValue("@ProjectID",project);
|
||||
restore.Parameters.Add("@JsonData",System.Data.SqlDbType.NVarChar,-1).Value=payload;
|
||||
await restore.ExecuteNonQueryAsync();
|
||||
using var check=new SqlCommand("SELECT @@TRANCOUNT",db,transaction);
|
||||
if(Convert.ToInt32(check.ExecuteScalar())!=1)throw new InvalidOperationException("Restore escaped its outer transaction");
|
||||
transaction.Rollback();
|
||||
Console.WriteLine("RUNTIME_RESTORE_CONTRACT passed; actual repository/export/restore; outer transaction rolled back.");
|
||||
return;
|
||||
}
|
||||
catch {try{transaction.Rollback();}catch{}throw;}
|
||||
}
|
||||
var keys=c.GetProperty("keys_path").GetString()!;
|
||||
var url=c.GetProperty("url").GetString()!;
|
||||
if(!url.StartsWith("http://127.0.0.1:",StringComparison.Ordinal))throw new InvalidOperationException("Loopback binding required");
|
||||
@ -75,6 +104,10 @@ internal sealed class NoExternalRequests:HttpMessageHandler
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
|
||||
=> throw new InvalidOperationException("Outbound HTTP disabled in qualification");
|
||||
}
|
||||
internal sealed class QualificationConnections(string value):PlotLine.Data.ISqlConnectionFactory
|
||||
{
|
||||
public System.Data.IDbConnection CreateConnection()=>new SqlConnection(value);
|
||||
}
|
||||
|
||||
// Explicit clone-only test authentication, absent from PlotLine/production binaries.
|
||||
// Loopback binding and SQL identity guards above are mandatory before registration.
|
||||
|
||||
@ -8,3 +8,33 @@ The release package is data, never a privileged executable. Atlas prepares it fr
|
||||
a clean Git commit. An administrator installs the helper, database worker, target
|
||||
configuration and independent release-verification public key. The transfer account
|
||||
can submit signed packages but cannot change the helper, trust anchor or target.
|
||||
|
||||
`qualify.py` restores two fresh copies in the existing Atlas SQL container, executes
|
||||
the reviewed plan, verifies COPY_ONLY/CHECKSUM backups and compares every original
|
||||
business column. It refuses existing databases/output/media and never uses REPLACE.
|
||||
Use `--backup`, `--backup-sha256`, `--source` (clean worktree), `--package` (private
|
||||
draft manifest/SQL), `--worker` (built from that SHA), `--output` (new private path)
|
||||
and `--database-prefix PlotDirector_Qualification_UNIQUE`. Input/resulting schema
|
||||
fingerprints must have been established through reviewed exploratory qualification;
|
||||
unknown results are never accepted by the production package validator.
|
||||
|
||||
For the isolated `QualificationHost`, publish on Atlas, copy the **qualified**
|
||||
`PlotLine.staticwebassets.endpoints.json` beside the host DLL and verify that its
|
||||
loaded PlotLine DLL hash exactly matches the qualified payload. Its private JSON
|
||||
contains the isolated connection, owner-ID allowlist, random request token, loopback
|
||||
URL, content root, key/upload paths and expected DLL hash. It removes all application
|
||||
background services and blocks external HttpClient requests. Browser qualification
|
||||
must also block outbound requests; a locally cached SignalR script can substitute
|
||||
for its public CDN dependency. Never put this configuration or recovered files in Git.
|
||||
|
||||
`QualificationHost --restore-contract` exercises the real application export,
|
||||
encoding and SQL restore under the restricted runtime role, always rolling back
|
||||
its clone-only outer transaction. It refuses an owner/DDL-capable runtime identity.
|
||||
This test tool and its authentication scheme are never installed on Production.
|
||||
|
||||
DatabaseWorker protocol is JSON lines over stdin/stdout, with a private connection
|
||||
configuration path as its sole argument. Operations: inspect, begin, idle, backup,
|
||||
migrate, health and activated. The session lock spans begin through process exit.
|
||||
fingerprint/integrity operations accept only qualification database names. Errors
|
||||
return a safe type/SQL number, script identity and batch number, never SQL text or
|
||||
connection diagnostics. Root activation evidence preserves the failure stage.
|
||||
|
||||
@ -47,6 +47,9 @@ def command(args, *, account=None, timeout=120):
|
||||
class Worker:
|
||||
def __init__(self, config):
|
||||
protected(config['worker'])
|
||||
protected(Path(config['worker']).parent, directory=True)
|
||||
for dependency in Path(config['worker']).parent.rglob('*'):
|
||||
protected(dependency, directory=dependency.is_dir())
|
||||
protected(config['database_config'], secret=True)
|
||||
database_config = load(config['database_config'])
|
||||
require(database_config['database'] == config['database'], 'Database configuration target mismatch')
|
||||
@ -161,7 +164,8 @@ def health(cfg, destination, manifest, worker):
|
||||
for path in ('/', '/Account/Login'):
|
||||
for attempt in range(20):
|
||||
try:
|
||||
status = command(['/usr/bin/curl', '--silent', '--show-error', '--noproxy', '*', '--connect-timeout', '2',
|
||||
status = command(['/usr/bin/curl', '--silent', '--show-error', '--noproxy', '*',
|
||||
'--header', 'Host: plotdirector.com', '--header', 'X-Forwarded-Proto: https', '--connect-timeout', '2',
|
||||
'--max-time', '5', '--output', '/dev/null', '--write-out', '%{http_code}', cfg['health_base'] + path], account=cfg['runtime_account'], timeout=10)
|
||||
if status in ('200', '301', '302', '307', '308'):
|
||||
break
|
||||
@ -173,11 +177,13 @@ def health(cfg, destination, manifest, worker):
|
||||
require((Path(cfg['root']) / 'current').resolve(strict=True) == destination / 'app', 'Active release identity mismatch')
|
||||
require(file_digest(destination / 'app/PlotLine.dll') == manifest['files']['app/PlotLine.dll'], 'Installed DLL checksum mismatch')
|
||||
identity = json.loads(command(['/usr/bin/curl', '--silent', '--show-error', '--fail', '--noproxy', '*',
|
||||
'--header', 'Host: plotdirector.com', '--header', 'X-Forwarded-Proto: https',
|
||||
'--connect-timeout', '2', '--max-time', '10', cfg['health_base'] + '/_deployment/health'],
|
||||
account=cfg['runtime_account'], timeout=15))
|
||||
require(identity.get('healthy') is True and identity.get('version') == manifest['version']
|
||||
and identity.get('sourceCommit') == manifest['source_commit'] and identity.get('database') == cfg['database'],
|
||||
'Running application/database identity mismatch')
|
||||
require(identity.get('environment') == cfg['environment'], 'Running application environment mismatch')
|
||||
worker.call('health')
|
||||
|
||||
|
||||
@ -230,6 +236,10 @@ def activate(package_id, validate=False, rollback=False):
|
||||
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')
|
||||
event('backup-start')
|
||||
worker.call('backup', path=str(backup))
|
||||
|
||||
35
Tools/Deployment/provision/runtime-account.sql
Normal file
35
Tools/Deployment/provision/runtime-account.sql
Normal file
@ -0,0 +1,35 @@
|
||||
-- Phase 2 DBA-only preparation. No passwords or server-login creation here.
|
||||
-- Execute in PlotLine after securely creating/reconciling its runtime login/user.
|
||||
-- Role can be created empty before migrations; 321 installs its permissions.
|
||||
SET XACT_ABORT ON;
|
||||
IF DB_NAME()<>N'PlotLine' THROW 51000,'Expected native web1 PlotLine database.',1;
|
||||
DECLARE @RuntimeUser sysname=N'PlotLineApp';
|
||||
DECLARE @Principal int=DATABASE_PRINCIPAL_ID(@RuntimeUser),@Sid varbinary(85);
|
||||
IF @Principal IS NULL THROW 51000,'Create/reconcile runtime database user first.',1;
|
||||
SELECT @Sid=sid FROM sys.database_principals WHERE principal_id=@Principal;
|
||||
IF @Sid=(SELECT owner_sid FROM sys.databases WHERE name=DB_NAME())
|
||||
THROW 51000,'Runtime must not own the database; administrator review required.',1;
|
||||
IF EXISTS(SELECT 1 FROM sys.server_role_members m JOIN sys.server_principals p ON p.principal_id=m.member_principal_id WHERE p.sid=@Sid)
|
||||
THROW 51000,'Runtime server-role membership is forbidden.',1;
|
||||
IF EXISTS(SELECT 1 FROM sys.database_permissions WHERE grantee_principal_id=@Principal
|
||||
AND state IN('G','W') AND permission_name IN('CONTROL','ALTER','ALTER ANY ROLE','ALTER ANY USER','CREATE TABLE','IMPERSONATE'))
|
||||
THROW 51000,'Unexpected explicit runtime privilege; reconcile before proceeding.',1;
|
||||
IF EXISTS(SELECT 1 FROM sys.database_role_members m JOIN sys.database_principals r ON r.principal_id=m.role_principal_id
|
||||
WHERE m.member_principal_id=@Principal AND r.name IN('db_ddladmin','db_securityadmin','db_accessadmin','db_backupoperator'))
|
||||
THROW 51000,'Unexpected privileged runtime database role; reconcile first.',1;
|
||||
BEGIN TRANSACTION;
|
||||
IF DATABASE_PRINCIPAL_ID(N'PlotDirectorRuntime') IS NULL EXEC(N'CREATE ROLE [PlotDirectorRuntime] AUTHORIZATION [dbo];');
|
||||
DECLARE @Sql nvarchar(max);
|
||||
IF IS_ROLEMEMBER(N'PlotDirectorRuntime',@RuntimeUser)<>1
|
||||
BEGIN
|
||||
SET @Sql=N'ALTER ROLE [PlotDirectorRuntime] ADD MEMBER '+QUOTENAME(@RuntimeUser)+N';';
|
||||
EXEC sys.sp_executesql @Sql;
|
||||
END;
|
||||
IF IS_ROLEMEMBER(N'db_owner',@RuntimeUser)=1
|
||||
BEGIN
|
||||
SET @Sql=N'ALTER ROLE [db_owner] DROP MEMBER '+QUOTENAME(@RuntimeUser)+N';';
|
||||
EXEC sys.sp_executesql @Sql;
|
||||
END;
|
||||
COMMIT;
|
||||
-- After approved migration/activation, /_deployment/health must report healthy.
|
||||
-- It refuses runtime ownership, backup/DDL powers and history/policy mutation.
|
||||
@ -6,9 +6,16 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import fcntl
|
||||
import resource
|
||||
import signal
|
||||
import shutil
|
||||
import stat
|
||||
|
||||
INBOX=Path('/srv/plotdirector/incoming')
|
||||
LIMIT=4*1024**3
|
||||
UPLOAD_LOCK=Path('/srv/plotdirector/incoming-upload.lock')
|
||||
FREE_FLOOR=10*1024**3
|
||||
|
||||
|
||||
def main():
|
||||
@ -25,6 +32,18 @@ def main():
|
||||
if operation=='rollback':args.append('--rollback')
|
||||
args.append(release)
|
||||
raise SystemExit(subprocess.run(args,env={'PATH':'/usr/sbin:/usr/bin:/sbin:/bin','LANG':'C.UTF-8'},cwd='/').returncode)
|
||||
# These limits apply only to unprivileged transfer, never to the activation
|
||||
# worker/.NET subprocess. Serialize uploads and retain space for other sites.
|
||||
resource.setrlimit(resource.RLIMIT_AS,(256*1024**2,256*1024**2))
|
||||
resource.setrlimit(resource.RLIMIT_CPU,(120,120))
|
||||
signal.alarm(1800)
|
||||
os.nice(10)
|
||||
lock=os.open(UPLOAD_LOCK,os.O_RDWR|os.O_NOFOLLOW)
|
||||
info=os.fstat(lock)
|
||||
if not stat.S_ISREG(info.st_mode) or info.st_uid!=0 or info.st_nlink!=1 or info.st_mode&0o007:
|
||||
raise ValueError('Invalid protected upload lock')
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
if shutil.disk_usage(INBOX).free<FREE_FLOOR+LIMIT:raise ValueError('Insufficient staging space')
|
||||
destination=INBOX/release
|
||||
destination.mkdir(mode=0o700) # Refuses replacement, including symlinks.
|
||||
received=set()
|
||||
@ -39,7 +58,9 @@ def main():
|
||||
total+=member.size
|
||||
if total>LIMIT+32768:raise ValueError('Transfer size exceeded')
|
||||
with tar.extractfile(member) as source,(destination/member.name).open('xb') as target:
|
||||
while block:=source.read(1024**2):target.write(block)
|
||||
while block:=source.read(1024**2):
|
||||
if shutil.disk_usage(INBOX).free<FREE_FLOOR+len(block):raise ValueError('Staging space floor reached')
|
||||
target.write(block)
|
||||
target.flush();os.fsync(target.fileno())
|
||||
if received!={'package.tar','authorization.json','authorization.sig'}:
|
||||
raise ValueError('Incomplete transfer; administrator must remove the incomplete incoming directory before retry')
|
||||
|
||||
@ -23,7 +23,7 @@ class ActivationFailureTests(unittest.TestCase):
|
||||
self.cfg={'root':str(self.root),'inbox':str(self.root/'inbox'),'evidence':str(self.root/'evidence'),
|
||||
'backup':str(self.root/'backup'),'runtime_account':'root','migration_account':'root',
|
||||
'public_key':'not-used','minimum_free_bytes':1,'service':'plotdirector-qualification.service',
|
||||
'health_base':'http://127.0.0.1:5999','database':'PlotLine'}
|
||||
'health_base':'http://127.0.0.1:5999','database':'PlotLine','environment':'Production'}
|
||||
self.calls=[];self.state='active';self.failure=None;self.status='200';self.complete=False;self.activations=[]
|
||||
outer=self
|
||||
class FakeWorker:
|
||||
@ -32,7 +32,7 @@ class ActivationFailureTests(unittest.TestCase):
|
||||
outer.calls.append(op)
|
||||
if outer.failure==op:raise Refused('Injected '+op+' failure')
|
||||
if op=='backup':Path(values['path']).write_bytes(b'verified-fixture')
|
||||
if op=='begin':return {'complete':outer.complete}
|
||||
if op=='begin':return {'complete':outer.complete,'database_bytes':1024}
|
||||
if op=='activated':outer.activations.append(values)
|
||||
return {}
|
||||
def close(self):outer.calls.append('worker-close')
|
||||
@ -54,7 +54,7 @@ class ActivationFailureTests(unittest.TestCase):
|
||||
return self.state
|
||||
if args[0].endswith('curl'):
|
||||
self.calls.append('http')
|
||||
return self.status if '--output' in args else json.dumps({'healthy':True,'version':'1.0.0','sourceCommit':'a'*40,'database':'PlotLine'})
|
||||
return self.status if '--output' in args else json.dumps({'healthy':True,'version':'1.0.0','sourceCommit':'a'*40,'database':'PlotLine','environment':'Production'})
|
||||
raise AssertionError('Unexpected executable')
|
||||
|
||||
def run_activation(self,validate=False,free=10**12,rollback=False):
|
||||
@ -98,6 +98,10 @@ class ActivationFailureTests(unittest.TestCase):
|
||||
with self.assertRaises(Refused):self.run_activation(free=0)
|
||||
self.assertEqual(self.calls,[])
|
||||
|
||||
def test_database_backup_budget_is_checked_before_backup_or_shutdown(self):
|
||||
with self.assertRaises(Refused):self.run_activation(free=1024)
|
||||
self.assertIn('begin',self.calls);self.assertNotIn('backup',self.calls);self.assertNotIn('service-stop',self.calls)
|
||||
|
||||
def test_install_permission_failure_leaves_service_stopped(self):
|
||||
with patch.object(activate,'install',side_effect=PermissionError('injected')):
|
||||
with self.assertRaises(PermissionError):self.run_activation()
|
||||
|
||||
21
Tools/Deployment/test_dispatch.py
Normal file
21
Tools/Deployment/test_dispatch.py
Normal file
@ -0,0 +1,21 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
class ForcedCommandTests(unittest.TestCase):
|
||||
def test_shell_and_sftp_requests_are_rejected_without_execution(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
marker=Path(directory)/'must-not-exist'
|
||||
for command in ('id','internal-sftp','sftp',f'touch {marker}','activate ../../outside','activate release; id','upload ../outside',''):
|
||||
with self.subTest(command=command):
|
||||
p=subprocess.run([sys.executable,str(Path(__file__).with_name('ssh_dispatch.py'))],
|
||||
env={**os.environ,'SSH_ORIGINAL_COMMAND':command},capture_output=True,text=True)
|
||||
self.assertNotEqual(p.returncode,0)
|
||||
self.assertFalse(marker.exists())
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Loading…
x
Reference in New Issue
Block a user