Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cert Manager: Fix extension to get config from annotations #1159

Merged
merged 1 commit into from
Feb 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ public static CertificateConfigBuilder newBuilder(Map<String, Object> map) {

private static CertificateConfig getCertificateConfig(Map<String, Object> map) {
CertificateConfigBuilder certificate = new CertificateConfigBuilder()
.withName(getString(map, "name", ""))
.withSecretName(getString(map, "secretName"));
.withName(getOptionalString(map, "name").orElse(null))
.withSecretName(getOptionalString(map, "secretName").orElse(null));

// optional configuration
getOptionalMap(map, "subject").ifPresent(s -> certificate.withSubject(getSubject(s)));
Expand Down Expand Up @@ -92,9 +92,15 @@ private static SelfSigned getSelfSignedConfig(Map<String, Object> map) {
}

private static Vault getVaultConfig(Map<String, Object> map) {
Optional<String> server = getOptionalString(map, "server");
Optional<String> path = getOptionalString(map, "path");
if (!server.isPresent() && !path.isPresent()) {
return null;
}

VaultBuilder issuer = new VaultBuilder()
.withServer(getString(map, "server"))
.withPath(getString(map, "path"));
.withServer(server.get())
.withPath(path.get());

// optional configuration
getOptionalMap(map, "authTokenSecretRef").ifPresent(a -> issuer.withAuthTokenSecretRef(getLocalObjectRef(a)));
Expand Down Expand Up @@ -125,8 +131,13 @@ private static VaultAppRole getVaultAppRole(Map<String, Object> map) {
}

private static CA getCaConfig(Map<String, Object> map) {
Optional<String> secretName = getOptionalString(map, "secretName");
if (!secretName.isPresent()) {
return null;
}

CABuilder issuer = new CABuilder()
.withSecretName(getString(map, "secretName"));
.withSecretName(secretName.get());

// optional configuration
getOptionalArrayString(map, "crlDistributionPoints").ifPresent(issuer::withCrlDistributionPoints);
Expand Down Expand Up @@ -172,8 +183,13 @@ private static Subject getSubject(Map<String, Object> map) {
}

private static IssuerRef getIssuerRef(Map<String, Object> objectMap) {
Optional<String> name = getOptionalString(objectMap, "name");
if (!name.isPresent()) {
return null;
}

IssuerRefBuilder builder = new IssuerRefBuilder();
builder.withName(getString(objectMap, "name"));
builder.withName(name.get());
getOptionalString(objectMap, "kind").ifPresent(builder::withKind);
getOptionalString(objectMap, "group").ifPresent(builder::withGroup);
return builder.build();
Expand Down Expand Up @@ -206,24 +222,10 @@ private static boolean getBoolean(Map<String, Object> map, String key, boolean d
}).orElse(defaultValue);
}

private static String getString(Map<String, Object> map, String key) {
return getOptionalString(map, key)
.orElseThrow(() -> new IllegalArgumentException("Missing property '" + key + "' in Certificate"));
}

private static String getString(Map<String, Object> map, String key, String defaultStr) {
return getOptionalString(map, key).orElse(defaultStr);
}

private static Optional<String> getOptionalString(Map<String, Object> map, String key) {
return Optional.ofNullable(get(map, key)).map(o -> (String) o).filter(Strings::isNotNullOrEmpty);
}

private static Map<String, Object> getMap(Map<String, Object> map, String key) {
return getOptionalMap(map, key)
.orElseThrow(() -> new IllegalArgumentException("Missing property '" + key + "' in Certificate"));
}

private static Optional<Map<String, Object>> getOptionalMap(Map<String, Object> map, String key) {
return Optional.ofNullable(get(map, key)).map(o -> (Map<String, Object>) o);
}
Expand Down
81 changes: 81 additions & 0 deletions tests/issue-1158-spring-boot-certmanager-with-annotations/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<artifactId>dekorate-tests</artifactId>
<groupId>io.dekorate</groupId>
<version>3.4-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>

<groupId>io.dekorate</groupId>
<artifactId>issue-1158-spring-boot-certmanager-with-annotations</artifactId>
<name>Dekorate :: Tests :: Annotations :: Cert-Manager :: Spring Boot with certificates using annotations</name>

<dependencies>
<dependency>
<groupId>io.dekorate</groupId>
<artifactId>kubernetes-spring-starter</artifactId>
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>io.dekorate</groupId>
<artifactId>certmanager-annotations</artifactId>
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>io.sundr</groupId>
<artifactId>builder-annotations</artifactId>
<scope>compile</scope>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${version.spring-boot}</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>${version.spring-boot}</version>
</dependency>

<!-- Testing -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${version.junit-jupiter}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${version.junit-jupiter}</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<inherited>true</inherited>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${version.spring-boot}</version>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Copyright 2018 The original 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.dekorate.certmanager;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import io.dekorate.certmanager.annotation.Certificate;
import io.dekorate.certmanager.annotation.CertificateKeystore;
import io.dekorate.certmanager.annotation.CertificateKeystores;
import io.dekorate.certmanager.annotation.CertificatePrivateKey;
import io.dekorate.certmanager.annotation.LocalObjectReference;
import io.dekorate.certmanager.annotation.PrivateKeyAlgorithm;
import io.dekorate.certmanager.annotation.PrivateKeyEncoding;
import io.dekorate.certmanager.annotation.SelfSigned;
import io.dekorate.certmanager.annotation.Subject;

@SpringBootApplication
@Certificate(secretName = "tls-secret", selfSigned = @SelfSigned(enabled = true), usages = { "server auth",
"client auth" }, dnsNames = { "kubernetes-example.com", "localhost" }, subject = @Subject(organizations = { "Dekorate",
"Community" }), duration = "2160h0m0s", renewBefore = "360h0m0s", privateKey = @CertificatePrivateKey(algorithm = PrivateKeyAlgorithm.RSA, encoding = PrivateKeyEncoding.PKCS8, size = 2048), keystores = @CertificateKeystores(pkcs12 = @CertificateKeystore(create = true, passwordSecretRef = @LocalObjectReference(name = "pkcs12-pass", key = "password"))))
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Copyright 2018 The original 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.dekorate.certmanager;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class HelloController {

private static final String HELLO = "hello world!";

@RequestMapping("/")
public String hello() {
return HELLO;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Spring Boot configuration
server.port=8443
server.ssl.enabled=true
server.ssl.key-store-type=PKCS12

# Dekorate configuration
## To expose the application using Ingress
dekorate.kubernetes.ingress.host=kubernetes-example.com
dekorate.kubernetes.ingress.expose=true
dekorate.kubernetes.ingress.tlsSecretName=tls-secret
## To include the keystore secret
dekorate.options.input-path=k8s

## To configure the application for using the generated Certificate and Issuer resources
dekorate.kubernetes.env-vars[0].name=SERVER_SSL_KEY_STORE
dekorate.kubernetes.env-vars[0].value=/etc/certs/keystore.p12
dekorate.kubernetes.env-vars[1].name=SERVER_SSL_KEY_STORE_PASSWORD
dekorate.kubernetes.env-vars[1].secret=pkcs12-pass
dekorate.kubernetes.env-vars[1].value=password
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
apiVersion: v1
kind: Secret
metadata:
name: pkcs12-pass
data:
password: c3VwZXJzZWNyZXQ=
type: Opaque
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Copyright 2018 The original 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.dekorate.certmanager;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

import io.dekorate.utils.Serialization;
import io.fabric8.certmanager.api.model.v1.Certificate;
import io.fabric8.certmanager.api.model.v1.Issuer;
import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesList;
import io.fabric8.kubernetes.api.model.PodSpec;
import io.fabric8.kubernetes.api.model.apps.Deployment;

public class SpringBootCertManagerTest {

private static final String EXPECTED_VOLUME_NAME = "volume-certs";
private static final String EXPECTED_SECRET_NAME = "tls-secret";
private static final String HTTPS = "HTTPS";

@Test
public void shouldContainCertificate() {
Certificate certificate = findFirst(Certificate.class);

assertEquals(EXPECTED_SECRET_NAME, certificate.getSpec().getSecretName());
}

@Test
public void shouldContainSelfSignedIssuer() {
Issuer issuer = findFirst(Issuer.class);
assertNotNull(issuer.getSpec().getSelfSigned());
}

@Test
public void shouldContainVolumesAndSchemaInProbesShouldBeHttps() {
Deployment deployment = findFirst(Deployment.class);

PodSpec podTemplate = deployment.getSpec().getTemplate().getSpec();
assertTrue(podTemplate.getVolumes().stream()
.anyMatch(v -> v.getName().equals(EXPECTED_VOLUME_NAME) && v.getSecret().getSecretName().equals(EXPECTED_SECRET_NAME)));
assertTrue(podTemplate.getContainers().stream()
.allMatch(c -> c.getVolumeMounts().stream().anyMatch(m -> m.getName().equals(EXPECTED_VOLUME_NAME))));
assertTrue(podTemplate.getContainers().stream()
.allMatch(c -> c.getReadinessProbe().getHttpGet().getScheme().equals(HTTPS)));
assertTrue(podTemplate.getContainers().stream()
.allMatch(c -> c.getLivenessProbe().getHttpGet().getScheme().equals(HTTPS)));
}

<T extends HasMetadata> T findFirst(Class<T> clazz) {
KubernetesList list = Serialization
.unmarshalAsList(
SpringBootCertManagerTest.class.getClassLoader().getResourceAsStream("META-INF/dekorate/kubernetes.yml"));
assertNotNull(list);

return (T) list.getItems().stream()
.filter(clazz::isInstance)
.findFirst()
.orElseThrow(IllegalStateException::new);
}
}
1 change: 1 addition & 0 deletions tests/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@
<module>issue-1120-kind-multiple-container-ports</module>
<module>issue-1123-ingress-multiple-container-ports</module>
<module>issue-1124-route-multiple-container-ports</module>
<module>issue-1158-spring-boot-certmanager-with-annotations</module>
</modules>

</project>