Java Code Examples for hudson.security.ACL

The following are top voted examples for showing how to use hudson.security.ACL. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dockerhub-notification-plugin   File: TriggerStore.java   View source code 7 votes vote down vote up
@CheckForNull
public Run<?, ?> getRun() {
    if (StringUtils.isBlank(buildId)) {
        return null;
    }
    final Job<?, ?> job = getJob();
    if (job != null) {
        SecurityContext old = ACL.impersonate(ACL.SYSTEM);
        try {
            return job.getBuild(buildId);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Unable to retrieve run " + jobName + ":" + buildId, e);
        } finally {
            SecurityContextHolder.setContext(old);
        }
    }
    return null;
}
 
Example 2
Project: gitea-plugin   File: GiteaServer.java   View source code 6 votes vote down vote up
/**
 * Looks up the {@link StandardCredentials} to use for auto-management of hooks.
 *
 * @return the credentials or {@code null}.
 */
@CheckForNull
public StandardCredentials credentials() {
    return StringUtils.isBlank(credentialsId) ? null : CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    Jenkins.getActiveInstance(),
                    ACL.SYSTEM,
                    URIRequirementBuilder.fromUri(serverUrl).build()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(GiteaAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
}
 
Example 3
Project: gitea-plugin   File: GiteaServer.java   View source code 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
    Jenkins.getActiveInstance().checkPermission(Jenkins.ADMINISTER);
    StandardListBoxModel result = new StandardListBoxModel();
    serverUrl = GiteaServers.normalizeServerUrl(serverUrl);
    result.includeMatchingAs(
            ACL.SYSTEM,
            Jenkins.getActiveInstance(),
            StandardCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            AuthenticationTokens.matcher(GiteaAuth.class)
    );
    return result;
}
 
Example 4
Project: jenkins-client-plugin   File: ClusterConfig.java   View source code 6 votes vote down vote up
public static ListBoxModel doFillCredentialsIdItems(String credentialsId) {
    if (credentialsId == null) {
        credentialsId = "";
    }

    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
        // Important! Otherwise you expose credentials metadata to random
        // web requests.
        return new StandardListBoxModel()
                .includeCurrentValue(credentialsId);
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeAs(ACL.SYSTEM, Jenkins.getInstance(),
                    OpenShiftTokenCredentials.class)
            // .includeAs(ACL.SYSTEM, Jenkins.getInstance(),
            // StandardUsernamePasswordCredentials.class)
            // .includeAs(ACL.SYSTEM, Jenkins.getInstance(),
            // StandardCertificateCredentials.class)
            // TODO: Make own type for token or use the existing token
            // generator auth type used by sync plugin? or kubernetes?
            .includeCurrentValue(credentialsId);
}
 
Example 5
Project: azure-cli-plugin   File: AzureCLIBuilder.java   View source code 6 votes vote down vote up
public ListBoxModel doFillPrincipalCredentialIdItems(
        @AncestorInPath Item item,
        @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(credentialsId);
        }
    } else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return result.includeCurrentValue(credentialsId);
        }
    }
    List<AzureCredentials> creds = CredentialsProvider.lookupCredentials(AzureCredentials.class, item, ACL.SYSTEM, Collections.<DomainRequirement>emptyList());
    for (AzureCredentials cred
            :
            creds) {
        result.add(cred.getId());
    }
    return result.includeEmptyValue()
            .includeCurrentValue(credentialsId);
}
 
Example 6
Project: Jenkins-Plugin-Examples   File: RetryStepTest.java   View source code 6 votes vote down vote up
@Issue("JENKINS-41276")
@Test
public void abortShouldNotRetry() throws Exception {
    r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "int count = 0; retry(3) { echo 'trying '+(count++); semaphore 'start'; echo 'NotHere' } echo 'NotHere'", true));
    final WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("start/1", b);
    ACL.impersonate(User.get("dev").impersonate(), new Runnable() {
        @Override public void run() {
            b.getExecutor().doStop();
        }
    });
    r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
    r.assertLogContains("trying 0", b);
    r.assertLogContains("Aborted by dev", b);
    r.assertLogNotContains("trying 1", b);
    r.assertLogNotContains("trying 2", b);
    r.assertLogNotContains("NotHere", b);

}
 
Example 7
Project: mirrorgate-jenkins-builds-collector   File: MirrorGatePublisher.java   View source code 6 votes vote down vote up
public ListBoxModel doFillMirrorgateCredentialsIdItems(
        @AncestorInPath Item item,
        @QueryParameter("mirrorgateCredentialsId") String credentialsId) {

    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(credentialsId);
        }
    } else if (!item.hasPermission(Item.EXTENDED_READ)
            && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
        return result.includeCurrentValue(credentialsId);
    }
    return result
            .includeEmptyValue()
            .includeAs(ACL.SYSTEM, item, StandardUsernamePasswordCredentials.class);
}
 
Example 8
Project: gerrit-plugin   File: GerritSCMSource.java   View source code 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(
    @AncestorInPath Item context,
    @QueryParameter String remote,
    @QueryParameter String credentialsId) {
  if (context == null && !Jenkins.getActiveInstance().hasPermission(Jenkins.ADMINISTER)
      || context != null && !context.hasPermission(Item.EXTENDED_READ)) {
    return new StandardListBoxModel().includeCurrentValue(credentialsId);
  }
  return new StandardListBoxModel()
      .includeEmptyValue()
      .includeMatchingAs(
          context instanceof Queue.Task
              ? Tasks.getAuthenticationOf((Queue.Task) context)
              : ACL.SYSTEM,
          context,
          StandardUsernameCredentials.class,
          URIRequirementBuilder.fromUri(remote).build(),
          GitClient.CREDENTIALS_MATCHER)
      .includeCurrentValue(credentialsId);
}
 
Example 9
Project: gitlab-branch-source-plugin   File: GitLabSCMSourceSettings.java   View source code 6 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillCheckoutCredentialsIdItems(@AncestorInPath SCMSourceOwner context, @QueryParameter String connectionName, @QueryParameter String checkoutCredentialsId) {
    if (context == null && !Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ||
            context != null && !context.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(checkoutCredentialsId);
    }

    StandardListBoxModel result = new StandardListBoxModel();
    result.add("- anonymous -", CHECKOUT_CREDENTIALS_ANONYMOUS);
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            SettingsUtils.gitLabConnectionRequirements(connectionName),
            GitClient.CREDENTIALS_MATCHER
    );
}
 
Example 10
Project: CPWR-CodeCoverage   File: CodeCoverageBuilder.java   View source code 6 votes vote down vote up
/**
 * Fills in the Login Credentials selection box with applicable connections.
 * 
 * @param context
 *            filter for login credentials
 * @param credentialsId
 *            existing login credentials; can be null
 * @param project
 *            the Jenkins project
 * 
 * @return login credentials selection
 */
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId,
		@AncestorInPath Item project)
{
	List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM,
			Collections.<DomainRequirement> emptyList());

	ListBoxModel model = new ListBoxModel();
	model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false));

	for (StandardUsernamePasswordCredentials c : creds)
	{
		boolean isSelected = false;
		if (credentialsId != null)
		{
			isSelected = credentialsId.matches(c.getId());
		}

		String description = Util.fixEmptyAndTrim(c.getDescription());
		model.add(new Option(c.getUsername() + (description != null ? " (" + description + ')' : StringUtils.EMPTY), //$NON-NLS-1$
				c.getId(), isSelected));
	}

	return model;
}
 
Example 11
Project: compuware-scm-downloader-plugin   File: PdsConfiguration.java   View source code 6 votes vote down vote up
/**
 * Fills in the Login Credentials selection box with applicable Jenkins credentials.
 * 
 * @param context
 *            filter for credentials
 * @param credentialsId
 *            existing login credentials; can be null
 * @param project
 *            the Jenkins project
 * 
 * @return credential selections
 */
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId, @AncestorInPath Item project)
{
	List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM,
			Collections.<DomainRequirement> emptyList());

	StandardListBoxModel model = new StandardListBoxModel();
	model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false));

	for (StandardUsernamePasswordCredentials c : creds)
	{
		boolean isSelected = false;
		if (credentialsId != null)
		{
			isSelected = credentialsId.matches(c.getId());
		}

		String description = Util.fixEmptyAndTrim(c.getDescription());
		model.add(new Option(c.getUsername() + (description != null ? " (" + description + ')' : StringUtils.EMPTY), //$NON-NLS-1$
				c.getId(), isSelected));
	}

	return model;
}
 
Example 12
Project: compuware-scm-downloader-plugin   File: EndevorConfiguration.java   View source code 6 votes vote down vote up
/**
 * Fills in the Login Credentials selection box with applicable Jenkins credentials.
 * 
 * @param context
 *            filter for credentials
 * @param credentialsId
 *            existing login credentials; can be null
 * @param project
 *            the Jenkins project
 * 
 * @return credential selections
 */
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId, @AncestorInPath Item project)
{
	List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM,
			Collections.<DomainRequirement> emptyList());

	StandardListBoxModel model = new StandardListBoxModel();
	model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false));

	for (StandardUsernamePasswordCredentials c : creds)
	{
		boolean isSelected = false;
		if (credentialsId != null)
		{
			isSelected = credentialsId.matches(c.getId());
		}

		String description = Util.fixEmptyAndTrim(c.getDescription());
		model.add(new Option(c.getUsername() + (description != null ? " (" + description + ')' : StringUtils.EMPTY), //$NON-NLS-1$
				c.getId(), isSelected));
	}

	return model;
}
 
Example 13
Project: compuware-scm-downloader-plugin   File: CpwrScmConfiguration.java   View source code 6 votes vote down vote up
/**
 * Retrieves login information given a credential ID.
 * 
 * @param project
 *            the Jenkins project
 *
 * @return a Jenkins credential with login information
 */
protected StandardUsernamePasswordCredentials getLoginInformation(Item project)
{
	StandardUsernamePasswordCredentials credential = null;

	List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList());

	IdMatcher matcher = new IdMatcher(getCredentialsId());
	for (StandardUsernamePasswordCredentials c : credentials)
	{
		if (matcher.matches(c))
		{
			credential = c;
		}
	}

	return credential;
}
 
Example 14
Project: compuware-scm-downloader-plugin   File: IspwConfiguration.java   View source code 6 votes vote down vote up
/**
 * Retrieves login information given a credential ID
 * 
 * @param project
 *            the Jenkins project
 *
 * @return a Jenkins credential with login information
 */
protected StandardUsernamePasswordCredentials getLoginInformation(Item project)
{
	StandardUsernamePasswordCredentials credential = null;

	List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList());

	IdMatcher matcher = new IdMatcher(getCredentialsId());
	for (StandardUsernamePasswordCredentials c : credentials)
	{
		if (matcher.matches(c))
		{
			credential = c;
		}
	}

	return credential;
}
 
Example 15
Project: openshift-sync-plugin   File: CredentialsUtils.java   View source code 6 votes vote down vote up
public static String getCurrentToken() {
    String credentialsId = GlobalPluginConfiguration.get()
            .getCredentialsId();
    if (credentialsId.equals("")) {
        return "";
    }

    OpenShiftToken token = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(OpenShiftToken.class,
                    Jenkins.getActiveInstance(), ACL.SYSTEM,
                    Collections.<DomainRequirement> emptyList()),
            CredentialsMatchers.withId(credentialsId));

    if (token != null) {
        return token.getToken();
    }

    return "";
}
 
Example 16
Project: openshift-sync-plugin   File: JenkinsUtils.java   View source code 6 votes vote down vote up
private static void terminateRun(final WorkflowRun run) {
	ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Void, RuntimeException>() {
		@Override
		public Void call() throws RuntimeException {
			run.doTerm();
			Timer.get().schedule(new SafeTimerTask() {
				@Override
				public void doRun() {
					ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Void, RuntimeException>() {
						@Override
						public Void call() throws RuntimeException {
							run.doKill();
							return null;
						}
					});
				}
			}, 5, TimeUnit.SECONDS);
			return null;
		}
	});
}
 
Example 17
Project: openshift-sync-plugin   File: JenkinsUtils.java   View source code 6 votes vote down vote up
@SuppressFBWarnings("SE_BAD_FIELD")
public static boolean cancelQueuedBuild(WorkflowJob job, Build build) {
	String buildUid = build.getMetadata().getUid();
	final Queue buildQueue = Jenkins.getActiveInstance().getQueue();
	for (final Queue.Item item : buildQueue.getItems()) {
		for (Cause cause : item.getCauses()) {
			if (cause instanceof BuildCause && ((BuildCause) cause).getUid().equals(buildUid)) {
				return ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Boolean, RuntimeException>() {
					@Override
					public Boolean call() throws RuntimeException {
						buildQueue.cancel(item);
						return true;
					}
				});
			}
		}
	}
	return cancelNotYetStartedBuild(job, build);
}
 
Example 18
Project: openshift-sync-plugin   File: BuildWatcher.java   View source code 6 votes vote down vote up
private static synchronized void innerDeleteEventToJenkinsJobRun(
        final Build build) throws Exception {
    final WorkflowJob job = getJobFromBuild(build);
    if (job != null) {
        ACL.impersonate(ACL.SYSTEM,
                new NotReallyRoleSensitiveCallable<Void, Exception>() {
                    @Override
                    public Void call() throws Exception {
                        cancelBuild(job, build, true);
                        return null;
                    }
                });
    } else {
        // in case build was created and deleted quickly, prior to seeing BC
        // event, clear out from pre-BC cache
        removeBuildFromNoBCList(build);
    }
}
 
Example 19
Project: impersonation-plugin   File: ImpersonationAction.java   View source code 6 votes vote down vote up
@RequirePOST
public HttpResponse doImpersonate(StaplerRequest req, @QueryParameter String name) {
    Authentication auth = Jenkins.getAuthentication();
    GrantedAuthority[] authorities = auth.getAuthorities();
    if (authorities == null || StringUtils.isBlank(name)) {
        return HttpResponses.redirectToContextRoot();
    }
    GrantedAuthority authority = null;
    for (GrantedAuthority a : authorities) {
        if (a.getAuthority().equals(name)) {
            authority = a;
            break;
        }
    }
    if (authority == null) {
        return HttpResponses.redirectToContextRoot();
    }
    if (!SecurityRealm.AUTHENTICATED_AUTHORITY.equals(authority)) {
        ACL.impersonate(new ImpersonationAuthentication(auth, authority, SecurityRealm.AUTHENTICATED_AUTHORITY));
    } else {
        ACL.impersonate(new ImpersonationAuthentication(auth, SecurityRealm.AUTHENTICATED_AUTHORITY));
    }
    return HttpResponses.redirectToContextRoot();
}
 
Example 20
Project: pipeline-maven-plugin   File: DownstreamPipelineTriggerRunListener.java   View source code 6 votes vote down vote up
protected boolean isUpstreamBuildVisibleByDownstreamBuildAuth(@Nonnull WorkflowJob upstreamPipeline, @Nonnull Queue.Task downstreamPipeline) {
    Authentication auth = Tasks.getAuthenticationOf(downstreamPipeline);
    Authentication downstreamPipelineAuth;
    if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) {
        downstreamPipelineAuth = Jenkins.ANONYMOUS; // cf. BuildTrigger
    } else {
        downstreamPipelineAuth = auth;
    }

    try (ACLContext _ = ACL.as(downstreamPipelineAuth)) {
        WorkflowJob upstreamPipelineObtainedAsImpersonated = Jenkins.getInstance().getItemByFullName(upstreamPipeline.getFullName(), WorkflowJob.class);
        boolean result = upstreamPipelineObtainedAsImpersonated != null;
        LOGGER.log(Level.FINE, "isUpstreamBuildVisibleByDownstreamBuildAuth({0}, {1}): taskAuth: {2}, downstreamPipelineAuth: {3}, upstreamPipelineObtainedAsImpersonated:{4}, result: {5}",
                new Object[]{upstreamPipeline, downstreamPipeline, auth, downstreamPipelineAuth, upstreamPipelineObtainedAsImpersonated, result});
        return result;
    }
}
 
Example 21
Project: compuware-scm-downloader-plugin   File: PdsConfiguration.java   View source code 6 votes vote down vote up
/**
 * Fills in the Login Credentials selection box with applicable Jenkins credentials.
 * 
 * @param context
 *            filter for credentials
 * @param credentialsId
 *            existing login credentials; can be null
 * @param project
 *            the Jenkins project
 * 
 * @return credential selections
 */
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId, @AncestorInPath Item project)
{
	List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM,
			Collections.<DomainRequirement> emptyList());

	StandardListBoxModel model = new StandardListBoxModel();
	model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false));

	for (StandardUsernamePasswordCredentials c : creds)
	{
		boolean isSelected = false;
		if (credentialsId != null)
		{
			isSelected = credentialsId.matches(c.getId());
		}

		String description = Util.fixEmptyAndTrim(c.getDescription());
		model.add(new Option(c.getUsername() + (description != null ? " (" + description + ')' : StringUtils.EMPTY), //$NON-NLS-1$
				c.getId(), isSelected));
	}

	return model;
}
 
Example 22
Project: compuware-scm-downloader-plugin   File: EndevorConfiguration.java   View source code 6 votes vote down vote up
/**
 * Fills in the Login Credentials selection box with applicable Jenkins credentials.
 * 
 * @param context
 *            filter for credentials
 * @param credentialsId
 *            existing login credentials; can be null
 * @param project
 *            the Jenkins project
 * 
 * @return credential selections
 */
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Jenkins context, @QueryParameter String credentialsId, @AncestorInPath Item project)
{
	List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM,
			Collections.<DomainRequirement> emptyList());

	StandardListBoxModel model = new StandardListBoxModel();
	model.add(new Option(StringUtils.EMPTY, StringUtils.EMPTY, false));

	for (StandardUsernamePasswordCredentials c : creds)
	{
		boolean isSelected = false;
		if (credentialsId != null)
		{
			isSelected = credentialsId.matches(c.getId());
		}

		String description = Util.fixEmptyAndTrim(c.getDescription());
		model.add(new Option(c.getUsername() + (description != null ? " (" + description + ')' : StringUtils.EMPTY), //$NON-NLS-1$
				c.getId(), isSelected));
	}

	return model;
}
 
Example 23
Project: compuware-scm-downloader-plugin   File: CpwrScmConfiguration.java   View source code 6 votes vote down vote up
/**
 * Retrieves login information given a credential ID.
 * 
 * @param project
 *            the Jenkins project
 *
 * @return a Jenkins credential with login information
 */
protected StandardUsernamePasswordCredentials getLoginInformation(Item project)
{
	StandardUsernamePasswordCredentials credential = null;

	List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList());

	IdMatcher matcher = new IdMatcher(getCredentialsId());
	for (StandardUsernamePasswordCredentials c : credentials)
	{
		if (matcher.matches(c))
		{
			credential = c;
		}
	}

	return credential;
}
 
Example 24
Project: compuware-scm-downloader-plugin   File: IspwConfiguration.java   View source code 6 votes vote down vote up
/**
 * Retrieves login information given a credential ID
 * 
 * @param project
 *            the Jenkins project
 *
 * @return a Jenkins credential with login information
 */
protected StandardUsernamePasswordCredentials getLoginInformation(Item project)
{
	StandardUsernamePasswordCredentials credential = null;

	List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials(
			StandardUsernamePasswordCredentials.class, project, ACL.SYSTEM, Collections.<DomainRequirement> emptyList());

	IdMatcher matcher = new IdMatcher(getCredentialsId());
	for (StandardUsernamePasswordCredentials c : credentials)
	{
		if (matcher.matches(c))
		{
			credential = c;
		}
	}

	return credential;
}
 
Example 25
Project: jenkins-gitlab-security-plugin   File: GitLabACL.java   View source code 6 votes vote down vote up
@Override
public boolean hasPermission(Authentication a, Permission permission) {
    if(ACL.SYSTEM_USERNAME.equals(a.getName())) {
        return true;
    }
    GrantedAuthority[] authorities = a.getAuthorities();
    if(ArrayUtils.isEmpty(authorities)) {
        return false;
    }
    for(GrantedAuthority authority : authorities) {
        if(StringUtils.endsWith(authority.getAuthority(), GitLabGrantedAuthority.GITLAB_ADMIN_SUFFIX)) {
            return true;
        }
        if(authority instanceof GitLabGrantedAuthority) {
            if(hasPermissionForJob((GitLabGrantedAuthority) authority, permission)) {
                return true;
            }
        }
    }
    return this.project == null && Jenkins.READ == permission;
}
 
Example 26
Project: phabricator-jenkins-plugin   File: ConduitCredentialsDescriptor.java   View source code 6 votes vote down vote up
public static ListBoxModel doFillCredentialsIDItems(@AncestorInPath Jenkins context) {
    if (context == null || !context.hasPermission(Item.CONFIGURE)) {
        return new StandardListBoxModel();
    }

    List<DomainRequirement> domainRequirements = new ArrayList<DomainRequirement>();
    return new StandardListBoxModel()
            .withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(ConduitCredentials.class)),
                    CredentialsProvider.lookupCredentials(
                            StandardCredentials.class,
                            context,
                            ACL.SYSTEM,
                            domainRequirements));
}
 
Example 27
Project: figshare-plugin   File: FigShareNotifier.java   View source code 6 votes vote down vote up
/**
 * Constructor called from a Jelly view. The parameters are given by a user.
 *
 * @param credentialsId figshare credential ID, selected out of a combo box
 * @param articleTitle figshare article title
 * @param articleDescription figshare article description
 * @param antPattern an ant-like pattern (e.g. **\/*.png)
 */
@DataBoundConstructor
public FigShareNotifier(String credentialsId, String articleTitle, String articleDescription, String antPattern) {
    this.credentialsId = credentialsId;
    this.articleTitle = articleTitle;
    this.articleDescription = articleDescription;
    this.antPattern = antPattern;

    // Get credential defined by user, using credential ID
    List<FigShareOauthCredentials> credentials = CredentialsProvider.lookupCredentials(
            FigShareOauthCredentials.class, Jenkins.getInstance(), ACL.SYSTEM,
            Collections.<DomainRequirement> emptyList());
    FigShareOauthCredentials credential = CredentialsMatchers.firstOrNull(credentials,
            CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId)));

    this.credential = credential;
    if (null == credential) {
        LOGGER.warning(String.format(
                "Could not locate credential with ID %s. figshare integration is disabled for this notifier",
                credentialsId));
    }
}
 
Example 28
Project: jenkins-github-pull-request-comments   File: GhprcRootAction.java   View source code 6 votes vote down vote up
private Set<GhprcWebHook> getWebHooks() {
    final Set<GhprcWebHook> webHooks = new HashSet<GhprcWebHook>();

    // We need this to get access to list of repositories
    Authentication old = SecurityContextHolder.getContext().getAuthentication();
    SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);

    try {
        for (AbstractProject<?, ?> job : Jenkins.getInstance().getAllItems(AbstractProject.class)) {
            GhprcTrigger trigger = job.getTrigger(GhprcTrigger.class);
            if (trigger == null || trigger.getWebHook() == null) {
                continue;
            }
            webHooks.add(trigger.getWebHook());
        }
    } finally {
        SecurityContextHolder.getContext().setAuthentication(old);
    }

    if (webHooks.size() == 0) {
        logger.log(Level.WARNING, "No projects found using GitHub pull request trigger");
    }

    return webHooks;
}
 
Example 29
Project: jenkins-github-pull-request-comments   File: GhprcGitHubAuth.java   View source code 6 votes vote down vote up
/**
 * Stapler helper method.
 *
 * @param context
 *            the context.
 * @param remoteBase
 *            the remote base.
 * @return list box model.
 * @throws URISyntaxException 
 */
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, @QueryParameter String serverAPIUrl) throws URISyntaxException {
    List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(serverAPIUrl).build();
    
    return new StandardListBoxModel()
            .withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                    CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                    CredentialsMatchers.instanceOf(StringCredentials.class)),
            CredentialsProvider.lookupCredentials(StandardCredentials.class,
                    context,
                    ACL.SYSTEM,
                    domainRequirements)
                    );
}
 
Example 30
Project: jenkins-github-pull-request-comments   File: Ghprc.java   View source code 6 votes vote down vote up
public static StandardCredentials lookupCredentials(Item context, String credentialId, String uri) {
    String contextName = "(Jenkins.instance)";
    if (context != null) {
        contextName = context.getFullName();
    }
    logger.log(Level.INFO, "Looking up credentials for {0}, using context {1} for url {2}", new Object[] { credentialId, contextName, uri });
    
    List<StandardCredentials> credentials;
    
    if (context == null) {
        credentials = CredentialsProvider.lookupCredentials(StandardCredentials.class, Jenkins.getInstance(), ACL.SYSTEM,
                URIRequirementBuilder.fromUri(uri).build());
    } else {
        credentials = CredentialsProvider.lookupCredentials(StandardCredentials.class, context, ACL.SYSTEM,
                URIRequirementBuilder.fromUri(uri).build());
    }
    
    logger.log(Level.INFO, "Found {0} credentials", new Object[]{credentials.size()});
    
    return (credentialId == null) ? null : CredentialsMatchers.firstOrNull(credentials,
                CredentialsMatchers.withId(credentialId));
}
 
Example 31
Project: jenkins-slack-webhook-plugin   File: WebhookEndpoint.java   View source code 6 votes vote down vote up
public SlackTextMessage scheduleJob(String projectName) {
    ACL.impersonate(ACL.SYSTEM);
    String response = "";

    Project project =
        Jenkins.getInstance().getItemByFullName(projectName, Project.class);

    boolean success = false;

    if (project != null)
        success = project.scheduleBuild(new SlackWebhookCause(this.slackUser));
    else
        return new SlackTextMessage("Could not find project ("+projectName+")\n");

    if (success) 
        return new SlackTextMessage("Build scheduled for project "+ projectName+"\n");
    else
        return new SlackTextMessage("Build not scheduled due to an issue with Jenkins");
}
 
Example 32
Project: gitlab-auth-plugin   File: GitLabGlobalACL.java   View source code 6 votes vote down vote up
/**
 * Checks if the given principal has permission to use the permission.
 * 
 * @param auth       the authentication object
 * @param permission the permission
 * @return true if the given principal has permission
 */
@Override
public boolean hasPermission(Authentication auth, Permission permission) {
    if (auth == ACL.SYSTEM) {
        return true;
    }
    
    if(isLoggedIn(auth)) {
        GitLabUserDetails user = (GitLabUserDetails) auth.getPrincipal();
        
        if (isPermissionSetStandard(user, permission)) {
            return true;
        }
    }
    return isPermissionSetAnon(permission);
}
 
Example 33
Project: gitlab-auth-plugin   File: GitLabAuthorization.java   View source code 6 votes vote down vote up
/**
 * Gets the ACL for the given folder.
 * 
 * @param folder the folder
 * @return an ACL
 */
public ACL getACL(Folder folder) {
    GitLabFolderAuthorization folderAuth = folder.getProperties().get(GitLabFolderAuthorization.class);
    
    if (folder.getParent() instanceof Folder) {
        return getACL((Folder) folder.getParent());
    }
    
    if(folderAuth != null) {
        // groupId is 0 if its not a GitLab folder.
        if (folderAuth.getGroupId() != 0) {
            return folderAuth.getACL();
        }
    }
    return getRootACL();
}
 
Example 34
Project: jenkins-kubernetes-plugin   File: KubectlBuildWrapper.java   View source code 6 votes vote down vote up
/**
 * Get the {@link StandardCredentials}.
 *
 * @return the credentials matching the {@link #credentialsId} or {@code null} is {@code #credentialsId} is blank
 * @throws AbortException if no {@link StandardCredentials} matching {@link #credentialsId} is found
 */
@CheckForNull
private StandardCredentials getCredentials() throws AbortException {
    if (StringUtils.isBlank(credentialsId)) {
        return null;
    }
    StandardCredentials result = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(StandardCredentials.class,
                    Jenkins.getInstance(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList()),
            CredentialsMatchers.withId(credentialsId)
    );
    if (result == null) {
        throw new AbortException("No credentials found for id \"" + credentialsId + "\"");
    }
    return result;
}
 
Example 35
Project: jenkins-kubernetes-plugin   File: KubernetesCloud.java   View source code 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
    return new StandardListBoxModel().withEmptySelection() //
            .withMatching( //
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(TokenProducer.class),
                            CredentialsMatchers.instanceOf(
                                    org.jenkinsci.plugins.kubernetes.credentials.TokenProducer.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(StringCredentials.class)), //
                    CredentialsProvider.lookupCredentials(StandardCredentials.class, //
                            Jenkins.getInstance(), //
                            ACL.SYSTEM, //
                            serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
                                    : Collections.EMPTY_LIST //
                    ));

}
 
Example 36
Project: google-oauth-plugin   File: GoogleRobotCredentials.java   View source code 6 votes vote down vote up
/**
 * Helper utility for populating a jelly list box with matching
 * {@link GoogleRobotCredentials} to avoid listing credentials that avoids
 * surfacing those with insufficient permissions.
 *
 * Modeled after:
 *    http://developer-blog.cloudbees.com/2012/10/using-ssh-from-jenkins.html
 *
 * @param clazz The class annotated with @RequiresDomain indicating its scope
 * requirements.
 * @return a list box populated solely with credentials compatible for the
 *         extension being configured.
 */
public static CredentialsListBoxModel getCredentialsListBox(Class<?> clazz) {
  GoogleOAuth2ScopeRequirement requirement =
      DomainRequirementProvider.of(clazz, GoogleOAuth2ScopeRequirement.class);

  if (requirement == null) {
    throw new IllegalArgumentException(
        Messages.GoogleRobotCredentials_NoAnnotation(clazz.getSimpleName()));
  }

  CredentialsListBoxModel listBox = new CredentialsListBoxModel(requirement);
  Iterable<GoogleRobotCredentials> allGoogleCredentials =
      CredentialsProvider.lookupCredentials(
          GoogleRobotCredentials.class, Jenkins.getInstance(), ACL.SYSTEM,
          ImmutableList.<DomainRequirement>of(requirement));

  for (GoogleRobotCredentials credentials : allGoogleCredentials) {
    String name = CredentialsNameProvider.name(credentials);
    listBox.add(name, credentials.getId());
  }
  return listBox;
}
 
Example 37
Project: deployer-framework-plugin   File: DeployNowProjectAction.java   View source code 6 votes vote down vote up
/**
 * Returns {@code true} if and only if a one click deployment is valid. In other words
 * {@link #isOneClickDeployPossible()} says there are artifacts for deployment. {@link #isOneClickDeployValid()}
 * says the configured one click deploy is fully defined and {@link #isOneClickDeploy()} says that the user
 * has enabled one click deploy for the project.
 *
 * @return {@code true} if and only if a one click deployment is valid.
 */
@SuppressWarnings("unused") // used by stapler
@Exported(name = "oneClickDeployValid", visibility = 2)
public boolean isOneClickDeployValid() {
    if (owner != null && owner.hasPermission(DEPLOY)) {
        DeployNowJobProperty property = owner.getProperty(DeployNowJobProperty.class);
        if (property != null) {
            if (property.isOneClickDeploy()) {
                if (owner.hasPermission(OWN_AUTH) && DeployHost.isValid(property.getHosts(), owner,
                        Hudson.getAuthentication())) {
                    return true;
                }
                if (owner.hasPermission(JOB_AUTH) && DeployHost.isValid(property.getHosts(), owner,
                        ACL.SYSTEM)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 38
Project: deployer-framework-plugin   File: PromotionCapabilitiesResolver.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    if (build instanceof Promotion) {
        build = ((Promotion) build).getTarget();
    }
    try {
        for (DeployHost<? extends DeployHost<?, ?>, ? extends DeployTarget<?>> set : getHosts()) {
            if (!Engine.create(set)
                    .withCredentials(build.getProject(), ACL.SYSTEM)
                    .from(build, DeploySourceOrigin.RUN)
                    .withLauncher(launcher)
                    .withListener(listener)
                    .build()
                    .perform()) {
                return false;
            }
        }
    } catch (Throwable t) {
        // deployment failed - > fail the build
        t.printStackTrace(listener.getLogger());
        return false;
    }
    return true;
}
 
Example 39
Project: deployer-framework-plugin   File: DeployBuilder.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {
    try {
        for (DeployHost<? extends DeployHost<?, ?>, ? extends DeployTarget<?>> set : hosts) {
            if (!Engine.create(set)
                    .withCredentials(build.getProject(), ACL.SYSTEM)
                    .from(build, DeploySourceOrigin.WORKSPACE)
                    .withLauncher(launcher)
                    .withListener(listener)
                    .build()
                    .perform()) {
                return false;
            }
        }
    } catch (Throwable t) {
        // deployment failed - > fail the build
        t.printStackTrace(listener.getLogger());
        return false;
    }
    return true;
}
 
Example 40
Project: deployer-framework-plugin   File: DeployNowRunAction.java   View source code 6 votes vote down vote up
@Exported(name = "oneClickDeployValid", visibility = 2)
public boolean isOneClickDeployValid() {
    if (owner != null && owner.getParent().hasPermission(DEPLOY)) {
        DeployNowJobProperty property = owner.getParent().getProperty(DeployNowJobProperty.class);
        if (property != null) {
            if (property.isOneClickDeploy()) {
                List<? extends DeployHost<?, ?>> sets = property.getHosts();
                if (owner.getParent().hasPermission(OWN_AUTH) && DeployHost
                        .isValid(sets, owner, Hudson.getAuthentication())) {
                    return true;
                }
                if (owner.getParent().hasPermission(JOB_AUTH) && DeployHost.isValid(sets, owner, ACL.SYSTEM)) {
                    return true;
                }
            }
        }
    }
    return false;
}