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 */ 016package com.revetsec.saml; 017 018import com.google.errorprone.annotations.CheckReturnValue; 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.crypto.UnsealException; 024import com.revetsec.internal.encoding.Base64Url; 025import com.revetsec.internal.encoding.EncodingException; 026import com.revetsec.internal.encoding.StrictUtf8; 027import org.jspecify.annotations.NonNull; 028import org.jspecify.annotations.Nullable; 029import javax.annotation.concurrent.Immutable; 030import java.time.Clock; 031import java.time.Instant; 032import java.time.format.DateTimeParseException; 033import java.util.Arrays; 034import java.util.Optional; 035 036import static java.util.Objects.requireNonNull; 037 038/** 039 * Identity and session fields from a checked assertion for later front-channel logout matching. 040 * The application stores this reference alongside its own application session. 041 * 042 * @since 1.0.0 043 */ 044@Immutable 045public final class SamlSessionReference { 046 // Canonical v1 is ASCII. Well-formed UTF-16 needs at most three UTF-8 bytes per code unit. 047 // Three required fields: 4 * (256 + 2048 + 4096) = 25,600 base64url characters. 048 // Five optional 2048-unit fields: 5 * ceil(4 * (1 + 3 * 2048) / 3) = 40,970. 049 // Instant's longest canonical text is 37 ASCII characters: its optional part needs 51. 050 // Version plus nine separators add 10. This bound covers the existing field profile. 051 private static final int MAXIMUM_SERIALIZED_LENGTH = 66_631; 052 private final @NonNull String connectionId; 053 private final @NonNull String identityProviderEntityId; 054 private final @NonNull SamlNameId nameId; 055 private final @Nullable String sessionIndex; 056 private final @Nullable Instant sessionNotOnOrAfter; 057 058 SamlSessionReference(@NonNull String connectionId, @NonNull String identityProviderEntityId, 059 @NonNull SamlNameId nameId, @Nullable String sessionIndex, 060 @Nullable Instant sessionNotOnOrAfter) { 061 this.connectionId = connectionId; 062 this.identityProviderEntityId = identityProviderEntityId; 063 this.nameId = nameId; 064 this.sessionIndex = sessionIndex; 065 this.sessionNotOnOrAfter = sessionNotOnOrAfter; 066 } 067 068 /** 069 * Returns the application-defined IdP namespace. 070 * 071 * @return connection ID 072 * @since 1.0.0 073 */ 074 public @NonNull String getIdentityProviderConnectionId() { return connectionId; } 075 /** 076 * Returns the checked IdP entity ID. 077 * 078 * @return entity ID 079 * @since 1.0.0 080 */ 081 public @NonNull String getIdentityProviderEntityId() { return identityProviderEntityId; } 082 /** 083 * Returns the checked NameID and qualifiers used for logout matching. 084 * 085 * @return NameID 086 * @since 1.0.0 087 */ 088 public @NonNull SamlNameId getNameId() { return nameId; } 089 /** 090 * Returns the session index when the IdP supplied one. 091 * 092 * @return optional session index 093 * @since 1.0.0 094 */ 095 public @NonNull Optional<@NonNull String> getSessionIndex() { return Optional.ofNullable(sessionIndex); } 096 /** 097 * Returns the IdP's session expiry when supplied. 098 * 099 * @return optional expiry 100 * @since 1.0.0 101 */ 102 public @NonNull Optional<@NonNull Instant> getSessionNotOnOrAfter() { 103 return Optional.ofNullable(sessionNotOnOrAfter); 104 } 105 106 /** 107 * Serializes the checked logout continuity fields for trusted application storage. 108 * This contains personal data and is not itself proof of identity or authenticity. 109 * The version-1 form uses at most 66,631 ASCII characters, including base64url expansion 110 * of well-formed fields at their existing validation limits. This storage budget is 111 * separate from a sealer's configured limit and from browser cookie limits. 112 * 113 * @return bounded versioned storage form 114 * @since 1.0.0 115 */ 116 public @NonNull String toSerializedForm() { 117 try { 118 String serialized = "1." + part(connectionId) + '.' + part(identityProviderEntityId) 119 + '.' + part(nameId.getValue()) + '.' + optionalPart(nameId.rawFormat()) 120 + '.' + optionalPart(nameId.rawNameQualifier()) 121 + '.' + optionalPart(nameId.rawSpNameQualifier()) 122 + '.' + optionalPart(nameId.rawSpProvidedId()) 123 + '.' + optionalPart(sessionIndex) 124 + '.' + optionalPart(sessionNotOnOrAfter == null ? null 125 : sessionNotOnOrAfter.toString()); 126 if (serialized.length() > MAXIMUM_SERIALIZED_LENGTH) throw invalid(); 127 return serialized; 128 } catch (EncodingException exception) { throw invalid(); } 129 } 130 131 /** 132 * Restores a bounded reference from trusted application storage. It validates 133 * structure, but cannot authenticate the original SAML assertion. Browser-side 134 * storage must use {@link #fromSealedFormResult(String, StateSealer, String, Clock)}. 135 * 136 * @param serializedForm versioned storage form 137 * @return parsed logout continuity reference or a fixed structural rejection, never authenticated identity 138 * @since 1.0.0 139 */ 140 @CheckReturnValue 141 public static @NonNull SamlSessionReferenceParseResult fromSerializedFormResult(@NonNull String serializedForm) { 142 try { 143 return SamlSessionReferenceParseResult.fromReference(parseSerializedForm(serializedForm)); 144 } catch (IllegalArgumentException rejected) { 145 return SamlSessionReferenceParseResult.fromRejection(); 146 } 147 } 148 149 private static @NonNull SamlSessionReference parseSerializedForm(@NonNull String serializedForm) { 150 requireNonNull(serializedForm); 151 try { 152 if (serializedForm.length() > MAXIMUM_SERIALIZED_LENGTH) throw invalid(); 153 String[] fields = serializedForm.split("\\.", -1); 154 if (fields.length != 10 || !fields[0].equals("1")) throw invalid(); 155 String connection = required(fields[1], 256); 156 String idp = required(fields[2], 2048); 157 String value = required(fields[3], 4096); 158 SamlNameId restoredName = new SamlNameId(value, 159 optional(fields[4], 2048), optional(fields[5], 2048), 160 optional(fields[6], 2048), optional(fields[7], 2048)); 161 String index = optional(fields[8], 2048); 162 String end = optional(fields[9], 64); 163 Instant expiry = end == null ? null : Instant.parse(end); 164 return new SamlSessionReference(connection, idp, restoredName, index, expiry); 165 } catch (EncodingException | DateTimeParseException | IllegalArgumentException invalid) { 166 throw invalid(); 167 } 168 } 169 170 private static @NonNull String part(@NonNull String value) throws EncodingException { 171 byte[] bytes = StrictUtf8.encode(value); 172 try { return Base64Url.encode(bytes); } 173 finally { Arrays.fill(bytes, (byte) 0); } 174 } 175 176 private static @NonNull String optionalPart(@Nullable String value) throws EncodingException { 177 return value == null ? "-" : part("x" + value); 178 } 179 180 private static @NonNull String required(@NonNull String encoded, int maximum) 181 throws EncodingException { 182 String value = decoded(encoded); 183 if (value.isEmpty() || value.length() > maximum) throw invalid(); 184 return value; 185 } 186 187 private static @Nullable String optional(@NonNull String encoded, int maximum) 188 throws EncodingException { 189 if (encoded.equals("-")) return null; 190 String value = decoded(encoded); 191 if (!value.startsWith("x") || value.length() - 1 > maximum) throw invalid(); 192 return value.substring(1); 193 } 194 195 private static @NonNull String decoded(@NonNull String encoded) throws EncodingException { 196 if (encoded.isEmpty() || encoded.length() > MAXIMUM_SERIALIZED_LENGTH) throw invalid(); 197 byte[] bytes = Base64Url.decode(encoded); 198 try { 199 if (bytes.length > MAXIMUM_SERIALIZED_LENGTH) throw invalid(); 200 return StrictUtf8.decode(bytes); 201 } finally { Arrays.fill(bytes, (byte) 0); } 202 } 203 204 /** 205 * Seals the reference under a SAML-specific type and application context. 206 * The application chooses an expiry no later than its own session lifetime. 207 * A valid reference can exceed even the largest allowed seal. Prefer 208 * {@link #toSealedFormResult(StateSealer, String, Instant)} to handle that expected outcome. 209 * 210 * @param sealer active and verification keys 211 * @param context application-selected session context 212 * @param expiresAt absolute seal expiry 213 * @return sealed storage form 214 * @throws IllegalArgumentException if an argument is invalid or the reference exceeds the configured seal limit 215 * @throws IllegalStateException if the cryptographic provider cannot seal 216 * @since 1.0.0 217 */ 218 public @NonNull String toSealedForm(@NonNull StateSealer sealer, @NonNull String context, 219 @NonNull Instant expiresAt) { 220 return SealedStateAccess.get().seal(requireNonNull(sealer), SealedStateType.SAML_SESSION, 221 toSerializedForm(), requireNonNull(context), requireNonNull(expiresAt)); 222 } 223 224 /** 225 * Seals logout continuity fields or reports a size limit or provider failure explicitly. 226 * Only {@link SamlSessionReferenceSealResult.Succeeded} contains a sealed value. A valid 227 * reference need not fit a seal: use trusted server-side storage when it is too large, 228 * without truncating identifiers or weakening the sealer's configured bound. 229 * Size refusal performs no random draws or encryption. Null and invalid arguments remain 230 * programmer errors, including an invalid context even when the reference is too large. 231 * 232 * @param sealer active and verification keys 233 * @param context application-selected session context 234 * @param expiresAt absolute seal expiry, no later than the application's session lifetime 235 * @return a sealed value, an expected size refusal, or an unavailable cryptographic provider 236 * @throws NullPointerException if a required argument is null 237 * @throws IllegalArgumentException if the context or reference text is invalid 238 * @since 1.0.0 239 */ 240 @CheckReturnValue 241 public @NonNull SamlSessionReferenceSealResult toSealedFormResult(@NonNull StateSealer sealer, 242 @NonNull String context, @NonNull Instant expiresAt) { 243 requireNonNull(sealer); 244 requireNonNull(context); 245 requireNonNull(expiresAt); 246 SealerV1.requireContext(context); 247 String serialized = toSerializedForm(); 248 SealedStateAccess.Operations access = SealedStateAccess.get(); 249 // The versioned storage form is ASCII, so characters equal plaintext UTF-8 bytes. 250 long length = SealerV1.sealedLength(access.getActiveKeyId(sealer).length(), serialized.length()); 251 if (length > access.getMaximumSealedLength(sealer)) 252 return SamlSessionReferenceSealResult.TooLarge.INSTANCE; 253 try { 254 return new SamlSessionReferenceSealResult.Succeeded(access.seal(sealer, 255 SealedStateType.SAML_SESSION, serialized, context, expiresAt)); 256 } catch (IllegalStateException unavailable) { 257 return SamlSessionReferenceSealResult.Unavailable.INSTANCE; 258 } 259 } 260 261 /** 262 * Opens a SAML session reference under the same application context. 263 * Opening does not create or authenticate an identity. 264 * 265 * @param sealedForm sealed storage form 266 * @param sealer active and verification keys 267 * @param context original application context 268 * @param clock time source for expiry 269 * @return parsed logout continuity reference or a fixed sealed-state/structural rejection 270 * @since 1.0.0 271 */ 272 @CheckReturnValue 273 public static @NonNull SamlSessionReferenceParseResult fromSealedFormResult(@NonNull String sealedForm, 274 @NonNull StateSealer sealer, @NonNull String context, @NonNull Clock clock) { 275 try { 276 return fromSerializedFormResult(SealedStateAccess.get().unseal(requireNonNull(sealer), 277 SealedStateType.SAML_SESSION, requireNonNull(sealedForm), requireNonNull(context), 278 requireNonNull(clock))); 279 } catch (UnsealException exception) { 280 return SamlSessionReferenceParseResult.fromSealedStateRejection(); 281 } 282 } 283 284 private static @NonNull IllegalArgumentException invalid() { 285 return new IllegalArgumentException("Invalid SAML session reference."); 286 } 287 /** 288 * Redacts the session identifiers. 289 * 290 * @return redacted description 291 * @since 1.0.0 292 */ 293 @Override public @NonNull String toString() { return "SamlSessionReference{<redacted>}"; } 294}