Search in sources :

Example 61 with Role

use of io.fabric8.kubernetes.api.model.rbac.Role in project devspaces-images by redhat-developer.

the class KubernetesWorkspaceServiceAccountTest method shouldCreateMetricsRoleIfAPIEnabledOnServer.

@Test
public void shouldCreateMetricsRoleIfAPIEnabledOnServer() throws Exception {
    KubernetesClient localK8sClient = spy(serverMock.getClient());
    when(localK8sClient.supportsApiPath(eq("/apis/metrics.k8s.io"))).thenReturn(true);
    when(clientFactory.create(anyString())).thenReturn(localK8sClient);
    // when
    serviceAccount.prepare();
    // then
    // make sure metrics role & rb added
    RoleList rl = k8sClient.rbac().roles().inNamespace(NAMESPACE).list();
    assertTrue(rl.getItems().stream().anyMatch(r -> r.getMetadata().getName().equals(METRICS_ROLE_NAME)));
    RoleBindingList rbl = k8sClient.rbac().roleBindings().inNamespace(NAMESPACE).list();
    assertTrue(rbl.getItems().stream().anyMatch(rb -> rb.getMetadata().getName().equals(SA_NAME + "-metrics")));
}
Also used : Arrays(java.util.Arrays) KubernetesClientFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientFactory) Listeners(org.testng.annotations.Listeners) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RoleBindingList(io.fabric8.kubernetes.api.model.rbac.RoleBindingList) Mock(org.mockito.Mock) Role(io.fabric8.kubernetes.api.model.rbac.Role) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) Mockito.spy(org.mockito.Mockito.spy) Collections.singletonList(java.util.Collections.singletonList) RoleBuilder(io.fabric8.kubernetes.api.model.rbac.RoleBuilder) SECRETS_ROLE_NAME(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.AbstractWorkspaceServiceAccount.SECRETS_ROLE_NAME) CONFIGMAPS_ROLE_NAME(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.AbstractWorkspaceServiceAccount.CONFIGMAPS_ROLE_NAME) RoleBindingBuilder(io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder) KubernetesServer(io.fabric8.kubernetes.client.server.mock.KubernetesServer) MockitoTestNGListener(org.mockito.testng.MockitoTestNGListener) ServiceAccountBuilder(io.fabric8.kubernetes.api.model.ServiceAccountBuilder) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) CREDENTIALS_SECRET_NAME(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.AbstractWorkspaceServiceAccount.CREDENTIALS_SECRET_NAME) Mockito.when(org.mockito.Mockito.when) PolicyRule(io.fabric8.kubernetes.api.model.rbac.PolicyRule) RoleList(io.fabric8.kubernetes.api.model.rbac.RoleList) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) Assert.assertTrue(org.testng.Assert.assertTrue) Optional(java.util.Optional) METRICS_ROLE_NAME(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.AbstractWorkspaceServiceAccount.METRICS_ROLE_NAME) Collections(java.util.Collections) PREFERENCES_CONFIGMAP_NAME(org.eclipse.che.workspace.infrastructure.kubernetes.namespace.AbstractWorkspaceServiceAccount.PREFERENCES_CONFIGMAP_NAME) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) RoleList(io.fabric8.kubernetes.api.model.rbac.RoleList) RoleBindingList(io.fabric8.kubernetes.api.model.rbac.RoleBindingList) Test(org.testng.annotations.Test)

Example 62 with Role

use of io.fabric8.kubernetes.api.model.rbac.Role in project syndesis-qe by syndesisio.

the class PublicApiUtils method createServiceAccount.

/**
 * Method creates service account for Public API and gives them competent role
 */
public static void createServiceAccount() {
    ServiceAccount existServiceAccount = OpenShiftUtils.getInstance().serviceAccounts().withName(SERVICE_ACCOUNT_NAME).get();
    if (existServiceAccount == null) {
        OpenShiftUtils.getInstance().serviceAccounts().createNew().withNewMetadata().withName(SERVICE_ACCOUNT_NAME).endMetadata().done();
        OpenShiftUtils.getInstance().addRoleToUser("edit", "system:serviceaccount:" + TestConfiguration.openShiftNamespace() + ":syndesis-cd-client");
    }
    publicApiToken = OpenShiftUtils.binary().execute("sa", "get-token", SERVICE_ACCOUNT_NAME);
}
Also used : ServiceAccount(io.fabric8.kubernetes.api.model.ServiceAccount)

Example 63 with Role

use of io.fabric8.kubernetes.api.model.rbac.Role in project docker-maven-plugin by fabric8io.

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.' or 'registry.') 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,
 * @return the authentication configuration or <code>null</code> if none could be found
 *
 * @throws MojoFailureException
 */
private AuthConfig createStandardAuthConfig(boolean isPush, Map authConfigMap, Settings settings, String user, String registry) throws MojoExecutionException {
    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, LookupMode.REGISTRY }) {
        // System properties docker.username and docker.password always take precedence
        ret = getAuthConfigFromSystemProperties(lookupMode);
        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
        if (lookupMode != LookupMode.REGISTRY) {
            ret = getAuthConfigFromOpenShiftConfig(lookupMode, authConfigMap);
            if (ret != null) {
                log.debug("AuthConfig: OpenShift credentials");
                return ret;
            }
        }
        // Get configuration from global plugin config
        ret = getAuthConfigFromPluginConfiguration(lookupMode, authConfigMap);
        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);
    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();
        if (ret != null) {
            log.debug("AuthConfig: AWS credentials from AWS SDK");
            return ret;
        }
        ret = getAuthConfigFromAwsEnvironmentVariables();
        if (ret != null) {
            log.debug("AuthConfig: AWS credentials from ENV variables");
            return ret;
        }
        try {
            ret = getAuthConfigFromEC2InstanceRole();
        } 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();
        } 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(io.fabric8.maven.docker.access.AuthConfig) IOException(java.io.IOException) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 64 with Role

use of io.fabric8.kubernetes.api.model.rbac.Role in project fabric8 by jboss-fuse.

the class GitHttpServerRegistrationHandler method registerServlet.

private void registerServlet(Path dataPath, String realm, String role) throws Exception {
    synchronized (gitRemoteUrl) {
        basePath = dataPath.resolve(Paths.get("git", "servlet"));
        Path fabricRepoPath = basePath.resolve("fabric");
        String servletBase = basePath.toFile().getAbsolutePath();
        // Init and clone the local repo.
        File fabricRoot = fabricRepoPath.toFile();
        if (!fabricRoot.exists()) {
            LOGGER.info("Cloning master root repo into {}", fabricRoot);
            File localRepo = gitDataStore.get().getGit().getRepository().getDirectory();
            git = Git.cloneRepository().setTimeout(10).setBare(true).setNoCheckout(true).setCloneAllBranches(true).setDirectory(fabricRoot).setURI(localRepo.toURI().toString()).call();
        } else {
            LOGGER.info("{} already exists", fabricRoot);
            git = Git.open(fabricRoot);
        }
        HttpContext base = httpService.get().createDefaultHttpContext();
        HttpContext secure = new GitSecureHttpContext(base, curator.get(), realm, role);
        Dictionary<String, Object> initParams = new Hashtable<String, Object>();
        initParams.put("base-path", servletBase);
        initParams.put("repository-root", servletBase);
        initParams.put("export-all", "true");
        httpService.get().registerServlet("/git", new FabricGitServlet(git, curator.get()), initParams, secure);
        registerGitHttpEndpoint();
    }
}
Also used : ZkPath(io.fabric8.zookeeper.ZkPath) Path(java.nio.file.Path) Hashtable(java.util.Hashtable) HttpContext(org.osgi.service.http.HttpContext) File(java.io.File)

Example 65 with Role

use of io.fabric8.kubernetes.api.model.rbac.Role in project fabric8 by jboss-fuse.

the class ClusterBootstrapManager method getCreateEnsembleOptions.

static CreateEnsembleOptions getCreateEnsembleOptions(RuntimeProperties sysprops, Map<String, Object> options) {
    String username = (String) options.remove("username");
    String password = (String) options.remove("password");
    String role = (String) options.remove("role");
    if (username == null || password == null || role == null) {
        throw new FabricException("Must specify an administrator username, password and administrative role when creating a fabric");
    }
    Object profileObject = options.remove("profiles");
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    CreateEnsembleOptions.Builder builder = mapper.convertValue(options, CreateEnsembleOptions.Builder.class);
    if (profileObject != null) {
        List profiles = mapper.convertValue(profileObject, List.class);
        builder.profiles(profiles);
    }
    org.apache.felix.utils.properties.Properties userProps = null;
    try {
        userProps = new org.apache.felix.utils.properties.Properties(sysprops.getConfPath().resolve("users.properties").toFile());
    } catch (IOException e) {
        userProps = new org.apache.felix.utils.properties.Properties();
    }
    if (userProps.get(username) == null) {
        userProps.put(username, password + "," + role);
    }
    CreateEnsembleOptions answer = builder.users(userProps).withUser(username, password, role).build();
    LOG.debug("Creating ensemble with options: {}", answer);
    System.setProperty(ZkDefs.GLOBAL_RESOLVER_PROPERTY, answer.getGlobalResolver());
    System.setProperty(ZkDefs.LOCAL_RESOLVER_PROPERTY, answer.getResolver());
    System.setProperty(ZkDefs.MANUAL_IP, answer.getManualIp());
    System.setProperty(ZkDefs.BIND_ADDRESS, answer.getBindAddress());
    System.setProperty(ZkDefs.MINIMUM_PORT, "" + answer.getMinimumPort());
    System.setProperty(ZkDefs.MAXIMUM_PORT, "" + answer.getMaximumPort());
    return answer;
}
Also used : FabricException(io.fabric8.api.FabricException) CreateEnsembleOptions(io.fabric8.api.CreateEnsembleOptions) IOException(java.io.IOException) RuntimeProperties(io.fabric8.api.RuntimeProperties) List(java.util.List) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

Role (io.fabric8.kubernetes.api.model.rbac.Role)40 RoleRefBuilder (io.fabric8.kubernetes.api.model.rbac.RoleRefBuilder)31 RoleBinding (io.fabric8.kubernetes.api.model.rbac.RoleBinding)27 SubjectBuilder (io.fabric8.kubernetes.api.model.rbac.SubjectBuilder)25 RoleRef (io.fabric8.kubernetes.api.model.rbac.RoleRef)24 RoleBindingBuilder (io.fabric8.kubernetes.api.model.rbac.RoleBindingBuilder)21 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)19 RoleBuilder (io.fabric8.kubernetes.api.model.rbac.RoleBuilder)18 Subject (io.fabric8.kubernetes.api.model.rbac.Subject)18 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)16 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)16 Mockito.when (org.mockito.Mockito.when)16 PolicyRule (io.fabric8.kubernetes.api.model.rbac.PolicyRule)15 RoleList (io.fabric8.kubernetes.api.model.rbac.RoleList)15 Test (org.junit.Test)15 RoleBindingList (io.fabric8.kubernetes.api.model.rbac.RoleBindingList)14 List (java.util.List)14 IOException (java.io.IOException)13 Collections (java.util.Collections)13 Optional (java.util.Optional)13