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.oidc;
018
019import com.revetsec.StateSealer;
020import com.revetsec.internal.crypto.SealedStateAccess;
021import com.revetsec.internal.crypto.SealedStateType;
022import com.revetsec.internal.crypto.SealerV1;
023import com.revetsec.internal.Limits;
024import com.revetsec.internal.crypto.UnsealException;
025import com.revetsec.internal.jose.RegisteredClaims;
026import com.revetsec.json.JsonObject;
027import com.google.errorprone.annotations.CheckReturnValue;
028import org.jspecify.annotations.NonNull;
029import javax.annotation.concurrent.Immutable;
030import java.time.Duration;
031import java.util.Set;
032import static java.util.Objects.requireNonNull;
033
034/**
035 * An explicitly retained logout credential bound to the original OIDC continuity reference. It is not an identity
036 * proof. The compact ID token is emitted only inside explicit trusted-storage serialization or a prepared logout
037 * request. Parsing checks structure and continuity, without signature validation or rejecting an expired ID token.
038 * Immutable strings and parser/provider-owned copies cannot be erased; owned temporary byte arrays are cleared.
039 * @author <a href="https://www.revetkn.com">Mark Allen</a>
040 * @since 1.0.0
041 */
042@Immutable
043public final class OidcLogoutHint {
044        private final @NonNull OidcSessionReference reference;
045        private final @NonNull String compact;
046        private final @NonNull String referenceForm;
047        private final int referenceBytes;
048        OidcLogoutHint(@NonNull OidcSessionReference reference, @NonNull String compact) {
049                this.reference = requireNonNull(reference); this.compact = requireNonNull(compact);
050                try {
051                        OidcLogoutSupport.continuity(reference, OidcLogoutSupport.token(compact));
052                        this.referenceForm = reference.toSerializedForm(); this.referenceBytes = OidcLogoutSupport.text(this.referenceForm, OidcLogoutSupport.REFERENCE_LIMIT);
053                        JsonObject stored = OidcLogoutSupport.object(this.referenceForm, OidcLogoutSupport.REFERENCE_LIMIT);
054                        OidcLogoutSupport.client(OidcLogoutSupport.field(stored, "client_id", OidcLogoutSupport.FIELD_LIMIT));
055                        if (!(stored.getMembers().get("claims") instanceof JsonObject claims)) throw OidcLogoutSupport.invalid();
056                        OidcLogoutSupport.field(claims, "iss", OidcLogoutSupport.FIELD_LIMIT);
057                } catch (IllegalArgumentException | OidcValidationException invalid) { throw OidcLogoutSupport.failure(OidcLogoutException.Reason.HINT_MISMATCH); }
058        }
059        @NonNull OidcSessionReference reference() { return this.reference; }
060        @NonNull String compact() { return this.compact; }
061
062        /**
063         * Emits a credential-bearing versioned JSON envelope for trusted application storage. Never log this value.
064         * @return bounded serialized hint; parsing it creates no identity
065         * @throws OidcLogoutException if the selected representation cannot fit
066         * @since 1.0.0
067         */
068        public @NonNull String toSerializedForm() {
069                String referenceForm = this.referenceForm;
070                String prefix = "{\"v\":1,\"reference\":"; String middle = ",\"id_token\":\""; String suffix = "\"}";
071                long bytes = (long) this.referenceBytes + this.compact.length() + prefix.length() + middle.length() + suffix.length();
072                if (bytes > OidcLogoutSupport.HINT_LIMIT) throw OidcLogoutSupport.failure(OidcLogoutException.Reason.INPUT_LIMIT);
073                return prefix + referenceForm + middle + this.compact + suffix;
074        }
075        /**
076         * Seals under a dedicated logout-hint type and the sealer's configured clock/lifetime profile. Valid large hints
077         * can exceed the unchanged sealer size ceiling; no truncation or chunking is performed.
078         * @param sealer application-owned sealer
079         * @param context fixed application context
080         * @param lifetime explicit sealing lifetime
081         * @return typed sealed credential for trusted storage
082         * @throws NullPointerException if a required argument is null
083         * @throws OidcLogoutException if size/configuration, interruption or the provider prevents sealing
084         * @since 1.0.0
085         */
086        public @NonNull String toSealedForm(@NonNull StateSealer sealer, @NonNull String context, @NonNull Duration lifetime) {
087                requireNonNull(sealer); requireNonNull(context); requireNonNull(lifetime); OidcLogoutSupport.interrupted();
088                String plaintext = toSerializedForm();
089                try {
090                        SealerV1.requireContext(context); Limits.SEAL_LIFETIME.require(lifetime);
091                        int length = OidcLogoutSupport.text(plaintext, OidcLogoutSupport.HINT_LIMIT);
092                        if (SealerV1.sealedLength(SealedStateAccess.get().getActiveKeyId(sealer).length(), length) > SealedStateAccess.get().getMaximumSealedLength(sealer))
093                                throw OidcLogoutSupport.invalid();
094                } catch (IllegalArgumentException invalid) { throw OidcLogoutSupport.failure(OidcLogoutException.Reason.STORAGE_PROFILE_UNSUPPORTED); }
095                try {
096                        String sealed = SealedStateAccess.get().sealForLifetime(sealer, SealedStateType.OIDC_LOGOUT_HINT, plaintext, context, lifetime);
097                        OidcLogoutSupport.interrupted(); return sealed;
098                } catch (OidcLogoutException failure) { throw failure; }
099                catch (VirtualMachineError fatal) { throw fatal; }
100                catch (RuntimeException | Error failure) { OidcLogoutSupport.interrupted(); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); }
101        }
102        /**
103         * Restores a structurally consistent credential from trusted application storage. No identity is authenticated.
104         * @param serializedForm credential-bearing storage form; never log it
105         * @return parsed credential or one value-free rejection
106         * @throws NullPointerException if serializedForm is null
107         * @since 1.0.0
108         */
109        @CheckReturnValue
110        public static @NonNull OidcLogoutHintParseResult fromSerializedFormResult(@NonNull String serializedForm) {
111                requireNonNull(serializedForm); OidcLogoutSupport.interrupted();
112                try {
113                        JsonObject envelope = OidcLogoutSupport.object(serializedForm, OidcLogoutSupport.HINT_LIMIT); OidcLogoutSupport.version(envelope);
114                        if (!envelope.getMembers().keySet().equals(Set.of("v", "reference", "id_token")) || !(envelope.getMembers().get("reference") instanceof JsonObject original)) throw OidcLogoutSupport.invalid();
115                        OidcSessionReferenceParseResult parsed = OidcSessionReference.fromSerializedFormResult(original.toJson());
116                        if (!(parsed instanceof OidcSessionReferenceParseResult.Succeeded success)) throw OidcLogoutSupport.invalid();
117                        OidcLogoutHint hint = new OidcLogoutHint(success.getReference(), OidcLogoutSupport.field(envelope, "id_token", OidcLogoutSupport.TOKEN_LIMIT));
118                        OidcLogoutSupport.interrupted(); return OidcLogoutHintParseResult.fromHint(hint);
119                } catch (OidcLogoutException invalid) {
120                        if (invalid.getReason() != OidcLogoutException.Reason.HINT_MISMATCH && invalid.getReason() != OidcLogoutException.Reason.INPUT_LIMIT) throw invalid;
121                        return OidcLogoutHintParseResult.fromRejection();
122                } catch (IllegalArgumentException | OidcValidationException invalid) { return OidcLogoutHintParseResult.fromRejection(); }
123        }
124        /**
125         * Opens only a typed logout hint using the sealer's configured clock. Invalid/tampered/cross-purpose/expired
126         * sealed state releases no hint. Provider and interruption failures remain distinct fixed exceptions.
127         * @param sealedForm received typed sealed credential
128         * @param sealer application-owned sealer
129         * @param context original application context
130         * @return restored credential or value-free rejection, never authenticated identity
131         * @throws NullPointerException if a required argument is null
132         * @throws OidcLogoutException if the provider or interruption prevents opening
133         * @since 1.0.0
134         */
135        @CheckReturnValue
136        public static @NonNull OidcLogoutHintParseResult fromSealedFormResult(@NonNull String sealedForm, @NonNull StateSealer sealer, @NonNull String context) {
137                requireNonNull(sealedForm); requireNonNull(sealer); requireNonNull(context); OidcLogoutSupport.interrupted();
138                try { SealerV1.requireContext(context); } catch (IllegalArgumentException invalid) { throw OidcLogoutSupport.failure(OidcLogoutException.Reason.STORAGE_PROFILE_UNSUPPORTED); }
139                try {
140                        String opened = SealedStateAccess.get().unsealUsingConfiguredClock(sealer, SealedStateType.OIDC_LOGOUT_HINT, sealedForm, context);
141                        OidcLogoutSupport.interrupted(); return fromSerializedFormResult(opened);
142                } catch (UnsealException invalid) { return OidcLogoutHintParseResult.fromRejection(); }
143                catch (OidcLogoutException failure) { throw failure; }
144                catch (VirtualMachineError fatal) { throw fatal; }
145                catch (RuntimeException | Error failure) { OidcLogoutSupport.interrupted(); throw OidcLogoutSupport.failure(OidcLogoutException.Reason.PROVIDER_UNAVAILABLE); }
146        }
147        /** Redacts every credential and continuity field.
148         * @return redacted description
149         * @since 1.0.0
150         */
151        @Override public @NonNull String toString() { return "OidcLogoutHint{credential=<redacted>, reference=<redacted>}"; }
152}