feat(messaging): 브로커 중립 메시징 플랫폼 24개 leaf 추가

messaging-superpowers-package 설계서/계획서 기반 구현.
registry를 19 → 43 leaf로 확장하고 src/messaging 아래 24개 leaf를 등록.

- core-api: M1 publish/consume + M2 batch·delayed·pause-resume
- policy/transport-spi: 재시도 결정, DLQ orchestration, admission control, lifecycle
- kafka·rabbit(Stable): contiguous commit, confirm/return 상관, 배치, 보안 설정
- pulsar·nats(Experimental): 기본 비활성, live 인증 없음을 코드로 기록
- outbox/inbox/claim-check: 트랜잭션 결합, lease, 무결성 검증
- admin: plan → approve → execute를 타입으로 강제
- 문서 9종, infra compose 7종, JMH 벤치마크 3종

검증: 아키텍처 게이트 3종 통과, 24개 leaf 전부 check 통과,
messaging 테스트 604개 통과/0 실패.

미완: 계획서가 요구한 실 브로커 IT 40개 중 7개만 작성.
Rabbit 13 / Outbox 6 / Inbox 4 / NATS·Pulsar·Share 5 / testkit 2 /
starter·admin 3, 그리고 TLS·ACL 2개가 남음.
This commit is contained in:
DongHyeonka
2026-08-14 14:55:38 +09:00
parent 432130fd62
commit e23ed9486e
475 changed files with 39748 additions and 0 deletions
@@ -0,0 +1,141 @@
package dev.caskeleton.messaging.security;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* The exact broker permissions a deployment declares it needs.
*
* <p>Written down so the grant can be reviewed and diffed rather than discovered from a broker
* dump. The manifest is what the platform checks itself against at startup: a runtime that holds
* more than it declares is a finding, because the extra permission is the one nobody reasoned
* about.
*
* <p>Destructive permissions are named separately from ordinary ones. {@code DELETE_TOPIC} and
* {@code PURGE} are not "write, but more"; they destroy data an application can never restore, so
* an application runtime declaring one is rejected outright.
*
* @param principal the broker principal the grants belong to
* @param grants the declared permissions
*/
public record BrokerAclManifest(String principal, List<Grant> grants) {
/** One declared permission over one resource pattern. */
public record Grant(Operation operation, ResourceType resourceType, String pattern) {
public Grant {
Objects.requireNonNull(operation, "operation must not be null");
Objects.requireNonNull(resourceType, "resourceType must not be null");
if (pattern == null || pattern.isBlank()) {
throw new IllegalArgumentException("pattern must not be blank");
}
}
}
/** The broker resources a grant can cover. */
public enum ResourceType {
/** A topic, exchange, or stream. */
DESTINATION,
/** A consumer group or subscription. */
GROUP,
/** The broker or cluster itself. */
CLUSTER
}
/** The operations a grant can permit. */
public enum Operation {
/** Publish to a destination. */
WRITE(false),
/** Consume from a destination. */
READ(false),
/** Read metadata. */
DESCRIBE(false),
/** Create a destination or group. */
CREATE(false),
/** Change a destination's configuration. */
ALTER(true),
/** Remove a destination or group. */
DELETE(true),
/** Discard the messages in a destination. */
PURGE(true);
private final boolean destructive;
Operation(boolean destructive) {
this.destructive = destructive;
}
/**
* Reports whether this operation can destroy data.
*
* @return true for the destructive operations
*/
public boolean isDestructive() {
return destructive;
}
}
public BrokerAclManifest {
Objects.requireNonNull(grants, "grants must not be null");
if (principal == null || principal.isBlank()) {
throw new IllegalArgumentException("principal must not be blank");
}
grants = List.copyOf(grants);
}
/**
* Returns the declared destructive grants.
*
* @return the destructive grants
*/
public List<Grant> destructiveGrants() {
return grants.stream().filter(grant -> grant.operation().isDestructive()).toList();
}
/**
* Refuses a manifest that gives an application runtime destructive power.
*
* @throws MessagingConfigurationException when a destructive grant is declared
*/
public void requireApplicationRuntime() {
List<Grant> destructive = destructiveGrants();
if (!destructive.isEmpty()) {
throw new MessagingConfigurationException(
"APPLICATION_HOLDS_DESTRUCTIVE_GRANT",
"principal %s declares %s, which an application runtime must never hold"
.formatted(principal, destructive.stream().map(Grant::operation).toList()));
}
}
/**
* Reports the permissions the runtime holds but never declared.
*
* <p>Excess is the finding, not the shortfall: a missing grant fails loudly on first use, while
* an undeclared extra one sits unnoticed until it is abused.
*
* @param observed the grants the broker actually reports for this principal
* @return the observed grants that this manifest does not declare
*/
public Set<Grant> undeclared(Set<Grant> observed) {
Objects.requireNonNull(observed, "observed must not be null");
Set<Grant> extra = new LinkedHashSet<>(observed);
extra.removeAll(Set.copyOf(grants));
return Set.copyOf(extra);
}
/**
* Reports the declared permissions the broker does not actually grant.
*
* @param observed the grants the broker actually reports for this principal
* @return the declared grants that are missing
*/
public Set<Grant> missing(Set<Grant> observed) {
Objects.requireNonNull(observed, "observed must not be null");
Set<Grant> absent = new LinkedHashSet<>(grants);
absent.removeAll(observed);
return Set.copyOf(absent);
}
}
@@ -0,0 +1,78 @@
package dev.caskeleton.messaging.security;
/**
* A closed set of broker authentication mechanisms, referenced by credential id.
*
* <p>No variant carries a secret. The platform stores an identifier and resolves the material
* through a {@link CredentialProvider} at connect time, so a rotation is a provider concern and a
* heap dump or configuration print never yields a usable credential.
*/
public sealed interface BrokerCredentialProfile
permits BrokerCredentialProfile.SaslScram,
BrokerCredentialProfile.OAuth2,
BrokerCredentialProfile.MutualTls,
BrokerCredentialProfile.UsernamePassword,
BrokerCredentialProfile.Nkey {
/**
* Returns the credential identifier this profile resolves.
*
* @return the credential id
*/
String credentialId();
/**
* SASL/SCRAM authentication.
*
* @param credentialId the credential id
*/
record SaslScram(String credentialId) implements BrokerCredentialProfile {
public SaslScram {
CredentialIds.require(credentialId);
}
}
/**
* OAuth2 bearer authentication.
*
* @param credentialId the credential id
*/
record OAuth2(String credentialId) implements BrokerCredentialProfile {
public OAuth2 {
CredentialIds.require(credentialId);
}
}
/**
* Mutual TLS authentication.
*
* @param credentialId the credential id
*/
record MutualTls(String credentialId) implements BrokerCredentialProfile {
public MutualTls {
CredentialIds.require(credentialId);
}
}
/**
* Plain username and password authentication.
*
* @param credentialId the credential id
*/
record UsernamePassword(String credentialId) implements BrokerCredentialProfile {
public UsernamePassword {
CredentialIds.require(credentialId);
}
}
/**
* NATS NKey authentication.
*
* @param credentialId the credential id
*/
record Nkey(String credentialId) implements BrokerCredentialProfile {
public Nkey {
CredentialIds.require(credentialId);
}
}
}
@@ -0,0 +1,41 @@
package dev.caskeleton.messaging.security;
import java.util.Objects;
import java.util.Optional;
/**
* The security posture for one broker connection.
*
* <p>Producer, consumer, and admin credentials are separate fields rather than one connection
* credential. That separation is what makes "an application cannot purge a topic" enforceable: the
* runtime never holds admin material, so a compromised handler has nothing to escalate with.
*
* @param broker the broker name
* @param production whether this profile is used in production
* @param tlsEnabled whether transport encryption is on
* @param hostnameVerification whether the server certificate hostname is verified
* @param producer the producer credential
* @param consumer the consumer credential
* @param admin the admin credential, absent in an application runtime
* @param access the destination access policy
*/
public record BrokerSecurityProfile(
String broker,
boolean production,
boolean tlsEnabled,
boolean hostnameVerification,
BrokerCredentialProfile producer,
BrokerCredentialProfile consumer,
Optional<BrokerCredentialProfile> admin,
DestinationAccessPolicy access) {
public BrokerSecurityProfile {
Objects.requireNonNull(producer, "producer credential must not be null");
Objects.requireNonNull(consumer, "consumer credential must not be null");
Objects.requireNonNull(admin, "admin credential must not be null");
Objects.requireNonNull(access, "access policy must not be null");
if (broker == null || broker.isBlank()) {
throw new IllegalArgumentException("broker must not be blank");
}
}
}
@@ -0,0 +1,98 @@
package dev.caskeleton.messaging.security;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/**
* The transport-encryption rules a broker connection must satisfy before it is opened.
*
* <p>Checked at startup, not per connection. A TLS misconfiguration that surfaces on the first
* publish has already shipped; one that refuses to start is caught in the deployment that
* introduced it.
*
* <p>Disabling hostname verification is treated as a separate, worse failure than disabling TLS.
* Plaintext is at least obviously insecure, whereas TLS without hostname verification looks
* encrypted in every dashboard while accepting any certificate a man in the middle presents.
*/
public final class BrokerTlsPolicy {
/** Protocol versions with known practical attacks. */
private static final Set<String> FORBIDDEN_PROTOCOLS =
Set.of("SSLv2", "SSLv3", "TLSv1", "TLSv1.1");
/** The minimum acceptable protocol version. */
public static final String MINIMUM_PROTOCOL = "TLSv1.2";
private final boolean allowPlaintextOutsideProduction;
/** Creates a policy that permits plaintext only outside production. */
public BrokerTlsPolicy() {
this(true);
}
/**
* Creates a policy.
*
* @param allowPlaintextOutsideProduction whether non-production profiles may run without TLS
*/
public BrokerTlsPolicy(boolean allowPlaintextOutsideProduction) {
this.allowPlaintextOutsideProduction = allowPlaintextOutsideProduction;
}
/**
* Validates one broker's transport security.
*
* @param profile the broker security profile
* @param enabledProtocols the protocol versions the connection would negotiate
* @throws MessagingConfigurationException when the posture is not acceptable
*/
public void validate(BrokerSecurityProfile profile, List<String> enabledProtocols) {
Objects.requireNonNull(profile, "profile must not be null");
Objects.requireNonNull(enabledProtocols, "enabledProtocols must not be null");
if (!profile.tlsEnabled()) {
if (profile.production() || !allowPlaintextOutsideProduction) {
throw new MessagingConfigurationException(
"TLS_REQUIRED",
"broker %s runs in production and must not use a plaintext connection"
.formatted(profile.broker()));
}
return;
}
if (!profile.hostnameVerification()) {
throw new MessagingConfigurationException(
"HOSTNAME_VERIFICATION_REQUIRED",
"broker %s enables TLS without hostname verification, which accepts any certificate"
.formatted(profile.broker()));
}
List<String> forbidden =
enabledProtocols.stream().filter(FORBIDDEN_PROTOCOLS::contains).toList();
if (!forbidden.isEmpty()) {
throw new MessagingConfigurationException(
"TLS_PROTOCOL_TOO_OLD",
"broker %s enables %s; the minimum is %s"
.formatted(profile.broker(), forbidden, MINIMUM_PROTOCOL));
}
if (enabledProtocols.isEmpty()) {
throw new MessagingConfigurationException(
"TLS_PROTOCOL_UNSPECIFIED",
"broker %s enables TLS without naming a protocol version, so the negotiated version "
.formatted(profile.broker())
+ "depends on the JVM default rather than on this policy");
}
}
/**
* Reports whether a protocol version is acceptable.
*
* @param protocol the protocol version
* @return true when the version may be negotiated
*/
public static boolean isAcceptable(String protocol) {
return protocol != null && !FORBIDDEN_PROTOCOLS.contains(protocol);
}
}
@@ -0,0 +1,37 @@
package dev.caskeleton.messaging.security;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
/**
* Validation shared by every credential profile variant.
*
* <p>The bounded slug pattern is not cosmetic. Credential ids reach log lines and metric tags, so
* an unbounded id is a cardinality problem, and an id that looks like a secret is a leak. The
* heuristic check rejects the most common accident: pasting the secret itself where the reference
* belongs.
*/
final class CredentialIds {
private static final Pattern VALID = Pattern.compile("[a-z0-9][a-z0-9._-]{1,63}");
private static final Set<String> SECRET_LOOKING_PREFIXES =
Set.of("bearer ", "basic ", "sk-", "-----begin", "eyj");
private CredentialIds() {}
static void require(String credentialId) {
if (credentialId == null || !VALID.matcher(credentialId).matches()) {
throw new IllegalArgumentException(
"credentialId must match [a-z0-9][a-z0-9._-]{1,63}: " + credentialId);
}
String lowered = credentialId.toLowerCase(Locale.ROOT);
for (String prefix : SECRET_LOOKING_PREFIXES) {
if (lowered.startsWith(prefix)) {
throw new IllegalArgumentException(
"credentialId looks like a secret value rather than a reference");
}
}
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.messaging.security;
import java.time.Instant;
import java.util.Optional;
/**
* Resolves credential material from an identifier.
*
* <p>Implementations are expected to fetch late and cache briefly. Returning an expiry lets the
* runtime rotate a generation before the broker starts refusing connections, rather than after.
*/
public interface CredentialProvider {
/**
* Resolves the secret for a credential id.
*
* @param credentialId the identifier
* @return the resolved material
*/
char[] resolve(String credentialId);
/**
* Returns when the credential stops being valid, when that is known.
*
* @param credentialId the identifier
* @return the expiry instant when known
*/
Optional<Instant> expiresAt(String credentialId);
}
@@ -0,0 +1,54 @@
package dev.caskeleton.messaging.security;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
/**
* When a credential must be replaced, and how much slack remains.
*
* <p>Rotation is scheduled ahead of expiry rather than triggered by an authentication failure. By
* the time the broker starts refusing connections, in-flight publishes are already failing and the
* consumer has already stopped: rotating early turns an outage into a generation swap nobody
* notices.
*
* @param credentialId the credential to rotate
* @param expiresAt when the credential stops being valid, when known
* @param rotateBefore how far ahead of expiry to rotate
*/
public record CredentialRotationPlan(
String credentialId, Optional<Instant> expiresAt, Duration rotateBefore) {
public CredentialRotationPlan {
Objects.requireNonNull(expiresAt, "expiresAt must not be null");
Objects.requireNonNull(rotateBefore, "rotateBefore must not be null");
if (credentialId == null || credentialId.isBlank()) {
throw new IllegalArgumentException("credentialId must not be blank");
}
if (rotateBefore.isNegative()) {
throw new IllegalArgumentException("rotateBefore must not be negative");
}
}
/**
* Reports whether the credential should be rotated now.
*
* @param now the current instant
* @return true once the rotation window has opened
*/
public boolean isDue(Instant now) {
Objects.requireNonNull(now, "now must not be null");
return expiresAt.map(expiry -> !now.isBefore(expiry.minus(rotateBefore))).orElse(false);
}
/**
* Reports whether the credential has already expired.
*
* @param now the current instant
* @return true once expired
*/
public boolean isExpired(Instant now) {
return expiresAt.map(expiry -> !now.isBefore(expiry)).orElse(false);
}
}
@@ -0,0 +1,143 @@
package dev.caskeleton.messaging.security;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
/**
* One credential's live state: when it was resolved, when it expires, and whether it is due for
* rotation.
*
* <p>Holds the material in a {@code char[]} that {@link #clear()} overwrites. A {@code String}
* cannot be erased — it stays in the constant pool and in every heap dump taken until the next GC
* decides otherwise — so the type of the field is itself part of the control.
*
* <p>Rotation is driven from the expiry, ahead of it. Waiting for the broker to start refusing
* connections turns a scheduled, invisible rotation into an outage.
*/
public final class CredentialRuntime {
/** How far ahead of expiry a credential is considered due for rotation. */
public static final Duration DEFAULT_ROTATION_LEAD = Duration.ofMinutes(30);
private final String credentialId;
private final Instant resolvedAt;
private final Optional<Instant> expiresAt;
private final Duration rotationLead;
private char[] material;
/**
* Creates a runtime entry.
*
* @param credentialId the credential reference
* @param material the resolved secret, taken by reference and cleared by {@link #clear()}
* @param resolvedAt when the material was resolved
* @param expiresAt when it stops being valid, when known
* @param rotationLead how far ahead of expiry rotation should begin
*/
public CredentialRuntime(
String credentialId,
char[] material,
Instant resolvedAt,
Optional<Instant> expiresAt,
Duration rotationLead) {
CredentialIds.require(credentialId);
Objects.requireNonNull(material, "material must not be null");
Objects.requireNonNull(resolvedAt, "resolvedAt must not be null");
Objects.requireNonNull(expiresAt, "expiresAt must not be null");
Objects.requireNonNull(rotationLead, "rotationLead must not be null");
if (rotationLead.isNegative()) {
throw new IllegalArgumentException("rotationLead must not be negative");
}
if (material.length == 0) {
throw new IllegalArgumentException("credential material must not be empty");
}
this.credentialId = credentialId;
this.material = material;
this.resolvedAt = resolvedAt;
this.expiresAt = expiresAt;
this.rotationLead = rotationLead;
}
/**
* Returns the credential reference.
*
* @return the credential id
*/
public String credentialId() {
return credentialId;
}
/**
* Returns a copy of the material.
*
* <p>A copy, so a caller that clears its own array cannot blind every other holder.
*
* @return the secret material
* @throws IllegalStateException once {@link #clear()} has run
*/
public char[] material() {
if (material.length == 0) {
throw new IllegalStateException("credential " + credentialId + " has already been cleared");
}
return material.clone();
}
/**
* Returns when the material was resolved.
*
* @return the resolution instant
*/
public Instant resolvedAt() {
return resolvedAt;
}
/**
* Returns the expiry when it is known.
*
* @return the expiry instant
*/
public Optional<Instant> expiresAt() {
return expiresAt;
}
/**
* Reports whether the credential has expired.
*
* @param now the current instant
* @return true when the expiry is known and has passed
*/
public boolean isExpired(Instant now) {
Objects.requireNonNull(now, "now must not be null");
return expiresAt.map(expiry -> !now.isBefore(expiry)).orElse(false);
}
/**
* Reports whether rotation should begin.
*
* @param now the current instant
* @return true when the credential is inside its rotation lead or already expired
*/
public boolean isDueForRotation(Instant now) {
Objects.requireNonNull(now, "now must not be null");
return expiresAt.map(expiry -> !now.isBefore(expiry.minus(rotationLead))).orElse(false);
}
/** Overwrites the material in place. */
public void clear() {
Arrays.fill(material, '\0');
material = new char[0];
}
/**
* Returns a representation that names the credential without revealing it.
*
* @return a safe description
*/
@Override
public String toString() {
return "CredentialRuntime[credentialId=%s, expiresAt=%s]".formatted(credentialId, expiresAt);
}
}
@@ -0,0 +1,122 @@
package dev.caskeleton.messaging.security;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* Resolves credentials late, caches them briefly, and clears the old material on rotation.
*
* <p>Late resolution is what makes rotation possible at all. A credential read once at startup and
* held for the process lifetime cannot be rotated without a restart, which is why rotation gets
* skipped in practice.
*
* <p>The previous generation is cleared as soon as the new one is installed. Keeping it "just in
* case" is how a revoked credential stays live in memory long after the store says it is gone.
*/
public final class CredentialRuntimeRegistry {
private final CredentialProvider provider;
private final Duration rotationLead;
private final Map<String, CredentialRuntime> resolved = new ConcurrentHashMap<>();
/**
* Creates a registry with the default rotation lead.
*
* @param provider the credential source
*/
public CredentialRuntimeRegistry(CredentialProvider provider) {
this(provider, CredentialRuntime.DEFAULT_ROTATION_LEAD);
}
/**
* Creates a registry.
*
* @param provider the credential source
* @param rotationLead how far ahead of expiry rotation begins
*/
public CredentialRuntimeRegistry(CredentialProvider provider, Duration rotationLead) {
this.provider = Objects.requireNonNull(provider, "provider must not be null");
this.rotationLead = Objects.requireNonNull(rotationLead, "rotationLead must not be null");
}
/**
* Returns the live credential, resolving or rotating it as needed.
*
* @param credentialId the credential reference
* @param now the current instant
* @return the live credential
*/
public CredentialRuntime resolve(String credentialId, Instant now) {
CredentialIds.require(credentialId);
Objects.requireNonNull(now, "now must not be null");
CredentialRuntime current = resolved.get(credentialId);
if (current != null && !current.isDueForRotation(now)) {
return current;
}
CredentialRuntime replacement = fetch(credentialId, now);
resolved.put(credentialId, replacement);
if (current != null) {
// Clear only after the replacement is installed, so a concurrent reader never observes a
// window with no usable credential.
current.clear();
}
return replacement;
}
/**
* Returns the credentials that are inside their rotation lead.
*
* @param now the current instant
* @return the credential ids due for rotation
*/
public List<String> dueForRotation(Instant now) {
Objects.requireNonNull(now, "now must not be null");
return resolved.entrySet().stream()
.filter(entry -> entry.getValue().isDueForRotation(now))
.map(Map.Entry::getKey)
.sorted()
.toList();
}
/**
* Returns the credentials that have already expired.
*
* @param now the current instant
* @return the expired credential ids
*/
public List<String> expired(Instant now) {
Objects.requireNonNull(now, "now must not be null");
return resolved.entrySet().stream()
.filter(entry -> entry.getValue().isExpired(now))
.map(Map.Entry::getKey)
.sorted()
.toList();
}
/**
* Returns how many credentials are currently held.
*
* @return the cached credential count
*/
public int size() {
return resolved.size();
}
/** Clears every held credential, for shutdown. */
public void clearAll() {
resolved.values().forEach(CredentialRuntime::clear);
resolved.clear();
}
private CredentialRuntime fetch(String credentialId, Instant now) {
char[] material = provider.resolve(credentialId);
Optional<Instant> expiresAt = provider.expiresAt(credentialId);
return new CredentialRuntime(credentialId, material, now, expiresAt, rotationLead);
}
}
@@ -0,0 +1,70 @@
package dev.caskeleton.messaging.security;
import dev.caskeleton.messaging.api.destination.DestinationName;
import java.util.Objects;
import java.util.Set;
/**
* Which destinations each role may touch.
*
* <p>The platform checks this before the broker does. Relying only on broker ACLs means an
* accidental publish surfaces as a generic authorization error at runtime, in the adapter, with no
* record of which application module attempted it.
*
* @param publishable destinations the producer credential may publish to
* @param consumable destinations the consumer credential may consume
* @param administrable destinations the admin credential may operate on
*/
public record DestinationAccessPolicy(
Set<DestinationName> publishable,
Set<DestinationName> consumable,
Set<DestinationName> administrable) {
public DestinationAccessPolicy {
Objects.requireNonNull(publishable, "publishable must not be null");
Objects.requireNonNull(consumable, "consumable must not be null");
Objects.requireNonNull(administrable, "administrable must not be null");
publishable = Set.copyOf(publishable);
consumable = Set.copyOf(consumable);
administrable = Set.copyOf(administrable);
}
/**
* Returns a policy that permits nothing.
*
* @return the empty policy
*/
public static DestinationAccessPolicy denyAll() {
return new DestinationAccessPolicy(Set.of(), Set.of(), Set.of());
}
/**
* Reports whether publishing is permitted.
*
* @param destination the logical destination
* @return true when permitted
*/
public boolean mayPublish(DestinationName destination) {
return publishable.contains(destination);
}
/**
* Reports whether consuming is permitted.
*
* @param destination the logical destination
* @return true when permitted
*/
public boolean mayConsume(DestinationName destination) {
return consumable.contains(destination);
}
/**
* Reports whether administration is permitted.
*
* @param destination the logical destination
* @return true when permitted
*/
public boolean mayAdminister(DestinationName destination) {
return administrable.contains(destination);
}
}
@@ -0,0 +1,65 @@
package dev.caskeleton.messaging.security;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.error.MessageAuthorizationException;
import java.util.Objects;
/**
* Checks a destination operation against the platform's own access policy.
*
* <p>Runs before the broker's ACL, and the failure it raises names the logical destination and the
* role. A broker ACL denial arrives as a connection-level error with no application context, which
* makes "which module tried to publish where" an investigation rather than a log line.
*/
public final class DestinationAccessValidator {
private final DestinationAccessPolicy policy;
/**
* Creates a validator over an access policy.
*
* @param policy the destination access policy
*/
public DestinationAccessValidator(DestinationAccessPolicy policy) {
this.policy = Objects.requireNonNull(policy, "policy must not be null");
}
/**
* Requires publish permission.
*
* @param destination the logical destination
*/
public void requirePublish(DestinationName destination) {
if (!policy.mayPublish(destination)) {
throw new MessageAuthorizationException(
"DESTINATION_PUBLISH_DENIED",
"the producer credential may not publish to " + destination.value());
}
}
/**
* Requires consume permission.
*
* @param destination the logical destination
*/
public void requireConsume(DestinationName destination) {
if (!policy.mayConsume(destination)) {
throw new MessageAuthorizationException(
"DESTINATION_CONSUME_DENIED",
"the consumer credential may not consume " + destination.value());
}
}
/**
* Requires administer permission.
*
* @param destination the logical destination
*/
public void requireAdminister(DestinationName destination) {
if (!policy.mayAdminister(destination)) {
throw new MessageAuthorizationException(
"DESTINATION_ADMIN_DENIED",
"the admin credential may not administer " + destination.value());
}
}
}
@@ -0,0 +1,50 @@
package dev.caskeleton.messaging.security;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
/**
* Startup validation of a broker's security posture.
*
* <p>These checks are boot failures rather than warnings. An unencrypted production broker
* connection or a shared producer/admin credential is not a degraded mode the platform can run in
* safely; both are the kind of misconfiguration that stays invisible until it is exploited.
*/
public final class MessageSecurityValidator {
/**
* Validates one broker security profile.
*
* @param profile the profile to validate
* @throws IllegalArgumentException when the posture is unsafe
*/
public void validate(BrokerSecurityProfile profile) {
Objects.requireNonNull(profile, "profile must not be null");
if (profile.production() && !profile.tlsEnabled()) {
throw new IllegalArgumentException(
"a production broker connection requires TLS: " + profile.broker());
}
if (profile.production() && !profile.hostnameVerification()) {
throw new IllegalArgumentException(
"a production broker connection requires TLS hostname verification: " + profile.broker());
}
Set<String> credentialIds = new LinkedHashSet<>();
credentialIds.add(profile.producer().credentialId());
if (!credentialIds.add(profile.consumer().credentialId())) {
throw new IllegalArgumentException(
"producer and consumer must use separate credentials: " + profile.broker());
}
if (profile.admin().isPresent()
&& !credentialIds.add(profile.admin().orElseThrow().credentialId())) {
throw new IllegalArgumentException(
"the admin credential must be separate from producer and consumer: " + profile.broker());
}
if (profile.production() && profile.admin().isPresent()) {
throw new IllegalArgumentException(
"an application runtime must not hold an admin credential: " + profile.broker());
}
}
}
@@ -0,0 +1,218 @@
package dev.caskeleton.messaging.security;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
class CredentialRuntimeRegistryTest {
private static final String CREDENTIAL_ID = "kafka.producer";
private static final Instant NOW = Instant.parse("2026-08-10T09:00:00Z");
/** Hands out a fresh generation on each resolve so rotation is observable. */
private static final class CountingProvider implements CredentialProvider {
private final AtomicInteger generation = new AtomicInteger();
private final Optional<Instant> expiry;
private CountingProvider(Optional<Instant> expiry) {
this.expiry = expiry;
}
@Override
public char[] resolve(String credentialId) {
return ("generation-" + generation.incrementAndGet()).toCharArray();
}
@Override
public Optional<Instant> expiresAt(String credentialId) {
return expiry;
}
int resolutions() {
return generation.get();
}
}
@Test
void aCredentialIsResolvedOnceAndReusedUntilItIsDue() {
CountingProvider provider = new CountingProvider(Optional.of(NOW.plus(Duration.ofHours(4))));
CredentialRuntimeRegistry registry = new CredentialRuntimeRegistry(provider);
registry.resolve(CREDENTIAL_ID, NOW);
registry.resolve(CREDENTIAL_ID, NOW.plus(Duration.ofMinutes(5)));
assertThat(provider.resolutions()).isEqualTo(1);
}
@Test
void rotationHappensBeforeExpiryNotAfterIt() {
Instant expiry = NOW.plus(Duration.ofMinutes(20));
CountingProvider provider = new CountingProvider(Optional.of(expiry));
CredentialRuntimeRegistry registry = new CredentialRuntimeRegistry(provider);
registry.resolve(CREDENTIAL_ID, NOW);
registry.resolve(CREDENTIAL_ID, NOW.plus(Duration.ofMinutes(1)));
assertThat(provider.resolutions())
.as("waiting for the broker to refuse the connection turns rotation into an outage")
.isEqualTo(2);
}
@Test
void theSupersededGenerationIsWipedNotJustDropped() {
Instant expiry = NOW.plus(Duration.ofMinutes(20));
CredentialRuntimeRegistry registry =
new CredentialRuntimeRegistry(new CountingProvider(Optional.of(expiry)));
CredentialRuntime first = registry.resolve(CREDENTIAL_ID, NOW);
registry.resolve(CREDENTIAL_ID, NOW.plus(Duration.ofMinutes(1)));
assertThatThrownBy(first::material)
.as("a revoked credential must not stay readable in memory")
.isInstanceOf(IllegalStateException.class);
}
@Test
void aCredentialWithNoKnownExpiryIsNeverRotatedOnATimer() {
CountingProvider provider = new CountingProvider(Optional.empty());
CredentialRuntimeRegistry registry = new CredentialRuntimeRegistry(provider);
registry.resolve(CREDENTIAL_ID, NOW);
registry.resolve(CREDENTIAL_ID, NOW.plus(Duration.ofDays(30)));
assertThat(provider.resolutions()).isEqualTo(1);
}
@Test
void materialIsHandedOutAsACopySoOneHolderCannotBlindTheOthers() {
CredentialRuntimeRegistry registry =
new CredentialRuntimeRegistry(new CountingProvider(Optional.empty()));
CredentialRuntime credential = registry.resolve(CREDENTIAL_ID, NOW);
char[] borrowed = credential.material();
java.util.Arrays.fill(borrowed, 'x');
assertThat(credential.material()).containsExactly("generation-1".toCharArray());
}
@Test
void theDescriptionNamesTheCredentialWithoutRevealingIt() {
CredentialRuntimeRegistry registry =
new CredentialRuntimeRegistry(new CountingProvider(Optional.empty()));
String described = registry.resolve(CREDENTIAL_ID, NOW).toString();
assertThat(described).contains(CREDENTIAL_ID).doesNotContain("generation-1");
}
@Test
void expiredCredentialsAreReportedForAlerting() {
Instant expiry = NOW.plus(Duration.ofMinutes(5));
CredentialRuntimeRegistry registry =
new CredentialRuntimeRegistry(
new CountingProvider(Optional.of(expiry)), Duration.ofMinutes(1));
registry.resolve(CREDENTIAL_ID, NOW);
assertThat(registry.expired(NOW.plus(Duration.ofMinutes(10)))).containsExactly(CREDENTIAL_ID);
}
@Test
void clearingTheRegistryWipesEverythingItHeld() {
CredentialRuntimeRegistry registry =
new CredentialRuntimeRegistry(new CountingProvider(Optional.empty()));
CredentialRuntime credential = registry.resolve(CREDENTIAL_ID, NOW);
registry.clearAll();
assertThat(registry.size()).isZero();
assertThatThrownBy(credential::material).isInstanceOf(IllegalStateException.class);
}
@Test
void aProductionBrokerCannotRunWithoutTls() {
assertThatThrownBy(
() -> new BrokerTlsPolicy().validate(profile(true, false, true), List.of("TLSv1.3")))
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("plaintext");
}
@Test
void tlsWithoutHostnameVerificationIsRefusedEvenThoughItLooksEncrypted() {
assertThatThrownBy(
() -> new BrokerTlsPolicy().validate(profile(true, true, false), List.of("TLSv1.3")))
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("hostname verification");
}
@Test
void anObsoleteProtocolVersionIsRefused() {
assertThatThrownBy(
() ->
new BrokerTlsPolicy()
.validate(profile(true, true, true), List.of("TLSv1.3", "TLSv1.1")))
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("TLSv1.1");
}
@Test
void anApplicationRuntimeMayNotHoldADestructiveGrant() {
BrokerAclManifest manifest =
new BrokerAclManifest(
"orders-api",
List.of(
new BrokerAclManifest.Grant(
BrokerAclManifest.Operation.WRITE,
BrokerAclManifest.ResourceType.DESTINATION,
"orders.*"),
new BrokerAclManifest.Grant(
BrokerAclManifest.Operation.DELETE,
BrokerAclManifest.ResourceType.DESTINATION,
"orders.*")));
assertThatThrownBy(manifest::requireApplicationRuntime)
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("DELETE");
}
@Test
void aGrantTheBrokerHoldsButNobodyDeclaredIsTheFinding() {
BrokerAclManifest.Grant declared =
new BrokerAclManifest.Grant(
BrokerAclManifest.Operation.WRITE,
BrokerAclManifest.ResourceType.DESTINATION,
"orders.*");
BrokerAclManifest.Grant extra =
new BrokerAclManifest.Grant(
BrokerAclManifest.Operation.DELETE,
BrokerAclManifest.ResourceType.DESTINATION,
"orders.*");
BrokerAclManifest manifest = new BrokerAclManifest("orders-api", List.of(declared));
assertThat(manifest.undeclared(Set.of(declared, extra)))
.as("a missing grant fails loudly on first use; an extra one waits to be abused")
.containsExactly(extra);
}
private static BrokerSecurityProfile profile(
boolean production, boolean tls, boolean hostnameVerification) {
BrokerCredentialProfile credential = new BrokerCredentialProfile.SaslScram("kafka.producer");
return new BrokerSecurityProfile(
"kafka",
production,
tls,
hostnameVerification,
credential,
credential,
Optional.empty(),
DestinationAccessPolicy.denyAll());
}
}
@@ -0,0 +1,148 @@
package dev.caskeleton.messaging.security;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.destination.DestinationName;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.Test;
class MessageSecurityValidatorTest {
private final MessageSecurityValidator validator = new MessageSecurityValidator();
@Test
void productionBrokerWithoutTlsIsRejected() {
BrokerSecurityProfile profile = BrokerSecurityProfileFixtures.productionWithoutTls();
assertThatThrownBy(() -> validator.validate(profile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("TLS");
}
@Test
void productionBrokerWithoutHostnameVerificationIsRejected() {
BrokerSecurityProfile profile = BrokerSecurityProfileFixtures.productionWithoutHostnameCheck();
assertThatThrownBy(() -> validator.validate(profile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("hostname");
}
@Test
void producerAndConsumerMustUseSeparateCredentials() {
BrokerSecurityProfile profile = BrokerSecurityProfileFixtures.sharedProducerConsumer();
assertThatThrownBy(() -> validator.validate(profile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("separate credentials");
}
@Test
void anApplicationRuntimeMustNotHoldAnAdminCredential() {
BrokerSecurityProfile profile = BrokerSecurityProfileFixtures.productionWithAdmin();
assertThatThrownBy(() -> validator.validate(profile))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("admin credential");
}
@Test
void aCredentialIdThatLooksLikeASecretIsRejected() {
assertThatThrownBy(() -> new BrokerCredentialProfile.OAuth2("bearer abcdef123456"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void accessPolicySeparatesPublishConsumeAndAdminister() {
DestinationName orders = new DestinationName("order-events");
DestinationAccessPolicy policy =
new DestinationAccessPolicy(Set.of(orders), Set.of(), Set.of());
assertThatCode(
() -> {
if (!policy.mayPublish(orders)
|| policy.mayConsume(orders)
|| policy.mayAdminister(orders)) {
throw new IllegalStateException("access policy roles are not separated");
}
})
.doesNotThrowAnyException();
}
@Test
void aCoherentProductionProfileValidates() {
assertThatCode(() -> validator.validate(BrokerSecurityProfileFixtures.production()))
.doesNotThrowAnyException();
}
}
/** Builds broker security profiles for validator tests. */
final class BrokerSecurityProfileFixtures {
private BrokerSecurityProfileFixtures() {}
static BrokerSecurityProfile production() {
return new BrokerSecurityProfile(
"kafka-primary",
true,
true,
true,
new BrokerCredentialProfile.SaslScram("kafka-producer"),
new BrokerCredentialProfile.SaslScram("kafka-consumer"),
Optional.empty(),
DestinationAccessPolicy.denyAll());
}
static BrokerSecurityProfile productionWithoutTls() {
BrokerSecurityProfile base = production();
return new BrokerSecurityProfile(
base.broker(),
true,
false,
true,
base.producer(),
base.consumer(),
base.admin(),
base.access());
}
static BrokerSecurityProfile productionWithoutHostnameCheck() {
BrokerSecurityProfile base = production();
return new BrokerSecurityProfile(
base.broker(),
true,
true,
false,
base.producer(),
base.consumer(),
base.admin(),
base.access());
}
static BrokerSecurityProfile sharedProducerConsumer() {
return new BrokerSecurityProfile(
"kafka-primary",
false,
true,
true,
new BrokerCredentialProfile.SaslScram("kafka-app"),
new BrokerCredentialProfile.SaslScram("kafka-app"),
Optional.empty(),
DestinationAccessPolicy.denyAll());
}
static BrokerSecurityProfile productionWithAdmin() {
BrokerSecurityProfile base = production();
return new BrokerSecurityProfile(
base.broker(),
true,
true,
true,
base.producer(),
base.consumer(),
Optional.of(new BrokerCredentialProfile.SaslScram("kafka-admin")),
base.access());
}
}