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;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.internal.Limits;
021import com.revetsec.internal.crypto.ConstantTime;
022import com.revetsec.internal.crypto.EntropySource;
023import com.revetsec.internal.crypto.SealedStateAccess;
024import com.revetsec.internal.crypto.SealedStateType;
025import com.revetsec.internal.crypto.SealerV1;
026import com.revetsec.internal.crypto.UnsealException;
027import com.revetsec.internal.crypto.AuthenticatedRecord;
028import com.revetsec.internal.crypto.ClosedMigrationIntent;
029import com.revetsec.internal.encoding.EncodingException;
030import com.revetsec.internal.encoding.StrictUtf8;
031import org.jspecify.annotations.NonNull;
032import org.jspecify.annotations.Nullable;
033
034import javax.annotation.concurrent.NotThreadSafe;
035import javax.annotation.concurrent.ThreadSafe;
036import java.security.GeneralSecurityException;
037import java.time.Clock;
038import java.time.Duration;
039import java.time.Instant;
040import java.util.ArrayList;
041import java.util.Arrays;
042import java.util.LinkedHashMap;
043import java.util.List;
044import java.util.Map;
045import java.util.Set;
046
047import static java.util.Objects.requireNonNull;
048
049/**
050 * Seals short strings into opaque, URL- and cookie-safe values that only a holder of the same keys can open, and
051 * only for the same context before they expire.
052 * <p>
053 * Revetsec uses sealed values to carry pending sign-in state through the browser, and applications can seal their
054 * own data with {@link #seal(String, String, Duration)} and {@link #unsealResult(String, String)}. A sealed value is
055 * encrypted and authenticated with AES-256-GCM under a key derived with HKDF-SHA256 from the sealing key and a fresh
056 * random salt, so every value gets its own encryption key, and it is written in unpadded base64url. It carries, in
057 * the clear, the ID of the key that sealed it; everything else is encrypted, authenticated or both. Values sealed
058 * here are application data: Revetsec seals its own pending state under other type labels, bound into both the key
059 * derivation and the authenticated data, so a value of one kind does not open as the other.
060 * <p>
061 * <strong>Context.</strong> Every value is bound to a context string, such as the name of the cookie that carries
062 * it or the identity provider it concerns, and opens only for the same context. A context is 1 to 256 characters of
063 * well-formed UTF-16 (no unpaired surrogate). It is not secret and is not stored in the value.
064 * <p>
065 * <strong>Lifetime.</strong> {@code seal} takes a lifetime from 1 second to 400 days. The value's expiry, which it
066 * carries encrypted, is the current time from the builder's {@link Clock} rounded up to a whole second, plus the
067 * lifetime rounded down to whole seconds. So a value opens for at least the lifetime's whole seconds and at most one
068 * second more, and it stops opening at the first instant at or after its expiry.
069 * <p>
070 * <strong>Failures.</strong> Arguments are checked first: a {@code null} throws {@link NullPointerException}, and an
071 * invalid context, plaintext or lifetime, or a plaintext too long to seal, throws {@link IllegalArgumentException}.
072 * Every failure to open a value returns the same opaque {@link StateUnsealResult.Rejected} outcome, whether the
073 * value was tampered with, truncated, malformed, too long, sealed for another context, sealed under a key this sealer
074 * does not hold, or expired. Opening never tries more than one key: the key ID in the value selects exactly one.
075 * <p>
076 * <strong>Keys and rotation.</strong> The {@linkplain Builder#build() built} sealer seals with its active key and
077 * opens values sealed under its active key or any of its verification keys (at most 16). To rotate:
078 * <ol>
079 *   <li>add the new key as a verification key on every instance, so each can open values the new key seals;</li>
080 *   <li>promote it: make it the active key and the old key a verification key;</li>
081 *   <li>once every expiring value sealed under the old key has expired and every permanent protocol record has
082 *   been migrated, retire the old key.</li>
083 * </ol>
084 * Permanent protocol records, including TOTP credentials, do not age out with cookies. Their authenticated
085 * resealing, outstanding writers and retained backups need an explicit key-retirement inventory.
086 * Rotate at once if a key may have been disclosed: whoever holds a key can seal values that every sealer holding it
087 * accepts. Use one key per application.
088 * <p>
089 * <strong>Size.</strong> A sealed value is {@code ceil(4 * (54 + k + p) / 3)} characters long for a key ID of
090 * {@code k} characters and a plaintext of {@code p} UTF-8 bytes; a 700-byte plaintext under key ID {@code 2026-09}
091 * seals to 1,015 characters. The {@code seal} operation refuses, and {@code unsealResult} rejects before decoding, any
092 * value longer than {@link Builder#maximumSealedLength(Integer)}: 3,800 characters by default, which leaves room for a cookie's name
093 * and attributes within the 4,096 bytes per cookie that RFC 6265 section 6.1 asks browsers to support.
094 * <p>
095 * Instances are immutable and safe for concurrent use.
096 *
097 * @author <a href="https://www.revetkn.com">Mark Allen</a>
098 * @since 1.0.0
099 */
100@ThreadSafe
101public final class StateSealer {
102        /**
103         * The most verification keys a sealer holds besides its active key (G6-9).
104         */
105        private static final int MAXIMUM_VERIFICATION_KEYS = 16;
106
107        static {
108                // G6-10: the protocol packages reach the internal type labels through this accessor, never through the public
109                // API. SealedStateAccess.get() forces this initialization first.
110                SealedStateAccess.set(new SealedStateOperations());
111        }
112
113        private final SealerV1.@NonNull Key activeKey;
114        /**
115         * The active key and every verification key, by key ID.
116         */
117        @NonNull
118        private final Map<@NonNull String, SealerV1.@NonNull Key> keysByKeyId;
119        @NonNull
120        private final List<@NonNull String> verificationKeyIds;
121        @NonNull
122        private final Clock clock;
123        private final int maximumSealedLength;
124        @NonNull
125        private final EntropySource entropySource;
126
127        private StateSealer(SealerV1.@NonNull Key activeKey,
128                                                                                        @NonNull Map<@NonNull String, SealerV1.@NonNull Key> keysByKeyId,
129                                                                                        @NonNull List<@NonNull String> verificationKeyIds,
130                                                                                        @NonNull Clock clock,
131                                                                                        int maximumSealedLength,
132                                                                                        @NonNull EntropySource entropySource) {
133                this.activeKey = activeKey;
134                this.keysByKeyId = keysByKeyId;
135                this.verificationKeyIds = verificationKeyIds;
136                this.clock = clock;
137                this.maximumSealedLength = maximumSealedLength;
138                this.entropySource = entropySource;
139        }
140
141        /**
142         * Starts building a sealer that seals with {@code activeKey}.
143         *
144         * @param activeKey the key that seals new values; it also opens them
145         * @return a new builder
146         * @throws NullPointerException if {@code activeKey} is {@code null}
147         * @since 1.0.0
148         */
149        @NonNull
150        public static Builder withActiveKey(@NonNull SealingKey activeKey) {
151                return new Builder(activeKey);
152        }
153
154        /**
155         * Seals {@code plaintext} for {@code context}, to open until {@code lifetime} from now.
156         * <p>
157         * Every call returns a different value, even for the same arguments, because each draws a fresh random salt and
158         * IV.
159         *
160         * @param plaintext the text to seal, well-formed UTF-16; it may be empty
161         * @param context   the context to bind: 1 to 256 characters of well-formed UTF-16
162         * @param lifetime  how long the value opens, from 1 second to 400 days; only whole seconds count
163         * @return the sealed value, in unpadded base64url
164         * @throws NullPointerException     if an argument is {@code null}
165         * @throws IllegalArgumentException if the context or lifetime is out of range, the plaintext or context contains an
166         *                                  unpaired surrogate, or the sealed value would be longer than
167         *                                  {@link Builder#maximumSealedLength(Integer)}
168         * @throws IllegalStateException    if the platform's cryptographic provider refuses to seal or cannot supply
169         *                                  random bytes
170         * @since 1.0.0
171         */
172        @NonNull
173        public String seal(@NonNull String plaintext,
174                                                                                 @NonNull String context,
175                                                                                 @NonNull Duration lifetime) {
176                return sealForLifetime(SealedStateType.APP, plaintext, context, lifetime);
177        }
178
179        private @NonNull String sealForLifetime(@NonNull SealedStateType type, @NonNull String plaintext,
180                        @NonNull String context, @NonNull Duration lifetime) {
181                requireNonNull(plaintext);
182                requireNonNull(context);
183                requireNonNull(lifetime);
184                SealerV1.requireContext(context);
185                Limits.SEAL_LIFETIME.require(lifetime);
186
187                // Neither sum can overflow: the largest Instant is about 3.2E16 seconds and the lifetime at most 400 days.
188                long notAfter = ceilingEpochSecond(this.clock.instant()) + lifetime.toSeconds();
189                return sealUntil(type, plaintext, context, notAfter);
190        }
191
192        /**
193         * Opens application state once and returns its authenticated plaintext or one undifferentiated rejection.
194         * Expiry, wrong context, unknown keys, malformed input and authentication failure expose no differing detail.
195         *
196         * @param sealed untrusted sealed state
197         * @param context trusted application context
198         * @return the opening outcome
199         * @throws NullPointerException if either argument is null
200         * @throws IllegalArgumentException if the context is invalid
201         * @since 1.0.0
202         */
203        @CheckReturnValue
204        public @NonNull StateUnsealResult unsealResult(@NonNull String sealed, @NonNull String context) {
205                requireNonNull(sealed);
206                requireNonNull(context);
207                SealerV1.requireContext(context);
208
209                Instant now = this.clock.instant();
210                try {
211                        return StateUnsealResult.fromValue(SealerV1.open(sealed, this.maximumSealedLength, this.keysByKeyId,
212                                        SealedStateType.APP, context, now));
213                } catch (UnsealException rejection) {
214                        return StateUnsealResult.fromRejection();
215                }
216        }
217
218        /**
219         * Returns a description of this sealer's configuration, which names its key IDs but never renders a key.
220         *
221         * @return a description of this sealer without its secrets
222         * @since 1.0.0
223         */
224        @Override
225        @NonNull
226        public String toString() {
227                return getClass().getSimpleName() + "{activeKeyId=" + this.activeKey.getKeyId() + ", verificationKeyIds="
228                                + this.verificationKeyIds + ", maximumSealedLength=" + this.maximumSealedLength + "}";
229        }
230
231        /**
232         * Seals under {@code type} with the active key. The context has been checked.
233         */
234        @NonNull
235        private String sealUntil(@NonNull SealedStateType type,
236                                                                                                         @NonNull String plaintext,
237                                                                                                         @NonNull String context,
238                                                                                                         long notAfter) {
239                int keyIdLength = this.activeKey.getKeyId().length();
240
241                // UTF-8 never has fewer bytes than UTF-16 has code units, so an oversized plaintext is refused before it is
242                // encoded.
243                if (SealerV1.sealedLength(keyIdLength, plaintext.length()) > this.maximumSealedLength)
244                        throw tooLong();
245
246                byte[] plaintextBytes;
247
248                try {
249                        plaintextBytes = StrictUtf8.encode(plaintext);
250                } catch (EncodingException e) {
251                        throw new IllegalArgumentException("A plaintext must be well-formed UTF-16.");
252                }
253
254                try {
255                        // Checked outside sealWithProvider, so this IllegalArgumentException is never mistaken for a provider failure.
256                        if (SealerV1.sealedLength(keyIdLength, plaintextBytes.length) > this.maximumSealedLength)
257                                throw tooLong();
258
259                        return sealWithProvider(type, context, notAfter, plaintextBytes);
260                } finally {
261                        Arrays.fill(plaintextBytes, (byte) 0);
262                }
263        }
264
265        @NonNull
266        private String sealWithProvider(@NonNull SealedStateType type,
267                                                                                                                                        @NonNull String context,
268                                                                                                                                        long notAfter,
269                                                                                                                                        byte @NonNull [] plaintextBytes) {
270                try {
271                        // The salt and IV are drawn here, because the SecureRandom is a JCA provider too: a PKCS#11 or native one
272                        // can throw ProviderException at any draw.
273                        byte[] salt = this.entropySource.nextBytes(SealerV1.SALT_LENGTH);
274                        byte[] iv = this.entropySource.nextBytes(SealerV1.IV_LENGTH);
275
276                        return SealerV1.seal(this.activeKey, type, context, notAfter, plaintextBytes, salt, iv);
277                } catch (GeneralSecurityException | RuntimeException e) {
278                        // Every argument has been checked, so only the provider or the SecureRandom can fail here.
279                        throw new IllegalStateException("The cryptographic provider refused to seal.", e);
280                }
281        }
282
283        /**
284         * The first epoch second at or after {@code instant}.
285         */
286        private static long ceilingEpochSecond(@NonNull Instant instant) {
287                return instant.getNano() == 0 ? instant.getEpochSecond() : instant.getEpochSecond() + 1;
288        }
289
290        @NonNull
291        private IllegalArgumentException tooLong() {
292                return new IllegalArgumentException("The sealed value would be longer than the maximum sealed length of "
293                                + this.maximumSealedLength + " characters.");
294        }
295
296        /**
297         * Builds a {@link StateSealer}.
298         * <p>
299         * {@link #build()} checks the keys together and runs a self-test: it seals and opens a fixed value with the active
300         * key, checks that an altered copy does not open and that the value does not open under another context, and
301         * checks that a fixed input seals to its known bytes.
302         *
303         * @author <a href="https://www.revetkn.com">Mark Allen</a>
304         * @since 1.0.0
305         */
306        @NotThreadSafe
307        @CheckReturnValue
308        public static final class Builder {
309                @NonNull
310                private final SealingKey activeKey;
311                @NonNull
312                private List<@NonNull SealingKey> verificationKeys;
313                @Nullable
314                private Clock clock;
315                @Nullable
316                private Integer maximumSealedLength;
317
318                private Builder(@NonNull SealingKey activeKey) {
319                        this.activeKey = requireNonNull(activeKey);
320                        this.verificationKeys = List.of();
321                }
322
323                /**
324                 * Sets the keys that open values sealed earlier under other keys, such as the previous active key during a
325                 * rotation. They never seal.
326                 *
327                 * @param verificationKeys at most 16 keys, each with its own key ID and its own key bytes, none of them the
328                 *                         active key; {@code null} restores the default, none. The list is copied
329                 * @return this builder
330                 * @throws NullPointerException if the list contains {@code null}
331                 * @since 1.0.0
332                 */
333                @NonNull
334                public Builder verificationKeys(@Nullable List<@NonNull SealingKey> verificationKeys) {
335                        this.verificationKeys = verificationKeys == null ? List.of() : List.copyOf(verificationKeys);
336                        return this;
337                }
338
339                /**
340                 * Sets the clock that supplies the current time for sealing and opening.
341                 *
342                 * @param clock the clock; {@code null} restores the default, {@link Clock#systemUTC()}
343                 * @return this builder
344                 * @since 1.0.0
345                 */
346                @NonNull
347                public Builder clock(@Nullable Clock clock) {
348                        this.clock = clock;
349                        return this;
350                }
351
352                /**
353                 * Sets the longest sealed value, in characters, that {@code seal} returns and {@code unsealResult} decodes.
354                 * Also bounds each newly emitted WebAuthn store-record chunk. Historical WebAuthn framed-record
355                 * opening retains its fixed 16,384-character chunk ceiling when this emission setting is lowered;
356                 * authentication, expiry, record framing and admitted-time checks still apply.
357                 *
358                 * @param maximumSealedLength from 1,024 to 16,384; {@code null} restores the default, 3,800. {@link #build()}
359                 *                            checks the range
360                 * @return this builder
361                 * @since 1.0.0
362                 */
363                @NonNull
364                public Builder maximumSealedLength(@Nullable Integer maximumSealedLength) {
365                        this.maximumSealedLength = maximumSealedLength;
366                        return this;
367                }
368
369                /**
370                 * Builds the sealer.
371                 *
372                 * @return a new sealer
373                 * @throws IllegalArgumentException if the maximum sealed length is out of range, there are more than 16
374                 *                                  verification keys, or two keys share a key ID or key bytes
375                 * @throws IllegalStateException    if the platform's cryptographic provider refuses HMAC-SHA256 or AES-GCM,
376                 *                                  cannot supply random bytes, or fails the self-test
377                 * @since 1.0.0
378                 */
379                @NonNull
380                public StateSealer build() {
381                        int maximum = this.maximumSealedLength == null
382                                        ? Limits.STATE_SEALER_MAXIMUM_SEALED_LENGTH.getDefaultIntValue()
383                                        : Limits.STATE_SEALER_MAXIMUM_SEALED_LENGTH.require(this.maximumSealedLength);
384
385                        if (this.verificationKeys.size() > MAXIMUM_VERIFICATION_KEYS)
386                                throw new IllegalArgumentException("A StateSealer holds at most " + MAXIMUM_VERIFICATION_KEYS
387                                                + " verification keys.");
388
389                        List<SealingKey> keys = new ArrayList<>(1 + this.verificationKeys.size());
390                        keys.add(this.activeKey);
391                        keys.addAll(this.verificationKeys);
392                        requireDistinct(keys);
393
394                        Map<String, SealerV1.Key> keysByKeyId = new LinkedHashMap<>();
395                        List<String> verificationKeyIds = new ArrayList<>(this.verificationKeys.size());
396                        EntropySource entropySource;
397                        SealerV1.Key derivedActiveKey;
398                        boolean passesSelfTest;
399
400                        try {
401                                // Inside the try: the platform's SecureRandom can fail to construct (a JVM-environment failure, section
402                                // 9.6), which must be the same IllegalStateException as a refusing cipher.
403                                entropySource = EntropySource.fromDefaults();
404                                derivedActiveKey = derive(this.activeKey);
405                                keysByKeyId.put(derivedActiveKey.getKeyId(), derivedActiveKey);
406
407                                for (SealingKey key : this.verificationKeys) {
408                                        keysByKeyId.put(key.getKeyId(), derive(key));
409                                        verificationKeyIds.add(key.getKeyId());
410                                }
411
412                                passesSelfTest = SealerV1.passesSelfTest(derivedActiveKey, entropySource.nextBytes(SealerV1.SALT_LENGTH),
413                                                entropySource.nextBytes(SealerV1.IV_LENGTH));
414                        } catch (GeneralSecurityException | RuntimeException e) {
415                                throw new IllegalStateException("The cryptographic provider refused StateSealer's self-test.", e);
416                        }
417
418                        if (!passesSelfTest)
419                                throw new IllegalStateException("The cryptographic provider failed StateSealer's self-test.");
420
421                        return new StateSealer(derivedActiveKey, Map.copyOf(keysByKeyId), List.copyOf(verificationKeyIds),
422                                        this.clock == null ? Clock.systemUTC() : this.clock, maximum, entropySource);
423                }
424
425                /**
426                 * Rejects two keys with the same key ID or the same key bytes, both compared in constant time.
427                 */
428                private static void requireDistinct(@NonNull List<@NonNull SealingKey> keys) {
429                        for (int first = 0; first < keys.size(); ++first) {
430                                for (int second = first + 1; second < keys.size(); ++second) {
431                                        if (ConstantTime.isEqual(keys.get(first).getKeyId(), keys.get(second).getKeyId()))
432                                                throw new IllegalArgumentException("Every sealing key needs its own key ID.");
433                                        if (keys.get(first).hasSameKeyBytes(keys.get(second)))
434                                                throw new IllegalArgumentException("Every sealing key needs its own key bytes.");
435                                }
436                        }
437                }
438
439                private static SealerV1.@NonNull Key derive(@NonNull SealingKey key) throws GeneralSecurityException {
440                        byte[] keyBytes = key.copyKeyBytes();
441
442                        try {
443                                return SealerV1.Key.fromMasterKey(key.getKeyId(), keyBytes);
444                        } finally {
445                                Arrays.fill(keyBytes, (byte) 0);
446                        }
447                }
448        }
449
450        /**
451         * The internal, label-aware sealing and opening that {@link SealedStateAccess} hands to the protocol packages.
452         */
453        @ThreadSafe
454        private static final class SealedStateOperations implements SealedStateAccess.Operations {
455                // WAR2 framing bounds authenticated chunks to 16,384 ASCII characters. Reads of retained
456                // records must not shrink with the independently configured future emission cap.
457                private static final int WEBAUTHN_RECORD_OPENING_LIMIT = 16_384;
458
459                private static int recordOpeningLimit(@NonNull StateSealer sealer, @NonNull SealedStateType type) {
460                        return type == SealedStateType.WEBAUTHN_RECORD ? WEBAUTHN_RECORD_OPENING_LIMIT : sealer.maximumSealedLength;
461                }
462
463                @Override
464                public @NonNull AuthenticatedRecord openRecord(@NonNull StateSealer sealer, @NonNull SealedStateType type,
465                                @NonNull String sealed, @NonNull String context, @NonNull Clock clock) throws UnsealException {
466                        requireNonNull(sealer);
467                        requireNonNull(type);
468                        requireNonNull(sealed);
469                        requireNonNull(context);
470                        requireNonNull(clock);
471                        SealerV1.requireContext(context);
472                        return SealerV1.openRecord(sealed, recordOpeningLimit(sealer, type), sealer.keysByKeyId, type, context, clock.instant());
473                }
474
475                @Override
476                public @NonNull AuthenticatedRecord openForMigration(@NonNull StateSealer sealer, @NonNull SealedStateType type,
477                                @NonNull String sealed, @NonNull String context, @NonNull ClosedMigrationIntent intent) throws UnsealException {
478                        requireNonNull(sealer);
479                        return SealerV1.openForMigration(sealed, recordOpeningLimit(sealer, type), sealer.keysByKeyId, type, context, intent);
480                }
481
482                @Override
483                public @NonNull AuthenticatedRecord openPermanentFence(@NonNull StateSealer sealer, @NonNull String sealed,
484                                @NonNull String context) throws UnsealException {
485                        requireNonNull(sealer);
486                        return SealerV1.openPermanentFence(sealed, sealer.maximumSealedLength, sealer.keysByKeyId, context);
487                }
488
489  @Override public @NonNull Integer getMaximumSealedLength(@NonNull StateSealer sealer) {
490   return requireNonNull(sealer).maximumSealedLength;
491  }
492
493        @Override public @NonNull String getActiveKeyId(@NonNull StateSealer sealer) {
494            return requireNonNull(sealer).activeKey.getKeyId();
495        }
496
497        @Override public @NonNull Set<@NonNull String> getOpeningKeyIds(@NonNull StateSealer sealer) {
498            return Set.copyOf(requireNonNull(sealer).keysByKeyId.keySet());
499        }
500
501        @Override public @NonNull String sealDurable(@NonNull StateSealer sealer,
502                @NonNull String plaintext, @NonNull String context) {
503            requireNonNull(sealer);
504            requireNonNull(plaintext);
505            SealerV1.requireContext(context);
506            if (plaintext.length() > 48_000) throw new IllegalArgumentException("Durable record too large");
507            byte[] bytes;
508            try { bytes = StrictUtf8.encode(plaintext); }
509            catch (EncodingException failure) { throw new IllegalArgumentException("Invalid durable text"); }
510            try {
511                if (SealerV1.sealedLength(sealer.activeKey.getKeyId().length(), bytes.length) > 65_536)
512                    throw new IllegalArgumentException("Durable record too large");
513                return sealer.sealWithProvider(SealedStateType.TOTP_RECORD, context, Long.MAX_VALUE, bytes);
514            } finally { Arrays.fill(bytes, (byte) 0); }
515        }
516
517        @Override public @NonNull String unsealDurable(@NonNull StateSealer sealer,
518                @NonNull String sealed, @NonNull String context) throws UnsealException {
519            return SealerV1.openDurable(sealed, requireNonNull(sealer).keysByKeyId, context);
520        }
521
522                @Override
523                public @NonNull String sealForLifetime(@NonNull StateSealer sealer, @NonNull SealedStateType type,
524                                @NonNull String plaintext, @NonNull String context, @NonNull Duration lifetime) {
525                        requireNonNull(sealer); requireNonNull(type);
526                        if (type != SealedStateType.OIDC_LOGOUT_HINT && type != SealedStateType.OIDC_SESSION)
527                                throw new IllegalArgumentException("The lifetime operation requires an OIDC application-storage type.");
528                        return sealer.sealForLifetime(type, plaintext, context, lifetime);
529                }
530
531                @Override
532                public @NonNull String unsealUsingConfiguredClock(@NonNull StateSealer sealer, @NonNull SealedStateType type,
533                                @NonNull String sealed, @NonNull String context) throws UnsealException {
534                        requireNonNull(sealer); requireNonNull(type);
535                        if (type != SealedStateType.OIDC_LOGOUT_HINT && type != SealedStateType.OIDC_SESSION)
536                                throw new IllegalArgumentException("The configured-clock operation requires an OIDC application-storage type.");
537                        return unseal(sealer, type, sealed, context, sealer.clock);
538                }
539
540                @Override
541                @NonNull
542                public String seal(@NonNull StateSealer sealer,
543                                                                                         @NonNull SealedStateType type,
544                                                                                         @NonNull String plaintext,
545                                                                                         @NonNull String context,
546                                                                                         @NonNull Instant expiresAt) {
547                        requireNonNull(sealer);
548                        requireNonNull(type);
549                        requireNonNull(plaintext);
550                        requireNonNull(context);
551                        requireNonNull(expiresAt);
552                        SealerV1.requireContext(context);
553
554                        return sealer.sealUntil(type, plaintext, context, ceilingEpochSecond(expiresAt));
555                }
556
557                @Override
558                @NonNull
559                public String unseal(@NonNull StateSealer sealer,
560                                                                                                 @NonNull SealedStateType type,
561                                                                                                 @NonNull String sealed,
562                                                                                                 @NonNull String context,
563                                                                                                 @NonNull Clock clock) throws UnsealException {
564                        requireNonNull(sealer);
565                        requireNonNull(type);
566                        requireNonNull(sealed);
567                        requireNonNull(context);
568                        requireNonNull(clock);
569                        SealerV1.requireContext(context);
570
571                        return SealerV1.open(sealed, sealer.maximumSealedLength, sealer.keysByKeyId, type, context, clock.instant());
572                }
573        }
574}