001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.jose; 018 019import com.google.errorprone.annotations.CheckReturnValue; 020import com.revetsec.OutboundUriPolicy; 021import com.revetsec.internal.Limits; 022import com.revetsec.internal.ObserverDispatch; 023import com.revetsec.internal.http.Deadline; 024import com.revetsec.internal.http.HttpClientChecks; 025import com.revetsec.internal.http.HttpExchange; 026import com.revetsec.internal.http.RuntimeFloor; 027import com.revetsec.internal.http.UriChecks; 028import com.revetsec.internal.jose.KeyQuery; 029import com.revetsec.internal.jose.KeySelection; 030import org.jspecify.annotations.NonNull; 031import org.jspecify.annotations.Nullable; 032 033import javax.annotation.concurrent.NotThreadSafe; 034import javax.annotation.concurrent.ThreadSafe; 035import java.net.URI; 036import java.net.http.HttpClient; 037import java.time.Clock; 038import java.time.Duration; 039 040import static java.util.Objects.requireNonNull; 041 042/** 043 * A JSON Web Key Set fetched from a URI and cached, such as an OpenID provider's {@code jwks_uri}. 044 * <p> 045 * <strong>Lazy, on the caller's thread.</strong> {@link Builder#build()} does no I/O, creates no HTTP client and starts 046 * no thread. The first call that needs a key, or {@link #warmUp()}, fetches the key set on the calling thread, and 047 * concurrent callers wait for that one fetch, each within its own deadline: a validation's is this source's request 048 * timeout. Revetsec starts no thread of its own; the JDK's HTTP client runs its own, as it always does. 049 * <p> 050 * <strong>Caching.</strong> A fetched key set stays fresh for a time to live taken from the response's 051 * {@code Cache-Control} ({@code max-age}; {@code no-store} and {@code no-cache} mean the minimum) or {@code Expires}, 052 * clamped to the minimum and maximum time to live, or for the default time to live when the response has neither. 053 * There are no conditional requests. After it expires, the next call that needs a key fetches it again. A key set in 054 * which every key was skipped is still a key set, so an identity provider can withdraw all its keys; each skipped key 055 * is reported to {@link JoseObserver#didSkipJwk(URI, Integer, JwkSkipReason)} on every fetch. 056 * <p> 057 * <strong>Unknown keys.</strong> A token whose key is not in a fresh key set (an unknown {@code kid}, or no key that 058 * fits a token without one) refreshes the key set early, at most once per unknown-key refresh cooldown. The cooldown 059 * holds back only these refreshes: the first fetch, {@link #warmUp()} and refreshes after expiry neither wait for it 060 * nor start it, so a key an identity provider starts using just after a scheduled fetch is fetched at once. A request 061 * sent for an unknown key keeps its cooldown whatever its outcome. A key named by the token's {@code kid} that does not 062 * fit the token's algorithm, or two keys that fit, never cause a refresh. 063 * <p> 064 * <strong>Failures.</strong> A failed fetch, a timeout included, starts a backoff that every fetch respects, 065 * {@link #warmUp()} included: the unknown-key cooldown, doubled after each further failure up to ten cooldowns (at 066 * most 10 minutes), which is 30, 60, 120, 240 and then 300 seconds at the default cooldown. A {@code Retry-After} on a 067 * 429 or 503 may lengthen a step, up to that cap. A successful fetch does not reset the backoff: the failure count 068 * falls by one for each full cap interval without a failure. During a backoff no request is sent, and each call that 069 * would have fetched is reported to {@link JoseObserver#didSuppressJwksFetch(URI, Duration)}. At the 070 * defaults, one endpoint that keeps failing gets at most 15 requests in its first hour, and 12 an hour after that. 071 * <p> 072 * <strong>Request limit.</strong> No more than two requests of any kind start within one cooldown. 073 * {@link Builder#build()} refuses a cooldown longer than the minimum time to live, so each successful fetch leaves a 074 * key set fresh for at least one cooldown, and each failed one starts a backoff of at least one cooldown. The 075 * unknown-key cooldown, the backoff and the time to live therefore keep requests within this limit on their own, and 076 * it holds back no call, a refresh after expiry included, unless fetches were cut short: by an interrupt, by an 077 * {@link Error}, or by a leader held past the longest a fetch may take, as a slow observer can hold it. A call the 078 * limit holds back sends nothing and is reported to 079 * {@link JoseObserver#didSuppressJwksFetch(URI, Duration)}: an expired key set answers it for the keys it 080 * holds, a call for an unknown key gets no key, and any other call throws a transient 081 * {@link JwksUnavailableException} of category {@link com.revetsec.ErrorCategory#TRANSPORT} with no cause. 082 * <p> 083 * <strong>Stale keys.</strong> While refreshes fail or are held back, an expired key set still answers, for the keys 084 * it holds, until the maximum staleness after its expiry, provided the cached snapshot remains retained. 085 * An observed clock rollback discards the snapshot entirely, including otherwise eligible stale keys. A failed 086 * refresh after rollback has no stale fallback; only a later successful fetch establishes another snapshot. 087 * Catching up the wall clock does not revive the discarded material. Other calls throw {@link JwksUnavailableException}. 088 * <p> 089 * <strong>Time.</strong> The time to live, cooldown, backoff and staleness follow the configured {@link Clock}. An 090 * instant recorded in the future of the clock's current time counts as passed. Any observed backward step 091 * discards the cached key set, even inside its original fresh/stale window, and never extends that old window. Deadlines and elapsed times use {@link System#nanoTime()}. 092 * <p> 093 * <strong>Bound to one URI, not to an issuer.</strong> Share an instance only among validators that expect the same 094 * issuer, because every key in it is trusted for any token they check. Sources compare by reference. 095 * {@link #toString()} shows the URI cut to its scheme, host, port and path, and the settings. 096 * 097 * @author <a href="https://www.revetkn.com">Mark Allen</a> 098 * @since 1.0.0 099 */ 100@ThreadSafe 101public final class RemoteJwksSource implements JwksSource { 102 @NonNull 103 private final URI uri; 104 @NonNull 105 private final HttpExchange httpExchange; 106 @NonNull 107 private final JwksSettings settings; 108 @NonNull 109 private final JwksCache cache; 110 111 /** 112 * Creates a source from settings and a URI that were already checked: the form {@link Builder#build()} uses, and 113 * a later milestone's component that embeds a key source. It does no I/O and does not check the URI again; a URI 114 * the exchange refuses fails each fetch with {@link com.revetsec.ErrorCategory#CONFIGURATION}. 115 * 116 * @param uri the key set's URI 117 * @param httpExchange the component's exchange helper 118 * @param settings the checked settings 119 */ 120 RemoteJwksSource(@NonNull URI uri, 121 @NonNull HttpExchange httpExchange, 122 @NonNull JwksSettings settings) { 123 this.uri = requireNonNull(uri); 124 this.httpExchange = requireNonNull(httpExchange); 125 this.settings = requireNonNull(settings); 126 this.cache = new JwksCache(uri, httpExchange, settings); 127 } 128 129 /** 130 * Starts building a source for the key set at {@code uri}. 131 * 132 * @param uri the key set's URI: absolute, {@code https} (or {@code http} to a loopback host where allowed), with no 133 * user information and no fragment, and permitted by the outbound URI policy; a query is allowed. 134 * {@link Builder#build()} checks it 135 * @return a new builder 136 * @throws NullPointerException if {@code uri} is {@code null} 137 * @since 1.0.0 138 */ 139 @NonNull 140 public static Builder withUri(@NonNull URI uri) { 141 return new Builder(uri); 142 } 143 144 void warmUp(java.util.function.@NonNull LongSupplier remainingNanos) { 145 this.cache.warmUp(Deadline.fromNow(Duration.ofNanos(Math.max(0, remainingNanos.getAsLong())))); 146 } 147 148 /** 149 * Fetches the key set now, unless a fresh one is cached (even one with no usable key), so the first validation 150 * does not wait for it. It waits for a fetch another caller already started instead of starting its own. It 151 * follows the backoff after a failure, throwing that failure without sending a request, and the limit of two 152 * requests per cooldown, but not the unknown-key cooldown, which it neither waits for nor starts. It waits at most 153 * the request timeout. 154 * 155 * @throws JwksUnavailableException if the fetch failed, a recent failure or the request limit held it 156 * back, or the wait ended, even when an expired key set is still cached 157 * @since 1.0.0 158 */ 159 public void warmUp() { 160 this.cache.warmUp(Deadline.fromNow(this.settings.requestTimeout())); 161 } 162 163 /** 164 * Returns the key set's URI. 165 * 166 * @return the URI, as configured 167 * @since 1.0.0 168 */ 169 @NonNull 170 public URI getUri() { 171 return this.uri; 172 } 173 174 /** 175 * Selects the key for {@code query} within this source's request timeout: the standalone form a validator uses. 176 * 177 * @param query the token's algorithm, key ID and effective algorithm set 178 * @return the selection, after at most one completed fetch 179 * @throws JwksUnavailableException if no usable key set is available for this call 180 */ 181 @NonNull 182 KeySelection select(@NonNull KeyQuery query) { 183 return select(query, Deadline.fromNow(this.settings.requestTimeout())); 184 } 185 186 /** 187 * Selects the key for {@code query} within {@code deadline}: the form a caller with its own budget uses. A fetch 188 * this call leads that its deadline ends counts as a failed fetch, like any other timeout. 189 * 190 * @param query the token's algorithm, key ID and effective algorithm set 191 * @param deadline the caller's deadline, which bounds any fetch or wait 192 * @return the selection, after at most one completed fetch 193 * @throws JwksUnavailableException if no usable key set is available for this call 194 */ 195 @NonNull 196 KeySelection select(@NonNull KeyQuery query, 197 @NonNull Deadline deadline) { 198 return this.cache.select(query, deadline); 199 } 200 201 /** 202 * Test seam (plan A-2): this source's key-set cache, whose 203 * {@link JwksCache#awaitWaitersForTests(Integer, Duration)} waits until callers have joined a fetch another caller 204 * leads. 205 * 206 * @return this source's key-set cache 207 */ 208 @NonNull 209 JwksCache cacheForTests() { 210 return this.cache; 211 } 212 213 /** 214 * The exchange helper, for the zero-thread and single-client checks. 215 */ 216 @NonNull 217 HttpExchange httpExchangeForTests() { 218 return this.httpExchange; 219 } 220 221 /** 222 * Describes the source by its URI, cut to its scheme, host, port and path, and its settings. 223 * 224 * @return the description 225 * @since 1.0.0 226 */ 227 @Override 228 @NonNull 229 public String toString() { 230 return getClass().getSimpleName() + "{uri=" + this.cache.getReportedUri() + ", " + this.settings + "}"; 231 } 232 233 /** 234 * Builds a {@link RemoteJwksSource}. 235 * <p> 236 * Each setter stores its value, and {@link #build()} checks them all, in this order: each setting against its 237 * range, then the time-to-live order, then the unknown-key refresh cooldown against the minimum time to live; the 238 * minimum Java runtime; an injected client's redirect policy; then the URI. 239 * {@code null} restores a setting's default. Nothing here does I/O. 240 * 241 * @author <a href="https://www.revetkn.com">Mark Allen</a> 242 * @since 1.0.0 243 */ 244 @NotThreadSafe 245 @CheckReturnValue 246 public static final class Builder { 247 @NonNull 248 private final URI uri; 249 @Nullable 250 private HttpClient httpClient; 251 @Nullable 252 private OutboundUriPolicy outboundUriPolicy; 253 @Nullable 254 private Boolean allowInsecureLoopback; 255 @Nullable 256 private Clock clock; 257 @Nullable 258 private Duration requestTimeout; 259 @Nullable 260 private Duration minimumTimeToLive; 261 @Nullable 262 private Duration defaultTimeToLive; 263 @Nullable 264 private Duration maximumTimeToLive; 265 @Nullable 266 private Duration unknownKeyRefreshCooldown; 267 @Nullable 268 private Duration maximumStaleness; 269 @Nullable 270 private Integer maximumResponseBytes; 271 @Nullable 272 private Integer maximumKeys; 273 @Nullable 274 private JoseObserver observer; 275 @Nullable 276 private Boolean acknowledgeUnpatchedRuntime; 277 278 private Builder(@NonNull URI uri) { 279 this.uri = requireNonNull(uri); 280 } 281 282 /** 283 * Sets the HTTP client to fetch with. Build rejects redirect following, an Authenticator or a CookieHandler 284 * without sending a request. The application owns injected TLS/proxy configuration and egress beyond URI checks. 285 * 286 * @param httpClient a client using Redirect.NEVER, with no Authenticator or CookieHandler; {@code null} restores the default, a process-wide 287 * client Revetsec creates on the first fetch 288 * @return this builder 289 * @since 1.0.0 290 */ 291 @NonNull 292 public Builder httpClient(@Nullable HttpClient httpClient) { 293 this.httpClient = httpClient; 294 return this; 295 } 296 297 /** 298 * Sets the policy the URI must pass. 299 * 300 * @param outboundUriPolicy the policy; {@code null} restores the default, 301 * {@link OutboundUriPolicy#defaultInstance()} 302 * @return this builder 303 * @since 1.0.0 304 */ 305 @NonNull 306 public Builder outboundUriPolicy(@Nullable OutboundUriPolicy outboundUriPolicy) { 307 this.outboundUriPolicy = outboundUriPolicy; 308 return this; 309 } 310 311 /** 312 * Sets whether plain {@code http} is allowed to a loopback address or to exactly {@code localhost}, for tests. 313 * A request to {@code localhost} reaches loopback only as the host's name resolution decides, which usually 314 * means its hosts file. 315 * 316 * @param allowInsecureLoopback whether to allow it; {@code null} restores the default, {@code false} 317 * @return this builder 318 * @since 1.0.0 319 */ 320 @NonNull 321 public Builder allowInsecureLoopback(@Nullable Boolean allowInsecureLoopback) { 322 this.allowInsecureLoopback = allowInsecureLoopback; 323 return this; 324 } 325 326 /** 327 * Sets the clock for the time to live, cooldown, backoff and staleness. Outside tests, keep the default: a 328 * clock that stands still never lets the key set expire. 329 * 330 * @param clock the clock; {@code null} restores the default, {@link Clock#systemUTC()} 331 * @return this builder 332 * @since 1.0.0 333 */ 334 @NonNull 335 public Builder clock(@Nullable Clock clock) { 336 this.clock = clock; 337 return this; 338 } 339 340 /** 341 * Sets how long one fetch may take, which is also the deadline of a standalone call. 342 * 343 * @param requestTimeout from 1 to 60 seconds; {@code null} restores the default, 10 seconds 344 * @return this builder 345 * @since 1.0.0 346 */ 347 @NonNull 348 public Builder requestTimeout(@Nullable Duration requestTimeout) { 349 this.requestTimeout = requestTimeout; 350 return this; 351 } 352 353 /** 354 * Sets the shortest time a fetched key set is cached, whatever its cache headers say. It must be at least the 355 * unknown-key refresh cooldown, so that the limit of two requests per cooldown holds back no refresh after 356 * expiry unless fetches were cut short; {@link #build()} checks that. 357 * 358 * @param minimumTimeToLive from 30 seconds to 1 hour, and no shorter than the unknown-key refresh cooldown; 359 * {@code null} restores the default, 1 minute 360 * @return this builder 361 * @since 1.0.0 362 */ 363 @NonNull 364 public Builder minimumTimeToLive(@Nullable Duration minimumTimeToLive) { 365 this.minimumTimeToLive = minimumTimeToLive; 366 return this; 367 } 368 369 /** 370 * Sets the time a fetched key set is cached when its response has neither {@code max-age} nor {@code Expires}. 371 * 372 * @param defaultTimeToLive from 30 seconds to 24 hours; {@code null} restores the default, 10 minutes 373 * @return this builder 374 * @since 1.0.0 375 */ 376 @NonNull 377 public Builder defaultTimeToLive(@Nullable Duration defaultTimeToLive) { 378 this.defaultTimeToLive = defaultTimeToLive; 379 return this; 380 } 381 382 /** 383 * Sets the longest time a fetched key set is cached, whatever its cache headers say. 384 * 385 * @param maximumTimeToLive from 1 minute to 24 hours; {@code null} restores the default, 6 hours 386 * @return this builder 387 * @since 1.0.0 388 */ 389 @NonNull 390 public Builder maximumTimeToLive(@Nullable Duration maximumTimeToLive) { 391 this.maximumTimeToLive = maximumTimeToLive; 392 return this; 393 } 394 395 /** 396 * Sets the shortest time between two refreshes that tokens with unknown key IDs trigger. It is also the first 397 * step of the backoff after a failed fetch, and the window of the limit of two requests of any kind. It must be 398 * no longer than the minimum time to live, so that this limit holds back no refresh after expiry unless fetches 399 * were cut short; {@link #build()} checks that. 400 * 401 * @param unknownKeyRefreshCooldown from 1 second to 10 minutes, and no longer than the minimum time to live; 402 * {@code null} restores the default, 30 seconds 403 * @return this builder 404 * @since 1.0.0 405 */ 406 @NonNull 407 public Builder unknownKeyRefreshCooldown(@Nullable Duration unknownKeyRefreshCooldown) { 408 this.unknownKeyRefreshCooldown = unknownKeyRefreshCooldown; 409 return this; 410 } 411 412 /** 413 * Sets how long after it expires a key set may still answer for the keys it holds, while refreshes fail or are 414 * held back. 415 * 416 * @param maximumStaleness from zero, which never serves an expired key set, to 24 hours; {@code null} restores 417 * the default, 12 hours 418 * @return this builder 419 * @since 1.0.0 420 */ 421 @NonNull 422 public Builder maximumStaleness(@Nullable Duration maximumStaleness) { 423 this.maximumStaleness = maximumStaleness; 424 return this; 425 } 426 427 /** 428 * Sets the largest key set response body accepted, in bytes. 429 * 430 * @param maximumResponseBytes from 16 KiB to 4 MiB; {@code null} restores the default, 256 KiB 431 * @return this builder 432 * @since 1.0.0 433 */ 434 @NonNull 435 public Builder maximumResponseBytes(@Nullable Integer maximumResponseBytes) { 436 this.maximumResponseBytes = maximumResponseBytes; 437 return this; 438 } 439 440 /** 441 * Sets the most keys a key set may hold, counting every element of its {@code keys} array, usable or not. 442 * 443 * @param maximumKeys from 1 to 1,000; {@code null} restores the default, 100 444 * @return this builder 445 * @since 1.0.0 446 */ 447 @NonNull 448 public Builder maximumKeys(@Nullable Integer maximumKeys) { 449 this.maximumKeys = maximumKeys; 450 return this; 451 } 452 453 /** 454 * Sets the observer that receives this source's events. 455 * 456 * @param observer the observer; {@code null} restores the default, {@link JoseObserver#disabledInstance()} 457 * @return this builder 458 * @since 1.0.0 459 */ 460 @NonNull 461 public Builder observer(@Nullable JoseObserver observer) { 462 this.observer = observer; 463 return this; 464 } 465 466 /** 467 * Sets whether to allow a Java runtime below Revetsec's minimum for network I/O (17.0.3, or 18.0.1 on Java 18), 468 * whose TLS and certificate checks are exposed to CVE-2022-21449. The choice is reported to 469 * {@link JoseObserver#didUseUnpatchedRuntime(String)} when the source is built and on every fetch. 470 * 471 * @param acknowledgeUnpatchedRuntime whether to accept the risk; {@code null} restores the default, 472 * {@code false} 473 * @return this builder 474 * @since 1.0.0 475 */ 476 @NonNull 477 public Builder acknowledgeUnpatchedRuntime(@Nullable Boolean acknowledgeUnpatchedRuntime) { 478 this.acknowledgeUnpatchedRuntime = acknowledgeUnpatchedRuntime; 479 return this; 480 } 481 482 /** 483 * Builds the source, with no I/O. 484 * 485 * @return a new source 486 * @throws IllegalArgumentException if a setting is out of range, the time-to-live settings are not ordered 487 * minimum, default, maximum, the unknown-key refresh cooldown is longer than 488 * the minimum time to live, the injected client follows redirects, or the URI 489 * is not permitted 490 * @throws IllegalStateException if the Java runtime is below Revetsec's minimum for network I/O and that was 491 * not acknowledged 492 * @since 1.0.0 493 */ 494 @NonNull 495 public RemoteJwksSource build() { 496 return build(Runtime.version()); 497 } 498 499 /** 500 * {@link #build()} for a given runtime version, so tests can check the runtime floor. 501 */ 502 @NonNull 503 RemoteJwksSource build(Runtime.@NonNull Version runtimeVersion) { 504 requireNonNull(runtimeVersion); 505 506 Duration timeout = Limits.REQUEST_TIMEOUT.require(orDefault(this.requestTimeout, 507 Limits.REQUEST_TIMEOUT.getDefaultDuration())); 508 Duration minimum = Limits.JWKS_MINIMUM_TIME_TO_LIVE.require(orDefault(this.minimumTimeToLive, 509 Limits.JWKS_MINIMUM_TIME_TO_LIVE.getDefaultDuration())); 510 Duration standard = Limits.JWKS_DEFAULT_TIME_TO_LIVE.require(orDefault(this.defaultTimeToLive, 511 Limits.JWKS_DEFAULT_TIME_TO_LIVE.getDefaultDuration())); 512 Duration maximum = Limits.JWKS_MAXIMUM_TIME_TO_LIVE.require(orDefault(this.maximumTimeToLive, 513 Limits.JWKS_MAXIMUM_TIME_TO_LIVE.getDefaultDuration())); 514 Duration cooldown = Limits.JWKS_UNKNOWN_KEY_ID_COOLDOWN.require(orDefault(this.unknownKeyRefreshCooldown, 515 Limits.JWKS_UNKNOWN_KEY_ID_COOLDOWN.getDefaultDuration())); 516 Duration staleness = Limits.JWKS_MAXIMUM_STALENESS.require(orDefault(this.maximumStaleness, 517 Limits.JWKS_MAXIMUM_STALENESS.getDefaultDuration())); 518 int responseBytes = this.maximumResponseBytes == null ? Limits.JWKS_RESPONSE_BODY_SIZE.getDefaultIntValue() 519 : Limits.JWKS_RESPONSE_BODY_SIZE.require(this.maximumResponseBytes.intValue()); 520 int keys = this.maximumKeys == null ? Limits.JWKS_KEY_COUNT.getDefaultIntValue() 521 : Limits.JWKS_KEY_COUNT.require(this.maximumKeys.intValue()); 522 Limits.requireJwksTimeToLiveOrder(minimum, standard, maximum); 523 Limits.requireJwksCooldownWithinMinimumTimeToLive(cooldown, minimum); 524 525 boolean acknowledged = this.acknowledgeUnpatchedRuntime != null && this.acknowledgeUnpatchedRuntime; 526 RuntimeFloor.require(runtimeVersion, acknowledged); 527 528 OutboundUriPolicy policy = this.outboundUriPolicy == null ? OutboundUriPolicy.defaultInstance() 529 : this.outboundUriPolicy; 530 boolean insecureLoopback = this.allowInsecureLoopback != null && this.allowInsecureLoopback; 531 if (this.httpClient != null) 532 HttpClientChecks.requireNeverRedirects(this.httpClient); 533 UriChecks.requirePermitted(this.uri, policy, insecureLoopback); 534 HttpExchange exchange = HttpExchange.fromHttpClient(this.httpClient, policy, insecureLoopback); 535 536 JoseObserver sourceObserver = this.observer == null ? JoseObserver.disabledInstance() : this.observer; 537 @Nullable String unpatchedRuntimeVersion = RuntimeFloor.isBelowFloor(runtimeVersion) ? runtimeVersion.toString() 538 : null; 539 540 if (unpatchedRuntimeVersion != null) 541 ObserverDispatch.dispatch(sourceObserver, observer -> observer.didUseUnpatchedRuntime(unpatchedRuntimeVersion)); 542 543 JwksSettings settings = new JwksSettings(this.clock == null ? Clock.systemUTC() : this.clock, timeout, minimum, 544 standard, maximum, cooldown, staleness, responseBytes, keys, sourceObserver, unpatchedRuntimeVersion); 545 546 return new RemoteJwksSource(this.uri, exchange, settings); 547 } 548 549 @NonNull 550 private static Duration orDefault(@Nullable Duration value, 551 @NonNull Duration defaultValue) { 552 return value == null ? defaultValue : value; 553 } 554 } 555}