-- 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