🎉 Init

This commit is contained in:
2026-07-19 16:43:30 +02:00
commit 3e380643d7
61 changed files with 4644 additions and 0 deletions
+100
View File
@@ -0,0 +1,100 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode
#
# Before building the container image run:
#
# ./mvnw package
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/reconciler-jvm .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/reconciler-jvm
#
# If you want to include the debug port into your docker image
# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.
# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005
# when running the container
#
# Then run the container using :
#
# docker run -i --rm -p 8080:8080 quarkus/reconciler-jvm
#
# This image uses the `run-java.sh` script to run the application.
# This scripts computes the command line to execute your Java application, and
# includes memory/GC tuning.
# You can configure the behavior using the following environment properties:
# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") - Be aware that this will override
# the default JVM options, use `JAVA_OPTS_APPEND` to append options
# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options
# in JAVA_OPTS (example: "-Dsome.property=foo")
# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is
# used to calculate a default maximal heap memory based on a containers restriction.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio
# of the container available memory as set here. The default is `50` which means 50%
# of the available memory is used as an upper boundary. You can skip this mechanism by
# setting this value to `0` in which case no `-Xmx` option is added.
# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This
# is used to calculate a default initial heap memory based on the maximum heap memory.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio
# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`
# is used as the initial heap size. You can skip this mechanism by setting this value
# to `0` in which case no `-Xms` option is added (example: "25")
# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.
# This is used to calculate the maximum value of the initial heap memory. If used in
# a container without any memory constraints for the container then this option has
# no effect. If there is a memory constraint then `-Xms` is limited to the value set
# here. The default is 4096MB which means the calculated value of `-Xms` never will
# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")
# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output
# when things are happening. This option, if set to true, will set
# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").
# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:
# true").
# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").
# - CONTAINER_CORE_LIMIT: A calculated core limit as described in
# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")
# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").
# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.
# (example: "20")
# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.
# (example: "40")
# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.
# (example: "4")
# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus
# previous GC times. (example: "90")
# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")
# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")
# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should
# contain the necessary JRE command-line options to specify the required GC, which
# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).
# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")
# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")
# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be
# accessed directly. (example: "foo.example.com,bar.example.com")
#
# You can find more information about the UBI base runtime images and their configuration here:
# https://rh-openjdk.github.io/redhat-openjdk-containers/
###
FROM registry.access.redhat.com/ubi8/openjdk-21:1.23
ENV LANGUAGE='en_US:en'
# We make four distinct layers so if there are application changes the library layers can be re-used
COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/
COPY --chown=185 target/quarkus-app/*.jar /deployments/
COPY --chown=185 target/quarkus-app/app/ /deployments/app/
COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/
EXPOSE 8080
USER 185
ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]
@@ -0,0 +1,17 @@
package dev.dinauer.lockaway.reconciler;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import java.util.List;
import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
@RegisterRestClient(configKey = "backend-api")
@Path("/secrets")
public interface BackendClient
{
@GET
@Produces(MediaType.APPLICATION_JSON)
List<LockawaySecret> get();
}
@@ -0,0 +1,17 @@
package dev.dinauer.lockaway.reconciler;
import io.fabric8.kubernetes.client.KubernetesClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@ApplicationScoped
public class KubernetesNamespaceService
{
@Inject
KubernetesClient kubernetesClient;
public boolean exists(String name)
{
return kubernetesClient.namespaces().withName(name).get() != null;
}
}
@@ -0,0 +1,107 @@
package dev.dinauer.lockaway.reconciler;
import dev.dinauer.lockaway.reconciler.crypto.DecryptionService;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
@ApplicationScoped
public class KubernetesSecretService
{
public static final String LABEL_SECRET_NAME = "lockaway.dev/secret-name";
private static final String ANNOTATION_CONTENT_HASH = "lockaway.dev/content-hash";
private static final String FIELD_MANAGER = "lockaway-reconciler";
@Inject
KubernetesClient kubernetesClient;
@Inject
DecryptionService decryptionService;
public List<Secret> get()
{
return kubernetesClient.secrets().inAnyNamespace().withLabel(LABEL_SECRET_NAME).list().getItems();
}
public void apply(LockawayNamespaceSecret lockawayNamespaceSecret, String contentHash) throws UnmanagedSecretException
{
LockawaySecret lockawaySecret = lockawayNamespaceSecret.lockawaySecret();
String namespace = lockawayNamespaceSecret.namespace();
String name = lockawaySecret.name();
String type = lockawaySecret.type();
Map<String, String> stringData = lockawaySecret.entries()
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> decryptionService.decrypt(e.getValue())));
Secret existing = kubernetesClient.secrets().inNamespace(namespace).withName(name).get();
if (Objects.nonNull(existing))
{
if (isUnmanaged(existing))
{
throw new UnmanagedSecretException(namespace, name);
}
if (isDifferentType(existing, lockawayNamespaceSecret))
{
kubernetesClient.secrets().inNamespace(namespace).withName(name).delete();
}
}
Secret desired = new SecretBuilder()
.withNewMetadata()
.withName(name)
.withNamespace(namespace)
.addToLabels(LABEL_SECRET_NAME, name)
.addToAnnotations(ANNOTATION_CONTENT_HASH, contentHash)
.endMetadata()
.withType(type)
.withStringData(stringData)
.build();
kubernetesClient.secrets().inNamespace(namespace).resource(desired)
.fieldManager(FIELD_MANAGER)
.forceConflicts()
.serverSideApply();
}
public void remove(String namespace, String name) throws UnmanagedSecretException
{
Secret existing = kubernetesClient.secrets().inNamespace(namespace).withName(name).get();
if (Objects.nonNull(existing))
{
if (isUnmanaged(existing))
{
throw new UnmanagedSecretException(namespace, name);
}
kubernetesClient.secrets().inNamespace(namespace).withName(name).delete();
}
}
private boolean isUnmanaged(Secret secret)
{
if (Objects.isNull(secret.getMetadata().getLabels()))
{
return true;
}
return !secret.getMetadata().getLabels().containsKey(LABEL_SECRET_NAME);
}
private boolean isDifferentType(Secret existing, LockawayNamespaceSecret desired)
{
return !existing.getType().equalsIgnoreCase(desired.lockawaySecret().type());
}
public boolean contentHashMatches(Secret existing, String contentHash)
{
return existing.getMetadata().getAnnotations() != null && contentHash.equals(existing.getMetadata().getAnnotations().get(ANNOTATION_CONTENT_HASH));
}
}
@@ -0,0 +1,5 @@
package dev.dinauer.lockaway.reconciler;
public record LockawayNamespaceSecret(String namespace, LockawaySecret lockawaySecret)
{
}
@@ -0,0 +1,8 @@
package dev.dinauer.lockaway.reconciler;
import java.util.List;
import java.util.Map;
public record LockawaySecret(String name, List<String> namespaces, String contentHash, Map<String, String> entries, String type)
{
}
@@ -0,0 +1,145 @@
package dev.dinauer.lockaway.reconciler;
import io.fabric8.kubernetes.api.model.Secret;
import io.quarkus.scheduler.Scheduled;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.*;
import java.util.stream.Collectors;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ApplicationScoped
public class Reconciler
{
private static final Logger LOG = LoggerFactory.getLogger(Reconciler.class);
@Inject
@RestClient
BackendClient backendClient;
@Inject
KubernetesSecretService kubernetesSecretService;
@Inject
KubernetesNamespaceService kubernetesNamespaceService;
@Scheduled(every = "60s")
void reconcile()
{
List<LockawayNamespaceSecret> desired = resolve(backendClient.get());
List<Secret> existing = kubernetesSecretService.get();
create(desired, existing);
update(desired, existing);
prune(desired, existing);
}
private void create(List<LockawayNamespaceSecret> desired, List<Secret> existing)
{
Set<SecretKey> existingKeys = existing.stream().map(Reconciler::keyOf).collect(Collectors.toSet());
for (LockawayNamespaceSecret lockawayNamespaceSecret : desired)
{
if (!existingKeys.contains(keyOf(lockawayNamespaceSecret)))
{
if (kubernetesNamespaceService.exists(lockawayNamespaceSecret.namespace()))
{
try
{
kubernetesSecretService.apply(lockawayNamespaceSecret, lockawayNamespaceSecret.lockawaySecret().contentHash());
LOG.info("[CREATE] {}/{}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name());
}
catch (Exception e)
{
LOG.error("Failed to create secret {}/{}: {}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name(), e.getMessage());
}
}
}
}
}
private void update(List<LockawayNamespaceSecret> desired, List<Secret> existing)
{
Map<SecretKey, Secret> existingByKey = existing.stream().collect(Collectors.toMap(Reconciler::keyOf, s -> s));
for (LockawayNamespaceSecret lockawayNamespaceSecret : desired)
{
Secret current = existingByKey.get(keyOf(lockawayNamespaceSecret));
if (current != null)
{
String contentHash = lockawayNamespaceSecret.lockawaySecret().contentHash();
if (!kubernetesSecretService.contentHashMatches(current, contentHash))
{
if (kubernetesNamespaceService.exists(lockawayNamespaceSecret.namespace()))
{
try
{
kubernetesSecretService.apply(lockawayNamespaceSecret, contentHash);
LOG.info("[UPDATE] {}/{}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name());
}
catch (Exception e)
{
LOG.error("Failed to update secret {}/{}: {}", lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name(), e.getMessage());
}
}
}
}
}
}
private void prune(List<LockawayNamespaceSecret> desired, List<Secret> existing)
{
Set<SecretKey> desiredKeys = desired.stream().map(Reconciler::keyOf).collect(Collectors.toSet());
for (Secret secret : existing)
{
if (!desiredKeys.contains(keyOf(secret)))
{
if (kubernetesNamespaceService.exists(secret.getMetadata().getNamespace()))
{
try
{
kubernetesSecretService.remove(secret.getMetadata().getNamespace(), secret.getMetadata().getName());
LOG.info("[REMOVE] {}/{}", secret.getMetadata().getNamespace(), secret.getMetadata().getName());
}
catch (Exception e)
{
LOG.error("Failed to remove secret {}/{}: {}", secret.getMetadata().getNamespace(), secret.getMetadata().getName(), e.getMessage());
}
}
}
}
}
private List<LockawayNamespaceSecret> resolve(List<LockawaySecret> lockawaySecrets)
{
List<LockawayNamespaceSecret> lockawayNamespaceSecrets = new ArrayList<>();
for (LockawaySecret lockawaySecret : lockawaySecrets)
{
for (String namespace : lockawaySecret.namespaces())
{
lockawayNamespaceSecrets.add(new LockawayNamespaceSecret(namespace, lockawaySecret));
}
}
return lockawayNamespaceSecrets;
}
private static SecretKey keyOf(LockawayNamespaceSecret lockawayNamespaceSecret)
{
return new SecretKey(lockawayNamespaceSecret.namespace(), lockawayNamespaceSecret.lockawaySecret().name());
}
private static SecretKey keyOf(Secret secret)
{
return new SecretKey(secret.getMetadata().getNamespace(),
secret.getMetadata().getLabels().get(KubernetesSecretService.LABEL_SECRET_NAME));
}
private record SecretKey(String namespace, String name)
{
}
}
@@ -0,0 +1,9 @@
package dev.dinauer.lockaway.reconciler;
public class UnmanagedSecretException extends Exception
{
public UnmanagedSecretException(String namespace, String name)
{
super(String.format("Found unmanaged secret %s/%s", namespace, name));
}
}
@@ -0,0 +1,41 @@
package dev.dinauer.lockaway.reconciler.crypto;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
@ApplicationScoped
public class DecryptionService
{
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int IV_LENGTH_BYTES = 12;
private static final int TAG_LENGTH_BITS = 128;
@Inject
MasterKeyProvider masterKeyProvider;
public String decrypt(String encoded)
{
try
{
byte[] data = Base64.getDecoder().decode(encoded);
byte[] iv = Arrays.copyOfRange(data, 0, IV_LENGTH_BYTES);
byte[] ciphertext = Arrays.copyOfRange(data, IV_LENGTH_BYTES, data.length);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, masterKeyProvider.getKey(), new GCMParameterSpec(TAG_LENGTH_BITS, iv));
byte[] plaintext = cipher.doFinal(ciphertext);
return new String(plaintext, StandardCharsets.UTF_8);
}
catch (GeneralSecurityException e)
{
throw new IllegalStateException("Failed to decrypt value", e);
}
}
}
@@ -0,0 +1,61 @@
package dev.dinauer.lockaway.reconciler.crypto;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.eclipse.microprofile.config.inject.ConfigProperty;
@ApplicationScoped
public class MasterKeyProvider
{
private static final String HKDF_INFO = "lockaway-secret-encryption-v1";
private static final String HMAC_ALGORITHM = "HmacSHA256";
private static final int KEY_LENGTH_BYTES = 32;
private final SecretKeySpec derivedKey;
@Inject
public MasterKeyProvider(@ConfigProperty(name = "lockaway.master.key") String masterKey)
{
this.derivedKey = deriveKey(masterKey.getBytes(StandardCharsets.UTF_8));
}
public SecretKeySpec getKey()
{
return derivedKey;
}
private SecretKeySpec deriveKey(byte[] masterKeyBytes)
{
try
{
byte[] salt = new byte[32];
byte[] prk = hmac(salt, masterKeyBytes);
byte[] okm = hmac(prk, concat(HKDF_INFO.getBytes(StandardCharsets.UTF_8), new byte[] { 1 }));
return new SecretKeySpec(Arrays.copyOf(okm, KEY_LENGTH_BYTES), "AES");
}
catch (GeneralSecurityException e)
{
throw new IllegalStateException("Failed to derive encryption key.", e);
}
}
private byte[] hmac(byte[] key, byte[] data) throws GeneralSecurityException
{
Mac mac = Mac.getInstance(HMAC_ALGORITHM);
mac.init(new SecretKeySpec(key, HMAC_ALGORITHM));
return mac.doFinal(data);
}
private byte[] concat(byte[] a, byte[] b)
{
byte[] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
}
@@ -0,0 +1,2 @@
%dev.quarkus.rest-client.backend-api.url=http://localhost:8080
%dev.lockaway.master.key=testtest