Skip to content

fix(auth): fail with an AuthException when a redirect response has no url - #1728

Merged
spydon merged 2 commits into
mainfrom
lukasklingsbo/sdk-1497-cast-the-url-field-explicitly-when-building-oauthresponse-in
Aug 17, 2026
Merged

spydon merged 2 commits into
mainfrom
lukasklingsbo/sdk-1497-cast-the-url-field-explicitly-when-building-oauthresponse-in

Conversation

@spydon

@spydon spydon commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

Bug fix. Closes SDK-1497.

What is the current behavior?

Two methods read a url out of an untyped response body without checking it.

getLinkIdentityUrl handed the value straight to OAuthResponse:

return OAuthResponse(provider: provider, url: response['url']);

getSSOSignInUrl cast it:

return Uri.parse(response['url'] as String);

strict-casts is not enabled, so the first line compiles as an implicit
downcast. Both forms behave the same at runtime: if the server omits url, or
sends a number or a list for it, the caller gets a bare TypeError from
whichever line consumes the value first, with nothing pointing at the response
that caused it. A TypeError is also outside this package's exception
hierarchy, so callers that catch AuthException do not see it.

Worth being explicit about: adding an as String to the first line would have
changed nothing at runtime. The implicit downcast already throws the same
TypeError in the same place. Only a real check changes the behaviour.

What is the new behavior?

Both call sites read the field through one helper that validates it and throws
an AuthException at the response boundary:

String _urlFromResponse(dynamic response) {
  final url = response is Map ? response['url'] : null;
  if (url is! String) {
    throw AuthException('No url detected.');
  }
  return url;
}

The message follows the convention the client already uses for missing response
fields (No access_token detected., No refresh_token detected., and so on).
The response is Map guard means a body that is not an object at all, a JSON
list for instance, reports the same error rather than a NoSuchMethodError.

Tests

packages/supabase_auth/test/redirect_url_mock_test.dart covers both methods
against three malformed bodies each: field absent, field present with the wrong
type, and a body that is not an object. All six fail with a TypeError on the
old code and pass on the new code, so they pin down the behaviour rather than
just the happy path.

The mock is a small reusable JsonResponseMockClient in test/mocks/, since
every existing mocked test in this package hand-rolls its own client.

No backend needed: dart test test/redirect_url_mock_test.dart runs standalone.

Notes

Not a breaking change, so this does not need to wait for v3.

SDK-1496 changes OAuthResponse.url to a Uri and touches the same
getLinkIdentityUrl line. That PR is stacked on this branch, so merge this one
first.

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation of SSO and identity-link responses.
    • Clear authentication errors are now shown when a valid URL is missing, malformed, null, or returned in an unexpected format.
    • Prevented invalid authentication redirect data from being used.
  • Tests

    • Added coverage for missing URLs, invalid URL values, null responses, and unexpected response formats.
    • Added reusable HTTP response mocking for authentication scenarios.

… url

getLinkIdentityUrl passed the decoded body straight into OAuthResponse, and
getSSOSignInUrl cast it with a bare 'as String'. The body is untyped, so a
server that omits 'url' or sends the wrong type for it surfaced as a
TypeError from whichever line consumed the value first, outside this
package's exception hierarchy.

Read the field through one helper that checks it and throws an
AuthException instead, matching how the client already reports missing
response fields such as 'No access_token detected.'.
@spydon
spydon requested a review from a team as a code owner August 17, 2026 08:16
@github-actions github-actions Bot added the auth This issue or pull request is related to authentication label Aug 17, 2026
@coderabbitai

coderabbitai Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 84e62466-78c2-4227-ada6-f70742e3f1c6

📥 Commits

Reviewing files that changed from the base of the PR and between 8c7bbe3 and 015fb61.

📒 Files selected for processing (1)
  • packages/supabase_auth/test/redirect_url_mock_test.dart
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/supabase_auth/test/redirect_url_mock_test.dart

Included review availability: Your plan includes up to 4 reviews per rolling hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

SSO and identity-link URL responses now use shared validation. Invalid or missing URL values throw AuthException. Tests use a configurable JSON HTTP mock for invalid response bodies.

Changes

Redirect URL validation

Layer / File(s) Summary
Validate redirect URL responses
packages/supabase_auth/lib/src/auth_client.dart
SSO and identity-link URL retrieval use _urlFromResponse, which requires a string url and throws AuthException('No url detected.') for invalid responses.
Test invalid redirect URL responses
packages/supabase_auth/test/mocks/json_response_mock_client.dart, packages/supabase_auth/test/redirect_url_mock_test.dart
Added a configurable JSON HTTP mock and tests for missing, non-string, non-object, and null URL responses.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to 015fb

The change converts malformed redirect responses into the package's expected AuthException instead of an unhandled type error, with focused tests covering the affected cases; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: throwing AuthException when a redirect response lacks a valid URL.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch lukasklingsbo/sdk-1497-cast-the-url-field-explicitly-when-building-oauthresponse-in

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

A server that answers with a literal JSON null decodes to null, reaches the
same guard and reports the same AuthException, so cover it for both methods.

This also settles DCM's avoid-unnecessary-nullable-parameters warning on the
test helper honestly: the parameter is nullable because a null body is now a
case under test, rather than dropping the '?' to quiet the rule.
@spydon
spydon merged commit 1a4801f into main Aug 17, 2026
38 checks passed
@spydon
spydon deleted the lukasklingsbo/sdk-1497-cast-the-url-field-explicitly-when-building-oauthresponse-in branch August 17, 2026 09:45
spydon added a commit that referenced this pull request Aug 17, 2026
…ing (#1729)

## What kind of change does this PR introduce?

Breaking change, refactor. Closes SDK-1496.

> [!NOTE]
> This was originally stacked on #1728. That has landed, so this branch
is
> rebased directly onto `main` and stands on its own.

## What is the current behavior?

#1722 changed `getSSOSignInUrl` to return a `Future<Uri>`, which left
the two
sibling URL getters disagreeing with it:

| Method | Returns |
| --- | --- |
| `AuthClient.getSSOSignInUrl` | `Future<Uri>` |
| `AuthClient.getOAuthSignInUrl` | `Future<OAuthResponse>` with `String
url` |
| `AuthClient.getLinkIdentityUrl` | `Future<OAuthResponse>` with `String
url` |

Shipping v3 that way means three URL-returning auth methods with two
different
types for the same concept, and callers still writing `Uri.parse` for
two of
them.

## What is the new behavior?

`OAuthResponse.url` is a `Uri`. Both getters share that type, so this
covers
them in one change and makes all three consistent.

Two internal tidy-ups fall out of it:

- `_getUrlForProvider` returns the `Uri` it builds rather than a whole
`OAuthResponse`. `getLinkIdentityUrl` only ever wanted the URL to send a
request to, and the response type belongs at the public boundary, so it
is now
  constructed there by both public methods.
- `supabase_flutter`'s `_launchAuthUrl` takes a `Uri` and drops its
internal
  `Uri.parse`. It hands the value straight to `launchUrl`.

## The wire format is unchanged

This is the part worth scrutinising, since the URL is built by string
interpolation and is now parsed before it leaves the client.

The query is still built with `Uri(queryParameters: ...)` exactly as
before, and
`Uri.parse` round-trips the result byte for byte. Verified against the
shapes
this code actually produces:

```
SAME  ...?provider=google&redirect_to=https%3A%2F%2Fsupabase.com
SAME  ...?provider=github&scopes=repo&redirect_to=redirectToURL
SAME  ...?provider=custom%3Amy-oidc-provider&scopes=openid+profile+email
SAME  ...?provider=google&redirect_to=my-app%3A%2F%2Fcallback%3Fa%3Db%26c%3Dd
SAME  ...?provider=google&code_challenge=abc-_~.123&flow_type=pkce
```

Percent-encoded redirect targets, nested query strings inside
`redirect_to`,
plus-encoded spaces in `scopes` and the PKCE challenge characters all
survive
unchanged. `client_test.dart` also still asserts one full URL by exact
string
equality, including `%3A%2F%2F`, and passes against a real GoTrue.

## Tests

Existing coverage was updated rather than replaced. Three tests in
`client_test.dart` named "can append a redirectUrl", "can append scopes"
and
"can append options" only asserted `isA<String>()` and never checked the
thing
their names promise. Now that `url` is a `Uri` they read the parameters
directly:

```dart
expect(response.url.queryParameters['scopes'], 'repo');
```

The remaining `isA<String>()` assertions became `isA<Uri>()`. Those were
tautological before this PR and still are, so they are left alone rather
than
rewritten here.

Verified with the local Supabase stack running:

- `packages/supabase_auth`: `dart test -j 1`, 472 passing, which
includes
  `getLinkIdentityUrl` against real GoTrue returning a real Google URL
- `packages/supabase_flutter`: `flutter test`, 76 passing
- `dart analyze packages`: no issues
- `dart format`: no changes

## Migration

`MIGRATION.md` gets an `OAuthResponse.url` section next to the
`getSSOSignInUrl` one, and the affected `sdk-compliance.yaml` notes are
updated.



<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Enhancements**
* OAuth sign-in and identity-linking URLs are now returned as `Uri`
values.
* URL query parameters can be inspected directly without manual parsing.
  * Flutter launches OAuth URLs directly and preserves the provided URI.

* **Documentation**
* Added migration guidance for upgrading from v2 to v3, including
converting URIs to text with `toString()` when needed.
  * Documented Dart and Flutter OAuth URL and return-type differences.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth This issue or pull request is related to authentication

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants