Search in sources :

Example 1 with ACLContext

use of hudson.security.ACLContext in project blueocean-plugin by jenkinsci.

the class BitbucketServerEndpointContainer method create.

@Override
public ScmServerEndpoint create(JSONObject request) {
    try {
        Jenkins.get().checkPermission(Item.CREATE);
    } catch (Exception e) {
        throw new ServiceException.ForbiddenException("User does not have permission to create repository", e);
    }
    List<ErrorMessage.Error> errors = new LinkedList<>();
    // Validate name
    final String name = (String) request.get(ScmServerEndpoint.NAME);
    if (StringUtils.isBlank(name)) {
        errors.add(new ErrorMessage.Error(ScmServerEndpoint.NAME, ErrorMessage.Error.ErrorCodes.MISSING.toString(), ScmServerEndpoint.NAME + " is required"));
    }
    String url = (String) request.get(ScmServerEndpoint.API_URL);
    final BitbucketEndpointConfiguration endpointConfiguration = BitbucketEndpointConfiguration.get();
    if (StringUtils.isBlank(url)) {
        errors.add(new ErrorMessage.Error(ScmServerEndpoint.API_URL, ErrorMessage.Error.ErrorCodes.MISSING.toString(), ScmServerEndpoint.API_URL + " is required"));
    } else {
        try {
            String version = BitbucketServerApi.getVersion(url);
            if (!BitbucketServerApi.isSupportedVersion(version)) {
                errors.add(new ErrorMessage.Error(BitbucketServerEndpoint.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), Messages.bbserver_version_validation_error(version, BitbucketServerApi.MINIMUM_SUPPORTED_VERSION)));
            } else {
                // validate presence of endpoint with same name
                url = BitbucketEndpointConfiguration.normalizeServerUrl(url);
                for (AbstractBitbucketEndpoint endpoint : endpointConfiguration.getEndpoints()) {
                    if (url.equals(endpoint.getServerUrl())) {
                        errors.add(new ErrorMessage.Error(ScmServerEndpoint.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), ScmServerEndpoint.API_URL + " already exists"));
                        break;
                    }
                }
            }
        } catch (ServiceException e) {
            errors.add(new ErrorMessage.Error(BitbucketServerEndpoint.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), StringUtils.isBlank(e.getMessage()) ? "Invalid URL" : e.getMessage()));
        }
    }
    if (!errors.isEmpty()) {
        throw new ServiceException.BadRequestException(new ErrorMessage(400, "Failed to create Bitbucket server endpoint").addAll(errors));
    }
    final com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketServerEndpoint endpoint = new com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketServerEndpoint(name, url, false, null);
    try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
        // We need to escalate privilege to add user defined endpoint to
        endpointConfiguration.addEndpoint(endpoint);
    }
    return new BitbucketServerEndpoint(endpoint, this);
}
Also used : AbstractBitbucketEndpoint(com.cloudbees.jenkins.plugins.bitbucket.endpoints.AbstractBitbucketEndpoint) ServiceException(io.jenkins.blueocean.commons.ServiceException) LinkedList(java.util.LinkedList) ACLContext(hudson.security.ACLContext) ServiceException(io.jenkins.blueocean.commons.ServiceException) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) BitbucketEndpointConfiguration(com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration)

Example 2 with ACLContext

use of hudson.security.ACLContext in project blueocean-plugin by jenkinsci.

the class BlueOceanCredentialsProvider method getCredentials.

@Nonnull
public <C extends Credentials> List<C> getCredentials(@Nonnull final Class<C> type, @Nullable ItemGroup itemGroup, @Nullable Authentication authentication, @Nonnull List<DomainRequirement> domainRequirements) {
    final List<C> result = new ArrayList<>();
    final FolderPropertyImpl prop = propertyOf(itemGroup);
    if (prop != null && prop.domain.test(domainRequirements)) {
        final User proxyUser = User.get(prop.getUser(), false, Collections.emptyMap());
        if (proxyUser != null) {
            try (ACLContext ignored = ACL.as(proxyUser.impersonate())) {
                for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
                    for (Domain d : s.getDomains()) {
                        if (d.test(PROXY_REQUIREMENT)) {
                            for (Credentials c : filter(s.getCredentials(d), withId(prop.getId()))) {
                                if (type.isInstance(c)) {
                                    result.add((C) c);
                                }
                            }
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
Also used : UsernameNotFoundException(org.acegisecurity.userdetails.UsernameNotFoundException) ACLContext(hudson.security.ACLContext) User(hudson.model.User) ArrayList(java.util.ArrayList) CredentialsStore(com.cloudbees.plugins.credentials.CredentialsStore) Domain(com.cloudbees.plugins.credentials.domains.Domain) Credentials(com.cloudbees.plugins.credentials.Credentials) IdCredentials(com.cloudbees.plugins.credentials.common.IdCredentials) Nonnull(javax.annotation.Nonnull)

Example 3 with ACLContext

use of hudson.security.ACLContext in project blueocean-plugin by jenkinsci.

the class GithubServerContainer method create.

@CheckForNull
public ScmServerEndpoint create(@JsonBody JSONObject request) {
    try {
        Jenkins.get().checkPermission(Item.CREATE);
    } catch (Exception e) {
        throw new ServiceException.ForbiddenException("User does not have permission to create repository.", e);
    }
    List<ErrorMessage.Error> errors = new LinkedList<>();
    // Validate name
    final String name = (String) request.get(GithubServer.NAME);
    if (StringUtils.isEmpty(name)) {
        errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.NAME + " is required"));
    } else {
        GithubServer byName = findByName(name);
        if (byName != null) {
            errors.add(new ErrorMessage.Error(GithubServer.NAME, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.NAME + " already exists for server at '" + byName.getApiUrl() + "'"));
        }
    }
    // Validate url
    final String url = (String) request.get(GithubServer.API_URL);
    if (StringUtils.isEmpty(url)) {
        errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.MISSING.toString(), GithubServer.API_URL + " is required"));
    } else {
        Endpoint byUrl = GitHubConfiguration.get().findEndpoint(url);
        if (byUrl != null) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + byUrl.getName() + "'"));
        }
    }
    if (StringUtils.isNotEmpty(url)) {
        // Validate that the URL represents a GitHub API endpoint
        try {
            HttpURLConnection connection = HttpRequest.get(url).connect();
            if (connection.getHeaderField("X-GitHub-Request-Id") == null) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_SERVER));
            } else {
                boolean isGithubCloud = false;
                boolean isGithubEnterprise = false;
                try {
                    InputStream inputStream;
                    int code = connection.getResponseCode();
                    if (200 <= code && code < 300) {
                        inputStream = HttpRequest.getInputStream(connection);
                    } else {
                        inputStream = HttpRequest.getErrorStream(connection);
                    }
                    TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
                    };
                    Map<String, String> responseBody = GithubScm.getMappingObjectReader().forType(typeRef).readValue(inputStream);
                    isGithubCloud = code == 200 && responseBody.containsKey("current_user_url");
                    isGithubEnterprise = code == 401 && responseBody.containsKey("message");
                } catch (IllegalArgumentException | IOException ioe) {
                    LOGGER.log(Level.INFO, "Could not parse response body from Github");
                }
                if (!isGithubCloud && !isGithubEnterprise) {
                    errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), ERROR_MESSAGE_INVALID_APIURL));
                }
            }
        } catch (Throwable e) {
            errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.toString()));
            LOGGER.log(Level.INFO, "Could not connect to Github", e);
        }
    }
    if (errors.isEmpty()) {
        try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
            // We need to escalate privilege to add user defined endpoint to
            GitHubConfiguration config = GitHubConfiguration.get();
            String sanitizedUrl = discardQueryString(url);
            Endpoint endpoint = new Endpoint(sanitizedUrl, name);
            if (!config.addEndpoint(endpoint)) {
                errors.add(new ErrorMessage.Error(GithubServer.API_URL, ErrorMessage.Error.ErrorCodes.ALREADY_EXISTS.toString(), GithubServer.API_URL + " is already registered as '" + endpoint.getName() + "'"));
            } else {
                return new GithubServer(endpoint, getLink());
            }
        }
    }
    ErrorMessage message = new ErrorMessage(400, "Failed to create GitHub server");
    message.addAll(errors);
    throw new ServiceException.BadRequestException(message);
}
Also used : GitHubConfiguration(org.jenkinsci.plugins.github_branch_source.GitHubConfiguration) HashMap(java.util.HashMap) HttpURLConnection(java.net.HttpURLConnection) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) TypeReference(com.fasterxml.jackson.core.type.TypeReference) InputStream(java.io.InputStream) IOException(java.io.IOException) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) LinkedList(java.util.LinkedList) Endpoint(org.jenkinsci.plugins.github_branch_source.Endpoint) ScmServerEndpoint(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint) ACLContext(hudson.security.ACLContext) ServiceException(io.jenkins.blueocean.commons.ServiceException) JSONObject(net.sf.json.JSONObject) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) CheckForNull(javax.annotation.CheckForNull)

Example 4 with ACLContext

use of hudson.security.ACLContext in project blueocean-plugin by jenkinsci.

the class JwtAuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    if (!shouldApply(request)) {
        chain.doFilter(req, rsp);
        return;
    }
    Authentication token = verifyToken(request);
    if (token == null) {
        // no JWT token found, which is fine --- we just assume the request is authenticated in other means
        // Some routes that require valid JWT token will check for the presence of JWT token during Stapler
        // request routing, not here.
        chain.doFilter(req, rsp);
        return;
    }
    // create a new context and set it to holder to not clobber existing context
    try (ACLContext ctx = ACL.as2(token)) {
        request.setAttribute(JWT_TOKEN_VALIDATED, true);
        chain.doFilter(req, rsp);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ACLContext(hudson.security.ACLContext) Authentication(org.springframework.security.core.Authentication)

Aggregations

ACLContext (hudson.security.ACLContext)4 ErrorMessage (io.jenkins.blueocean.commons.ErrorMessage)2 ServiceException (io.jenkins.blueocean.commons.ServiceException)2 LinkedList (java.util.LinkedList)2 AbstractBitbucketEndpoint (com.cloudbees.jenkins.plugins.bitbucket.endpoints.AbstractBitbucketEndpoint)1 BitbucketEndpointConfiguration (com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration)1 Credentials (com.cloudbees.plugins.credentials.Credentials)1 CredentialsStore (com.cloudbees.plugins.credentials.CredentialsStore)1 IdCredentials (com.cloudbees.plugins.credentials.common.IdCredentials)1 Domain (com.cloudbees.plugins.credentials.domains.Domain)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 User (hudson.model.User)1 ScmServerEndpoint (io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 HttpURLConnection (java.net.HttpURLConnection)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 CheckForNull (javax.annotation.CheckForNull)1 Nonnull (javax.annotation.Nonnull)1