Skip to content
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 @@ -58,12 +58,14 @@ final class DefaultBedrockPrincipalVerifier implements BedrockPrincipalVerifier
Set.of("provider", "record_id", "revision", "verified_at");

private final Map<String, PublicKey> keys;
private final PrincipalKeyResolver keyResolver;
private final Clock clock;
private final ReplayCache replay;

DefaultBedrockPrincipalVerifier(VerifierConfiguration configuration) {
this.clock = configuration.clock();
this.replay = new ReplayCache(configuration.replayCapacity(), clock);
this.keyResolver = configuration.keyResolver();
Map<String, PublicKey> parsed = new HashMap<>();
configuration.publicKeys().forEach((kid, key) -> parsed.put(kid, parsePublicKey(key)));
this.keys = Map.copyOf(parsed);
Expand All @@ -89,6 +91,7 @@ public VerifiedBedrockPrincipal verifyAndConsume(
}

PublicKey key = keys.get(parsed.kid);
if (key == null && keyResolver != null) key = resolvedKey(parsed.kid);
if (key == null) throw reject(PrincipalError.TRUST);
if (!verifySignature(key, parsed.signingInput, parsed.signature)) {
throw reject(PrincipalError.SIGNATURE);
Expand Down Expand Up @@ -207,6 +210,21 @@ kind, new CanonicalXuid(claims.canonicalXuid), unlinked, linked,
expected.sourceProtocolVersion(), expected.policyRevision()));
}

private PublicKey resolvedKey(String kid) {
byte[] raw;
try {
raw = keyResolver.resolve(kid);
} catch (RuntimeException ignored) {
return null;
}
if (raw == null || raw.length != 32) return null;
try {
return parsePublicKey(raw.clone());
} catch (IllegalArgumentException ignored) {
return null;
}
}

private static void validateTime(Claims claims, long now) throws PrincipalVerificationException {
if (!numericDate(claims.iat) || !numericDate(claims.nbf) || !numericDate(claims.exp)
|| claims.nbf > claims.iat || claims.iat > claims.exp
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.minekube.connect.api.player.principal;

/**
* Resolves the raw Ed25519 verifier key for a compact-envelope {@code kid} that is not among the
* statically configured keys.
*
* <p>Configured {@link VerifierConfiguration.Builder#publicKey(String, byte[])} pins are always
* consulted first; this resolver is only a fallback for a kid the static set does not contain. It
* exists so a consumer can follow a metadata-published key rotation without replacing (and thereby
* resetting the replay cache of) its verifier instance.
*
* <p>Implementations must validate the material they return and must be safe for concurrent use.
* Returning {@code null} means this kid is not trusted; the verifier then rejects the envelope
* with {@link PrincipalError#TRUST}.
*/
@FunctionalInterface
public interface PrincipalKeyResolver {
/**
* @param kid the non-secret JWS key id from the envelope header
* @return the raw 32-byte Ed25519 public key, or {@code null} when this kid is not trusted
*/
byte[] resolve(String kid);

/** A resolver that never supplies a key. */
static PrincipalKeyResolver none() {
return kid -> null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@
/** Immutable verifier dependencies. Static keys are keyed by the frozen non-secret JWS kid. */
public final class VerifierConfiguration {
private final Map<String, byte[]> publicKeys;
private final PrincipalKeyResolver keyResolver;
private final Clock clock;
private final int replayCapacity;

private VerifierConfiguration(Builder builder) {
Map<String, byte[]> keys = new LinkedHashMap<>();
builder.publicKeys.forEach((kid, key) -> keys.put(kid, key.clone()));
this.publicKeys = Collections.unmodifiableMap(keys);
this.keyResolver = builder.keyResolver;
this.clock = builder.clock;
this.replayCapacity = builder.replayCapacity;
}
Expand All @@ -32,9 +34,11 @@ Map<String, byte[]> publicKeys() {

Clock clock() { return clock; }
int replayCapacity() { return replayCapacity; }
PrincipalKeyResolver keyResolver() { return keyResolver; }

public static final class Builder {
private final Map<String, byte[]> publicKeys = new LinkedHashMap<>();
private PrincipalKeyResolver keyResolver;
private Clock clock = Clock.systemUTC();
private int replayCapacity = 65_536;

Expand All @@ -53,6 +57,15 @@ public Builder clock(Clock clock) {
return this;
}

/**
* Supplies keys for envelope kids that are not covered by the static pins. Static pins
* always win; this hook is never consulted for a kid that was configured explicitly.
*/
public Builder keyResolver(PrincipalKeyResolver keyResolver) {
this.keyResolver = Objects.requireNonNull(keyResolver, "keyResolver");
return this;
}

public Builder replayCapacity(int replayCapacity) {
if (replayCapacity <= 0 || replayCapacity > 65_536) {
throw new IllegalArgumentException("replayCapacity must be between 1 and 65536");
Expand Down
14 changes: 12 additions & 2 deletions core/src/main/java/com/minekube/connect/ConnectPlatform.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import com.minekube.connect.api.logger.ConnectLogger;
import com.minekube.connect.api.packet.PacketHandlers;
import com.minekube.connect.bedrock.BedrockAdmissionCoordinator;
import com.minekube.connect.bedrock.BedrockPrincipalKeySource;
import com.minekube.connect.config.ConfigHolder;
import com.minekube.connect.config.ConfigLoader;
import com.minekube.connect.config.ConnectConfig;
Expand Down Expand Up @@ -65,6 +66,7 @@ public class ConnectPlatform {

private ConnectConfig config;
private Injector guice;
private BedrockPrincipalKeySource principalKeys;

public ConnectPlatform(
ConnectApi api,
Expand Down Expand Up @@ -99,7 +101,9 @@ public void init(
@Named("dataDirectory") Path dataDirectory,
ConfigLoader configLoader,
ConfigHolder configHolder,
PacketHandlers packetHandlers) {
PacketHandlers packetHandlers,
BedrockPrincipalKeySource principalKeys) {
this.principalKeys = principalKeys;

if (!Files.isDirectory(dataDirectory)) {
try {
Expand Down Expand Up @@ -181,7 +185,13 @@ public boolean disable() {
try {
admissionCoordinator.close();
} finally {
guice.getInstance(CommonPlatformInjector.class).shutdown();
try {
// Stops the background key refresh thread; the parent-scoped key source
// restarts it lazily on first use after a reload.
if (principalKeys != null) principalKeys.close();
} finally {
guice.getInstance(CommonPlatformInjector.class).shutdown();
}
}
}
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,31 @@ public final class BedrockPrincipalConsumer {
private static final int MAX_ENVELOPE_BYTES = 16 * 1024;
private final Supplier<ConnectConfig> config;
private final Clock clock;
private BedrockPrincipalVerifier verifier;
private final BedrockPrincipalKeySource keySource;
private volatile BedrockPrincipalVerifier verifier;
private volatile boolean remoteKeys;

@Inject
public BedrockPrincipalConsumer(ConfigHolder configHolder) {
this(Objects.requireNonNull(configHolder, "configHolder")::get, Clock.systemUTC());
public BedrockPrincipalConsumer(
ConfigHolder configHolder, BedrockPrincipalKeySource keySource) {
this(Objects.requireNonNull(configHolder, "configHolder")::get, Clock.systemUTC(),
keySource);
}

BedrockPrincipalConsumer(ConnectConfig config, Clock clock) {
this(() -> Objects.requireNonNull(config, "config"), clock);
this(config, clock, null);
}

private BedrockPrincipalConsumer(Supplier<ConnectConfig> config, Clock clock) {
BedrockPrincipalConsumer(
ConnectConfig config, Clock clock, BedrockPrincipalKeySource keySource) {
this(() -> Objects.requireNonNull(config, "config"), clock, keySource);
}

private BedrockPrincipalConsumer(
Supplier<ConnectConfig> config, Clock clock, BedrockPrincipalKeySource keySource) {
this.config = Objects.requireNonNull(config, "config");
this.clock = Objects.requireNonNull(clock, "clock");
this.keySource = keySource;
}

public Optional<VerifiedBedrockPrincipal> verify(Session session) {
Expand Down Expand Up @@ -98,7 +109,9 @@ public Optional<VerifiedBedrockPrincipal> verify(Session session) {
if (envelope.size() > MAX_ENVELOPE_BYTES) {
throw new BedrockPrincipalAdmissionException(PrincipalError.MALFORMED);
}
return Optional.of(verifier().verifyAndConsume(
BedrockPrincipalVerifier active = verifier();
requireTrustMaterial();
return Optional.of(active.verifyAndConsume(
SignedPrincipalEnvelope.of(strictUtf8(envelope.toByteArray())),
expected));
} catch (PrincipalVerificationException error) {
Expand All @@ -119,26 +132,45 @@ private synchronized BedrockPrincipalVerifier verifier() {
if (principalConfig == null) {
throw new BedrockPrincipalAdmissionException(PrincipalError.READINESS);
}
VerifierConfiguration.Builder configuration = VerifierConfiguration.builder().clock(clock);
Map<String, String> pins = principalConfig.getPublicKeys();
if (pins == null || pins.isEmpty()) {
boolean hasPins = pins != null && !pins.isEmpty();
if (!hasPins && (keySource == null || !keySource.usable())) {
// Zero-config means absent pins are filled from the metadata document. Unreachable
// metadata is a named, fail-closed condition rather than an ordinary trust failure.
throw new BedrockPrincipalAdmissionException(PrincipalError.METADATA_UNAVAILABLE);
}
VerifierConfiguration.Builder configuration = VerifierConfiguration.builder().clock(clock);
try {
pins.forEach((kid, encoded) -> {
byte[] decoded = Base64.getUrlDecoder().decode(encoded);
if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(encoded)) {
throw new IllegalArgumentException();
}
configuration.publicKey(kid, decoded);
});
verifier = BedrockPrincipalVerifierFactory.create(configuration.build());
return verifier;
if (hasPins) {
pins.forEach((kid, encoded) -> {
byte[] decoded = Base64.getUrlDecoder().decode(encoded);
if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(encoded)) {
throw new IllegalArgumentException();
}
configuration.publicKey(kid, decoded);
});
} else {
// Static pins always win. The resolver is only the fallback for a rotating key set
// published by the metadata document; the verifier (and its replay cache) stays one
// instance across rotations.
configuration.keyResolver(keySource::resolve);
}
BedrockPrincipalVerifier created = BedrockPrincipalVerifierFactory.create(
configuration.build());
remoteKeys = !hasPins;
verifier = created;
return created;
} catch (RuntimeException ignored) {
throw new BedrockPrincipalAdmissionException(PrincipalError.TRUST);
}
}

private void requireTrustMaterial() {
if (remoteKeys && (keySource == null || !keySource.usable())) {
throw new BedrockPrincipalAdmissionException(PrincipalError.METADATA_UNAVAILABLE);
}
}

private ConnectConfig config() {
return Objects.requireNonNull(config.get(), "config");
}
Expand Down
Loading
Loading