Search in sources :

Example 21 with AuthConfig

use of org.eclipse.jkube.kit.build.api.auth.AuthConfig in project jkube by eclipse.

the class AuthConfigFactoryTest method testGetAuthConfigFromSettings.

@Test
public void testGetAuthConfigFromSettings() {
    // Given
    List<RegistryServerConfiguration> settings = new ArrayList<>();
    settings.add(RegistryServerConfiguration.builder().id("testregistry.io").username("testuser").password("testpass").build());
    // When
    AuthConfig authConfig = AuthConfigFactory.getAuthConfigFromSettings(settings, "testuser", "testregistry.io", s -> s);
    // Then
    assertAuthConfig(authConfig, "testuser", "testpass");
}
Also used : ArrayList(java.util.ArrayList) AuthConfig(org.eclipse.jkube.kit.build.api.auth.AuthConfig) RegistryServerConfiguration(org.eclipse.jkube.kit.common.RegistryServerConfiguration) Test(org.junit.Test)

Example 22 with AuthConfig

use of org.eclipse.jkube.kit.build.api.auth.AuthConfig in project jkube by eclipse.

the class AuthConfigFactoryTest method fargateTaskRole.

@Test
public void fargateTaskRole() throws IOException {
    givenAwsSdkIsDisabled();
    String containerCredentialsUri = "v2/credentials/" + randomUUID();
    String accessKeyId = randomUUID().toString();
    String secretAccessKey = randomUUID().toString();
    String sessionToken = randomUUID().toString();
    givenEcsMetadataService("/" + containerCredentialsUri, accessKeyId, secretAccessKey, sessionToken);
    setupEcsMetadataConfiguration(httpServer, containerCredentialsUri);
    AuthConfig authConfig = factory.createAuthConfig(false, true, null, Collections.emptyList(), "user", ECR_NAME, s -> s);
    verifyAuthConfig(authConfig, accessKeyId, secretAccessKey, null, sessionToken);
}
Also used : AuthConfig(org.eclipse.jkube.kit.build.api.auth.AuthConfig) Test(org.junit.Test)

Example 23 with AuthConfig

use of org.eclipse.jkube.kit.build.api.auth.AuthConfig in project jkube by eclipse.

the class AuthConfigFactory method getAuthConfigFromEC2InstanceRole.

// ===================================================================================================
// if the local credentials don't contain user and password, use EC2 instance
// role credentials
private static AuthConfig getAuthConfigFromEC2InstanceRole(KitLogger log) throws IOException {
    log.debug("No user and password set for ECR, checking EC2 instance role");
    try (CloseableHttpClient client = HttpClients.custom().useSystemProperties().build()) {
        // we can set very low timeouts because the request returns almost instantly on
        // an EC2 instance
        // on a non-EC2 instance we can fail early
        RequestConfig conf = RequestConfig.custom().setConnectionRequestTimeout(1000).setConnectTimeout(1000).setSocketTimeout(1000).build();
        // get instance role - if available
        HttpGet request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials");
        request.setConfig(conf);
        String instanceRole;
        try (CloseableHttpResponse response = client.execute(request)) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                // no instance role found
                log.debug("No instance role found, return code was %d", response.getStatusLine().getStatusCode());
                return null;
            }
            // read instance role
            try (InputStream is = response.getEntity().getContent()) {
                instanceRole = IOUtils.toString(is, StandardCharsets.UTF_8);
            }
        }
        log.debug("Found instance role %s, getting temporary security credentials", instanceRole);
        // get temporary credentials
        request = new HttpGet("http://169.254.169.254/latest/meta-data/iam/security-credentials/" + UrlEscapers.urlPathSegmentEscaper().escape(instanceRole));
        request.setConfig(conf);
        try (CloseableHttpResponse response = client.execute(request)) {
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                log.debug("No security credential found, return code was %d", response.getStatusLine().getStatusCode());
                // no instance role found
                return null;
            }
            // read instance role
            try (Reader r = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8)) {
                JsonObject securityCredentials = new Gson().fromJson(r, JsonObject.class);
                String user = securityCredentials.getAsJsonPrimitive("AccessKeyId").getAsString();
                String password = securityCredentials.getAsJsonPrimitive("SecretAccessKey").getAsString();
                String token = securityCredentials.getAsJsonPrimitive("Token").getAsString();
                log.debug("Received temporary access key %s...", user.substring(0, 8));
                return new AuthConfig(user, password, "none", token);
            }
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) AuthConfig(org.eclipse.jkube.kit.build.api.auth.AuthConfig)

Example 24 with AuthConfig

use of org.eclipse.jkube.kit.build.api.auth.AuthConfig in project jkube by eclipse.

the class AuthConfigFactory method createStandardAuthConfig.

/**
 * Create an authentication config object which can be used for communication with a Docker registry
 *
 * The authentication information is looked up at various places (in this order):
 *
 * <ul>
 *    <li>From system properties</li>
 *    <li>From the provided map which can contain key-value pairs</li>
 *    <li>From the openshift settings in ~/.config/kube</li>
 *    <li>From the Maven settings stored typically in ~/.m2/settings.xml</li>
 * </ul>
 *
 * The following properties (prefix with 'docker.') and config key are evaluated:
 *
 * <ul>
 *     <li>username: User to authenticate</li>
 *     <li>password: Password to authenticate. Can be encrypted</li>
 *     <li>email: Optional EMail address which is send to the registry, too</li>
 * </ul>
 *
 * @param isPush if true this AuthConfig is created for a push, if false it's for a pull
 * @param authConfigMap String-String Map holding configuration info from the plugin's configuration. Can be <code>null</code> in
 *                   which case the settings are consulted.
 * @param settings the global Maven settings object
 * @param user user to check for
 * @param registry registry to use, might be null in which case a default registry is checked,
 * @param passwordDecryptionMethod a function to customize how password should be decoded
 * @param log Kit logger
 * @return the authentication configuration or <code>null</code> if none could be found
 *
 * @throws IOException any exception in case of fetching authConfig
 */
private static AuthConfig createStandardAuthConfig(boolean isPush, Map authConfigMap, List<RegistryServerConfiguration> settings, String user, String registry, UnaryOperator<String> passwordDecryptionMethod, KitLogger log, AwsSdkHelper awsSdkHelper) throws IOException {
    AuthConfig ret;
    // Check first for specific configuration based on direction (pull or push), then for a default value
    for (LookupMode lookupMode : new LookupMode[] { getLookupMode(isPush), LookupMode.DEFAULT }) {
        // System properties jkube.docker.username and jkube.docker.password always take precedence
        ret = getAuthConfigFromSystemProperties(lookupMode, passwordDecryptionMethod);
        if (ret != null) {
            log.debug("AuthConfig: credentials from system properties");
            return ret;
        }
        // Check for openshift authentication either from the plugin config or from system props
        ret = getAuthConfigFromOpenShiftConfig(lookupMode, authConfigMap);
        if (ret != null) {
            log.debug("AuthConfig: OpenShift credentials");
            return ret;
        }
        // Get configuration from global plugin config
        ret = getAuthConfigFromPluginConfiguration(lookupMode, authConfigMap, passwordDecryptionMethod);
        if (ret != null) {
            log.debug("AuthConfig: credentials from plugin config");
            return ret;
        }
    }
    // ===================================================================
    // These are lookups based on registry only, so the direction (push or pull) doesn't matter:
    // Now lets lookup the registry & user from ~/.m2/setting.xml
    ret = getAuthConfigFromSettings(settings, user, registry, passwordDecryptionMethod);
    if (ret != null) {
        log.debug("AuthConfig: credentials from ~/.m2/setting.xml");
        return ret;
    }
    // check EC2 instance role if registry is ECR
    if (EcrExtendedAuth.isAwsRegistry(registry)) {
        ret = getAuthConfigViaAwsSdk(awsSdkHelper, log);
        if (ret != null) {
            log.debug("AuthConfig: AWS credentials from AWS SDK");
            return ret;
        }
        ret = getAuthConfigFromAwsEnvironmentVariables(awsSdkHelper, log);
        if (ret != null) {
            log.debug("AuthConfig: AWS credentials from ENV variables");
            return ret;
        }
        try {
            ret = getAuthConfigFromEC2InstanceRole(log);
        } catch (ConnectTimeoutException ex) {
            log.debug("Connection timeout while retrieving instance meta-data, likely not an EC2 instance (%s)", ex.getMessage());
        } catch (IOException ex) {
            // don't make that an error since it may fail if not run on an EC2 instance
            log.warn("Error while retrieving EC2 instance credentials: %s", ex.getMessage());
        }
        if (ret != null) {
            log.debug("AuthConfig: credentials from EC2 instance role");
            return ret;
        }
        try {
            ret = getAuthConfigFromTaskRole(awsSdkHelper, log);
        } catch (ConnectTimeoutException ex) {
            log.debug("Connection timeout while retrieving ECS meta-data, likely not an ECS instance (%s)", ex.getMessage());
        } catch (IOException ex) {
            log.warn("Error while retrieving ECS Task role credentials: %s", ex.getMessage());
        }
        if (ret != null) {
            log.debug("AuthConfig: credentials from ECS Task role");
            return ret;
        }
    }
    // No authentication found
    return null;
}
Also used : AuthConfig(org.eclipse.jkube.kit.build.api.auth.AuthConfig) IOException(java.io.IOException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 25 with AuthConfig

use of org.eclipse.jkube.kit.build.api.auth.AuthConfig in project jkube by eclipse.

the class RegistryService method pushImage.

/**
 * Push a set of images to a registry
 *
 * @param imageConfig image to push (but only if they have a build configuration)
 * @param retries how often to retry
 * @param registryConfig a global registry configuration
 * @param skipTag flag to skip pushing tagged images
 * @throws IOException exception
 */
public void pushImage(ImageConfiguration imageConfig, int retries, RegistryConfig registryConfig, boolean skipTag) throws IOException {
    BuildConfiguration buildConfig = imageConfig.getBuildConfiguration();
    String name = imageConfig.getName();
    if (buildConfig != null) {
        String configuredRegistry = EnvUtil.firstRegistryOf(new ImageName(imageConfig.getName()).getRegistry(), imageConfig.getRegistry(), registryConfig.getRegistry());
        AuthConfig authConfig = createAuthConfig(true, new ImageName(name).getUser(), configuredRegistry, registryConfig);
        long start = System.currentTimeMillis();
        docker.pushImage(name, authConfig, configuredRegistry, retries);
        log.info("Pushed %s in %s", name, EnvUtil.formatDurationTill(start));
        if (!skipTag) {
            for (String tag : imageConfig.getBuildConfiguration().getTags()) {
                if (tag != null) {
                    docker.pushImage(new ImageName(name, tag).getFullName(), authConfig, configuredRegistry, retries);
                }
            }
        }
    }
}
Also used : BuildConfiguration(org.eclipse.jkube.kit.config.image.build.BuildConfiguration) ImageName(org.eclipse.jkube.kit.config.image.ImageName) AuthConfig(org.eclipse.jkube.kit.build.api.auth.AuthConfig)

Aggregations

AuthConfig (org.eclipse.jkube.kit.build.api.auth.AuthConfig)42 Test (org.junit.Test)34 RegistryAuthConfig (org.eclipse.jkube.kit.build.api.auth.RegistryAuthConfig)10 JsonObject (com.google.gson.JsonObject)6 Expectations (mockit.Expectations)6 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 Date (java.util.Date)3 MockUp (mockit.MockUp)3 ImageName (org.eclipse.jkube.kit.config.image.ImageName)3 ArrayList (java.util.ArrayList)2 HttpPost (org.apache.http.client.methods.HttpPost)2 StringEntity (org.apache.http.entity.StringEntity)2 AuthConfigFactory (org.eclipse.jkube.kit.build.service.docker.auth.AuthConfigFactory)2 RegistryServerConfiguration (org.eclipse.jkube.kit.common.RegistryServerConfiguration)2 SystemMock (org.eclipse.jkube.kit.common.SystemMock)2 Credential (com.google.cloud.tools.jib.api.Credential)1 Gson (com.google.gson.Gson)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 KubernetesList (io.fabric8.kubernetes.api.model.KubernetesList)1