From 29897e35ec0d1b4fe75f845e6d629cc5ab794c13 Mon Sep 17 00:00:00 2001 From: Dmitrii Date: Sun, 9 Aug 2026 21:46:55 -0700 Subject: [PATCH] feat: add native OIDC endpoints for mobile/desktop clients (#7804) Co-authored-by: Michael Genson <71845777+michael-genson@users.noreply.github.com> --- .../getting-started/authentication/oidc-v2.md | 16 ++++ frontend/app/lib/api/types/user.ts | 11 +++ mealie/routes/auth/auth.py | 69 +++++++++++++- mealie/schema/user/__init__.py | 12 ++- mealie/schema/user/auth.py | 17 ++++ tests/e2e/oidc-native.spec.ts | 84 +++++++++++++++++ .../user_tests/test_oidc_native.py | 93 +++++++++++++++++++ tests/utils/api_routes/__init__.py | 4 + 8 files changed, 303 insertions(+), 3 deletions(-) create mode 100644 tests/e2e/oidc-native.spec.ts create mode 100644 tests/integration_tests/user_tests/test_oidc_native.py diff --git a/docs/docs/documentation/getting-started/authentication/oidc-v2.md b/docs/docs/documentation/getting-started/authentication/oidc-v2.md index d63ce757c..9a8acb003 100644 --- a/docs/docs/documentation/getting-started/authentication/oidc-v2.md +++ b/docs/docs/documentation/getting-started/authentication/oidc-v2.md @@ -83,6 +83,22 @@ There are two (optional) [environment variables](../installation/backend-config. `OIDC_ADMIN_GROUP`: Users that are in this group (within your IdP) will be made an **admin** in Mealie. Users in this group do not need to be in the `OIDC_USER_GROUP` +## Native and mobile clients + +Native apps (mobile or desktop) authenticate using the **system browser** instead of an embedded WebView. This is required for **passkey-only** providers such as [Pocket ID](https://pocket-id.org), because WebAuthn/passkeys do not work inside embedded WebViews. + +Unlike the web flow, a native client performs its own [PKCE](https://oauth.net/2/pkce/) authorization request, captures the authorization code at an app-controlled redirect URI, and then has Mealie exchange it. No browser session cookie is involved, so the exchange works from a native HTTP client. + +These endpoints are available automatically whenever OIDC is configured — there is no separate flag to enable them: + +- `GET /api/auth/oauth/native/config` — returns the `authorization_endpoint`, `client_id`, and `scope` the client needs to build its own authorization request. +- `POST /api/auth/oauth/native/token` — exchanges `{ code, code_verifier, redirect_uri, nonce? }` for a Mealie access token. + +The native flow reuses your existing **confidential** OIDC client and `OIDC_CLIENT_SECRET` — the same setup as the web flow. The only additional step is in your identity provider: **register the native client's redirect URI** (a custom scheme such as `app-scheme://oauth/callback`, supplied by the app) on the same OIDC client. The provider validates this redirect URI, so it is the access control for native logins — no Mealie-side configuration is required. + +!!! note + Providers that require a separate **public** (secret-less) native client — notably Google and Microsoft Entra — are not yet supported by this flow. Self-hosted providers that let you add a redirect URI to the existing confidential client (Pocket ID, Authentik, Authelia, Keycloak, …) work today. + ## Examples Example configurations for several Identity Providers have been provided by the Community in the [GitHub Discussions](https://github.com/mealie-recipes/mealie/discussions/categories/oauth-provider-example). diff --git a/frontend/app/lib/api/types/user.ts b/frontend/app/lib/api/types/user.ts index c1dc7a706..2d4db700d 100644 --- a/frontend/app/lib/api/types/user.ts +++ b/frontend/app/lib/api/types/user.ts @@ -159,6 +159,17 @@ export interface LongLiveTokenOut { id: number; createdAt?: string | null; } +export interface NativeOIDCTokenRequest { + code: string; + code_verifier: string; + redirect_uri: string; + nonce?: string | null; +} +export interface OIDCNativeConfig { + authorization_endpoint: string; + client_id: string; + scope: string; +} export interface PasswordResetToken { token: string; } diff --git a/mealie/routes/auth/auth.py b/mealie/routes/auth/auth.py index 4502dfb0d..a1fe2c4fd 100644 --- a/mealie/routes/auth/auth.py +++ b/mealie/routes/auth/auth.py @@ -1,6 +1,6 @@ from typing import Annotated, Any -from authlib.integrations.starlette_client import OAuth +from authlib.integrations.starlette_client import OAuth, OAuthError from fastapi import APIRouter, Depends, Header, Request, Response, status from fastapi.exceptions import HTTPException from fastapi.responses import RedirectResponse @@ -18,7 +18,7 @@ from mealie.db.db_setup import generate_session from mealie.lang import get_locale_provider from mealie.routes._base.routers import UserAPIRouter from mealie.schema.user import PrivateUser -from mealie.schema.user.auth import CredentialsRequestForm +from mealie.schema.user.auth import CredentialsRequestForm, NativeOIDCTokenRequest, OIDCNativeConfig from .auth_cache import AuthCache @@ -144,6 +144,71 @@ async def oauth_callback(request: Request, session: Session = Depends(generate_s return MealieAuthToken.respond(access_token) +@public_router.get("/oauth/native/config", response_model=OIDCNativeConfig) +async def oauth_native_config(): + """Return the parameters a native client needs to build its own OIDC authorization request.""" + if not settings.OIDC_READY: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="OIDC is not configured", + ) + + client = oauth.create_client("oidc") + metadata = await client.load_server_metadata() + return OIDCNativeConfig( + authorization_endpoint=metadata["authorization_endpoint"], + client_id=client.client_id, + scope=client.client_kwargs.get("scope", "openid email profile"), + ) + + +@public_router.post("/oauth/native/token") +async def oauth_native_token(data: NativeOIDCTokenRequest, session: Session = Depends(generate_session)): + """Exchange a native client's authorization code for a Mealie token. + + The native client owns PKCE and state, so the exchange happens server-side without a browser + session cookie. This lets passkey-capable system-browser logins (e.g. Pocket ID) work, which + the cookie-coupled web callback cannot support. + """ + if not settings.OIDC_READY: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="OIDC is not configured", + ) + + client = oauth.create_client("oidc") + try: + token = await client.fetch_access_token( + code=data.code, + code_verifier=data.code_verifier, + redirect_uri=data.redirect_uri, + ) + userinfo = await client.parse_id_token(token, nonce=data.nonce) + except OAuthError as e: + logger.error("[OIDC] Native token exchange failed: %s", e) + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) from e + + auth = None + try: + auth_provider = OpenIDProvider(session, userinfo) + auth = auth_provider.authenticate() + except MissingClaimException: + try: + logger.debug("[OIDC] Claims not present in the id_token, pulling user info") + userinfo = await client.userinfo(token=token) + auth_provider = OpenIDProvider(session, userinfo, use_default_groups=True) + auth = auth_provider.authenticate() + except MissingClaimException: + logger.error("[OIDC] Required claims not present in ID token or userinfo endpoint") + auth = None + + if not auth: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) + + access_token, _ = auth + return MealieAuthToken.respond(access_token) + + @user_router.get("/refresh") async def refresh_token(current_user: PrivateUser = Depends(get_current_user)): """Use a valid token to get another token""" diff --git a/mealie/schema/user/__init__.py b/mealie/schema/user/__init__.py index f3c7f03cf..b5ef0348e 100644 --- a/mealie/schema/user/__init__.py +++ b/mealie/schema/user/__init__.py @@ -1,5 +1,13 @@ # This file is auto-generated by gen_schema_exports.py -from .auth import CredentialsRequest, CredentialsRequestForm, Token, TokenData, UnlockResults +from .auth import ( + CredentialsRequest, + CredentialsRequestForm, + NativeOIDCTokenRequest, + OIDCNativeConfig, + Token, + TokenData, + UnlockResults, +) from .registration import CreateUserRegistration from .user import ( ChangePassword, @@ -41,6 +49,8 @@ __all__ = [ "CreateUserRegistration", "CredentialsRequest", "CredentialsRequestForm", + "NativeOIDCTokenRequest", + "OIDCNativeConfig", "Token", "TokenData", "UnlockResults", diff --git a/mealie/schema/user/auth.py b/mealie/schema/user/auth.py index cc6b14a65..71683eb9c 100644 --- a/mealie/schema/user/auth.py +++ b/mealie/schema/user/auth.py @@ -26,6 +26,23 @@ class CredentialsRequest(BaseModel): remember_me: bool = False +class OIDCNativeConfig(BaseModel): + """Parameters a native client needs to start an OIDC authorization request itself.""" + + authorization_endpoint: str + client_id: str + scope: str + + +class NativeOIDCTokenRequest(BaseModel): + """An authorization code captured by a native client, for server-side exchange.""" + + code: str + code_verifier: str + redirect_uri: str + nonce: str | None = None + + class CredentialsRequestForm: """Class that represents a user's credentials from the login form""" diff --git a/tests/e2e/oidc-native.spec.ts b/tests/e2e/oidc-native.spec.ts new file mode 100644 index 000000000..d8e830a0a --- /dev/null +++ b/tests/e2e/oidc-native.spec.ts @@ -0,0 +1,84 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { test, expect } from '@playwright/test'; + +// Native (mobile/desktop) OIDC flow: the client owns PKCE + state and captures the redirect +// itself; the server exchanges the code without a browser session cookie. Verified end-to-end +// against the mock-oauth2-server from docker-compose, mirroring the web OIDC tests in login.spec.ts. + +const REDIRECT_URI = 'http://localhost:9999/native-callback'; +const NATIVE_CONFIG_URL = '/api/auth/oauth/native/config'; +const NATIVE_TOKEN_URL = '/api/auth/oauth/native/token'; + +test('oidc native flow exchanges an app-captured code for a mealie token', async ({ page, request }) => { + const configResp = await request.get(NATIVE_CONFIG_URL); + expect(configResp.status()).toBe(200); + const config = await configResp.json(); + + // The native client generates its own PKCE pair, state, and nonce. + const codeVerifier = randomBytes(32).toString('base64url'); + const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url'); + const state = 'native-state'; + const nonce = 'native-nonce'; + + const username = 'nativeUser'; + const claims = { + sub: username, + email: `${username}@example.com`, + email_verified: true, + preferred_username: username, + name: 'Native User', + groups: ['user'], + }; + + const authUrl = + `${config.authorization_endpoint}?response_type=code` + + `&client_id=${encodeURIComponent(config.client_id)}` + + `&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` + + `&scope=${encodeURIComponent(config.scope)}` + + `&state=${state}&nonce=${nonce}` + + `&code_challenge=${codeChallenge}&code_challenge_method=S256`; + + // Capture the redirect URL. The browser will navigate to localhost:9999 (nothing listening) + // and show a connection error — that's fine. We only need the code from the URL, which + // page.on('request') captures before the network failure. + let capturedUrl = ''; + page.on('request', (req) => { + if (req.url().startsWith(REDIRECT_URI)) { + capturedUrl = req.url(); + } + }); + + await page.goto(authUrl); + await page.getByPlaceholder('Enter any user/subject').fill(username); + await page.getByPlaceholder('Optional claims JSON value,').fill(JSON.stringify(claims)); + await page.getByRole('button', { name: 'Sign-in' }).click(); + + await expect.poll(() => capturedUrl).toContain('code='); + const code = new URL(capturedUrl).searchParams.get('code'); + + const tokenResp = await request.post(NATIVE_TOKEN_URL, { + data: { code, code_verifier: codeVerifier, redirect_uri: REDIRECT_URI, nonce }, + }); + expect(tokenResp.status()).toBe(200); + + const token = await tokenResp.json(); + expect(token.access_token).toBeTruthy(); + + // The minted token is a usable Mealie token. + const selfResp = await request.get('/api/users/self', { + headers: { Authorization: `Bearer ${token.access_token}` }, + }); + expect(selfResp.status()).toBe(200); + expect((await selfResp.json()).username).toBe(username); +}); + +test('oidc native token rejects an invalid authorization code', async ({ request }) => { + const resp = await request.post(NATIVE_TOKEN_URL, { + data: { + code: 'invalid-code', + code_verifier: 'invalid-verifier', + redirect_uri: REDIRECT_URI, + }, + }); + expect(resp.status()).toBe(401); +}); diff --git a/tests/integration_tests/user_tests/test_oidc_native.py b/tests/integration_tests/user_tests/test_oidc_native.py new file mode 100644 index 000000000..8b71dc6ce --- /dev/null +++ b/tests/integration_tests/user_tests/test_oidc_native.py @@ -0,0 +1,93 @@ +from authlib.integrations.starlette_client import OAuthError +from fastapi.testclient import TestClient +from joserfc.errors import InvalidClaimError +from pytest import MonkeyPatch + +from mealie.app import app +from mealie.routes.auth import auth as auth_routes +from tests.utils import api_routes + +native_token_request = { + "code": "expired-authorization-code", + "code_verifier": "code-verifier", + "redirect_uri": "mealie://oidc-callback", + "nonce": "nonce", +} + + +class OAuthClientMock: + """Stands in for the authlib OIDC client, failing the way a rejected code or id_token does""" + + def __init__(self, token_error: Exception | None = None, id_token_error: Exception | None = None): + self.token_error = token_error + self.id_token_error = id_token_error + + async def fetch_access_token(self, **kwargs) -> dict: + if self.token_error: + raise self.token_error + return {"access_token": "access-token", "id_token": "id-token"} + + async def parse_id_token(self, token, nonce=None) -> dict: + if self.id_token_error: + raise self.id_token_error + return {} + + +class OAuthMock: + def __init__(self, client: OAuthClientMock): + self.client = client + + def create_client(self, name: str) -> OAuthClientMock: + return self.client + + +def setup_oidc( + monkeypatch: MonkeyPatch, token_error: Exception | None = None, id_token_error: Exception | None = None +) -> None: + monkeypatch.setattr(type(auth_routes.settings), "OIDC_READY", property(lambda self: True)) + client = OAuthClientMock(token_error=token_error, id_token_error=id_token_error) + monkeypatch.setattr(auth_routes, "oauth", OAuthMock(client), raising=False) + + +def test_native_config_returns_404_when_oidc_not_configured(api_client: TestClient): + response = api_client.get(api_routes.auth_oauth_native_config) + + assert response.status_code == 404 + assert response.json()["detail"] == "OIDC is not configured" + + +def test_native_token_returns_404_when_oidc_not_configured(api_client: TestClient): + response = api_client.post(api_routes.auth_oauth_native_token, json=native_token_request) + + assert response.status_code == 404 + assert response.json()["detail"] == "OIDC is not configured" + + +def test_native_token_returns_401_when_code_is_rejected(api_client: TestClient, monkeypatch: MonkeyPatch): + setup_oidc(monkeypatch, token_error=OAuthError("invalid_grant", "authorization code is invalid or expired")) + + response = api_client.post(api_routes.auth_oauth_native_token, json=native_token_request) + + assert response.status_code == 401 + + +def test_native_token_returns_500_on_unexpected_errors(monkeypatch: MonkeyPatch): + setup_oidc(monkeypatch, token_error=RuntimeError("the IdP is unreachable")) + + # anything that isn't an OAuthError is a server-side failure, not a bad code, so it must not + # become a 401; this client returns the 500 instead of re-raising the way the shared one does + client = TestClient(app, raise_server_exceptions=False) + response = client.post(api_routes.auth_oauth_native_token, json=native_token_request) + + assert response.status_code == 500 + + +def test_native_token_returns_500_when_id_token_is_rejected(monkeypatch: MonkeyPatch): + setup_oidc(monkeypatch, id_token_error=InvalidClaimError("nonce")) + + # authlib validates the id_token with joserfc, whose errors are not OAuthError, so a bad nonce + # or signature is a 500 here, matching the web /oauth/callback route's unwrapped behavior + client = TestClient(app, raise_server_exceptions=False) + response = client.post(api_routes.auth_oauth_native_token, json=native_token_request) + + assert response.status_code == 500 diff --git a/tests/utils/api_routes/__init__.py b/tests/utils/api_routes/__init__.py index 4031eb2f8..f73105e34 100644 --- a/tests/utils/api_routes/__init__.py +++ b/tests/utils/api_routes/__init__.py @@ -45,6 +45,10 @@ auth_oauth = "/api/auth/oauth" """`/api/auth/oauth`""" auth_oauth_callback = "/api/auth/oauth/callback" """`/api/auth/oauth/callback`""" +auth_oauth_native_config = "/api/auth/oauth/native/config" +"""`/api/auth/oauth/native/config`""" +auth_oauth_native_token = "/api/auth/oauth/native/token" +"""`/api/auth/oauth/native/token`""" auth_refresh = "/api/auth/refresh" """`/api/auth/refresh`""" auth_token = "/api/auth/token"