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.saml; 018 019import org.jspecify.annotations.NonNull; 020import org.jspecify.annotations.Nullable; 021import javax.annotation.concurrent.ThreadSafe; 022import java.time.Clock; 023import java.time.Duration; 024import java.time.Instant; 025import java.util.Comparator; 026import java.util.HashMap; 027import java.util.Map; 028import java.util.NavigableSet; 029import java.util.Objects; 030import java.util.TreeSet; 031import java.util.concurrent.TimeUnit; 032import java.util.concurrent.locks.ReentrantLock; 033import java.util.function.Predicate; 034 035/** 036 * Bounded, process-local store for pending SAML login and logout with atomic single consumption. 037 * Restarting this process loses pending attempts. Distributed deployments supply their own shared store. 038 * Expiry maintenance removes at most 64 unrelated expired records per operation, plus the 039 * addressed record when expired. An ordered index retains exactly one node per stored record; 040 * consuming a record also unlinks its node. Operations remain serialized, including conditional 041 * validation, and their time budget does not guarantee a wall-clock execution bound. 042 * 043 * @since 1.0.0 044 */ 045@ThreadSafe 046public final class InMemoryPendingSamlAuthenticationStore implements PendingSamlAuthenticationStore { 047 private static final int CLEANUP_BATCH = 64; 048 private final @NonNull ReentrantLock lock = new ReentrantLock(); 049 private final @NonNull Map<@NonNull String, @NonNull Entry> entries; 050 private final @NonNull NavigableSet<@NonNull Entry> expirations = new TreeSet<>( 051 Comparator.comparing(Entry::expiresAt).thenComparing(Entry::key)); 052 private final @NonNull Clock clock; 053 private final int maximumEntries; 054 private @NonNull Instant lastObserved = Instant.MIN; 055 056 private InMemoryPendingSamlAuthenticationStore(@NonNull Clock clock, int maximumEntries) { 057 this(clock,maximumEntries,new HashMap<>()); 058 } 059 060 @SuppressWarnings("unchecked") 061 InMemoryPendingSamlAuthenticationStore(@NonNull Clock clock, int maximumEntries, 062 @NonNull Map<@NonNull String, ?> entries) { 063 this.clock = clock; 064 this.maximumEntries = maximumEntries; 065 Objects.requireNonNull(entries); 066 if (!entries.isEmpty()) throw new IllegalArgumentException("Initial SAML pending entries must be empty"); 067 this.entries = (Map<@NonNull String,@NonNull Entry>)(Map<?,?>)entries; 068 } 069 070 /** 071 * Creates an empty store with an explicit capacity. 072 * 073 * @param clock validation clock 074 * @param maximumEntries maximum live attempts, from 1 to 1000000 075 * @return local store 076 * @since 1.0.0 077 */ 078 public static @NonNull InMemoryPendingSamlAuthenticationStore fromLimit(@NonNull Clock clock, 079 @NonNull Integer maximumEntries) { 080 Objects.requireNonNull(clock); 081 Objects.requireNonNull(maximumEntries); 082 if (maximumEntries < 1 || maximumEntries > 1_000_000) 083 throw new IllegalArgumentException("Invalid SAML pending capacity"); 084 return new InMemoryPendingSamlAuthenticationStore(clock, maximumEntries); 085 } 086 087 /** 088 * Creates a process-local store with 65536 slots. 089 * 090 * @return local store 091 * @since 1.0.0 092 */ 093 public static @NonNull InMemoryPendingSamlAuthenticationStore fromDefaults() { 094 return fromLimit(Clock.systemUTC(), 65_536); 095 } 096 097 @Override public @NonNull SamlPendingSaveResult save(@NonNull String browserBinding, 098 @NonNull String relayStateHandle, @NonNull String sealedRecord, 099 @NonNull Instant expiresAt, @NonNull Duration remaining) { 100 Objects.requireNonNull(browserBinding); 101 Objects.requireNonNull(relayStateHandle); 102 Objects.requireNonNull(sealedRecord); 103 Objects.requireNonNull(expiresAt); 104 Objects.requireNonNull(remaining); 105 if (browserBinding.isEmpty() || relayStateHandle.isEmpty() || sealedRecord.isEmpty()) 106 throw new IllegalArgumentException("Empty pending key or record"); 107 long deadline = deadline(remaining); 108 if (deadline == 0) return SamlPendingSaveResult.UNAVAILABLE; 109 if (!acquire(deadline)) return SamlPendingSaveResult.UNAVAILABLE; 110 try { 111 Instant now = now(); 112 if (now == null || !now.isBefore(expiresAt) || expired(deadline)) 113 return SamlPendingSaveResult.UNAVAILABLE; 114 String key = key(browserBinding, relayStateHandle); 115 Entry existing = entries.get(key); 116 if (existing != null && now.isBefore(existing.expiresAt())) 117 return SamlPendingSaveResult.ALREADY_PRESENT; 118 if (existing != null) remove(existing); 119 if (!cleanExpired(now, deadline)) return SamlPendingSaveResult.UNAVAILABLE; 120 if (entries.size() >= maximumEntries) return SamlPendingSaveResult.CAPACITY_REFUSED; 121 if (expired(deadline)) return SamlPendingSaveResult.UNAVAILABLE; 122 Entry added = new Entry(key, sealedRecord, expiresAt); 123 entries.put(key, added); 124 expirations.add(added); 125 return expired(deadline) ? SamlPendingSaveResult.INDETERMINATE : SamlPendingSaveResult.SAVED; 126 } finally { lock.unlock(); } 127 } 128 129 @Override public @NonNull SamlPendingConsumeResult consume(@NonNull String browserBinding, 130 @NonNull String relayStateHandle, @NonNull Duration remaining) { 131 return consumeIfMatches(browserBinding, relayStateHandle, record -> true, remaining); 132 } 133 134 @SuppressWarnings("ReferenceEquality") // Removal requires the same live Entry, including identical replacements. 135 @Override public @NonNull SamlPendingConsumeResult consumeIfMatches(@NonNull String browserBinding, 136 @NonNull String relayStateHandle, @NonNull Predicate<@NonNull String> sealedRecordMatches, 137 @NonNull Duration remaining) { 138 Objects.requireNonNull(browserBinding); 139 Objects.requireNonNull(relayStateHandle); 140 Objects.requireNonNull(sealedRecordMatches); 141 Objects.requireNonNull(remaining); 142 if (browserBinding.isEmpty() || relayStateHandle.isEmpty()) 143 throw new IllegalArgumentException("Empty pending key"); 144 long deadline = deadline(remaining); 145 if (deadline == 0 || !acquire(deadline)) return SamlPendingConsumeResult.Unavailable.INSTANCE; 146 try { 147 Instant now = now(); 148 if (now == null || expired(deadline)) return SamlPendingConsumeResult.Unavailable.INSTANCE; 149 if (!cleanExpired(now, deadline)) return SamlPendingConsumeResult.Unavailable.INSTANCE; 150 String key = key(browserBinding, relayStateHandle); 151 Entry existing = entries.get(key); 152 if (existing == null) return SamlPendingConsumeResult.Missing.INSTANCE; 153 if (!now.isBefore(existing.expiresAt())) { 154 remove(existing); 155 return SamlPendingConsumeResult.Missing.INSTANCE; 156 } 157 boolean matches; 158 try { matches = sealedRecordMatches.test(existing.sealedRecord()); } 159 catch (RuntimeException exception) { return SamlPendingConsumeResult.Unavailable.INSTANCE; } 160 now = now(); 161 if (now == null || expired(deadline)) return SamlPendingConsumeResult.Unavailable.INSTANCE; 162 // The lock is reentrant: validation must not authorize a record already consumed or 163 // replaced by a recursive call made by the predicate. 164 if (entries.get(key) != existing || !now.isBefore(existing.expiresAt()) || !matches) 165 return SamlPendingConsumeResult.Missing.INSTANCE; 166 if (expired(deadline)) return SamlPendingConsumeResult.Unavailable.INSTANCE; 167 remove(existing); 168 return expired(deadline) ? SamlPendingConsumeResult.Indeterminate.INSTANCE 169 : SamlPendingConsumeResult.Consumed.fromSealedRecord(existing.sealedRecord()); 170 } finally { lock.unlock(); } 171 } 172 173 // Called only under lock after a non-rollback clock observation. No lazy tombstones: 174 // arbitrary consume/save churn must not grow the expiry index beyond store capacity. 175 private boolean cleanExpired(@NonNull Instant now, long deadline) { 176 for (int removed = 0; removed < CLEANUP_BATCH; removed++) { 177 if (expired(deadline)) return false; 178 if (expirations.isEmpty()) return true; 179 Entry first = expirations.first(); 180 if (now.isBefore(first.expiresAt())) return true; 181 remove(first); 182 } 183 return !expired(deadline); 184 } 185 186 private void remove(@NonNull Entry entry) { 187 entries.remove(entry.key()); 188 expirations.remove(entry); 189 } 190 191 private @Nullable Instant now() { 192 Instant value; 193 try { value = clock.instant(); } 194 catch (RuntimeException exception) { return null; } 195 if (value.isBefore(lastObserved)) return null; 196 lastObserved = value; 197 return value; 198 } 199 200 private static @NonNull String key(@NonNull String binding, @NonNull String relay) { 201 return binding.length() + ":" + binding + relay.length() + ":" + relay; 202 } 203 204 private static long deadline(@NonNull Duration remaining) { 205 if (remaining.isZero() || remaining.isNegative() || Thread.currentThread().isInterrupted()) return 0; 206 long nanos; 207 try { nanos = remaining.compareTo(Duration.ofSeconds(30)) > 0 208 ? Duration.ofSeconds(30).toNanos() : remaining.toNanos(); } 209 catch (ArithmeticException exception) { nanos = Duration.ofSeconds(30).toNanos(); } 210 return System.nanoTime() + nanos; 211 } 212 213 private boolean acquire(long deadline) { 214 try { 215 long wait = deadline - System.nanoTime(); 216 return wait > 0 && lock.tryLock(wait, TimeUnit.NANOSECONDS); 217 } catch (InterruptedException exception) { 218 Thread.currentThread().interrupt(); 219 return false; 220 } 221 } 222 223 static boolean expired(long deadline) { 224 return expiredAt(deadline, System.nanoTime(), Thread.currentThread().isInterrupted()); 225 } 226 227 static boolean expiredAt(long deadline, long now, boolean interrupted) { 228 return interrupted || deadline - now <= 0; 229 } 230 231 /** 232 * Redacts pending data. 233 * 234 * @return redacted description 235 * @since 1.0.0 236 */ 237 @Override public @NonNull String toString() { return "InMemoryPendingSamlAuthenticationStore{<redacted>}"; } 238 239 private record Entry(@NonNull String key, @NonNull String sealedRecord, @NonNull Instant expiresAt) { } 240}