diff --git a/packages/supabase/lib/src/supabase_client.dart b/packages/supabase/lib/src/supabase_client.dart index df3e83a16..bf1b436ef 100644 --- a/packages/supabase/lib/src/supabase_client.dart +++ b/packages/supabase/lib/src/supabase_client.dart @@ -176,6 +176,7 @@ class SupabaseClient { autoRefreshToken: authOptions.autoRefreshToken, authAsyncStorage: authOptions.pkceAsyncStorage, authFlowType: authOptions.authFlowType, + appendPkceFlowIdToRedirects: authOptions.appendPkceFlowIdToRedirects, ); _authHttpClient = AuthHttpClient( _supabaseKey, @@ -327,6 +328,7 @@ class SupabaseClient { required bool autoRefreshToken, required AuthAsyncStorage? authAsyncStorage, required AuthFlowType authFlowType, + required bool appendPkceFlowIdToRedirects, }) { final authHeaders = {...headers}; authHeaders['apikey'] = _supabaseKey; @@ -339,6 +341,7 @@ class SupabaseClient { httpClient: _authApiHttpClient, asyncStorage: authAsyncStorage, flowType: authFlowType, + appendPkceFlowIdToRedirects: appendPkceFlowIdToRedirects, ); } diff --git a/packages/supabase/lib/src/supabase_client_options.dart b/packages/supabase/lib/src/supabase_client_options.dart index 6a295bbcd..600e38d31 100644 --- a/packages/supabase/lib/src/supabase_client_options.dart +++ b/packages/supabase/lib/src/supabase_client_options.dart @@ -45,10 +45,19 @@ class AuthClientOptions { final AuthAsyncStorage? pkceAsyncStorage; final AuthFlowType authFlowType; + /// Whether to append the reserved `sb_flow_id` query parameter to the + /// redirect URL of pkce flows, so a callback can be matched to the flow that + /// started it. + /// + /// Check your redirect URL allow list first, see + /// [AuthClient.appendPkceFlowIdToRedirects]. + final bool appendPkceFlowIdToRedirects; + const AuthClientOptions({ this.autoRefreshToken = true, this.pkceAsyncStorage, this.authFlowType = AuthFlowType.pkce, + this.appendPkceFlowIdToRedirects = false, }); } diff --git a/packages/supabase_auth/lib/src/auth_client.dart b/packages/supabase_auth/lib/src/auth_client.dart index 6c92b8103..88baf1a3e 100644 --- a/packages/supabase_auth/lib/src/auth_client.dart +++ b/packages/supabase_auth/lib/src/auth_client.dart @@ -8,6 +8,7 @@ import 'package:supabase_auth/supabase_auth.dart'; import 'package:supabase_auth/src/auth_constants.dart'; import 'package:supabase_auth/src/fetch.dart'; import 'package:supabase_auth/src/helper.dart'; +import 'package:supabase_auth/src/pkce_verifier_store.dart'; import 'package:supabase_auth/src/types/fetch_options.dart'; import 'package:http/http.dart'; import 'package:logging/logging.dart'; @@ -49,6 +50,9 @@ class _SessionState { /// do not need to outlive the process. /// /// Set [flowType] to [AuthFlowType.implicit] to perform old implicit auth flow. +/// +/// Set [AuthClient.appendPkceFlowIdToRedirects] to match a pkce callback to the +/// flow that started it when several flows can be pending at once. /// {@endtemplate} class AuthClient { /// Namespace for the Supabase Auth admin API methods. These can be used for @@ -100,8 +104,24 @@ class AuthClient { sync: true, ); - /// Local storage to store pkce code verifiers. - final AuthAsyncStorage? _asyncStorage; + /// Keeps one code verifier per pending pkce flow. Null when no + /// [AuthAsyncStorage] was provided, in which case the pkce flow cannot run. + final PKCEVerifierStore? _pkceVerifierStore; + + /// Whether the reserved `sb_flow_id` query parameter is appended to the + /// redirect URL of pkce flows, so a callback can be matched to the flow that + /// started it. + /// + /// Only needed for flows that hand back no flow id, such as email OTP, + /// password recovery and email change. Elsewhere pass the + /// [OAuthResponse.flowId] of [getOAuthSignInUrl] or [getLinkIdentityUrl] to + /// [exchangeCodeForSession] instead. + /// + /// Defaults to false, because the [redirect URL allow + /// list](https://supabase.com/docs/guides/auth/redirect-urls) is matched + /// against the full URL: an entry without a wildcard stops matching once the + /// parameter is appended, and the redirect falls back to your Site URL. + final bool appendPkceFlowIdToRedirects; /// Receive a notification every time an auth event happens. /// @@ -158,6 +178,7 @@ class AuthClient { Client? httpClient, AuthAsyncStorage? asyncStorage, AuthFlowType flowType = AuthFlowType.pkce, + this.appendPkceFlowIdToRedirects = false, }) : assert( flowType != AuthFlowType.pkce || asyncStorage != null, 'You need to provide asyncStorage to perform pkce flow. Pass a ' @@ -167,7 +188,9 @@ class AuthClient { _url = url ?? AuthConstants.defaultAuthUrl, _headers = {...AuthConstants.defaultHeaders, ...?headers}, _httpClient = httpClient, - _asyncStorage = asyncStorage, + _pkceVerifierStore = asyncStorage == null + ? null + : PKCEVerifierStore(asyncStorage), _flowType = flowType { _autoRefreshToken = autoRefreshToken ?? true; @@ -314,21 +337,24 @@ class AuthClient { final Map response; if (email != null) { - final codeChallenge = await _generatePKCECodeChallenge(); + final pkceFlow = await _startPKCEFlow(); response = await _fetch.request( '$_url/signup', HttpMethod.post, options: AuthRequestOptions( headers: _headers, - redirectTo: emailRedirectTo, + redirectTo: _maybeAppendFlowIdToRedirect( + emailRedirectTo, + pkceFlow?.flowId, + ), body: { 'email': email, 'password': password, 'data': data, 'gotrue_meta_security': {'captcha_token': captchaToken}, - 'code_challenge': codeChallenge, - 'code_challenge_method': codeChallenge != null ? 's256' : null, + 'code_challenge': pkceFlow?.codeChallenge, + 'code_challenge_method': pkceFlow != null ? 's256' : null, }, ), ); @@ -425,14 +451,18 @@ class AuthClient { String? scopes, Map? queryParameters, }) async { - final url = await _getUrlForProvider( + final urlResponse = await _getUrlForProvider( provider, url: '$_url/authorize', redirectTo: redirectTo, scopes: scopes, queryParameters: queryParameters, ); - return OAuthResponse(provider: provider, url: url); + return OAuthResponse( + provider: provider, + url: urlResponse.url, + flowId: urlResponse.flowId, + ); } /// Verifies the PKCE code verifier and retrieves a session. @@ -441,14 +471,41 @@ class AuthClient { /// [resetPasswordForEmail], which emits [AuthChangeEvent.passwordRecovery], /// or by an email change through [updateUser], which emits /// [AuthChangeEvent.userUpdated]. - Future exchangeCodeForSession(String authCode) async { + /// + /// When several PKCE flows are pending at the same time, pass the [flowId] of + /// the flow the [authCode] belongs to, so the code is exchanged with the code + /// verifier that flow created. [getOAuthSignInUrl] and [getLinkIdentityUrl] + /// return it as [OAuthResponse.flowId], and with + /// [appendPkceFlowIdToRedirects] enabled it also arrives on the callback URL + /// as the reserved `sb_flow_id` query parameter, which [getSessionFromUrl] + /// reads for you. + /// + /// When a [flowId] is given but its stored verifier is gone, because it was + /// evicted, already used, or created on another device, this throws instead + /// of trying another flow's verifier: a mismatched verifier would spend the + /// single-use [authCode]. Without a [flowId] the verifier of the most + /// recently started flow is used, as it always was. + Future exchangeCodeForSession( + String authCode, { + String? flowId, + }) async { assert( - _asyncStorage != null, + _pkceVerifierStore != null, 'You need to provide asyncStorage to perform pkce flow.', ); - final codeVerifierRawString = await _asyncStorage!.getItem( - key: '${AuthConstants.defaultStorageKey}-code-verifier', + final requestedFlowId = PKCEVerifierStore.validateFlowId(flowId); + if (flowId != null && requestedFlowId == null) { + // Told apart from a missing verifier so the message points at the + // callback URL rather than at storage. Bounded because the id comes + // from that URL. + throw AuthException( + 'PKCE flow id is not a valid flow id: ${_bounded(flowId)}', + ); + } + + final codeVerifierRawString = await _pkceVerifierStore!.retrieve( + flowId: requestedFlowId, ); if (codeVerifierRawString == null) { throw AuthException('Code verifier could not be found in local storage.'); @@ -467,9 +524,7 @@ class AuthClient { ), ); - await _asyncStorage.removeItem( - key: '${AuthConstants.defaultStorageKey}-code-verifier', - ); + await _pkceVerifierStore.remove(flowId: requestedFlowId); final authSessionUrlResponse = AuthSessionUrlResponse( session: Session.fromJson(response)!, @@ -485,28 +540,53 @@ class AuthClient { return authSessionUrlResponse; } - /// Generates a PKCE code verifier, persists it, and returns the derived code - /// challenge. + /// Starts a PKCE flow by generating a code verifier and persisting it in a + /// slot of its own, and returns the derived code challenge together with the + /// id of the flow it belongs to. /// /// Returns `null` when the client is not using the PKCE flow. When /// [storageEventName] is provided it is appended to the stored verifier so it /// can be recovered in [exchangeCodeForSession]. - Future _generatePKCECodeChallenge({String? storageEventName}) async { + Future<({String codeChallenge, String flowId})?> _startPKCEFlow({ + String? storageEventName, + }) async { if (_flowType != AuthFlowType.pkce) { return null; } assert( - _asyncStorage != null, + _pkceVerifierStore != null, 'You need to provide asyncStorage to perform pkce flow.', ); final codeVerifier = generatePKCEVerifier(); - await _asyncStorage!.setItem( - key: '${AuthConstants.defaultStorageKey}-code-verifier', - value: storageEventName == null + final flowId = PKCEVerifierStore.generateFlowId(); + final evicted = await _pkceVerifierStore!.store( + flowId: flowId, + verifier: storageEventName == null ? codeVerifier : '$codeVerifier/$storageEventName', ); - return generatePKCEChallenge(codeVerifier); + for (final evictedFlowId in evicted) { + _log.warning( + 'Evicted the oldest pending PKCE verifier to start a new flow, ' + 'flow id: $evictedFlowId', + ); + } + return (codeChallenge: generatePKCEChallenge(codeVerifier), flowId: flowId); + } + + /// Caps untrusted input echoed back in an exception message to the longest + /// flow id the store accepts. + static String _bounded(String value) => + value.length <= 64 ? value : '${value.substring(0, 64)}...'; + + /// Appends the flow id to [redirectTo] so the callback can be matched to the + /// verifier stored for its flow, when [appendPkceFlowIdToRedirects] allows + /// it. + String? _maybeAppendFlowIdToRedirect(String? redirectTo, String? flowId) { + if (redirectTo == null || flowId == null || !appendPkceFlowIdToRedirects) { + return redirectTo; + } + return appendPKCEFlowIdToRedirect(redirectTo, flowId); } /// Allows signing in with an ID token issued by supported providers. Common @@ -638,20 +718,23 @@ class AuthClient { OtpChannel channel = OtpChannel.sms, }) async { if (email != null) { - final codeChallenge = await _generatePKCECodeChallenge(); + final pkceFlow = await _startPKCEFlow(); await _fetch.request( '$_url/otp', HttpMethod.post, options: AuthRequestOptions( headers: _headers, - redirectTo: emailRedirectTo, + redirectTo: _maybeAppendFlowIdToRedirect( + emailRedirectTo, + pkceFlow?.flowId, + ), body: { 'email': email, 'data': data ?? {}, 'create_user': shouldCreateUser ?? true, 'gotrue_meta_security': {'captcha_token': captchaToken}, - 'code_challenge': codeChallenge, - 'code_challenge_method': codeChallenge != null ? 's256' : null, + 'code_challenge': pkceFlow?.codeChallenge, + 'code_challenge_method': pkceFlow != null ? 's256' : null, }, ), ); @@ -791,7 +874,7 @@ class AuthClient { 'providerId or domain has to be provided.', ); - final codeChallenge = await _generatePKCECodeChallenge(); + final pkceFlow = await _startPKCEFlow(); final response = await _fetch.request( '$_url/sso', @@ -800,12 +883,15 @@ class AuthClient { body: { 'provider_id': ?providerId, 'domain': ?domain, - 'redirect_to': ?redirectTo, + 'redirect_to': ?_maybeAppendFlowIdToRedirect( + redirectTo, + pkceFlow?.flowId, + ), if (captchaToken != null) 'gotrue_meta_security': {'captcha_token': captchaToken}, 'skip_http_redirect': true, - 'code_challenge': codeChallenge, - 'code_challenge_method': codeChallenge != null ? 's256' : null, + 'code_challenge': pkceFlow?.codeChallenge, + 'code_challenge_method': pkceFlow != null ? 's256' : null, }, headers: _headers, ), @@ -883,9 +969,7 @@ class AuthClient { ); } - final codeChallenge = email != null - ? await _generatePKCECodeChallenge() - : null; + final pkceFlow = email != null ? await _startPKCEFlow() : null; final body = { 'email': ?email, @@ -893,15 +977,18 @@ class AuthClient { 'type': type.snakeCase, 'gotrue_meta_security': {'captcha_token': captchaToken}, if (email != null) ...{ - 'code_challenge': codeChallenge, - 'code_challenge_method': codeChallenge != null ? 's256' : null, + 'code_challenge': pkceFlow?.codeChallenge, + 'code_challenge_method': pkceFlow != null ? 's256' : null, }, }; final options = AuthRequestOptions( headers: _headers, body: body, - redirectTo: emailRedirectTo, + redirectTo: _maybeAppendFlowIdToRedirect( + emailRedirectTo, + pkceFlow?.flowId, + ), ); final response = await _fetch.request( @@ -943,8 +1030,8 @@ class AuthClient { throw AuthSessionMissingException(); } - final codeChallenge = attributes.email != null - ? await _generatePKCECodeChallenge( + final pkceFlow = attributes.email != null + ? await _startPKCEFlow( storageEventName: AuthChangeEvent.userUpdated.name, ) : null; @@ -952,15 +1039,18 @@ class AuthClient { final body = { ...attributes.toJson(), if (attributes.email != null) ...{ - 'code_challenge': codeChallenge, - 'code_challenge_method': codeChallenge != null ? 's256' : null, + 'code_challenge': pkceFlow?.codeChallenge, + 'code_challenge_method': pkceFlow != null ? 's256' : null, }, }; final options = AuthRequestOptions( headers: _headers, body: body, jwt: accessToken, - redirectTo: emailRedirectTo, + redirectTo: _maybeAppendFlowIdToRedirect( + emailRedirectTo, + pkceFlow?.flowId, + ), ); final response = await _fetch.request( '$_url/user', @@ -1072,7 +1162,10 @@ class AuthClient { final authCode = url.queryParameters['code']; if (authCode != null) { - return await exchangeCodeForSession(authCode); + return await exchangeCodeForSession( + authCode, + flowId: url.queryParameters[AuthConstants.pkceFlowIdParam], + ); } if (_flowType == AuthFlowType.pkce && @@ -1149,9 +1242,7 @@ class AuthClient { if (scope != SignOutScope.others) { _removeSession(); - await _asyncStorage?.removeItem( - key: '${AuthConstants.defaultStorageKey}-code-verifier', - ); + await _pkceVerifierStore?.removeAll(); notifyAllSubscribers( AuthChangeEvent.signedOut, signOutReason: reason, @@ -1181,21 +1272,21 @@ class AuthClient { String? redirectTo, String? captchaToken, }) async { - final codeChallenge = await _generatePKCECodeChallenge( + final pkceFlow = await _startPKCEFlow( storageEventName: AuthChangeEvent.passwordRecovery.name, ); final body = { 'email': email, 'gotrue_meta_security': {'captcha_token': captchaToken}, - 'code_challenge': codeChallenge, - 'code_challenge_method': codeChallenge != null ? 's256' : null, + 'code_challenge': pkceFlow?.codeChallenge, + 'code_challenge_method': pkceFlow != null ? 's256' : null, }; final fetchOptions = AuthRequestOptions( headers: _headers, body: body, - redirectTo: redirectTo, + redirectTo: _maybeAppendFlowIdToRedirect(redirectTo, pkceFlow?.flowId), ); await _fetch.request( '$_url/recover', @@ -1275,7 +1366,7 @@ class AuthClient { skipBrowserRedirect: true, ); final response = await _fetch.request( - authorizeUrl.toString(), + authorizeUrl.url.toString(), HttpMethod.get, options: AuthRequestOptions( headers: _headers, @@ -1285,6 +1376,7 @@ class AuthClient { return OAuthResponse( provider: provider, url: Uri.parse(_urlFromResponse(response)), + flowId: authorizeUrl.flowId, ); } @@ -1496,8 +1588,10 @@ class AuthClient { ); } - /// Returns the OAuth sign in URL constructed from the [url] parameter. - Future _getUrlForProvider( + /// Returns the OAuth sign in URL constructed from the [url] parameter, + /// together with the id of the pkce flow it started, `null` on the implicit + /// flow. + Future<({Uri url, String? flowId})> _getUrlForProvider( OAuthProvider provider, { required String url, required String? scopes, @@ -1505,20 +1599,26 @@ class AuthClient { required Map? queryParameters, bool skipBrowserRedirect = false, }) async { - final codeChallenge = await _generatePKCECodeChallenge(); + final pkceFlow = await _startPKCEFlow(); final urlParameters = { 'provider': provider.name, 'scopes': ?scopes, - 'redirect_to': ?redirectTo, + 'redirect_to': ?_maybeAppendFlowIdToRedirect( + redirectTo, + pkceFlow?.flowId, + ), ...?queryParameters, - if (codeChallenge != null) ...{ + if (pkceFlow != null) ...{ 'flow_type': _flowType.name, - 'code_challenge': codeChallenge, + 'code_challenge': pkceFlow.codeChallenge, 'code_challenge_method': 's256', }, if (skipBrowserRedirect) 'skip_http_redirect': 'true', }; - return Uri.parse('$url?${Uri(queryParameters: urlParameters).query}'); + return ( + url: Uri.parse('$url?${Uri(queryParameters: urlParameters).query}'), + flowId: pkceFlow?.flowId, + ); } /// Reads the `url` field out of a response that is expected to carry one. diff --git a/packages/supabase_auth/lib/src/auth_constants.dart b/packages/supabase_auth/lib/src/auth_constants.dart index fd3fbf62c..992863da0 100644 --- a/packages/supabase_auth/lib/src/auth_constants.dart +++ b/packages/supabase_auth/lib/src/auth_constants.dart @@ -12,6 +12,18 @@ class AuthConstants { /// storage key prefix to store code verifiers static const String defaultStorageKey = 'supabase.auth.token'; + /// Reserved query parameter appended to `redirectTo` URLs of PKCE flows when + /// `appendPkceFlowIdToRedirects` is enabled. + /// + /// It round-trips through the auth server untouched and identifies the + /// verifier slot the callback belongs to. The verifier itself never + /// appears in a URL. + static const String pkceFlowIdParam = 'sb_flow_id'; + + /// Maximum number of PKCE code verifiers kept in storage at once. Starting + /// another flow beyond this evicts the oldest pending verifier. + static const int pkceMaxConcurrentFlows = 5; + /// The margin to use when checking if a token is expired. static const expiryMargin = Duration(seconds: 30); diff --git a/packages/supabase_auth/lib/src/helper.dart b/packages/supabase_auth/lib/src/helper.dart index 871794ee3..12ea8f8ec 100644 --- a/packages/supabase_auth/lib/src/helper.dart +++ b/packages/supabase_auth/lib/src/helper.dart @@ -1,5 +1,6 @@ import 'dart:convert'; +import 'package:supabase_auth/src/auth_constants.dart'; import 'package:supabase_auth/src/types/auth_exception.dart'; import 'package:supabase_auth/src/types/jwt.dart'; import 'package:meta/meta.dart'; @@ -76,6 +77,55 @@ JwtPayload decodeJwtPayload(String token) { } } +/// Appends the reserved flow id parameter to a `redirectTo` URL, replacing any +/// occurrence already there. +/// +/// Works on the string rather than going through [Uri] so that custom schemes +/// used by deep links and the exact encoding of the app's own parameters +/// survive untouched. A fragment stays at the end of the URL. +/// +/// An occurrence already in the fragment is dropped too, because +/// `getSessionFromUrl` folds the fragment into the query parameters, where a +/// stale copy parsed after the appended one would win. +@internal +String appendPKCEFlowIdToRedirect(String redirectTo, String flowId) { + final fragmentIndex = redirectTo.indexOf('#'); + var fragment = fragmentIndex == -1 ? '' : redirectTo.substring(fragmentIndex); + var base = fragmentIndex == -1 + ? redirectTo + : redirectTo.substring(0, fragmentIndex); + + final queryIndex = base.indexOf('?'); + if (queryIndex != -1) { + final path = base.substring(0, queryIndex); + final remaining = _withoutFlowId(base.substring(queryIndex + 1)); + base = remaining.isEmpty ? path : '$path?$remaining'; + } + + if (fragment.length > 1) { + final remaining = _withoutFlowId(fragment.substring(1)); + fragment = remaining.isEmpty ? '' : '#$remaining'; + } + + final separator = base.contains('?') ? '&' : '?'; + return '$base$separator${AuthConstants.pkceFlowIdParam}=' + '${Uri.encodeQueryComponent(flowId)}$fragment'; +} + +/// Drops the reserved flow id parameter from an `&` joined list of pairs. +/// +/// Matching is on the whole name so that a parameter of the app's own whose +/// name merely starts with the reserved one, such as `sb_flow_idx`, is kept. +String _withoutFlowId(String pairs) => pairs + .split('&') + .where( + (pair) => + pair.isNotEmpty && + pair != AuthConstants.pkceFlowIdParam && + !pair.startsWith('${AuthConstants.pkceFlowIdParam}='), + ) + .join('&'); + /// Validates the expiration time of a JWT /// /// Throws [AuthException] if the exp claim is missing or the JWT has expired. diff --git a/packages/supabase_auth/lib/src/pkce_verifier_store.dart b/packages/supabase_auth/lib/src/pkce_verifier_store.dart new file mode 100644 index 000000000..29d2a85c0 --- /dev/null +++ b/packages/supabase_auth/lib/src/pkce_verifier_store.dart @@ -0,0 +1,209 @@ +import 'dart:convert'; +import 'dart:math'; + +import 'package:supabase_auth/src/auth_constants.dart'; +import 'package:supabase_auth/src/types/auth_async_storage.dart'; +import 'package:meta/meta.dart'; + +/// Stores PKCE code verifiers in a separate slot per flow, so several flows can +/// be pending at the same time. +/// +/// Under a single fixed key a flow started later overwrites the verifier of a +/// flow that is still pending, breaking whichever of the two completes second. +/// Each flow instead gets a slot keyed by its own flow id. Since +/// [AuthAsyncStorage] cannot enumerate keys, the ids of the pending slots are +/// tracked in an index entry, oldest first. At most +/// [AuthConstants.pkceMaxConcurrentFlows] slots are kept: starting another flow +/// evicts the oldest. +/// +/// The verifier of the most recently started flow is also written to the key +/// that was used before slots existed, so an exchange that cannot identify its +/// flow keeps working exactly as it did. +@internal +class PKCEVerifierStore { + PKCEVerifierStore(this._storage); + + final AuthAsyncStorage _storage; + + /// The mutation the next one has to wait for, null while none is in flight. + /// + /// [store], [remove] and [removeAll] each read the index and write it back + /// with an await in between, so two overlapping calls would drop one of the + /// two updates and leave behind a slot the index no longer lists, out of + /// reach of both eviction and [removeAll]. Reads are not chained: they touch + /// a single key, and [remove] performs one while holding the chain. + Future? _mutations; + + /// Runs [mutation] after the one before it, starting it right away when the + /// store is idle so a lone mutation is not held back by an extra event loop + /// turn. + Future _serialize(Future Function() mutation) { + final pending = _mutations; + final result = pending == null + ? mutation() + : pending.then((_) => mutation()); + // The error is swallowed here only so a failed mutation does not poison the + // ones queued behind it. The caller still sees it through [result]. + _mutations = result.then((_) {}, onError: (_) {}); + return result; + } + + /// Flow ids can arrive from a callback URL, so anything outside the shape + /// this store generates is rejected before it is used to build a key. + static final _flowIdPattern = RegExp(r'^[a-zA-Z0-9_-]{8,64}$'); + + static const _legacyKey = '${AuthConstants.defaultStorageKey}-code-verifier'; + static const _indexKey = + '${AuthConstants.defaultStorageKey}-flows-code-verifier'; + + static String _slotKey(String flowId) => + '${AuthConstants.defaultStorageKey}-flow-$flowId-code-verifier'; + + /// Returns [flowId] when it has the shape of a flow id, `null` otherwise. + static String? validateFlowId(String? flowId) => + flowId != null && _flowIdPattern.hasMatch(flowId) ? flowId : null; + + /// Generates an identifier for a new PKCE flow. + /// + /// The id only selects a verifier held in storage and is never secret, but it + /// is generated from a secure source so that concurrent flows cannot collide. + static String generateFlowId() { + final random = Random.secure(); + return List.generate( + 16, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + } + + /// Stores [verifier] in [flowId]'s own slot, evicting the oldest pending slot + /// when that would exceed [AuthConstants.pkceMaxConcurrentFlows]. + /// + /// Throws an [ArgumentError] when [flowId] does not have the shape + /// [generateFlowId] produces. The index drops ids it cannot validate, so a + /// slot stored under a malformed id would never be evicted or removed again. + /// + /// Returns the ids of the flows whose verifiers were evicted. + Future> store({ + required String flowId, + required String verifier, + }) async { + if (validateFlowId(flowId) == null) { + throw ArgumentError.value(flowId, 'flowId', 'Not a valid flow id'); + } + + return _serialize(() => _store(flowId: flowId, verifier: verifier)); + } + + Future> _store({ + required String flowId, + required String verifier, + }) async { + await _storage.setItem(key: _slotKey(flowId), value: verifier); + + final index = (await _readIndex()).where((id) => id != flowId).toList() + ..add(flowId); + final evicted = []; + while (index.length > AuthConstants.pkceMaxConcurrentFlows) { + final oldest = index.removeAt(0); + await _storage.removeItem(key: _slotKey(oldest)); + evicted.add(oldest); + } + await _storage.setItem(key: _indexKey, value: jsonEncode(index)); + + // Mirror the most recently started flow under the key used before slots + // existed, so an exchange that carries no flow id behaves as it always has. + await _storage.setItem(key: _legacyKey, value: verifier); + + return evicted; + } + + /// Reads the verifier stored for [flowId], or the one of the most recently + /// started flow when [flowId] is `null`. + /// + /// A given [flowId] is looked up in its slot only, deliberately without + /// falling back to the key used before slots existed: submitting another + /// flow's verifier would spend the single-use auth code. + Future retrieve({String? flowId}) => + _storage.getItem(key: flowId == null ? _legacyKey : _slotKey(flowId)); + + /// Removes the verifier of [flowId], or the one of the most recently started + /// flow when [flowId] is `null`. + /// + /// Slots of other pending flows are always left alone. A verifier is always + /// removed from both its own slot and the legacy key, whichever of the two it + /// was found through, so a spent verifier cannot be reached again by the + /// other route. + Future remove({String? flowId}) => + _serialize(() => _remove(flowId: flowId)); + + Future _remove({String? flowId}) async { + final verifier = await retrieve(flowId: flowId); + final index = await _readIndex(); + + // Without a flow id the verifier came from the legacy key, which mirrors + // whichever flow started last. Its slot is found by value, since the legacy + // key does not record which flow that was. + final spentFlowIds = flowId != null + ? [flowId] + : verifier == null + ? const [] + : [ + for (final id in index) + if (await _storage.getItem(key: _slotKey(id)) == verifier) id, + ]; + + for (final spentFlowId in spentFlowIds) { + await _storage.removeItem(key: _slotKey(spentFlowId)); + } + + final remaining = index.where((id) => !spentFlowIds.contains(id)).toList(); + if (remaining.length != index.length) { + if (remaining.isEmpty) { + await _storage.removeItem(key: _indexKey); + } else { + await _storage.setItem(key: _indexKey, value: jsonEncode(remaining)); + } + } + + // The legacy key mirrors the most recently started flow, which may be this + // one. Leaving a spent verifier there would let a later exchange without a + // flow id reuse it. + final legacyVerifier = await _storage.getItem(key: _legacyKey); + if (verifier != null && verifier == legacyVerifier) { + await _storage.removeItem(key: _legacyKey); + } + } + + /// Removes every pending verifier, used when the session is torn down. + Future removeAll() => _serialize(_removeAll); + + Future _removeAll() async { + for (final flowId in await _readIndex()) { + await _storage.removeItem(key: _slotKey(flowId)); + } + await _storage.removeItem(key: _indexKey); + await _storage.removeItem(key: _legacyKey); + } + + /// The index goes through the same validation as a flow id read off a URL: + /// with cookie backed storage its contents are no more trustworthy. + Future> _readIndex() async { + final index = await _storage.getItem(key: _indexKey); + if (index == null) { + return []; + } + final Object? decoded; + try { + decoded = jsonDecode(index); + } on FormatException { + return []; + } + if (decoded is! List) { + return []; + } + return decoded + .map((id) => validateFlowId(id is String ? id : null)) + .nonNulls + .toList(); + } +} diff --git a/packages/supabase_auth/lib/src/types/auth_response.dart b/packages/supabase_auth/lib/src/types/auth_response.dart index 7ea3ddd2b..5b87dde57 100644 --- a/packages/supabase_auth/lib/src/types/auth_response.dart +++ b/packages/supabase_auth/lib/src/types/auth_response.dart @@ -23,10 +23,22 @@ class OAuthResponse { /// The provider's authorization URL to send the user to. final Uri url; + /// Identifier of the PKCE flow this call started. + /// + /// Pass it as the `flowId` of [AuthClient.exchangeCodeForSession] to + /// exchange the auth code with this flow's code verifier when several flows + /// are pending at the same time. `null` when the client is not using the PKCE + /// flow. + /// + /// The id only selects a verifier held in storage, it never contains the + /// verifier itself. + final String? flowId; + /// Instantiates an `OAuthResponse` object from json response. const OAuthResponse({ required this.provider, required this.url, + this.flowId, }); } diff --git a/packages/supabase_auth/test/pkce_flow_test.dart b/packages/supabase_auth/test/pkce_flow_test.dart new file mode 100644 index 000000000..81a76d5f2 --- /dev/null +++ b/packages/supabase_auth/test/pkce_flow_test.dart @@ -0,0 +1,701 @@ +import 'dart:convert'; + +import 'package:supabase_auth/supabase_auth.dart'; +import 'package:supabase_auth/src/auth_constants.dart'; +import 'package:supabase_auth/src/helper.dart'; +import 'package:supabase_auth/src/pkce_verifier_store.dart'; +import 'package:http/http.dart'; +import 'package:test/test.dart'; + +import 'utils.dart'; + +/// Records the code verifier each `/token` exchange submits and answers with a +/// session, so a test can assert which flow's verifier was used. +class PKCETokenMockClient extends BaseClient { + final submittedCodeVerifiers = []; + + @override + Future send(BaseRequest request) async { + if (request is Request && + request.url.queryParameters['grant_type'] == 'pkce') { + final body = jsonDecode(request.body) as Map; + submittedCodeVerifiers.add(body['code_verifier'] as String); + } + + return StreamedResponse( + Stream.value( + utf8.encode( + jsonEncode({ + 'access_token': 'my-access-token', + 'token_type': 'bearer', + 'expires_in': 3600, + 'refresh_token': 'my-refresh-token', + 'user': { + 'id': userId1, + 'aud': '', + 'role': '', + 'email': email1, + 'app_metadata': {}, + 'user_metadata': {}, + 'created_at': '2023-04-01T09:38:59.784028Z', + 'updated_at': '2023-04-01T09:38:59.908816Z', + }, + }), + ), + ), + 200, + request: request, + ); + } +} + +/// Records the `redirect_to` of the last request, which the auth server takes +/// as a query parameter. +class RedirectRecordingMockClient extends BaseClient { + String? lastRedirectTo; + + @override + Future send(BaseRequest request) async { + lastRedirectTo = request.url.queryParameters['redirect_to']; + return StreamedResponse( + Stream.value(utf8.encode(jsonEncode({}))), + 200, + request: request, + ); + } +} + +/// Delays every operation so overlapping calls into [PKCEVerifierStore] are +/// forced to interleave rather than happening to complete in call order. +class SlowAsyncStorage extends AuthAsyncStorage { + final _items = {}; + + Future get _delay => Future.delayed(Duration.zero); + + @override + Future getItem({required String key}) async { + await _delay; + return _items[key]; + } + + @override + Future setItem({required String key, required String value}) async { + await _delay; + _items[key] = value; + } + + @override + Future removeItem({required String key}) async { + await _delay; + _items.remove(key); + } +} + +void main() { + const legacyKey = '${AuthConstants.defaultStorageKey}-code-verifier'; + const indexKey = '${AuthConstants.defaultStorageKey}-flows-code-verifier'; + + String slotKey(String flowId) => + '${AuthConstants.defaultStorageKey}-flow-$flowId-code-verifier'; + + group('PKCEVerifierStore', () { + late TestAsyncStorage storage; + late PKCEVerifierStore store; + + setUp(() { + storage = TestAsyncStorage(); + store = PKCEVerifierStore(storage); + }); + + test('keeps concurrent flows in slots of their own', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + await store.store(flowId: 'flow-two', verifier: 'verifier-two'); + + expect(await store.retrieve(flowId: 'flow-one'), 'verifier-one'); + expect(await store.retrieve(flowId: 'flow-two'), 'verifier-two'); + }); + + test( + 'mirrors the most recently started flow under the legacy key', + () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + await store.store(flowId: 'flow-two', verifier: 'verifier-two'); + + expect(await store.retrieve(), 'verifier-two'); + expect(await storage.getItem(key: legacyKey), 'verifier-two'); + }, + ); + + test('does not fall back to the legacy key for an unknown flow', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + + expect(await store.retrieve(flowId: 'flow-unknown'), isNull); + }); + + test('evicts the oldest verifier past the concurrency limit', () async { + final flowIds = List.generate( + AuthConstants.pkceMaxConcurrentFlows + 2, + (index) => 'flow-id-$index', + ); + + final evicted = []; + for (final flowId in flowIds) { + evicted.addAll( + await store.store(flowId: flowId, verifier: 'verifier-$flowId'), + ); + } + + expect(evicted, [flowIds[0], flowIds[1]]); + expect(await store.retrieve(flowId: flowIds[0]), isNull); + expect(await store.retrieve(flowId: flowIds[1]), isNull); + for (final flowId in flowIds.skip(2)) { + expect(await store.retrieve(flowId: flowId), 'verifier-$flowId'); + } + }); + + test('storing a flow again does not consume another slot', () async { + for ( + var attempt = 0; + attempt < AuthConstants.pkceMaxConcurrentFlows; + attempt++ + ) { + await store.store(flowId: 'flow-one', verifier: 'verifier-$attempt'); + } + final evicted = await store.store( + flowId: 'flow-two', + verifier: 'verifier-two', + ); + + expect(evicted, isEmpty); + expect(await store.retrieve(flowId: 'flow-one'), isNotNull); + }); + + test('removing a flow leaves the other pending flows alone', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + await store.store(flowId: 'flow-two', verifier: 'verifier-two'); + + await store.remove(flowId: 'flow-one'); + + expect(await store.retrieve(flowId: 'flow-one'), isNull); + expect(await store.retrieve(flowId: 'flow-two'), 'verifier-two'); + }); + + test('removing a flow clears the legacy key it mirrors', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + + await store.remove(flowId: 'flow-one'); + + expect(await storage.getItem(key: legacyKey), isNull); + }); + + test('removing a flow keeps a legacy key of a newer flow', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + await store.store(flowId: 'flow-two', verifier: 'verifier-two'); + + await store.remove(flowId: 'flow-one'); + + expect(await storage.getItem(key: legacyKey), 'verifier-two'); + }); + + test('removing without a flow id also clears the owning slot', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + + await store.remove(); + + expect(await storage.getItem(key: legacyKey), isNull); + expect(await store.retrieve(flowId: 'flow-one'), isNull); + expect(await storage.getItem(key: indexKey), isNull); + }); + + test('removing without a flow id keeps the older flows', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + await store.store(flowId: 'flow-two', verifier: 'verifier-two'); + + await store.remove(); + + expect(await store.retrieve(flowId: 'flow-two'), isNull); + expect(await store.retrieve(flowId: 'flow-one'), 'verifier-one'); + expect(jsonDecode(await storage.getItem(key: indexKey) ?? ''), [ + 'flow-one', + ]); + }); + + test('removeAll clears every pending verifier and the index', () async { + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + await store.store(flowId: 'flow-two', verifier: 'verifier-two'); + + await store.removeAll(); + + expect(await storage.getItem(key: slotKey('flow-one')), isNull); + expect(await storage.getItem(key: slotKey('flow-two')), isNull); + expect(await storage.getItem(key: indexKey), isNull); + expect(await storage.getItem(key: legacyKey), isNull); + }); + + test('ignores an index that is not a list of flow ids', () async { + await storage.setItem(key: indexKey, value: 'not json at all'); + await store.store(flowId: 'flow-one', verifier: 'verifier-one'); + + expect(await store.retrieve(flowId: 'flow-one'), 'verifier-one'); + expect(jsonDecode(await storage.getItem(key: indexKey) ?? ''), [ + 'flow-one', + ]); + }); + + test('drops index entries that are not shaped like a flow id', () async { + await storage.setItem( + key: indexKey, + value: jsonEncode(['../escape', 7, 'flow-one']), + ); + + await store.removeAll(); + + expect(await storage.getItem(key: slotKey('flow-one')), isNull); + }); + + test('rejects a flow id it could never evict again', () async { + await expectLater( + store.store(flowId: '../escape', verifier: 'my-verifier'), + throwsA(isA()), + ); + + expect(await storage.getItem(key: indexKey), isNull); + expect(await storage.getItem(key: legacyKey), isNull); + expect(await storage.getItem(key: slotKey('../escape')), isNull); + }); + + test('keeps every concurrently started flow in the index', () async { + final slowStorage = SlowAsyncStorage(); + final slowStore = PKCEVerifierStore(slowStorage); + + await Future.wait([ + slowStore.store(flowId: 'flow-one', verifier: 'verifier-one'), + slowStore.store(flowId: 'flow-two', verifier: 'verifier-two'), + ]); + + expect(jsonDecode(await slowStorage.getItem(key: indexKey) ?? ''), [ + 'flow-one', + 'flow-two', + ]); + + // An untracked slot is one removeAll cannot reach, so a verifier would + // outlive the sign out that was supposed to clear it. + await slowStore.removeAll(); + expect(await slowStorage.getItem(key: slotKey('flow-one')), isNull); + expect(await slowStorage.getItem(key: slotKey('flow-two')), isNull); + }); + + group('validateFlowId', () { + test('accepts a generated flow id', () { + final flowId = PKCEVerifierStore.generateFlowId(); + + expect(PKCEVerifierStore.validateFlowId(flowId), flowId); + }); + + test('rejects ids that could escape the storage key', () { + expect(PKCEVerifierStore.validateFlowId(null), isNull); + expect(PKCEVerifierStore.validateFlowId(''), isNull); + expect(PKCEVerifierStore.validateFlowId('short'), isNull); + expect(PKCEVerifierStore.validateFlowId('../../escape'), isNull); + expect(PKCEVerifierStore.validateFlowId('has.a.dot.in.it'), isNull); + expect(PKCEVerifierStore.validateFlowId('a' * 65), isNull); + }); + }); + + group('generateFlowId', () { + test('generates distinct ids', () { + final flowIds = List.generate( + 100, + (_) => PKCEVerifierStore.generateFlowId(), + ); + + expect(flowIds.toSet(), hasLength(flowIds.length)); + }); + }); + }); + + group('appendPKCEFlowIdToRedirect', () { + test('appends to a URL without a query', () { + expect( + appendPKCEFlowIdToRedirect('https://example.com/callback', 'flow-one'), + 'https://example.com/callback?sb_flow_id=flow-one', + ); + }); + + test('appends to a URL that already has a query', () { + expect( + appendPKCEFlowIdToRedirect( + 'https://example.com/callback?next=%2Fhome', + 'flow-one', + ), + 'https://example.com/callback?next=%2Fhome&sb_flow_id=flow-one', + ); + }); + + test('replaces a flow id that is already there', () { + expect( + appendPKCEFlowIdToRedirect( + 'https://example.com/callback?sb_flow_id=stale&next=%2Fhome', + 'flow-one', + ), + 'https://example.com/callback?next=%2Fhome&sb_flow_id=flow-one', + ); + }); + + test('drops a valueless flow id that is already there', () { + expect( + appendPKCEFlowIdToRedirect( + 'https://example.com/callback?sb_flow_id', + 'flow-one', + ), + 'https://example.com/callback?sb_flow_id=flow-one', + ); + }); + + test('keeps a parameter whose name only shares the prefix', () { + expect( + appendPKCEFlowIdToRedirect( + 'https://example.com/callback?sb_flow_idx=1', + 'flow-one', + ), + 'https://example.com/callback?sb_flow_idx=1&sb_flow_id=flow-one', + ); + }); + + test('drops a flow id that is already in the fragment', () { + expect( + appendPKCEFlowIdToRedirect( + 'https://example.com/callback#sb_flow_id=stale&next=%2Fhome', + 'flow-one', + ), + 'https://example.com/callback?sb_flow_id=flow-one#next=%2Fhome', + ); + }); + + test('drops a fragment that held nothing but a flow id', () { + expect( + appendPKCEFlowIdToRedirect( + 'https://example.com/callback#sb_flow_id=stale', + 'flow-one', + ), + 'https://example.com/callback?sb_flow_id=flow-one', + ); + }); + + test('keeps the fragment at the end of the URL', () { + expect( + appendPKCEFlowIdToRedirect( + 'https://example.com/callback?next=%2Fhome#section', + 'flow-one', + ), + 'https://example.com/callback?next=%2Fhome&sb_flow_id=flow-one#section', + ); + }); + + test('leaves a custom deep link scheme untouched', () { + expect( + appendPKCEFlowIdToRedirect( + 'io.supabase.flutter://callback', + 'flow-one', + ), + 'io.supabase.flutter://callback?sb_flow_id=flow-one', + ); + }); + }); + + group('concurrent PKCE flows', () { + late TestAsyncStorage storage; + late PKCETokenMockClient mockClient; + late AuthClient client; + + setUp(() { + storage = TestAsyncStorage(); + mockClient = PKCETokenMockClient(); + client = AuthClient( + url: 'https://example.com', + httpClient: mockClient, + asyncStorage: storage, + ); + }); + + test('getOAuthSignInUrl returns the id of the flow it started', () async { + final response = await client.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + + expect(PKCEVerifierStore.validateFlowId(response.flowId), isNotNull); + }); + + test('getOAuthSignInUrl returns no flow id on the implicit flow', () async { + final implicitClient = AuthClient( + url: 'https://example.com', + httpClient: mockClient, + asyncStorage: storage, + flowType: AuthFlowType.implicit, + ); + + final response = await implicitClient.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + + expect(response.flowId, isNull); + }); + + test('a later flow does not overwrite an earlier flow verifier', () async { + final first = await client.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + final second = await client.getOAuthSignInUrl( + provider: OAuthProvider.github, + ); + + final store = PKCEVerifierStore(storage); + final firstVerifier = await store.retrieve(flowId: first.flowId); + final secondVerifier = await store.retrieve(flowId: second.flowId); + + expect(firstVerifier, isNotNull); + expect(secondVerifier, isNotNull); + expect(firstVerifier, isNot(secondVerifier)); + }); + + test('exchanging with a flow id uses that flow verifier', () async { + final first = await client.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + await client.getOAuthSignInUrl(provider: OAuthProvider.github); + + final expectedVerifier = await PKCEVerifierStore( + storage, + ).retrieve(flowId: first.flowId); + + await client.exchangeCodeForSession( + 'my-auth-code', + flowId: first.flowId, + ); + + expect(mockClient.submittedCodeVerifiers, [expectedVerifier]); + }); + + test('exchanging without a flow id uses the most recent flow', () async { + await client.getOAuthSignInUrl(provider: OAuthProvider.google); + final second = await client.getOAuthSignInUrl( + provider: OAuthProvider.github, + ); + + final expectedVerifier = await PKCEVerifierStore( + storage, + ).retrieve(flowId: second.flowId); + + await client.exchangeCodeForSession('my-auth-code'); + + expect(mockClient.submittedCodeVerifiers, [expectedVerifier]); + expect( + await PKCEVerifierStore(storage).retrieve(flowId: second.flowId), + isNull, + ); + }); + + test('exchanging one flow leaves the other one exchangeable', () async { + final first = await client.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + final second = await client.getOAuthSignInUrl( + provider: OAuthProvider.github, + ); + + final store = PKCEVerifierStore(storage); + final firstVerifier = await store.retrieve(flowId: first.flowId); + final secondVerifier = await store.retrieve(flowId: second.flowId); + + await client.exchangeCodeForSession( + 'first-auth-code', + flowId: first.flowId, + ); + await client.exchangeCodeForSession( + 'second-auth-code', + flowId: second.flowId, + ); + + expect(mockClient.submittedCodeVerifiers, [ + firstVerifier, + secondVerifier, + ]); + }); + + test('exchanging with an unknown flow id throws', () async { + await client.getOAuthSignInUrl(provider: OAuthProvider.google); + + await expectLater( + client.exchangeCodeForSession( + 'my-auth-code', + flowId: PKCEVerifierStore.generateFlowId(), + ), + throwsA(isA()), + ); + expect(mockClient.submittedCodeVerifiers, isEmpty); + }); + + test('exchanging with a malformed flow id reports the flow id', () async { + await client.getOAuthSignInUrl(provider: OAuthProvider.google); + + await expectLater( + client.exchangeCodeForSession('my-auth-code', flowId: '../escape'), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'PKCE flow id is not a valid flow id: ../escape', + ), + ), + ); + expect(mockClient.submittedCodeVerifiers, isEmpty); + }); + + test('exchanging with an overlong flow id bounds the message', () async { + await client.getOAuthSignInUrl(provider: OAuthProvider.google); + + await expectLater( + client.exchangeCodeForSession('my-auth-code', flowId: 'a' * 500), + throwsA( + isA().having( + (error) => error.message.length, + 'message length', + lessThan(128), + ), + ), + ); + expect(mockClient.submittedCodeVerifiers, isEmpty); + }); + + test('exchanging an already exchanged flow throws', () async { + final response = await client.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + + await client.exchangeCodeForSession( + 'my-auth-code', + flowId: response.flowId, + ); + + await expectLater( + client.exchangeCodeForSession( + 'my-auth-code', + flowId: response.flowId, + ), + throwsA(isA()), + ); + }); + + test('getSessionFromUrl picks the flow the callback belongs to', () async { + final first = await client.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + await client.getOAuthSignInUrl(provider: OAuthProvider.github); + + final expectedVerifier = await PKCEVerifierStore( + storage, + ).retrieve(flowId: first.flowId); + + await client.getSessionFromUrl( + Uri.parse( + 'io.supabase.flutter://callback?code=my-auth-code' + '&sb_flow_id=${first.flowId}', + ), + ); + + expect(mockClient.submittedCodeVerifiers, [expectedVerifier]); + }); + + test('signOut clears every pending verifier', () async { + final first = await client.getOAuthSignInUrl( + provider: OAuthProvider.google, + ); + final second = await client.getOAuthSignInUrl( + provider: OAuthProvider.github, + ); + + await client.signOut(); + + final store = PKCEVerifierStore(storage); + expect(await store.retrieve(flowId: first.flowId), isNull); + expect(await store.retrieve(flowId: second.flowId), isNull); + expect(await store.retrieve(), isNull); + }); + }); + + group('appendPkceFlowIdToRedirects', () { + late RedirectRecordingMockClient mockClient; + + setUp(() { + mockClient = RedirectRecordingMockClient(); + }); + + AuthClient buildClient({required bool appendPkceFlowIdToRedirects}) { + return AuthClient( + url: 'https://example.com', + httpClient: mockClient, + asyncStorage: TestAsyncStorage(), + appendPkceFlowIdToRedirects: appendPkceFlowIdToRedirects, + ); + } + + test('is not appended by default', () async { + await buildClient( + appendPkceFlowIdToRedirects: false, + ).signInWithOtp(email: email1, emailRedirectTo: 'myapp://callback'); + + expect(mockClient.lastRedirectTo, 'myapp://callback'); + }); + + test('is appended to the redirect of an email OTP', () async { + await buildClient( + appendPkceFlowIdToRedirects: true, + ).signInWithOtp(email: email1, emailRedirectTo: 'myapp://callback'); + + final redirectTo = Uri.parse(mockClient.lastRedirectTo!); + expect( + PKCEVerifierStore.validateFlowId( + redirectTo.queryParameters[AuthConstants.pkceFlowIdParam], + ), + isNotNull, + ); + }); + + test('is appended to the redirect of a password recovery', () async { + await buildClient( + appendPkceFlowIdToRedirects: true, + ).resetPasswordForEmail(email1, redirectTo: 'myapp://callback'); + + expect( + mockClient.lastRedirectTo, + contains('${AuthConstants.pkceFlowIdParam}='), + ); + }); + + test('is appended to the redirect handed to the OAuth provider', () async { + final response = + await buildClient( + appendPkceFlowIdToRedirects: true, + ).getOAuthSignInUrl( + provider: OAuthProvider.google, + redirectTo: 'myapp://callback', + ); + + final redirectTo = Uri.parse( + response.url.queryParameters['redirect_to']!, + ); + expect( + redirectTo.queryParameters[AuthConstants.pkceFlowIdParam], + response.flowId, + ); + }); + + test('is not appended when there is no redirect URL', () async { + await buildClient( + appendPkceFlowIdToRedirects: true, + ).signInWithOtp(email: email1); + + expect(mockClient.lastRedirectTo, isNull); + }); + }); +} diff --git a/packages/supabase_flutter/lib/src/clear_auth_url_parameters.dart b/packages/supabase_flutter/lib/src/clear_auth_url_parameters.dart index 89f5320f9..c6350fde2 100644 --- a/packages/supabase_flutter/lib/src/clear_auth_url_parameters.dart +++ b/packages/supabase_flutter/lib/src/clear_auth_url_parameters.dart @@ -13,6 +13,7 @@ const _authParameters = { 'error_code', 'error_description', 'type', + 'sb_flow_id', }; /// Returns [url] with all authentication parameters removed from both the diff --git a/packages/supabase_flutter/lib/src/flutter_auth_client_options.dart b/packages/supabase_flutter/lib/src/flutter_auth_client_options.dart index a6fbfbcb3..bce1cbf2c 100644 --- a/packages/supabase_flutter/lib/src/flutter_auth_client_options.dart +++ b/packages/supabase_flutter/lib/src/flutter_auth_client_options.dart @@ -31,6 +31,7 @@ class FlutterAuthClientOptions extends AuthClientOptions { super.authFlowType, super.autoRefreshToken, super.pkceAsyncStorage, + super.appendPkceFlowIdToRedirects, this.localStorage, this.detectSessionInUri = true, this.detectSessionInUriPredicate, @@ -42,6 +43,7 @@ class FlutterAuthClientOptions extends AuthClientOptions { bool? autoRefreshToken, LocalStorage? localStorage, AuthAsyncStorage? pkceAsyncStorage, + bool? appendPkceFlowIdToRedirects, bool? detectSessionInUri, bool Function(Uri uri)? detectSessionInUriPredicate, bool? persistSession, @@ -51,6 +53,8 @@ class FlutterAuthClientOptions extends AuthClientOptions { autoRefreshToken: autoRefreshToken ?? this.autoRefreshToken, localStorage: localStorage ?? this.localStorage, pkceAsyncStorage: pkceAsyncStorage ?? this.pkceAsyncStorage, + appendPkceFlowIdToRedirects: + appendPkceFlowIdToRedirects ?? this.appendPkceFlowIdToRedirects, detectSessionInUri: detectSessionInUri ?? this.detectSessionInUri, detectSessionInUriPredicate: detectSessionInUriPredicate ?? this.detectSessionInUriPredicate, diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index e3b96312f..2fbcf2292 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -109,6 +109,9 @@ features: status: implemented symbols: - AuthClient.exchangeCodeForSession + - AuthClient.appendPkceFlowIdToRedirects + - AuthClientOptions.appendPkceFlowIdToRedirects + - OAuthResponse.flowId auth.sign_in.resend_confirmation: status: implemented symbols: