-
Notifications
You must be signed in to change notification settings - Fork 0
fix(llc): fix userId for guest #128
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
renefloor
wants to merge
4
commits into
main
Choose a base branch
from
renefloor/flu-373-guest-and-anonymous-login
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+285
−6
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
210 changes: 210 additions & 0 deletions
210
packages/stream_core/test/api/interceptors/auth_interceptor_test.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,210 @@ | ||
| import 'dart:convert'; | ||
|
|
||
| import 'package:stream_core/stream_core.dart'; | ||
| import 'package:test/test.dart'; | ||
|
|
||
| // A minimal HttpClientAdapter that captures the outgoing RequestOptions and | ||
| // always responds with an empty successful response. | ||
| class _CapturingHttpClientAdapter implements HttpClientAdapter { | ||
| RequestOptions? lastRequest; | ||
|
|
||
| @override | ||
| Future<ResponseBody> fetch( | ||
| RequestOptions options, | ||
| Stream<Uint8List>? requestStream, | ||
| Future<void>? cancelFuture, | ||
| ) async { | ||
| lastRequest = options; | ||
| return ResponseBody.fromString( | ||
| '{}', | ||
| 200, | ||
| headers: { | ||
| Headers.contentTypeHeader: [Headers.jsonContentType], | ||
| }, | ||
| ); | ||
| } | ||
|
|
||
| @override | ||
| void close({bool force = false}) {} | ||
| } | ||
|
|
||
| // An adapter that always responds with a token-expired API error (code 40), | ||
| // counting how many times it is hit so a retry can be detected. [onFetch], if | ||
| // provided, runs when the request is dispatched — used to simulate a token | ||
| // manager being swapped in mid-flight. | ||
| class _TokenExpiredHttpClientAdapter implements HttpClientAdapter { | ||
| _TokenExpiredHttpClientAdapter({this.onFetch}); | ||
|
|
||
| final void Function()? onFetch; | ||
|
|
||
| var _requestCount = 0; | ||
| int get requestCount => _requestCount; | ||
|
|
||
| @override | ||
| Future<ResponseBody> fetch( | ||
| RequestOptions options, | ||
| Stream<Uint8List>? requestStream, | ||
| Future<void>? cancelFuture, | ||
| ) async { | ||
| _requestCount++; | ||
| onFetch?.call(); | ||
| return ResponseBody.fromString( | ||
| jsonEncode({ | ||
| 'code': 40, // token expired | ||
| 'details': <int>[], | ||
| 'duration': '0ms', | ||
| 'message': 'token expired', | ||
| 'more_info': '', | ||
| 'StatusCode': 401, | ||
| }), | ||
| 401, | ||
| headers: { | ||
| Headers.contentTypeHeader: [Headers.jsonContentType], | ||
| }, | ||
| ); | ||
| } | ||
|
|
||
| @override | ||
| void close({bool force = false}) {} | ||
| } | ||
|
|
||
| UserToken _generateTestUserToken(String userId) { | ||
| String b64UrlNoPad(Object jsonObj) { | ||
| final bytes = utf8.encode(jsonEncode(jsonObj)); | ||
| return base64Url.encode(bytes).replaceAll('=', ''); | ||
| } | ||
|
|
||
| final header = {'alg': 'none', 'typ': 'JWT'}; | ||
| final payload = {'user_id': userId}; | ||
|
|
||
| final jwt = '${b64UrlNoPad(header)}.${b64UrlNoPad(payload)}.'; | ||
| return UserToken(jwt); | ||
| } | ||
|
|
||
| void main() { | ||
| group('AuthInterceptor', () { | ||
| test( | ||
| 'picks up a TokenManager swapped in while the token is loading, so the ' | ||
| 'user_id query parameter reflects a server-resolved id (guest exchange)', | ||
| () async { | ||
| // Simulates the guest flow: the token provider resolves to a | ||
| // server-assigned id and swaps in a new TokenManager carrying that id | ||
| // before the request headers are written. The interceptor reads the | ||
| // manager through the getter, so it observes the swapped instance. | ||
| late TokenManager tokenManager; | ||
| tokenManager = TokenManager( | ||
| userId: 'requested-id', | ||
| tokenProvider: TokenProvider.dynamic((_) async { | ||
| final token = _generateTestUserToken('server-assigned-id'); | ||
| tokenManager = TokenManager( | ||
| userId: token.userId, | ||
| tokenProvider: TokenProvider.static(token), | ||
| ); | ||
| return token; | ||
| }), | ||
| ); | ||
|
|
||
| final dio = Dio(BaseOptions(baseUrl: 'https://example.com')); | ||
| final adapter = _CapturingHttpClientAdapter(); | ||
| dio.httpClientAdapter = adapter; | ||
| dio.interceptors.add(AuthInterceptor(dio, () => tokenManager)); | ||
|
|
||
| await dio.get<void>('/test'); | ||
|
|
||
| expect( | ||
| adapter.lastRequest?.queryParameters['user_id'], | ||
| 'server-assigned-id', | ||
| ); | ||
| }, | ||
| ); | ||
|
|
||
| test( | ||
| 'uses the current TokenManager userId when nothing swaps it ' | ||
| '(regular/anonymous users)', | ||
| () async { | ||
| final tokenManager = TokenManager( | ||
| userId: 'user-123', | ||
| tokenProvider: TokenProvider.static( | ||
| _generateTestUserToken('user-123'), | ||
| ), | ||
| ); | ||
|
|
||
| final dio = Dio(BaseOptions(baseUrl: 'https://example.com')); | ||
| final adapter = _CapturingHttpClientAdapter(); | ||
| dio.httpClientAdapter = adapter; | ||
| dio.interceptors.add(AuthInterceptor(dio, () => tokenManager)); | ||
|
|
||
| await dio.get<void>('/test'); | ||
|
|
||
| expect(adapter.lastRequest?.queryParameters['user_id'], 'user-123'); | ||
| }, | ||
| ); | ||
|
|
||
| test( | ||
| 'does not retry a token-expired response when using a static provider ' | ||
| '(e.g. a guest token): the error is surfaced to the caller instead of ' | ||
| 'silently re-minting the token', | ||
| () async { | ||
| final tokenManager = TokenManager( | ||
| userId: 'guest-1', | ||
| tokenProvider: TokenProvider.static(_generateTestUserToken('guest-1')), | ||
| ); | ||
|
|
||
| final dio = Dio(BaseOptions(baseUrl: 'https://example.com')); | ||
| final adapter = _TokenExpiredHttpClientAdapter(); | ||
| dio.httpClientAdapter = adapter; | ||
| dio.interceptors.add(AuthInterceptor(dio, () => tokenManager)); | ||
|
|
||
| await expectLater( | ||
| dio.get<void>('/test'), | ||
| throwsA(isA<DioException>()), | ||
| ); | ||
|
|
||
| // A static provider must not trigger the refresh-and-retry path, so | ||
| // the request is attempted exactly once. | ||
| expect(adapter.requestCount, 1); | ||
| }, | ||
| ); | ||
|
|
||
| test( | ||
| 'forwards a token-expired error without retrying when the token manager ' | ||
| 'is swapped to a static provider after the request was dispatched ' | ||
| '(guest exchange resolving mid-flight)', | ||
| () async { | ||
| // Starts on a dynamic manager and swaps to a static one carrying the | ||
| // server-resolved id once the request is already in flight, mirroring | ||
| // the guest flow. onError observes the swapped-in (static) manager and | ||
| // must forward the error rather than expire + retry. | ||
| var tokenManager = TokenManager( | ||
| userId: 'requested-id', | ||
| tokenProvider: TokenProvider.dynamic( | ||
| (_) async => _generateTestUserToken('requested-id'), | ||
| ), | ||
| ); | ||
|
|
||
| final dio = Dio(BaseOptions(baseUrl: 'https://example.com')); | ||
| final adapter = _TokenExpiredHttpClientAdapter( | ||
| onFetch: () { | ||
| tokenManager = TokenManager( | ||
| userId: 'server-assigned-id', | ||
| tokenProvider: TokenProvider.static( | ||
| _generateTestUserToken('server-assigned-id'), | ||
| ), | ||
| ); | ||
| }, | ||
| ); | ||
| dio.httpClientAdapter = adapter; | ||
| dio.interceptors.add(AuthInterceptor(dio, () => tokenManager)); | ||
|
|
||
| await expectLater( | ||
| dio.get<void>('/test'), | ||
| throwsA(isA<DioException>()), | ||
| ); | ||
|
|
||
| // The swapped-in manager is static, so the error is surfaced without a | ||
| // refresh-and-retry: the request is attempted exactly once. | ||
| expect(adapter.requestCount, 1); | ||
| }, | ||
| ); | ||
| }); | ||
| } |
44 changes: 44 additions & 0 deletions
44
packages/stream_core/test/ws/client/web_socket_connection_state_test.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| import 'package:stream_core/stream_core.dart'; | ||
| import 'package:test/test.dart'; | ||
|
|
||
| StreamApiError _apiError(int code) => StreamApiError( | ||
| code: code, | ||
| details: const [], | ||
| duration: '0ms', | ||
| message: 'error $code', | ||
| moreInfo: '', | ||
| statusCode: 401, | ||
| ); | ||
|
|
||
| Disconnected _serverDisconnect(StreamApiError apiError) => Disconnected( | ||
| source: ServerInitiated( | ||
| error: WebSocketEngineException( | ||
| reason: apiError.message, | ||
| code: 4001, | ||
| error: apiError, | ||
| ), | ||
| ), | ||
| ); | ||
|
|
||
| void main() { | ||
| group('WebSocketConnectionState.isAutomaticReconnectionEnabled', () { | ||
| test( | ||
| 'is disabled when the server closes with a token-expired error, so an ' | ||
| 'expired (e.g. guest) token does not trigger a silent reconnect loop', | ||
| () { | ||
| // Token-invalid error codes are 40..42; 40 = token expired. | ||
| final state = _serverDisconnect(_apiError(40)); | ||
|
|
||
| expect(state.isAutomaticReconnectionEnabled, isFalse); | ||
| }, | ||
| ); | ||
|
|
||
| test('is enabled for a generic, retryable server-initiated disconnection', () { | ||
| // A server error that is neither a normal closure (1000), a token error | ||
| // (40..42), nor a client error (400..499) should still reconnect. | ||
| final state = _serverDisconnect(_apiError(43)); | ||
|
|
||
| expect(state.isAutomaticReconnectionEnabled, isTrue); | ||
| }); | ||
| }); | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.