Search code examples
jenkinsgroovypermissions

How do I remove specific Jenkins User permissions form a User using Groovy?


I am able to add a specific Permission to a User using the following common script:

import hudson.model.*
import Jenkins.*
import hudson.security.Permission
import hudson.security.GlobalMatrixAuthorizationStrategy

String userId = "my_user"
List<String> userPermissionList = [hudson.model.Item.CONFIGURE]

Hudson instance = Jenkins.get()
GlobalMatrixAuthorizationStrategy authStrategy = Jenkins.instance.getAuthorizationStrategy()

// Adding each permission from list
userPermissionList.each { permission ->
    authStrategy.add(permission, userId)
    instance.setAuthorizationStrategy(authStrategy)
}

instance.save()

However, I looked everywhere to find how to remove a specific permission from a user. Looking at GlobalMatrixAuthorizationStrategy, there is a add() method, however no remove() of any sort.

Is this even possible??? (it has to be)

Or do I have add the difference to the user? As in, clear the user of all permissions and add back all but the ones I want to remove.


Solution

  • Solution

    The Permission class has an attribute called enabled with associated getters and setters. You can add a permission by setting permission.enabled = true and to remove the permission you should explicitly set permission.enabled = false

    The default value for permission.enabled may be different depending on what version of Jenkins you are running. It is best to explicitly set this value either way

    import hudson.model.*
    import Jenkins.*
    import hudson.security.Permission
    import hudson.security.GlobalMatrixAuthorizationStrategy
    
    def userId = "gnocras"
    def userPermissionList = [hudson.model.Item.CONFIGURE]
    
    Hudson instance = Jenkins.get()
    GlobalMatrixAuthorizationStrategy authStrategy = Jenkins.instance.getAuthorizationStrategy()
    
    // Removing each permission from list
    userPermissionList.each { permission ->
        permission.enabled = false
        authStrategy.add(permission, userId)
        instance.setAuthorizationStrategy(authStrategy)
    }
    
    instance.save()
    

    This intended to be ran in the Jenkin's Script Console

    Before running the above script the user had the following permission

    with permission

    And after running this script the user had the following permission

    without permission

    If I rerun the script with permission.enabled = true the user has the following permission

    with permission