public FormValidation doValidate(
     @QueryParameter String username,
     @QueryParameter String apiKey,
     @QueryParameter boolean disableStatusColumn,
     @QueryParameter boolean reuseSauceAuth) {
   try {
     SauceOnDemandAuthentication credential =
         reuseSauceAuth
             ? new SauceOnDemandAuthentication()
             : new SauceOnDemandAuthentication(
                 username, Secret.toString(Secret.fromString(apiKey)));
     // we aren't interested in the results of the REST API call - just the fact that we executed
     // without an error is enough to verify the connection
     if (reuseSauceAuth
         && StringUtils.isBlank(credential.getUsername())
         && StringUtils.isBlank(credential.getAccessKey())) {
       return FormValidation.error("Unable to find ~/.sauce-ondemand file");
     } else {
       String response =
           new SauceREST(credential.getUsername(), credential.getAccessKey())
               .retrieveResults("tunnels");
       if (response != null && !response.equals("")) {
         return FormValidation.ok("Success");
       } else {
         return FormValidation.error("Failed to connect to Sauce OnDemand");
       }
     }
   } catch (Exception e) {
     return FormValidation.error(e, "Failed to connect to Sauce OnDemand");
   }
 }
 /**
  * Copy constructor.
  *
  * @param config the Config object to be copied.
  */
 public Config(IGerritHudsonTriggerConfig config) {
   gerritHostName = config.getGerritHostName();
   gerritSshPort = config.getGerritSshPort();
   gerritProxy = config.getGerritProxy();
   gerritUserName = config.getGerritUserName();
   gerritEMail = config.getGerritEMail();
   notificationLevel = config.getNotificationLevel();
   gerritAuthKeyFile = new File(config.getGerritAuthKeyFile().getPath());
   gerritAuthKeyFilePassword = Secret.fromString(config.getGerritAuthKeyFilePassword());
   useRestApi = config.isUseRestApi();
   gerritHttpUserName = config.getGerritHttpUserName();
   gerritHttpPassword = Secret.fromString(config.getGerritHttpPassword());
   restCodeReview = config.isRestCodeReview();
   restVerified = config.isRestVerified();
   gerritBuildCurrentPatchesOnly = config.isGerritBuildCurrentPatchesOnly();
   numberOfWorkerThreads = config.getNumberOfReceivingWorkerThreads();
   numberOfSendingWorkerThreads = config.getNumberOfSendingWorkerThreads();
   gerritBuildStartedVerifiedValue = config.getGerritBuildStartedVerifiedValue();
   gerritBuildStartedCodeReviewValue = config.getGerritBuildStartedCodeReviewValue();
   gerritBuildSuccessfulVerifiedValue = config.getGerritBuildSuccessfulVerifiedValue();
   gerritBuildSuccessfulCodeReviewValue = config.getGerritBuildSuccessfulCodeReviewValue();
   gerritBuildFailedVerifiedValue = config.getGerritBuildFailedVerifiedValue();
   gerritBuildFailedCodeReviewValue = config.getGerritBuildFailedCodeReviewValue();
   gerritBuildUnstableVerifiedValue = config.getGerritBuildUnstableVerifiedValue();
   gerritBuildUnstableCodeReviewValue = config.getGerritBuildUnstableCodeReviewValue();
   gerritBuildNotBuiltVerifiedValue = config.getGerritBuildNotBuiltVerifiedValue();
   gerritBuildNotBuiltCodeReviewValue = config.getGerritBuildNotBuiltCodeReviewValue();
   gerritVerifiedCmdBuildStarted = config.getGerritCmdBuildStarted();
   gerritVerifiedCmdBuildFailed = config.getGerritCmdBuildFailed();
   gerritVerifiedCmdBuildSuccessful = config.getGerritCmdBuildSuccessful();
   gerritVerifiedCmdBuildUnstable = config.getGerritCmdBuildUnstable();
   gerritVerifiedCmdBuildNotBuilt = config.getGerritCmdBuildNotBuilt();
   gerritFrontEndUrl = config.getGerritFrontEndUrl();
   enableManualTrigger = config.isEnableManualTrigger();
   enablePluginMessages = config.isEnablePluginMessages();
   buildScheduleDelay = config.getBuildScheduleDelay();
   dynamicConfigRefreshInterval = config.getDynamicConfigRefreshInterval();
   enableProjectAutoCompletion = config.isEnableProjectAutoCompletion();
   projectListFetchDelay = config.getProjectListFetchDelay();
   projectListRefreshInterval = config.getProjectListRefreshInterval();
   if (config.getCategories() != null) {
     categories = new LinkedList<VerdictCategory>();
     for (VerdictCategory cat : config.getCategories()) {
       categories.add(new VerdictCategory(cat.getVerdictValue(), cat.getVerdictDescription()));
     }
   }
   if (config.getReplicationConfig() != null) {
     replicationConfig = new ReplicationConfig(config.getReplicationConfig());
   }
   watchdogTimeoutMinutes = config.getWatchdogTimeoutMinutes();
   watchTimeExceptionData = addWatchTimeExceptionData(config.getExceptionData());
 }
Beispiel #3
0
 public static AWSCredentialsProvider createCredentialsProvider(
     final boolean useInstanceProfileForCredentials,
     final String accessId,
     final String secretKey) {
   return createCredentialsProvider(
       useInstanceProfileForCredentials, accessId.trim(), Secret.fromString(secretKey.trim()));
 }
Beispiel #4
0
  protected EC2Cloud(
      String id,
      boolean useInstanceProfileForCredentials,
      String accessId,
      String secretKey,
      String privateKey,
      String instanceCapStr,
      List<? extends SlaveTemplate> templates) {
    super(id);
    this.useInstanceProfileForCredentials = useInstanceProfileForCredentials;
    this.accessId = accessId.trim();
    this.secretKey = Secret.fromString(secretKey.trim());
    this.privateKey = new EC2PrivateKey(privateKey);

    if (templates == null) {
      this.templates = Collections.emptyList();
    } else {
      this.templates = templates;
    }

    if (instanceCapStr.equals("")) {
      this.instanceCap = Integer.MAX_VALUE;
    } else {
      this.instanceCap = Integer.parseInt(instanceCapStr);
    }

    readResolve(); // set parents
  }
 public void stagingRepository(
     String repository, String user, String password, boolean skipDeletion) {
   this.stagingRepository = repository;
   this.stagingUser = user;
   this.stagingPassword = Secret.fromString(password);
   this.skipDeletion = skipDeletion;
 }
Beispiel #6
0
    @Override
    public boolean configure(StaplerRequest req, JSONObject json) throws FormException {
      // this code is brain dead
      smtpHost = nullify(json.getString("smtpServer"));
      setAdminAddress(json.getString("adminAddress"));

      defaultSuffix = nullify(json.getString("defaultSuffix"));
      String url = nullify(json.getString("url"));
      if (url != null && !url.endsWith("/")) url += '/';
      hudsonUrl = url;

      if (json.has("useSMTPAuth")) {
        JSONObject auth = json.getJSONObject("useSMTPAuth");
        smtpAuthUsername = nullify(auth.getString("smtpAuthUserName"));
        smtpAuthPassword = Secret.fromString(nullify(auth.getString("smtpAuthPassword")));
      } else {
        smtpAuthUsername = null;
        smtpAuthPassword = null;
      }
      smtpPort = nullify(json.getString("smtpPort"));
      useSsl = json.getBoolean("useSsl");
      charset = json.getString("charset");
      if (charset == null || charset.length() == 0) charset = "UTF-8";

      save();
      return true;
    }
 public FormValidation doValidate(
     @QueryParameter String url,
     @QueryParameter String username,
     @QueryParameter String password,
     @QueryParameter String id,
     @QueryParameter String name)
     throws IOException {
   return new Composition(name, url, username, Secret.fromString(password), id).validate();
 }
 @Override
 public void configure(StaplerRequest req, JSONObject formData)
     throws IOException, ServletException, Descriptor.FormException {
   reuseSauceAuth = formData.getBoolean("reuseSauceAuth");
   disableStatusColumn = formData.getBoolean("disableStatusColumn");
   username = formData.getString("username");
   apiKey = Secret.fromString(formData.getString("apiKey"));
   sauceConnectDirectory = formData.getString("sauceConnectDirectory");
   save();
 }
  @Override
  public void configureClientProxy(
      final HttpClient httpClient,
      final HostConfiguration hostConfiguration,
      final HttpState httpState,
      final ConnectionInstanceData connectionInstanceData) {
    hostConfiguration.setProxyHost(proxyHost);

    if (proxyHost != null) {
      final String proxyUser = proxyHost.getProxyUser();
      final Secret proxySecret = proxyHost.getProxySecret();
      if (proxyUser != null && proxySecret != null) {
        httpState.setProxyCredentials(
            AuthScope.ANY, new UsernamePasswordCredentials(proxyUser, proxySecret.getPlainText()));
      } else {
        httpState.setProxyCredentials(AuthScope.ANY, new DefaultNTCredentials());
      }
    }
  }
    public FormValidation doCheckStashUserPassword(@QueryParameter String value)
        throws IOException, ServletException {

      if (value.trim().equals("")
          && ((stashPassword == null) || stashPassword.getPlainText().trim().equals(""))) {
        return FormValidation.warning(
            "You should use a non-empty password here or in the " + "global configuration!");
      } else {
        return FormValidation.ok();
      }
    }
 private TestflightUploader.UploadRequest createPartialUploadRequest(
     TestflightTeam team, EnvVars vars, AbstractBuild<?, ?> build) {
   TestflightUploader.UploadRequest ur = new TestflightUploader.UploadRequest();
   TokenPair tokenPair = getTokenPair(team.getTokenPairName());
   ur.filePaths = vars.expand(StringUtils.trim(team.getFilePath()));
   ur.dsymPath = vars.expand(StringUtils.trim(team.getDsymPath()));
   ur.apiToken = vars.expand(Secret.toString(tokenPair.getApiToken()));
   ur.buildNotes = createBuildNotes(vars.expand(buildNotes), build.getChangeSet());
   ur.lists = vars.expand(lists);
   ur.notifyTeam = notifyTeam;
   ProxyConfiguration proxy = getProxy();
   ur.proxyHost = proxy.name;
   ur.proxyPass = proxy.getPassword();
   ur.proxyPort = proxy.port;
   ur.proxyUser = proxy.getUserName();
   ur.replace = replace;
   ur.teamToken = vars.expand(Secret.toString(tokenPair.getTeamToken()));
   ur.debug = debug;
   return ur;
 }
 public ActiveDirectoryUnixAuthenticationProvider(ActiveDirectorySecurityRealm realm) {
   if (realm.domain == null)
     throw new IllegalArgumentException(
         "Active Directory domain name is required but it is not set");
   this.domainNames = realm.domain.split(",");
   this.site = realm.site;
   this.bindName = realm.bindName;
   this.server = realm.server;
   this.bindPassword = Secret.toString(realm.bindPassword);
   this.descriptor = realm.getDescriptor();
 }
Beispiel #13
0
  public static AWSCredentialsProvider createCredentialsProvider(
      final boolean useInstanceProfileForCredentials,
      final String accessId,
      final Secret secretKey) {

    if (useInstanceProfileForCredentials) {
      return new InstanceProfileCredentialsProvider();
    }

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessId, Secret.toString(secretKey));
    return new StaticCredentialsProvider(credentials);
  }
    @Override
    public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {

      // to persist global configuration information,
      // set that to properties and call save().
      stashUser = formData.getString("stashUser");
      stashPassword = Secret.fromString(formData.getString("stashPassword"));
      stashRootUrl = formData.getString("stashRootUrl");
      ignoreUnverifiedSsl = formData.getBoolean("ignoreUnverifiedSsl");
      includeBuildNumberInKey = formData.getBoolean("includeBuildNumberInKey");
      save();
      return super.configure(req, formData);
    }
 /**
  * Constructor SSHLauncher creates a new SSHLauncher instance.
  *
  * @param port The port to connect on.
  * @param username The username to connect as.
  * @param password The password to connect with.
  * @param privatekey The ssh privatekey to connect with.
  * @param jvmOptions jvm options.
  * @param javaPath optional path to java.
  */
 @DataBoundConstructor
 public SSHConnector(
     int port,
     String username,
     String password,
     String privatekey,
     String jvmOptions,
     String javaPath) {
   this.jvmOptions = jvmOptions;
   this.port = port == 0 ? 22 : port;
   this.username = username;
   this.password = Secret.fromString(fixEmpty(password));
   this.privatekey = privatekey;
   this.javaPath = javaPath;
 }
 public void put(String url) throws IOException {
   DBObject token = getToken(url);
   GithubAuthenticationToken auth =
       (GithubAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
   GitHub gh = auth.getGitHub();
   if (token != null) {
     delete(token);
   }
   String accessToken = Secret.fromString(auth.getAccessToken()).getEncryptedValue();
   BasicDBObject doc =
       new BasicDBObject("user", gh.getMyself().getLogin())
           .append("access_token", accessToken)
           .append("repo_url", url);
   save(doc);
 }
    @Override
    public void decorateHome(final JenkinsRule jenkinsRule, final File home) throws Exception {
      final String jobFolder = parent.getJobFolder();
      final String configXmlPath = jobFolder + "config.xml";
      final File configXmlFile = new File(home, configXmlPath);

      final String tfsServerUrl = helper.getServerUrl();
      XmlHelper.pokeValue(configXmlFile, "/project/scm/serverUrl", tfsServerUrl);

      final String projectPath = parent.getPathInTfvc();
      XmlHelper.pokeValue(configXmlFile, "/project/scm/projectPath", projectPath);

      final String workspaceName = "Hudson-${JOB_NAME}-${COMPUTERNAME}";
      XmlHelper.pokeValue(configXmlFile, "/project/scm/workspaceName", workspaceName);

      final String userName = helper.getUserName();
      XmlHelper.pokeValue(configXmlFile, "/project/scm/userName", userName);

      final String userPassword = helper.getUserPassword();
      final SecretOverride secretOverride = new SecretOverride();
      try {
        final Secret secret = Secret.fromString(userPassword);
        encryptedPassword = secret.getEncryptedValue();
      } finally {
        try {
          secretOverride.close();
        } catch (IOException e) {
          // ignore
        }
      }
      final String projectScmPassword = "******";
      final String currentPassword = XmlHelper.peekValue(configXmlFile, projectScmPassword);
      if (currentPassword != null) {
        XmlHelper.pokeValue(configXmlFile, projectScmPassword, encryptedPassword);
      }
    }
  @DataBoundConstructor
  public ActiveDirectorySecurityRealm(
      String domain, String site, String bindName, String bindPassword, String server) {
    this.domain = fixEmpty(domain);
    this.site = fixEmpty(site);
    this.bindName = fixEmpty(bindName);
    this.bindPassword = Secret.fromString(fixEmpty(bindPassword));

    // append default port if not specified
    server = fixEmpty(server);
    if (server != null) {
      if (!server.contains(":")) server += ":3268";
    }

    this.server = server;
  }
 @Before
 public void setup() throws IOException {
   for (CredentialsStore credentialsStore :
       CredentialsProvider.lookupStores(Jenkins.getInstance())) {
     if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
       List<Domain> domains = credentialsStore.getDomains();
       credentialsStore.addCredentials(
           domains.get(0),
           new StringCredentialsImpl(
               CredentialsScope.SYSTEM,
               API_TOKEN_ID,
               "GitLab API Token",
               Secret.fromString(API_TOKEN_ID)));
     }
   }
 }
 @DataBoundConstructor
 public StashNotifier(
     String stashServerBaseUrl,
     String stashUserName,
     String stashUserPassword,
     boolean ignoreUnverifiedSSLPeer,
     String commitSha1,
     boolean includeBuildNumberInKey) {
   this.stashServerBaseUrl =
       stashServerBaseUrl.endsWith("/")
           ? stashServerBaseUrl.substring(0, stashServerBaseUrl.length() - 1)
           : stashServerBaseUrl;
   this.stashUserName = stashUserName;
   this.stashUserPassword = Secret.fromString(stashUserPassword);
   this.ignoreUnverifiedSSLPeer = ignoreUnverifiedSSLPeer;
   this.commitSha1 = commitSha1;
   this.includeBuildNumberInKey = includeBuildNumberInKey;
 }
Beispiel #21
0
    /**
     * @param keyLength Block size of the asymmetric cipher, in bits. I thought I can get it from
     *     {@code asym.getBlockSize()} but that doesn't work with Sun's implementation.
     */
    public CombinedCipherInputStream(InputStream in, Cipher asym, String algorithm, int keyLength)
        throws IOException, GeneralSecurityException {
      super(in);

      String keyAlgorithm = getKeyAlgorithm(algorithm);

      // first read the symmetric key cipher
      byte[] symKeyBytes = new byte[keyLength / 8];
      new DataInputStream(in).readFully(symKeyBytes);
      SecretKey symKey = new SecretKeySpec(asym.doFinal(symKeyBytes), keyAlgorithm);

      // the rest of the data will be decrypted by this symmetric cipher
      Cipher sym = Secret.getCipher(algorithm);
      sym.init(
          Cipher.DECRYPT_MODE,
          symKey,
          keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded()));
      super.in = new CipherInputStream(in, sym);
    }
Beispiel #22
0
    public CombinedCipherOutputStream(OutputStream out, Cipher asym, String algorithm)
        throws IOException, GeneralSecurityException {
      super(out);

      // create a new symmetric cipher key used for this stream
      String keyAlgorithm = getKeyAlgorithm(algorithm);
      SecretKey symKey = KeyGenerator.getInstance(keyAlgorithm).generateKey();

      // place the symmetric key by encrypting it with asymmetric cipher
      out.write(asym.doFinal(symKey.getEncoded()));

      // the rest of the data will be encrypted by this symmetric cipher
      Cipher sym = Secret.getCipher(algorithm);
      sym.init(
          Cipher.ENCRYPT_MODE,
          symKey,
          keyAlgorithm.equals(algorithm) ? null : new IvParameterSpec(symKey.getEncoded()));
      super.out = new CipherOutputStream(out, sym);
    }
Beispiel #23
0
    /**
     * Send an email to the admin address
     *
     * @throws IOException
     * @throws ServletException
     * @throws InterruptedException
     */
    public FormValidation doSendTestMail(
        @QueryParameter String smtpServer,
        @QueryParameter String adminAddress,
        @QueryParameter boolean useSMTPAuth,
        @QueryParameter String smtpAuthUserName,
        @QueryParameter String smtpAuthPassword,
        @QueryParameter boolean useSsl,
        @QueryParameter String smtpPort)
        throws IOException, ServletException, InterruptedException {
      try {
        if (!useSMTPAuth) smtpAuthUserName = smtpAuthPassword = null;

        MimeMessage msg =
            new MimeMessage(
                createSession(
                    smtpServer,
                    smtpPort,
                    useSsl,
                    smtpAuthUserName,
                    Secret.fromString(smtpAuthPassword)));
        msg.setSubject("Test email #" + ++testEmailCount);
        msg.setContent(
            "This is test email #"
                + testEmailCount
                + " sent from Hudson Continuous Integration server.",
            "text/plain");
        msg.setFrom(new InternetAddress(adminAddress));
        msg.setSentDate(new Date());
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(adminAddress));

        Transport.send(msg);

        return FormValidation.ok("Email was successfully sent");
      } catch (MessagingException e) {
        return FormValidation.errorWithMarkup(
            "<p>Failed to send out e-mail</p><pre>"
                + Util.escape(Functions.printThrowable(e))
                + "</pre>");
      }
    }
Beispiel #24
0
    private static Session createSession(
        String smtpHost,
        String smtpPort,
        boolean useSsl,
        String smtpAuthUserName,
        Secret smtpAuthPassword) {
      smtpPort = fixEmptyAndTrim(smtpPort);
      smtpAuthUserName = fixEmptyAndTrim(smtpAuthUserName);

      Properties props = new Properties(System.getProperties());
      if (fixEmptyAndTrim(smtpHost) != null) props.put("mail.smtp.host", smtpHost);
      if (smtpPort != null) {
        props.put("mail.smtp.port", smtpPort);
      }
      if (useSsl) {
        /* This allows the user to override settings by setting system properties but
         * also allows us to use the default SMTPs port of 465 if no port is already set.
         * It would be cleaner to use smtps, but that's done by calling session.getTransport()...
         * and thats done in mail sender, and it would be a bit of a hack to get it all to
         * coordinate, and we can make it work through setting mail.smtp properties.
         */
        if (props.getProperty("mail.smtp.socketFactory.port") == null) {
          String port = smtpPort == null ? "465" : smtpPort;
          props.put("mail.smtp.port", port);
          props.put("mail.smtp.socketFactory.port", port);
        }
        if (props.getProperty("mail.smtp.socketFactory.class") == null) {
          props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        props.put("mail.smtp.socketFactory.fallback", "false");
      }
      if (smtpAuthUserName != null) props.put("mail.smtp.auth", "true");

      // avoid hang by setting some timeout.
      props.put("mail.smtp.timeout", "60000");
      props.put("mail.smtp.connectiontimeout", "60000");

      return Session.getInstance(
          props, getAuthenticator(smtpAuthUserName, Secret.toString(smtpAuthPassword)));
    }
  /**
   * Returns the HTTP POST request ready to be sent to the Stash build API for the given build and
   * change set.
   *
   * @param stashBuildNotificationEntity a entity containing the parameters for Stash
   * @param commitSha1 the SHA1 of the commit that was built
   * @return the HTTP POST request to the Stash build API
   */
  private HttpPost createRequest(
      final HttpEntity stashBuildNotificationEntity, final String commitSha1) {

    String url = stashServerBaseUrl;
    String username = stashUserName;
    String pwd = Secret.toString(stashUserPassword);
    DescriptorImpl descriptor = getDescriptor();

    if ("".equals(url) || url == null) url = descriptor.getStashRootUrl();
    if ("".equals(username) || username == null) username = descriptor.getStashUser();
    if ("".equals(pwd) || pwd == null) pwd = descriptor.getStashPassword().getPlainText();

    HttpPost req = new HttpPost(url + "/rest/build-status/1.0/commits/" + commitSha1);

    req.addHeader(
        BasicScheme.authenticate(new UsernamePasswordCredentials(username, pwd), "UTF-8", false));

    req.addHeader("Content-type", "application/json");
    req.setEntity(stashBuildNotificationEntity);

    return req;
  }
 public void releaseRepository(String repository, String user, String password) {
   this.releaseRepository = repository;
   this.releaseUser = user;
   this.releasePassword = Secret.fromString(password);
 }
 public String getValue() {
   return value != null ? Secret.toString(value) : null;
 }
 @Override
 public void buildEnvVars(AbstractBuild<?, ?> build, Map<String, String> env) {
   env.put(name.toUpperCase(), value != null ? Secret.toString(value) : null);
 }
 @DataBoundConstructor
 public PasswordParameterValue(String name, String value, String description) {
   super(name, description);
   this.value = Secret.fromString(value);
 }
 /**
  * Sets gerritHttpPassword.
  *
  * @param gerritHttpPassword the password
  * @see #getGerritHttpPassword()
  */
 public void setGerritHttpPassword(String gerritHttpPassword) {
   this.gerritHttpPassword = Secret.fromString(gerritHttpPassword);
 }