com.cloudbees.plugins.credentials.common.IdCredentials Java Examples
The following examples show how to use
com.cloudbees.plugins.credentials.common.IdCredentials.
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: MultiBinding.java From credentials-binding-plugin with MIT License | 6 votes |
/** * Looks up the actual credentials. * @param build the build. * @return the credentials * @throws FileNotFoundException if the credentials could not be found (for convenience, rather than returning null) */ protected final @Nonnull C getCredentials(@Nonnull Run<?,?> build) throws IOException { IdCredentials cred = CredentialsProvider.findCredentialById(credentialsId, IdCredentials.class, build); if (cred==null) throw new CredentialNotFoundException("Could not find credentials entry with ID '" + credentialsId + "'"); if (type().isInstance(cred)) { CredentialsProvider.track(build, cred); return type().cast(cred); } Descriptor expected = Jenkins.getActiveInstance().getDescriptor(type()); throw new CredentialNotFoundException("Credentials '"+credentialsId+"' is of type '"+ cred.getDescriptor().getDisplayName()+"' where '"+ (expected!=null ? expected.getDisplayName() : type().getName())+ "' was expected"); }
Example #2
Source File: WithMavenStepExecution2.java From pipeline-maven-plugin with MIT License | 6 votes |
@Override public String apply(@javax.annotation.Nullable Credentials credentials) { if (credentials == null) return "null"; String result = ClassUtils.getShortName(credentials.getClass()) + "["; if (credentials instanceof IdCredentials) { IdCredentials idCredentials = (IdCredentials) credentials; result += "id: " + idCredentials.getId() + ","; } if (credentials instanceof UsernameCredentials) { UsernameCredentials usernameCredentials = (UsernameCredentials) credentials; result += "username: " + usernameCredentials.getUsername() + ""; } result += "]"; return result; }
Example #3
Source File: RegistryEndpointStepTest.java From docker-workflow-plugin with MIT License | 6 votes |
@Test public void stepExecutionWithCredentials() throws Exception { assumeNotWindows(); IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials); WorkflowJob p = r.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " mockDockerLoginWithEcho {\n" + " withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" + " }\n" + " }\n" + "}", true)); WorkflowRun b = r.buildAndAssertSuccess(p); r.assertLogContains("docker login -u me -p pass https://my-reg:1234", r.assertBuildStatusSuccess(r.waitForCompletion(b))); }
Example #4
Source File: ServerEndpointStepTest.java From docker-workflow-plugin with MIT License | 6 votes |
@Test public void configRoundTrip() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate"); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials); StepConfigTester sct = new StepConfigTester(story.j); Map<String,Object> serverConfig = new TreeMap<String,Object>(); serverConfig.put("uri", "tcp://host:2375"); serverConfig.put("credentialsId", serverCredentials.getId()); Map<String,Object> config = Collections.<String,Object>singletonMap("server", serverConfig); ServerEndpointStep step = DescribableHelper.instantiate(ServerEndpointStep.class, config); step = sct.configRoundTrip(step); DockerServerEndpoint server = step.getServer(); assertNotNull(server); assertEquals("tcp://host:2375", server.getUri()); assertEquals(serverCredentials.getId(), server.getCredentialsId()); assertEquals(config, DescribableHelper.uninstantiate(step)); } }); }
Example #5
Source File: ServerEndpointStepTest.java From docker-workflow-plugin with MIT License | 6 votes |
@Test public void stepExecutionWithCredentials() { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { assumeNotWindows(); IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate"); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj"); p.setDefinition(new CpsFlowDefinition( "node {\n" + " withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" + " sh 'echo would be connecting to $DOCKER_HOST'\n" + " sh 'echo DOCKER_TLS_VERIFY=$DOCKER_TLS_VERIFY'\n" + " sh 'echo DOCKER_CERT_PATH=$DOCKER_CERT_PATH is not empty'\n" + " }\n" + "}", true)); WorkflowRun b = story.j.buildAndAssertSuccess(p); story.j.assertLogContains("would be connecting to tcp://host:1234", b); story.j.assertLogContains("DOCKER_TLS_VERIFY=1", b); story.j.assertLogNotContains("DOCKER_CERT_PATH= is not empty", b); } }); }
Example #6
Source File: DockerRegistryEndpoint.java From docker-commons-plugin with MIT License | 6 votes |
/** * Plugins that want to refer to a {@link IdCredentials} should do so via ID string, * and use this method to resolve it and convert to {@link DockerRegistryToken}. * * Implements the logic {@link CredentialsProvider#findCredentialById(String, Class, Run, DomainRequirement...)} * but for an {@link Item}. * * @param context * If you are a build step trying to access DockerHub in the context of a build/job, * specify that job. Otherwise null. If you are scoped to something else, you might * have to interact with {@link CredentialsProvider} directly. * * @deprecated Call {@link #getToken(Run)} */ @Deprecated public @CheckForNull DockerRegistryToken getToken(Item context) { if (credentialsId == null) { return null; } // as a build step, your access to credentials are constrained by what the build // can access, hence Jenkins.getAuthentication() List<DomainRequirement> requirements = Collections.emptyList(); try { requirements = Collections.<DomainRequirement>singletonList(new HostnameRequirement(getEffectiveUrl().getHost())); } catch (IOException e) { // shrug off this error and move on. We are matching with ID anyway. LOGGER.log(Level.FINE, "Unable to add domain requirement for endpoint URL", e); } // look for subtypes that know how to create a token, such as Google Container Registry return AuthenticationTokens.convert(DockerRegistryToken.class, firstOrNull(CredentialsProvider.lookupCredentials( IdCredentials.class, context, Jenkins.getAuthentication(), requirements), allOf(AuthenticationTokens.matcher(DockerRegistryToken.class), withId(credentialsId)))); }
Example #7
Source File: DockerRegistryEndpoint.java From docker-commons-plugin with MIT License | 6 votes |
/** * Plugins that want to refer to a {@link IdCredentials} should do so via ID string, * and use this method to resolve it and convert to {@link DockerRegistryToken}. * * @param context * If you are a build step trying to access DockerHub in the context of a build/job, * specify that build. Otherwise null. If you are scoped to something else, you might * have to interact with {@link CredentialsProvider} directly. */ @CheckForNull DockerRegistryToken getToken(@CheckForNull Run context) { if (credentialsId == null) { return null; } List<DomainRequirement> requirements = Collections.emptyList(); try { requirements = Collections.<DomainRequirement>singletonList(new HostnameRequirement(getEffectiveUrl().getHost())); } catch (IOException e) { LOGGER.log(Level.FINE, "Unable to add domain requirement for endpoint URL", e); } return AuthenticationTokens.convert(DockerRegistryToken.class, CredentialsProvider.findCredentialById(credentialsId, IdCredentials.class, context, requirements)); }
Example #8
Source File: CredentialApi.java From blueocean-plugin with MIT License | 5 votes |
@POST @WebMethod(name = "") public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException { User authenticatedUser = User.current(); if(authenticatedUser == null){ throw new ServiceException.UnauthorizedException("No authenticated user found"); } JSONObject jsonObject = body.getJSONObject("credentials"); final IdCredentials credentials = request.bindJSON(IdCredentials.class, jsonObject); String domainName = DOMAIN_NAME; if(jsonObject.get("domain") != null && jsonObject.get("domain") instanceof String){ domainName = (String) jsonObject.get("domain"); } CredentialsUtils.createCredentialsInUserStore(credentials, authenticatedUser, domainName, ImmutableList.of(new BlueOceanDomainSpecification())); CredentialsStoreAction.DomainWrapper domainWrapper = credentialStoreAction.getDomain(domainName); if(domainWrapper != null) { CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredential(credentials.getId()); if (credentialsWrapper != null){ return new CreateResponse( new CredentialApi.Credential( credentialsWrapper, getLink().rel("domains").rel(domainName).rel("credentials"))); } } //this should never happen throw new ServiceException.UnexpectedErrorException("Unexpected error, failed to create credential"); }
Example #9
Source File: DockerCloud.java From docker-plugin with MIT License | 5 votes |
@Restricted(NoExternalUse.class) public static AuthConfig getAuthConfig(DockerRegistryEndpoint registry, ItemGroup context) { AuthConfig auth = new AuthConfig(); // we can't use DockerRegistryEndpoint#getToken as this one do check domainRequirement based on registry URL // but in some context (typically, passing registry auth for `docker build`) we just can't guess this one. final Credentials c = firstOrNull(CredentialsProvider.lookupCredentials( IdCredentials.class, context, ACL.SYSTEM, Collections.EMPTY_LIST), withId(registry.getCredentialsId())); final DockerRegistryToken t = c == null ? null : AuthenticationTokens.convert(DockerRegistryToken.class, c); if (t == null) { throw new IllegalArgumentException("Invalid Credential ID " + registry.getCredentialsId()); } final String token = t.getToken(); // What docker-commons claim to be a "token" is actually configuration storage // see https://github.com/docker/docker-ce/blob/v17.09.0-ce/components/cli/cli/config/configfile/file.go#L214 // i.e base64 encoded username : password final String decode = new String(Base64.decodeBase64(token), StandardCharsets.UTF_8); int i = decode.indexOf(':'); if (i > 0) { String username = decode.substring(0, i); auth.withUsername(username); } auth.withPassword(decode.substring(i+1)); if (registry.getUrl() != null) { auth.withRegistryAddress(registry.getUrl()); } return auth; }
Example #10
Source File: DockerServerCredentialsTest.java From docker-commons-plugin with MIT License | 5 votes |
@Test public void configRoundTripData() throws Exception { 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); j.submit(j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/credential/"+credentials.getId()+"/update") .getFormByName("update")); j.assertEqualDataBoundBeans(credentials, CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(IdCredentials.class, j.getInstance(), ACL.SYSTEM, new DockerServerDomainRequirement()), CredentialsMatchers.withId(credentials.getId()))); }
Example #11
Source File: DockerServerCredentialsTest.java From docker-commons-plugin with MIT License | 5 votes |
@Test public void configRoundTripEmpty() throws Exception { 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(""), "", ""); store.addDomain(domain, credentials); j.submit(j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/credential/"+credentials.getId()+"/update") .getFormByName("update")); j.assertEqualDataBoundBeans(credentials, CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(IdCredentials.class, j.getInstance(), ACL.SYSTEM, new DockerServerDomainRequirement()), CredentialsMatchers.withId(credentials.getId()))); }
Example #12
Source File: ConfigTest.java From docker-commons-plugin with MIT License | 5 votes |
@Test public void configRoundTrip() throws Exception { CredentialsStore store = CredentialsProvider.lookupStores(r.jenkins).iterator().next(); IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, Secret.fromString("clientKey"), "clientCertificate", "serverCaCertificate"); store.addCredentials(Domain.global(), serverCredentials); IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass"); store.addCredentials(Domain.global(), registryCredentials); SampleDockerBuilder b1 = new SampleDockerBuilder(new DockerServerEndpoint("", ""), new DockerRegistryEndpoint("http://dhe.mycorp.com/", registryCredentials.getId())); r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1)); b1 = new SampleDockerBuilder(new DockerServerEndpoint("tcp://192.168.1.104:8333", serverCredentials.getId()), new DockerRegistryEndpoint("", "")); r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1)); r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).setInstallations(new DockerTool("Docker 1.5", "/usr/local/docker15", Collections.<ToolProperty<?>>emptyList())); b1.setToolName("Docker 1.5"); r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1)); }
Example #13
Source File: RegistryEndpointStepTest.java From docker-workflow-plugin with MIT License | 5 votes |
@Test public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception { assumeNotWindows(); r.getInstance().setSecurityRealm(r.createDummySecurityRealm()); MockAuthorizationStrategy auth = new MockAuthorizationStrategy() .grant(Jenkins.READ).everywhere().to("alice", "bob") .grant(Computer.BUILD).everywhere().to("alice", "bob") // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById // uses when determining whether to include item-scope credentials in the search. .grant(Item.CONFIGURE).everywhere().to("alice"); r.getInstance().setAuthorizationStrategy(auth); IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials); String script = "node {\n" + " mockDockerLoginWithEcho {\n" + " withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" + " }\n" + " }\n" + "}"; WorkflowJob p1 = r.createProject(WorkflowJob.class, "prj1"); p1.setDefinition(new CpsFlowDefinition(script, true)); WorkflowJob p2 = r.createProject(WorkflowJob.class, "prj2"); p2.setDefinition(new CpsFlowDefinition(script, true)); Map<String, Authentication> jobsToAuths = new HashMap<>(); jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate()); jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate()); QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths)); // Alice has Credentials.USE_ITEM permission and should be able to use the credential. WorkflowRun b1 = r.buildAndAssertSuccess(p1); r.assertLogContains("docker login -u me -p pass https://my-reg:1234", b1); // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential. r.assertBuildStatus(Result.FAILURE, p2.scheduleBuild2(0)); }
Example #14
Source File: GitHubStatusNotificationStep.java From pipeline-githubnotify-step-plugin with MIT License | 5 votes |
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project) { AbstractIdCredentialsListBoxModel result = new StandardListBoxModel(); if (!project.hasPermission(Item.CONFIGURE)) { return result; } List<UsernamePasswordCredentials> credentialsList = CredentialsProvider.lookupCredentials(UsernamePasswordCredentials.class, project, ACL.SYSTEM); for (UsernamePasswordCredentials credential : credentialsList) { result = result.with((IdCredentials) credential); } return result; }
Example #15
Source File: CredentialApi.java From blueocean-plugin with MIT License | 5 votes |
@POST @WebMethod(name = "") @Deprecated public CreateResponse create(@JsonBody JSONObject body, StaplerRequest request) throws IOException { final IdCredentials credentials = request.bindJSON(IdCredentials.class, body.getJSONObject("credentials")); domainWrapper.getStore().addCredentials(domainWrapper.getDomain(), credentials); final Domain domain = domainWrapper.getDomain(); domainWrapper.getStore().addCredentials(domain, credentials); return new CreateResponse(new Credential(domainWrapper.getCredentials().get(credentials.getId()), getLink())); }
Example #16
Source File: BlueOceanCredentialsProvider.java From blueocean-plugin with MIT License | 5 votes |
@Nonnull @Override public <C extends IdCredentials> ListBoxModel getCredentialIds(@Nonnull Class<C> type, @Nullable ItemGroup itemGroup, @Nullable Authentication authentication, @Nonnull List<DomainRequirement> domainRequirements, @Nonnull CredentialsMatcher matcher) { ListBoxModel result = new ListBoxModel(); FolderPropertyImpl prop = propertyOf(itemGroup); if (prop != null && prop.domain.test(domainRequirements)) { result.add(Messages.BlueOceanCredentialsProvider_DisplayName(), prop.getId()); } return result; }
Example #17
Source File: ServerEndpointStepTest.java From docker-workflow-plugin with MIT License | 4 votes |
@Test public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception { assumeNotWindows(); story.then(r -> { story.j.getInstance().setSecurityRealm(story.j.createDummySecurityRealm()); MockAuthorizationStrategy auth = new MockAuthorizationStrategy() .grant(Jenkins.READ).everywhere().to("alice", "bob") .grant(Computer.BUILD).everywhere().to("alice", "bob") // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById // uses when determining whether to include item-scope credentials in the search. .grant(Item.CONFIGURE).everywhere().to("alice"); story.j.getInstance().setAuthorizationStrategy(auth); IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate"); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials); String script = "node {\n" + " withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" + " sh 'echo would be connecting to $DOCKER_HOST'\n" + " sh 'echo DOCKER_TLS_VERIFY=$DOCKER_TLS_VERIFY'\n" + " sh 'echo DOCKER_CERT_PATH=$DOCKER_CERT_PATH is not empty'\n" + " }\n" + "}"; WorkflowJob p1 = story.j.jenkins.createProject(WorkflowJob.class, "prj1"); p1.setDefinition(new CpsFlowDefinition(script, true)); WorkflowJob p2 = story.j.jenkins.createProject(WorkflowJob.class, "prj2"); p2.setDefinition(new CpsFlowDefinition(script, true)); Map<String, Authentication> jobsToAuths = new HashMap<>(); jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate()); jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate()); QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths)); // Alice has Credentials.USE_ITEM permission and should be able to use the credential. WorkflowRun b1 = story.j.buildAndAssertSuccess(p1); story.j.assertLogContains("would be connecting to tcp://host:1234", b1); story.j.assertLogContains("DOCKER_TLS_VERIFY=1", b1); story.j.assertLogNotContains("DOCKER_CERT_PATH= is not empty", b1); // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential. WorkflowRun b2 = story.j.buildAndAssertSuccess(p2); story.j.assertLogContains("would be connecting to tcp://host:1234", b2); story.j.assertLogContains("DOCKER_TLS_VERIFY=\n", b2); story.j.assertLogContains("DOCKER_CERT_PATH= is not empty", b2); }); }
Example #18
Source File: DockerServerCredentialsTest.java From docker-commons-plugin with MIT License | 4 votes |
private IdCredentials findFirstWithId(String credentialsId) { return CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials(IdCredentials.class, j.getInstance(), ACL.SYSTEM, new DockerServerDomainRequirement()), CredentialsMatchers.withId(credentialsId)); }