Не вижу роли и привилегии из Groovy скрипта после создания в Nexus - PullRequest
0 голосов
/ 23 сентября 2019

Я выполняю этот скриптовый скрипт внутри Nexus

import org.sonatype.nexus.common.entity.*
import org.sonatype.nexus.security.*
import org.sonatype.nexus.security.authz.*
import org.sonatype.nexus.security.role.*
import org.sonatype.nexus.security.privilege.*
import org.sonatype.nexus.security.user.UserManager;
import org.sonatype.nexus.selector.*
import com.google.common.collect.ImmutableMap

// use container.lookup to fetch internal APIs we need to use
def selectorManager = container.lookup(SelectorManager.class.name)
def securitySystem = container.lookup(SecuritySystem.class.name)
def authorizationManager = security.getSecuritySystem().getAuthorizationManager(UserManager.DEFAULT_SOURCE)

def userMail = "user@mail.com"
def requiredFormats = ["maven2", "docker"]
// ----------------
def username = userMail.toLowerCase().substring(0, userMail.indexOf("@"));
def pathMap = ["docker": "^\"/v2/${username}/\"", "maven2": "^\"${username}/\"", "npm": "^\"@${username}\"", "raw": "^\"${username}\""]
// ----------------
def privilegeIds = []

requiredFormats.each{ requiredFormat ->

  // create content selector (if not already present)
  def selectorConfig = new SelectorConfiguration(
      "name" : username + "-" + requiredFormat + "-selector",
      "type" : "csel",
      "description" : "Selector for " + username + " to see part of the " + requiredFormat + " repository",
      "attributes" : ["expression": "format==\"" + requiredFormat + "\" and path=" + pathMap.get(requiredFormat).toString()]
  )

  if (selectorManager.browse().find { it -> it.name == selectorConfig.name } == null) {
    selectorManager.create(selectorConfig)
  }

  // create content selector privilege
  def privelegeProperties = ImmutableMap.builder()
    .put("contentSelector", selectorConfig.getName())
    .put("repository", "*-" + requiredFormat)
    .put("actions", '*')
    .build()
  def privilegeConfig = new org.sonatype.nexus.security.privilege.Privilege(
      "id": "id-" + username + "-" + requiredFormat + "-privelege",
      "name": username + "-" + requiredFormat + "-privilege",
      "description": "Privelege for " + username + " to access the " + requiredFormat + " repository",
      "type": "repository-content-selector",
      "properties": privelegeProperties
  )
  privilegeIds.add(privilegeConfig.getId())
  try {
    authorizationManager.getPrivilege(privilegeConfig.getId())
  } catch (NoSuchPrivilegeException ex) {
    authorizationManager.addPrivilege(privilegeConfig)
  }
}

// create a role with privileges
def roleConfig = new org.sonatype.nexus.security.role.Role(
    "roleId": username + "-role",
    "source": "Nexus",
    "name": username + "-role",
    "description": "Role for " + username + " to access the repositories",
    "readOnly": false,
    "privileges": privilegeIds,
    "roles": []
)
try {
  privilegeIds.each{ privilegeId ->
    authorizationManager.getRole(username + "-role").addPrivilege(privilegeId)
  }
  // def rolePriveleges = authorizationManager.getRole(username + "-role").privileges.add(privilegeIds)
  // authorizationManager.deleteRole(username + "-role")
  // roleConfig.setPrivileges(rolePriveleges)
} catch (NoSuchRoleException) {
  // create a roleIdentifier for role
  def roleIdentifier = new org.sonatype.nexus.security.role.RoleIdentifier('default', roleConfig.getRoleId())
  authorizationManager.addRole(roleConfig)

  // assign a role to a user
  def user = security.getSecuritySystem().getUser(userMail)

  user.addRole(roleIdentifier)
  // security.getSecuritySystem().setUsersRoles(user.userId, 'LDAP', user.getRoles())
}

Затем я могу увидеть роль с привилегиями через Интернет, но при выполнении следующего скрипта я получаю ошибку NoSuchRoleException.

import org.sonatype.nexus.security.user.UserManager
import org.sonatype.nexus.common.entity.*
import org.sonatype.nexus.security.*
import org.sonatype.nexus.security.role.*
import org.sonatype.nexus.security.authz.*
import org.sonatype.nexus.selector.*
def securitySystem = container.lookup(SecuritySystem.class.name)
security.getSecuritySystem().getAuthorizationManager(UserManager.DEFAULT_SOURCE).deleteRole('<the correct ID of the created role>')

Я изучил код Nexus и существующие пользовательские решения на форумах столько, сколько мог, но я не понимаю, в чем проблема.

Пожалуйста, не отсылайте меня на эту ссылку

Итак, я хочу:

  1. Создать ContentSelector (✔)
  2. Создать привилегии с помощью ContentSelectors (✔)
  3. Создать роль, котораясовокупные привилегии (✔)
  4. Назначить роль пользователю LDAP (✔)
  5. Удалить любую привилегию из существующей роли (x)
  6. Добавить любую привилегию из существующей роли (x)
  7. Отмена роли для пользователя (x)
  8. Удаление роли (✔)
...