Repository navigation
feat(auth2): Use url-safe base64 encoding for session key - #3834
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the 📝 WalkthroughWalkthroughSession key parsing and building logic was refactored out of the authentication business logic into a new internal utility module. The new module provides functions for constructing and parsing session keys in a URL-safe format. Corresponding unit tests were added to verify correct encoding, decoding, and format compliance. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Server (auth_sessions.dart)
participant SessionKeyUtil (session_key.dart)
Client->>Server (auth_sessions.dart): Sends session key string
Server (auth_sessions.dart)->>SessionKeyUtil (session_key.dart): tryParseSessionKey(session, key)
SessionKeyUtil (session_key.dart)-->>Server (auth_sessions.dart): Returns (authSessionId, secret) or null
Server (auth_sessions.dart)-->>Client: Proceeds with authentication result
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes ✨ Finishing Touches🧪 Generate unit tests✅ Copyable Unit Test edits generated.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
dbb836c to
d4a17ad
Compare
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
|
Note Unit test generation is an Early Access feature. Expect some limitations and changes as we gather feedback and continue to improve it. Generating unit tests... This may take up to 20 minutes. |
|
Here are the copyable unit test edits: Copyable Editsmodules/new_serverpod_auth/serverpod_auth_session/serverpod_auth_session_server/test/session_key_test.dart@@ -8,55 +8,489 @@
import 'integration/test_tools/serverpod_test_tools.dart';
void main() {
+
withServerpod(
- 'Given a session key based on a session secret which would result in `+` when base64 encoded,',
+ 'Given buildSessionKey function with various inputs',
(final sessionBuilder, final endpoints) {
late Session session;
- final secret = Uint8List.fromList([250]);
- final authSessionId = const Uuid().v4obj();
- late String sessionKey;
setUp(() {
session = sessionBuilder.build();
+ });
+
+ group('buildSessionKey edge cases', () {
+ test(
+ 'when secret is empty, then creates a valid session key',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([]);
+
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ expect(sessionKey, isNotEmpty);
+ expect(sessionKey, startsWith('sas:'));
+ expect(sessionKey.split(':').length, equals(3));
+ expect(sessionKey, isNot(contains('+')));
+ expect(sessionKey, isNot(contains('/')));
+ },
+ );
+
+ test(
+ 'when secret contains all possible byte values, then creates URL-safe key',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList(List.generate(256, (i) => i));
+
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ expect(sessionKey, isNotEmpty);
+ expect(sessionKey, startsWith('sas:'));
+ expect(sessionKey.split(':').length, equals(3));
+ expect(sessionKey, isNot(contains('+')));
+ expect(sessionKey, isNot(contains('/')));
+ },
+ );
+
+ test(
+ 'when secret is a single zero byte, then creates valid session key',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([0]);
+
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ expect(sessionKey, isNotEmpty);
+ expect(sessionKey, startsWith('sas:'));
+ expect(sessionKey, endsWith(':AA=='));
+ expect(sessionKey.split(':').length, equals(3));
+ },
+ );
+
+ test(
+ 'when secret is maximum single byte value (255), then creates valid session key',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([255]);
+
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ expect(sessionKey, isNotEmpty);
+ expect(sessionKey, startsWith('sas:'));
+ expect(sessionKey, endsWith(':_w=='));
+ expect(sessionKey.split(':').length, equals(3));
+ },
+ );
+
+ test(
+ 'when called multiple times with same inputs, then produces identical keys',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([123, 45, 67]);
+
+ final sessionKey1 = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+ final sessionKey2 = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ expect(sessionKey1, equals(sessionKey2));
+ },
+ );
+
+ test(
+ 'when called with different authSessionId but same secret, then produces different keys',
+ () {
+ final authSessionId1 = const Uuid().v4obj();
+ final authSessionId2 = const Uuid().v4obj();
+ final secret = Uint8List.fromList([123, 45, 67]);
+
+ final sessionKey1 = buildSessionKey(
+ authSessionId: authSessionId1,
+ secret: secret,
+ );
+ final sessionKey2 = buildSessionKey(
+ authSessionId: authSessionId2,
+ secret: secret,
+ );
+
+ expect(sessionKey1, isNot(equals(sessionKey2)));
+ },
+ );
+
+ test(
+ 'when called with same authSessionId but different secret, then produces different keys',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret1 = Uint8List.fromList([123, 45, 67]);
+ final secret2 = Uint8List.fromList([123, 45, 68]);
- assert(base64Encode(secret) == '+g==');
+ final sessionKey1 = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret1,
+ );
+ final sessionKey2 = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret2,
+ );
- sessionKey = buildSessionKey(
- authSessionId: authSessionId,
- secret: secret,
+ expect(sessionKey1, isNot(equals(sessionKey2)));
+ },
);
+
+ test(
+ 'when building session key, then follows sas:uuid:secret format',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([1, 2, 3]);
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ final parts = sessionKey.split(':');
+ expect(parts.length, equals(3));
+ expect(parts[0], equals('sas'));
+ expect(parts[1], matches(RegExp(r'^[A-Za-z0-9_-]*={0,2}$'))); // URL-safe base64 UUID
+ expect(parts[2], matches(RegExp(r'^[A-Za-z0-9_-]*={0,2}$'))); // URL-safe base64 secret
+ },
+ );
+ });
+ },
+ );
+
+ withServerpod(
+ 'Given tryParseSessionKey function with various inputs',
+ (final sessionBuilder, final endpoints) {
+ late Session session;
+
+ setUp(() {
+ session = sessionBuilder.build();
});
- test(
- 'when inspecting the key, then it does not contain a "+" because the encoding is URL safe.',
- () {
- expect(sessionKey, isNot(contains('+')));
- },
- );
+ group('tryParseSessionKey success cases', () {
+ test(
+ 'when given a valid session key with empty secret, then parses correctly',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([]);
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
- test(
- 'when inspecting the key, then it does at least one ":" to be usable as a Basic auth header.',
- () {
- expect(sessionKey, contains(':'));
- },
- );
+ final keyParts = tryParseSessionKey(session, sessionKey);
- test(
- 'when inspecting the key, then contains the secret in the expected format.',
- () {
- expect(sessionKey, endsWith(':-g=='));
- },
- );
+ expect(keyParts, isNotNull);
+ expect(keyParts!.authSessionId, equals(authSessionId));
+ expect(keyParts.secret, equals(secret));
+ },
+ );
+
+ test(
+ 'when given a valid session key with large secret, then parses correctly',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList(List.generate(100, (i) => i % 256));
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ final keyParts = tryParseSessionKey(session, sessionKey);
+
+ expect(keyParts, isNotNull);
+ expect(keyParts!.authSessionId, equals(authSessionId));
+ expect(keyParts.secret, equals(secret));
+ },
+ );
+
+ test(
+ 'when given a session key with special byte values in secret, then parses correctly',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([0, 63, 127, 128, 191, 255]); // Various byte values
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ final keyParts = tryParseSessionKey(session, sessionKey);
+
+ expect(keyParts, isNotNull);
+ expect(keyParts!.authSessionId, equals(authSessionId));
+ expect(keyParts.secret, equals(secret));
+ },
+ );
+ });
+
+ group('tryParseSessionKey failure cases', () {
+ test(
+ 'when given an empty string, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, '');
+
+ expect(keyParts, isNull);
+ },
+ );
- test(
- 'when parsing the key, then it can be read again.',
- () {
- final keyParts = tryParseSessionKey(session, sessionKey);
+ test(
+ 'when given a string without sas prefix, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'invalid:session:key');
- expect(keyParts?.authSessionId, authSessionId);
- expect(keyParts?.secret, secret);
- },
- );
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given a string with wrong prefix, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'wrong:session:key');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given a string with only sas prefix, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'sas');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given a string with sas but only one colon, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'sas:only-one-part');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given a string with too many parts, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'sas:part1:part2:part3:part4');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given invalid base64 UUID part, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'sas:invalid-base64!@#:dGVzdA==');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given invalid base64 secret part, then returns null',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final validUuidBase64 = base64Url.encode(authSessionId.toBytes());
+ final keyParts = tryParseSessionKey(session, 'sas:$validUuidBase64:invalid-base64!@#');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given empty parts after prefix, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'sas::');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given whitespace in session key, then returns null',
+ () {
+ final keyParts = tryParseSessionKey(session, 'sas: part1 : part2 ');
+
+ expect(keyParts, isNull);
+ },
+ );
+
+ test(
+ 'when given valid format but invalid UUID bytes, then returns null',
+ () {
+ // Create invalid UUID bytes (not 16 bytes)
+ final invalidUuidBytes = Uint8List.fromList([1, 2, 3]); // Too short
+ final invalidUuidBase64 = base64Url.encode(invalidUuidBytes);
+ final keyParts = tryParseSessionKey(session, 'sas:$invalidUuidBase64:dGVzdA==');
+
+ expect(keyParts, isNull);
+ },
+ );
+ });
+
+ group('tryParseSessionKey roundtrip consistency', () {
+ test(
+ 'when building and parsing multiple different session keys, then all roundtrip correctly',
+ () {
+ final testCases = [
+ Uint8List.fromList([]),
+ Uint8List.fromList([0]),
+ Uint8List.fromList([255]),
+ Uint8List.fromList([1, 2, 3, 4, 5]),
+ Uint8List.fromList(List.generate(32, (i) => i)),
+ Uint8List.fromList(List.generate(128, (i) => (i * 7) % 256)),
+ Uint8List.fromList([63, 255, 191]), // Creates special base64 chars
+ ];
+
+ for (final secret in testCases) {
+ final authSessionId = const Uuid().v4obj();
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+ final keyParts = tryParseSessionKey(session, sessionKey);
+
+ expect(keyParts, isNotNull, reason: 'Failed for secret: $secret');
+ expect(keyParts!.authSessionId, equals(authSessionId), reason: 'AuthSessionId mismatch for secret: $secret');
+ expect(keyParts.secret, equals(secret), reason: 'Secret mismatch for secret: $secret');
+ }
+ },
+ );
+
+ test(
+ 'when building 100 random session keys, then all roundtrip correctly',
+ () {
+ for (int i = 0; i < 100; i++) {
+ final authSessionId = const Uuid().v4obj();
+ final secretLength = (i % 50) + 1; // 1 to 50 bytes
+ final secret = Uint8List.fromList(
+ List.generate(secretLength, (index) => (index * 17 + i * 3) % 256)
+ );
+
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+ final keyParts = tryParseSessionKey(session, sessionKey);
+
+ expect(keyParts, isNotNull, reason: 'Failed for iteration $i');
+ expect(keyParts!.authSessionId, equals(authSessionId), reason: 'AuthSessionId mismatch for iteration $i');
+ expect(keyParts.secret, equals(secret), reason: 'Secret mismatch for iteration $i');
+ }
+ },
+ );
+ });
+
+ group('session key format validation', () {
+ test(
+ 'when building session keys, then all follow sas:uuid:secret format pattern',
+ () {
+ for (int i = 0; i < 10; i++) {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList(List.generate(i + 1, (index) => (index * 13) % 256));
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ // Should follow sas:uuid:secret format
+ expect(sessionKey, matches(RegExp(r'^sas:[A-Za-z0-9_-]+={0,2}:[A-Za-z0-9_-]*={0,2}$')));
+ expect(sessionKey, isNot(contains(' ')));
+ expect(sessionKey, isNot(contains('\n')));
+ expect(sessionKey, isNot(contains('\r')));
+ expect(sessionKey, isNot(contains('\t')));
+ }
+ },
+ );
+
+ test(
+ 'when building session keys, then they are suitable for Basic auth headers',
+ () {
+ final authSessionId = const Uuid().v4obj();
+ final secret = Uint8List.fromList([1, 2, 3]);
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+
+ // Should contain exactly 2 colons (making 3 parts)
+ expect(':'.allMatches(sessionKey).length, equals(2));
+
+ // Should not contain characters that would break HTTP headers
+ expect(sessionKey, isNot(contains(' ')));
+ expect(sessionKey, isNot(contains('\n')));
+ expect(sessionKey, isNot(contains('\r')));
+ expect(sessionKey, isNot(contains('\t')));
+ expect(sessionKey, isNot(contains('"')));
+ expect(sessionKey, isNot(contains('\'')));
+ },
+ );
+
+ test(
+ 'when building session key with various UUID versions, then all work correctly',
+ () {
+ final uuidVersions = [
+ const Uuid().v1obj(),
+ const Uuid().v4obj(),
+ const Uuid().v6obj(),
+ const Uuid().v7obj(),
+ ];
+
+ for (final authSessionId in uuidVersions) {
+ final secret = Uint8List.fromList([1, 2, 3]);
+ final sessionKey = buildSessionKey(
+ authSessionId: authSessionId,
+ secret: secret,
+ );
+ final keyParts = tryParseSessionKey(session, sessionKey);
+
+ expect(keyParts, isNotNull, reason: 'Failed for UUID version ${authSessionId.version}');
+ expect(keyParts!.authSessionId, equals(authSessionId));
+ expect(keyParts.secret, equals(secret));
+ }
+ },
+ );
+ });
+
+ group('error handling and logging', () {
+ test(
+ 'when parsing malformed keys, then logs appropriate debug messages',
+ () {
+ // Test various malformed keys that should trigger different error paths
+ final malformedKeys = [
+ 'wrong:prefix:here',
+ 'sas:invalid-uuid:validbase64',
+ 'sas:dmFsaWRfdXVpZA==:invalid-base64!',
+ 'sas:too:many:parts:here',
+ 'sas:',
+ 'sas:only-one-part',
+ ];
+
+ for (final malformedKey in malformedKeys) {
+ final keyParts = tryParseSessionKey(session, malformedKey);
+ expect(keyParts, isNull, reason: 'Should return null for: $malformedKey');
+ // Note: We can't easily test log output without additional setup,
+ // but this ensures the function handles errors gracefully
+ }
+ },
+ );
+ });
},
);
} |
|
@tp - Since the token no longer strictly adheres to the After some reading it seems fine to have a custom format for the token: https://datatracker.ietf.org/doc/html/rfc6750 |
|
@SandPod Yes, I would love to switch to that format. We just have to be careful with backwards compatibility on the server. I think currently we can not do an E2E test from one version to another, but I would love to have this checked with a "real" 2.9.x client against the server. Otherwise blind-coding this and going to a different code path for So maybe this is a good first step, and then when the |
|
Sounds good to me! Then we just need to make sure that we don't release this before we switched over to the other header. |
I attempted to simplify the format further by encoding the entire dataset in one URL-safe base64 encoded String, but since the Serverpod
Clienttakes the raw "session key" and sends it as aBasicauthorization header, that failed (rightfully) in the Relic webserver, as the string did not contain a:anymore and thus did not match theuser:passschema.Thus we have to stick with this format for now, unless we change the client/server (while keeping backwards compatibility). For this token as well as JWT it might be prudent to support the
Bearertoken pattern, and not further modify the values.Summary by CodeRabbit
Refactor
Tests