feat: jpa, messaging, notification, mongo, graphql 어댑터터 구현체 추가

This commit is contained in:
DongHyeonka
2026-08-15 13:01:58 +09:00
parent e23ed9486e
commit f56dd3e4eb
174 changed files with 10338 additions and 1274 deletions
@@ -0,0 +1,93 @@
package dev.caskeleton.messaging.admin;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
/**
* Where a destructive operation records that it started, how far it got, and how it ended.
*
* <p>The implementation this replaced was a {@code ConcurrentHashMap} registered by the starter as
* the default. Two consequences followed, and both are worse than having no store at all because
* the map made the platform look protected. A restart forgot every claim, so the same approval
* could be executed again by the same process. And two replicas each had their own map, so both
* could claim the same approval at the same moment and each believe it was the only one.
*
* <p>Implementations must therefore be shared and durable, must enforce uniqueness on {@code
* (approvalTicket, planDigest)}, and must hand out leases with a monotonic fencing token so a
* process that stalled past its lease cannot write over the replica that took over from it.
*/
public interface AdminOperationJournal {
/**
* Claims an operation, or resumes the previous attempt at it.
*
* @param approvalTicket the approval authorising the operation
* @param planDigest the exact plan
* @param operationId this execution's identity
* @param leaseOwner the runtime claiming it
* @param leaseDuration how long the lease holds before another runtime may take over
* @param now the current instant
* @return the lease, carrying the point to resume from
* @throws dev.caskeleton.messaging.api.error.MessageAuthorizationException when the operation
* already completed, or another runtime holds a live lease on it
*/
AdminOperationLease begin(
String approvalTicket,
PlanDigest planDigest,
String operationId,
String leaseOwner,
Duration leaseDuration,
Instant now);
/**
* Records durable progress and extends the lease.
*
* @param lease the lease held
* @param itemsCompleted how many items are now durably done
* @param leaseDuration how much longer to hold the lease
* @param now the current instant
* @throws dev.caskeleton.messaging.api.error.MessageAuthorizationException when the lease has
* been taken over by a newer token
*/
void checkpoint(
AdminOperationLease lease, int itemsCompleted, Duration leaseDuration, Instant now);
/**
* Marks the operation finished. The approval is spent.
*
* @param lease the lease held
* @param itemsCompleted the final count
* @param now the current instant
*/
void complete(AdminOperationLease lease, int itemsCompleted, Instant now);
/**
* Marks the operation failed at its current checkpoint, leaving it resumable.
*
* @param lease the lease held
* @param itemsCompleted how many items are durably done
* @param failureCode a sanitised, bounded reason
* @param now the current instant
*/
void fail(AdminOperationLease lease, int itemsCompleted, String failureCode, Instant now);
/**
* Reads the journal entry for an operation.
*
* @param approvalTicket the approval
* @param planDigest the plan
* @return the record, when the operation has been journalled
*/
Optional<AdminOperationRecord> find(String approvalTicket, PlanDigest planDigest);
/**
* Whether this implementation survives a restart and is shared between replicas.
*
* <p>Declared rather than inferred so the starter can refuse to run a production profile on an
* in-memory journal instead of discovering the gap during an incident.
*
* @return true when the journal is durable and shared
*/
boolean isDurable();
}
@@ -0,0 +1,55 @@
package dev.caskeleton.messaging.admin;
import java.util.Objects;
/**
* The right to execute one journalled operation, and the point to resume it from.
*
* <p>{@code resumeFrom} is the whole reason a lease is handed out rather than a boolean. A retry
* after a crash is not a new execution of the approval — it is the same operation continuing, and
* treating it as new is what republishes the items the first attempt already moved.
*
* @param approvalTicket the approval being executed
* @param planDigest the plan being executed
* @param operationId this execution's identity
* @param leaseOwner the runtime holding the lease
* @param leaseToken the fencing token; a write from an older token must be refused
* @param resumeFrom how many items the previous attempt durably completed
*/
public record AdminOperationLease(
String approvalTicket,
PlanDigest planDigest,
String operationId,
String leaseOwner,
long leaseToken,
int resumeFrom) {
/** Validates the lease. */
public AdminOperationLease {
Objects.requireNonNull(planDigest, "planDigest must not be null");
if (approvalTicket == null || approvalTicket.isBlank()) {
throw new IllegalArgumentException("approvalTicket must not be blank");
}
if (operationId == null || operationId.isBlank()) {
throw new IllegalArgumentException("operationId must not be blank");
}
if (leaseOwner == null || leaseOwner.isBlank()) {
throw new IllegalArgumentException("leaseOwner must not be blank");
}
if (leaseToken < 1) {
throw new IllegalArgumentException("a lease token starts at one");
}
if (resumeFrom < 0) {
throw new IllegalArgumentException("resumeFrom must not be negative");
}
}
/**
* Reports whether this lease continues an earlier attempt.
*
* @return true when items were already completed
*/
public boolean isResumption() {
return resumeFrom > 0;
}
}
@@ -0,0 +1,63 @@
package dev.caskeleton.messaging.admin;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
/**
* One row of the destructive-operation journal.
*
* <p>Keyed by {@code (approvalTicket, planDigest)} rather than by the ticket alone, because the
* ticket alone cannot distinguish "this approval already ran" from "this approval is being reused
* for a different plan" — and those need opposite answers.
*
* @param approvalTicket the approval that authorised the operation
* @param planDigest the exact plan that was authorised
* @param operationId the caller-side identity of this execution
* @param state where the operation stands
* @param itemsCompleted how many items are durably done
* @param leaseOwner which runtime currently holds the lease
* @param leaseToken the fencing token, incremented on every takeover
* @param leaseExpiresAt when another runtime may take the lease over
* @param startedAt when the operation first began
* @param finishedAt when it reached a terminal state
* @param failureCode the sanitised reason it failed, when it did
*/
public record AdminOperationRecord(
String approvalTicket,
PlanDigest planDigest,
String operationId,
AdminOperationState state,
int itemsCompleted,
String leaseOwner,
long leaseToken,
Instant leaseExpiresAt,
Instant startedAt,
Optional<Instant> finishedAt,
Optional<String> failureCode) {
/** Validates the record. */
public AdminOperationRecord {
Objects.requireNonNull(planDigest, "planDigest must not be null");
Objects.requireNonNull(state, "state must not be null");
Objects.requireNonNull(leaseExpiresAt, "leaseExpiresAt must not be null");
Objects.requireNonNull(startedAt, "startedAt must not be null");
Objects.requireNonNull(finishedAt, "finishedAt must not be null");
Objects.requireNonNull(failureCode, "failureCode must not be null");
if (approvalTicket == null || approvalTicket.isBlank()) {
throw new IllegalArgumentException("approvalTicket must not be blank");
}
if (operationId == null || operationId.isBlank()) {
throw new IllegalArgumentException("operationId must not be blank");
}
if (leaseOwner == null || leaseOwner.isBlank()) {
throw new IllegalArgumentException("leaseOwner must not be blank");
}
if (itemsCompleted < 0) {
throw new IllegalArgumentException("itemsCompleted must not be negative");
}
if (leaseToken < 1) {
throw new IllegalArgumentException("a lease token starts at one");
}
}
}
@@ -0,0 +1,21 @@
package dev.caskeleton.messaging.admin;
/**
* Where a journalled destructive operation stands.
*
* <p>The store this replaces recorded one fact — "this approval was claimed" — and recorded it
* before any work happened. A run that died halfway had consumed its approval, left no record of
* how far it got, and offered the operator two equally bad choices: request a fresh approval and
* redo work that may already have been done, or leave the operation half-applied.
*/
public enum AdminOperationState {
/** Claimed and in progress. A lease is held; the checkpoint says how far it got. */
STARTED,
/** Every item finished. The approval is spent and must not run again. */
COMPLETED,
/** The run stopped before finishing. It may be resumed from its checkpoint under a new lease. */
FAILED
}
@@ -0,0 +1,98 @@
package dev.caskeleton.messaging.admin;
import dev.caskeleton.messaging.api.destination.DestinationName;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
/**
* Everything an issuer signs when granting one destructive operation.
*
* <p>{@link AdminApproval} carried a ticket, an approver, and a window. Nothing in it said which
* operation, on which destination, against which topology, or up to what impact — so the same
* approval authorised every plan presented inside the window, and the audit trail recorded a ticket
* that proved nothing about what was executed.
*
* <p>Every field here is part of the signed canonical form, which is what makes the grant
* non-transferable: change the target, the topology version, the impact ceiling, or the plan, and
* the signature no longer verifies.
*
* @param approval the ticket, approver, and validity window
* @param requestedBy the operator who will execute it, kept separate from the approver
* @param operation the destructive operation being authorised
* @param source the destination read from
* @param target the destination written to, when the operation has one
* @param topologyVersion the topology the impact estimate was computed against
* @param maxImpact the largest number of messages the approver agreed to
* @param planDigest the fingerprint of the exact plan
*/
public record ApprovalGrant(
AdminApproval approval,
String requestedBy,
DestructiveOperation operation,
DestinationName source,
Optional<DestinationName> target,
String topologyVersion,
long maxImpact,
PlanDigest planDigest) {
/** Validates the grant and enforces subject separation. */
public ApprovalGrant {
Objects.requireNonNull(approval, "approval must not be null");
Objects.requireNonNull(operation, "operation must not be null");
Objects.requireNonNull(source, "source must not be null");
Objects.requireNonNull(target, "target must not be null");
Objects.requireNonNull(topologyVersion, "topologyVersion must not be null");
Objects.requireNonNull(planDigest, "planDigest must not be null");
if (requestedBy == null || requestedBy.isBlank()) {
throw new IllegalArgumentException("requestedBy must not be blank");
}
if (approval.approvedBy().equals(requestedBy)) {
// Four-eyes, expressed where it cannot be skipped: an operator approving their own
// destructive operation is the control not existing.
throw new IllegalArgumentException(
"the approver and the operator must be different people; both are " + requestedBy);
}
if (maxImpact < 0) {
throw new IllegalArgumentException("maxImpact must not be negative");
}
}
/**
* Renders the grant deterministically for signing and verification.
*
* <p>Every field is length-prefixed rather than delimited. A delimiter can be smuggled into a
* ticket or an identity to make two different grants render identically; a length prefix cannot.
*
* @return the canonical form
*/
public String canonicalForm() {
StringBuilder canonical = new StringBuilder("v1");
appendField(canonical, approval.ticket());
appendField(canonical, approval.approvedBy());
appendField(canonical, requestedBy);
appendField(canonical, operation.name());
appendField(canonical, source.value());
appendField(canonical, target.map(DestinationName::value).orElse(""));
appendField(canonical, topologyVersion);
appendField(canonical, Long.toString(maxImpact));
appendField(canonical, planDigest.value());
appendField(canonical, approval.approvedAt().toString());
appendField(canonical, approval.validUntil().toString());
return canonical.toString();
}
private static void appendField(StringBuilder canonical, String value) {
canonical.append(value.length()).append(':').append(value);
}
/**
* Reports whether the grant still authorises anything.
*
* @param now the current instant
* @return true while inside the approval window
*/
public boolean isValidAt(Instant now) {
return approval.isValidAt(now);
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.messaging.admin;
import java.time.Instant;
/**
* The only thing that can turn a signed grant into a {@link VerifiedApproval}.
*
* <p>An implementation must check, at minimum: the issuer's signature over {@link
* ApprovalGrant#canonicalForm()}, that the approval window is open at {@code now}, and that the
* digest the caller is about to execute is the digest that was signed. Everything else the grant
* binds — operation, source, target, topology version, impact ceiling, approver-versus-operator
* separation — is inside the canonical form, so a signature check covers them all at once.
*/
public interface ApprovalVerifier {
/**
* Verifies a signed grant against the plan actually about to run.
*
* @param grant what the issuer signed
* @param signature the issuer's signature over the grant's canonical form
* @param executingDigest the digest of the plan the caller is about to execute
* @param now the current instant
* @return the verified approval
* @throws dev.caskeleton.messaging.api.error.MessageAuthorizationException when anything about
* the grant, the signature, the window, or the digest does not hold
*/
VerifiedApproval verify(
ApprovalGrant grant, String signature, PlanDigest executingDigest, Instant now);
}
@@ -1,5 +1,6 @@
package dev.caskeleton.messaging.admin;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.error.MessageAuthorizationException;
import java.time.Instant;
import java.util.Objects;
@@ -17,11 +18,42 @@ import java.util.Objects;
* @param loopAcknowledged whether the approver accepted the previously-redriven candidates
*/
public record ApprovedRedrivePlan(
RedrivePlan plan, AdminApproval approval, boolean loopAcknowledged) {
RedrivePlan plan, VerifiedApproval approval, boolean loopAcknowledged) {
/** Binds the approval to this exact plan at construction. */
public ApprovedRedrivePlan {
Objects.requireNonNull(plan, "plan must not be null");
Objects.requireNonNull(approval, "approval must not be null");
if (!approval.grant().planDigest().equals(plan.digest())) {
throw new MessageAuthorizationException(
"APPROVAL_PLAN_MISMATCH",
"approval %s was issued for a different plan than the one it is attached to"
.formatted(approval.ticket()));
}
if (approval.grant().operation() != DestructiveOperation.REDRIVE) {
throw new MessageAuthorizationException(
"APPROVAL_OPERATION_MISMATCH",
"approval %s authorises %s, not a redrive"
.formatted(approval.ticket(), approval.grant().operation()));
}
if (!approval.grant().source().equals(plan.request().source())
|| !approval.grant().target().equals(java.util.Optional.of(plan.request().target()))) {
throw new MessageAuthorizationException(
"APPROVAL_SOURCE_MISMATCH",
"approval %s authorises %s to %s, not %s to %s"
.formatted(
approval.ticket(),
approval.grant().source().value(),
approval.grant().target().map(DestinationName::value).orElse("(none)"),
plan.request().source().value(),
plan.request().target().value()));
}
if (plan.candidates() > approval.grant().maxImpact()) {
throw new MessageAuthorizationException(
"APPROVAL_IMPACT_EXCEEDED",
"the plan moves %d messages but the approver agreed to at most %d"
.formatted(plan.candidates(), approval.grant().maxImpact()));
}
}
/**
@@ -39,6 +71,13 @@ public record ApprovedRedrivePlan(
throw new MessageAuthorizationException(
"APPROVAL_EXPIRED", "approval %s is not valid at %s".formatted(approval.ticket(), now));
}
if (!approval.grant().topologyVersion().equals(currentTopologyVersion)) {
throw new MessageAuthorizationException(
"TOPOLOGY_CHANGED_SINCE_APPROVAL",
"approval %s was signed against topology %s but the broker is now at %s"
.formatted(
approval.ticket(), approval.grant().topologyVersion(), currentTopologyVersion));
}
if (!plan.topologyVersion().equals(currentTopologyVersion)) {
throw new MessageAuthorizationException(
"TOPOLOGY_CHANGED_SINCE_APPROVAL",
@@ -14,11 +14,41 @@ import java.util.Objects;
* @param plan the plan that was approved
* @param approval the approval authorising it
*/
public record ApprovedReplayPlan(ReplayPlan plan, AdminApproval approval) {
public record ApprovedReplayPlan(ReplayPlan plan, VerifiedApproval approval) {
/** Binds the approval to this exact plan at construction. */
public ApprovedReplayPlan {
Objects.requireNonNull(plan, "plan must not be null");
Objects.requireNonNull(approval, "approval must not be null");
if (!approval.grant().planDigest().equals(plan.digest())) {
// A genuine, verified approval for a different plan. Checking it here means the mismatch
// cannot survive to the execute call under any code path.
throw new MessageAuthorizationException(
"APPROVAL_PLAN_MISMATCH",
"approval %s was issued for a different plan than the one it is attached to"
.formatted(approval.ticket()));
}
if (approval.grant().operation() != DestructiveOperation.REPLAY) {
throw new MessageAuthorizationException(
"APPROVAL_OPERATION_MISMATCH",
"approval %s authorises %s, not a replay"
.formatted(approval.ticket(), approval.grant().operation()));
}
if (!approval.grant().source().equals(plan.request().destination())) {
throw new MessageAuthorizationException(
"APPROVAL_SOURCE_MISMATCH",
"approval %s authorises %s, not %s"
.formatted(
approval.ticket(),
approval.grant().source().value(),
plan.request().destination().value()));
}
if (plan.estimatedMessages() > approval.grant().maxImpact()) {
throw new MessageAuthorizationException(
"APPROVAL_IMPACT_EXCEEDED",
"the plan moves about %d messages but the approver agreed to at most %d"
.formatted(plan.estimatedMessages(), approval.grant().maxImpact()));
}
}
/**
@@ -36,6 +66,13 @@ public record ApprovedReplayPlan(ReplayPlan plan, AdminApproval approval) {
throw new MessageAuthorizationException(
"APPROVAL_EXPIRED", "approval %s is not valid at %s".formatted(approval.ticket(), now));
}
if (!approval.grant().topologyVersion().equals(currentTopologyVersion)) {
throw new MessageAuthorizationException(
"TOPOLOGY_CHANGED_SINCE_APPROVAL",
"approval %s was signed against topology %s but the broker is now at %s"
.formatted(
approval.ticket(), approval.grant().topologyVersion(), currentTopologyVersion));
}
if (!plan.topologyVersion().equals(currentTopologyVersion)) {
// Every number in the plan was computed against the old topology, so the approver agreed to
// an impact estimate that no longer describes what would happen.
@@ -9,7 +9,7 @@ import java.util.Optional;
/**
* The single gate every destructive messaging operation passes through.
*
* <p>Three conditions, all required. The caller must hold the admin credential — an application
* <p>Four conditions, all required. The caller must hold the admin credential — an application
* runtime does not, by construction. The approval must be present and inside its validity window.
* And a dry run is always permitted, because the way to make operators plan before they act is to
* make planning free.
@@ -35,7 +35,7 @@ public final class DestructiveOperationGuard {
*
* @param operation the operation
* @param destination the destination affected
* @param approval the approval, when one was supplied
* @param approval the verified approval, when one was supplied
* @param dryRun whether this is a plan-only run
* @param now the current instant
* @throws MessageAuthorizationException when the operation is not authorised
@@ -43,7 +43,7 @@ public final class DestructiveOperationGuard {
public void authorize(
DestructiveOperation operation,
DestinationName destination,
Optional<AdminApproval> approval,
Optional<VerifiedApproval> approval,
boolean dryRun,
Instant now) {
Objects.requireNonNull(operation, "operation must not be null");
@@ -59,7 +59,7 @@ public final class DestructiveOperationGuard {
"ADMIN_CREDENTIAL_REQUIRED",
operation + " on " + destination.value() + " requires the admin credential");
}
AdminApproval granted =
VerifiedApproval granted =
approval.orElseThrow(
() ->
new MessageAuthorizationException(
@@ -69,5 +69,27 @@ public final class DestructiveOperationGuard {
throw new MessageAuthorizationException(
"APPROVAL_EXPIRED", "approval " + granted.ticket() + " is outside its validity window");
}
if (granted.grant().operation() != operation) {
// The approval verified — for something else. A guard that only checks presence and window
// lets a verified redrive approval authorise a destination deletion.
throw new MessageAuthorizationException(
"APPROVAL_OPERATION_MISMATCH",
"approval "
+ granted.ticket()
+ " authorises "
+ granted.grant().operation()
+ ", not "
+ operation);
}
if (!granted.grant().source().equals(destination)) {
throw new MessageAuthorizationException(
"APPROVAL_SOURCE_MISMATCH",
"approval "
+ granted.ticket()
+ " authorises "
+ granted.grant().source().value()
+ ", not "
+ destination.value());
}
}
}
@@ -0,0 +1,111 @@
package dev.caskeleton.messaging.admin;
import dev.caskeleton.messaging.api.error.MessageAuthorizationException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.HexFormat;
import java.util.Objects;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Verifies grants with a shared HMAC-SHA256 issuing key.
*
* <p>A shared secret rather than a public-key signature is a deliberate scope choice: the issuer is
* the change-management system operated by the same organisation as the runtime, so key
* distribution is already solved and the property that matters — that an operator cannot mint an
* approval for themselves — holds as long as the key is not on the operator's machine. A public-key
* verifier can be substituted by implementing {@link ApprovalVerifier}; nothing else in the
* platform depends on how the signature is produced.
*
* <p>Comparison is constant-time. A verifier that compares with {@code equals} leaks the signature
* one byte at a time to a caller who can retry, which for an offline attacker with unlimited
* attempts is the whole secret.
*/
public final class HmacApprovalVerifier implements ApprovalVerifier {
private static final String ALGORITHM = "HmacSHA256";
private final byte[] issuingKey;
/**
* Creates a verifier over the issuing key.
*
* @param issuingKey the shared secret the approval issuer signs with
*/
public HmacApprovalVerifier(byte[] issuingKey) {
Objects.requireNonNull(issuingKey, "issuingKey must not be null");
if (issuingKey.length < 32) {
throw new IllegalArgumentException(
"the approval issuing key must be at least 256 bits; a shorter key makes the signature"
+ " brute-forceable offline");
}
this.issuingKey = issuingKey.clone();
}
/**
* Produces the signature an issuer would attach to a grant.
*
* <p>Present because the issuer and the verifier must agree on the canonical form exactly, and a
* second implementation of that agreement is a second thing to drift. Holding this key is what
* makes a caller an issuer — it is not, and must not become, available to the runtime that
* executes operations.
*
* @param grant the grant to sign
* @return the hexadecimal signature
*/
public String sign(ApprovalGrant grant) {
Objects.requireNonNull(grant, "grant must not be null");
return HexFormat.of().formatHex(mac(grant.canonicalForm()));
}
@Override
public VerifiedApproval verify(
ApprovalGrant grant, String signature, PlanDigest executingDigest, Instant now) {
Objects.requireNonNull(grant, "grant must not be null");
Objects.requireNonNull(signature, "signature must not be null");
Objects.requireNonNull(executingDigest, "executingDigest must not be null");
Objects.requireNonNull(now, "now must not be null");
if (!grant.planDigest().equals(executingDigest)) {
// The signature would verify: this is a genuine approval, for a different plan. Replaying one
// approval across plans is the attack the digest binding exists to stop.
throw new MessageAuthorizationException(
"APPROVAL_PLAN_MISMATCH",
"approval %s was issued for plan %s but the plan about to execute is %s"
.formatted(
grant.approval().ticket(), grant.planDigest().value(), executingDigest.value()));
}
if (!grant.isValidAt(now)) {
throw new MessageAuthorizationException(
"APPROVAL_EXPIRED",
"approval %s is not valid at %s".formatted(grant.approval().ticket(), now));
}
byte[] presented;
try {
presented = HexFormat.of().parseHex(signature);
} catch (IllegalArgumentException malformed) {
throw new MessageAuthorizationException(
"APPROVAL_SIGNATURE_INVALID", "the approval signature is not hexadecimal");
}
if (!MessageDigest.isEqual(mac(grant.canonicalForm()), presented)) {
throw new MessageAuthorizationException(
"APPROVAL_SIGNATURE_INVALID",
("approval %s does not verify against the issuing key; the grant was altered after it"
+ " was signed, or it was never issued")
.formatted(grant.approval().ticket()));
}
return VerifiedApproval.of(grant);
}
private byte[] mac(String canonicalForm) {
try {
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(new SecretKeySpec(issuingKey, ALGORITHM));
return mac.doFinal(canonicalForm.getBytes(StandardCharsets.UTF_8));
} catch (java.security.GeneralSecurityException failure) {
throw new IllegalStateException("HMAC-SHA256 is required of every Java runtime", failure);
}
}
}
@@ -0,0 +1,47 @@
package dev.caskeleton.messaging.admin;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.Objects;
/**
* The fingerprint of exactly what an approver agreed to.
*
* <p>An approval used to name a ticket and a window and nothing else, so it authorised any plan
* presented within that window. The operator who got a redrive of one dead-letter destination
* approved could execute a redrive of a different one with the same ticket, and every audit record
* would look correct. Binding the signature to this digest is what makes an approval about a plan
* rather than about a period of time.
*
* @param value the lowercase hexadecimal SHA-256 of the plan's canonical form
*/
public record PlanDigest(String value) {
/** Validates the digest shape. */
public PlanDigest {
Objects.requireNonNull(value, "value must not be null");
if (!value.matches("[0-9a-f]{64}")) {
throw new IllegalArgumentException("a plan digest is 64 lowercase hexadecimal characters");
}
}
/**
* Digests a plan's canonical form.
*
* @param canonicalForm the plan rendered deterministically, field by field
* @return the digest
*/
public static PlanDigest ofCanonical(String canonicalForm) {
Objects.requireNonNull(canonicalForm, "canonicalForm must not be null");
try {
byte[] digest =
MessageDigest.getInstance("SHA-256")
.digest(canonicalForm.getBytes(StandardCharsets.UTF_8));
return new PlanDigest(HexFormat.of().formatHex(digest));
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException("SHA-256 is required of every Java runtime", impossible);
}
}
}
@@ -39,6 +39,28 @@ public record RedrivePlan(
}
}
/**
* The fingerprint an approver's signature is bound to.
*
* <p>Source, target, batch size, and both candidate counts are in it, so an approval for a
* redrive of one dead-letter destination cannot be presented for a redrive of another.
*
* @return the digest of this exact plan
*/
public PlanDigest digest() {
return PlanDigest.ofCanonical(
String.join(
"|",
"REDRIVE",
request.redriveId().toString(),
request.source().value(),
request.target().value(),
Integer.toString(request.batchSize()),
Integer.toString(candidates),
Integer.toString(alreadyRedrivenCandidates),
topologyVersion));
}
/**
* Reports whether this redrive would replay messages that already failed a redrive.
*
@@ -39,6 +39,30 @@ public record ReplayPlan(
}
}
/**
* The fingerprint an approver's signature is bound to.
*
* <p>Every field that changes what would happen is in it. An approval signed over this digest
* cannot be presented for a plan that reads a different destination, targets a different consumer
* group, starts from a different position, or estimates a different impact.
*
* @return the digest of this exact plan
*/
public PlanDigest digest() {
return PlanDigest.ofCanonical(
String.join(
"|",
"REPLAY",
request.replayId().toString(),
request.destination().value(),
Boolean.toString(request.isolatedConsumerGroup()),
request.from().toString(),
request.to().map(Object::toString).orElse(""),
Long.toString(estimatedMessages),
topologyVersion,
Boolean.toString(targetsLiveConsumerGroup)));
}
/**
* Returns a one-line operator-facing summary of the impact.
*
@@ -0,0 +1,88 @@
package dev.caskeleton.messaging.admin;
import java.time.Instant;
import java.util.Objects;
/**
* A grant that an {@link ApprovalVerifier} has checked, and that nobody else can manufacture.
*
* <p>The approved-plan types used to hold a plain {@code AdminApproval} record with a public
* constructor, so "this plan was approved" was a claim the caller made about itself. Any code that
* could reach the execute method could write {@code new AdminApproval("TICKET-1", "someone", now,
* later)} and the platform believed it.
*
* <p>This class has no public constructor and no public factory. The only way to obtain one is to
* present a grant and a signature to a verifier, which is exactly the property the type is for:
* holding a {@code VerifiedApproval} is itself the evidence that verification happened.
*/
public final class VerifiedApproval {
private final ApprovalGrant grant;
private VerifiedApproval(ApprovalGrant grant) {
this.grant = Objects.requireNonNull(grant, "grant must not be null");
}
/**
* Mints a verified approval. Package-private on purpose: only a verifier in this package may call
* it, so the type cannot be forged from application or adapter code.
*/
static VerifiedApproval of(ApprovalGrant grant) {
return new VerifiedApproval(grant);
}
/**
* The grant that was verified.
*
* @return the grant
*/
public ApprovalGrant grant() {
return grant;
}
/**
* The approval ticket, for audit records and journal keys.
*
* @return the ticket
*/
public String ticket() {
return grant.approval().ticket();
}
/**
* Who approved the operation.
*
* @return the approver identity
*/
public String approvedBy() {
return grant.approval().approvedBy();
}
/**
* Reports whether the approval window is still open.
*
* @param now the current instant
* @return true while inside the window
*/
public boolean isValidAt(Instant now) {
return grant.isValidAt(now);
}
@Override
public boolean equals(Object other) {
return other instanceof VerifiedApproval verified && grant.equals(verified.grant);
}
@Override
public int hashCode() {
return grant.hashCode();
}
@Override
public String toString() {
// Deliberately not the whole grant: this string reaches logs, and the plan digest plus the
// ticket identify the operation without restating who approved what to an audience that has
// not been authorised to read it.
return "VerifiedApproval[" + ticket() + " " + grant.planDigest().value().substring(0, 12) + "]";
}
}
@@ -17,8 +17,35 @@ class DestructiveOperationGuardTest {
private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z");
private static final DestinationName ORDERS = new DestinationName("order-events");
private static final AdminApproval VALID =
new AdminApproval("CHG-1001", "operator", NOW.minusSeconds(60), NOW.plusSeconds(3600));
private static final HmacApprovalVerifier ISSUER =
new HmacApprovalVerifier(
"an-issuing-key-of-at-least-32-bytes!".getBytes(java.nio.charset.StandardCharsets.UTF_8));
private static final VerifiedApproval VALID =
verified(DestructiveOperation.REPLAY, ORDERS, NOW.minusSeconds(60), NOW.plusSeconds(3600));
/**
* A grant the issuer signed, verified the way the runtime verifies it.
*
* <p>The guard used to take a plain {@code AdminApproval} record, which any caller could
* construct. Every case below now has to go through a real signature to get an approval object at
* all, which is the property the type change was made for.
*/
private static VerifiedApproval verified(
DestructiveOperation operation, DestinationName source, Instant from, Instant until) {
PlanDigest digest = PlanDigest.ofCanonical(operation + "|" + source.value());
ApprovalGrant grant =
new ApprovalGrant(
new AdminApproval("CHG-1001", "approver", from, until),
"operator",
operation,
source,
Optional.empty(),
"v1",
Long.MAX_VALUE,
digest);
return ISSUER.verify(grant, ISSUER.sign(grant), digest, from);
}
@Test
void anApplicationRuntimeCannotRedrive() {
@@ -45,8 +72,12 @@ class DestructiveOperationGuardTest {
@Test
void anExpiredApprovalDoesNotAuthorise() {
DestructiveOperationGuard guard = new DestructiveOperationGuard(true);
AdminApproval expired =
new AdminApproval("CHG-1000", "operator", NOW.minusSeconds(7200), NOW.minusSeconds(60));
VerifiedApproval expired =
verified(
DestructiveOperation.OFFSET_RESET,
ORDERS,
NOW.minusSeconds(7200),
NOW.minusSeconds(60));
assertThatThrownBy(
() ->