|
| 1 | +/* |
| 2 | + * Copyright 2025 LiveKit |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +import Foundation |
| 18 | + |
| 19 | +/// A token source that caches credentials from any other ``TokenSourceConfigurable`` using a configurable store. |
| 20 | +/// |
| 21 | +/// This wrapper improves performance by avoiding redundant token requests when credentials are still valid. |
| 22 | +/// It automatically validates cached tokens and fetches new ones when needed. |
| 23 | +public actor CachingTokenSource: TokenSourceConfigurable, Loggable { |
| 24 | + /// A tuple containing the request and response that were cached. |
| 25 | + public typealias Cached = (TokenRequestOptions, TokenSourceResponse) |
| 26 | + |
| 27 | + /// A closure that validates whether cached credentials are still valid. |
| 28 | + /// |
| 29 | + /// The validator receives the original request options and cached response, and should return |
| 30 | + /// `true` if the cached credentials are still valid for the given request. |
| 31 | + public typealias Validator = @Sendable (TokenRequestOptions, TokenSourceResponse) -> Bool |
| 32 | + |
| 33 | + /// Protocol for storing and retrieving cached token credentials. |
| 34 | + /// |
| 35 | + /// Implement this protocol to create custom storage solutions like Keychain, |
| 36 | + /// or database-backed storage for token caching. |
| 37 | + public protocol Store: Sendable { |
| 38 | + /// Store credentials in the store. |
| 39 | + /// |
| 40 | + /// This replaces any existing cached credentials with the new ones. |
| 41 | + func store(_ credentials: CachingTokenSource.Cached) async |
| 42 | + |
| 43 | + /// Retrieve the cached credentials. |
| 44 | + /// - Returns: The cached credentials if found, nil otherwise |
| 45 | + func retrieve() async -> CachingTokenSource.Cached? |
| 46 | + |
| 47 | + /// Clear all stored credentials. |
| 48 | + func clear() async |
| 49 | + } |
| 50 | + |
| 51 | + private let source: TokenSourceConfigurable |
| 52 | + private let store: Store |
| 53 | + private let validator: Validator |
| 54 | + |
| 55 | + /// Initialize a caching wrapper around any token source. |
| 56 | + /// |
| 57 | + /// - Parameters: |
| 58 | + /// - source: The underlying token source to wrap and cache |
| 59 | + /// - store: The store implementation to use for caching (defaults to in-memory store) |
| 60 | + /// - validator: A closure to determine if cached credentials are still valid (defaults to JWT expiration check) |
| 61 | + public init( |
| 62 | + _ source: TokenSourceConfigurable, |
| 63 | + store: Store = InMemoryTokenStore(), |
| 64 | + validator: @escaping Validator = { _, response in response.hasValidToken() } |
| 65 | + ) { |
| 66 | + self.source = source |
| 67 | + self.store = store |
| 68 | + self.validator = validator |
| 69 | + } |
| 70 | + |
| 71 | + public func fetch(_ options: TokenRequestOptions) async throws -> TokenSourceResponse { |
| 72 | + if let (cachedOptions, cachedResponse) = await store.retrieve(), |
| 73 | + cachedOptions == options, |
| 74 | + validator(cachedOptions, cachedResponse) |
| 75 | + { |
| 76 | + log("Using cached credentials", .debug) |
| 77 | + return cachedResponse |
| 78 | + } |
| 79 | + |
| 80 | + log("Requesting new credentials", .debug) |
| 81 | + let newResponse = try await source.fetch(options) |
| 82 | + await store.store((options, newResponse)) |
| 83 | + |
| 84 | + return newResponse |
| 85 | + } |
| 86 | + |
| 87 | + /// Invalidate the cached credentials, forcing a fresh fetch on the next request. |
| 88 | + public func invalidate() async { |
| 89 | + await store.clear() |
| 90 | + } |
| 91 | + |
| 92 | + /// Get the cached credentials |
| 93 | + /// - Returns: The cached response if found, nil otherwise. |
| 94 | + public func cachedResponse() async -> TokenSourceResponse? { |
| 95 | + await store.retrieve()?.1 |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +public extension TokenSourceConfigurable { |
| 100 | + /// Wraps this token source with caching capabilities. |
| 101 | + /// |
| 102 | + /// The returned token source will reuse valid tokens and only fetch new ones when needed. |
| 103 | + /// |
| 104 | + /// - Parameters: |
| 105 | + /// - store: The store implementation to use for caching (defaults to in-memory store) |
| 106 | + /// - validator: A closure to determine if cached credentials are still valid (defaults to JWT expiration check) |
| 107 | + /// - Returns: A caching token source that wraps this token source |
| 108 | + func cached(store: CachingTokenSource.Store = InMemoryTokenStore(), |
| 109 | + validator: @escaping CachingTokenSource.Validator = { _, response in response.hasValidToken() }) -> CachingTokenSource |
| 110 | + { |
| 111 | + CachingTokenSource(self, store: store, validator: validator) |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +// MARK: - Store |
| 116 | + |
| 117 | +/// A simple in-memory store implementation for token caching. |
| 118 | +/// |
| 119 | +/// This store keeps credentials in memory and is lost when the app is terminated. |
| 120 | +/// Suitable for development and testing, but consider persistent storage for production. |
| 121 | +public actor InMemoryTokenStore: CachingTokenSource.Store { |
| 122 | + private var cached: CachingTokenSource.Cached? |
| 123 | + |
| 124 | + public init() {} |
| 125 | + |
| 126 | + public func store(_ credentials: CachingTokenSource.Cached) async { |
| 127 | + cached = credentials |
| 128 | + } |
| 129 | + |
| 130 | + public func retrieve() async -> CachingTokenSource.Cached? { |
| 131 | + cached |
| 132 | + } |
| 133 | + |
| 134 | + public func clear() async { |
| 135 | + cached = nil |
| 136 | + } |
| 137 | +} |
| 138 | + |
| 139 | +// MARK: - Validation |
| 140 | + |
| 141 | +public extension TokenSourceResponse { |
| 142 | + /// Validates whether the JWT token is still valid and not expired. |
| 143 | + /// |
| 144 | + /// - Parameter tolerance: Time tolerance in seconds for token expiration check (default: 60 seconds) |
| 145 | + /// - Returns: `true` if the token is valid and not expired, `false` otherwise |
| 146 | + func hasValidToken(withTolerance tolerance: TimeInterval = 60) -> Bool { |
| 147 | + guard let jwt = jwt() else { |
| 148 | + return false |
| 149 | + } |
| 150 | + |
| 151 | + do { |
| 152 | + try jwt.nbf.verifyNotBefore() |
| 153 | + try jwt.exp.verifyNotExpired(currentDate: Date().addingTimeInterval(tolerance)) |
| 154 | + } catch { |
| 155 | + return false |
| 156 | + } |
| 157 | + |
| 158 | + return true |
| 159 | + } |
| 160 | + |
| 161 | + /// Extracts the JWT payload from the participant token. |
| 162 | + /// |
| 163 | + /// - Returns: The JWT payload if successfully parsed, nil otherwise |
| 164 | + func jwt() -> LiveKitJWTPayload? { |
| 165 | + LiveKitJWTPayload.fromUnverified(token: participantToken) |
| 166 | + } |
| 167 | +} |
0 commit comments