@Initializer(after = InitMilestone.PLUGINS_STARTED) public static void migrate() throws IOException { GitLabConnectionConfig descriptor = (GitLabConnectionConfig) Jenkins.getInstance().getDescriptor(GitLabConnectionConfig.class); for (GitLabConnection connection : descriptor.getConnections()) { if (connection.apiTokenId == null && connection.apiToken != null) { for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) { if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) { List<Domain> domains = credentialsStore.getDomains(); connection.apiTokenId = UUID.randomUUID().toString(); credentialsStore.addCredentials(domains.get(0), new GitLabApiTokenImpl(CredentialsScope.SYSTEM, connection.apiTokenId, "GitLab API Token", Secret.fromString(connection.apiToken))); } } } } descriptor.save(); } }
/** * {@inheritDoc} */ @Override public String getIconClassName() { return store.getProvider().getIconClassName(); }
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; }
@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); 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; if (!destinationStore.isDomainsModifiable()) { return HttpResponses.status(400); destinationStore.checkPermission(CREATE); if (destinationDomain.equals(domain.getDomain())) { return HttpResponses.redirectToDot(); if (destinationStore.addCredentials(destinationDomain, credentials)) { if (getStore().removeCredentials(domain.getDomain(), credentials)) { return HttpResponses.redirectTo("../.."); } else { destinationStore.removeCredentials(destinationDomain, credentials);
if (systemProvider == null) return false; final CredentialsStore credentialsStore = systemProvider.getStore(Jenkins.getInstance()); if (credentialsStore == null) return false; for (final Domain d : credentialsStore.getDomains()) { for (Credentials c : credentialsStore.getCredentials(d)) { if (!(c instanceof StringCredentials)) continue; final boolean wasUpdated = credentialsStore.updateCredentials(d, c, creds); if (!wasUpdated) { LOGGER.warning("Updating Token credential failed during update call.");
@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());
@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 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); } }); }
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);
Item item = context instanceof Item ? (Item) context : null; ItemGroup group = context instanceof ItemGroup ? (ItemGroup) context : context instanceof User ? Jenkins.getActiveInstance() : null; Set<String> ids = new HashSet<String>(); for (CredentialsStore p : CredentialsProvider.lookupStores(context)) { if (p.hasPermission(CredentialsProvider.VIEW)) { for (Domain domain : p.getDomains()) { for (Credentials c : p.getCredentials(domain)) { CredentialsScope scope = c.getScope(); if (scope != null && !scope.isVisible(context)) { masked = false; result.add(new TableEntry(p.getProvider(), p, domain, c, masked));
@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)); }
@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); }
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));
/** * Gets the check id url for the specified store. * * @param store the store. * @return the url of the id check endpoint. * @throws UnsupportedEncodingException if the JVM does not implement the JLS. */ public String getCheckIdUrl(CredentialsStore store) throws UnsupportedEncodingException { ModelObject context = store.getContext(); for (ContextResolver r : ExtensionList.lookup(ContextResolver.class)) { String token = r.getToken(context); if (token != null) { return Jenkins.getActiveInstance().getRootUrlFromRequest() + "/" + getDescriptorUrl() + "/checkId?provider=" + r.getClass().getName() + "&token=" + URLEncoder.encode(token, "UTF-8"); } } return Jenkins.getActiveInstance().getRootUrlFromRequest() + "/" + getDescriptorUrl() + "/checkId?provider=null&token=null"; }
@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); }
@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()); }
@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(); }
@BeforeClass public static void setup() throws Exception { CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next(); store.addCredentials(Domain.global(), globalCred); }
for (CredentialsStore s : lookupStores(jenkins)) { try { s.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Forced save credentials stores: Could not save " + s, e); for (Item item : jenkins.getAllItems(Item.class)) { count++; if (count % 100 == 0) { count); for (CredentialsStore s : lookupStores(item)) { if (item == s.getContext()) { s.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Forced save credentials stores: Could not save " + s, e); for (CredentialsStore s : lookupStores(user)) { if (user == s.getContext()) { s.save(); } catch (IOException e) { LOGGER.log(Level.WARNING, "Forced save credentials stores: Could not save " + s, e);
/** * Returns the {@link Item#getFullDisplayName()} or nearest approximation. * * @return the {@link Item#getFullDisplayName()} or nearest approximation. */ public final String getFullDisplayName() { String n; ModelObject context = getStore().getContext(); if (context instanceof Item) { n = ((Item) context).getFullDisplayName(); } else if (context instanceof ItemGroup) { n = ((ItemGroup) context).getFullDisplayName(); } else if (context instanceof User) { n = Messages.CredentialsStoreAction_UserDisplayName(((User) context).getDisplayName()); } else { // TODO switch to Jenkins.getInstance() once 2.0+ is the baseline n = Jenkins.getActiveInstance().getFullDisplayName(); } if (n.length() == 0) { return getDisplayName(); } else { return n + " \u00BB " + getDisplayName(); } }