platform/test/csrf_token_test.dart

51 lines
1.5 KiB
Dart
Raw Normal View History

2017-01-13 03:11:55 +00:00
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_security/angel_security.dart';
import 'package:angel_test/angel_test.dart';
import 'package:http/http.dart' as http;
import 'package:test/test.dart';
2019-04-20 14:53:52 +00:00
final RegExp _sessId = RegExp(r'DARTSESSID=([^;]+);');
2017-01-13 03:11:55 +00:00
main() async {
Angel app;
TestClient client;
setUp(() async {
2019-04-20 14:53:52 +00:00
app = Angel()..responseFinalizers.add(setCsrfToken());
2017-01-13 03:11:55 +00:00
2019-04-20 14:53:52 +00:00
app.chain([verifyCsrfToken()]).get('/valid', (req, res) => 'Valid!');
2017-01-13 03:11:55 +00:00
client = await connectTo(app);
});
tearDown(() => client.close());
test('need pre-existing token', () async {
var response = await client.get('/valid?csrf_token=evil');
print(response.body);
expect(response, hasStatus(400));
expect(response.body, contains('Missing'));
});
test('fake token', () async {
// Get a valid CSRF, but ignore it.
var response = await client.get('/');
var sessionId = getCookie(response);
response = await client.get('/valid?csrf_token=evil',
headers: {'cookie': 'DARTSESSID=$sessionId'});
print(response.body);
expect(response, hasStatus(400));
expect(response.body.contains('Valid'), isFalse);
expect(response.body, contains('Invalid CSRF token'));
});
}
String getCookie(http.Response response) {
if (response.headers.containsKey('set-cookie')) {
var header = response.headers['set-cookie'];
var match = _sessId.firstMatch(header);
return match?.group(1);
} else
return null;
}