Skip to content

Commit e69c194

Browse files
CaiJingLongdevin-ai-integration[bot]GLM-5.2
committed
✨ Address review feedback on CORS preflight warning
- Remove the public export of corsPreflightReason to avoid adding permanent public API surface for testing only. - Extract collectCorsPreflightReasons and corsEnrichedErrorReason into pure functions in cors.dart so the upload-listener, withCredentials, and enriched-error branches are unit-testable without a browser. - Add enableCORSWarning opt-out flag (defaults to true) so apps that handle CORS correctly can silence the per-request warning. - Add 8 unit tests covering the new pure functions. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-Authored-By: GLM-5.2 <[email protected]>
1 parent 8b8f69c commit e69c194

4 files changed

Lines changed: 163 additions & 30 deletions

File tree

‎plugins/web_adapter/CHANGELOG.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@
44

55
- Warn when a request is not a CORS "simple request" and will trigger a
66
preflight (OPTIONS) request, and enrich the `XMLHttpRequest.onError` message
7-
with CORS guidance when the request was preflighted.
7+
with CORS guidance when the request was preflighted. The warning can be
8+
disabled via `BrowserHttpClientAdapter(enableCORSWarning: false)`; the
9+
enriched error message is always emitted.
810

911
## 2.2.0
1012

‎plugins/web_adapter/lib/src/adapter_impl.dart‎

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,14 @@ import 'package:web/web.dart' as web;
1010

1111
import 'cors.dart';
1212

13-
export 'cors.dart' show corsPreflightReason;
14-
1513
BrowserHttpClientAdapter createAdapter() => BrowserHttpClientAdapter();
1614

1715
/// The default [HttpClientAdapter] for Web platforms.
1816
class BrowserHttpClientAdapter implements HttpClientAdapter {
19-
BrowserHttpClientAdapter({this.withCredentials = false});
17+
BrowserHttpClientAdapter({
18+
this.withCredentials = false,
19+
this.enableCORSWarning = true,
20+
});
2021

2122
/// These are aborted if the client is closed.
2223
@visibleForTesting
@@ -31,6 +32,15 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
3132
/// for each request.
3233
bool withCredentials;
3334

35+
/// Whether to emit a warning log when a request is not a CORS "simple
36+
/// request" and will trigger a preflight (OPTIONS) request.
37+
///
38+
/// Defaults to `true`. Set to `false` to silence the warning in apps that
39+
/// already handle CORS preflight correctly and find the per-request log
40+
/// noisy. The enriched error message in [DioException.connectionError] is
41+
/// always emitted regardless of this setting.
42+
bool enableCORSWarning;
43+
3444
@override
3545
Future<ResponseBody> fetch(
3646
RequestOptions options,
@@ -70,23 +80,14 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
7080
// Detect configurations that will trigger a CORS preflight request so we
7181
// can warn the developer and enrich the eventual error message.
7282
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests
73-
final preflightReasons = <String>[
74-
if (corsPreflightReason(options) case final reason?) reason,
75-
];
7683
final willRegisterUploadListener = requestStream != null &&
7784
(sendTimeout > Duration.zero || onSendProgress != null);
78-
if (willRegisterUploadListener) {
79-
preflightReasons.add(
80-
'an upload progress listener (sendTimeout or onSendProgress) '
81-
'forces a preflight request',
82-
);
83-
}
84-
if (xhr.withCredentials) {
85-
preflightReasons.add(
86-
'withCredentials is enabled, which requires a CORS preflight request',
87-
);
88-
}
89-
if (preflightReasons.isNotEmpty) {
85+
final preflightReasons = collectCorsPreflightReasons(
86+
options,
87+
willRegisterUploadListener: willRegisterUploadListener,
88+
withCredentials: xhr.withCredentials,
89+
);
90+
if (preflightReasons.isNotEmpty && enableCORSWarning) {
9091
warningLog(
9192
'This request is not a CORS "simple request" and will trigger a '
9293
'preflight (OPTIONS) request: ${preflightReasons.join('; ')}. '
@@ -252,20 +253,14 @@ class BrowserHttpClientAdapter implements HttpClientAdapter {
252253
// Unfortunately, the underlying XMLHttpRequest API doesn't expose any
253254
// specific information about the error itself.
254255
// See also: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onerror
255-
final baseReason = 'The XMLHttpRequest onError callback was called. '
256-
'This typically indicates an error on the network layer.';
257-
final reason = preflightReasons.isEmpty
258-
? baseReason
259-
: '$baseReason If this is a cross-origin request, the browser may '
260-
'have blocked it because the request is not a CORS "simple '
261-
'request" (${preflightReasons.join('; ')}). Verify that the '
262-
'server responds correctly to the CORS preflight (OPTIONS) '
263-
'request. See '
264-
'https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests';
265256
completer.completeError(
266257
DioException.connectionError(
267258
requestOptions: options,
268-
reason: reason,
259+
reason: corsEnrichedErrorReason(
260+
'The XMLHttpRequest onError callback was called. '
261+
'This typically indicates an error on the network layer.',
262+
preflightReasons,
263+
),
269264
),
270265
StackTrace.current,
271266
);

‎plugins/web_adapter/lib/src/cors.dart‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,52 @@ String? corsPreflightReason(RequestOptions options) {
5151
}
5252
return null;
5353
}
54+
55+
/// Collects all reasons why a request will trigger a CORS preflight, combining
56+
/// the static [corsPreflightReason] analysis with runtime factors that only
57+
/// the adapter knows: whether an upload progress listener will be registered
58+
/// ([willRegisterUploadListener]) and whether credentials are being sent
59+
/// ([withCredentials]).
60+
///
61+
/// Returns an empty list when the request is a CORS "simple request".
62+
/// This is a pure function so it can be unit-tested without a browser.
63+
List<String> collectCorsPreflightReasons(
64+
RequestOptions options, {
65+
bool willRegisterUploadListener = false,
66+
bool withCredentials = false,
67+
}) {
68+
final reasons = <String>[
69+
if (corsPreflightReason(options) case final reason?) reason,
70+
];
71+
if (willRegisterUploadListener) {
72+
reasons.add(
73+
'an upload progress listener (sendTimeout or onSendProgress) '
74+
'forces a preflight request',
75+
);
76+
}
77+
if (withCredentials) {
78+
reasons.add(
79+
'withCredentials is enabled, which requires a CORS preflight request',
80+
);
81+
}
82+
return reasons;
83+
}
84+
85+
/// Builds the error reason for `XMLHttpRequest.onError`, appending CORS
86+
/// guidance when [preflightReasons] is non-empty.
87+
///
88+
/// This is a pure function so it can be unit-tested without a browser.
89+
String corsEnrichedErrorReason(
90+
String baseReason,
91+
List<String> preflightReasons,
92+
) {
93+
if (preflightReasons.isEmpty) {
94+
return baseReason;
95+
}
96+
return '$baseReason If this is a cross-origin request, the browser may '
97+
'have blocked it because the request is not a CORS "simple '
98+
'request" (${preflightReasons.join('; ')}). Verify that the '
99+
'server responds correctly to the CORS preflight (OPTIONS) '
100+
'request. See '
101+
'https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests';
102+
}

‎plugins/web_adapter/test/cors_preflight_test.dart‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,91 @@ void main() {
127127
expect(corsPreflightReason(options), isNull);
128128
});
129129
});
130+
131+
group('collectCorsPreflightReasons', () {
132+
test('simple GET produces no reasons', () {
133+
final options = RequestOptions(method: 'GET');
134+
expect(
135+
collectCorsPreflightReasons(options),
136+
isEmpty,
137+
);
138+
});
139+
140+
test('upload listener adds a reason', () {
141+
final options = RequestOptions(
142+
method: 'POST',
143+
headers: {Headers.contentTypeHeader: Headers.textPlainContentType},
144+
);
145+
final reasons = collectCorsPreflightReasons(
146+
options,
147+
willRegisterUploadListener: true,
148+
);
149+
expect(reasons, hasLength(1));
150+
expect(reasons.first, contains('upload progress listener'));
151+
});
152+
153+
test('withCredentials adds a reason', () {
154+
final options = RequestOptions(method: 'GET');
155+
final reasons = collectCorsPreflightReasons(
156+
options,
157+
withCredentials: true,
158+
);
159+
expect(reasons, hasLength(1));
160+
expect(reasons.first, contains('withCredentials'));
161+
});
162+
163+
test('non-simple method and upload listener and withCredentials', () {
164+
final options = RequestOptions(method: 'PUT');
165+
final reasons = collectCorsPreflightReasons(
166+
options,
167+
willRegisterUploadListener: true,
168+
withCredentials: true,
169+
);
170+
expect(reasons, hasLength(3));
171+
expect(reasons[0], contains('PUT'));
172+
expect(reasons[1], contains('upload progress listener'));
173+
expect(reasons[2], contains('withCredentials'));
174+
});
175+
176+
test('simple POST with text/plain and no listener is empty', () {
177+
final options = RequestOptions(
178+
method: 'POST',
179+
headers: {Headers.contentTypeHeader: Headers.textPlainContentType},
180+
);
181+
expect(
182+
collectCorsPreflightReasons(options),
183+
isEmpty,
184+
);
185+
});
186+
});
187+
188+
group('corsEnrichedErrorReason', () {
189+
const baseReason = 'The XMLHttpRequest onError callback was called. '
190+
'This typically indicates an error on the network layer.';
191+
192+
test('returns base reason when no preflight reasons', () {
193+
expect(
194+
corsEnrichedErrorReason(baseReason, []),
195+
baseReason,
196+
);
197+
});
198+
199+
test('appends CORS guidance when preflight reasons exist', () {
200+
final reason = corsEnrichedErrorReason(baseReason, [
201+
'the request method "PUT" is not a CORS-safelisted method',
202+
]);
203+
expect(reason, startsWith(baseReason));
204+
expect(reason, contains('cross-origin'));
205+
expect(reason, contains('PUT'));
206+
expect(reason, contains('CORS preflight'));
207+
});
208+
209+
test('joins multiple reasons with semicolons', () {
210+
final reason = corsEnrichedErrorReason(baseReason, [
211+
'reason one',
212+
'reason two',
213+
]);
214+
expect(reason, contains('reason one; reason two'));
215+
});
216+
});
130217
}

0 commit comments

Comments
 (0)