yochananrachamim / AzureSQL

132 stars 61 forks source link

Insufficient permissions to run #29

Closed rexxmagnus closed 2 years ago

rexxmagnus commented 2 years ago

I've got a webjob triggered by my asp.net server that executes several stored procedures as part of a maintenance cycle (triggered by C#), however the user I'm accessing the database as doesn't appear able to run the AzureSQLMaintenance sproc. The command (exec AzureSQLMaintenance 'all') errors out with the following message:


The specified schema name "154e669f-8721-4e64-863b-e6cc9148f10f@93a5c70e-b223-4d0e-a0cf-4b358d5ba4a0" either does not exist or you do not have permission to use it.
-----------------------
set operation = all
set mode = smart
set ResumableIndexRebuild = 0
set RebuildHeaps = 0
set LogToTable = 0
-----------------------

I'm using an Azure security group (which has the relevant website added as a member), which has permissions enabled on the database as below:

CREATE USER [SQLAccess] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [SQLAccess];
ALTER ROLE db_datawriter ADD MEMBER [SQLAccess];
ALTER ROLE db_ddladmin ADD MEMBER [SQLAccess];

CREATE ROLE db_executer
GRANT EXECUTE to db_executer
ALTER ROLE db_executer ADD MEMBER [SQLAccess];
GO

I have also tried adding the user as db_owner, but that doesn't seem to have any effect on running the procedure. I can successfully run the procedure via SSMS, logged in as myself (I'm a member of a group that is set as the Azure Active Directory admin for the server) and the server is set to accept Azure Active Directory authentication only. I can also trigger the job successfully while running the webserver on my local machine, which uses my azure credentials (the ones that fall into the AAD admin role).

Any clue whether adding extra permissions will fix the issue for the SQLAccess user, or am I looking in the wrong place?

rexxmagnus commented 2 years ago

I seem to have solved this by modifying the maintenance procedure, running it with execute as SELF (which gives the permissions of the person who ran the create/alter script). This means the procedure can run with the required server-level permissions, which cannot be granted to users at database level.

CREATE PROCEDURE [dbo].[AzureSQLMaintenance] 
    (
        @operation nvarchar(10) = null,
        @mode nvarchar(10) = 'smart',
        @ResumableIndexRebuild bit = 0,
        @RebuildHeaps bit = 0,
        @LogToTable bit = 0,
        @debug nvarchar(10) = 'none'
    ) 
    WITH EXECUTE AS SELF
AS ...