com.spotify.docker.client.messages.RegistryAuth Java Examples
The following examples show how to use
com.spotify.docker.client.messages.RegistryAuth.
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: RegistryAuthSupplierChain.java From docker-registry-artifact-plugin with Apache License 2.0 | 6 votes |
RegistryAuthSupplierChain(ArtifactStoreConfig artifactStoreConfig, AWSTokenRequestGenerator tokenRequestGenerator) { String username, password; if (artifactStoreConfig.isRegistryTypeEcr()) { String[] usernameAndPassword = tokenRequestGenerator.getUsernameAndPasswordFromECRToken(artifactStoreConfig); username = usernameAndPassword[0]; password = usernameAndPassword[1]; } else { username = artifactStoreConfig.getUsername(); password = artifactStoreConfig.getPassword(); } registryAuth = RegistryAuth.builder() .username(username) .serverAddress(artifactStoreConfig.getRegistryUrl()) .password(password).build(); }
Example #2
Source File: DockerConfigReaderTest.java From docker-client with Apache License 2.0 | 6 votes |
@Test public void testFromDockerConfig_AddressProtocol() throws IOException { final Path path = getTestFilePath("dockerConfig/protocolMissing.json"); // Server address matches exactly what's in the config file final RegistryAuth noProto = reader.authForRegistry(path, "docker.example.com"); assertThat(noProto.serverAddress(), equalTo("docker.example.com")); // Server address doesn't have a protocol but the entry in the config file does (https) final RegistryAuth httpsProto = reader.authForRegistry(path, "repo.example.com"); assertThat(httpsProto.serverAddress(), equalTo("https://repo.example.com")); // Server address doesn't have a protocol but the entry in the config file does (http) final RegistryAuth httpProto = reader.authForRegistry(path, "local.example.com"); assertThat(httpProto.serverAddress(), equalTo("http://local.example.com")); }
Example #3
Source File: DockerConfigReaderTest.java From docker-client with Apache License 2.0 | 6 votes |
@Test public void testConfigFromEnv() throws IOException { DockerHost.SystemDelegate systemDelegate = mock(DockerHost.SystemDelegate.class); when(systemDelegate.getenv("DOCKER_CONFIG")) .thenReturn("src/test/resources/dockerConfigFromEnv"); when(systemDelegate.getProperty("os.name")).thenReturn(System.getProperty("os.name")); DockerHost.setSystemDelegate(systemDelegate); try { DockerConfigReader dockerConfigReader = new DockerConfigReader(); Path path = dockerConfigReader.defaultConfigPath(); assertThat(path.toString().replace("\\", "/"), equalTo("src/test/resources/dockerConfigFromEnv/config.json")); final RegistryAuth registryAuth = dockerConfigReader.anyRegistryAuth(); assertThat(registryAuth, equalTo(DOCKER_AUTH_CONFIG)); } finally { DockerHost.restoreSystemDelegate(); } }
Example #4
Source File: ContainerRegistryAuthSupplier.java From docker-client with Apache License 2.0 | 6 votes |
@Override public RegistryConfigs authForBuild() throws DockerException { final AccessToken accessToken; try { accessToken = getAccessToken(); } catch (IOException e) { // do not fail as the GCR access token may not be necessary for building the image currently // being built log.warn("unable to get access token for Google Container Registry, " + "configuration for building image will not contain RegistryAuth for GCR", e); return RegistryConfigs.empty(); } final Map<String, RegistryAuth> configs = new HashMap<>(GCR_REGISTRIES.size()); for (String serverName : GCR_REGISTRIES) { configs.put(serverName, authForAccessToken(accessToken)); } return RegistryConfigs.create(configs); }
Example #5
Source File: ContainerRegistryAuthSupplier.java From docker-client with Apache License 2.0 | 6 votes |
@Override public RegistryAuth authFor(final String imageName) throws DockerException { final String[] imageParts = imageName.split("/", 2); if (imageParts.length < 2 || !GCR_REGISTRIES.contains(imageParts[0])) { // not an image on GCR return null; } final AccessToken accessToken; try { accessToken = getAccessToken(); } catch (IOException e) { throw new DockerException(e); } return authForAccessToken(accessToken); }
Example #6
Source File: MultiRegistryAuthSupplierTest.java From docker-client with Apache License 2.0 | 6 votes |
@Test public void testAuthFor() throws Exception { final String image1 = "foobar:latest"; final RegistryAuth auth1 = RegistryAuth.builder().build(); when(supplier1.authFor(image1)).thenReturn(auth1); assertThat(multiSupplier.authFor(image1), is(auth1)); verify(supplier2, never()).authFor(image1); // test fallback final String image2 = "bizbat:1.2.3"; final RegistryAuth auth2 = RegistryAuth.builder() .email("[email protected]") .build(); when(supplier1.authFor(image2)).thenReturn(null); when(supplier2.authFor(image2)).thenReturn(auth2); assertThat(multiSupplier.authFor(image2), is(auth2)); }
Example #7
Source File: DockerConfigReader.java From docker-client with Apache License 2.0 | 6 votes |
private RegistryAuth authForRegistry(final DockerConfig config, final String registry) throws IOException { // If the registry shows up in "auths", return it final Map<String, RegistryAuth> auths = config.auths(); if (auths != null && auths.get(registry) != null) { return auths.get(registry).toBuilder().serverAddress(registry).build(); } // Else, we use a credential helper. final String credsStore = getCredentialStore(config, registry); if (credsStore != null) { return authWithCredentialHelper(credsStore, registry); } return null; }
Example #8
Source File: MultiRegistryAuthSupplierTest.java From docker-client with Apache License 2.0 | 6 votes |
@Test public void testAuthForSwarm() throws Exception { final RegistryAuth auth1 = RegistryAuth.builder() .email("[email protected]") .build(); when(supplier1.authForSwarm()).thenReturn(auth1); assertThat(multiSupplier.authForSwarm(), is(auth1)); verify(supplier2, never()).authForSwarm(); // test fallback final RegistryAuth auth2 = RegistryAuth.builder() .email("[email protected]") .build(); when(supplier1.authForSwarm()).thenReturn(null); when(supplier2.authForSwarm()).thenReturn(auth2); assertThat(multiSupplier.authForSwarm(), is(auth2)); }
Example #9
Source File: MultiRegistryAuthSupplierTest.java From docker-client with Apache License 2.0 | 6 votes |
/** * Test what happens if one of the Suppliers returns null for authForBuild(). */ @Test public void testAuthForBuild_ReturnsNull() throws Exception { when(supplier1.authForBuild()).thenReturn(null); final RegistryConfigs registryConfigs = RegistryConfigs.create(ImmutableMap.of( "a", RegistryAuth.builder() .username("1") .serverAddress("a") .build(), "b", RegistryAuth.builder() .username("2") .serverAddress("b") .build() )); when(supplier2.authForBuild()).thenReturn(registryConfigs); assertThat(multiSupplier.authForBuild(), is(registryConfigs)); }
Example #10
Source File: DockerConfig.java From docker-client with Apache License 2.0 | 6 votes |
@JsonCreator public static DockerConfig create( @JsonProperty("credHelpers") final Map<String, String> credHelpers, @JsonProperty("auths") final Map<String, RegistryAuth> auths, @JsonProperty("HttpHeaders") final Map<String, String> httpHeaders, @JsonProperty("credsStore") final String credsStore, @JsonProperty("detachKeys") final String detachKeys, @JsonProperty("stackOrchestrator") final String stackOrchestrator, @JsonProperty("psFormat") final String psFormat, @JsonProperty("imagesFormat") final String imagesFormat) { return new AutoValue_DockerConfig( credHelpers == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(credHelpers), auths == null ? ImmutableMap.<String, RegistryAuth>of() : ImmutableMap.copyOf(auths), httpHeaders == null ? ImmutableMap.<String, String>of() : ImmutableMap.copyOf(httpHeaders), credsStore, detachKeys, stackOrchestrator, psFormat, imagesFormat); }
Example #11
Source File: PushMojoTest.java From docker-maven-plugin with Apache License 2.0 | 6 votes |
public void testPushPrivateRepo() throws Exception { final File pom = getPom("/pom-push-private-repo.xml"); final PushMojo mojo = (PushMojo) lookupMojo("push", pom); assertNotNull(mojo); final RegistryAuth authConfig = mojo.registryAuth(); assertEquals("dxia3", authConfig.username()); assertEquals("SxpxdUQA2mvX7oj", authConfig.password()); // verify decryption assertEquals("[email protected]", authConfig.email()); final DockerClient docker = mock(DockerClient.class); mojo.execute(docker); verify(docker) .push(eq("dxia3/docker-maven-plugin-auth"), any(AnsiProgressHandler.class)); }
Example #12
Source File: PushPullIT.java From docker-client with Apache License 2.0 | 6 votes |
@Test public void testPushImageToPrivateAuthedRegistryWithAuth() throws Exception { registryContainerId = startAuthedRegistry(client); // Push an image to the private registry and check it succeeds final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); client.build(Paths.get(dockerDirectory), LOCAL_IMAGE); client.tag(LOCAL_IMAGE, LOCAL_IMAGE_2); client.push(LOCAL_IMAGE); // Push the same image again under a different user final RegistryAuth registryAuth = RegistryAuth.builder() .username(LOCAL_AUTH_USERNAME_2) .password(LOCAL_AUTH_PASSWORD_2) .build(); client.push(LOCAL_IMAGE_2, registryAuth); // We should be able to pull it again client.pull(LOCAL_IMAGE); client.pull(LOCAL_IMAGE_2); }
Example #13
Source File: PushPullIT.java From docker-client with Apache License 2.0 | 6 votes |
@Test public void testPushHubPublicImageWithAuth() throws Exception { // Push an image to a public repo on Docker Hub and check it succeeds final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); final RegistryAuth registryAuth = RegistryAuth.builder() .username(HUB_AUTH_USERNAME) .password(HUB_AUTH_PASSWORD) .build(); final DockerClient client = DefaultDockerClient .fromEnv() .registryAuthSupplier(new FixedRegistryAuthSupplier( registryAuth, RegistryConfigs.create(singletonMap(HUB_NAME, registryAuth)))) .build(); client.build(Paths.get(dockerDirectory), HUB_PUBLIC_IMAGE); client.push(HUB_PUBLIC_IMAGE); }
Example #14
Source File: AbstractDockerMojoTest.java From docker-maven-plugin with Apache License 2.0 | 6 votes |
@Test public void testAuthorizationConfigurationWithServerAddress() throws Exception { ReflectionTestUtils.setField(sut, "serverId", SERVER_ID); ReflectionTestUtils.setField(sut, "registryUrl", REGISTRY_URL); when(settings.getServer(SERVER_ID)).thenReturn(mockServer()); when(builder.registryAuthSupplier(authSupplierCaptor.capture())).thenReturn(builder); sut.execute(); final RegistryAuthSupplier supplier = authSupplierCaptor.getValue(); final String image = REGISTRY_URL + "/foo/bar:blah"; final RegistryAuth authConfig = supplier.authFor(image); assertThat(authConfig).isNotNull(); assertThat(authConfig.email()).isEqualTo(EMAIL); assertThat(authConfig.password()).isEqualTo(PASSWORD); assertThat(authConfig.username()).isEqualTo(USERNAME); assertThat(authConfig.serverAddress()).isEqualTo(REGISTRY_URL); }
Example #15
Source File: RegistryAuthSupplierChainTest.java From docker-registry-artifact-plugin with Apache License 2.0 | 6 votes |
@Test public void shouldSetUsernameAndPasswordByMakingARequestToECRIfTypeIsEcr() { GetAuthorizationTokenResult mockAuthorizationTokenResult = mock(GetAuthorizationTokenResult.class); AuthorizationData mockAuthorization = mock(AuthorizationData.class); List<AuthorizationData> authorizationData = new ArrayList<>(); authorizationData.add(mockAuthorization); final ArtifactStoreConfig artifactStoreConfig = new ArtifactStoreConfig("https://12345.dkr.ecr.region.amazonaws.com", "ecr", "awsAccessKeyId", "awsSecretAccessKey", "awsRegion"); String usernameAndPassword="AWS:secretAuthorizationToken"; when(mockAmazonEcrClient.getAuthorizationToken(any(GetAuthorizationTokenRequest.class))).thenReturn(mockAuthorizationTokenResult); when(mockAuthorizationTokenResult.getAuthorizationData()).thenReturn(authorizationData); when(mockAuthorization.getAuthorizationToken()).thenReturn(Base64.getEncoder().encodeToString(usernameAndPassword.getBytes())); final RegistryAuthSupplierChain registryAuthSupplierChain = new RegistryAuthSupplierChain(artifactStoreConfig, new AWSTokenRequestGenerator(new MockAwsECRClientBuilder(new ClientConfigurationFactory()))); final RegistryAuth registryAuth = registryAuthSupplierChain.authFor("foo"); assertThat(registryAuth.serverAddress()).isEqualTo(artifactStoreConfig.getRegistryUrl()); assertThat(registryAuth.username()).isEqualTo("AWS"); assertThat(registryAuth.password()).isEqualTo("secretAuthorizationToken"); }
Example #16
Source File: DefaultDockerClient.java From docker-client with Apache License 2.0 | 6 votes |
@Override public void push(final String image, final ProgressHandler handler, final RegistryAuth registryAuth) throws DockerException, InterruptedException { final ImageRef imageRef = new ImageRef(image); WebTarget resource = resource().path("images").path(imageRef.getImage()).path("push"); if (imageRef.getTag() != null) { resource = resource.queryParam("tag", imageRef.getTag()); } try { requestAndTail(POST, handler, resource, resource.request(APPLICATION_JSON_TYPE) .header("X-Registry-Auth", authHeader(registryAuth))); } catch (DockerRequestException e) { switch (e.status()) { case 404: throw new ImageNotFoundException(image, e); default: throw e; } } }
Example #17
Source File: DefaultDockerClient.java From docker-client with Apache License 2.0 | 6 votes |
@Override public ServiceCreateResponse createService(final ServiceSpec spec, final RegistryAuth config) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.24"); final WebTarget resource = resource().path("services").path("create"); try { return request(POST, ServiceCreateResponse.class, resource, resource.request(APPLICATION_JSON_TYPE) .header("X-Registry-Auth", authHeader(config)), Entity.json(spec)); } catch (DockerRequestException e) { switch (e.status()) { case 406: throw new DockerException("Server error or node is not part of swarm.", e); case 409: throw new DockerException("Name conflicts with an existing object.", e); default: throw e; } } }
Example #18
Source File: DefaultDockerClient.java From docker-client with Apache License 2.0 | 6 votes |
@Override public void updateService(final String serviceId, final Long version, final ServiceSpec spec, final RegistryAuth config) throws DockerException, InterruptedException { assertApiVersionIsAbove("1.24"); try { WebTarget resource = resource().path("services").path(serviceId).path("update"); resource = resource.queryParam("version", version); request(POST, String.class, resource, resource.request(APPLICATION_JSON_TYPE) .header("X-Registry-Auth", authHeader(config)), Entity.json(spec)); } catch (DockerRequestException e) { switch (e.status()) { case 404: throw new ServiceNotFoundException(serviceId); default: throw e; } } }
Example #19
Source File: MavenRegistryAuthSupplier.java From dockerfile-maven with Apache License 2.0 | 6 votes |
private RegistryAuth createRegistryAuth(Server server) throws DockerException { SettingsDecryptionRequest decryptionRequest = new DefaultSettingsDecryptionRequest(server); SettingsDecryptionResult decryptionResult = settingsDecrypter.decrypt(decryptionRequest); if (decryptionResult.getProblems().isEmpty()) { log.debug("Successfully decrypted Maven server password"); } else { for (SettingsProblem problem : decryptionResult.getProblems()) { log.error("Settings problem for server {}: {}", server.getId(), problem); } throw new DockerException("Failed to decrypt Maven server password"); } return RegistryAuth.builder() .username(server.getUsername()) .password(decryptionResult.getServer().getPassword()) .build(); }
Example #20
Source File: PushPullIT.java From docker-client with Apache License 2.0 | 6 votes |
@Test public void testPushHubPrivateImageWithAuth() throws Exception { // Push an image to a private repo on Docker Hub and check it succeeds final String dockerDirectory = Resources.getResource("dockerDirectory").getPath(); final RegistryAuth registryAuth = RegistryAuth.builder() .username(HUB_AUTH_USERNAME) .password(HUB_AUTH_PASSWORD) .build(); final DockerClient client = DefaultDockerClient .fromEnv() .registryAuthSupplier(new FixedRegistryAuthSupplier( registryAuth, RegistryConfigs.create(singletonMap(HUB_NAME, registryAuth)))) .build(); client.build(Paths.get(dockerDirectory), HUB_PRIVATE_IMAGE); client.push(HUB_PRIVATE_IMAGE); }
Example #21
Source File: AbstractDockerMojoTest.java From docker-maven-plugin with Apache License 2.0 | 6 votes |
@Test public void testAuthorizationConfiguration() throws Exception { ReflectionTestUtils.setField(sut, "serverId", SERVER_ID); when(settings.getServer(SERVER_ID)).thenReturn(mockServer()); when(builder.registryAuthSupplier(authSupplierCaptor.capture())).thenReturn(builder); sut.execute(); final RegistryAuthSupplier supplier = authSupplierCaptor.getValue(); // we can't inspect the supplier details itself, but we can test that the instance passed // to the constructor returns our static RegistryAuth when asked for it final RegistryAuth authConfig = supplier.authForBuild().configs().get(SERVER_ID); assertThat(authConfig).isNotNull(); assertThat(authConfig.email()).isEqualTo(EMAIL); assertThat(authConfig.password()).isEqualTo(PASSWORD); assertThat(authConfig.username()).isEqualTo(USERNAME); assertThat(authConfig.serverAddress()).isEqualTo(SERVER_ID); }
Example #22
Source File: DockerClientFactory.java From docker-swarm-elastic-agent-plugin with Apache License 2.0 | 6 votes |
private static DefaultDockerClient createClient(ClusterProfileProperties clusterProfileProperties) throws Exception { DefaultDockerClient.Builder builder = DefaultDockerClient.builder(); builder.uri(clusterProfileProperties.getDockerURI()); if (clusterProfileProperties.getDockerURI().startsWith("https://")) { setupCerts(clusterProfileProperties, builder); } if (clusterProfileProperties.useDockerAuthInfo()) { final RegistryAuth registryAuth = clusterProfileProperties.registryAuth(); LOG.info(format("Using private docker registry server `{0}`.", registryAuth.serverAddress())); builder.registryAuth(registryAuth); } DefaultDockerClient docker = builder.build(); String ping = docker.ping(); if (!"OK".equals(ping)) { throw new RuntimeException("Could not ping the docker server, the server said '" + ping + "' instead of 'OK'."); } return docker; }
Example #23
Source File: DockerConfigReaderTest.java From docker-client with Apache License 2.0 | 5 votes |
@Test public void testFromDockerConfig_WrongConfigs() throws Exception { final RegistryAuth registryAuth1 = reader.anyRegistryAuth(getTestFilePath("dockerConfig/wrongConfig1.json")); assertThat(registryAuth1, is(emptyRegistryAuth())); final RegistryAuth registryAuth2 = reader.anyRegistryAuth(getTestFilePath("dockerConfig/wrongConfig2.json")); assertThat(registryAuth2, is(emptyRegistryAuth())); }
Example #24
Source File: DockerConfigReaderTest.java From docker-client with Apache License 2.0 | 5 votes |
@Test public void testFromDockerConfig_IncompleteConfig() throws Exception { final RegistryAuth registryAuth = reader.anyRegistryAuth(getTestFilePath("dockerConfig/incompleteConfig.json")); final RegistryAuth expected = RegistryAuth.builder() .email("[email protected]") .serverAddress("https://different.docker.io/v1/") .build(); assertThat(registryAuth, is(expected)); }
Example #25
Source File: DefaultDockerClient.java From docker-client with Apache License 2.0 | 5 votes |
private String authHeader(final RegistryAuth registryAuth) throws DockerException { // the docker daemon requires that the X-Registry-Auth header is specified // with a non-empty string even if your registry doesn't use authentication if (registryAuth == null) { return "null"; } try { return Base64.encodeBase64String(ObjectMapperProvider .objectMapper() .writeValueAsBytes(registryAuth)); } catch (JsonProcessingException ex) { throw new DockerException("Could not encode X-Registry-Auth header", ex); } }
Example #26
Source File: DockerConfigReaderTest.java From docker-client with Apache License 2.0 | 5 votes |
private static Matcher<RegistryAuth> emptyRegistryAuth() { return new CustomTypeSafeMatcher<RegistryAuth>("an empty RegistryAuth") { @Override protected boolean matchesSafely(final RegistryAuth item) { return item.email() == null && item.identityToken() == null && item.password() == null && item.email() == null; } }; }
Example #27
Source File: DockerConfigReaderTest.java From docker-client with Apache License 2.0 | 5 votes |
@Test public void testFromDockerConfig_MultiConfig() throws Exception { final Path path = getTestFilePath("dockerConfig/multiConfig.json"); final RegistryAuth myDockParsed = reader.authForRegistry(path, "https://narnia.mydock.io/v1/"); assertThat(myDockParsed, equalTo(MY_AUTH_CONFIG)); final RegistryAuth dockerIoParsed = reader.authForRegistry(path, "https://index.docker.io/v1/"); assertThat(dockerIoParsed, equalTo(DOCKER_AUTH_CONFIG)); }
Example #28
Source File: AbstractDockerMojo.java From docker-maven-plugin with Apache License 2.0 | 5 votes |
private String serverIdFor(RegistryAuth registryAuth) { if (serverId != null) { return serverId; } if (registryAuth.serverAddress() != null) { return registryAuth.serverAddress(); } return "index.docker.io"; }
Example #29
Source File: DefaultDockerClient.java From docker-client with Apache License 2.0 | 5 votes |
@Override public void pull(final String image, final RegistryAuth registryAuth, final ProgressHandler handler) throws DockerException, InterruptedException { final ImageRef imageRef = new ImageRef(image); WebTarget resource = resource().path("images").path("create"); resource = resource.queryParam("fromImage", imageRef.getImage()); if (imageRef.getTag() != null) { resource = resource.queryParam("tag", imageRef.getTag()); } try { requestAndTail(POST, handler, resource, resource .request(APPLICATION_JSON_TYPE) .header("X-Registry-Auth", authHeader(registryAuth))); } catch (DockerRequestException e) { switch (e.status()) { case 404: throw new ImageNotFoundException(image, e); default: throw e; } } }
Example #30
Source File: PushPullIT.java From docker-client with Apache License 2.0 | 5 votes |
@Test public void testPullHubPrivateImageWithAuth() throws Exception { final RegistryAuth registryAuth = RegistryAuth.builder() .username(HUB_AUTH_USERNAME2) .password(HUB_AUTH_PASSWORD2) .build(); client.pull("dxia2/scratch-private:latest", registryAuth); }