com.spotify.docker.client.auth.RegistryAuthSupplier Java Examples

The following examples show how to use com.spotify.docker.client.auth.RegistryAuthSupplier. 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: AbstractDockerMojoTest.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: AbstractDockerMojoTest.java    From docker-maven-plugin with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Nonnull
private DockerClient openDockerClient() throws MojoExecutionException {
  final RegistryAuthSupplier authSupplier = createRegistryAuthSupplier();

  try {
    return DefaultDockerClient.fromEnv()
        .readTimeoutMillis(readTimeoutMillis)
        .connectTimeoutMillis(connectTimeoutMillis)
        .registryAuthSupplier(authSupplier)
        .useProxy(useProxy)
        .build();
  } catch (DockerCertificateException e) {
    throw new MojoExecutionException("Could not load Docker certificates", e);
  }
}
 
Example #4
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
@Nonnull
private RegistryAuthSupplier createRegistryAuthSupplier() {
  final List<RegistryAuthSupplier> suppliers = new ArrayList<>();

  if (useMavenSettingsForAuth) {
    suppliers.add(new MavenRegistryAuthSupplier(session.getSettings(), settingsDecrypter));
  }

  if (dockerConfigFile == null || "".equals(dockerConfigFile.getName())) {
    suppliers.add(new ConfigFileRegistryAuthSupplier());
  } else {
    suppliers.add(
        new ConfigFileRegistryAuthSupplier(
          new DockerConfigReader(),
          dockerConfigFile.toPath()
        )
    );
  }
  if (googleContainerRegistryEnabled) {
    try {
      final RegistryAuthSupplier googleSupplier = googleContainerRegistryAuthSupplier();
      if (googleSupplier != null) {
        suppliers.add(0, googleSupplier);
      }
    } catch (IOException ex) {
      getLog().info("Ignoring exception while loading Google credentials", ex);
    }
  } else {
    getLog().info("Google Container Registry support is disabled");
  }

  MavenPomAuthSupplier pomSupplier = new MavenPomAuthSupplier(this.username, this.password);
  if (pomSupplier.hasUserName()) {
    suppliers.add(pomSupplier);
  }

  return new MultiRegistryAuthSupplier(suppliers);
}
 
Example #5
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to load a GCR compatible RegistryAuthSupplier based on a few conditions:
 * <ol>
 * <li>First check to see if the environemnt variable DOCKER_GOOGLE_CREDENTIALS is set and points
 * to a readable file</li>
 * <li>Otherwise check if the Google Application Default Credentials can be loaded</li>
 * </ol>
 * Note that we use a special environment variable of our own in addition to any environment
 * variable that the ADC loading uses (GOOGLE_APPLICATION_CREDENTIALS) in case there is a need for
 * the user to use the latter env var for some other purpose in their build.
 *
 * @return a GCR RegistryAuthSupplier, or null
 * @throws IOException if an IOException occurs while loading the credentials
 */
@Nullable
private RegistryAuthSupplier googleContainerRegistryAuthSupplier() throws IOException {
  GoogleCredentials credentials = null;

  final String googleCredentialsPath = System.getenv("DOCKER_GOOGLE_CREDENTIALS");
  if (googleCredentialsPath != null) {
    final File file = new File(googleCredentialsPath);
    if (file.exists()) {
      try (FileInputStream inputStream = new FileInputStream(file)) {
        credentials = GoogleCredentials.fromStream(inputStream);
        getLog().info("Using Google credentials from file: " + file.getAbsolutePath());
      }
    }
  }

  // use the ADC last
  if (credentials == null) {
    try {
      credentials = GoogleCredentials.getApplicationDefault();
      getLog().info("Using Google application default credentials");
    } catch (IOException ex) {
      // No GCP default credentials available
      getLog().debug("Failed to load Google application default credentials", ex);
    }
  }

  if (credentials == null) {
    return null;
  }

  return ContainerRegistryAuthSupplier.forCredentials(credentials).build();
}
 
Example #6
Source File: DefaultDockerClientUnitTest.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("deprecated")
public void buildThrowsIfRegistryAuthandRegistryAuthSupplierAreBothSpecified() {
  thrown.expect(IllegalStateException.class);
  thrown.expectMessage("LOGIC ERROR");

  final RegistryAuthSupplier authSupplier = mock(RegistryAuthSupplier.class);

  //noinspection deprecation
  DefaultDockerClient.builder()
      .registryAuth(RegistryAuth.builder().identityToken("hello").build())
      .registryAuthSupplier(authSupplier)
      .build();
}
 
Example #7
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 #8
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 #9
Source File: AbstractDockerMojo.java    From docker-maven-plugin with Apache License 2.0 4 votes vote down vote up
@Override
@Nonnull
public String apply(@Nonnull final RegistryAuthSupplier input) {
  return input.getClass().getSimpleName();
}