Skip to content

Commit

Permalink
server k8s common module
Browse files Browse the repository at this point in the history
Signed-off-by: Abhijeet V <31417623+abvaidya@users.noreply.github.com>
  • Loading branch information
abvaidya committed May 30, 2024
1 parent 95c568e commit efd4d76
Show file tree
Hide file tree
Showing 13 changed files with 402 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,31 @@ default String getApplicationSecret(String appName, String keyName) {

/**
* Retrieve the application secret based on the configured key name as char[].
* @deprecated
* The application name specifies what component is this secret for;
* for example, jdbc for accessing the secret for the jdbc user.
* The default implementation assumes the key name is the secret.
* @param appName application name for the secret
* @param keyName configured value for the secret
* @return secret for the given key and application as char[]
*/
@Deprecated
default char[] getSecret(String appName, String keyName) {
final String secret = getApplicationSecret(appName, keyName);
return secret != null ? secret.toCharArray() : null;
}

/**
* Retrieve the application secret based on the configured key name as char[].
* The application name specifies what component is this secret for;
* for example, jdbc for accessing the secret for the jdbc user.
* The default implementation assumes the key name is the secret.
* @param appName application name for the secret
* @param keygroupName key group name for the secret
* @param keyName name of the secret
* @return secret for the given key and application as char[]
*/
default char[] getSecret(String appName, String keygroupName, String keyName) {
return keyName.toCharArray();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public class AWSParameterStorePrivateKeyStore implements PrivateKeyStore {
}

@Override
public char[] getSecret(String appName, String keyName) {
public char[] getSecret(String appName, String keygroupName, String keyName) {
return getSsmParameter(keyName).toCharArray();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public void testGetSecret() {
when(ssmClient.getParameter(any(Consumer.class)))
.thenReturn(GetParameterResponse.builder().parameter(Parameter.builder().value("secret").build()).build());
AWSParameterStorePrivateKeyStore store = (AWSParameterStorePrivateKeyStore)getFactory(ssmClient).create();
assertEquals(store.getSecret("app1", "key1"), "secret".toCharArray());
assertEquals(store.getSecret("app1", null, "key1"), "secret".toCharArray());
}

@Test
Expand Down
12 changes: 12 additions & 0 deletions libs/java/server_k8s_common/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Athenz Server Common Classes
============================

Common classes used throughout Athenz Server components if server is deployed in Kubernetes.

- KeyStore: PrivateKeyStore implementation using Kubernetes secrets

## License

Copyright The Athenz Authors

Licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
63 changes: 63 additions & 0 deletions libs/java/server_k8s_common/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright The Athenz Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.yahoo.athenz</groupId>
<artifactId>athenz</artifactId>
<version>1.11.60-SNAPSHOT</version>
<relativePath>../../../pom.xml</relativePath>
</parent>

<artifactId>athenz-server-k8s-common</artifactId>
<name>athenz-k8s-server-common</name>
<description>Athenz Kubernetes Server Common Packages</description>
<packaging>jar</packaging>

<properties>
<code.coverage.min>1.00</code.coverage.min>
</properties>

<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.server.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.server.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>${okhttp3.mockwebserver.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.yahoo.athenz</groupId>
<artifactId>athenz-auth-core</artifactId>
<version>${project.parent.version}</version>
</dependency>
<dependency>
<groupId>io.kubernetes</groupId>
<artifactId>client-java</artifactId>
<version>${kubernetes-client.version}</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright The Athenz Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.athenz.server.k8s.common.impl;

import com.yahoo.athenz.auth.PrivateKeyStore;
import com.yahoo.athenz.auth.ServerPrivateKey;
import com.yahoo.athenz.auth.util.Crypto;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Secret;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.invoke.MethodHandles;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

public class KubernetesSecretPrivateKeyStore implements PrivateKeyStore {

private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

private static final String ZMS_SERVICE = "zms";
private static final String ZTS_SERVICE = "zts";
private static final String MSD_SERVICE = "msd";

private static final String ATHENZ_PROP_K8S_ZMS_KEY_NAME = "athenz.k8s.zms.key_name";
private static final String ATHENZ_PROP_K8S_ZMS_KEY_ID_NAME = "athenz.k8s.zms.key_id_name";
private static final String ATHENZ_PROP_K8S_ZTS_KEY_NAME = "athenz.k8s.zts.key_name";
private static final String ATHENZ_PROP_K8S_ZTS_KEY_ID_NAME = "athenz.k8s.zts.key_id_name";
private static final String ATHENZ_PROP_K8S_MSD_KEY_NAME = "athenz.k8s.msd.key_name";
private static final String ATHENZ_PROP_K8S_MSD_KEY_ID_NAME = "athenz.k8s.msd.key_id_name";

private static final String ATHENZ_K8S_DEFAULT_KEY_NAME = "service_k8s_private_key";
private static final String ATHENZ_K8S_DEFAULT_KEY_ID_NAME = "service_k8s_private_key_id";

private final ApiClient k8sClient;

private static final String ATHENZ_K8S_CONNECT_TIMEOUT = "athenz.k8s.connect_timeout";
private static final String ATHENZ_K8S_READ_TIMEOUT = "athenz.k8s.read_timeout";

public KubernetesSecretPrivateKeyStore(ApiClient k8sClient) {
this.k8sClient = k8sClient;
this.k8sClient.setConnectTimeout(Integer.parseInt(System.getProperty(ATHENZ_K8S_CONNECT_TIMEOUT, "500")));
this.k8sClient.setReadTimeout(Integer.parseInt(System.getProperty(ATHENZ_K8S_READ_TIMEOUT, "2000")));
Configuration.setDefaultApiClient(k8sClient);
}

@Override
public ServerPrivateKey getPrivateKey(String service, String namespace,
String secretName, String algorithm) {
String keyName;
String keyIdName;
final String objectSuffix = "." + algorithm.toLowerCase();
if (ZMS_SERVICE.equals(service)) {
keyName = System.getProperty(ATHENZ_PROP_K8S_ZMS_KEY_NAME, ATHENZ_K8S_DEFAULT_KEY_NAME) + objectSuffix;
keyIdName = System.getProperty(ATHENZ_PROP_K8S_ZMS_KEY_ID_NAME, ATHENZ_K8S_DEFAULT_KEY_ID_NAME) + objectSuffix;
} else if (ZTS_SERVICE.equals(service)) {
keyName = System.getProperty(ATHENZ_PROP_K8S_ZTS_KEY_NAME, ATHENZ_K8S_DEFAULT_KEY_NAME) + objectSuffix;
keyIdName = System.getProperty(ATHENZ_PROP_K8S_ZTS_KEY_ID_NAME, ATHENZ_K8S_DEFAULT_KEY_ID_NAME) + objectSuffix;
} else if (MSD_SERVICE.equals(service)) {
keyName = System.getProperty(ATHENZ_PROP_K8S_MSD_KEY_NAME, ATHENZ_K8S_DEFAULT_KEY_NAME) + objectSuffix;
keyIdName = System.getProperty(ATHENZ_PROP_K8S_MSD_KEY_ID_NAME, ATHENZ_K8S_DEFAULT_KEY_ID_NAME) + objectSuffix;
} else {
LOG.error("Unknown service specified: {}", service);
return null;
}

PrivateKey pkey = null;
try {
pkey = Crypto.loadPrivateKey(getSecretFromK8S(namespace, secretName, keyName));
} catch (Exception ex) {
LOG.error("unable to load private key", ex);
}
return pkey == null ? null : new ServerPrivateKey(pkey, getSecretFromK8S(namespace, secretName, keyIdName));
}

@Override
public char[] getSecret(String namespace, String secretName, String keyName) {
return getSecretFromK8S(namespace, secretName, keyName).toCharArray();
}

String getSecretFromK8S(String namespace, String secretName, String keyName) {
try {
CoreV1Api api = new CoreV1Api(k8sClient);
V1Secret secret = api.readNamespacedSecret(secretName, namespace).execute();
if (secret != null && secret.getData() != null && secret.getData().get(keyName) != null) {
return new String(secret.getData().get(keyName), StandardCharsets.UTF_8);
} else {
LOG.error("Unable to retrieve secret={} for key={} from namespace={}", secretName, keyName, namespace);
return "";
}
} catch (ApiException e) {
LOG.error("Error in retrieving secret={} for key={} from namespace={}", secretName, keyName, namespace);
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright The Athenz Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.athenz.server.k8s.common.impl;

import com.yahoo.athenz.auth.PrivateKeyStore;
import com.yahoo.athenz.auth.PrivateKeyStoreFactory;
import io.kubernetes.client.util.Config;

public class KubernetesSecretPrivateKeyStoreFactory implements PrivateKeyStoreFactory {
@Override
public PrivateKeyStore create() {
try {
return new KubernetesSecretPrivateKeyStore(Config.defaultClient());
} catch (Exception ex) {
throw new RuntimeException("Unable to create KubernetesSecretPrivateKeyStore", ex);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* Copyright The Athenz Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.athenz.server.k8s.common.impl;

import com.yahoo.athenz.auth.PrivateKeyStore;
import io.kubernetes.client.util.Config;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.testng.annotations.Test;

import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;

public class KubernetesSecretPrivateKeyStoreFactoryTest {
@Test
public void createKubernetesSecretPrivateKeyStore() {
PrivateKeyStore privateKeyStore = new KubernetesSecretPrivateKeyStoreFactory().create();
assertTrue(privateKeyStore instanceof KubernetesSecretPrivateKeyStore);
}

@Test
public void createKubernetesSecretPrivateKeyStoreException() {
try (MockedStatic<Config> configMockedStatic = Mockito.mockStatic(Config.class)) {
configMockedStatic.when(Config::defaultClient).thenThrow(new RuntimeException("mocked exception"));
try {
new KubernetesSecretPrivateKeyStoreFactory().create();
fail();
} catch (RuntimeException ex) {
assertTrue(ex.getMessage().contains("Unable to create KubernetesSecretPrivateKeyStore"));
}
}
}
}
Loading

0 comments on commit efd4d76

Please sign in to comment.