com.spotify.docker.client.messages.RegistryConfigs Java Examples

The following examples show how to use com.spotify.docker.client.messages.RegistryConfigs. 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: PushPullIT.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: ContainerRegistryAuthSupplier.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: PushPullIT.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: MultiRegistryAuthSupplierTest.java    From docker-client with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 6 votes vote down vote up
private String authRegistryHeader(final RegistryConfigs registryConfigs)
    throws DockerException {
  if (registryConfigs == null) {
    return null;
  }
  try {
    String authRegistryJson =
        ObjectMapperProvider.objectMapper().writeValueAsString(registryConfigs.configs());

    final String apiVersion = version().apiVersion();
    final int versionComparison = compareVersion(apiVersion, "1.19");

    // Version below 1.19
    if (versionComparison < 0) {
      authRegistryJson = "{\"configs\":" + authRegistryJson + "}";
    } else if (versionComparison == 0) {
      // Version equal 1.19
      authRegistryJson = "{\"auths\":" + authRegistryJson + "}";
    }

    return Base64.encodeBase64String(authRegistryJson.getBytes(StandardCharsets.UTF_8));
  } catch (JsonProcessingException | InterruptedException ex) {
    throw new DockerException("Could not encode X-Registry-Config header", ex);
  }
}
 
Example #6
Source File: DockerConfigReaderTest.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDuplicateServerInAuthsAndCredHelpers() throws Exception {
  final Path path = getTestFilePath("dockerConfig/duplicateServerInAuthsAndCredHelpers.json");

  final String registry = "https://index.docker.io/v1/";
  final DockerCredentialHelperAuth testAuth =
      DockerCredentialHelperAuth.create(
          "dockerman",
          "sw4gy0lo",
          registry
      );
  when(credentialHelperDelegate.get("magic-missile", registry)).thenReturn(testAuth);

  // Test that for duplicate registries, credHelpers is preferred over auths.
  final RegistryConfigs registryConfigs = RegistryConfigs.builder()
      .addConfig(registry, testAuth.toRegistryAuth())
      .build();
  assertThat(reader.authForAllRegistries(path), is(registryConfigs));
}
 
Example #7
Source File: MavenRegistryAuthSupplier.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Override
public RegistryConfigs authForBuild() throws DockerException {
  final Map<String, RegistryAuth> allConfigs = new HashMap<>();
  for (Server server : settings.getServers()) {
    allConfigs.put(server.getId(), createRegistryAuth(server));
  }
  return RegistryConfigs.create(allConfigs);
}
 
Example #8
Source File: AbstractDockerMojo.java    From docker-maven-plugin with Apache License 2.0 5 votes vote down vote up
private RegistryAuthSupplier authSupplier() throws MojoExecutionException {

    final List<RegistryAuthSupplier> suppliers = new ArrayList<>();

    // prioritize the docker config file
    suppliers.add(new ConfigFileRegistryAuthSupplier());

    // then Google Container Registry support
    final RegistryAuthSupplier googleRegistrySupplier = googleContainerRegistryAuthSupplier();
    if (googleRegistrySupplier != null) {
      suppliers.add(googleRegistrySupplier);
    }

    // lastly, use any explicitly configured RegistryAuth as a catch-all
    final RegistryAuth registryAuth = registryAuth();
    if (registryAuth != null) {
      final RegistryConfigs configsForBuild = RegistryConfigs.create(ImmutableMap.of(
          serverIdFor(registryAuth), registryAuth
      ));
      suppliers.add(new FixedRegistryAuthSupplier(registryAuth, configsForBuild));
    }

    getLog().info("Using authentication suppliers: " +
                  Lists.transform(suppliers, new SupplierToClassNameFunction()));

    return new MultiRegistryAuthSupplier(suppliers);
  }
 
Example #9
Source File: PushPullIT.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildHubPrivateImageWithAuth() throws Exception {
  final String dockerDirectory = Resources.getResource("dockerDirectoryNeedsAuth").getPath();
  final RegistryAuth registryAuth = RegistryAuth.builder()
      .username(HUB_AUTH_USERNAME2)
      .password(HUB_AUTH_PASSWORD2)
      .build();
  final DockerClient client = DefaultDockerClient
      .fromEnv()
      .registryAuthSupplier(new FixedRegistryAuthSupplier(
          registryAuth, RegistryConfigs.create(singletonMap(HUB_NAME, registryAuth))))
      .build();

  client.build(Paths.get(dockerDirectory), "testauth", BuildParam.pullNewerImage());
}
 
Example #10
Source File: PushPullIT.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  final RegistryAuth registryAuth = RegistryAuth.builder()
      .username(LOCAL_AUTH_USERNAME)
      .password(LOCAL_AUTH_PASSWORD)
      .build();
  client = DefaultDockerClient
      .fromEnv()
      .registryAuthSupplier(new FixedRegistryAuthSupplier(
          registryAuth, RegistryConfigs.create(singletonMap(HUB_NAME, registryAuth))))
      .build();

  System.out.printf("- %s\n", testName.getMethodName());
}
 
Example #11
Source File: MultiRegistryAuthSupplierTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthForBuild() throws Exception {

  final RegistryAuth auth1 = RegistryAuth.builder()
      .username("1")
      .serverAddress("a")
      .build();

  final RegistryAuth auth2 = RegistryAuth.builder()
      .username("2")
      .serverAddress("b")
      .build();

  final RegistryAuth auth3 = RegistryAuth.builder()
      .username("3")
      .serverAddress("b")
      .build();

  final RegistryAuth auth4 = RegistryAuth.builder()
      .username("4")
      .serverAddress("c")
      .build();

  when(supplier1.authForBuild()).thenReturn(RegistryConfigs.create(ImmutableMap.of(
      "a", auth1,
      "b", auth2
  )));

  when(supplier2.authForBuild()).thenReturn(RegistryConfigs.create(ImmutableMap.of(
      "b", auth3,
      "c", auth4
  )));

  // ensure that supplier1 had priority for server b
  assertThat(multiSupplier.authForBuild().configs(), allOf(
      hasEntry("a", auth1),
      hasEntry("b", auth2),
      hasEntry("c", auth4)
  ));
}
 
Example #12
Source File: ContainerRegistryAuthSupplierTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthForBuild_TokenWithoutExpirationDoesNotCauseRefresh() throws Exception {
  final AccessToken accessToken = new AccessToken(tokenValue, null);
  final GoogleCredentials credentials = new GoogleCredentials(accessToken);

  final ContainerRegistryAuthSupplier supplier =
      new ContainerRegistryAuthSupplier(credentials, clock,
          TimeUnit.SECONDS.toMillis(minimumExpirationSecs), refresher);

  final RegistryConfigs configs = supplier.authForBuild();
  assertThat(configs.configs().values(), is(not(empty())));
  assertThat(configs.configs().values(), everyItem(matchesAccessToken(accessToken)));

  verify(refresher, never()).refresh(credentials);
}
 
Example #13
Source File: ContainerRegistryAuthSupplierTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthForBuild_ExceptionOnRefresh() throws Exception {
  when(clock.millis())
      .thenReturn(expiration.minusSeconds(minimumExpirationSecs - 1).getMillis());

  doThrow(new IOException("failure!!")).when(refresher).refresh(credentials);

  final RegistryConfigs configs = supplier.authForBuild();
  assertThat(configs.configs().values(), is(empty()));
}
 
Example #14
Source File: ContainerRegistryAuthSupplierTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthForBuild_RefreshNeeded() throws Exception {
  when(clock.millis())
      .thenReturn(expiration.minusSeconds(minimumExpirationSecs - 1).getMillis());

  final RegistryConfigs configs = supplier.authForBuild();
  assertThat(configs.configs().values(), is(not(empty())));
  assertThat(configs.configs().values(), everyItem(matchesAccessToken(accessToken)));

  verify(refresher).refresh(credentials);
}
 
Example #15
Source File: ContainerRegistryAuthSupplierTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthForBuild_NoRefresh() throws Exception {
  when(clock.millis())
      .thenReturn(expiration.minusSeconds(minimumExpirationSecs + 1).getMillis());

  final RegistryConfigs configs = supplier.authForBuild();
  assertThat(configs.configs().values(), is(not(empty())));
  assertThat(configs.configs().values(), everyItem(matchesAccessToken(accessToken)));

  verify(refresher, never()).refresh(credentials);
}
 
Example #16
Source File: ConfigFileRegistryAuthSupplierTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthForBuild_Success() throws Exception {
  final RegistryConfigs configs = RegistryConfigs.create(ImmutableMap.of(
      "server1",
      RegistryAuth.builder()
          .serverAddress("server1")
          .username("user1")
          .password("pass1")
          .build()
  ));

  when(reader.authForAllRegistries(configFile.toPath())).thenReturn(configs);

  assertThat(supplier.authForBuild(), is(equalTo(configs)));
}
 
Example #17
Source File: DockerConfigReaderTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCredHelpers() throws Exception {
  final Path path = getTestFilePath("dockerConfig/credHelpers.json");

  final String registry1 = "https://foo.io";
  final String registry2 = "https://adventure.zone";
  final String registry3 = "https://beyond.zone";
  final DockerCredentialHelperAuth testAuth1 =
          DockerCredentialHelperAuth.create(
                  "cool user",
                  "cool password",
                  registry1
          );
  final DockerCredentialHelperAuth testAuth2 =
          DockerCredentialHelperAuth.create(
                  "taako",
                  "lupe",
                  registry2
          );

  when(credentialHelperDelegate.get("a-cred-helper", registry1)).thenReturn(testAuth1);
  when(credentialHelperDelegate.get("magic-missile", registry2)).thenReturn(testAuth2);
  when(credentialHelperDelegate.get("elusive-helper", registry3)).thenReturn(null);

  final RegistryConfigs expected = RegistryConfigs.builder()
          .addConfig(registry1, testAuth1.toRegistryAuth())
          .addConfig(registry2, testAuth2.toRegistryAuth())
          .build();
  final RegistryConfigs configs = reader.authForAllRegistries(path);

  assertThat(configs, is(expected));
}
 
Example #18
Source File: DockerConfigReaderTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseRegistryConfigs() throws Exception {
  final Path path = getTestFilePath("dockerConfig/multiConfig.json");
  final RegistryConfigs configs = reader.authForAllRegistries(path);

  assertThat(configs.configs(), allOf(
      hasEntry("https://index.docker.io/v1/", DOCKER_AUTH_CONFIG),
      hasEntry("https://narnia.mydock.io/v1/", MY_AUTH_CONFIG)
  ));
}
 
Example #19
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE")
@Override
public String build(final Path directory, final String name, final String dockerfile,
                    final ProgressHandler handler, final BuildParam... params)
    throws DockerException, InterruptedException, IOException {
  checkNotNull(handler, "handler");

  WebTarget resource = noTimeoutResource().path("build");

  for (final BuildParam param : params) {
    resource = resource.queryParam(param.name(), param.value());
  }
  if (name != null) {
    resource = resource.queryParam("t", name);
  }
  if (dockerfile != null) {
    resource = resource.queryParam("dockerfile", dockerfile);
  }

  // Convert auth to X-Registry-Config format
  final RegistryConfigs registryConfigs = registryAuthSupplier.authForBuild();

  final BuildProgressHandler buildHandler = new BuildProgressHandler(handler);

  try (final CompressedDirectory compressedDirectory = CompressedDirectory.create(directory);
       final InputStream fileStream = Files.newInputStream(compressedDirectory.file())) {
      
    requestAndTail(POST, buildHandler, resource,
                   resource.request(APPLICATION_JSON_TYPE)
                       .header("X-Registry-Config",
                               authRegistryHeader(registryConfigs)),
                   Entity.entity(fileStream, "application/tar"));

    return buildHandler.getImageId();
  }
}
 
Example #20
Source File: ConfigFileRegistryAuthSupplier.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Override
public RegistryConfigs authForBuild() throws DockerException {
  if (!configFileExists()) {
    return null;
  }

  try {
    return reader.authForAllRegistries(path);
  } catch (IOException e) {
    throw new DockerException(e);
  }
}
 
Example #21
Source File: MultiRegistryAuthSupplier.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Override
public RegistryConfigs authForBuild() throws DockerException {
  final Map<String, RegistryAuth> allConfigs = new HashMap<>();
  // iterate through suppliers in reverse so that the earlier suppliers in the list
  // have precedence
  for (RegistryAuthSupplier supplier : Lists.reverse(suppliers)) {
    final RegistryConfigs configs = supplier.authForBuild();
    if (configs != null && configs.configs() != null) {
      allConfigs.putAll(configs.configs());
    }
  }
  return RegistryConfigs.create(allConfigs);
}
 
Example #22
Source File: MavenPomAuthSupplier.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Override
public RegistryConfigs authForBuild() {
  final Map<String, RegistryAuth> allConfigs = new HashMap<>();
  if (hasUserName()) {
    allConfigs.put(
        "config",
        RegistryAuth.builder()
            .username(this.userName)
            .password(this.password)
            .build()
    );
  }
  return RegistryConfigs.create(allConfigs);
}
 
Example #23
Source File: DockerConfigReaderTest.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testCredsStoreAndCredHelpersAndAuth() throws Exception {
  final Path path = getTestFilePath("dockerConfig/credsStoreAndCredHelpersAndAuth.json");

  // This registry is in the file, in the "auths" sections
  final String registry1 = DOCKER_AUTH_CONFIG.serverAddress();
  assertThat(reader.authForRegistry(path, registry1), is(DOCKER_AUTH_CONFIG));

  // This registry is in the "credHelpers" section. It will give us a
  // credsStore value which will trigger our mock and give us testAuth2.
  final String registry2 = "https://adventure.zone";
  final DockerCredentialHelperAuth testAuth2 =
      DockerCredentialHelperAuth.create(
          "taako",
          "lupe",
          registry2
      );
  when(credentialHelperDelegate.get("magic-missile", registry2)).thenReturn(testAuth2);
  assertThat(reader.authForRegistry(path, registry2), is(testAuth2.toRegistryAuth()));

  // This registry is not in the "auths" or anywhere else. It should default
  // to using the credsStore value, and our mock will return testAuth3.
  final String registry3 = "https://rush.in";
  final DockerCredentialHelperAuth testAuth3 =
      DockerCredentialHelperAuth.create(
          "magnus",
          "julia",
          registry3
      );
  when(credentialHelperDelegate.get("starblaster", registry3)).thenReturn(testAuth3);
  assertThat(reader.authForRegistry(path, registry3), is(testAuth3.toRegistryAuth()));

  // Finally, when we get auths for *all* registries in the file, we only expect
  // auths for the two registries that are explicitly mentioned.
  // Since registry1 is in the "auths" and registry2 is in the "credHelpers",
  // we will see auths for them.
  final RegistryConfigs registryConfigs = RegistryConfigs.builder()
          .addConfig(registry2, testAuth2.toRegistryAuth())
          .addConfig(registry1, DOCKER_AUTH_CONFIG)
          .build();
  assertThat(reader.authForAllRegistries(path), is(registryConfigs));
}
 
Example #24
Source File: DockerConfigReaderTest.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testParseNoAuths() throws Exception {
  final Path path = getTestFilePath("dockerConfig/noAuths.json");
  final RegistryConfigs configs = reader.authForAllRegistries(path);
  assertThat(configs, equalTo(RegistryConfigs.empty()));
}
 
Example #25
Source File: RegistryAuthSupplier.java    From docker-client with Apache License 2.0 4 votes vote down vote up
/** Authentication info to pass in the X-Registry-Config header when building an image. */
RegistryConfigs authForBuild() throws DockerException;
 
Example #26
Source File: FixedRegistryAuthSupplier.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Override
public RegistryConfigs authForBuild() {
  return configsForBuild;
}
 
Example #27
Source File: DefaultDockerClientUnitTest.java    From docker-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testBuildPassesMultipleRegistryConfigs() throws Exception {
  final RegistryConfigs registryConfigs = RegistryConfigs.create(ImmutableMap.of(
      "server1", RegistryAuth.builder()
          .serverAddress("server1")
          .username("u1")
          .password("p1")
          .email("e1")
          .build(),

      "server2", RegistryAuth.builder()
          .serverAddress("server2")
          .username("u2")
          .password("p2")
          .email("e2")
          .build()
  ));

  final RegistryAuthSupplier authSupplier = mock(RegistryAuthSupplier.class);
  when(authSupplier.authForBuild()).thenReturn(registryConfigs);

  final DefaultDockerClient client = builder.registryAuthSupplier(authSupplier)
      .build();

  // build() calls /version to check what format of header to send
  enqueueServerApiVersion("1.20");

  server.enqueue(new MockResponse()
          .setResponseCode(200)
          .addHeader("Content-Type", "application/json")
          .setBody(
              fixture("fixtures/1.22/build.json")
          )
  );

  final Path path = Paths.get(Resources.getResource("dockerDirectory").toURI());

  client.build(path);

  final RecordedRequest versionRequest = takeRequestImmediately();
  assertThat(versionRequest.getMethod(), is("GET"));
  assertThat(versionRequest.getPath(), is("/version"));

  final RecordedRequest buildRequest = takeRequestImmediately();
  assertThat(buildRequest.getMethod(), is("POST"));
  assertThat(buildRequest.getPath(), is("/build"));

  final String registryConfigHeader = buildRequest.getHeader("X-Registry-Config");
  assertThat(registryConfigHeader, is(not(nullValue())));

  // check that the JSON in the header is equivalent to what we mocked out above from
  // the registryAuthSupplier
  final JsonNode headerJsonNode = toJson(BaseEncoding.base64().decode(registryConfigHeader));
  assertThat(headerJsonNode, is(toJson(registryConfigs.configs())));
}
 
Example #28
Source File: FixedRegistryAuthSupplier.java    From docker-client with Apache License 2.0 4 votes vote down vote up
public FixedRegistryAuthSupplier(final RegistryAuth registryAuth,
                                 final RegistryConfigs configsForBuild) {
  this.registryAuth = registryAuth;
  this.configsForBuild = configsForBuild;
}
 
Example #29
Source File: RegistryAuthSupplierChain.java    From docker-registry-artifact-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public RegistryConfigs authForBuild() {
    return RegistryConfigs.create(Collections.singletonMap(registryAuth.serverAddress(), registryAuth));
}
 
Example #30
Source File: DockerConfigReader.java    From docker-client with Apache License 2.0 2 votes vote down vote up
/**
 * Parse the contents of the config file and generate all possible
 * {@link RegistryAuth}s, which are bundled into a {@link RegistryConfigs} instance.
 * @param configPath Path to config file.
 * @return All registry configs that can be generated from the config file
 * @throws IOException If the file cannot be read, or its JSON cannot be parsed
 * @deprecated Use {@link #authForAllRegistries(Path)} instead.
 */
@Deprecated
public RegistryConfigs fromConfig(final Path configPath) throws IOException {
  return authForAllRegistries(configPath);
}