0

NOTE: I have checked this question and answer and it did not answer my use case: Permission for querying dbo.sysobjects

I have the following stored procedure to create a sequence if it does not exist:

ALTER PROCEDURE seq.CreateSequenceIfNotExists 
    @FullSequenceName nvarchar(500)
WITH EXECUTE AS 'SequenceCreator'
AS
BEGIN
    SET NOCOUNT ON;
        
    IF (NOT EXISTS (SELECT 1
                    FROM sys.objects
                    WHERE object_id = OBJECT_ID(@FullSequenceName) AND type = 'SO'))
    BEGIN
        DECLARE @SequenceCreateSql NVARCHAR(700)
        SET @SequenceCreateSql = CONCAT('CREATE SEQUENCE ', @FullSequenceName, 'START WITH 1 INCREMENT BY 1 NO CACHE')
        EXEC sp_executesql @stmnt = @SequenceCreateSql
    END
END
GO

The user it runs as (SequenceCreator) has ONLY the following permission:

GRANT CREATE SEQUENCE ON SCHEMA::seq TO SequenceCreator  
GO

When this stored procedure runs, it works fine to create the sequence. But when I run it a second time, the query to sys.objects returns no rows and it tries to create a the sequence again (it returns one row when I run it as dbo (as expected)).

I assume that the user SequenceCreator does not have the permissions to query this row in sys.objects.

What are the minimum permissions needed to allow this user to check for the existence of sequences that it creates?

(NOTE: I need it to be the "minimum permissions", because I cannot parameterize the name of the sequence, so it could be hit with a SQL injection attack. Though unlikely in my use case, I need the user to not have any real permissions to exploit)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • What user owns the `seq` schema? You could `GRANT VIEW DEFINITION ON SCHEMA::seq TO SequenceCreator;`, which will proved meta-data visibility. Personally, I would avoid `EXECUTE AS` and instead sign the proc based on a certificate user with the needed permissions. That way, you only need to grant exec permissions on the proc to users that need that ability. – Dan Guzman Jul 30 '21 at 20:58
  • @DanGuzman - Right now `dbo` owns the schema `seq`. (I can change that if needed). I like the `VIEW DEFINITION` option, I will look into that. I was planning to do similar to what you outline with the certificate user with my SQL User without a login, but I will look into what you suggest for added security. – Vaccano Jul 30 '21 at 21:27

0 Answers0