private String createCredentials(String username, String password) { String credentialId = name + "_" + username; try{ StandardCredentials credential = retrieveCredential(credentialId); if (credential != null) { return StringUtils.EMPTY; } UsernamePasswordCredentialsImpl migrateCredential = new UsernamePasswordCredentialsImpl( CredentialsScope.GLOBAL, name + "_" + username, "Migrated Coverity Credential", username, password); CredentialsStore store = CredentialsProvider.lookupStores(Jenkins.getInstance()).iterator().next(); store.addCredentials(Domain.global(), migrateCredential); } catch (IOException ioe) { logger.warning("Migrating username and password into credentials encountered IOException" + "\nPlease try to resolve this issue by adding credentials manually"); return StringUtils.EMPTY; } return credentialId; }
private static String createCredentials(String serverAPIUrl, StandardCredentials credentials) throws Exception { List<DomainSpecification> specifications = new ArrayList<DomainSpecification>(2); URI serverUri = new URI(serverAPIUrl); if (serverUri.getPort() > 0) { specifications.add(new HostnamePortSpecification(serverUri.getHost() + ":" + serverUri.getPort(), null)); } else { specifications.add(new HostnameSpecification(serverUri.getHost(), null)); } specifications.add(new SchemeSpecification(serverUri.getScheme())); String path = serverUri.getPath(); if (StringUtils.isEmpty(path)) { path = "/"; } specifications.add(new PathSpecification(path, null, false)); Domain domain = new Domain(serverUri.getHost(), "Auto generated credentials domain", specifications); CredentialsStore provider = new SystemCredentialsProvider.StoreImpl(); provider.addDomain(domain, credentials); return credentials.getId(); }
/** * Returns {@code true} if and only if the supplied {@link DomainRequirement}s are a match for this {@link Domain}. * * @param requirements the {@link DomainRequirement}s to test. * @return {@code true} if and only if the supplied {@link DomainRequirement}s are a match for this {@link Domain}. */ public boolean test(DomainRequirement... requirements) { return test(Arrays.asList(requirements)); }
/** * Stapler's constructor. * * @param domain the domain. * @param credentials the credentials. */ @DataBoundConstructor public DomainCredentials(Domain domain, List<Credentials> credentials) { this.domain = domain == null ? Domain.global() : domain.resolve(); this.credentials = credentials == null ? new ArrayList<Credentials>() : new ArrayList<Credentials>(credentials); }
protected static Domain getDomainByName(CredentialsStore store, String domain) { if (StringUtils.equals("_", domain) || StringUtils.isBlank(domain) || "(global)".equals(domain)) { return Domain.global(); } else { for (Domain d : store.getDomains()) { if (domain.equals(d.getName())) { return d; } } } return null; }
final List<StandardUsernameCredentials> credentialsForDomain = CredentialsProvider.lookupCredentials( StandardUsernameCredentials.class, Jenkins.getInstance(), ACL.SYSTEM, new HostnamePortRequirement(site.hostname, site.port)); final StandardUsernameCredentials existingCredentials = CredentialsMatchers.firstOrNull(credentialsForDomain, "migrated from previous ssh-plugin version"); } else if (!Strings.isNullOrEmpty(legacy.password)) { credentialsToCreate = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, createdCredentialId, "migrated from previous ssh-plugin version", legacy.username, legacy.password); } else { final Domain sshDomain = new Domain("ssh-plugin-" + site.hostname, "migrated ssh-plugin credentials-" + site.hostname, Lists.newArrayList(hostnameSpec));
@SuppressWarnings("unused") // stapler web method public HttpResponse doDoMove(StaplerRequest req, @QueryParameter String destination) throws IOException { if (getStore().getDomains().size() <= 1) { return HttpResponses.status(400); Jenkins jenkins = Jenkins.getActiveInstance(); getStore().checkPermission(DELETE); final String splitKey = domain.getParent().getUrlName() + "/"; int split = destination.lastIndexOf(splitKey); ? User .get(contextName.substring("user:".length(), split - 1), false, Collections.emptyMap()) : jenkins.getItemByFullName(contextName); if (context == null) { split = destination.lastIndexOf(splitKey, split - 1); for (CredentialsStore store : CredentialsProvider.lookupStores(context)) { if (store.getContext() == context) { for (Domain d : store.getDomains()) { if (domainName.equals("_") ? d.getName() == null : domainName.equals(d.getName())) { destinationStore = store; destinationDomain = d; destinationStore.checkPermission(CREATE); if (destinationDomain.equals(domain.getDomain())) { return HttpResponses.redirectToDot();
@Test public void configRoundTrip() throws Exception { FreeStyleProject p = r.createFreeStyleProject(); MercurialSCM scm = new MercurialSCM("http://repo/"); assertEquals("default", scm.getRevision()); scm.setRevisionType(MercurialSCM.RevisionType.TAG); scm.setRevision("LATEST"); UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "test", "bob", "s3cr3t"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c); scm.setCredentialsId(c.getId()); scm.setModules("src"); scm.setSubdir("checkout"); r.jenkins.getDescriptorByType(MercurialInstallation.DescriptorImpl.class).setInstallations(new MercurialInstallation[] {new MercurialInstallation("caching", null, "hg", false, true, false, null, null)}); scm.setInstallation("caching"); p.setScm(scm); XmlFile xml = p.getConfigFile(); System.out.println(xml.asString()); r.configRoundtrip(p); System.out.println(xml.asString()); scm = (MercurialSCM) p.getScm(); assertEquals(MercurialSCM.RevisionType.TAG, scm.getRevisionType()); assertEquals("LATEST", scm.getRevision()); assertEquals(c.getId(), scm.getCredentialsId()); assertEquals("s3cr3t", ((UsernamePasswordCredentialsImpl) scm.getCredentials(p, new EnvVars())).getPassword().getPlainText()); assertEquals("src", scm.getModules());
@Test public void given_nestedFolderAndSystemCredentials_when_builtAsUserWithUseItem_then_folderCredentialFound() throws Exception { SystemCredentialsProvider.getInstance().getCredentials().add( new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "You don't want me", "bar", "fly") ); Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); folderStore.addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "Prof. Xavier", "prof", "xavier")); Folder child = f.createProject(Folder.class, "child"); getFolderStore(child).addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "Dr. Fu Manchu", "foo", "manchu")); FreeStyleProject prj = child.createProject(FreeStyleProject.class, "job"); prj.getBuildersList().add(new HasCredentialBuilder("foo-manchu", Matchers.hasProperty("username", is("foo")))); JenkinsRule.DummySecurityRealm realm = r.createDummySecurityRealm(); r.jenkins.setSecurityRealm(realm); strategy.grant(Computer.BUILD).everywhere().to("bob"); r.jenkins.setAuthorizationStrategy(strategy); HashMap<String, Authentication> jobsToUsers = new HashMap<String, Authentication>(); jobsToUsers.put(prj.getFullName(), User.get("bob").impersonate());
m.hg(sampleRepo, "commit", "--addremove", "--message=flow"); MercurialSCMSource s = new MercurialSCMSource("ssh://test@" + container.ipBound(22) + ":" + container.port(22) + "/" + sampleRepo); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "creds", "test", new BasicSSHUserPrivateKey.FileOnMasterPrivateKeySource(container.getPrivateKey().getAbsolutePath()), null, null)); s.setCredentialsId("creds"); assertNotNull(toolHome); String remoteHgLoc = inst.executableWithSubstitution(toolHome); r.jenkins.getDescriptorByType(MercurialInstallation.DescriptorImpl.class).setInstallations( new MercurialInstallation("default", "", "hg", false, true, null, false, "[ui]\nssh = ssh -o UserKnownHostsFile=" + tmp.newFile("known_hosts") + " -o StrictHostKeyChecking=no\n" + "remotecmd = " + remoteHgLoc, null)); s.setTraits(Collections.<SCMSourceTrait>singletonList(new MercurialInstallationSCMSourceTrait("default"))); WorkflowMultiBranchProject mp = r.jenkins.createProject(WorkflowMultiBranchProject.class, "p"); mp.getSourcesList().add(new BranchSource(s)); WorkflowJob p = PipelineTest.scheduleAndFindBranchProject(mp, "default"); assertEquals(1, mp.getItems().size()); r.waitUntilNoActivity(); WorkflowRun b = p.getLastBuild(); assertNotNull(b); r.assertBuildStatusSuccess(b);
@Test public void doFillCredentialsIdItemsWithoutJobWhenAdmin() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); ProjectMatrixAuthorizationStrategy as = new ProjectMatrixAuthorizationStrategy(); as.add(Jenkins.ADMINISTER, "alice"); r.jenkins.setAuthorizationStrategy(as); final UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "test", "bob", "s3cr3t"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c); ACL.impersonate(User.get("alice").impersonate(), new Runnable() { @Override public void run() { ListBoxModel options = r.jenkins.getDescriptorByType(MercurialSCM.DescriptorImpl.class).doFillCredentialsIdItems(null, "http://nowhere.net/"); assertEquals(CredentialsNameProvider.name(c), options.get(1).name); } }); }
@Test public void credentialsAvailableAtFolderScope() throws Exception { Folder f = createFolder(); List<StandardUsernamePasswordCredentials> asGroup = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, (ItemGroup) f, ACL.SYSTEM, Collections.emptyList()); List<StandardUsernamePasswordCredentials> asItem = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, (Item) f, ACL.SYSTEM, Collections.emptyList()); assertThat(asGroup, is(asItem)); CredentialsStore folderStore = getFolderStore(f); UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test-id", "description", "test-user", "secret"); folderStore.addCredentials(Domain.global(), credentials); asGroup = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, (ItemGroup) f, ACL.SYSTEM, Collections.emptyList()); asItem = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class, (Item) f, ACL.SYSTEM, Collections.emptyList()); assertThat(asGroup, is(asItem)); assertThat(asGroup, hasItem(credentials)); assertThat(asItem, hasItem(credentials)); }
Proc p = runSvnServe(getClass().getResource("HUDSON-1379.zip")); try { SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList() )); FreeStyleProject b = r.createFreeStyleProject(); b.setScm(new SubversionSCM("svn://localhost/bob", "1-bob", ".")); FreeStyleProject c = r.createFreeStyleProject(); c.setScm(new SubversionSCM("svn://localhost/charlie", "2-charlie", ".")); r.assertBuildStatus(Result.FAILURE, b.scheduleBuild2(0).get()); SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Arrays.<Credentials>asList( new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "1-bob", null, "bob","bob") r.assertBuildStatus(Result.FAILURE, c.scheduleBuild2(0).get()); SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Arrays.<Credentials>asList( new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "1-bob", null, "bob","bob"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "2-charlie", null, "charlie","charlie")
@BeforeClass public static void setup() throws Exception { CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next(); String usernamePasswordCredentialsId = "FOOcredentials"; UsernamePasswordCredentialsImpl usernamePassword = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, usernamePasswordCredentialsId, "sample", usernamePasswordUsername, usernamePasswordPassword); store.addCredentials(Domain.global(), usernamePassword); StringCredentialsImpl mixedEnvCred1 = new StringCredentialsImpl(CredentialsScope.GLOBAL, mixedEnvCred1Id, "test", Secret.fromString(mixedEnvCred1Secret)); store.addCredentials(Domain.global(), mixedEnvCred1); UsernamePasswordCredentialsImpl mixedEnvCred2 = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, mixedEnvCred2Id, "sample", mixedEnvCred2U, mixedEnvCred2P); store.addCredentials(Domain.global(), mixedEnvCred2); StringCredentialsImpl mixedEnvCred3 = new StringCredentialsImpl(CredentialsScope.GLOBAL, mixedEnvCred3Id, "test", Secret.fromString(mixedEnvCred3Secret)); store.addCredentials(Domain.global(), mixedEnvCred3); FileCredentialsImpl fileCred = new FileCredentialsImpl(CredentialsScope.GLOBAL, fileCredId, "test", fileCredName, SecretBytes.fromBytes(fileCredContent.getBytes())); store.addCredentials(Domain.global(), fileCred); FileCredentialsImpl otherFileCred = new FileCredentialsImpl(CredentialsScope.GLOBAL, otherFileCredId, "test", otherFileCredName, SecretBytes.fromBytes(otherFileCredContent.getBytes())); store.addCredentials(Domain.global(), otherFileCred); folder = j.jenkins.createProject(Folder.class, "testFolder"); folder.addProperty(new FolderCredentialsProvider.FolderCredentialsProperty(new DomainCredentials[0])); j.configRoundtrip(folder); CredentialsStore folderStore = folder.getProperties().get(FolderCredentialsProvider.FolderCredentialsProperty.class).getStore(); StringCredentialsImpl sc = new StringCredentialsImpl(CredentialsScope.GLOBAL, mixedEnvCred1Id, "test", Secret.fromString(mixedEnvInFolderCred1Secret)); folderStore.addCredentials(Domain.global(), sc); UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, mixedEnvCred2Id, "sample", mixedEnvInFoldercred2U, mixedEnvInFolderCred2P); folderStore.addCredentials(Domain.global(), c); SSHUserPrivateKey k = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "sshCred1", "bobby", new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource("abc123"), null, "sample"); store.addCredentials(Domain.global(), k); }
String username = "bob"; String password = "s3cr3t"; UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test", "sample", username, password); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c); WorkflowJob job = r.jenkins.createProject(WorkflowJob.class, "credentialed"); job.setDefinition(new CpsFlowDefinition( "node{ withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'test',\n" + )); WorkflowRun run = job.scheduleBuild2(0).getStartCondition().get(); r.waitForCompletion(run); FlowExecution exec = run.getExecution(); String log = r.getLog(run); ForkScanner scanner = new ForkScanner(); List<FlowNode> filtered = scanner.filteredNodes(exec, new DescriptorMatchPredicate(BindingStep.DescriptorImpl.class));
@Test public void given_folderCredential_when_builtAsUserWithoutUseItem_then_credentialNotFound() throws Exception { Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); folderStore.addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "Dr. Fu Manchu", "foo", "manchu")); FreeStyleProject prj = f.createProject(FreeStyleProject.class, "job"); prj.getBuildersList().add(new HasCredentialBuilder("foo-manchu")); JenkinsRule.DummySecurityRealm realm = r.createDummySecurityRealm(); r.jenkins.setSecurityRealm(realm); MockAuthorizationStrategy strategy = new MockAuthorizationStrategy(); strategy.grant(Item.BUILD).everywhere().to("bob"); strategy.grant(Computer.BUILD).everywhere().to("bob"); r.jenkins.setAuthorizationStrategy(strategy); HashMap<String, Authentication> jobsToUsers = new HashMap<String, Authentication>(); jobsToUsers.put(prj.getFullName(), User.get("bob").impersonate()); MockQueueItemAuthenticator authenticator = new MockQueueItemAuthenticator(jobsToUsers); QueueItemAuthenticatorConfiguration.get().getAuthenticators().clear(); QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(authenticator); r.assertBuildStatus(Result.FAILURE, prj.scheduleBuild2(0).get()); }
@BeforeClass public static void setUpAgentAndCreds() throws Exception { s = j.createOnlineSlave(); s.setLabelString("some-label docker here"); s.getNodeProperties().add(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("ONAGENT", "true"), new EnvironmentVariablesNodeProperty.Entry("WHICH_AGENT", "first"))); s.setNumExecutors(2); s2 = j.createOnlineSlave(); s2.setLabelString("other-docker"); s2.getNodeProperties().add(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("ONAGENT", "true"), new EnvironmentVariablesNodeProperty.Entry("WHICH_AGENT", "second"))); CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next(); String usernamePasswordCredentialsId = "FOOcredentials"; UsernamePasswordCredentialsImpl usernamePassword = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, usernamePasswordCredentialsId, "sample", usernamePasswordUsername, usernamePasswordPassword); store.addCredentials(Domain.global(), usernamePassword); }
@Test public void withDefaults() throws Exception { Folder folder = j.createProject(Folder.class); getFolderStore(folder).addCredentials(Domain.global(), folderCred); getFolderStore(folder).addCredentials(Domain.global(), grandParentCred); folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId())); expect("declarativeDockerConfigWithOverride") .inFolder(folder) .runFromRepo(false) .logContains("Docker Label is: other-label", "Registry URL is: https://other.registry", "Registry Creds ID is: " + grandParentCred.getId()).go(); }
@Issue("SECURITY-303") @Test public void credentialsAccess() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.READ, Item.READ, Item.BUILD, Item.CONFIGURE).everywhere().to("devlead"). grant(Jenkins.READ, Item.READ, Item.BUILD).everywhere().to("user")); SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Collections.<Credentials>singletonList( new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "svncreds", null, "svn", "s3cr3t")))); r.createFreeStyleProject("p"); assertSniff("devlead", "svn:s3cr3t", /* server response is bad, Jenkins should say so */ false); assertSniff("user", null, /* Jenkins should not even try to connect, pretend it is OK */ true); } private void assertSniff(String user, String sniffed, boolean ok) throws Exception {