Search in sources :

Example 6 with AuthorizationFailedException

use of jetbrains.buildServer.server.rest.errors.AuthorizationFailedException in project teamcity-rest by JetBrains.

the class CompatibilityPolicy method applyTo.

public void applyTo(@NotNull final SBuildAgent agent, @NotNull final ServiceLocator serviceLocator) {
    if (!AuthUtil.canViewAgentDetails(serviceLocator.getSingletonService(SecurityContext.class).getAuthorityHolder(), agent)) {
        // can get pool name i from the error message if we do not check this
        throw new AuthorizationFailedException("No permission to view agent details");
    }
    final AgentTypeManager agentTypeManager = serviceLocator.getSingletonService(AgentTypeManager.class);
    final int agentTypeId = agent.getAgentTypeId();
    final String valueUp = policy.trim().toLowerCase();
    if (POLICY_ANY.equals(valueUp)) {
        agentTypeManager.setRunConfigurationPolicy(agentTypeId, BuildAgentManager.RunConfigurationPolicy.ALL_COMPATIBLE_CONFIGURATIONS);
    } else if (POLICY_SELECTED.equals(valueUp)) {
        if (buildTypes == null) {
            buildTypes = new BuildTypes();
        }
        List<jetbrains.buildServer.BuildType> buildTypesFromPosted = buildTypes.getBuildTypesFromPosted(serviceLocator);
        BuildAgentManager.RunConfigurationPolicy previousPolicy = agentTypeManager.getRunConfigurationPolicy(agentTypeId);
        Set<String> previous_canRunConfigurations = agentTypeManager.getCanRunConfigurations(agentTypeId);
        try {
            agentTypeManager.setRunConfigurationPolicy(agentTypeId, BuildAgentManager.RunConfigurationPolicy.SELECTED_COMPATIBLE_CONFIGURATIONS);
            agentTypeManager.excludeRunConfigurationsFromAllowed(agentTypeId, previous_canRunConfigurations.toArray(new String[0]));
            agentTypeManager.includeRunConfigurationsToAllowed(agentTypeId, buildTypesFromPosted.stream().map(jetbrains.buildServer.BuildType::getBuildTypeId).toArray(String[]::new));
        } catch (Exception e) {
            agentTypeManager.setRunConfigurationPolicy(agentTypeId, previousPolicy);
            agentTypeManager.excludeRunConfigurationsFromAllowed(agentTypeId, agentTypeManager.getCanRunConfigurations(agentTypeId).toArray(new String[0]));
            agentTypeManager.includeRunConfigurationsToAllowed(agentTypeId, previous_canRunConfigurations.toArray(new String[0]));
            throw e;
        }
    } else {
        throw new BadRequestException("Unexpected policy '" + policy + "', expected '" + POLICY_ANY + "' or '" + POLICY_SELECTED + "'");
    }
}
Also used : Set(java.util.Set) BuildTypes(jetbrains.buildServer.server.rest.model.buildType.BuildTypes) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) SecurityContext(jetbrains.buildServer.serverSide.auth.SecurityContext) AgentTypeManager(jetbrains.buildServer.serverSide.agentTypes.AgentTypeManager) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) List(java.util.List) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException)

Example 7 with AuthorizationFailedException

use of jetbrains.buildServer.server.rest.errors.AuthorizationFailedException in project teamcity-rest by JetBrains.

the class BuildTypeRequest method serveBuildTypeTemplate.

/**
 * @Deprecated Use .../templates instead
 */
@GET
@Path("/{btLocator}/template")
@Produces({ "application/xml", "application/json" })
@ApiOperation(hidden = true, value = "Use .../templates instead")
public BuildType serveBuildTypeTemplate(@ApiParam(format = LocatorName.BUILD_TYPE) @PathParam("btLocator") String buildTypeLocator, @QueryParam("fields") String fields) {
    SBuildType buildType = myBuildTypeFinder.getBuildType(null, buildTypeLocator, true);
    final BuildTypeTemplate template;
    try {
        template = buildType.getTemplate();
    } catch (BuildTypeTemplateNotFoundException e) {
        throw new AuthorizationFailedException("The template is not accessible. Cross-hierarchy template use?");
    }
    if (template == null) {
        // todo: how to report it duly?
        throw new NotFoundException("No template associated.");
    }
    return new BuildType(new BuildTypeOrTemplate(template), new Fields(fields), myBeanContext);
}
Also used : BuildTypeOrTemplate(jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 8 with AuthorizationFailedException

use of jetbrains.buildServer.server.rest.errors.AuthorizationFailedException in project teamcity-rest by JetBrains.

the class UserRequest method createToken.

@POST
@Path("/{userLocator}/tokens")
@Produces({ "application/xml", "application/json" })
@ApiOperation(value = "Create a new authentication token for the matching user.", nickname = "addUserToken")
public Token createToken(Token token, @PathParam("userLocator") String userLocator, @QueryParam("fields") String fields) {
    if (token.getName() == null) {
        throw new BadRequestException("name cannot be empty");
    }
    if (TeamCityProperties.getBooleanOrTrue(UserFinder.REST_CHECK_ADDITIONAL_PERMISSIONS_ON_USERS_AND_GROUPS)) {
        myUserFinder.checkViewAllUsersPermission();
    }
    final TokenAuthenticationModel tokenAuthenticationModel = myBeanContext.getSingletonService(TokenAuthenticationModel.class);
    final SUser user = myUserFinder.getItem(userLocator, true);
    try {
        final AuthenticationToken authenticationToken;
        if (token.getPermissionRestrictions() != null) {
            final List<PermissionRestriction> permissionRestrictions = token.getPermissionRestrictions().myPermissionRestrictions;
            if (permissionRestrictions == null) {
                throw new IllegalArgumentException("Malformed permission restrictions");
            }
            final Map<RoleScope, Permissions> restrictions = new HashMap<>();
            for (PermissionRestriction permissionRestriction : permissionRestrictions) {
                final RoleScope roleScope;
                if (BooleanUtils.isTrue(permissionRestriction.isGlobalScope)) {
                    roleScope = RoleScope.globalScope();
                } else if (permissionRestriction.project != null && permissionRestriction.project.id != null) {
                    final SProject project = myBeanContext.getSingletonService(ProjectManager.class).findProjectByExternalId(permissionRestriction.project.id);
                    if (project == null) {
                        throw new NotFoundException("Project not found for external id [" + permissionRestriction.project.id + "]");
                    }
                    roleScope = RoleScope.projectScope(project.getProjectId());
                } else {
                    throw new IllegalArgumentException("Malformed permission restrictions, either isGlobalScope should be set to true or project should not be null");
                }
                if (permissionRestriction.permission == null || permissionRestriction.permission.id == null) {
                    throw new IllegalArgumentException("Permission should not be null");
                }
                try {
                    final Permission permission = Permission.valueOf(permissionRestriction.permission.id.toUpperCase());
                    if (roleScope.isGlobal()) {
                        if (!user.isPermissionGrantedGlobally(permission)) {
                            throw new AuthorizationFailedException("User don't have " + permission + " to be restricted globally");
                        }
                    } else {
                        if (!(user.isPermissionGrantedGlobally(permission) || user.isPermissionGrantedForProject(roleScope.getProjectId(), permission))) {
                            throw new AuthorizationFailedException("User don't have permission " + permission + " to be restricted on project [" + roleScope.getProjectId() + "]");
                        }
                    }
                    restrictions.merge(roleScope, new Permissions(permission), Permissions::mergeWith);
                } catch (IllegalArgumentException e) {
                    throw new BadRequestException("Permission not found for input [" + permissionRestriction.permission.name + "]");
                }
            }
            if (permissionRestrictions.isEmpty()) {
                throw new BadRequestException("Malformed permission restrictions");
            }
            authenticationToken = tokenAuthenticationModel.createToken(user.getId(), token.getName(), token.getExpirationTime(), new AuthenticationToken.PermissionsRestriction(restrictions));
        } else {
            authenticationToken = tokenAuthenticationModel.createToken(user.getId(), token.getName(), token.getExpirationTime());
        }
        return new Token(authenticationToken, authenticationToken.getValue(), new Fields(fields), myBeanContext);
    } catch (AuthenticationTokenStorage.CreationException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) SUser(jetbrains.buildServer.users.SUser) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) SProject(jetbrains.buildServer.serverSide.SProject) Fields(jetbrains.buildServer.server.rest.model.Fields) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) Permission(jetbrains.buildServer.serverSide.auth.Permission) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) ApiOperation(io.swagger.annotations.ApiOperation)

Example 9 with AuthorizationFailedException

use of jetbrains.buildServer.server.rest.errors.AuthorizationFailedException in project teamcity-rest by JetBrains.

the class DebugRequest method setCurrentSessionMaxInactiveInterval.

@PUT
@Path("/currentRequest/session/maxInactiveSeconds")
@Consumes("text/plain")
@Produces("text/plain")
public String setCurrentSessionMaxInactiveInterval(String maxInactiveSeconds, @Context HttpServletRequest request, @Context @NotNull final BeanContext beanContext) {
    if (!TeamCityProperties.getBoolean("rest.debug.currentRequest.session.maxInactiveSeconds.allowChange")) {
        throw new AuthorizationFailedException("Set " + "rest.debug.currentRequest.session.maxInactiveSeconds.allowChange" + " server internal property to enable request");
    }
    HttpSession session = request.getSession();
    session.setMaxInactiveInterval(Integer.valueOf(maxInactiveSeconds));
    return String.valueOf(session.getMaxInactiveInterval());
}
Also used : AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) HttpSession(javax.servlet.http.HttpSession)

Aggregations

AuthorizationFailedException (jetbrains.buildServer.server.rest.errors.AuthorizationFailedException)9 ApiOperation (io.swagger.annotations.ApiOperation)4 NotFoundException (jetbrains.buildServer.server.rest.errors.NotFoundException)4 Fields (jetbrains.buildServer.server.rest.model.Fields)3 SecurityContext (jetbrains.buildServer.serverSide.auth.SecurityContext)3 BadRequestException (jetbrains.buildServer.server.rest.errors.BadRequestException)2 BuildTypeOrTemplate (jetbrains.buildServer.server.rest.util.BuildTypeOrTemplate)2 SBuildAgent (jetbrains.buildServer.serverSide.SBuildAgent)2 SProject (jetbrains.buildServer.serverSide.SProject)2 Permission (jetbrains.buildServer.serverSide.auth.Permission)2 NotNull (org.jetbrains.annotations.NotNull)2 Logger (com.intellij.openapi.diagnostic.Logger)1 java.util (java.util)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 HttpSession (javax.servlet.http.HttpSession)1 BuildProject (jetbrains.buildServer.BuildProject)1 ParametersProvider (jetbrains.buildServer.parameters.ParametersProvider)1