private AuthCredentialsServiceState createCredentials(AuthCredentialsType type, boolean setKubeConfig) throws Throwable { AuthCredentialsServiceState credentials = new AuthCredentialsServiceState(); if (AuthCredentialsType.Bearer == type) { credentials.type = AuthCredentialsType.Bearer.toString(); credentials.publicKey = "token"; } else if (AuthCredentialsType.PublicKey == type) { credentials.type = AuthCredentialsType.PublicKey.toString(); credentials.publicKey = "certificate"; credentials.privateKey = "privateKey"; } else { credentials.type = type.toString(); } if (setKubeConfig) { credentials.customProperties = new HashMap<>(); credentials.customProperties.put("__kubeConfig", KUBE_CONFIG_JSON); } return doPost(credentials, AuthCredentialsService.FACTORY_LINK); }
private Operation createCaCredentials(String caCert, String caKey) { AuthCredentialsServiceState authCredentials = new AuthCredentialsServiceState(); authCredentials.documentSelfLink = ManagementUriParts.AUTH_CREDENTIALS_CA_LINK; authCredentials.type = AuthCredentialsType.PublicKeyCA.name(); authCredentials.userEmail = "core"; authCredentials.publicKey = caCert; authCredentials.privateKey = caKey; return Operation.createPost(this, AuthCredentialsService.FACTORY_LINK) .addPragmaDirective(Operation.PRAGMA_DIRECTIVE_FORCE_INDEX_UPDATE) .setBody(authCredentials); }
public static String createAuthorizationHeader(AuthCredentialsServiceState authState) { if (authState == null) { return null; } if (AuthCredentialsType.Bearer.toString().equals(authState.type)) { String token = EncryptionUtils.decrypt(authState.privateKey); return "Bearer " + token; } AuthCredentialsType authCredentialsType = AuthCredentialsType.valueOf(authState.type); if (AuthCredentialsType.Password == authCredentialsType) { String username = authState.userEmail; String password = EncryptionUtils.decrypt(authState.privateKey); String code = new String(Base64.getEncoder().encode( (username + ":" + password).getBytes())); return "Basic " + code; } return null; }
/** * Login in PKS and returns PKS context instance with token. */ private DeferredResult<PKSContext> login(Endpoint endpoint, AuthCredentialsServiceState authCredentials) { if (authCredentials == null) { return DeferredResult.completed(PKSContext.create(endpoint, null)); } AuthCredentialsType authCredentialsType = AuthCredentialsType.valueOf(authCredentials.type); if (AuthCredentialsType.Password == authCredentialsType) { String username = authCredentials.userEmail; String password = EncryptionUtils.decrypt(authCredentials.privateKey); return getClient() .login(endpoint.uaaEndpoint, username, password) .thenApply(uaaTokenResponse -> PKSContext.create(endpoint, uaaTokenResponse)); } throw new IllegalArgumentException("Credential type " + authCredentialsType.name() + " is not supported"); }
public static KubeConfig constructKubeConfig(String clusterAddress, AuthCredentialsServiceState credentials) { KubeConfig config = createKubeConfig(clusterAddress); KubeConfig.UserEntry userEntry = new KubeConfig.UserEntry(); userEntry.name = config.contexts.get(0).context.user; userEntry.user = new KubeConfig.AuthInfo(); config.users = Arrays.asList(userEntry); AuthCredentialsType credentialsType = AuthCredentialsType.valueOf(credentials.type); switch (credentialsType) { case Bearer: userEntry.user.token = EncryptionUtils.decrypt(credentials.privateKey); break; case PublicKey: userEntry.user.clientCertificateData = new String( Base64.getEncoder().encode(credentials.publicKey.getBytes())); userEntry.user.clientKeyData = new String(Base64.getEncoder() .encode(EncryptionUtils.decrypt(credentials.privateKey).getBytes())); break; case Password: userEntry.user.username = credentials.userEmail; userEntry.user.password = EncryptionUtils.decrypt(credentials.privateKey); break; default: throw new LocalizableValidationException("Unsupported credentials type", "adapter.unsuported.auth.credentials.type"); } return config; }
if (registryState.authCredentials != null) { AuthCredentialsServiceState authState = registryState.authCredentials; AuthCredentialsType authType = AuthCredentialsType.valueOf(authState.type); if (AuthCredentialsType.Password == authType) {
private void createCredentials(Operation op, String link, String token, KubeConfig kubeConfig, List<String> tenantLinks, Consumer<String> consumer) { AuthCredentialsServiceState credentials = new AuthCredentialsServiceState(); credentials.documentSelfLink = link; credentials.privateKey = token; credentials.type = AuthCredentialsType.Bearer.toString(); credentials.tenantLinks = tenantLinks; credentials.customProperties = new HashMap<>(4); credentials.customProperties.put(KUBE_CONFIG_PROP_NAME, Utils.toJson(kubeConfig)); // Set the display name of the credential to the cluster name, if it exists if (CollectionUtils.isNotEmpty(kubeConfig.clusters) && StringUtils.isNotEmpty(kubeConfig.clusters.get(0).name)) { credentials.customProperties.put(AuthUtils.AUTH_CREDENTIALS_NAME_PROP_NAME, kubeConfig.clusters.get(0).name); } Operation.createPost(getHost(), AuthCredentialsService.FACTORY_LINK) .setBodyNoCloning(credentials) .addPragmaDirective(Operation.PRAGMA_DIRECTIVE_FORCE_INDEX_UPDATE) .setCompletion((o, e) -> { if (e != null) { logWarning("Error creating PKS credentials state: %s", e.getMessage()); op.fail(e); return; } consumer.accept(link); }) .sendWith(this); }
private void createOrUpdateTargetSsl(KubernetesContext context) { URI uri = UriUtils.buildUri(context.host.address); if (!isSecure(uri)) { return; } String sslTrust = context.SSLTrustCertificate; if (sslTrust != null && trustManager != null) { String trustAlias = context.SSLTrustAlias; trustManager.putDelegate(trustAlias, sslTrust); } if (context.credentials == null || !AuthCredentialsType.PublicKey.name().equals(context.credentials.type)) { return; } String clientKey = EncryptionUtils.decrypt(context.credentials.privateKey); String clientCert = context.credentials.publicKey; String alias = context.host.address.toLowerCase(); if (clientKey != null && !clientKey.isEmpty()) { X509ExtendedKeyManager delegateKeyManager = (X509ExtendedKeyManager) CertificateUtil .getKeyManagers(alias, clientKey, clientCert)[0]; keyManager.putDelegate(alias, delegateKeyManager); } }
private void createHarborCredentials(Operation post, Consumer<String> callback) { AuthCredentialsServiceState state = new AuthCredentialsServiceState(); state.type = AuthCredentialsType.Password.toString(); state.userEmail = Harbor.DEFAULT_REGISTRY_USER_PREFIX + UUID.randomUUID(); state.privateKey = new BigInteger(160, new SecureRandom()).toString(32); sendRequest(Operation .createPost(UriUtils.buildUri(getHost(), ServiceUriPaths.CORE_CREDENTIALS)) .setBodyNoCloning(state) .setCompletion((o, e) -> { if (e != null) { logSevere("Unable to create default harbor credentials: %s", Utils.toString(e)); post.fail(e); return; } AuthCredentialsServiceState body = o.getBody(AuthCredentialsServiceState.class); callback.accept(body.documentSelfLink); })); }
public static AuthCredentialsServiceState createAuthCredentials(boolean uniqueSelfLink) { AuthCredentialsServiceState authCredentials = new AuthCredentialsServiceState(); authCredentials.documentSelfLink = AUTH_CREDENTIALS_ID; if (uniqueSelfLink) { authCredentials.documentSelfLink += "-" + UUID.randomUUID(); } authCredentials.type = AuthCredentialsType.PublicKey.name(); authCredentials.userEmail = "core"; authCredentials.privateKey = getFileContent("docker-host-private-key.PEM"); return authCredentials; }
protected AuthCredentialsServiceState createCredentialsWithKeys(String publicKey, String privateKey) throws Throwable { AuthCredentialsServiceState credentials = new AuthCredentialsServiceState(); credentials.publicKey = publicKey; credentials.privateKey = privateKey; credentials.type = AuthCredentialsType.PublicKey.toString(); return getOrCreateDocument(credentials, AuthCredentialsService.FACTORY_LINK); }
private Operation createClientCredentials(String caCert, String caKey) { X509Certificate caCertificate = CertificateUtil.createCertificate(caCert); KeyPair caKeyPair = CertificateUtil.createKeyPair(caKey); AuthCredentialsServiceState authCredentials = new AuthCredentialsServiceState(); authCredentials.documentSelfLink = ManagementUriParts.AUTH_CREDENTIALS_CLIENT_LINK; authCredentials.type = AuthCredentialsType.PublicKey.name(); authCredentials.userEmail = "core"; CertChainKeyPair signedForClient = CertificateUtil.generateSignedForClient("computeClient", caCertificate, caKeyPair.getPrivate()); authCredentials.publicKey = CertificateUtilExtended.toPEMformat( signedForClient.getCertificate(), getHost()); authCredentials.privateKey = CertificateUtilExtended.toPEMFormat( signedForClient.getPrivateKey(), getHost()); return Operation.createPost(this, AuthCredentialsService.FACTORY_LINK) .addPragmaDirective(Operation.PRAGMA_DIRECTIVE_FORCE_INDEX_UPDATE) .setBody(authCredentials); }
protected AuthCredentialsServiceState createCredentials(String username, String password, boolean isSystem) throws Throwable { AuthCredentialsServiceState credentials = new AuthCredentialsServiceState(); credentials.userEmail = username; credentials.privateKey = password; credentials.type = AuthCredentialsType.Password.toString(); if (isSystem) { credentials.customProperties = new HashMap<>(); credentials.customProperties.put(AuthConfigProvider.PROPERTY_SCOPE, AuthConfigProvider.CredentialsScope.SYSTEM.toString()); } return getOrCreateDocument(credentials, AuthCredentialsService.FACTORY_LINK); }
@Test public void testWithHarborProperty() throws Exception { createHarborConfigurationState("harbor.address"); TestContext t = new TestContext(1, Duration.ofSeconds(15)); harborInitRegistryService.handleStart(Operation .createGet(null) .setCompletion(t.getCompletion())); t.await(); RegistryState harborRegistry = getHarborRegistry(true); assertNotNull(harborRegistry); assertEquals("harbor.address", harborRegistry.address); assertNotNull(harborRegistry.authCredentialsLink); AuthCredentialsServiceState credentialsState = getCredentialsState( harborRegistry.authCredentialsLink); assertNotNull(credentialsState); assertNotNull(credentialsState.userEmail); assertNotNull(credentialsState.privateKey); assertEquals(AuthCredentialsType.Password.name(), credentialsState.type); assertTrue(credentialsState.userEmail.startsWith(Harbor.DEFAULT_REGISTRY_USER_PREFIX)); assertTrue(credentialsState.privateKey.length() > 20); }
@Test public void testConstructKubeConfigWithBearerToken() { String clusterAddress = "https://testhost:8443"; String token = "bearer_token"; AuthCredentialsServiceState creds = new AuthCredentialsServiceState(); creds.privateKey = token; creds.type = AuthCredentialsType.Bearer.toString(); KubeConfig config = KubernetesUtil.constructKubeConfig(clusterAddress, creds); assertNotNull(config); assertEquals(token, config.users.get(0).user.token); }
@Test public void testWithNewHarborProperty() throws Exception { testWithHarborProperty(); RegistryState registryOld = getHarborRegistry(true); updateHarborConfigurationState("harbor.address.new"); TestContext t = new TestContext(1, Duration.ofSeconds(15)); harborInitRegistryService.handleStart(Operation .createGet(null) .setCompletion(t.getCompletion())); t.await(); RegistryState registryNew = getHarborRegistry(true); assertEquals("harbor.address.new", registryNew.address); assertNotNull(registryNew.authCredentialsLink); assertNotEquals(registryOld.authCredentialsLink, registryNew.authCredentialsLink); AuthCredentialsServiceState credentialsNew = getCredentialsState( registryNew.authCredentialsLink); assertNotNull(credentialsNew.userEmail); assertNotNull(credentialsNew.privateKey); assertEquals(AuthCredentialsType.Password.name(), credentialsNew.type); assertTrue(credentialsNew.userEmail.startsWith(Harbor.DEFAULT_REGISTRY_USER_PREFIX)); assertTrue(credentialsNew.privateKey.length() > 20); }
@Test public void testConstructKubeConfigWithPassword() { String clusterAddress = "https://testhost:8443"; String username = "user1"; String password = "password123"; AuthCredentialsServiceState creds = new AuthCredentialsServiceState(); creds.userEmail = username; creds.privateKey = password; creds.type = AuthCredentialsType.Password.toString(); KubeConfig config = KubernetesUtil.constructKubeConfig(clusterAddress, creds); assertNotNull(config); assertEquals(username, config.users.get(0).user.username); assertEquals(password, config.users.get(0).user.password); }
@Before public void setUpMockKubernetesHost() throws Throwable { ServiceHost.Arguments args = new ServiceHost.Arguments(); args.sandbox = null; args.port = 0; mockKubernetesHost = createHost(); mockKubernetesHost.setMaintenanceIntervalMicros(TimeUnit.MILLISECONDS .toMicros(MAINTENANCE_INTERVAL_MILLIS)); kubernetesUri = UriUtils.buildUri(mockKubernetesHost, KubernetesPathConstants.BASE_PATH); kubernetesFailingUri = UriUtils.buildUri(mockKubernetesHost, KubernetesPathConstants.BASE_FAILING_PATH); kubernetesCredentials = new AuthCredentialsServiceState(); kubernetesCredentials.type = AuthCredentialsType.Password.name(); kubernetesCredentials.userEmail = "test@admiral"; kubernetesCredentials.privateKey = "password"; HostInitTestDcpServicesConfig.startServices(host); HostInitPhotonModelServiceConfig.startServices(host); HostInitCommonServiceConfig.startServices(host); HostInitComputeServicesConfig.startServices(host, false); HostInitKubernetesAdapterServiceConfig.startServices(host, false); waitForInitialBootServiceToBeSelfStopped(ComputeInitialBootService.SELF_LINK); host.log("Using test kubernetes URI: %s", kubernetesUri); System.setProperty("dcp.management.container.shell.availability.retry", "0"); host.startService( Operation.createPost(UriUtils.buildUri(host, MockTaskFactoryService.SELF_LINK)), new MockTaskFactoryService()); }
@Test(expected = LocalizableValidationException.class) public void testFailConstructKubeConfigWithUnsupportedCredentials() { AuthCredentialsServiceState creds = new AuthCredentialsServiceState(); creds.type = AuthCredentialsType.PublicKeyCA.toString(); KubernetesUtil.constructKubeConfig("https://localhost:6443", creds); fail("KubeConfig construction should have failed with unsupported credentials"); }
@Test public void testCreateAuthorizationHeader() { // No credentials assertNull(AuthUtils.createAuthorizationHeader(null)); // Non-password credentials AuthCredentialsServiceState credentials = new AuthCredentialsServiceState(); credentials.type = AuthCredentialsType.PublicKey.toString(); assertNull(AuthUtils.createAuthorizationHeader(credentials)); // Password credentials String email = "test@test.test"; String password = "test"; String expectedHeader = String.format("Basic %s", new String(Base64.getEncoder() .encode(String.format("%s:%s", email, password).getBytes()))); credentials = new AuthCredentialsServiceState(); credentials.type = AuthCredentialsType.Password.toString(); credentials.userEmail = email; credentials.privateKey = password; assertEquals(expectedHeader, AuthUtils.createAuthorizationHeader(credentials)); // Bearer token String token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJrdWJlcm5ldGVzL"; expectedHeader = String.format("Bearer %s", token); credentials = new AuthCredentialsServiceState(); credentials.type = "Bearer"; credentials.privateKey = token; assertEquals(expectedHeader, AuthUtils.createAuthorizationHeader(credentials)); }