Java Code Examples for hudson.security.ACL#as()

The following examples show how to use hudson.security.ACL#as() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitLabPersonalAccessTokenCreator.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Saves given credentials in jenkins for domain extracted from server url Adds them to domain
 * extracted from server url (will be generated if no any exists before). Domain will have
 * domain requirements consists of scheme and host from serverUrl arg
 *
 * @param serverUrl to extract (and create if no any) domain
 * @param credentials to save credentials
 */
private void saveCredentials(String serverUrl, final PersonalAccessToken credentials) {
    URI serverUri = URI.create(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL));

    List<DomainSpecification> specifications = asList(
        new SchemeSpecification(serverUri.getScheme()),
        new HostnameSpecification(serverUri.getHost(), null)
    );

    final Domain domain = new Domain(serverUri.getHost(), "GitLab domain (autogenerated)",
        specifications);
    try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
        new SystemCredentialsProvider.StoreImpl().addDomain(domain, credentials);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Can't add credentials for domain", e);
    }
}
 
Example 2
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
private void configureWith(Mapping entries,
    ConfigurationContext context) throws ConfiguratorException {
    // Initialize secret sources
    SecretSource.all().forEach(SecretSource::init);

    // Check input before actually applying changes,
    // so we don't let master in a weird state after some ConfiguratorException has been thrown
    final Mapping clone = entries.clone();
    checkWith(clone, context);

    final ObsoleteConfigurationMonitor monitor = ObsoleteConfigurationMonitor.get();
    monitor.reset();
    context.clearListeners();
    context.addListener(monitor::record);
    try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
        invokeWith(entries, (configurator, config) -> configurator.configure(config, context));
    }
}
 
Example 3
Source File: TokenReloadAction.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public void doIndex(StaplerRequest request, StaplerResponse response) throws IOException {
    String token = getReloadTokenProperty();

    if (Strings.isNullOrEmpty(token)) {
        response.sendError(404);
        LOGGER.warning("Configuration reload via token is not enabled");
    } else {
        String requestToken = getRequestToken(request);

        if (token.equals(requestToken)) {
            LOGGER.info("Configuration reload triggered via token");

            try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
                ConfigurationAsCode.get().configure();
            }
        } else {
            response.sendError(401);
            LOGGER.warning("Invalid token received, not reloading configuration");
        }
    }
}
 
Example 4
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Nonnull
@Override
public List<Credentials> getCredentials(@Nonnull Domain domain) {
    final List<Credentials> result = new ArrayList<>(1);
    if (domain.equals(FolderPropertyImpl.this.domain)) {
        final User proxyUser = User.get(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)) {
                            result.addAll(filter(s.getCredentials(d), withId(getId())));
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider.StoreImpl#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
 
Example 5
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
/**
 * Get all {@link AbstractFolder}s in the system
 *
 * @return full names of all {@link AbstractFolder}s in the system
 */
@GET
@Nonnull
@Restricted(NoExternalUse.class)
public JSONArray doGetAllFolders() {
    Jenkins jenkins = Jenkins.get();
    jenkins.checkPermission(Jenkins.ADMINISTER);
    List<AbstractFolder> folders;

    try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
        folders = jenkins.getAllItems(AbstractFolder.class);
    }

    return JSONArray.fromObject(folders.stream().map(AbstractItem::getFullName).collect(Collectors.toList()));
}
 
Example 6
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
/**
 * Get all {@link Computer}s in the system
 *
 * @return all Computers in the system
 */
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public List<Computer> getAllComputers() {
    Jenkins jenkins = Jenkins.get();
    jenkins.checkPermission(Jenkins.ADMINISTER);
    Computer[] computers;

    try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
        computers = jenkins.getComputers();
    }

    return Arrays.asList(computers);
}
 
Example 7
Source File: ConfigurationAsCodeTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("config.yml")
public void configurationImportTest() {
    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("admin"))) {
        assertTrue(j.jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("user1"))) {
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(j.jenkins.hasPermission(Jenkins.ADMINISTER));

        assertTrue(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.CONFIGURE));
        assertFalse(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.DELETE));
    }
}
 
Example 8
Source File: ConfigurationAsCodeTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("config3.yml")
public void configurationImportWithHumanReadableTest() {
    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("admin"))) {
        assertTrue(j.jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getOrCreateByIdOrFullName("user1"))) {
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(j.jenkins.hasPermission(Jenkins.ADMINISTER));

        assertTrue(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.CONFIGURE));
        assertFalse(Objects.requireNonNull(j.jenkins.getComputer("agent1")).hasPermission(Computer.DELETE));
    }
}
 
Example 9
Source File: RestartSurvivabilityTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
private void checkConfiguration() {
    Jenkins jenkins = Jenkins.get();
    try (ACLContext ignored = ACL.as(User.getById("admin", true))) {
        assertTrue(jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getById("user1", true))) {
        Folder folder = (Folder) jenkins.getItem("folder");
        assertNotNull(folder);
        assertTrue(jenkins.hasPermission(Jenkins.READ));
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(folder.hasPermission(Item.CONFIGURE));
        assertFalse(jenkins.hasPermission(Jenkins.ADMINISTER));

        Computer computer = jenkins.getComputer("foo");
        assertNotNull(computer);
        assertTrue(computer.hasPermission(Computer.CONFIGURE));
        assertFalse(computer.hasPermission(Computer.DELETE));
    }

    AuthorizationStrategy a = Jenkins.get().getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    assertEquals(strategy.getGlobalRoles().size(), 2);
    assertEquals(strategy.getFolderRoles().size(), 1);
    assertEquals(strategy.getAgentRoles().size(), 1);
}
 
Example 10
Source File: FolderBasedAuthorizationStrategyTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
public void permissionTest() {
    Jenkins jenkins = jenkinsRule.jenkins;

    try (ACLContext ignored = ACL.as(admin)) {
        assertTrue(jenkins.hasPermission(Jenkins.ADMINISTER));
        assertTrue(child3.hasPermission(Item.CONFIGURE));
        assertTrue(job1.hasPermission(Item.READ));
        assertTrue(job2.hasPermission(Item.CREATE));
    }

    try (ACLContext ignored = ACL.as(user1)) {
        assertTrue(jenkins.hasPermission(Permission.READ));
        assertTrue(root.hasPermission(Item.READ));
        assertTrue(job1.hasPermission(Item.READ));
        assertTrue(job2.hasPermission(Item.READ));

        assertFalse(job1.hasPermission(Item.CREATE));
        assertFalse(job1.hasPermission(Item.DELETE));
        assertFalse(job1.hasPermission(Item.CONFIGURE));
        assertFalse(job2.hasPermission(Item.CREATE));
        assertFalse(job2.hasPermission(Item.CONFIGURE));
    }

    try (ACLContext ignored = ACL.as(user2)) {
        assertTrue(jenkins.hasPermission(Permission.READ));
        assertTrue(child2.hasPermission(Item.READ));
        assertTrue(child1.hasPermission(Item.READ));
        assertTrue(job2.hasPermission(Item.CONFIGURE));
        assertFalse(job1.hasPermission(Item.CONFIGURE));
    }
}
 
Example 11
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@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;
}
 
Example 12
Source File: PipelineTriggerService.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
public boolean isUpstreamBuildVisibleByDownstreamBuildAuth(@Nonnull WorkflowJob upstreamPipeline, @Nonnull WorkflowJob downstreamPipeline) {
    Authentication downstreamPipelineAuth = Tasks.getAuthenticationOf(downstreamPipeline);

    // see https://github.com/jenkinsci/jenkins/blob/jenkins-2.176.2/core/src/main/java/jenkins/triggers/ReverseBuildTrigger.java#L132
    // jenkins.triggers.ReverseBuildTrigger#shouldTrigger
    try (ACLContext ignored = ACL.as(downstreamPipelineAuth)) {
        WorkflowJob upstreamPipelineObtainedAsImpersonated = getItemByFullName(upstreamPipeline.getFullName(), WorkflowJob.class);
        boolean result = upstreamPipelineObtainedAsImpersonated != null;
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "isUpstreamBuildVisibleByDownstreamBuildAuth(upstreamPipeline: {0}, downstreamPipeline: {1}): downstreamPipelineAuth: {2}, upstreamPipelineObtainedAsImpersonated:{3}, result: {4}",
                    new Object[]{upstreamPipeline.getFullName(), downstreamPipeline.getFullName(), downstreamPipelineAuth, upstreamPipelineObtainedAsImpersonated, result});
        }
        return result;
    }
}
 
Example 13
Source File: GHBranchSubscriber.java    From github-integration-plugin with MIT License 5 votes vote down vote up
static Set<Job> getBranchTriggerJobs(final String repo) {
    final Set<Job> ret = new HashSet<>();

    try (ACLContext ignored = ACL.as(SYSTEM)) {
        List<Job> jobs = Jenkins.getInstance().getAllItems(Job.class);
        ret.addAll(FluentIterableWrapper.from(jobs)
                .filter(isBuildable())
                .filter(withBranchTrigger())
                .filter(withBranchTriggerRepo(repo))
                .toSet()
        );
    }

    return ret;
}
 
Example 14
Source File: CauseActionConverter.java    From DotCi with MIT License 5 votes vote down vote up
@Override
public CauseAction decode(final Class targetClass, final Object fromDBObject, final MappedField optionalExtraInfo) {
    try (ACLContext _ = ACL.as(Jenkins.ANONYMOUS)) {
        if (fromDBObject == null) return null;

        final List causes = new ArrayList();
        final List rawList = (List) ((DBObject) fromDBObject).get("causes");
        for (final Object obj : rawList) {
            final DBObject dbObj = (DBObject) obj;
            final Object cause = getMapper().fromDBObject(optionalExtraInfo.getSubClass(), dbObj, getMapper().createEntityCache());
            causes.add(cause);
        }
        return new CauseAction(causes);
    }
}
 
Example 15
Source File: GitLabMergeRequestCommentTrigger.java    From gitlab-branch-source-plugin with MIT License 4 votes vote down vote up
@Override
public void isMatch() {
    if (getPayload().getObjectAttributes().getNoteableType()
        .equals(NoteEvent.NoteableType.MERGE_REQUEST)) {
        Integer mergeRequestId = getPayload().getMergeRequest().getIid();
        final Pattern mergeRequestJobNamePattern = Pattern
            .compile("^MR-" + mergeRequestId + "\\b.*$",
                Pattern.CASE_INSENSITIVE);
        final String commentBody = getPayload().getObjectAttributes().getNote();
        final String commentUrl = getPayload().getObjectAttributes().getUrl();
        try (ACLContext ctx = ACL.as(ACL.SYSTEM)) {
            boolean jobFound = false;
            for (final SCMSourceOwner owner : SCMSourceOwners.all()) {
                LOGGER.log(Level.FINEST, String.format("Source Owner: %s", owner.getFullDisplayName()));
                // This is a hack to skip owners which are children of a SCMNavigator
                if (owner.getFullDisplayName().contains(" ยป ")) {
                    continue;
                }
                for (SCMSource source : owner.getSCMSources()) {
                    if (!(source instanceof GitLabSCMSource)) {
                        continue;
                    }
                    GitLabSCMSource gitLabSCMSource = (GitLabSCMSource) source;
                    final GitLabSCMSourceContext sourceContext = new GitLabSCMSourceContext(
                        null, SCMHeadObserver.none())
                        .withTraits(gitLabSCMSource.getTraits());
                    if (!sourceContext.mrCommentTriggerEnabled()) {
                        continue;
                    }
                    if (gitLabSCMSource.getProjectId() == getPayload().getMergeRequest()
                        .getTargetProjectId() && isTrustedMember(gitLabSCMSource, sourceContext.onlyTrustedMembersCanTrigger())) {
                        for (Job<?, ?> job : owner.getAllJobs()) {
                            if (mergeRequestJobNamePattern.matcher(job.getName()).matches()) {
                                String expectedCommentBody = sourceContext.getCommentBody();
                                Pattern pattern = Pattern.compile(expectedCommentBody,
                                    Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
                                if (commentBody == null || pattern.matcher(commentBody)
                                    .matches()) {
                                    ParameterizedJobMixIn.scheduleBuild2(job, 0,
                                        new CauseAction(
                                            new GitLabMergeRequestCommentCause(commentUrl)));
                                    LOGGER.log(Level.INFO,
                                        "Triggered build for {0} due to MR comment on {1}",
                                        new Object[]{
                                            job.getFullName(),
                                            getPayload().getProject().getPathWithNamespace()
                                        }
                                    );
                                } else {
                                    LOGGER.log(Level.INFO,
                                        "MR comment does not match the trigger build string ({0}) for {1}",
                                        new Object[]{expectedCommentBody, job.getFullName()}
                                    );
                                }
                                break;
                            }
                            jobFound = true;
                        }
                    }
                }
            }
            if (!jobFound) {
                LOGGER.log(Level.INFO, "MR comment on {0} did not match any job",
                    new Object[]{
                        getPayload().getProject().getPathWithNamespace()
                    }
                );
            }
        }
    }
}
 
Example 16
Source File: PermissionAssert.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
private static boolean hasPermission(User user, final AccessControlled item, final Permission p) {
    try (ACLContext c = ACL.as(user)) {
        return item.hasPermission(p);
    }
}