-
Notifications
You must be signed in to change notification settings - Fork 87
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
Allow relative URLs in the redirect location header. #229
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
291b2b8
Allow relative URLs in the redirect location header.
isoos 1a87ca1
updated code + minimal test
isoos 12f5d34
Hide main method with option to skip local network check + local test.
isoos 3a4f8bc
@visibleForTesting
isoos bd36cb7
keep _safeUrlCheck without context class
isoos 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 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 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 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,144 @@ | ||
// Copyright 2023 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import 'dart:io'; | ||
|
||
import 'package:retry/retry.dart'; | ||
|
||
import 'private_ip.dart'; | ||
import 'unique_local_ip.dart'; | ||
import 'version.dart'; | ||
|
||
const defaultUserAgent = 'package:safe_url_check/$packageVersion ' | ||
'(+https://github.com/google/dart-neats/tree/master/safe_url_check)'; | ||
|
||
Future<bool> doSafeUrlCheck( | ||
Uri url, { | ||
int maxRedirects = 8, | ||
String userAgent = defaultUserAgent, | ||
HttpClient? client, | ||
RetryOptions retryOptions = const RetryOptions(maxAttempts: 3), | ||
Duration timeout = const Duration(seconds: 90), | ||
}) async { | ||
ArgumentError.checkNotNull(url, 'url'); | ||
ArgumentError.checkNotNull(maxRedirects, 'maxRedirects'); | ||
ArgumentError.checkNotNull(userAgent, 'userAgent'); | ||
ArgumentError.checkNotNull(retryOptions, 'retryOptions'); | ||
if (maxRedirects < 0) { | ||
throw ArgumentError.value( | ||
maxRedirects, | ||
'maxRedirects', | ||
'must be a positive integer', | ||
); | ||
} | ||
|
||
try { | ||
// Create client if one wasn't given. | ||
var c = client; | ||
c ??= HttpClient(); | ||
try { | ||
return await SafeUrlChecker( | ||
client: c, | ||
userAgent: userAgent, | ||
retryOptions: retryOptions, | ||
timeout: timeout, | ||
).checkUrl(url, maxRedirects); | ||
} finally { | ||
// Close client, if it was created here. | ||
if (client == null) { | ||
c.close(force: true); | ||
} | ||
} | ||
} on Exception { | ||
return false; | ||
} | ||
} | ||
|
||
class SafeUrlChecker { | ||
final HttpClient client; | ||
final String userAgent; | ||
final RetryOptions retryOptions; | ||
final Duration timeout; | ||
final bool skipLocalNetworkCheck; | ||
|
||
SafeUrlChecker({ | ||
required this.client, | ||
required this.userAgent, | ||
required this.retryOptions, | ||
required this.timeout, | ||
this.skipLocalNetworkCheck = false, | ||
isoos marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}); | ||
|
||
Future<bool> checkUrl( | ||
Uri url, | ||
int maxRedirects, | ||
) async { | ||
assert(maxRedirects >= 0); | ||
|
||
// If no scheme or not http or https, we fail. | ||
if (!url.hasScheme || (!url.isScheme('http') && !url.isScheme('https'))) { | ||
return false; | ||
} | ||
|
||
final ips = await retryOptions.retry(() async { | ||
final ips = await InternetAddress.lookup(url.host).timeout(timeout); | ||
if (ips.isEmpty) { | ||
throw Exception('DNS resolution failed'); | ||
} | ||
return ips; | ||
}); | ||
if (!skipLocalNetworkCheck) { | ||
for (final ip in ips) { | ||
// If given a loopback, linklocal or multicast IP, return false | ||
if (ip.isLoopback || | ||
ip.isLinkLocal || | ||
ip.isMulticast || | ||
isPrivateIpV4(ip) || | ||
isUniqueLocalIpV6(ip)) { | ||
return false; | ||
} | ||
} | ||
} | ||
|
||
final response = await retryOptions.retry(() async { | ||
// We can't use the HttpClient from dart:io with a custom socket, so instead | ||
// of making a connection to one of the IPs resolved above, and specifying | ||
// the host header, we rely on the OS caching DNS queries and not returning | ||
// different IPs for a second lookup. | ||
final request = await client.headUrl(url).timeout(timeout); | ||
request.followRedirects = false; | ||
request.headers.set(HttpHeaders.userAgentHeader, userAgent); | ||
final response = await request.close().timeout(timeout); | ||
await response.drain().catchError((e) => null).timeout(timeout); | ||
if (500 <= response.statusCode && response.statusCode < 600) { | ||
// retry again, when we hit a 5xx response | ||
throw Exception('internal server error'); | ||
} | ||
return response; | ||
}); | ||
if (200 <= response.statusCode && response.statusCode < 300) { | ||
return true; | ||
} | ||
if (response.isRedirect && | ||
response.headers[HttpHeaders.locationHeader]!.isNotEmpty && | ||
maxRedirects > 0) { | ||
final loc = Uri.parse(response.headers[HttpHeaders.locationHeader]![0]); | ||
final nextUri = url.resolveUri(loc); | ||
return checkUrl(nextUri, maxRedirects - 1); | ||
} | ||
|
||
// Response is 4xx, or some other unsupported code. | ||
return false; | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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 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,61 @@ | ||
// Copyright 2023 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// https://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import 'dart:io'; | ||
|
||
import 'package:retry/retry.dart'; | ||
import 'package:safe_url_check/src/safe_url_check.dart'; | ||
import 'package:test/test.dart'; | ||
|
||
void main() { | ||
late HttpServer server; | ||
setUpAll(() async { | ||
server = await HttpServer.bind(InternetAddress.anyIPv4, 0); | ||
server.listen((e) async { | ||
switch (e.requestedUri.path) { | ||
case '/redirect/local': | ||
e.response.statusCode = 303; | ||
e.response.headers.set('location', 'target'); | ||
await e.response.close(); | ||
return; | ||
case '/redirect/target': | ||
e.response.write('OK'); | ||
await e.response.close(); | ||
return; | ||
default: | ||
e.response.statusCode = 404; | ||
await e.response.close(); | ||
} | ||
}); | ||
}); | ||
|
||
tearDownAll(() async { | ||
await server.close(); | ||
}); | ||
|
||
test('relative redirect', () async { | ||
final client = HttpClient(); | ||
final checker = SafeUrlChecker( | ||
client: client, | ||
userAgent: defaultUserAgent, | ||
retryOptions: RetryOptions(), | ||
timeout: Duration(seconds: 2), | ||
skipLocalNetworkCheck: true, | ||
); | ||
expect( | ||
await checker.checkUrl( | ||
Uri.parse('http://localhost:${server.port}/redirect/local'), 2), | ||
isTrue); | ||
}); | ||
} |
This file contains 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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why are we creating a class that has no purpose?
This is just a convoluted way to make function, right?
Why not just keep the old
_safeUrlCheck
make itsafeUrlCheck
in thesafe_url_check/lib/src/safe_url_check.dart
file and add a parameterskipLocalNetworkCheck
which defaults tofalse
and has@visibleForTestingOnly
annotation.Or we could just accept that we don't have testing, or use httpbin.org for testing.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Or put the parameter on
doSafeUrlCheck
.This introduces a class
SafeUrlChecker
which we only every construct inorder to call a single method.It's just a confusing way to have a function that you can pass arguments to in two different ways.
Another, somewhat simpler and ugly option is to make a global:
Put this in an
lib/src/...
file and check it from withinsafeUrlCheck
.If no code actively sets this property, hopefully the compiler will optimize it away.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I didn't like the recursive function with 6+ parameters. The class keeps the non-changing parts as fields.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Updated, PTAL.