hudson.util.Secret Java Examples
The following examples show how to use
hudson.util.Secret.
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: DescriptorImpl.java From zulip-plugin with MIT License | 6 votes |
@Override public boolean configure(StaplerRequest req, JSONObject json) throws FormException { url = (String) json.get("url"); email = (String) json.get("email"); apiKey = Secret.fromString((String) json.get("apiKey")); stream = (String) json.get("stream"); topic = (String) json.get("topic"); jenkinsUrl = (String) json.get("jenkinsUrl"); smartNotify = Boolean.TRUE.equals(json.get("smartNotify")); save(); // Cleanup the configuration file from previous plugin id - humbug File oldConfig = new File(Jenkins.getInstance().getRootDir(), OLD_CONFIG_FILE_NAME); if (oldConfig.exists()) { if (oldConfig.delete()) { logger.log(Level.INFO, "Old humbug configuration file successfully cleaned up."); } else { logger.log(Level.WARNING, "Failed to cleanup old humbug configuration file."); } } return super.configure(req, json); }
Example #2
Source File: LambdaInvokeBuildStepTest.java From aws-lambda-jenkins-plugin with MIT License | 6 votes |
@Ignore @Test public void testHtml() throws Exception { List<JsonParameterVariables> jsonParameterVariables = new ArrayList<JsonParameterVariables>(); jsonParameterVariables.add(new JsonParameterVariables("KEY", "value")); LambdaInvokeBuildStepVariables variables = new LambdaInvokeBuildStepVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "function", "payload", true, jsonParameterVariables); FreeStyleProject p = j.createFreeStyleProject(); LambdaInvokeBuildStep before = new LambdaInvokeBuildStep(variables); p.getBuildersList().add(before); j.submit(j.createWebClient().getPage(p, "configure").getFormByName("config")); LambdaInvokeBuildStep after = p.getBuildersList().get(LambdaInvokeBuildStep.class); assertEquals(before, after); }
Example #3
Source File: AxivionSuite.java From warnings-ng-plugin with MIT License | 6 votes |
private UsernamePasswordCredentials withValidCredentials() { final List<StandardUsernamePasswordCredentials> all = CredentialsProvider.lookupCredentials( StandardUsernamePasswordCredentials.class, (Item) null, ACL.SYSTEM, Collections.emptyList()); StandardUsernamePasswordCredentials jenkinsCredentials = CredentialsMatchers.firstOrNull(all, CredentialsMatchers.withId(credentialsId)); if (jenkinsCredentials == null) { throw new ParsingException("Could not find the credentials for " + credentialsId); } return new UsernamePasswordCredentials( jenkinsCredentials.getUsername(), Secret.toString(jenkinsCredentials.getPassword())); }
Example #4
Source File: LambdaUploadPublisherTest.java From aws-lambda-jenkins-plugin with MIT License | 6 votes |
@Test @Ignore public void testHtml() throws Exception { LambdaUploadVariables variables = new LambdaUploadVariables(false, "accessKeyId", Secret.fromString("secretKey"), "eu-west-1", "ziplocation", "description", "function", "handler", "1024", "role", "nodejs", "30", true, false, "full", null, false, "", ""); List<LambdaUploadVariables> variablesList = new ArrayList<>(); variablesList.add(variables); FreeStyleProject p = j.createFreeStyleProject(); LambdaUploadPublisher before = new LambdaUploadPublisher(variablesList); p.getPublishersList().add(before); j.submit(j.createWebClient().getPage(p,"configure").getFormByName("config")); LambdaUploadPublisher after = p.getPublishersList().get(LambdaUploadPublisher.class); assertEquals(before, after); }
Example #5
Source File: ProxyConfiguratorTest.java From configuration-as-code-plugin with MIT License | 6 votes |
@Test @ConfiguredWithCode("Proxy.yml") public void describeProxyConfig() throws Exception { ConfiguratorRegistry registry = ConfiguratorRegistry.get(); ConfigurationContext context = new ConfigurationContext(registry); final CNode configNode = getProxyNode(context); Secret password = requireNonNull(Secret.decrypt(getProxyNode(context).getScalarValue("secretPassword"))); final String yamlConfig = Util.toYamlString(configNode); assertEquals(String.join("\n", "name: \"proxyhost\"", "noProxyHost: \"externalhost\"", "port: 80", "secretPassword: \"" + password.getEncryptedValue() + "\"", "testUrl: \"http://google.com\"", "userName: \"login\"", "" ), yamlConfig); }
Example #6
Source File: BindingStepTest.java From credentials-binding-plugin with MIT License | 6 votes |
@Issue("JENKINS-27389") @Test public void grabEnv() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { String credentialsId = "creds"; String secret = "s3cr3t"; CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret))); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("" + "def extract(id) {\n" + " def v\n" + " withCredentials([string(credentialsId: id, variable: 'temp')]) {\n" + " v = env.temp\n" + " }\n" + " v\n" + "}\n" + "node {\n" + " echo \"got: ${extract('" + credentialsId + "')}\"\n" + "}", true)); story.j.assertLogContains("got: " + secret, story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get())); } }); }
Example #7
Source File: AWSCodePipelineSCMTest.java From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 | 5 votes |
public void setUp() throws IOException, InterruptedException, ReflectiveOperationException { MockitoAnnotations.initMocks(this); jobId = UUID.randomUUID().toString(); jobNonce = UUID.randomUUID().toString(); // Override the secret key so that we can test this class without {@link jenkins.model.Jenkins}. Field field = Secret.class.getDeclaredField("SECRET"); field.setAccessible(true); field.set(null, RandomStringUtils.random(16)); }
Example #8
Source File: ConduitCredentialsImpl.java From phabricator-jenkins-plugin with MIT License | 5 votes |
@DataBoundConstructor public ConduitCredentialsImpl( @CheckForNull String id, @NonNull @CheckForNull String url, @Nullable String gateway, @CheckForNull String description, @CheckForNull String token) { super(id, description); this.url = url; this.gateway = gateway; this.token = Secret.fromString(token); }
Example #9
Source File: LambdaPublishBuildStepVariablesTest.java From aws-lambda-jenkins-plugin with MIT License | 5 votes |
@Test public void testGetLambdaClientConfig() throws Exception { LambdaPublishBuildStepVariables variables = new LambdaPublishBuildStepVariables(false, "ID", Secret.fromString("SECRET}"), "eu-west-1", "ARN", "ALIAS", "DESCRIPTION"); variables.expandVariables(new EnvVars()); LambdaClientConfig lambdaClientConfig = variables.getLambdaClientConfig(); AWSLambda lambda = lambdaClientConfig.getClient(); assertNotNull(lambda); }
Example #10
Source File: AWSCodePipelineSCM.java From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 | 5 votes |
public AWSCodePipelineSCM( final String projectName, final boolean clear, final String region, final String awsAccessKey, final String awsSecretKey, final String proxyHost, final String proxyPort, final String category, final String provider, final String version, final AWSClientFactory awsClientFactory) { clearWorkspace = clear; this.region = Validation.sanitize(region.trim()); this.awsAccessKey = Validation.sanitize(awsAccessKey.trim()); this.awsSecretKey = Secret.fromString(Validation.sanitize(awsSecretKey.trim())); this.proxyHost = Validation.sanitize(proxyHost.trim()); this.projectName = null; actionTypeCategory = Validation.sanitize(category.trim()); actionTypeProvider = Validation.sanitize(provider.trim()); actionTypeVersion = Validation.sanitize(version.trim()); this.awsClientFactory = awsClientFactory; if (proxyPort != null && !proxyPort.isEmpty()) { this.proxyPort = Integer.parseInt(proxyPort); } else { this.proxyPort = 0; } }
Example #11
Source File: SSHUserPrivateKeyBinding.java From credentials-binding-plugin with MIT License | 5 votes |
@Override public MultiEnvironment bind(Run<?,?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { SSHUserPrivateKey sshKey = getCredentials(build); UnbindableDir keyDir = UnbindableDir.create(workspace); FilePath keyFile = keyDir.getDirPath().child("ssh-key-" + keyFileVariable); StringBuilder contents = new StringBuilder(); for (String key : sshKey.getPrivateKeys()) { contents.append(key); contents.append('\n'); } keyFile.write(contents.toString(), "UTF-8"); keyFile.chmod(0400); Map<String, String> map = new LinkedHashMap<>(); map.put(keyFileVariable, keyFile.getRemote()); if (passphraseVariable != null) { Secret passphrase = sshKey.getPassphrase(); if (passphrase != null) { map.put(passphraseVariable, passphrase.getPlainText()); } else { map.put(passphraseVariable, ""); } } if (usernameVariable != null) { map.put(usernameVariable, sshKey.getUsername()); } return new MultiEnvironment(map, keyDir.getUnbinder()); }
Example #12
Source File: CreateUploadResourceTaskTest.java From appcenter-plugin with MIT License | 5 votes |
@Before public void setUp() { baseRequest = new UploadRequest.Builder() .setOwnerName("owner-name") .setAppName("app-name") .build(); given(mockTaskListener.getLogger()).willReturn(mockLogger); final AppCenterServiceFactory factory = new AppCenterServiceFactory(Secret.fromString("secret-token"), mockWebServer.url("/").toString(), mockProxyConfig); task = new CreateUploadResourceTask(mockTaskListener, factory); }
Example #13
Source File: CredentialsProviderImplTest.java From git-client-plugin with MIT License | 5 votes |
@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 #14
Source File: VaultAppRoleCredential.java From hashicorp-vault-plugin with MIT License | 5 votes |
@DataBoundConstructor public VaultAppRoleCredential(@CheckForNull CredentialsScope scope, @CheckForNull String id, @CheckForNull String description, @NonNull String roleId, @NonNull Secret secretId, String path) { super(scope, id, description); this.secretId = secretId; this.roleId = roleId; if (path == null) { this.path = "approle"; } else { this.path = path; } }
Example #15
Source File: LambdaInvokeBuildStepVariables.java From aws-lambda-jenkins-plugin with MIT License | 5 votes |
public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(awsSecretKey)), env); awsRegion = ExpansionUtils.expand(awsRegion, env); functionName = ExpansionUtils.expand(functionName, env); payload = ExpansionUtils.expand(payload, env); if(jsonParameters != null) { for (JsonParameterVariables jsonParameter : jsonParameters) { jsonParameter.expandVariables(env); } } }
Example #16
Source File: AWSCodePipelineSCM.java From aws-codepipeline-plugin-for-jenkins with Apache License 2.0 | 5 votes |
public void initializeModel() { final CodePipelineStateModel model = new CodePipelineStateModel(); model.setActionTypeCategory(actionTypeCategory); model.setAwsAccessKey(awsAccessKey); model.setAwsSecretKey(Secret.toString(awsSecretKey)); model.setCompressionType(CompressionType.None); model.setJob(job); model.setProxyHost(proxyHost); model.setProxyPort(proxyPort); model.setRegion(region); CodePipelineStateService.setModel(model); }
Example #17
Source File: LambdaEventSourceBuildStepVariables.java From aws-lambda-jenkins-plugin with MIT License | 5 votes |
@Deprecated public LambdaEventSourceBuildStepVariables(boolean useInstanceCredentials, String awsAccessKeyId, Secret awsSecretKey, String awsRegion, String functionName, String functionAlias, String eventSourceArn) { this.useInstanceCredentials = useInstanceCredentials; this.awsAccessKeyId = awsAccessKeyId; this.awsSecretKey = awsSecretKey != null ? awsSecretKey.getEncryptedValue() : null; this.awsRegion = awsRegion; this.functionName = functionName; this.functionAlias = functionAlias; this.eventSourceArn = eventSourceArn; }
Example #18
Source File: TestUtility.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
static void setupGitLabConnections(JenkinsRule jenkins, MockServerRule mockServer) throws IOException { GitLabConnectionConfig connectionConfig = jenkins.get(GitLabConnectionConfig.class); String apiTokenId = "apiTokenId"; 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, apiTokenId, "GitLab API Token", Secret.fromString(TestUtility.API_TOKEN))); } } connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V3, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V3GitLabClientBuilder(), false, 10, 10)); connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V4, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V4GitLabClientBuilder(), false, 10, 10)); }
Example #19
Source File: VaultStringCredentialImpl.java From hashicorp-vault-plugin with MIT License | 5 votes |
@NonNull @Override public Secret getSecret() { String k = defaultIfBlank(vaultKey, DEFAULT_VAULT_KEY); String s = getVaultSecret(path, k, engineVersion); if (s == null) { throw new VaultPluginException("Fetching from Vault failed for key " + k, null); } return Secret.fromString(s); }
Example #20
Source File: VaultGithubTokenCredential.java From hashicorp-vault-plugin with MIT License | 5 votes |
@Override public String getToken(Vault vault) { try { return vault.auth().loginByGithub(Secret.toString(accessToken)).getAuthClientToken(); } catch (VaultException e) { throw new VaultPluginException("could not log in into vault", e); } }
Example #21
Source File: DingTalkSecurityPolicyConfig.java From dingtalk-plugin with MIT License | 5 votes |
@DataBoundConstructor public DingTalkSecurityPolicyConfig(boolean checked, String type, String value, String desc) { this.checked = checked; this.type = type; this.value = Secret.fromString(value); this.desc = desc; }
Example #22
Source File: AWSDeviceFarmRecorder.java From aws-device-farm-jenkins-plugin with Apache License 2.0 | 5 votes |
/** * Validate top level configuration values. * * @param log Destination Task Log * @return Whether or not the configuration is valid. */ private boolean validateConfiguration(@Nonnull PrintStream log) { String roleArn = getRoleArn(); String akid = Secret.toString(getAkid()); String skid = Secret.toString(getSkid()); // [Required]: Auth Credentials if ((roleArn == null || roleArn.isEmpty()) && (akid == null || akid.isEmpty() || skid == null || skid.isEmpty())) { writeToLog(log, "Either IAM Role ARN or AKID/SKID must be set."); return false; } // [Required]: Project if (projectName == null || projectName.isEmpty()) { writeToLog(log, "Project must be set."); return false; } // [Required]: DevicePool if (devicePoolName == null || devicePoolName.isEmpty()) { writeToLog(log, "DevicePool must be set."); return false; } // [Required]: App Artifact if (!ifWebApp && (appArtifact == null || appArtifact.isEmpty())) { writeToLog(log, "Application Artifact must be set."); return false; } // [Required]: At least one test. if (testToRun == null || stringToTestType(testToRun) == null) { writeToLog(log, "A test type must be set."); return false; } return true; }
Example #23
Source File: ExportTest.java From configuration-as-code-plugin with MIT License | 5 votes |
@Test @Issue("SECURITY-1458") public void shouldNotExportValuesWithSecretConstructors() throws Exception { DataBoundConfigurator<DataBoundSecretConstructor> c = new DataBoundConfigurator<>(DataBoundSecretConstructor.class); String res = export(c, new DataBoundSecretConstructor(Secret.fromString("test"))); assertThat(res, not(containsString("test"))); }
Example #24
Source File: LambdaInvokeBuildStepVariables.java From aws-lambda-jenkins-plugin with MIT License | 5 votes |
@Deprecated public LambdaInvokeBuildStepVariables(boolean useInstanceCredentials, String awsAccessKeyId, Secret awsSecretKey, String awsRegion, String functionName, String payload, boolean synchronous, List<JsonParameterVariables> jsonParameters) { this.useInstanceCredentials = useInstanceCredentials; this.awsAccessKeyId = awsAccessKeyId; this.awsSecretKey = awsSecretKey != null ? awsSecretKey.getEncryptedValue() : null; this.awsRegion = awsRegion; this.functionName = functionName; this.payload = payload; this.synchronous = synchronous; this.jsonParameters = jsonParameters; }
Example #25
Source File: BindingStepTest.java From credentials-binding-plugin with MIT License | 5 votes |
@Issue("JENKINS-38831") @Test public void testTrackingOfCredential() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { String credentialsId = "creds"; String secret = "s3cr3t"; StringCredentialsImpl credentials = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)); Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credentials); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), credentials); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("" + "def extract(id) {\n" + " def v\n" + " withCredentials([[$class: 'StringBinding', credentialsId: id, variable: 'temp']]) {\n" + " v = env.temp\n" + " }\n" + " v\n" + "}\n" + "node {\n" + " echo \"got: ${extract('" + credentialsId + "')}\"\n" + "}", true)); assertThat("No fingerprint created until first use", fingerprint, nullValue()); story.j.assertLogContains("got: " + secret, story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get())); fingerprint = CredentialsProvider.getFingerprintOf(credentials); assertThat(fingerprint, notNullValue()); assertThat(fingerprint.getJobs(), hasItem(is(p.getFullName()))); } }); }
Example #26
Source File: IntegrationTest.java From zulip-plugin with MIT License | 5 votes |
private void verifyGlobalConfig() { DescriptorImpl globalConfig = j.jenkins.getDescriptorByType(DescriptorImpl.class); assertEquals("ZulipUrl", globalConfig.getUrl()); assertEquals("[email protected]", globalConfig.getEmail()); assertEquals("secret", Secret.toString(globalConfig.getApiKey())); assertEquals("defaultStream", globalConfig.getStream()); assertEquals("defaultTopic", globalConfig.getTopic()); assertTrue(globalConfig.isSmartNotify()); assertEquals("JenkinsUrl", globalConfig.getJenkinsUrl()); }
Example #27
Source File: GitLabConnectionConfigSSLTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
@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))); } } }
Example #28
Source File: LambdaPublishVariables.java From aws-lambda-jenkins-plugin with MIT License | 5 votes |
public void expandVariables(EnvVars env) { awsAccessKeyId = ExpansionUtils.expand(awsAccessKeyId, env); clearTextAwsSecretKey = ExpansionUtils.expand(Secret.toString(Secret.fromString(this.awsSecretKey)), env); awsRegion = ExpansionUtils.expand(this.awsRegion, env); functionARN = ExpansionUtils.expand(this.functionARN, env); functionAlias = ExpansionUtils.expand(this.functionAlias, env); versionDescription = ExpansionUtils.expand(this.versionDescription, env); }
Example #29
Source File: DockerServerEndpointTest.java From docker-commons-plugin with MIT License | 5 votes |
@Test public void smokes() throws Exception { DumbSlave slave = j.createOnlineSlave(); VirtualChannel channel = slave.getChannel(); FreeStyleProject item = j.createFreeStyleProject(); CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next(); assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class)); Domain domain = new Domain("docker", "A domain for docker credentials", Collections.<DomainSpecification>singletonList(new DockerServerDomainSpecification())); DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c"); store.addDomain(domain, credentials); DockerServerEndpoint endpoint = new DockerServerEndpoint("tcp://localhost:2736", credentials.getId()); FilePath dotDocker = DockerServerEndpoint.dotDocker(channel); List<FilePath> dotDockerKids = dotDocker.list(); int initialSize = dotDockerKids == null ? 0 : dotDockerKids.size(); KeyMaterialFactory factory = endpoint.newKeyMaterialFactory(item, channel); KeyMaterial keyMaterial = factory.materialize(); FilePath path = null; try { assertThat(keyMaterial.env().get("DOCKER_HOST", "missing"), is("tcp://localhost:2736")); assertThat(keyMaterial.env().get("DOCKER_TLS_VERIFY", "missing"), is("1")); assertThat(keyMaterial.env().get("DOCKER_CERT_PATH", "missing"), not("missing")); path = new FilePath(channel, keyMaterial.env().get("DOCKER_CERT_PATH", "missing")); if (!Functions.isWindows()) { assertThat(path.mode() & 0777, is(0700)); } assertThat(path.child("key.pem").readToString(), is("a")); assertThat(path.child("cert.pem").readToString(), is("b")); assertThat(path.child("ca.pem").readToString(), is("c")); } finally { keyMaterial.close(); } assertThat(path.child("key.pem").exists(), is(false)); assertThat(path.child("cert.pem").exists(), is(false)); assertThat(path.child("ca.pem").exists(), is(false)); assertThat(dotDocker.list().size(), is(initialSize)); }
Example #30
Source File: VaultTokenCredentialBindingIT.java From hashicorp-vault-plugin with MIT License | 5 votes |
@Test public void shouldFailIfMissingVaultAddress() { final String credentialsId = "creds"; final String token = "fakeToken"; final String jobId = "testJob"; story.addStep(new Statement() { @Override public void evaluate() throws Throwable { VaultTokenCredential c = new VaultTokenCredential(CredentialsScope.GLOBAL, credentialsId, "fake description", Secret.fromString(token)); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next() .addCredentials(Domain.global(), c); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, jobId); p.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withCredentials([[$class: 'VaultTokenCredentialBinding', addrVariable: 'VAULT_ADDR', tokenVariable: 'VAULT_TOKEN', credentialsId: '" + credentialsId + "']]) {\n" + " " + getShellString() + " 'echo \"" + getVariable("VAULT_ADDR") + ":" + getVariable("VAULT_TOKEN") + "\" > script'\n" + " }\n" + "}", true)); WorkflowRun b = p.scheduleBuild2(0).waitForStart(); story.j.assertBuildStatus(Result.FAILURE, story.j.waitForCompletion(b)); story.j.assertLogNotContains(token, b); } }); }