diff --git a/api/src/main/java/com/minekube/connect/api/player/principal/DefaultBedrockPrincipalVerifier.java b/api/src/main/java/com/minekube/connect/api/player/principal/DefaultBedrockPrincipalVerifier.java index 63a0c4fd8..3c82263cb 100644 --- a/api/src/main/java/com/minekube/connect/api/player/principal/DefaultBedrockPrincipalVerifier.java +++ b/api/src/main/java/com/minekube/connect/api/player/principal/DefaultBedrockPrincipalVerifier.java @@ -58,12 +58,14 @@ final class DefaultBedrockPrincipalVerifier implements BedrockPrincipalVerifier Set.of("provider", "record_id", "revision", "verified_at"); private final Map 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 parsed = new HashMap<>(); configuration.publicKeys().forEach((kid, key) -> parsed.put(kid, parsePublicKey(key))); this.keys = Map.copyOf(parsed); @@ -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); @@ -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 diff --git a/api/src/main/java/com/minekube/connect/api/player/principal/PrincipalKeyResolver.java b/api/src/main/java/com/minekube/connect/api/player/principal/PrincipalKeyResolver.java new file mode 100644 index 000000000..09e0cde9c --- /dev/null +++ b/api/src/main/java/com/minekube/connect/api/player/principal/PrincipalKeyResolver.java @@ -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. + * + *

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. + * + *

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; + } +} diff --git a/api/src/main/java/com/minekube/connect/api/player/principal/VerifierConfiguration.java b/api/src/main/java/com/minekube/connect/api/player/principal/VerifierConfiguration.java index 531c73289..9ac98a94f 100644 --- a/api/src/main/java/com/minekube/connect/api/player/principal/VerifierConfiguration.java +++ b/api/src/main/java/com/minekube/connect/api/player/principal/VerifierConfiguration.java @@ -9,6 +9,7 @@ /** Immutable verifier dependencies. Static keys are keyed by the frozen non-secret JWS kid. */ public final class VerifierConfiguration { private final Map publicKeys; + private final PrincipalKeyResolver keyResolver; private final Clock clock; private final int replayCapacity; @@ -16,6 +17,7 @@ private VerifierConfiguration(Builder builder) { Map 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; } @@ -32,9 +34,11 @@ Map publicKeys() { Clock clock() { return clock; } int replayCapacity() { return replayCapacity; } + PrincipalKeyResolver keyResolver() { return keyResolver; } public static final class Builder { private final Map publicKeys = new LinkedHashMap<>(); + private PrincipalKeyResolver keyResolver; private Clock clock = Clock.systemUTC(); private int replayCapacity = 65_536; @@ -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"); diff --git a/core/src/main/java/com/minekube/connect/ConnectPlatform.java b/core/src/main/java/com/minekube/connect/ConnectPlatform.java index 36c8796ea..8d0313c4f 100644 --- a/core/src/main/java/com/minekube/connect/ConnectPlatform.java +++ b/core/src/main/java/com/minekube/connect/ConnectPlatform.java @@ -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; @@ -65,6 +66,7 @@ public class ConnectPlatform { private ConnectConfig config; private Injector guice; + private BedrockPrincipalKeySource principalKeys; public ConnectPlatform( ConnectApi api, @@ -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 { @@ -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; diff --git a/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalConsumer.java b/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalConsumer.java index 35ead0b0f..a96a7a1e7 100644 --- a/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalConsumer.java +++ b/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalConsumer.java @@ -33,20 +33,31 @@ public final class BedrockPrincipalConsumer { private static final int MAX_ENVELOPE_BYTES = 16 * 1024; private final Supplier 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 config, Clock clock) { + BedrockPrincipalConsumer( + ConnectConfig config, Clock clock, BedrockPrincipalKeySource keySource) { + this(() -> Objects.requireNonNull(config, "config"), clock, keySource); + } + + private BedrockPrincipalConsumer( + Supplier config, Clock clock, BedrockPrincipalKeySource keySource) { this.config = Objects.requireNonNull(config, "config"); this.clock = Objects.requireNonNull(clock, "clock"); + this.keySource = keySource; } public Optional verify(Session session) { @@ -98,7 +109,9 @@ public Optional 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) { @@ -119,26 +132,45 @@ private synchronized BedrockPrincipalVerifier verifier() { if (principalConfig == null) { throw new BedrockPrincipalAdmissionException(PrincipalError.READINESS); } - VerifierConfiguration.Builder configuration = VerifierConfiguration.builder().clock(clock); Map 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"); } diff --git a/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalKeySource.java b/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalKeySource.java new file mode 100644 index 000000000..364647fa6 --- /dev/null +++ b/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalKeySource.java @@ -0,0 +1,606 @@ +package com.minekube.connect.bedrock; + +import com.google.gson.Gson; +import com.google.inject.Inject; +import com.google.inject.Singleton; +import com.google.inject.name.Named; +import com.minekube.connect.api.logger.ConnectLogger; +import com.minekube.connect.config.ConfigHolder; +import com.minekube.connect.config.ConnectConfig; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + +/** + * Runtime source of generation-2 verifier keys. + * + *

When {@code bedrock-principal.public-keys} is populated it is the only trust source: nothing + * is fetched and the pins win. When the map is empty the frozen metadata document at + * {@code metadata-origin + metadata-path} is fetched over HTTPS by one background daemon thread, + * cached for the advertised {@code cache_max_age_seconds}, revalidated with its {@code ETag}, and + * refreshed periodically so an idle connector keeps its keys. + * + *

The join path ({@link #resolve}, {@link #usable}) only reads the published immutable + * {@link Snapshot}; it never performs or waits for network I/O. A due or missing document, or an + * envelope {@code kid} the snapshot does not contain, only schedules a rate-limited background + * refresh. A failed refresh keeps the last good key set for a bounded stale window; once that + * window closes the connector has no usable trust material and fails closed. Only + * {@link #awaitUsable} blocks, and only off the join path before a capability advertisement. + */ +@Singleton +public final class BedrockPrincipalKeySource implements AutoCloseable { + + /** Where the keys currently accepted by the connector came from. */ + public enum Source { + /** Locally configured {@code public-keys} pins. */ + STATIC_PINS, + /** The generation-2 metadata document. */ + METADATA, + /** No usable trust source has been configured or fetched. */ + NONE + } + + /** Privacy-safe diagnostics view: source, last successful validation, and the trusted kid set. */ + public record TrustState(Source source, Instant lastSuccess, boolean fresh, Set kids) { + private static final TrustState NONE = new TrustState(Source.NONE, null, false, Set.of()); + + public TrustState { + Objects.requireNonNull(source, "source"); + kids = Collections.unmodifiableSet(new LinkedHashSet<>(Objects.requireNonNull(kids, "kids"))); + } + + static TrustState none() { + return NONE; + } + } + + /** Upper bound for the blocking warm-up before a capability advertisement. */ + static final Duration MAX_WARM_UP = Duration.ofSeconds(5); + + private static final Gson GSON = new Gson(); + private static final int METADATA_CALL_TIMEOUT_SECONDS = 5; + private static final int METADATA_BODY_LIMIT_BYTES = 64 * 1024; + private static final int METADATA_MAX_KEYS = 16; + private static final int METADATA_DEFAULT_CACHE_SECONDS = 300; + private static final int METADATA_MAX_CACHE_SECONDS = 300; + private static final int METADATA_MAX_STALE_SECONDS = 600; + /** Minimum spacing of fetches triggered by an unknown kid, and the first failure retry. */ + private static final int REFRESH_INTERVAL_SECONDS = 5; + private static final int MAX_RETRY_SECONDS = 60; + private static final Duration WARNING_INTERVAL = Duration.ofMinutes(5); + + private final Supplier config; + private final OkHttpClient httpClient; + private final ConnectLogger logger; + private final Supplier now; + private final Supplier schedulerFactory; + + /** The only state the join path reads. Replaced atomically, never mutated. */ + private volatile Snapshot snapshot; + + // Background refresh bookkeeping, guarded by this. No I/O ever runs under this monitor. + private ScheduledExecutorService scheduler; + private ScheduledFuture pending; + private boolean inFlight; + private long completedAttempts; + private long generation; + private int failures; + private Instant retryNotBefore = Instant.MIN; + private Instant forcedNotBefore = Instant.MIN; + private Instant lastWarning; + private Set announcedKids = Set.of(); + private final Set capabilityWithheld = + EnumSet.noneOf(BedrockPrincipalReadiness.Transport.class); + + /** + * Injection seam used by the plugin. The config is resolved lazily from {@link ConfigHolder} so + * this source can be constructed by the (config-agnostic) parent injector before + * {@code ConnectPlatform.init()} loads the configuration. + */ + @Inject + public BedrockPrincipalKeySource( + ConfigHolder configHolder, + @Named("defaultHttpClient") OkHttpClient httpClient, + ConnectLogger logger) { + this(Objects.requireNonNull(configHolder, "configHolder")::get, httpClient, logger, + Instant::now, BedrockPrincipalKeySource::newRefreshExecutor); + } + + BedrockPrincipalKeySource( + Supplier config, + OkHttpClient httpClient, + ConnectLogger logger, + Supplier now, + Supplier schedulerFactory) { + this.config = Objects.requireNonNull(config, "config"); + this.httpClient = Objects.requireNonNull(httpClient, "httpClient").newBuilder() + .callTimeout(METADATA_CALL_TIMEOUT_SECONDS, TimeUnit.SECONDS) + .followRedirects(false) + .followSslRedirects(false) + .build(); + this.logger = Objects.requireNonNull(logger, "logger"); + this.now = Objects.requireNonNull(now, "now"); + this.schedulerFactory = Objects.requireNonNull(schedulerFactory, "schedulerFactory"); + } + + /** + * Resolver hook for the verifier: static pins first, then the published metadata snapshot. + * Never blocks; an unknown kid schedules a rate-limited refresh and is untrusted for this join. + */ + byte[] resolve(String kid) { + if (kid == null) return null; + ConfigView view = view(); + if (view == null) return null; + if (view.hasPins()) return decodeKey(view.pins.get(kid)); + Snapshot current = current(view); + if (current == null) return null; + byte[] key = current.keys.get(kid); + if (key != null) return key.clone(); + // The envelope advertises a kid the snapshot does not contain: possibly a rotation. Learn + // it in the background; this join fails TRUST rather than waiting. + requestRefresh(view.scope, true); + return null; + } + + /** True when usable trust material is held now (pins or a document inside its stale window). */ + boolean usable() { + ConfigView view = view(); + if (view == null) return false; + if (view.hasPins()) return view.pinsAreUsable(); + return current(view) != null; + } + + /** + * Bounded warm-up for a capability advertisement: waits for an in-flight fetch to complete, at + * most {@link #MAX_WARM_UP}. Never call this on the join path. + */ + boolean awaitUsable(Duration timeout) { + ConfigView view = view(); + if (view == null) return false; + if (view.hasPins()) return view.pinsAreUsable(); + if (current(view) != null) return true; + long deadline = System.nanoTime() + Math.min( + Objects.requireNonNull(timeout, "timeout").toNanos(), MAX_WARM_UP.toNanos()); + synchronized (this) { + long attempts = completedAttempts; + while (inFlight && completedAttempts == attempts) { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) break; + try { + TimeUnit.NANOSECONDS.timedWait(this, remaining); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + break; + } + } + } + return current(view) != null; + } + + /** + * Records whether the latest advertisement on {@code transport} included v2. While one did not, + * the first refresh that obtains keys logs once that v2 is advertised only after a reconnect. + */ + synchronized void capabilityAdvertised( + BedrockPrincipalReadiness.Transport transport, boolean advertised) { + if (advertised) { + capabilityWithheld.remove(transport); + } else { + capabilityWithheld.add(transport); + } + } + + /** Diagnostics snapshot. Never performs a fetch. */ + TrustState state() { + ConfigView view = view(); + if (view == null) return TrustState.none(); + if (view.hasPins()) { + return new TrustState(Source.STATIC_PINS, null, true, view.pins.keySet()); + } + Snapshot current = snapshot; + if (current == null || !current.scope.equals(view.scope)) return TrustState.none(); + return new TrustState( + Source.METADATA, current.fetchedAt, !current.due(now.get()), current.keys.keySet()); + } + + /** Stops background refresh and drops the cached document. The next use starts it again. */ + @Override + public synchronized void close() { + generation++; + if (pending != null) pending.cancel(false); + pending = null; + if (scheduler != null) scheduler.shutdownNow(); + scheduler = null; + snapshot = null; + inFlight = false; + failures = 0; + retryNotBefore = Instant.MIN; + forcedNotBefore = Instant.MIN; + announcedKids = Set.of(); + capabilityWithheld.clear(); + notifyAll(); + } + + /** The snapshot for the configured scope when still inside its stale window; schedules refreshes. */ + private Snapshot current(ConfigView view) { + if (view.scope == null) return null; + Snapshot current = snapshot; + if (current == null || !current.scope.equals(view.scope)) { + requestRefresh(view.scope, false); + return null; + } + Instant time = now.get(); + if (current.due(time)) requestRefresh(view.scope, false); + return current.usable(time) ? current : null; + } + + private synchronized void requestRefresh(Scope scope, boolean force) { + if (inFlight) return; + Instant time = now.get(); + if (time.isBefore(retryNotBefore)) return; + Snapshot current = snapshot; + boolean matching = current != null && current.scope.equals(scope); + if (force) { + if (time.isBefore(forcedNotBefore)) return; + // A document fetched moments ago already is the newest view of the rotation. + if (matching && time.isBefore(current.fetchedAt.plusSeconds(REFRESH_INTERVAL_SECONDS))) { + return; + } + forcedNotBefore = time.plusSeconds(REFRESH_INTERVAL_SECONDS); + } else if (matching && !current.due(time)) { + return; + } + schedule(0); + } + + private synchronized void schedule(long delaySeconds) { + if (pending != null) pending.cancel(false); + if (scheduler == null) scheduler = schedulerFactory.get(); + if (delaySeconds == 0) inFlight = true; + pending = scheduler.schedule(this::refresh, delaySeconds, TimeUnit.SECONDS); + } + + /** Background task: the only code path that performs network I/O. */ + private void refresh() { + long startedGeneration; + Scope scope; + Snapshot previous; + synchronized (this) { + inFlight = true; + pending = null; + startedGeneration = generation; + ConfigView view = view(); + scope = view == null || view.hasPins() ? null : view.scope; + previous = snapshot != null && snapshot.scope.equals(scope) ? snapshot : null; + if (scope == null) { + // Pins or a non-capable configuration: nothing to fetch, so the loop stops. + finishAttempt(); + return; + } + } + Snapshot fetched = null; + String failure = null; + try { + fetched = fetch(scope, previous); + } catch (MetadataException rejected) { + failure = rejected.getMessage(); + } catch (IOException error) { + failure = "metadata fetch failed (" + error.getClass().getSimpleName() + ")"; + } catch (RuntimeException error) { + failure = "metadata document rejected (malformed)"; + } + synchronized (this) { + if (startedGeneration != generation) { + // close() ran meanwhile: discard the result and leave the new cycle's state alone. + return; + } + Instant time = now.get(); + if (fetched != null) { + snapshot = fetched; + failures = 0; + retryNotBefore = Instant.MIN; + announce(fetched, time); + finishAttempt(); + schedule(fetched.cacheSeconds); + return; + } + failures++; + long retry = Math.min(MAX_RETRY_SECONDS, + (long) REFRESH_INTERVAL_SECONDS << Math.min(failures - 1, 4)); + retryNotBefore = time.plusSeconds(retry); + warn(failure, time); + finishAttempt(); + schedule(retry); + } + } + + private void finishAttempt() { + inFlight = false; + completedAttempts++; + notifyAll(); + } + + private void announce(Snapshot fetched, Instant time) { + Set kids = fetched.keys.keySet(); + if (kids.isEmpty()) { + // A well-formed document with no installable key: trust nothing, including the keys + // of the previous document, so a revoke-all document takes effect at once. + warn("metadata document rejected (no usable key)", time); + announcedKids = Set.of(); + return; + } + if (!kids.equals(announcedKids)) { + announcedKids = Set.copyOf(kids); + logger.info("Bedrock principal v2 verifier keys obtained from the metadata document" + + " (kids: {})", String.join(", ", kids)); + } + if (!capabilityWithheld.isEmpty()) { + logger.warn("Bedrock principal v2 keys are now available, but the current Connect" + + " registration ({}) did not advertise " + BedrockPrincipalReadiness.CAPABILITY + + " because the key metadata was unavailable when it connected; it is" + + " advertised after the next reconnect", capabilityWithheld.toString()); + capabilityWithheld.clear(); + } + } + + private void warn(String reason, Instant time) { + if (lastWarning != null && time.isBefore(lastWarning.plus(WARNING_INTERVAL))) return; + lastWarning = time; + Snapshot current = snapshot; + String fallback = current != null && current.usable(time) + ? "keeping the last good keys until their stale window closes" + : "Bedrock principal v2 joins fail closed with METADATA_UNAVAILABLE"; + logger.warn("Bedrock principal v2 key {}; {}", reason, fallback); + } + + private Snapshot fetch(Scope scope, Snapshot previous) throws IOException { + Request.Builder request = new Request.Builder().url(scope.url).get() + .header("Accept", "application/json"); + boolean conditional = previous != null && previous.etag != null; + if (conditional) request.header("If-None-Match", previous.etag); + try (Response response = httpClient.newCall(request.build()).execute()) { + Instant time = now.get(); + if (conditional && response.code() == 304) { + return new Snapshot(scope, previous.keys, previous.etag, time, previous.cacheSeconds); + } + if (!response.isSuccessful()) { + throw new MetadataException("metadata fetch failed (HTTP " + response.code() + ")"); + } + ResponseBody body = response.body(); + if (body == null) throw new MetadataException("metadata fetch failed (empty body)"); + V2Metadata metadata = GSON.fromJson(readBody(body), V2Metadata.class); + return validated(scope, metadata, response.header("ETag"), time); + } + } + + private static Snapshot validated(Scope scope, V2Metadata metadata, String etag, Instant time) + throws MetadataException { + if (metadata == null + || !scope.issuer.equals(metadata.issuer) + || !scope.trustDomain.equals(metadata.trust_domain) + || !scope.audience.equals(metadata.audience)) { + throw new MetadataException("metadata document rejected (scope mismatch)"); + } + if (metadata.keys == null || metadata.keys.size() > METADATA_MAX_KEYS) { + throw new MetadataException("metadata document rejected (key set size)"); + } + Set seen = new HashSet<>(); + Map keys = new LinkedHashMap<>(); + for (V2PublicKey key : metadata.keys) { + // Duplicates are checked across every entry, revoked and skipped ones included, so an + // entry can never shadow or resurrect another with the same kid. + if (key == null || key.kid == null || key.kid.isEmpty() + || key.kid.getBytes(StandardCharsets.UTF_8).length > 128 + || !seen.add(key.kid)) { + throw new MetadataException("metadata document rejected (invalid or duplicate kid)"); + } + Boolean installable = installable(key.state); + // Forward compatibility: an entry of a key type or state this connector does not know + // is skipped, never installed, and does not invalidate the other entries. + if (installable == null || !supportedType(key)) continue; + byte[] raw = decodeKey(key.x); + if (raw == null) { + throw new MetadataException("metadata document rejected (non-canonical key)"); + } + // Revoked and disabled keys stay in the document to explain the rotation, but they are + // never installed as verifier keys. + if (installable) keys.put(key.kid, raw); + } + int cacheSeconds = metadata.cache_max_age_seconds; + if (cacheSeconds <= 0) cacheSeconds = METADATA_DEFAULT_CACHE_SECONDS; + cacheSeconds = Math.min(cacheSeconds, METADATA_MAX_CACHE_SECONDS); + return new Snapshot(scope, Collections.unmodifiableMap(keys), etag, time, cacheSeconds); + } + + /** {@code TRUE} installable, {@code FALSE} known but never installed, {@code null} unknown. */ + private static Boolean installable(String state) { + if (state == null) return null; + switch (state) { + case "current": + case "next": + case "previous": + return Boolean.TRUE; + case "revoked": + case "disabled": + return Boolean.FALSE; + default: + return null; + } + } + + private static boolean supportedType(V2PublicKey key) { + return "OKP".equals(key.kty) && "Ed25519".equals(key.crv) + && "EdDSA".equals(key.alg) && "sig".equals(key.use); + } + + private ConfigView view() { + try { + return ConfigView.from(Objects.requireNonNull(config.get(), "config") + .getBedrockPrincipal()); + } catch (RuntimeException ignored) { + return null; + } + } + + /** Canonical unpadded base64url raw Ed25519 key, shared by pins and metadata keys. */ + private static byte[] decodeKey(String encoded) { + if (encoded == null || encoded.isEmpty() || encoded.indexOf('=') >= 0) return null; + try { + byte[] decoded = Base64.getUrlDecoder().decode(encoded); + if (decoded.length != 32 + || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded) + .equals(encoded)) { + return null; + } + return decoded; + } catch (IllegalArgumentException ignored) { + return null; + } + } + + private static String readBody(ResponseBody body) throws IOException { + try (InputStream input = body.byteStream(); + ByteArrayOutputStream output = new ByteArrayOutputStream()) { + byte[] buffer = new byte[4096]; + int total = 0; + int read; + while ((read = input.read(buffer)) != -1) { + total += read; + if (total > METADATA_BODY_LIMIT_BYTES) { + throw new MetadataException("metadata document rejected (body exceeds limit)"); + } + output.write(buffer, 0, read); + } + return output.toString(StandardCharsets.UTF_8); + } + } + + private static ScheduledExecutorService newRefreshExecutor() { + ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, runnable -> { + Thread thread = new Thread(runnable, "connect-bedrock-principal-keys"); + thread.setDaemon(true); + return thread; + }); + executor.setRemoveOnCancelPolicy(true); + executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false); + return executor; + } + + /** A privacy-safe, operator-facing failure category. */ + private static final class MetadataException extends IOException { + private MetadataException(String reason) { + super(reason); + } + } + + /** The configured trust scope a document is fetched and validated for. */ + private record Scope(HttpUrl url, String issuer, String trustDomain, String audience) { + } + + /** Closed local view of the generation-2 configuration. */ + private static final class ConfigView { + private final Map pins; + private final Scope scope; + + private ConfigView(Map pins, Scope scope) { + this.pins = pins; + this.scope = scope; + } + + private static ConfigView from(ConnectConfig.BedrockPrincipalConfig config) { + if (config == null) return null; + Map pins = config.getPublicKeys() == null + ? Map.of() + : config.getPublicKeys(); + // Only an exact generation-2 require configuration with a valid HTTPS origin fetches. + HttpUrl url = BedrockPrincipalConfiguration.from(config).isCapable() + ? HttpUrl.parse(config.getMetadataOrigin() + config.getMetadataPath()) + : null; + Scope scope = url == null ? null : new Scope( + url, config.getIssuer(), config.getTrustDomain(), config.getAudience()); + return new ConfigView(pins, scope); + } + + private boolean hasPins() { + return !pins.isEmpty(); + } + + private boolean pinsAreUsable() { + for (String encoded : pins.values()) { + if (decodeKey(encoded) == null) return false; + } + return true; + } + } + + /** Immutable published key set; the join path reads nothing else. */ + private static final class Snapshot { + private final Scope scope; + private final Map keys; + private final String etag; + private final Instant fetchedAt; + private final int cacheSeconds; + + private Snapshot( + Scope scope, Map keys, String etag, Instant fetchedAt, + int cacheSeconds) { + this.scope = scope; + this.keys = keys; + this.etag = etag; + this.fetchedAt = fetchedAt; + this.cacheSeconds = cacheSeconds; + } + + /** The advertised {@code cache_max_age_seconds} has elapsed: revalidation is due. */ + private boolean due(Instant time) { + return !time.isBefore(fetchedAt.plusSeconds(cacheSeconds)); + } + + /** Keys present and the bounded stale-while-error window still open. */ + private boolean usable(Instant time) { + return !keys.isEmpty() && time.isBefore( + fetchedAt.plusSeconds((long) cacheSeconds + METADATA_MAX_STALE_SECONDS)); + } + } + + private static final class V2Metadata { + String issuer; + String trust_domain; + String audience; + int cache_max_age_seconds; + List keys; + } + + private static final class V2PublicKey { + String kid; + String kty; + String crv; + String alg; + String use; + String x; + String state; + } +} diff --git a/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalReadiness.java b/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalReadiness.java index e8b6aef90..ed23eecbe 100644 --- a/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalReadiness.java +++ b/core/src/main/java/com/minekube/connect/bedrock/BedrockPrincipalReadiness.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.Base64; import java.util.Comparator; +import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -39,26 +40,97 @@ public enum Transport { private final ConnectConfig config; private final Clock clock; + private final BedrockPrincipalKeySource keySource; + private final Map advertised = new EnumMap<>(Transport.class); public BedrockPrincipalReadiness(ConnectConfig config) { - this(config, Clock.systemUTC()); + this(config, Clock.systemUTC(), null); } BedrockPrincipalReadiness(ConnectConfig config, Clock clock) { + this(config, clock, null); + } + + /** + * Runtime trust view: readiness must account for keys fetched from the metadata document, not + * only for locally pinned ones. + */ + public BedrockPrincipalReadiness( + ConnectConfig config, BedrockPrincipalKeySource keySource) { + this(config, Clock.systemUTC(), keySource); + } + + BedrockPrincipalReadiness( + ConnectConfig config, Clock clock, BedrockPrincipalKeySource keySource) { this.config = Objects.requireNonNull(config, "config"); this.clock = Objects.requireNonNull(clock, "clock"); + this.keySource = keySource; + } + + private boolean metadataSourced() { + try { + ConnectConfig.BedrockPrincipalConfig principal = config.getBedrockPrincipal(); + return keySource != null + && BedrockPrincipalConfiguration.from(principal).isCapable() + && (principal.getPublicKeys() == null || principal.getPublicKeys().isEmpty()); + } catch (RuntimeException ignored) { + return false; + } } public boolean isReady() { try { ConnectConfig.BedrockPrincipalConfig principal = config.getBedrockPrincipal(); - return BedrockPrincipalConfiguration.from(principal).isCapable() - && usablePins(principal.getPublicKeys()); + if (!BedrockPrincipalConfiguration.from(principal).isCapable()) return false; + if (principal.getPublicKeys() != null && !principal.getPublicKeys().isEmpty()) { + return usablePins(principal.getPublicKeys()); + } + return keySource != null && keySource.usable(); } catch (RuntimeException ignored) { return false; } } + /** + * Whether a registration about to be sent may advertise {@link #CAPABILITY}. With metadata-sourced + * keys this first waits a bounded time (at most five seconds) for an in-flight key fetch, so a + * fresh connector advertises v2 as soon as keys are obtainable. Blocking: call it only while + * building a Watch connection or libp2p registration, never on the join path. + */ + public boolean advertise(Transport transport) { + Objects.requireNonNull(transport, "transport"); + boolean ready = isReady(); + if (metadataSourced()) { + if (!ready) { + ready = keySource.awaitUsable(BedrockPrincipalKeySource.MAX_WARM_UP) && isReady(); + } + keySource.capabilityAdvertised(transport, ready); + } + synchronized (advertised) { + advertised.put(transport, ready); + } + return ready; + } + + /** + * True when the last {@link #advertise} on {@code transport} no longer matches readiness, so the + * registration must be redone to add or withdraw {@link #CAPABILITY}. Never blocks. + */ + public boolean refresh(Transport transport) { + Boolean last; + synchronized (advertised) { + last = advertised.get(Objects.requireNonNull(transport, "transport")); + } + return last != null && last != isReady(); + } + + /** Privacy-safe fetch state: source, last successful refresh, freshness, and the kid set. */ + public BedrockPrincipalKeySource.TrustState trustState() { + return keySource == null + ? BedrockPrincipalKeySource.TrustState.none() + : keySource.state(); + } + public byte[] revision() { if (!isReady()) return new byte[0]; try { @@ -72,12 +144,19 @@ public byte[] revision() { update(digest, principal.getMetadataOrigin()); update(digest, principal.getMetadataPath()); update(digest, CORE_VECTOR_SHA256); - principal.getPublicKeys().entrySet().stream() + Map pins = principal.getPublicKeys() == null + ? Map.of() + : principal.getPublicKeys(); + pins.entrySet().stream() .sorted(Map.Entry.comparingByKey(Comparator.naturalOrder())) .forEach(entry -> { update(digest, entry.getKey()); update(digest, entry.getValue()); }); + // Metadata-sourced keys contribute only a fixed source marker next to the configured + // scope hashed above. Connectors of one endpoint fetch at different moments during a + // rotation, and the edge requires equal revisions across the fleet. + if (pins.isEmpty()) update(digest, "metadata"); return digest.digest(); } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable"); diff --git a/core/src/main/java/com/minekube/connect/module/CommonModule.java b/core/src/main/java/com/minekube/connect/module/CommonModule.java index 5c35bd764..f39bd1544 100644 --- a/core/src/main/java/com/minekube/connect/module/CommonModule.java +++ b/core/src/main/java/com/minekube/connect/module/CommonModule.java @@ -42,6 +42,7 @@ import com.minekube.connect.bedrock.BedrockAdmissionCoordinator; import com.minekube.connect.bedrock.BedrockIdentityKeyProvider; import com.minekube.connect.bedrock.BedrockIdentityReadiness; +import com.minekube.connect.bedrock.BedrockPrincipalKeySource; import com.minekube.connect.bedrock.BedrockPrincipalReadiness; import com.minekube.connect.config.ConfigHolder; import com.minekube.connect.config.ConfigLoader; @@ -153,8 +154,10 @@ public BedrockIdentityReadiness bedrockIdentityReadiness( @Provides @Singleton - public BedrockPrincipalReadiness bedrockPrincipalReadiness(ConfigHolder configHolder) { - return new BedrockPrincipalReadiness(configHolder.get()); + public BedrockPrincipalReadiness bedrockPrincipalReadiness( + ConfigHolder configHolder, + BedrockPrincipalKeySource keySource) { + return new BedrockPrincipalReadiness(configHolder.get(), keySource); } @Provides diff --git a/core/src/main/java/com/minekube/connect/register/WatcherRegister.java b/core/src/main/java/com/minekube/connect/register/WatcherRegister.java index 0dc4e0e27..0cb3ecf1a 100644 --- a/core/src/main/java/com/minekube/connect/register/WatcherRegister.java +++ b/core/src/main/java/com/minekube/connect/register/WatcherRegister.java @@ -34,6 +34,7 @@ import com.minekube.connect.bedrock.BedrockAdmissionCoordinator; import com.minekube.connect.bedrock.BedrockIdentityReadiness; import com.minekube.connect.bedrock.BedrockIdentityReadiness.Transport; +import com.minekube.connect.bedrock.BedrockPrincipalReadiness; import com.minekube.connect.network.netty.LocalSession; import com.minekube.connect.tunnel.Tunneler; import com.minekube.connect.tunnel.p2p.Libp2pEndpoint; @@ -67,6 +68,7 @@ public class WatcherRegister { @Inject private SimpleConnectApi api; @Inject private Libp2pEndpoint libp2pEndpoint; @Inject private BedrockIdentityReadiness bedrockIdentityReadiness; + @Inject private BedrockPrincipalReadiness bedrockPrincipalReadiness; @Inject private BedrockAdmissionCoordinator admissionCoordinator; // volatile: written from injection thread (start/stop) and read from the @@ -110,7 +112,13 @@ public boolean isHealthy() { } private void refreshWatchReadiness() { - if (bedrockIdentityReadiness != null && bedrockIdentityReadiness.refresh(Transport.WATCH)) { + boolean identityChanged = bedrockIdentityReadiness != null + && bedrockIdentityReadiness.refresh(Transport.WATCH); + // Signed principal v2 keys can arrive after (or expire during) a connection; reconnect so + // the Connect-Capabilities header matches what this connector can verify. + boolean principalChanged = bedrockPrincipalReadiness != null + && bedrockPrincipalReadiness.refresh(BedrockPrincipalReadiness.Transport.WATCH); + if (identityChanged || principalChanged) { watch(); } } diff --git a/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pEndpointRuntime.java b/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pEndpointRuntime.java index c25c21e91..3160ab1a2 100644 --- a/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pEndpointRuntime.java +++ b/core/src/main/java/com/minekube/connect/tunnel/p2p/Libp2pEndpointRuntime.java @@ -327,7 +327,8 @@ private List principalCapabilities() { } private List framedPrincipalCapabilities(List legacy) { - if (bedrockPrincipalReadiness == null || !bedrockPrincipalReadiness.isReady()) { + if (bedrockPrincipalReadiness == null + || !bedrockPrincipalReadiness.advertise(BedrockPrincipalReadiness.Transport.LIBP2P)) { return legacy; } List framed = new ArrayList<>(legacy); diff --git a/core/src/main/java/com/minekube/connect/watch/WatchClient.java b/core/src/main/java/com/minekube/connect/watch/WatchClient.java index f21f5aeeb..02645efff 100644 --- a/core/src/main/java/com/minekube/connect/watch/WatchClient.java +++ b/core/src/main/java/com/minekube/connect/watch/WatchClient.java @@ -108,7 +108,8 @@ public WebSocket watch(Watcher watcher) { if (bedrockIdentityReadiness.observe(Transport.WATCH)) { request.header(CAPABILITIES_HEADER, BedrockIdentityReadiness.CAPABILITY); } - if (bedrockPrincipalReadiness.isReady()) { + // Bounded warm-up (at most five seconds) so the header reflects obtainable metadata keys. + if (bedrockPrincipalReadiness.advertise(BedrockPrincipalReadiness.Transport.WATCH)) { request.addHeader(CAPABILITIES_HEADER, BedrockPrincipalReadiness.CAPABILITY); } diff --git a/core/src/test/java/com/minekube/connect/bedrock/BedrockPrincipalMetadataKeysTest.java b/core/src/test/java/com/minekube/connect/bedrock/BedrockPrincipalMetadataKeysTest.java new file mode 100644 index 000000000..8be88ae9f --- /dev/null +++ b/core/src/test/java/com/minekube/connect/bedrock/BedrockPrincipalMetadataKeysTest.java @@ -0,0 +1,802 @@ +package com.minekube.connect.bedrock; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.protobuf.ByteString; +import com.minekube.connect.api.logger.ConnectLogger; +import com.minekube.connect.api.player.principal.PrincipalError; +import com.minekube.connect.config.ConnectConfig; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Delayed; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import minekube.connect.v1alpha1.WatchServiceOuterClass.Authentication; +import minekube.connect.v1alpha1.WatchServiceOuterClass.GameProfile; +import minekube.connect.v1alpha1.WatchServiceOuterClass.Player; +import minekube.connect.v1alpha1.WatchServiceOuterClass.Session; +import minekube.connect.v1alpha1.WatchServiceOuterClass.SessionProtocol; +import okhttp3.OkHttpClient; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import okhttp3.mockwebserver.RecordedRequest; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +/** + * Zero-config generation-2 consumer: no {@code public-keys} pins, verifier keys fetched from the + * frozen metadata document by a background refresh that the join path never waits for. + */ +class BedrockPrincipalMetadataKeysTest { + private static final String ISSUER = "minekube-connect-test"; + private static final String TRUST_DOMAIN = "urn:minekube:connect:test:corpus-v2"; + private static final String AUDIENCE = "urn:minekube:connect:test:bedrock-principal:v2"; + private static final String KID = "connect-v2-test"; + private static final String KEY = "diQm8c6MI-Zwn1nie8hq4wqf3mYLuI96uJBC6NHCTDg"; + private static final String OTHER_KEY = key((byte) 7); + private static final String METADATA_PATH = + "/.well-known/minekube-connect/bedrock-principal-v2.json"; + private static final Duration PROMPT = Duration.ofMillis(500); + + private final JsonObject linked = vector("valid-linked"); + private final JsonObject unlinked = vector("valid-unlinked"); + private final Instant verificationTime = verificationTime(linked); + private final AtomicReference now = new AtomicReference<>(verificationTime); + private final ConnectLogger logger = mock(ConnectLogger.class); + private final List sources = new ArrayList<>(); + + @AfterEach + void closeSources() { + sources.forEach(BedrockPrincipalKeySource::close); + } + + @Test + void verifiesSignedProposalUsingFetchedMetadataKeysWithoutPins() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse() + .setHeader("Content-Type", "application/json") + .setHeader("ETag", "\"v1\"") + .setBody(metadata(300, entry(KID, KEY, "current")))); + BedrockPrincipalKeySource keys = backgroundKeys(server, config(Map.of())); + assertTrue(keys.awaitUsable(Duration.ofSeconds(5))); + BedrockPrincipalConsumer consumer = consumer(keys); + + var principal = consumer.verify(session(linked)).orElseThrow(); + + assertEquals(UUID.fromString("123e4567-e89b-12d3-a456-426614174000"), + principal.effectiveGameProfile().uuid()); + assertEquals("JavaOne", principal.effectiveGameProfile().name()); + assertEquals(METADATA_PATH, server.takeRequest().getPath()); + + // A second, different envelope inside cache_max_age reuses the cached document. + assertTrue(consumer.verify(session(unlinked)).isPresent()); + assertEquals(1, server.getRequestCount()); + assertEquals(BedrockPrincipalKeySource.Source.METADATA, keys.state().source()); + assertEquals(Set.of(KID), keys.state().kids()); + assertNotNull(keys.state().lastSuccess()); + verify(logger, times(1)).info(contains("verifier keys obtained"), any(Object[].class)); + } + } + + @Test + void failsClosedWithNamedErrorAndRateLimitedWarningWhenMetadataIsUnreachable() + throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setResponseCode(503)); + server.enqueue(new MockResponse().setResponseCode(503)); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + BedrockPrincipalConsumer consumer = consumer(keys); + + assertEquals(PrincipalError.METADATA_UNAVAILABLE, rejection(consumer, linked)); + scheduler.runImmediate(); + + assertEquals(PrincipalError.METADATA_UNAVAILABLE, rejection(consumer, linked)); + assertEquals(1, server.getRequestCount()); + assertEquals(BedrockPrincipalKeySource.Source.NONE, keys.state().source()); + verify(logger, times(1)).warn(anyString(), contains("HTTP 503"), anyString()); + + // The retry is backed off, and a second failure inside the warning interval is silent. + now.set(now.get().plusSeconds(6)); + assertFalse(keys.usable()); + scheduler.runImmediate(); + assertEquals(2, server.getRequestCount()); + verify(logger, times(1)).warn(anyString(), any(Object[].class)); + verify(logger, never()).info(anyString(), any(Object[].class)); + } + } + + @Test + void joinPathNeverWaitsForTheNetwork() throws Exception { + try (MockWebServer server = new MockWebServer()) { + // Cold: the only response is slow. The join fails fast instead of waiting for it. + server.enqueue(new MockResponse() + .setBody(metadata(1, entry(KID, KEY, "current"))) + .setHeadersDelay(2, TimeUnit.SECONDS)); + BedrockPrincipalKeySource cold = backgroundKeys(server, config(Map.of())); + BedrockPrincipalConsumer coldConsumer = consumer(cold); + assertTimeoutPreemptively(PROMPT, () -> assertEquals( + PrincipalError.METADATA_UNAVAILABLE, rejection(coldConsumer, linked))); + assertNotNull(server.takeRequest(2, TimeUnit.SECONDS), + "the cold join must still schedule a background fetch"); + } + + try (MockWebServer server = new MockWebServer()) { + // Warm: a due refresh is slow, yet joins keep verifying from the snapshot meanwhile. + server.enqueue(new MockResponse().setBody(metadata(1, entry(KID, KEY, "current")))); + server.enqueue(new MockResponse() + .setBody(metadata(1, entry(KID, KEY, "current"))) + .setHeadersDelay(2, TimeUnit.SECONDS)); + BedrockPrincipalKeySource warm = backgroundKeys(server, config(Map.of())); + assertTrue(warm.awaitUsable(Duration.ofSeconds(5))); + now.set(now.get().plusSeconds(2)); + BedrockPrincipalConsumer consumer = consumer(warm); + + assertTimeoutPreemptively(PROMPT, + () -> assertTrue(consumer.verify(session(linked)).isPresent())); + assertNotNull(server.takeRequest(2, TimeUnit.SECONDS)); + assertNotNull(server.takeRequest(1, TimeUnit.SECONDS), + "the due document is refreshed in the background"); + assertTimeoutPreemptively(PROMPT, + () -> assertTrue(consumer.verify(session(unlinked)).isPresent())); + } + } + + @Test + void unknownKidRefreshesInTheBackgroundAndIsRateLimited() throws Exception { + try (MockWebServer server = new MockWebServer()) { + // The first document is valid but lacks the envelope's kid; the kid is the rotation + // signal for one bounded background refresh. + server.enqueue(new MockResponse() + .setBody(metadata(300, entry("retired-kid", OTHER_KEY, "previous")))); + server.enqueue(new MockResponse() + .setBody(metadata(300, entry(KID, KEY, "current")))); + server.enqueue(new MockResponse() + .setBody(metadata(300, entry(KID, KEY, "current")))); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + scheduler.runImmediate(); + + // Fetched moments ago: no second fetch is forced yet, and this join fails TRUST. + assertEquals(PrincipalError.TRUST, rejection(consumer(keys), linked)); + assertEquals(0, scheduler.immediateCount()); + + now.set(now.get().plusSeconds(6)); + assertEquals(PrincipalError.TRUST, rejection(consumer(keys), linked)); + assertEquals(1, scheduler.immediateCount()); + scheduler.runImmediate(); + assertEquals(2, server.getRequestCount()); + + assertTrue(consumer(keys).verify(session(linked)).isPresent()); + assertEquals(Set.of(KID), keys.state().kids()); + + // A further unknown kid right after a forced refresh does not fetch again. + now.set(now.get().plusSeconds(6)); + assertNull(keys.resolve("unknown-kid")); + scheduler.runImmediate(); + assertEquals(3, server.getRequestCount()); + now.set(now.get().plusSeconds(1)); + assertNull(keys.resolve("unknown-kid")); + assertEquals(0, scheduler.immediateCount()); + } + } + + @Test + void revalidatesWithIfNoneMatchAfterCacheMaxAgeWhileStillServingTheSnapshot() + throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse() + .setHeader("ETag", "\"abc\"") + .setBody(metadata(1, entry(KID, KEY, "current")))); + server.enqueue(new MockResponse().setResponseCode(304).setHeader("ETag", "\"abc\"")); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + BedrockPrincipalConsumer consumer = consumer(keys); + assertFalse(keys.usable()); + scheduler.runImmediate(); + assertTrue(consumer.verify(session(linked)).isPresent()); + assertEquals(Duration.ofSeconds(1), scheduler.lastDelay(), + "the background refresh is scheduled at cache expiry"); + + now.set(now.get().plusSeconds(2)); + assertTrue(consumer.verify(session(unlinked)).isPresent()); + scheduler.runImmediate(); + + server.takeRequest(); + RecordedRequest revalidation = server.takeRequest(); + assertEquals("\"abc\"", revalidation.getHeader("If-None-Match")); + assertEquals(2, server.getRequestCount()); + assertTrue(keys.state().fresh()); + } + } + + @Test + void keepsLastGoodKeysOnlyForTheBoundedStaleWindow() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + for (int i = 0; i < 4; i++) server.enqueue(new MockResponse().setResponseCode(503)); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + scheduler.runImmediate(); + + now.set(verificationTime.plusSeconds(300 + 600 - 1)); + assertTrue(keys.usable(), "a due document stays usable inside the stale window"); + scheduler.runImmediate(); + assertTrue(keys.usable(), "a failed refresh keeps the last good keys"); + verify(logger).warn(anyString(), contains("HTTP 503"), contains("last good keys")); + + now.set(verificationTime.plusSeconds(300 + 600)); + assertFalse(keys.usable()); + assertEquals(PrincipalError.METADATA_UNAVAILABLE, rejection(consumer(keys), linked)); + } + } + + @Test + void staticPinsRemainAuthoritativeAndNeverFetch() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + ManualScheduler scheduler = new ManualScheduler(); + ConnectConfig pinned = config(Map.of(KID, KEY)); + BedrockPrincipalKeySource keys = keys(server, pinned, scheduler); + BedrockPrincipalConsumer consumer = new BedrockPrincipalConsumer( + pinned, fixedClock(verificationTime), keys); + + assertTrue(consumer.verify(session(linked)).isPresent()); + assertTrue(keys.awaitUsable(Duration.ofSeconds(5))); + + assertEquals(0, scheduler.scheduled.size()); + assertEquals(0, server.getRequestCount()); + assertEquals(BedrockPrincipalKeySource.Source.STATIC_PINS, keys.state().source()); + } + } + + @Test + void rejectsMetadataWhoseTrustScopeDisagreesWithConfiguration() throws Exception { + assertDocumentRejected(metadata("other-issuer", 300, entry(KID, KEY, "current")), + "scope mismatch"); + } + + @Test + void rejectsDuplicateKidsAcrossAllEntries() throws Exception { + assertDocumentRejected(metadata(300, + entry(KID, KEY, "current"), entry(KID, OTHER_KEY, "revoked")), + "duplicate kid"); + assertDocumentRejected(metadata(300, + entry("other-kid", OTHER_KEY, "current"), + entry(KID, KEY, "revoked"), entry(KID, KEY, "retired-in-a-future-version")), + "duplicate kid"); + } + + @Test + void revokedMetadataKeyIsNeverInstalled() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "revoked")))); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + scheduler.runImmediate(); + + assertEquals(PrincipalError.METADATA_UNAVAILABLE, rejection(consumer(keys), linked)); + verify(logger).warn(anyString(), contains("no usable key"), anyString()); + } + } + + @Test + void revokedKeyFailsTrustWhileAnotherKeyIsCurrent() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, + entry("k1", OTHER_KEY, "current"), entry(KID, KEY, "revoked")))); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + scheduler.runImmediate(); + assertTrue(keys.usable()); + + // The envelope is signed with the revoked key: TRUST, never verified. + assertEquals(PrincipalError.TRUST, rejection(consumer(keys), linked)); + assertEquals(Set.of("k1"), keys.state().kids()); + } + } + + @Test + void skipsEntriesOfUnknownStateOrKeyTypeWithoutRejectingTheDocument() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, + entry("future-state", OTHER_KEY, "staged"), + "{\"kid\":\"future-type\",\"kty\":\"EC\",\"crv\":\"P-256\",\"alg\":\"ES256\"," + + "\"use\":\"sig\",\"x\":\"not-an-ed25519-key\",\"state\":\"current\"}", + entry(KID, KEY, "current")))); + server.enqueue(new MockResponse().setBody(metadata(300, + entry("future-state", OTHER_KEY, "staged")))); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + scheduler.runImmediate(); + + assertTrue(consumer(keys).verify(session(linked)).isPresent()); + assertEquals(Set.of(KID), keys.state().kids()); + + // A document left with no installable key is not a usable trust source. + now.set(now.get().plusSeconds(301)); + keys.usable(); + scheduler.runImmediate(); + assertFalse(keys.usable()); + } + } + + @Test + void metadataFetchIsBoundedToFiveSecondsByTheProductionClient() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse() + .setBody(metadata(300, entry(KID, KEY, "current"))) + .setHeadersDelay(6, TimeUnit.SECONDS)); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + + assertTimeoutPreemptively(Duration.ofMillis(5_500), scheduler::runImmediate); + + assertFalse(keys.usable()); + verify(logger).warn(anyString(), contains("fetch failed"), anyString()); + } + } + + @Test + void redirectsAreNeverFollowed() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setResponseCode(302) + .setHeader("Location", "/elsewhere.json")); + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + scheduler.runImmediate(); + + assertFalse(keys.usable()); + assertEquals(1, server.getRequestCount()); + verify(logger).warn(anyString(), contains("HTTP 302"), anyString()); + } + } + + @Test + void readinessRevisionIsStableAcrossAKeyRotation() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + server.enqueue(new MockResponse().setBody(metadata(300, + entry("rotated", OTHER_KEY, "current"), entry(KID, KEY, "previous")))); + server.enqueue(new MockResponse().setBody(metadata(300, + entry("rotated", OTHER_KEY, "current")))); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + BedrockPrincipalReadiness readiness = new BedrockPrincipalReadiness( + config(Map.of()), fixedClock(verificationTime), keys); + assertFalse(readiness.isReady()); + scheduler.runImmediate(); + byte[] before = readiness.revision(); + assertEquals(32, before.length); + + for (int rotation = 0; rotation < 2; rotation++) { + now.set(now.get().plusSeconds(301)); + assertTrue(readiness.isReady()); + scheduler.runImmediate(); + assertArrayEquals(before, readiness.revision()); + } + assertEquals(Set.of("rotated"), keys.state().kids()); + + BedrockPrincipalReadiness pinned = new BedrockPrincipalReadiness( + config(Map.of(KID, KEY)), fixedClock(verificationTime), keys); + assertFalse(Arrays.equals(before, pinned.revision()), + "static-pin revisions keep hashing the pins"); + } + } + + @Test + void readinessAdvertisesAfterBoundedWarmUpAndReportsFetchState() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + BedrockPrincipalKeySource keys = backgroundKeys(server, config(Map.of())); + BedrockPrincipalReadiness readiness = new BedrockPrincipalReadiness( + config(Map.of()), fixedClock(verificationTime), keys); + + assertTrue(readiness.advertise(BedrockPrincipalReadiness.Transport.WATCH)); + assertTrue(readiness.isReady()); + assertEquals(32, readiness.revision().length); + assertEquals(BedrockPrincipalKeySource.Source.METADATA, readiness.trustState().source()); + assertTrue(readiness.trustState().fresh()); + assertEquals(Set.of(KID), readiness.trustState().kids()); + assertNotNull(readiness.trustState().lastSuccess()); + } + } + + @Test + void withheldCapabilityWarnsOnceWhenKeysArriveLater() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setResponseCode(503)); + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + BedrockPrincipalKeySource keys = backgroundKeys(server, config(Map.of())); + BedrockPrincipalReadiness readiness = new BedrockPrincipalReadiness( + config(Map.of()), fixedClock(verificationTime), keys); + + assertFalse(readiness.advertise(BedrockPrincipalReadiness.Transport.LIBP2P)); + assertEquals(BedrockPrincipalKeySource.Source.NONE, readiness.trustState().source()); + + now.set(now.get().plusSeconds(6)); + assertTrue(keys.awaitUsable(Duration.ofSeconds(5))); + verify(logger, times(1)).warn( + contains("advertised after the next reconnect"), eq("[LIBP2P]")); + assertTrue(readiness.advertise(BedrockPrincipalReadiness.Transport.LIBP2P)); + } + } + + @Test + void withheldCapabilityIsTrackedPerTransport() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setResponseCode(503)); + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + BedrockPrincipalKeySource keys = backgroundKeys(server, config(Map.of())); + BedrockPrincipalReadiness readiness = new BedrockPrincipalReadiness( + config(Map.of()), fixedClock(verificationTime), keys); + + assertFalse(readiness.advertise(BedrockPrincipalReadiness.Transport.WATCH)); + // A libp2p registration that advertised must not clear the Watch's withheld state. + keys.capabilityAdvertised(BedrockPrincipalReadiness.Transport.LIBP2P, true); + + now.set(now.get().plusSeconds(6)); + assertTrue(keys.awaitUsable(Duration.ofSeconds(5))); + verify(logger, times(1)).warn( + contains("advertised after the next reconnect"), eq("[WATCH]")); + } + } + + @Test + void readinessRefreshFlagsAdvertisementsThatNoLongerMatchKeyAvailability() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setResponseCode(503)); + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + for (int i = 0; i < 4; i++) server.enqueue(new MockResponse().setResponseCode(503)); + BedrockPrincipalKeySource keys = backgroundKeys(server, config(Map.of())); + BedrockPrincipalReadiness readiness = new BedrockPrincipalReadiness( + config(Map.of()), fixedClock(verificationTime), keys); + BedrockPrincipalReadiness.Transport watch = BedrockPrincipalReadiness.Transport.WATCH; + + assertFalse(readiness.refresh(watch), "nothing advertised yet: nothing to redo"); + assertFalse(readiness.advertise(watch)); + assertFalse(readiness.refresh(watch)); + + // Keys arrive after the registration withheld v2: up-flip. + now.set(now.get().plusSeconds(6)); + assertTrue(keys.awaitUsable(Duration.ofSeconds(5))); + assertTrue(readiness.refresh(watch)); + assertTrue(readiness.advertise(watch)); + assertFalse(readiness.refresh(watch)); + assertFalse(readiness.refresh(BedrockPrincipalReadiness.Transport.LIBP2P)); + + // Refreshes keep failing until the stale window closes: down-flip. + now.set(now.get().plusSeconds(300 + 600)); + assertTrue(readiness.refresh(watch)); + } + } + + @Test + void closeStopsBackgroundRefreshAndTheNextUseRestartsIt() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + List created = new ArrayList<>(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), () -> { + ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1); + created.add(executor); + return executor; + }); + assertTrue(keys.awaitUsable(Duration.ofSeconds(5))); + + keys.close(); + + assertTrue(created.get(0).isShutdown()); + assertEquals(BedrockPrincipalKeySource.Source.NONE, keys.state().source()); + assertTrue(keys.awaitUsable(Duration.ofSeconds(5))); + assertEquals(2, created.size()); + assertEquals(2, server.getRequestCount()); + } + } + + @Test + void capabilityStillRequiresGenerationTwoRequire() throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(metadata(300, entry(KID, KEY, "current")))); + ConnectConfig config = config(Map.of()); + set(config.getBedrockPrincipal(), "mode", "warn"); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalReadiness readiness = new BedrockPrincipalReadiness( + config, fixedClock(verificationTime), keys(server, config, scheduler)); + + assertFalse(readiness.advertise(BedrockPrincipalReadiness.Transport.WATCH)); + assertEquals(0, scheduler.scheduled.size(), "a non-require config never fetches"); + assertEquals(0, server.getRequestCount()); + } + } + + private void assertDocumentRejected(String document, String reason) throws Exception { + try (MockWebServer server = new MockWebServer()) { + server.enqueue(new MockResponse().setBody(document)); + ManualScheduler scheduler = new ManualScheduler(); + BedrockPrincipalKeySource keys = keys(server, config(Map.of()), scheduler); + assertFalse(keys.usable()); + scheduler.runImmediate(); + + assertFalse(keys.usable()); + assertEquals(PrincipalError.METADATA_UNAVAILABLE, rejection(consumer(keys), linked)); + verify(logger).warn(anyString(), contains(reason), anyString()); + org.mockito.Mockito.clearInvocations(logger); + } + } + + private PrincipalError rejection(BedrockPrincipalConsumer consumer, JsonObject vector) { + return assertThrows(BedrockPrincipalAdmissionException.class, + () -> consumer.verify(session(vector))).error(); + } + + private BedrockPrincipalConsumer consumer(BedrockPrincipalKeySource keys) { + return new BedrockPrincipalConsumer(config(Map.of()), fixedClock(verificationTime), keys); + } + + /** Production refresh thread; only the clock is controlled. */ + private BedrockPrincipalKeySource backgroundKeys(MockWebServer server, ConnectConfig config) { + return keys(server, config, () -> new ScheduledThreadPoolExecutor(1)); + } + + private BedrockPrincipalKeySource keys( + MockWebServer server, ConnectConfig config, ManualScheduler scheduler) { + return keys(server, config, () -> scheduler); + } + + private BedrockPrincipalKeySource keys( + MockWebServer server, ConnectConfig config, + java.util.function.Supplier scheduler) { + BedrockPrincipalKeySource keys = new BedrockPrincipalKeySource( + () -> config, routedTo(server), logger, now::get, scheduler); + sources.add(keys); + return keys; + } + + /** + * Routes the configured HTTPS origin to the mock server with an application interceptor only. + * The source derives its production client (call timeout, no redirects) from this one, so the + * tests exercise exactly those settings. + */ + private static OkHttpClient routedTo(MockWebServer server) { + return new OkHttpClient.Builder().addInterceptor(chain -> chain.proceed( + chain.request().newBuilder() + .url(server.url(chain.request().url().encodedPath())) + .build())).build(); + } + + private static Clock fixedClock(Instant instant) { + return Clock.fixed(instant, ZoneOffset.UTC); + } + + private static Instant verificationTime(JsonObject vector) { + return Instant.ofEpochSecond(vector.get("verification_time_unix").getAsLong()); + } + + private static ConnectConfig config(Map pins) { + ConnectConfig config = new ConnectConfig(); + Object principal = config.getBedrockPrincipal(); + set(principal, "configGeneration", 2); + set(principal, "mode", "require"); + set(principal, "issuer", ISSUER); + set(principal, "trustDomain", TRUST_DOMAIN); + set(principal, "audience", AUDIENCE); + set(principal, "metadataOrigin", "https://metadata.example"); + set(principal, "publicKeys", pins); + return config; + } + + private static String metadata(int cacheSeconds, String... entries) { + return metadata(ISSUER, cacheSeconds, entries); + } + + private static String metadata(String issuer, int cacheSeconds, String... entries) { + return "{" + + "\"issuer\":\"" + issuer + "\"," + + "\"trust_domain\":\"" + TRUST_DOMAIN + "\"," + + "\"audience\":\"" + AUDIENCE + "\"," + + "\"cache_max_age_seconds\":" + cacheSeconds + "," + + "\"keys\":[" + String.join(",", entries) + "]" + + "}"; + } + + private static String entry(String kid, String x, String state) { + return "{" + + "\"kid\":\"" + kid + "\"," + + "\"kty\":\"OKP\"," + + "\"crv\":\"Ed25519\"," + + "\"alg\":\"EdDSA\"," + + "\"use\":\"sig\"," + + "\"x\":\"" + x + "\"," + + "\"state\":\"" + state + "\"" + + "}"; + } + + private static String key(byte fill) { + byte[] raw = new byte[32]; + Arrays.fill(raw, fill); + return Base64.getUrlEncoder().withoutPadding().encodeToString(raw); + } + + private static Session session(JsonObject vector) { + JsonObject context = vector.getAsJsonObject("trusted_context"); + return Session.newBuilder() + .setId(context.get("connect_session_id").getAsString()) + .setPlayer(Player.newBuilder() + .setAddr("127.0.0.1") + .setProfile(GameProfile.newBuilder() + .setId("00000000-0000-0000-0000-000000000099") + .setName("UntrustedCarrier"))) + .setAuth(Authentication.newBuilder().setPassthrough(false)) + .setProtocol(SessionProtocol.SESSION_PROTOCOL_BEDROCK) + .setEndpointId(context.get("endpoint_id").getAsString()) + .setOrganizationId(context.get("organization_id").getAsString()) + .setConnectSessionNonce(ByteString.copyFrom(Base64.getUrlDecoder() + .decode(context.get("connect_session_nonce").getAsString()))) + .setSourceProtocolVersion(context.get("source_protocol_version").getAsInt()) + .setPolicyRevision(context.get("policy_revision").getAsLong()) + .setSignedBedrockPrincipalV2(ByteString.copyFromUtf8( + vector.get("compact_jws").getAsString())) + .build(); + } + + private static JsonObject vector(String name) { + try (var reader = new InputStreamReader(Objects.requireNonNull( + BedrockPrincipalMetadataKeysTest.class.getResourceAsStream( + "/bedrock-principal-v2/core-vectors.json")), StandardCharsets.UTF_8)) { + for (var value : JsonParser.parseReader(reader).getAsJsonArray()) { + if (name.equals(value.getAsJsonObject().get("name").getAsString())) { + return value.getAsJsonObject(); + } + } + throw new AssertionError("missing vector " + name); + } catch (java.io.IOException error) { + throw new AssertionError(error); + } + } + + private static void set(Object target, String name, Object value) { + try { + var field = target.getClass().getDeclaredField(name); + field.setAccessible(true); + field.set(target, value); + } catch (ReflectiveOperationException error) { + throw new AssertionError(error); + } + } + + /** + * Deterministic refresh scheduler: records every scheduled refresh and runs the immediate ones + * only when the test asks, on the test thread. + */ + private static final class ManualScheduler extends ScheduledThreadPoolExecutor { + private final List scheduled = new ArrayList<>(); + + private ManualScheduler() { + super(1); + } + + @Override + public synchronized ScheduledFuture schedule( + Runnable command, long delay, TimeUnit unit) { + Task task = new Task(command, Duration.ofNanos(unit.toNanos(delay))); + scheduled.add(task); + return task; + } + + synchronized long immediateCount() { + return scheduled.stream().filter(Task::runnableNow).count(); + } + + Duration lastDelay() { + synchronized (this) { + return scheduled.get(scheduled.size() - 1).delay; + } + } + + void runImmediate() { + List due; + synchronized (this) { + due = scheduled.stream().filter(Task::runnableNow).toList(); + scheduled.removeAll(due); + } + due.forEach(task -> { + task.done = true; + task.command.run(); + }); + } + } + + private static final class Task implements ScheduledFuture { + private final Runnable command; + private final Duration delay; + private volatile boolean cancelled; + private volatile boolean done; + + private Task(Runnable command, Duration delay) { + this.command = command; + this.delay = delay; + } + + private boolean runnableNow() { + return !cancelled && !done && delay.isZero(); + } + + @Override + public long getDelay(TimeUnit unit) { + return unit.convert(delay); + } + + @Override + public int compareTo(Delayed other) { + return Long.compare(getDelay(TimeUnit.NANOSECONDS), + other.getDelay(TimeUnit.NANOSECONDS)); + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + cancelled = true; + return !done; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public boolean isDone() { + return done || cancelled; + } + + @Override + public Object get() { + return null; + } + + @Override + public Object get(long timeout, TimeUnit unit) { + return null; + } + } +} diff --git a/core/src/test/java/com/minekube/connect/register/WatcherRegisterTest.java b/core/src/test/java/com/minekube/connect/register/WatcherRegisterTest.java index d3ed1b053..19700dcdd 100644 --- a/core/src/test/java/com/minekube/connect/register/WatcherRegisterTest.java +++ b/core/src/test/java/com/minekube/connect/register/WatcherRegisterTest.java @@ -1,6 +1,7 @@ package com.minekube.connect.register; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; @@ -10,6 +11,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -25,6 +27,15 @@ import com.minekube.connect.bedrock.BedrockIdentityReadiness; import com.minekube.connect.bedrock.BedrockIdentityReadiness.Transport; import com.minekube.connect.bedrock.VerifiedBedrockIdentityRegistry; +import com.minekube.connect.bedrock.BedrockPrincipalKeySource; +import com.minekube.connect.bedrock.BedrockPrincipalReadiness; +import com.minekube.connect.config.ConfigHolder; +import com.minekube.connect.tunnel.SessionDialGuard; +import java.util.concurrent.TimeUnit; +import okhttp3.Request; +import okhttp3.WebSocketListener; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; import com.minekube.connect.config.ConnectConfig; import com.minekube.connect.tunnel.p2p.Libp2pEndpoint; import com.minekube.connect.tunnel.Tunneler; @@ -137,6 +148,100 @@ void readinessTransitionReconnectsWatchAndWithdrawsThePreviousRegistration() thr verify(webSocket).close(1000, "watcher is reconnecting"); } + @Test + void principalKeysArrivingAfterConnectReconnectWatchWithTheV2Capability() throws Exception { + try (MockWebServer server = new MockWebServer()) { + // The warm-up fetch fails, so the first Watch connection withholds v2; the key + // source's background retry then obtains the keys. + server.enqueue(new MockResponse().setResponseCode(503)); + server.enqueue(new MockResponse().setBody(principalMetadata())); + ConnectConfig config = principalConfig(); + ConfigHolder holder = new ConfigHolder(); + holder.set(config); + OkHttpClient routed = new OkHttpClient.Builder().addInterceptor(chain -> chain.proceed( + chain.request().newBuilder() + .url(server.url(chain.request().url().encodedPath())) + .build())).build(); + BedrockPrincipalKeySource keys = new BedrockPrincipalKeySource( + holder, routed, mock(ConnectLogger.class)); + try { + BedrockPrincipalReadiness readiness = new BedrockPrincipalReadiness(config, keys); + OkHttpClient watchHttp = mock(OkHttpClient.class); + when(watchHttp.newWebSocket(any(Request.class), any(WebSocketListener.class))) + .thenReturn(mock(WebSocket.class)); + Fixture fixture = newFixture(); + inject(fixture.register, "watchClient", new WatchClient( + watchHttp, + config, + new BedrockIdentityReadiness(config, + new BedrockIdentityKeyProvider(config, new OkHttpClient())), + readiness, + null, + new SessionDialGuard())); + inject(fixture.register, "bedrockPrincipalReadiness", readiness); + register = fixture.register; + register.start(); + + invokeRefreshWatchReadiness(register); + List watches = watchRequests(watchHttp, 1); + assertFalse(capabilities(watches.get(0)).contains(BedrockPrincipalReadiness.CAPABILITY)); + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15); + while (!readiness.isReady() && System.nanoTime() < deadline) { + Thread.sleep(50); + } + assertTrue(readiness.isReady(), "the background retry obtains the keys"); + // The periodic readiness check may have reconnected already; either way the + // latest connection advertises v2. + invokeRefreshWatchReadiness(register); + watches = watchRequests(watchHttp, 2); + assertTrue(capabilities(watches.get(watches.size() - 1)) + .contains(BedrockPrincipalReadiness.CAPABILITY)); + + invokeRefreshWatchReadiness(register); + assertEquals(watches.size(), watchRequests(watchHttp, 2).size(), + "an unchanged advertisement does not reconnect again"); + } finally { + keys.close(); + } + } + } + + private static List watchRequests(OkHttpClient watchHttp, int minimum) { + ArgumentCaptor requests = ArgumentCaptor.forClass(Request.class); + verify(watchHttp, atLeast(minimum)).newWebSocket( + requests.capture(), any(WebSocketListener.class)); + return requests.getAllValues(); + } + + private static List capabilities(Request request) { + return request.headers("Connect-Capabilities"); + } + + private static ConnectConfig principalConfig() throws Exception { + ConnectConfig config = new ConnectConfig(); + Object principal = config.getBedrockPrincipal(); + setField(principal, "configGeneration", 2); + setField(principal, "mode", "require"); + setField(principal, "issuer", "minekube-connect-test"); + setField(principal, "trustDomain", "urn:minekube:connect:test:corpus-v2"); + setField(principal, "audience", "urn:minekube:connect:test:bedrock-principal:v2"); + setField(principal, "metadataOrigin", "https://metadata.example"); + setField(principal, "publicKeys", Map.of()); + return config; + } + + private static String principalMetadata() { + return "{\"issuer\":\"minekube-connect-test\"," + + "\"trust_domain\":\"urn:minekube:connect:test:corpus-v2\"," + + "\"audience\":\"urn:minekube:connect:test:bedrock-principal:v2\"," + + "\"cache_max_age_seconds\":300," + + "\"keys\":[{\"kid\":\"connect-v2-test\",\"kty\":\"OKP\"," + + "\"crv\":\"Ed25519\",\"alg\":\"EdDSA\",\"use\":\"sig\"," + + "\"x\":\"diQm8c6MI-Zwn1nie8hq4wqf3mYLuI96uJBC6NHCTDg\"," + + "\"state\":\"current\"}]}"; + } + @Test void stopBeforeStartDoesNotCreateScheduler() throws Exception { WatcherRegister register = new WatcherRegister(); diff --git a/docs/bedrock-identity.md b/docs/bedrock-identity.md index 61da64caa..46ea6e134 100644 --- a/docs/bedrock-identity.md +++ b/docs/bedrock-identity.md @@ -8,7 +8,10 @@ advertise generation-2 capability. ## Signed principal v2 New generated configuration includes `bedrock-principal.config-generation: 2` and `mode: require`, -with an empty `public-keys` map until host integration supplies usable pins. The v2 consumer accepts +with an empty `public-keys` map. An empty map means "zero config": the consumer fetches the frozen +well-known document at `metadata-origin + metadata-path` +(`/.well-known/minekube-connect/bedrock-principal-v2.json`) instead of requiring pins. The v2 +consumer accepts the compact signed principal only from authenticated Watch `Session` or libp2p `SessionOffer` field 12 (`signed_bedrock_principal_v2`); a game-profile property with the reserved v2 name is rejected. It verifies the closed schema, Ed25519 signature, proposal bindings, time bounds, identity/link @@ -16,7 +19,8 @@ invariants, and an atomic one-use replay key before applying the verifier-select A linked Java profile always takes precedence over the derived Bedrock profile. The connector advertises `bedrock-verified-principal-v2` only when generation 2 is in `require` -mode and its trust configuration and static Ed25519 pins are usable. Watch readiness challenges +mode, its trust configuration is capable, and usable trust material is available: either usable +static Ed25519 pins or a metadata document inside its stale window. Watch readiness challenges are answered on their authenticated lease. Libp2p first negotiates `kind-prefixed-v1` framing on a successful legacy renewal, then answers challenges on that same registration stream. Losing configuration, keys, framing, or the stream fails closed and suppresses operational readiness. @@ -36,6 +40,57 @@ bedrock-principal: "": "" ``` +Static pins are authoritative: they are the complete trust set, and a connector with pins never +fetches the metadata document. Leave `public-keys` empty for zero-config operation. + +### Runtime key document (no pins) + +With an empty `public-keys` map the connector fetches +`metadata-origin + metadata-path` over HTTPS. The document must carry the configured `issuer`, +`trust_domain`, and `audience`, plus a bounded `keys` array (at most 16 entries, body at most +64 KiB) of Ed25519 verification keys (`kid`, `kty: OKP`, `crv: Ed25519`, `alg: EdDSA`, +`use: sig`, canonical unpadded base64url `x`, and a `state`). Only `current`, `next`, and +`previous` keys are installed; `revoked` and `disabled` keys are never installed, so a revoked +key cannot verify a principal. Every `kid` must be unique across all entries, revoked ones +included, or the whole document is rejected. An entry with an unknown `state` or an unsupported +key type is skipped (never installed) without rejecting the other entries; a document left +without any installable key is not a usable trust source. + +Opting in needs only `config-generation: 2` and `mode: require` with an empty `public-keys` map. +Do not opt in on an endpoint that does not belong to an organization: the edge sends no signed +principal there, and `require` mode then refuses every Bedrock join. + +- Fetching runs on one background daemon thread (`connect-bedrock-principal-keys`) with at most + one request in flight. Joins never wait for the network: they read the last published key set + only. A missing or expired set fails that join with `METADATA_UNAVAILABLE`, and a `kid` the set + does not contain fails it with `TRUST`; both schedule a background refresh instead of blocking. +- `cache_max_age_seconds` (capped at 300) sets the refresh schedule. The connector refreshes in + the background at expiry even without joins, revalidating with the document `ETag`, so a `304` + keeps the cached keys without a body transfer. +- An envelope whose `kid` is not in the cached document triggers one rate-limited background + refresh (not within five seconds of the last fetch), which is how a published rotation is + picked up without restarting the connector. The join that carried the new `kid` may fail + `TRUST`; later joins verify once the refresh lands. +- A fetch is bounded to five seconds and never follows redirects. When refreshes fail, the last + good keys keep verifying for a bounded stale window of 600 seconds after expiry; after that the + connector fails closed. A revoked key is therefore dropped at most `cache_max_age_seconds` + plus the 600-second stale window after the document revokes it. +- The only blocking wait is a bounded warm-up of at most five seconds while the Watch connection + or libp2p registration is being built, so a starting connector advertises + `bedrock-verified-principal-v2` as soon as the document is obtainable. If no keys were + available then, the connector logs one warning per withheld transport when keys arrive. The + Watch connection reconnects within about five seconds whenever key availability no longer + matches what it advertised (keys arrived, or the stale window closed); a libp2p registration + picks the change up when it next registers. +- With no usable pins and no usable document, admission fails closed with + `METADATA_UNAVAILABLE`; the connector does not advertise `bedrock-verified-principal-v2`. + A failed fetch or rejected document is logged as a rate-limited warning, and the first key set + obtained (and each changed `kid` set) is logged once at info level, without key material. +- Readiness exposes the fetch state: source (`STATIC_PINS`, `METADATA`, `NONE`), last successful + refresh, freshness, and the trusted `kid` set. The readiness revision covers the configured trust + scope and a fixed metadata source marker, not the fetched keys, so every connector of one + endpoint reports the same revision while a rotation propagates. + Verification failures expose only the bounded `PrincipalError` category. Compact envelopes, nonces, replay IDs, XUIDs, and link material are excluded from exception messages, stack traces, principal `toString()` output, and sanitized session proposals.