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.google.errorprone.annotations.CheckReturnValue;
021import com.revetsec.internal.crypto.ConstantTime;
022import com.revetsec.internal.crypto.SealedStateAccess;
023import com.revetsec.internal.crypto.SealedStateType;
024import com.revetsec.internal.crypto.UnsealException;
025import com.revetsec.internal.encoding.StrictUtf8;
026import com.revetsec.internal.encoding.Base64Url;
027import com.revetsec.internal.encoding.EncodingException;
028import com.revetsec.internal.json.*;
029import com.revetsec.jose.JwtClaims;
030import com.revetsec.json.*;
031import org.jspecify.annotations.NonNull;
032import org.jspecify.annotations.Nullable;
033import javax.annotation.concurrent.Immutable;
034import java.nio.charset.StandardCharsets;
035import java.security.MessageDigest;
036import java.security.NoSuchAlgorithmException;
037import java.time.Duration;
038import java.time.Instant;
039import java.util.*;
040import static java.util.Objects.requireNonNull;
041
042/**
043 * Continuity reference for refresh and future logout. It holds original continuity claims, client binding and a
044 * SHA-256 nonce digest and the original flow's ACR acceptance set. It is not proof of identity and contains no access, refresh or compact ID token. Persist
045 * it in trusted application storage or seal it; parsing a serialized reference does not authenticate its fields.
046 * @author <a href="https://www.revetkn.com">Mark Allen</a>
047 * @since 1.0.0
048 */
049@Immutable
050public final class OidcSessionReference {
051        private static final int MAXIMUM_BYTES = 64 * 1_024;
052        private static final Set<String> CLAIM_NAMES = Set.of("iss", "sub", "aud", "iat", "azp", "auth_time", "sid");
053        private final JsonObject continuityClaims;
054        private final String clientId;
055        private final String nonceDigest;
056        private final Set<String> requiredAcrValues;
057        private final @Nullable String sessionId;
058        OidcSessionReference(@NonNull IdToken token, @NonNull String clientId) {
059                this(token, clientId, Set.of());
060        }
061        OidcSessionReference(@NonNull IdToken token, @NonNull String clientId, @NonNull Set<@NonNull String> requiredAcrValues) {
062                this.requiredAcrValues = Set.copyOf(OidcAuthenticationOptions.requireAcrValues(requiredAcrValues));
063                JsonObject.Builder fields = JsonObject.builder();
064                for (String name : CLAIM_NAMES) token.getClaims().getClaim(name).ifPresent(value -> fields.put(name, value));
065                this.continuityClaims = fields.build(); this.clientId = requireNonNull(clientId);
066                this.nonceDigest = digest(((JsonString) token.getClaims().getClaim("nonce").orElseThrow()).getValue());
067                this.sessionId = token.getClaims().getClaim("sid").map(value -> ((JsonString) value).getValue()).orElse(null);
068        }
069        private OidcSessionReference(@NonNull JsonObject claims, @NonNull String clientId, @NonNull String nonceDigest, @NonNull Set<@NonNull String> requiredAcrValues) {
070                this.requiredAcrValues = Set.copyOf(OidcAuthenticationOptions.requireAcrValues(requiredAcrValues));
071                this.continuityClaims = claims; this.clientId = clientId; this.nonceDigest = nonceDigest;
072                this.sessionId = claims.find("sid").map(value -> ((JsonString) value).getValue()).orElse(null);
073        }
074        static @NonNull String digest(@NonNull String nonce) {
075                byte[] input = nonce.getBytes(StandardCharsets.UTF_8);
076                try {
077                        byte[] result = MessageDigest.getInstance("SHA-256").digest(input);
078                        try { return Base64.getUrlEncoder().withoutPadding().encodeToString(result); }
079                        finally { Arrays.fill(result, (byte) 0); }
080                } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 is unavailable."); }
081                finally { Arrays.fill(input, (byte) 0); }
082        }
083        /**
084         * Returns the original flow's immutable local ACR acceptance set. An empty set imposes no ACR acceptance
085         * requirement. This is comparison policy from trusted storage, never authenticated identity or current assurance.
086         * @return saved acceptable ACR values
087         * @since 1.0.0
088         */
089        public @NonNull Set<@NonNull String> getRequiredAcrValues() { return this.requiredAcrValues; }
090        @NonNull JsonObject continuityClaims() { return this.continuityClaims; }
091        boolean matchesNonce(@NonNull String nonce) { return ConstantTime.isEqual(this.nonceDigest, digest(nonce)); }
092        boolean matchesOriginalReference(@NonNull OidcSessionReference other) {
093                if (!this.clientId.equals(other.clientId) || !this.requiredAcrValues.equals(other.requiredAcrValues) || !ConstantTime.isEqual(this.nonceDigest, other.nonceDigest)
094                                || !audiences(this.continuityClaims).equals(audiences(other.continuityClaims))) return false;
095                Map<String, JsonValue> original = new HashMap<>(this.continuityClaims.getMembers());
096                Map<String, JsonValue> restored = new HashMap<>(other.continuityClaims.getMembers());
097                original.remove("aud"); restored.remove("aud");
098                return original.equals(restored);
099        }
100        void checkMicrosoftEntraClient(@NonNull String clientId) {
101                if (!this.clientId.equals(clientId) || OidcIssuerPolicy.tenantFromIssuer(this.continuityClaims.find("iss").map(value -> ((JsonString) value).getValue()).orElseThrow()) == null) throw mismatch();
102        }
103        void checkClient(@NonNull String issuer, @NonNull String clientId) {
104                if (!this.continuityClaims.find("iss").map(value -> ((JsonString) value).getValue()).orElseThrow().equals(issuer) || !this.clientId.equals(clientId)) throw mismatch();
105        }
106        void checkContinuity(@NonNull JwtClaims claims) {
107                try {
108                        JsonObject current = claims.toJsonObject();
109                        if (!Objects.equals(current.getMembers().get("iss"), this.continuityClaims.getMembers().get("iss"))
110                                        || !Objects.equals(current.getMembers().get("sub"), this.continuityClaims.getMembers().get("sub"))
111                                        || !Set.copyOf(claims.getAudiences()).equals(audiences(this.continuityClaims))
112                                        || !Objects.equals(current.getMembers().get("azp"), this.continuityClaims.getMembers().get("azp"))) throw mismatch();
113                        Instant issuedAt = claims.getIssuedAt().orElseThrow();
114                        if (issuedAt.isBefore(JsonFields.numericDate(this.continuityClaims, "iat").orElseThrow())) throw mismatch();
115                        if (current.getMembers().containsKey("auth_time") && !JsonFields.numericDate(current, "auth_time")
116                                        .equals(JsonFields.numericDate(this.continuityClaims, "auth_time"))) throw mismatch();
117                        if (current.getMembers().get("nonce") instanceof JsonString nonce && !matchesNonce(nonce.getValue())) throw mismatch();
118                } catch (JsonFieldException invalid) { throw mismatch(); }
119        }
120        private static @NonNull OidcValidationException mismatch() { return OidcValidationException.fromReason(OidcValidationException.Reason.REFRESHED_ID_TOKEN_MISMATCH); }
121        private static @NonNull Set<@NonNull String> audiences(@NonNull JsonObject claims) {
122                JsonValue value = claims.getMembers().get("aud"); Set<String> result = new HashSet<>();
123                if (value instanceof JsonString text && !text.getValue().isEmpty()) result.add(text.getValue());
124                else if (value instanceof JsonArray array && !array.getElements().isEmpty()) {
125                        for (JsonValue item : array.getElements()) {
126                                if (!(item instanceof JsonString text) || text.getValue().isEmpty()) throw new IllegalArgumentException();
127                                result.add(text.getValue());
128                        }
129                } else throw new IllegalArgumentException();
130                return Set.copyOf(result);
131        }
132        /**
133         * Explicitly serializes the original continuity fields and nonce digest for trusted storage. This discloses
134         * issuer, subject and session data; do not log it. It neither authenticates fields nor creates an identity.
135         * @return versioned, bounded JSON storage form
136         * @since 1.0.0
137         */
138        public @NonNull String toSerializedForm() {
139                String value = JsonObject.builder().put("v", 2L).put("client_id", this.clientId).put("claims", this.continuityClaims).put("nonce_digest", this.nonceDigest).put("required_acr_values", JsonArray.fromElements(this.requiredAcrValues.stream().sorted().map(acr -> (JsonValue) JsonString.fromValue(acr)).toList())).build().toJson();
140                if (value.length() > MAXIMUM_BYTES) throw invalid();
141                byte[] bytes;
142                try { bytes = StrictUtf8.encode(value); } catch (EncodingException malformed) { throw invalid(); }
143                try { if (bytes.length > MAXIMUM_BYTES) throw invalid(); return value; } finally { Arrays.fill(bytes, (byte) 0); }
144        }
145        /**
146         * Parses a bounded version-2 reference from trusted application storage, returning a fixed rejection for invalid structure.
147         * Version 1 lacks the original acceptance policy and is rejected; authenticate again rather than infer it.
148         * This supplies no identity. Untrusted browser storage must use
149         * {@link #fromSealedFormResult(String, StateSealer, String)}.
150         * @param serializedForm versioned storage form
151         * @return parsed reference or fixed rejection
152         * @since 1.0.0
153         */
154        @CheckReturnValue
155        public static @NonNull OidcSessionReferenceParseResult fromSerializedFormResult(@NonNull String serializedForm) {
156                try { return OidcSessionReferenceParseResult.fromReference(parseSerializedForm(serializedForm)); }
157                catch (OidcValidationException rejected) { return OidcSessionReferenceParseResult.fromRejection(); }
158        }
159
160        /**
161         * Parses a bounded reference from trusted application storage. This factory checks structure only, supplies no
162         * identity and accepts no credentials. Untrusted browser storage must use {@link #fromSealedFormResult(String, StateSealer, String)}.
163         * @param serializedForm versioned storage form
164         * @return continuity reference, not authenticated identity
165         * @throws OidcValidationException if the structure is invalid
166         * @since 1.0.0
167         */
168        private static @NonNull OidcSessionReference parseSerializedForm(@NonNull String serializedForm) {
169                requireNonNull(serializedForm); byte @Nullable [] bytes = null;
170                try {
171                        if (serializedForm.length() > MAXIMUM_BYTES) throw new IllegalArgumentException();
172                        bytes = StrictUtf8.encode(serializedForm); JsonValue value = JsonCodec.parse(bytes, JsonLimits.protocolDocument(MAXIMUM_BYTES));
173                        if (!(value instanceof JsonObject envelope) || !envelope.getMembers().keySet().equals(Set.of("v", "client_id", "claims", "nonce_digest", "required_acr_values"))
174                                        || !referenceLong(envelope, "v").filter(v -> v == 2).isPresent() || !(envelope.getMembers().get("claims") instanceof JsonObject claims)) throw new IllegalArgumentException();
175                        String client = JsonFields.string(envelope, "client_id").filter(v -> !v.isEmpty()).orElseThrow(IllegalArgumentException::new);
176                        String digest = JsonFields.string(envelope, "nonce_digest").orElseThrow(IllegalArgumentException::new);
177                        if (digest.length() != 43) throw new IllegalArgumentException();
178                        byte[] decoded = Base64Url.decode(digest);
179                        try { if (decoded.length != 32) throw new IllegalArgumentException(); }
180                        finally { Arrays.fill(decoded, (byte) 0); }
181                        if (!CLAIM_NAMES.containsAll(claims.getMembers().keySet()) || !JsonFields.string(claims, "iss").filter(v -> !v.isEmpty()).isPresent()) throw new IllegalArgumentException();
182                        String subject = JsonFields.string(claims, "sub").orElseThrow(IllegalArgumentException::new);
183                        if (subject.isEmpty() || subject.length() > 255 || subject.chars().anyMatch(c -> c > 0x7f)) throw new IllegalArgumentException();
184                        if (!audiences(claims).contains(client) || JsonFields.numericDate(claims, "iat").isEmpty()) throw new IllegalArgumentException();
185                        JsonFields.numericDate(claims, "auth_time");
186                        for (String name : List.of("azp", "sid")) if (claims.getMembers().containsKey(name) && !(claims.getMembers().get(name) instanceof JsonString)) throw new IllegalArgumentException();
187                        if (!(envelope.getMembers().get("required_acr_values") instanceof JsonArray values)) throw new IllegalArgumentException();
188                        Set<String> required = new HashSet<>();
189                        for (JsonValue item : values.getElements()) {
190                                if (!(item instanceof JsonString text) || !required.add(text.getValue())) throw new IllegalArgumentException();
191                        }
192                        return new OidcSessionReference(claims, client, digest, OidcAuthenticationOptions.requireAcrValues(required));
193                } catch (JsonParseException | JsonFieldException | EncodingException | IllegalArgumentException invalid) { throw invalid(); }
194                finally { if (bytes != null) Arrays.fill(bytes, (byte) 0); }
195        }
196        /**
197         * Seals a reference under the OIDC-session type, an application-specific context and explicit lifetime. The sealer's lifetime and size
198         * bounds apply. The application owns session lifetime and refresh-token storage.
199         * @param sealer application sealer
200         * @param context application-specific OIDC session context
201         * @param lifetime how long the sealed reference opens
202         * @return sealed storage form
203         * @since 1.0.0
204         */
205        public @NonNull String toSealedForm(@NonNull StateSealer sealer, @NonNull String context, @NonNull Duration lifetime) {
206                return SealedStateAccess.get().sealForLifetime(requireNonNull(sealer), SealedStateType.OIDC_SESSION,
207                                toSerializedForm(), requireNonNull(context), requireNonNull(lifetime));
208        }
209        /**
210         * Opens a sealed reference under its original context. Invalid sealed state and invalid reference structure
211         * return the same fixed, value-free rejection. No identity is created by opening a reference.
212         * @param sealedForm sealed storage form
213         * @param sealer application sealer
214         * @param context original OIDC session context
215         * @return parsed reference or fixed rejection
216         * @since 1.0.0
217         */
218        @CheckReturnValue
219        public static @NonNull OidcSessionReferenceParseResult fromSealedFormResult(@NonNull String sealedForm,
220                        @NonNull StateSealer sealer, @NonNull String context) {
221                try {
222                        String opened = SealedStateAccess.get().unsealUsingConfiguredClock(requireNonNull(sealer),
223                                        SealedStateType.OIDC_SESSION, requireNonNull(sealedForm), requireNonNull(context));
224                        return fromSerializedFormResult(opened);
225                } catch (UnsealException invalid) { return OidcSessionReferenceParseResult.fromRejection(); }
226        }
227
228        private static @NonNull Optional<@NonNull Long> referenceLong(@NonNull JsonObject object, @NonNull String name) {
229                return object.find(name).flatMap(value -> {
230                        if (!(value instanceof JsonNumber number)) throw new IllegalArgumentException();
231                        return number.getLongValueExact();
232                });
233        }
234        private static @NonNull OidcValidationException invalid() { return OidcValidationException.fromReason(OidcValidationException.Reason.SESSION_REFERENCE_INVALID); }
235        /**
236         * Returns the original session ID, if present. This reference is not proof of identity.
237         * @return session ID
238         * @since 1.0.0
239         */
240        public @NonNull Optional<@NonNull String> getSessionId() { return Optional.ofNullable(this.sessionId); }
241        /**
242         * Redacts all session continuity fields.
243         * @return a redacted description
244         * @since 1.0.0
245         */
246        @Override public @NonNull String toString() { return "OidcSessionReference{session=<redacted>}"; }
247}