Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/better_networking/lib/services/http_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ Future<(HttpResponse?, Duration?, String?)> sendHttpRequestV1(

try {
if (authData != null && authData.type != APIAuthType.none) {
authenticatedRequestModel = await handleAuth(requestModel, authData);
authenticatedRequestModel = await handleAuth(
requestModel,
authData,
defaultUriScheme: defaultUriScheme,
);
}
} catch (e) {
return (null, null, e.toString());
Expand Down Expand Up @@ -267,6 +271,7 @@ Future<Stream<HttpStreamOutput>> streamHttpRequest(
authenticatedHttpRequestModel = await handleAuth(
httpRequestModel,
authData,
defaultUriScheme: defaultUriScheme,
);
}
} catch (e) {
Expand Down
6 changes: 4 additions & 2 deletions packages/better_networking/lib/utils/auth/handle_auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import 'oauth1_utils.dart';

Future<HttpRequestModel> handleAuth(
HttpRequestModel httpRequestModel,
AuthModel? authData,
) async {
AuthModel? authData, {
SupportedUriSchemes defaultUriScheme = kDefaultUriScheme,
}) async {
if (authData == null || authData.type == APIAuthType.none) {
return httpRequestModel;
}
Expand Down Expand Up @@ -165,6 +166,7 @@ Future<HttpRequestModel> handleAuth(
final client = generateOAuth1AuthHeader(
oauth1Model,
httpRequestModel,
defaultUriScheme: defaultUriScheme,
);

updatedHeaders.add(
Expand Down
17 changes: 14 additions & 3 deletions packages/better_networking/lib/utils/auth/oauth1_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:math' as math;
import 'package:crypto/crypto.dart';
import '../../models/models.dart';
import '../../consts.dart';
import '../uri_utils.dart';

/// Generates a simple OAuth 1.0a Authorization header directly from AuthOAuth1Model model
///
Expand All @@ -17,8 +18,9 @@ import '../../consts.dart';
/// - Formats the Authorization header
String generateOAuth1AuthHeader(
AuthOAuth1Model oauth1Model,
HttpRequestModel request,
) {
HttpRequestModel request, {
SupportedUriSchemes defaultUriScheme = kDefaultUriScheme,
}) {
// Generate OAuth parameters
final timestamp = (DateTime.now().millisecondsSinceEpoch ~/ 1000).toString();
final nonce = _generateNonce();
Expand All @@ -40,7 +42,16 @@ String generateOAuth1AuthHeader(

// Create signature base string and signing key
final method = request.method.name.toUpperCase();
final uri = Uri.parse(request.url);
// Normalise the URL exactly like the request itself will be (default scheme,
// localhost / IP handling) so the signed base URI matches what is sent.
final (uri, uriError) = getValidRequestUri(
request.url,
null,
defaultUriScheme: defaultUriScheme,
);
if (uri == null) {
throw ArgumentError(uriError ?? 'Invalid request URL');
}
final baseString = _createSignatureBaseString(method, uri, oauthParams);

// Generate signature based on signature method
Expand Down
59 changes: 59 additions & 0 deletions packages/better_networking/test/utils/auth/auth_handling_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,65 @@ void main() {
},
);

group('OAuth1 URL normalisation', () {
const oauth1Auth = AuthModel(
type: APIAuthType.oauth1,
oauth1: AuthOAuth1Model(
consumerKey: 'consumer-key',
consumerSecret: 'consumer-secret',
signatureMethod: OAuth1SignatureMethod.hmacSha1,
),
);

for (final url in [
'api.apidash.dev/users',
'localhost:8080/users',
'127.0.0.1:8080/users',
]) {
test(
'given handleAuth when OAuth1 is used with scheme-less URL $url then it should add an OAuth Authorization header',
() async {
final httpRequestModel = HttpRequestModel(
method: HTTPVerb.get,
url: url,
);

final result = await handleAuth(httpRequestModel, oauth1Auth);

final header = result.headers?.firstWhere(
(h) => h.name == 'Authorization',
);
expect(header?.value, startsWith('OAuth '));
expect(header?.value, contains('oauth_signature="'));
},
);
}

test(
'given handleAuth when OAuth1 is used with an unsupported scheme then it should throw a descriptive Exception',
() async {
const httpRequestModel = HttpRequestModel(
method: HTTPVerb.get,
url: 'ftp://api.apidash.dev/users',
);

expect(
() async => await handleAuth(httpRequestModel, oauth1Auth),
throwsA(
isA<Exception>().having(
(e) => e.toString(),
'message',
allOf(
contains('OAuth 1.0 authentication failed'),
contains('Unsupported URL Scheme'),
),
),
),
);
},
);
});

test(
'given handleAuth when OAuth2 authentication is provided but oauth2 data is null then it should throw Exception',
() async {
Expand Down