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.oauth; 018 019import com.revetsec.internal.Limits; 020import com.revetsec.internal.http.Deadline; 021import com.revetsec.internal.encoding.EncodingException; 022import com.revetsec.internal.encoding.StrictUtf8; 023import org.jspecify.annotations.NonNull; 024import org.jspecify.annotations.Nullable; 025 026import com.google.errorprone.annotations.CheckReturnValue; 027import javax.annotation.concurrent.NotThreadSafe; 028import javax.annotation.concurrent.ThreadSafe; 029import java.time.Clock; 030import java.time.Duration; 031import java.time.Instant; 032import java.util.HashMap; 033import java.util.Iterator; 034import java.util.Map; 035import java.util.Optional; 036import java.util.Arrays; 037import java.util.concurrent.TimeUnit; 038import java.util.concurrent.atomic.AtomicLong; 039import java.util.concurrent.locks.ReentrantLock; 040 041import static java.util.Objects.requireNonNull; 042 043/** 044 * A bounded, single-process pending-authorization store. It starts no worker thread; expiry is removed lazily on 045 * saves and consumes. An observed backward clock step cannot revive a record past an earlier observed expiry. 046 * A full store refuses a new login without evicting another live login. Use a durable shared 047 * {@link PendingAuthorizationStore} when callbacks may land on other nodes or after a restart. 048 * 049 * @author <a href="https://www.revetkn.com">Mark Allen</a> 050 * @since 1.0.0 051 */ 052@ThreadSafe 053public final class InMemoryPendingAuthorizationStore implements PendingAuthorizationStore { 054 private final @NonNull ReentrantLock lock = new ReentrantLock(); 055 private final @NonNull Map<@NonNull Key, @NonNull Entry> entries; 056 private final int maximumLiveEntries; 057 private final long maximumChargedBytes; 058 private final int maximumOpaqueRecordBytes; 059 private final @NonNull Clock clock; 060 private final @NonNull AtomicLong chargedBytes = new AtomicLong(); 061 private @Nullable Instant lastObserved; 062 063 private InMemoryPendingAuthorizationStore(@NonNull Builder builder) { 064 this(builder, new HashMap<>()); 065 } 066 067 @SuppressWarnings("unchecked") 068 InMemoryPendingAuthorizationStore(@NonNull Builder builder, @NonNull Map<?, ?> entries) { 069 if (builder.maximumOpaqueRecordBytes > builder.maximumChargedBytes) 070 throw new IllegalArgumentException("One record limit must not exceed the total store byte limit."); 071 if (!entries.isEmpty()) throw new IllegalArgumentException("Initial pending-authorization storage must be empty."); 072 this.entries = (Map<@NonNull Key, @NonNull Entry>) entries; 073 this.maximumLiveEntries = builder.maximumLiveEntries; 074 this.maximumChargedBytes = builder.maximumChargedBytes; 075 this.maximumOpaqueRecordBytes = builder.maximumOpaqueRecordBytes; 076 this.clock = builder.clock; 077 } 078 079 /** 080 * Starts a builder with bounded defaults. 081 * 082 * @return the builder 083 * @since 1.0.0 084 */ 085 public static @NonNull Builder builder() { 086 return new Builder(); 087 } 088 089 /** 090 * Constructs a store with the default limits and UTC system clock. 091 * 092 * @return the store 093 * @since 1.0.0 094 */ 095 public static @NonNull InMemoryPendingAuthorizationStore fromDefaults() { 096 return builder().build(); 097 } 098 099 /** 100 * Saves a record whose expiry is after now and no more than 60 minutes away. No live record is evicted. 101 * 102 * @param browserBinding the browser-specific binding 103 * @param state the authorization state 104 * @param opaqueRecord the opaque record 105 * @param expiresAt its exact expiry 106 * @param remaining positive time left for this operation 107 * @return the fixed storage outcome 108 * @since 1.0.0 109 */ 110 @Override 111 @CheckReturnValue 112 public @NonNull PendingAuthorizationSaveResult save(@NonNull String browserBinding, @NonNull String state, @NonNull String opaqueRecord, 113 @NonNull Instant expiresAt, @NonNull Duration remaining) { 114 requireNonNull(remaining); 115 checkLookupInputs(browserBinding, state); 116 requireNonNull(opaqueRecord); 117 requireNonNull(expiresAt); 118 if (opaqueRecord.isEmpty()) 119 throw new IllegalArgumentException("A pending record must not be empty."); 120 if (remaining.isZero() || remaining.isNegative() || Thread.currentThread().isInterrupted()) 121 return PendingAuthorizationSaveResult.UNAVAILABLE; 122 Deadline deadline = Deadline.fromNow(remaining); 123 if (deadline.isExpired()) return PendingAuthorizationSaveResult.UNAVAILABLE; 124 long recordBytes = utf8Length(opaqueRecord, this.maximumOpaqueRecordBytes); 125 if (deadline.isExpired() || Thread.currentThread().isInterrupted()) return PendingAuthorizationSaveResult.UNAVAILABLE; 126 if (recordBytes > this.maximumOpaqueRecordBytes) 127 return PendingAuthorizationSaveResult.CAPACITY_REFUSED; 128 long charged = recordBytes + utf8Length(browserBinding, this.maximumChargedBytes) 129 + utf8Length(state, this.maximumChargedBytes); 130 if (deadline.isExpired() || Thread.currentThread().isInterrupted()) return PendingAuthorizationSaveResult.UNAVAILABLE; 131 if (charged > this.maximumChargedBytes) 132 return PendingAuthorizationSaveResult.CAPACITY_REFUSED; 133 try { acquire(deadline); } 134 catch (PendingAuthorizationStoreException unavailable) { return PendingAuthorizationSaveResult.UNAVAILABLE; } 135 try { 136 if (deadline.isExpired() || Thread.currentThread().isInterrupted()) return PendingAuthorizationSaveResult.UNAVAILABLE; 137 Instant clockNow; 138 try { clockNow = this.clock.instant(); } 139 catch (RuntimeException unavailable) { return PendingAuthorizationSaveResult.UNAVAILABLE; } 140 if (clockNow == null || deadline.isExpired() || Thread.currentThread().isInterrupted()) 141 return PendingAuthorizationSaveResult.UNAVAILABLE; 142 Instant now = observedTime(clockNow); 143 if (!expiresAt.isAfter(now)) return PendingAuthorizationSaveResult.UNAVAILABLE; 144 if (expiresAt.isAfter(now.plus(Duration.ofMinutes(60)))) 145 throw new IllegalArgumentException("A pending record expiry must be within 60 minutes."); 146 pruneExpired(now); 147 if (deadline.isExpired() || Thread.currentThread().isInterrupted()) return PendingAuthorizationSaveResult.UNAVAILABLE; 148 Key key = new Key(browserBinding, state); 149 if (this.entries.containsKey(key)) return PendingAuthorizationSaveResult.ALREADY_PRESENT; 150 if (this.entries.size() >= this.maximumLiveEntries 151 || charged > this.maximumChargedBytes - this.chargedBytes.get()) 152 return PendingAuthorizationSaveResult.CAPACITY_REFUSED; 153 if (deadline.isExpired() || Thread.currentThread().isInterrupted()) return PendingAuthorizationSaveResult.UNAVAILABLE; 154 this.entries.put(key, new Entry(opaqueRecord, expiresAt, charged)); 155 this.chargedBytes.addAndGet(charged); 156 return deadline.isExpired() || Thread.currentThread().isInterrupted() 157 ? PendingAuthorizationSaveResult.INDETERMINATE : PendingAuthorizationSaveResult.SAVED; 158 } finally { 159 this.lock.unlock(); 160 } 161 } 162 163 /** 164 * Atomically removes the matching record, including an expired one. 165 * 166 * @param browserBinding the browser-specific binding 167 * @param state the authorization state 168 * @param remaining positive time left for this operation 169 * @return the record when it was still live 170 * @since 1.0.0 171 */ 172 @Override 173 public @NonNull Optional<@NonNull String> consume(@NonNull String browserBinding, @NonNull String state, 174 @NonNull Duration remaining) { 175 Deadline deadline = deadline(remaining); 176 checkLookupInputs(browserBinding, state); 177 acquire(deadline); 178 try { 179 if (deadline.isExpired()) throw unavailable(); 180 Instant clockNow = this.clock.instant(); 181 if (deadline.isExpired()) throw unavailable(); 182 Instant now = observedTime(clockNow); 183 Entry removed = this.entries.remove(new Key(browserBinding, state)); 184 if (removed == null) 185 return Optional.empty(); 186 this.chargedBytes.addAndGet(-removed.chargedBytes); 187 return now.isBefore(removed.expiresAt) ? Optional.of(removed.record) : Optional.empty(); 188 } finally { 189 this.lock.unlock(); 190 } 191 } 192 193 private static @NonNull Deadline deadline(@NonNull Duration remaining) { 194 if (requireNonNull(remaining).isNegative() || remaining.isZero()) throw unavailable(); 195 return Deadline.fromNow(remaining); 196 } 197 198 private void acquire(@NonNull Deadline deadline) { 199 try { 200 if (deadline.isExpired() || !this.lock.tryLock(Math.max(0, deadline.remainingNanos()), TimeUnit.NANOSECONDS)) 201 throw unavailable(); 202 } catch (InterruptedException failure) { 203 Thread.currentThread().interrupt(); 204 throw unavailable(); 205 } 206 } 207 208 private static @NonNull PendingAuthorizationStoreException unavailable() { 209 return PendingAuthorizationStoreException.fromReason(OAuthException.Reason.PENDING_AUTHORIZATION_STORE_UNAVAILABLE); 210 } 211 212 private @NonNull Instant observedTime(@NonNull Instant now) { 213 Instant previous = this.lastObserved; 214 if (previous == null || now.isAfter(previous)) { 215 this.lastObserved = now; 216 return now; 217 } 218 return previous; 219 } 220 221 private void pruneExpired(@NonNull Instant now) { 222 Iterator<Map.Entry<Key, Entry>> iterator = this.entries.entrySet().iterator(); 223 while (iterator.hasNext()) { 224 Entry entry = iterator.next().getValue(); 225 if (!now.isBefore(entry.expiresAt)) { 226 this.chargedBytes.addAndGet(-entry.chargedBytes); 227 iterator.remove(); 228 } 229 } 230 } 231 232 private static void checkLookupInputs(@NonNull String browserBinding, @NonNull String state) { 233 if (requireNonNull(browserBinding).isEmpty() || requireNonNull(state).isEmpty()) 234 throw new IllegalArgumentException("A browser binding and state must not be empty."); 235 } 236 237 private static long utf8Length(@NonNull String value, long cap) { 238 if (value.length() > cap) 239 return cap + 1; 240 byte[] encoded; 241 try { 242 encoded = StrictUtf8.encode(value); 243 } catch (EncodingException exception) { 244 throw new IllegalArgumentException("A pending record contains invalid text."); 245 } 246 try { 247 return encoded.length; 248 } finally { 249 Arrays.fill(encoded, (byte) 0); 250 } 251 } 252 253 private record Key(@NonNull String binding, @NonNull String state) { 254 } 255 256 private record Entry(@NonNull String record, @NonNull Instant expiresAt, long chargedBytes) { 257 } 258 259 /** 260 * Configures the store. The builder is not thread-safe; the built store is. 261 * 262 * @author <a href="https://www.revetkn.com">Mark Allen</a> 263 * @since 1.0.0 264 */ 265 @NotThreadSafe 266 @CheckReturnValue 267 public static final class Builder { 268 private int maximumLiveEntries = Limits.PENDING_AUTHORIZATION_STORE_ENTRIES.getDefaultIntValue(); 269 private long maximumChargedBytes = Limits.PENDING_AUTHORIZATION_STORE_BYTES.getDefaultValue(); 270 private int maximumOpaqueRecordBytes = Limits.PENDING_AUTHORIZATION_RECORD_BYTES.getDefaultIntValue(); 271 private @NonNull Clock clock = Clock.systemUTC(); 272 273 private Builder() { 274 } 275 276 /** 277 * Sets the maximum live entry count. 278 * 279 * @param value 16 to 65,536, or null which restores the default 280 * @return this builder 281 * @since 1.0.0 282 */ 283 public @NonNull Builder maximumLiveEntries(@Nullable Integer value) { 284 this.maximumLiveEntries = value == null ? Limits.PENDING_AUTHORIZATION_STORE_ENTRIES.getDefaultIntValue() : Math.toIntExact(Limits.PENDING_AUTHORIZATION_STORE_ENTRIES.require(value)); 285 return this; 286 } 287 288 /** 289 * Sets the maximum charged UTF-8 bytes across live records. 290 * 291 * @param value 64 KiB to 64 MiB, or null which restores the default 292 * @return this builder 293 * @since 1.0.0 294 */ 295 public @NonNull Builder maximumChargedBytes(@Nullable Long value) { 296 this.maximumChargedBytes = value == null ? Limits.PENDING_AUTHORIZATION_STORE_BYTES.getDefaultValue() : Limits.PENDING_AUTHORIZATION_STORE_BYTES.require(value); 297 return this; 298 } 299 300 /** 301 * Sets the maximum UTF-8 bytes in one opaque record. 302 * 303 * @param value 1 KiB to 64 KiB, or null which restores the default 304 * @return this builder 305 * @since 1.0.0 306 */ 307 public @NonNull Builder maximumOpaqueRecordBytes(@Nullable Integer value) { 308 this.maximumOpaqueRecordBytes = value == null ? Limits.PENDING_AUTHORIZATION_RECORD_BYTES.getDefaultIntValue() : Math.toIntExact(Limits.PENDING_AUTHORIZATION_RECORD_BYTES.require(value)); 309 return this; 310 } 311 312 /** 313 * Sets the clock used for expiry checks. 314 * 315 * @param value the clock, or null which restores the default 316 * @return this builder 317 * @since 1.0.0 318 */ 319 public @NonNull Builder clock(@Nullable Clock value) { 320 this.clock = value == null ? Clock.systemUTC() : value; 321 return this; 322 } 323 324 /** 325 * Builds the store without starting a thread or doing I/O. 326 * 327 * @return the store 328 * @since 1.0.0 329 */ 330 public @NonNull InMemoryPendingAuthorizationStore build() { 331 if (this.maximumOpaqueRecordBytes > this.maximumChargedBytes) 332 throw new IllegalArgumentException("One record limit must not exceed the total store byte limit."); 333 return new InMemoryPendingAuthorizationStore(this); 334 } 335 } 336}