Search in sources :

Example 1 with AuthorityHolder

use of jetbrains.buildServer.serverSide.auth.AuthorityHolder in project teamcity-rest by JetBrains.

the class PermissionAssignmentFinder method getPermissions.

@NotNull
private FinderDataBinding.ItemHolder<PermissionAssignmentData> getPermissions(@NotNull final TypedFinderBuilder.DimensionObjects dimensions, @NotNull final AuthorityHolder authorityHolder, @NotNull final ServiceLocator serviceLocator) {
    /* The rest of the code in this method is mostly performance optimization producing the same results (with possibly changed sorting).
    if (true) {
      List<Permission> globalPermissions = authorityHolder.getGlobalPermissions().toList();
      Set<Permission> globalPermissionsSet = new HashSet<>(globalPermissions); //TeamCity API issue: this set is used to exclude global permissions from project-level ones
      return FinderDataBinding.getItemHolder(Stream.concat(
        globalPermissions.stream().map(p -> new PermissionAssignmentData(p)),
        authorityHolder.getProjectsPermissions().entrySet().stream().flatMap(
          entry -> entry.getValue().toList().stream().filter(p -> !globalPermissionsSet.contains(p)).map(p -> new PermissionAssignmentData(p, entry.getKey())))));
    }
    */
    List<Permission> permissions_raw = dimensions.get(PERMISSION);
    List<List<SProject>> projects_raw = dimensions.get(PROJECT);
    if (projects_raw != null && !projects_raw.isEmpty() && projects_raw.size() > 1) {
        throw new BadRequestException("Multiple projects dimensions are not supported");
    }
    @Nullable List<SProject> projects = projects_raw == null || projects_raw.isEmpty() ? null : projects_raw.get(0);
    if (permissions_raw != null && !permissions_raw.isEmpty() && permissions_raw.size() > 1) {
        throw new BadRequestException("Multiple permissions dimensions are not supported");
    }
    // permissions_raw is ANDed, permissions is ORed, but so far it is not supported: todo implement
    List<Permission> permissions = permissions_raw;
    Stream<PermissionAssignmentData> result = Stream.empty();
    List<Boolean> global_raw = dimensions.get(GLOBAL);
    if (global_raw != null && !global_raw.isEmpty() && global_raw.size() > 1) {
        throw new BadRequestException("Multiple global dimensions are not supported");
    }
    Boolean global = global_raw == null ? null : global_raw.get(0);
    if ((permissions == null || permissions.isEmpty())) {
        if (projects == null) {
            if (global == null || global) {
                result = Stream.concat(result, authorityHolder.getGlobalPermissions().toList().stream().map(p -> new PermissionAssignmentData(p)));
            }
            if (global == null || !global) {
                result = Stream.concat(result, authorityHolder.getProjectsPermissions().entrySet().stream().flatMap(entry -> entry.getValue().toList().stream().filter(p -> p.isProjectAssociationSupported()).map(p -> new PermissionAssignmentData(p, entry.getKey()))));
            }
            return FinderDataBinding.getItemHolder(result);
        }
        if (global == null || global) {
            result = Stream.concat(result, authorityHolder.getGlobalPermissions().toList().stream().filter(p -> p.isProjectAssociationSupported()).map(p -> new PermissionAssignmentData(p)));
        }
        if (global == null || !global) {
            result = Stream.concat(result, projects.stream().flatMap(project -> {
                Permissions projectPermissions = authorityHolder.getProjectsPermissions().get(project.getProjectId());
                return projectPermissions == null ? Stream.empty() : projectPermissions.toList().stream().filter(p -> p.isProjectAssociationSupported()).map(p -> new PermissionAssignmentData(p, project.getProjectId()));
            }));
        }
        return FinderDataBinding.getItemHolder(result);
    }
    if (projects == null) {
        if (global == null || global) {
            result = Stream.concat(result, permissions.stream().filter(p -> authorityHolder.isPermissionGrantedGlobally(p)).map(p -> new PermissionAssignmentData(p)));
        }
        if (global == null || !global) {
            List<SProject> allProjects = serviceLocator.getSingletonService(ProjectManager.class).getProjects();
            result = Stream.concat(result, permissions.stream().filter(p -> p.isProjectAssociationSupported()).flatMap(p -> allProjects.stream().filter(project -> {
                Permissions projectPermissions = authorityHolder.getProjectsPermissions().get(project.getProjectId());
                return projectPermissions != null && projectPermissions.contains(p);
            }).map(project -> new PermissionAssignmentData(p, project.getProjectId()))));
        }
        return FinderDataBinding.getItemHolder(result);
    }
    if (global == null || global) {
        result = Stream.concat(result, permissions.stream().filter(p -> p.isProjectAssociationSupported()).filter(p -> authorityHolder.isPermissionGrantedGlobally(p)).map(p -> new PermissionAssignmentData(p)));
    }
    if (global == null || !global) {
        result = Stream.concat(result, projects.stream().flatMap(project -> permissions.stream().filter(p -> p.isProjectAssociationSupported()).filter(p -> {
            Permissions projectPermissions = authorityHolder.getProjectsPermissions().get(project.getProjectId());
            return projectPermissions != null && projectPermissions.contains(p);
        }).map(p -> new PermissionAssignmentData(p, project.getProjectId()))));
    }
    return FinderDataBinding.getItemHolder(result);
}
Also used : Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Stream(java.util.stream.Stream) ServiceLocator(jetbrains.buildServer.ServiceLocator) Permissions(jetbrains.buildServer.serverSide.auth.Permissions) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) Permission(jetbrains.buildServer.serverSide.auth.Permission) SProject(jetbrains.buildServer.serverSide.SProject) ProjectManager(jetbrains.buildServer.serverSide.ProjectManager) NotNull(org.jetbrains.annotations.NotNull) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) SProject(jetbrains.buildServer.serverSide.SProject) ProjectManager(jetbrains.buildServer.serverSide.ProjectManager) Permission(jetbrains.buildServer.serverSide.auth.Permission) Permissions(jetbrains.buildServer.serverSide.auth.Permissions) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) List(java.util.List) Nullable(org.jetbrains.annotations.Nullable) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with AuthorityHolder

use of jetbrains.buildServer.serverSide.auth.AuthorityHolder in project teamcity-rest by JetBrains.

the class BuildTypeRequest method deleteBuildType.

@DELETE
@Path("/{btLocator}")
@ApiOperation(value = "Delete build configuration matching the locator.", nickname = "deleteBuildType")
public void deleteBuildType(@ApiParam(format = LocatorName.BUILD_TYPE) @PathParam("btLocator") String buildTypeLocator) {
    BuildTypeOrTemplate buildType = myBuildTypeFinder.getBuildTypeOrTemplate(null, buildTypeLocator, false);
    AuthorityHolder authorityHolder = myBeanContext.getSingletonService(SecurityContext.class).getAuthorityHolder();
    buildType.remove((SUser) authorityHolder.getAssociatedUser(), buildType.isBuildType() ? "Build configuration removed" : "Template removed");
}
Also used : BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) SecurityContext(jetbrains.buildServer.serverSide.auth.SecurityContext) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) ApiOperation(io.swagger.annotations.ApiOperation)

Example 3 with AuthorityHolder

use of jetbrains.buildServer.serverSide.auth.AuthorityHolder in project teamcity-rest by JetBrains.

the class AbstractAgentPoolResolver method projects.

@NotNull
public AgentPoolProjectsConnection projects(@NotNull AbstractAgentPool pool, @NotNull ProjectsFilter filter, @NotNull DataFetchingEnvironment env) {
    jetbrains.buildServer.serverSide.agentPools.AgentPool realPool = pool.getRealPool();
    Collection<String> projectIds = realPool.getProjectIds();
    Stream<SProject> projects = myProjectManager.findProjects(projectIds).stream();
    if (filter.getArchived() != null) {
        projects = projects.filter(p -> p.isArchived() == filter.getArchived());
    }
    Integer excludedProjectsCount = null;
    if (env.getSelectionSet().contains("excludedCount")) {
        AuthorityHolder authHolder = mySecurityContext.getAuthorityHolder();
        excludedProjectsCount = (int) projectIds.stream().filter(projectId -> !authHolder.isPermissionGrantedForProject(projectId, Permission.VIEW_PROJECT)).count();
    }
    return new AgentPoolProjectsConnection(projects.collect(Collectors.toList()), excludedProjectsCount, PaginationArguments.everything());
}
Also used : AgentPool(jetbrains.buildServer.serverSide.agentPools.AgentPool) DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) CloudClientEx(jetbrains.buildServer.clouds.CloudClientEx) AbstractAgentPool(jetbrains.buildServer.server.graphql.model.agentPool.AbstractAgentPool) CloudProfile(jetbrains.buildServer.clouds.CloudProfile) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) AgentPoolProjectsConnection(jetbrains.buildServer.server.graphql.model.connections.agentPool.AgentPoolProjectsConnection) PaginationArguments(jetbrains.buildServer.server.graphql.model.connections.PaginationArguments) ArrayList(java.util.ArrayList) BooleanSupplier(java.util.function.BooleanSupplier) AgentPool(jetbrains.buildServer.serverSide.agentPools.AgentPool) CloudImage(jetbrains.buildServer.clouds.CloudImage) SAgentType(jetbrains.buildServer.serverSide.agentTypes.SAgentType) AgentTypeKey(jetbrains.buildServer.serverSide.agentTypes.AgentTypeKey) AgentPoolAgentsConnection(jetbrains.buildServer.server.graphql.model.connections.agentPool.AgentPoolAgentsConnection) AgentTypeFinder(jetbrains.buildServer.serverSide.agentTypes.AgentTypeFinder) CloudManager(jetbrains.buildServer.clouds.server.CloudManager) jetbrains.buildServer.serverSide(jetbrains.buildServer.serverSide) Collection(java.util.Collection) AgentPoolPermissions(jetbrains.buildServer.server.graphql.model.agentPool.AgentPoolPermissions) Collectors(java.util.stream.Collectors) List(java.util.List) Component(org.springframework.stereotype.Component) Stream(java.util.stream.Stream) ProjectsFilter(jetbrains.buildServer.server.graphql.model.filter.ProjectsFilter) Permission(jetbrains.buildServer.serverSide.auth.Permission) AgentPoolCloudImagesConnection(jetbrains.buildServer.server.graphql.model.connections.agentPool.AgentPoolCloudImagesConnection) Pair(com.intellij.openapi.util.Pair) AuthUtil(jetbrains.buildServer.serverSide.auth.AuthUtil) NotNull(org.jetbrains.annotations.NotNull) AgentPoolProjectsConnection(jetbrains.buildServer.server.graphql.model.connections.agentPool.AgentPoolProjectsConnection) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) NotNull(org.jetbrains.annotations.NotNull)

Example 4 with AuthorityHolder

use of jetbrains.buildServer.serverSide.auth.AuthorityHolder in project teamcity-rest by JetBrains.

the class AgentPoolMutation method bulkMoveAgentsToAgentPool.

@Used("graphql")
@NotNull
public DataFetcherResult<BulkMoveAgentToAgentsPoolPayload> bulkMoveAgentsToAgentPool(@NotNull BulkMoveAgentsToAgentPoolInput input) {
    DataFetcherResult.Builder<BulkMoveAgentToAgentsPoolPayload> result = DataFetcherResult.newResult();
    AgentPool targetPool = myAgentPoolManager.findAgentPoolById(input.getTargetAgentPoolRawId());
    if (targetPool == null) {
        return result.error(new EntityNotFoundGraphQLError("Target pool is not found.")).build();
    }
    if (targetPool.isProjectPool() || targetPool instanceof ReadOnlyAgentPool) {
        return result.error(new OperationFailedGraphQLError("Can't move agents to target pool.")).build();
    }
    if (!myAgentPoolActionsAccessChecker.canManageAgentsInPool(targetPool)) {
        return result.error(new OperationFailedGraphQLError("Can't move agents to target pool.")).build();
    }
    Set<String> projectsToCheck = new HashSet<>();
    Set<Integer> agentTypes = new HashSet<>();
    for (Integer agentId : input.getAgentRawIds()) {
        SBuildAgent agent = myBuildAgentManager.findAgentById(agentId, true);
        if (agent == null) {
            return result.error(new OperationFailedGraphQLError("One of the agents with given ids is not found.")).build();
        }
        agentTypes.add(agent.getAgentTypeId());
        projectsToCheck.addAll(agent.getAgentPool().getProjectIds());
    }
    AuthorityHolder authHolder = mySecurityContext.getAuthorityHolder();
    if (!AuthUtil.hasPermissionToManageAgentPoolsWithProjects(authHolder, projectsToCheck)) {
        return result.error(new OperationFailedGraphQLError("Not enough permissions on one of the agent pools.")).build();
    }
    try {
        myAgentPoolManager.moveAgentTypesToPool(input.getTargetAgentPoolRawId(), agentTypes);
    } catch (NoSuchAgentPoolException e) {
        return result.error(new EntityNotFoundGraphQLError("Target pool does not exist.")).build();
    } catch (PoolQuotaExceededException e) {
        LOG.debug(e.getMessage());
        return result.error(new OperationFailedGraphQLError("Target pool does not accept agents.")).build();
    } catch (AgentTypeCannotBeMovedException e) {
        LOG.debug(e.getMessage());
        return result.error(new OperationFailedGraphQLError("One of the selected agents can not be moved.")).build();
    }
    List<Agent> agents = new ArrayList<>();
    for (Integer agentId : input.getAgentRawIds()) {
        SBuildAgent agent = myBuildAgentManager.findAgentById(agentId, true);
        if (agent == null) {
            continue;
        }
        agents.add(new Agent(agent));
    }
    // should not be null at this stage
    AgentPool updatedTargetPool = myAgentPoolManager.findAgentPoolById(input.getTargetAgentPoolRawId());
    BulkMoveAgentToAgentsPoolPayload payload = new BulkMoveAgentToAgentsPoolPayload(agents, new jetbrains.buildServer.server.graphql.model.agentPool.AgentPool(updatedTargetPool));
    return result.data(payload).build();
}
Also used : Agent(jetbrains.buildServer.server.graphql.model.Agent) DataFetcherResult(graphql.execution.DataFetcherResult) OperationFailedGraphQLError(jetbrains.buildServer.server.graphql.util.OperationFailedGraphQLError) EntityNotFoundGraphQLError(jetbrains.buildServer.server.graphql.util.EntityNotFoundGraphQLError) jetbrains.buildServer.server.graphql.model.mutation.agentPool(jetbrains.buildServer.server.graphql.model.mutation.agentPool) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) Used(jetbrains.buildServer.Used) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with AuthorityHolder

use of jetbrains.buildServer.serverSide.auth.AuthorityHolder in project teamcity-rest by JetBrains.

the class AgentPoolMutation method unassignProjectFromAgentPool.

@Used("graphql")
@NotNull
public DataFetcherResult<UnassignProjectFromAgentPoolPayload> unassignProjectFromAgentPool(@NotNull UnassignProjectFromAgentPoolInput input) {
    DataFetcherResult.Builder<UnassignProjectFromAgentPoolPayload> result = DataFetcherResult.newResult();
    SProject project = myProjectManager.findProjectByExternalId(input.getProjectRawId());
    if (project == null) {
        return result.error(new EntityNotFoundGraphQLError("Project with given id does not exist.")).build();
    }
    AuthorityHolder authorityHolder = mySecurityContext.getAuthorityHolder();
    boolean canRemoveThisProject = AuthUtil.hasPermissionToManageAgentPoolsWithProject(authorityHolder, project.getProjectId());
    boolean thereAreOtherAssociatedPools = false;
    if (canRemoveThisProject) {
        // let's count other pools iff we are sure that we can potentially remove given project.
        thereAreOtherAssociatedPools = myAgentPoolManager.getAgentPoolsWithProject(project.getProjectId()).stream().map(poolId -> myAgentPoolManager.findAgentPoolById(poolId)).filter(Objects::nonNull).filter(pool -> !pool.isProjectPool()).count() > 1;
    }
    if (!canRemoveThisProject || !thereAreOtherAssociatedPools) {
        if (!canRemoveThisProject) {
            return result.error(new OperationFailedGraphQLError("Can't unassign project, not enough permissions.")).build();
        }
        return result.error(new OperationFailedGraphQLError("Can't unassign project, there are no other pools associated with this project.")).build();
    }
    Set<String> projectsToDisassociate;
    if (input.isRecursive()) {
        projectsToDisassociate = new HashSet<>();
        projectsToDisassociate.add(project.getProjectId());
        project.getProjects().stream().map(p -> p.getProjectId()).forEach(projectsToDisassociate::add);
    } else {
        projectsToDisassociate = Collections.singleton(project.getProjectId());
    }
    try {
        myAgentPoolManager.dissociateProjectsFromPool(input.getAgentPoolRawId(), projectsToDisassociate);
    } catch (NoSuchAgentPoolException e) {
        return result.error(new EntityNotFoundGraphQLError("Agent pool with given id does not exist.")).build();
    }
    AgentPool agentPool = myAgentPoolManager.findAgentPoolById(input.getAgentPoolRawId());
    if (agentPool == null) {
        LOG.warn(String.format("Agent pool with id=%d is missing after associating project id=%s", input.getAgentPoolRawId(), project.getProjectId()));
        return result.error(new UnexpectedServerGraphQLError("Agent pool with given id could not be found after operation.")).build();
    }
    return result.data(new UnassignProjectFromAgentPoolPayload(new Project(project), new jetbrains.buildServer.server.graphql.model.agentPool.AgentPool(agentPool))).build();
}
Also used : DataFetchingEnvironment(graphql.schema.DataFetchingEnvironment) CloudClientEx(jetbrains.buildServer.clouds.CloudClientEx) EntityNotFoundGraphQLError(jetbrains.buildServer.server.graphql.util.EntityNotFoundGraphQLError) UnexpectedServerGraphQLError(jetbrains.buildServer.server.graphql.util.UnexpectedServerGraphQLError) java.util(java.util) CloudProfile(jetbrains.buildServer.clouds.CloudProfile) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) BooleanUtils(org.apache.commons.lang3.BooleanUtils) jetbrains.buildServer.serverSide.agentPools(jetbrains.buildServer.serverSide.agentPools) DataFetcherResult(graphql.execution.DataFetcherResult) jetbrains.buildServer.server.graphql.model.mutation.agentPool(jetbrains.buildServer.server.graphql.model.mutation.agentPool) SecurityContext(jetbrains.buildServer.serverSide.auth.SecurityContext) Logger(com.intellij.openapi.diagnostic.Logger) Project(jetbrains.buildServer.server.graphql.model.Project) Agent(jetbrains.buildServer.server.graphql.model.Agent) GraphQLMutationResolver(graphql.kickstart.tools.GraphQLMutationResolver) Used(jetbrains.buildServer.Used) jetbrains.buildServer.serverSide(jetbrains.buildServer.serverSide) jetbrains.buildServer.serverSide.agentTypes(jetbrains.buildServer.serverSide.agentTypes) Collectors(java.util.stream.Collectors) CloudManagerBase(jetbrains.buildServer.clouds.server.CloudManagerBase) jetbrains.buildServer.server.graphql.model.mutation(jetbrains.buildServer.server.graphql.model.mutation) OperationFailedGraphQLError(jetbrains.buildServer.server.graphql.util.OperationFailedGraphQLError) Component(org.springframework.stereotype.Component) Pair(com.intellij.openapi.util.Pair) AuthUtil(jetbrains.buildServer.serverSide.auth.AuthUtil) CloudImage(jetbrains.buildServer.server.graphql.model.CloudImage) NotNull(org.jetbrains.annotations.NotNull) UnexpectedServerGraphQLError(jetbrains.buildServer.server.graphql.util.UnexpectedServerGraphQLError) Project(jetbrains.buildServer.server.graphql.model.Project) DataFetcherResult(graphql.execution.DataFetcherResult) OperationFailedGraphQLError(jetbrains.buildServer.server.graphql.util.OperationFailedGraphQLError) EntityNotFoundGraphQLError(jetbrains.buildServer.server.graphql.util.EntityNotFoundGraphQLError) jetbrains.buildServer.server.graphql.model.mutation.agentPool(jetbrains.buildServer.server.graphql.model.mutation.agentPool) AuthorityHolder(jetbrains.buildServer.serverSide.auth.AuthorityHolder) Used(jetbrains.buildServer.Used) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

AuthorityHolder (jetbrains.buildServer.serverSide.auth.AuthorityHolder)10 NotNull (org.jetbrains.annotations.NotNull)8 SecurityContext (jetbrains.buildServer.serverSide.auth.SecurityContext)4 Pair (com.intellij.openapi.util.Pair)3 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)3 List (java.util.List)3 Collectors (java.util.stream.Collectors)3 CloudClientEx (jetbrains.buildServer.clouds.CloudClientEx)3 CloudProfile (jetbrains.buildServer.clouds.CloudProfile)3 AgentPoolPermissions (jetbrains.buildServer.server.graphql.model.agentPool.AgentPoolPermissions)3 jetbrains.buildServer.serverSide (jetbrains.buildServer.serverSide)3 AuthUtil (jetbrains.buildServer.serverSide.auth.AuthUtil)3 Permission (jetbrains.buildServer.serverSide.auth.Permission)3 Component (org.springframework.stereotype.Component)3 DataFetcherResult (graphql.execution.DataFetcherResult)2 ArrayList (java.util.ArrayList)2 BooleanSupplier (java.util.function.BooleanSupplier)2 Stream (java.util.stream.Stream)2 Used (jetbrains.buildServer.Used)2 CloudImage (jetbrains.buildServer.clouds.CloudImage)2