com.cloudbees.plugins.credentials.common.StandardUsernameCredentials Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.common.StandardUsernameCredentials. 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: DockerComputerSSHConnector.java    From docker-plugin with MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, @QueryParameter String credentialsId) {
    if ( !hasPermission(context)) {
        return new StandardUsernameListBoxModel()
                .includeCurrentValue(credentialsId);
    }
    // Functionally the same as SSHLauncher's descriptor method, but without
    // filtering by host/port as we don't/can't know those yet.
    return new StandardUsernameListBoxModel()
            .includeMatchingAs(
                    ACL.SYSTEM,
                    context,
                    StandardUsernameCredentials.class,
                    Collections.emptyList(),
                    SSHAuthenticator.matcher(Connection.class))
            .includeCurrentValue(credentialsId);
}
 
Example #2
Source File: Site.java    From jira-steps-plugin with Apache License 2.0 6 votes vote down vote up
public FormValidation doCheckCredentialsId(@AncestorInPath Item item,
    final @QueryParameter String credentialsId,
    final @QueryParameter String url) {

  if (item == null) {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
      return FormValidation.ok();
    }
  } else if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
    return FormValidation.ok();
  }
  if (StringUtils.isBlank(credentialsId)) {
    return FormValidation.warning(Messages.Site_emptyCredentialsId());
  }

  List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(url).build();
  if (CredentialsProvider.listCredentials(StandardUsernameCredentials.class, item, getAuthentication(item), domainRequirements, CredentialsMatchers.withId(credentialsId)).isEmpty()) {
    return FormValidation.error(Messages.Site_invalidCredentialsId());
  }
  return FormValidation.ok();
}
 
Example #3
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Resolves the specified scan credentials in the specified context for use against the specified API endpoint.
 *
 * @param context           the context.
 * @param apiUri            the API endpoint.
 * @param scanCredentialsId the credentials to resolve.
 * @return the {@link StandardCredentials} or {@code null}
 */
@CheckForNull
public static StandardCredentials lookupScanCredentials(@CheckForNull Item context,
                                                        @CheckForNull String apiUri,
                                                        @CheckForNull String scanCredentialsId) {
    if (Util.fixEmpty(scanCredentialsId) == null) {
        return null;
    } else {
        return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                StandardUsernameCredentials.class,
                context,
                context instanceof Queue.Task
                        ? ((Queue.Task) context).getDefaultAuthentication()
                        : ACL.SYSTEM,
                githubDomainRequirements(apiUri)
            ),
            CredentialsMatchers.allOf(CredentialsMatchers.withId(scanCredentialsId), githubScanCredentialsMatcher())
        );
    }
}
 
Example #4
Source File: BuildStatusConfigTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies doFillCredentialsIdItems adds values from the credentials store
 * @throws IOException
 */
@Test
public void testDoFillHttpCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
    StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
    CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);

    BuildStatusConfig instance = new BuildStatusConfig();
    instance.setCredentialsId(testCredentials);

    ListBoxModel model = instance.doFillHttpCredentialsIdItems(testCredentials);

    assertEquals(2, model.size());
    ListBoxModel.Option item1 = model.get(0);
    assertEquals("", item1.value);
    assertEquals("- none -", item1.name);

    ListBoxModel.Option item2 = model.get(1);
    assertEquals(testCredentials, item2.value);
}
 
Example #5
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Populates a {@link ListBoxModel} with the checkout credentials appropriate for the supplied context against the
 * supplied API endpoint.
 *
 * @param context the context.
 * @param apiUri  the api endpoint.
 * @return a {@link ListBoxModel}.
 */
@NonNull
public static ListBoxModel listCheckoutCredentials(@CheckForNull Item context, String apiUri) {
    StandardListBoxModel result = new StandardListBoxModel();
    result.includeEmptyValue();
    result.add("- same as scan credentials -", GitHubSCMSource.DescriptorImpl.SAME);
    result.add("- anonymous -", GitHubSCMSource.DescriptorImpl.ANONYMOUS);
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            githubDomainRequirements(apiUri),
            GitClient.CREDENTIALS_MATCHER
    );
}
 
Example #6
Source File: BuildStatusConfigTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies doFillCredentialsIdItems adds values from the credentials store
 * @throws IOException 
 */
@Test
public void testDoFillCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
    StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
    CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);

    BuildStatusConfig instance = new BuildStatusConfig();
    instance.setCredentialsId(testCredentials);
    
    ListBoxModel model = instance.doFillCredentialsIdItems(testCredentials);
    
    assertEquals(2, model.size());
    ListBoxModel.Option item1 = model.get(0);
    assertEquals("", item1.value);
    assertEquals("- none -", item1.name);

    ListBoxModel.Option item2 = model.get(1);
    assertEquals(testCredentials, item2.value);
}
 
Example #7
Source File: SSHCheckoutTrait.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Form completion.
 *
 * @param context       the context.
 * @param apiUri        the server url.
 * @param credentialsId the current selection.
 * @return the form items.
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
                                             @QueryParameter String apiUri,
                                             @QueryParameter String credentialsId) {
    if (context == null
            ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    StandardListBoxModel result = new StandardListBoxModel();
    result.add(Messages.SSHCheckoutTrait_useAgentKey(), "");
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            Connector.githubDomainRequirements(apiUri),
            CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
}
 
Example #8
Source File: DockerSSHConnector.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@CheckForNull
public StandardUsernameCredentials getCredentials() {
    String credentialsIdf;

    if (isNull(credentialsId)) {
        credentialsIdf = (isNull(credentials)) ? null : credentials.getId();
    } else {
        credentialsIdf = credentialsId;
    }

    try {
        StandardUsernameCredentials credentialss;
        if (credentialsIdf == null) {
            credentialss = null;
        } else {
            credentialss = SSHLauncher.lookupSystemCredentials(credentialsIdf);
        }
        if (nonNull(credentialss)) {
            credentials = credentialss;
        }
    } catch (Throwable t) {
        // ignore
    }

    return credentials;
}
 
Example #9
Source File: GitLabSCMSourceSettings.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 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
Source File: DockerComputerSSHConnectorTest.java    From docker-plugin with MIT License 6 votes vote down vote up
@Test
public void connectAgentViaSSHUsingCredentialsKey() throws Exception {
    final InstanceIdentity id = InstanceIdentity.get();
    final String privateKey = PEMEncodable.create(id.getPrivate()).encode();
    final String publicKey = "ssh-rsa " + encode(new RSAKeyAlgorithm().encodePublicKey(id.getPublic()));
    final String credentialsId = "tempCredId";
    final StandardUsernameCredentials credentials = DockerComputerSSHConnector.makeCredentials(credentialsId, COMMON_IMAGE_USERNAME, privateKey);
    SystemCredentialsProvider.getInstance().getCredentials().add(credentials);
    final DockerComputerSSHConnector.SSHKeyStrategy sshKeyStrategy = new DockerComputerSSHConnector.ManuallyConfiguredSSHKey(credentialsId, new NonVerifyingKeyVerificationStrategy());
    final DockerComputerSSHConnector connector = new DockerComputerSSHConnector(sshKeyStrategy);
    connector.setJavaPath(SSH_SLAVE_IMAGE_JAVAPATH);
    final DockerTemplate template = new DockerTemplate(
            new DockerTemplateBase(SSH_SLAVE_IMAGE_IMAGENAME),
            connector,
            LABEL, COMMON_IMAGE_HOMEDIR, INSTANCE_CAP
    );
    template.getDockerTemplateBase().setEnvironmentsString("JENKINS_SLAVE_SSH_PUBKEY=" + publicKey);
    template.setName("connectAgentViaSSHUsingCredentialsKey");
    should_connect_agent(template);
}
 
Example #11
Source File: GerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
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 #12
Source File: GitPushStep.java    From simple-pull-request-job-plugin with Apache License 2.0 6 votes vote down vote up
protected Void run() throws Exception {
    FilePath ws = getContext().get(FilePath.class);
    TaskListener listener = this.getContext().get(TaskListener.class);
    EnvVars envVars = getContext().get(EnvVars.class);
    WorkflowJob job = getContext().get(WorkflowJob.class);
    GitOperations gitOperations = new GitOperations(ws, listener, envVars, url);
    StandardCredentials c = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    job,
                    Tasks.getAuthenticationOf((Queue.Task) job)),
            CredentialsMatchers.withId(credentialId));

    gitOperations.setUsernameAndPasswordCredential((StandardUsernameCredentials) c);
    gitOperations.setCurrentBranch(branch);
    gitOperations.push(true);
    return null;
}
 
Example #13
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
        @QueryParameter String serverName, @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        // must have admin if you want the list without a context
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you
            // want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            context, StandardUsernameCredentials.class, fromUri(getServerUrlFromName(serverName)).build(),
            GitClient.CREDENTIALS_MATCHER);
    return result;
}
 
Example #14
Source File: AnsibleAdHocCommandBuilder.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void perform(@Nonnull Run<?, ?> run, @Nonnull FilePath ws, @Nonnull Launcher launcher, @Nonnull TaskListener listener) throws InterruptedException, IOException {
    try {
        CLIRunner runner = new CLIRunner(run, ws, launcher, listener);
        Computer computer = Computer.currentComputer();
        if (computer == null) {
            throw new AbortException("The ansible playbook build step requires to be launched on a node");
        }
        String exe = AnsibleInstallation.getExecutable(ansibleName, AnsibleCommand.ANSIBLE, computer.getNode(), listener, run.getEnvironment(listener));
        AnsibleAdHocCommandInvocation invocation = new AnsibleAdHocCommandInvocation(exe, run, ws, listener);
        invocation.setHostPattern(hostPattern);
        invocation.setInventory(inventory);
        invocation.setModule(module);
        invocation.setModuleCommand(command);
        invocation.setSudo(sudo, sudoUser);
        invocation.setForks(forks);
        invocation.setCredentials(StringUtils.isNotBlank(credentialsId) ?
                CredentialsProvider.findCredentialById(credentialsId, StandardUsernameCredentials.class, run) :
                null);
        invocation.setAdditionalParameters(additionalParameters);
        invocation.setHostKeyCheck(hostKeyChecking);
        invocation.setUnbufferedOutput(unbufferedOutput);
        invocation.setColorizedOutput(colorizedOutput);
        if (!invocation.execute(runner)) {
            throw new AbortException("Ansible Ad-Hoc command execution failed");
        }
    } catch (IOException ioe) {
        Util.displayIOException(ioe, listener);
        ioe.printStackTrace(listener.fatalError(hudson.tasks.Messages.CommandInterpreter_CommandFailed()));
        throw ioe;
    } catch (AnsibleInvocationException aie) {
        listener.fatalError(aie.getMessage());
        throw new AbortException(aie.getMessage());
    }
}
 
Example #15
Source File: AbstractAnsibleBuilderDescriptor.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Project project) {
    return new StandardListBoxModel()
            .withEmptySelection()
            .withMatching(anyOf(
                        instanceOf(SSHUserPrivateKey.class),
                        instanceOf(UsernamePasswordCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, project));
}
 
Example #16
Source File: SSHCheckoutTrait.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Validation for checkout credentials.
 *
 * @param context   the context.
 * @param serverUrl the server url.
 * @param value     the current selection.
 * @return the validation results
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public FormValidation doCheckCredentialsId(@CheckForNull @AncestorInPath Item context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value) {
    if (context == null
            ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        // use agent key
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(
            SSHUserPrivateKey.class,
            context,
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(
            StandardUsernameCredentials.class,
            context,
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.error(Messages.SSHCheckoutTrait_incompatibleCredentials());
    }
    return FormValidation.warning(Messages.SSHCheckoutTrait_missingCredentials());
}
 
Example #17
Source File: AnsiblePlaybookBuilder.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
public void perform(@Nonnull Run<?, ?> run, @Nonnull Node node, @Nonnull FilePath ws, @Nonnull Launcher launcher, @Nonnull TaskListener listener, EnvVars envVars)
        throws InterruptedException, IOException
{
    try {
        CLIRunner runner = new CLIRunner(run, ws, launcher, listener);
        String exe = AnsibleInstallation.getExecutable(ansibleName, AnsibleCommand.ANSIBLE_PLAYBOOK, node, listener, envVars);
        AnsiblePlaybookInvocation invocation = new AnsiblePlaybookInvocation(exe, run, ws, listener);
        invocation.setPlaybook(playbook);
        invocation.setInventory(inventory);
        invocation.setLimit(limit);
        invocation.setTags(tags);
        invocation.setSkippedTags(skippedTags);
        invocation.setStartTask(startAtTask);
        invocation.setSudo(sudo, sudoUser);
        invocation.setForks(forks);
        invocation.setCredentials(StringUtils.isNotBlank(credentialsId) ?
            CredentialsProvider.findCredentialById(credentialsId, StandardUsernameCredentials.class, run) : null,
            copyCredentialsInWorkspace);
        invocation.setAdditionalParameters(additionalParameters);
        invocation.setHostKeyCheck(hostKeyChecking);
        invocation.setUnbufferedOutput(unbufferedOutput);
        invocation.setColorizedOutput(colorizedOutput);
        if (!invocation.execute(runner)) {
            throw new AbortException("Ansible playbook execution failed");
        }
    } catch (IOException ioe) {
        Util.displayIOException(ioe, listener);
        ioe.printStackTrace(listener.fatalError(hudson.tasks.Messages.CommandInterpreter_CommandFailed()));
        throw ioe;
    } catch (AnsibleInvocationException aie) {
        listener.fatalError(aie.getMessage());
        throw new AbortException(aie.getMessage());
    }
}
 
Example #18
Source File: AnsiblePlaybookStep.java    From ansible-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Project project) {
    return new StandardListBoxModel()
        .withEmptySelection()
        .withMatching(anyOf(
            instanceOf(SSHUserPrivateKey.class),
            instanceOf(UsernamePasswordCredentials.class)),
            CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, project));
}
 
Example #19
Source File: GitLabSCMNavigator.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
    @QueryParameter String serverName,
    @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
            && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
        context instanceof Queue.Task
            ? ((Queue.Task) context).getDefaultAuthentication()
            : ACL.SYSTEM,
        context,
        StandardUsernameCredentials.class,
        fromUri(getServerUrlFromName(serverName)).build(),
        GitClient.CREDENTIALS_MATCHER
    );
    return result;
}
 
Example #20
Source File: Connector.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Populates a {@link ListBoxModel} with the scan credentials appropriate for the supplied context against the
 * supplied API endpoint.
 *
 * @param context the context.
 * @param apiUri  the api endpoint.
 * @return a {@link ListBoxModel}.
 */
@NonNull
public static ListBoxModel listScanCredentials(@CheckForNull Item context, String apiUri) {
    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeMatchingAs(
                    context instanceof Queue.Task
                            ? ((Queue.Task) context).getDefaultAuthentication()
                            : ACL.SYSTEM,
                    context,
                    StandardUsernameCredentials.class,
                    githubDomainRequirements(apiUri),
                    githubScanCredentialsMatcher()
            );
}
 
Example #21
Source File: DockerCreateContainer.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public static ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new ListBoxModel();
    }

    return new SSHUserListBoxModel().withMatching(
            SSHAuthenticator.matcher(Connection.class),
            CredentialsProvider.lookupCredentials(
                    StandardUsernameCredentials.class,
                    context,
                    ACL.SYSTEM,
                    SSHLauncher.SSH_SCHEME)
    );
}
 
Example #22
Source File: DockerSSHConnector.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("checkstyle:ParameterNumber")
@DataBoundConstructor
public DockerSSHConnector(int port,
                          StandardUsernameCredentials credentials,
                          String credentialsId,
                          String jvmOptions,
                          String javaPath,
                          JDKInstaller jdkInstaller,
                          String prefixStartSlaveCmd,
                          String suffixStartSlaveCmd,
                          Integer launchTimeoutSeconds,
                          Integer maxNumRetries,
                          Integer retryWaitTime,
                          SshHostKeyVerificationStrategy sshHostKeyVerificationStrategy) {
    this.jvmOptions = jvmOptions;
    this.port = port == 0 ? 22 : port;
    this.credentials = credentials;
    this.credentialsId = credentialsId;
    this.javaPath = javaPath;
    this.jdkInstaller = jdkInstaller;
    this.prefixStartSlaveCmd = fixEmpty(prefixStartSlaveCmd);
    this.suffixStartSlaveCmd = fixEmpty(suffixStartSlaveCmd);
    this.launchTimeoutSeconds = launchTimeoutSeconds == null || launchTimeoutSeconds <= 0 ? null : launchTimeoutSeconds;
    this.maxNumRetries = maxNumRetries != null && maxNumRetries > 0 ? maxNumRetries : 0;
    this.retryWaitTime = retryWaitTime != null && retryWaitTime > 0 ? retryWaitTime : 0;
    this.sshHostKeyVerificationStrategy = sshHostKeyVerificationStrategy;
}
 
Example #23
Source File: DockerSSHConnector.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    if (context instanceof AccessControlled) {
        if (!((AccessControlled) context).hasPermission(Computer.CONFIGURE)) {
            return new ListBoxModel();
        }
    } else {
        if (!Jenkins.getInstance().hasPermission(Computer.CONFIGURE)) {
            return new ListBoxModel();
        }
    }
    return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class),
            CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context,
                    ACL.SYSTEM, SSH_SCHEME));
}
 
Example #24
Source File: SmartCredentialsProvider.java    From git-client-plugin with MIT License 5 votes vote down vote up
private boolean supports(StandardCredentials c, CredentialItem i) {
    if (c == null) {
        return false;
    }
    if (i instanceof StandardUsernameCredentialsCredentialItem) {
        return c instanceof StandardUsernameCredentials;
    }
    if (i instanceof CredentialItem.Username) {
        return c instanceof UsernameCredentials;
    }
    if (i instanceof CredentialItem.Password) {
        return c instanceof PasswordCredentials;
    }
    return false;
}
 
Example #25
Source File: SmartCredentialsProvider.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public synchronized boolean get(URIish uri, CredentialItem... credentialItems) throws UnsupportedCredentialItem {
    StandardCredentials c = specificCredentials.get(uri == null ? null : uri.toString());
    if (c == null) {
        c = defaultCredentials;
    }
    if (c == null) {
        return false;
    }
    for (CredentialItem i : credentialItems) {
        if (i instanceof StandardUsernameCredentialsCredentialItem && c instanceof StandardUsernameCredentials) {
            ((StandardUsernameCredentialsCredentialItem) i).setValue((StandardUsernameCredentials) c);
            continue;
        }
        if (i instanceof CredentialItem.Username && c instanceof UsernameCredentials) {
            ((CredentialItem.Username) i).setValue(((UsernameCredentials)c).getUsername());
            continue;
        }
        if (i instanceof CredentialItem.Password && c instanceof PasswordCredentials) {
            ((CredentialItem.Password) i).setValue(
                    ((PasswordCredentials) c).getPassword().getPlainText().toCharArray());
            continue;
        }
        if (i instanceof CredentialItem.StringType) {
            if (i.getPromptText().equals("Password: ") && c instanceof PasswordCredentials) {
                ((CredentialItem.StringType) i).setValue(((PasswordCredentials) c).getPassword().getPlainText());
                continue;
            }
        }
        throw new UnsupportedCredentialItem(uri, i.getClass().getName()
                + ":" + i.getPromptText());
    }
    return true;
}
 
Example #26
Source File: CredentialsProviderImplTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    Secret secret = Secret.fromString(SECRET_VALUE);
    listener = StreamTaskListener.fromStdout();
    StandardUsernameCredentials cred = new StandardUsernamePasswordCredentialsImpl(USER_NAME, secret);
    provider = new CredentialsProviderImpl(listener, cred);
}
 
Example #27
Source File: CredentialsProviderImplTest.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Test
public void testSupportsDisallowed() {
    Secret secret = Secret.fromString(SECRET_VALUE);
    listener = StreamTaskListener.fromStdout();
    StandardUsernameCredentials badCred = new MyUsernameCredentialsImpl(USER_NAME);
    CredentialsProviderImpl badProvider = new CredentialsProviderImpl(listener, badCred);
    CredentialItem.Username username = new CredentialItem.Username();
    assertNull(username.getValue());
    assertFalse(badProvider.supports(username));
    assertFalse(badProvider.get(uri, username));
    assertNull(username.getValue());
}
 
Example #28
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
@Override
public String apply(@Nullable Entry<String, StandardUsernameCredentials> entry) {
    if (entry == null)
        return null;
    String mavenServerId = entry.getKey();
    StandardUsernameCredentials credentials = entry.getValue();
    return "[" +
            "mavenServerId: '" + mavenServerId + "', " +
            "jenkinsCredentials: '" + credentials.getId() + "', " +
            "username: '" + credentials.getUsername() + "', " +
            "type: '" + ClassUtils.getShortName(credentials.getClass()) +
            "']";
}
 
Example #29
Source File: SSHCheckoutTrait.java    From gitea-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
                                             @QueryParameter String serverUrl,
                                             @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.add(Messages.SSHCheckoutTrait_useAgentKey(), "");
    result.includeMatchingAs(
            context instanceof Queue.Task ?
                    ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
    return result;
}
 
Example #30
Source File: SSHCheckoutTrait.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * Validation for checkout credentials.
 *
 * @param context   the context.
 * @param serverUrl the server url.
 * @param value     the current selection.
 * @return the validation results
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public FormValidation doCheckCredentialsId(@CheckForNull @AncestorInPath Item context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value) {
    if (context == null
            ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        // use agent key
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider
                    .lookupCredentials(SSHUserPrivateKey.class, context, context instanceof Queue.Task
                            ? ((Queue.Task) context).getDefaultAuthentication()
                            : ACL.SYSTEM, URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider
                    .lookupCredentials(StandardUsernameCredentials.class, context, context instanceof Queue.Task
                            ? ((Queue.Task) context).getDefaultAuthentication()
                            : ACL.SYSTEM, URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.error(Messages.SSHCheckoutTrait_incompatibleCredentials());
    }
    return FormValidation.warning(Messages.SSHCheckoutTrait_missingCredentials());
}