feat: add token refresh, fix remember me, and fix Safari token expiration (#8200)

This commit is contained in:
Michael Genson authored and GitHub committed 2026-08-24 14:49:11 -05:00
1 parent 0a825b3061
commit a1a49d22dc
33 files changed
+1565 -131

No files matched your search

@@ -120,6 +120,8 @@
Login session can be configured by setting the `TOKEN_TIME` variable on the backend container.
Sessions refresh automatically while Mealie is open, so `TOKEN_TIME` is how long you can go without using Mealie before you have to log in again, not a hard limit on the session. Ticking "Remember Me" at login keeps the session after you close the browser; leaving it unticked ends the session when the browser closes.
- [Backend Config](./installation/backend-config.md)
@@ -11,7 +11,7 @@
| DEFAULT_GROUP | Home | The default group for users |
| DEFAULT_HOUSEHOLD | Family | The default household for users in each group |
| BASE_URL | http://localhost:8080 | Used for notifications and the OIDC callback url |
| TOKEN_TIME | 48 | The time in hours that a login/auth token is valid. Must be <= 9600 (400 days, in hours). |
| TOKEN_TIME | 48 | The time in hours a login session lasts. Must be <= 9600 (400 days, in hours). |
| API_PORT | 9000 | The port exposed by backend API. **Do not change this if you're running in Docker** |
| API_DOCS | True | Turns on/off access to the API documentation locally |
| TZ | UTC | Must be set to get correct date/time on the server |
@@ -109,7 +109,7 @@ For usage, see [Usage - OpenID Connect](../authentication/oidc-v2.md)
| OIDC_ADMIN_GROUP | None | If specified, users belonging to this group will be made an admin. For more information see [this page](../authentication/oidc.md#groups) |
| OIDC_AUTO_REDIRECT | False | If `True`, then the login page will be bypassed an you will be sent directly to your Identity Provider. You can still get to the login page by adding `?direct=1` to the login URL |
| OIDC_PROVIDER_NAME | OAuth | The provider name is shown in SSO login button. "Login with <OIDC_PROVIDER_NAME\>" |
| OIDC_REMEMBER_ME | False | Because redirects bypass the login screen, you cant extend your session by clicking the "Remember Me" checkbox. By setting this value to true, a session will be extended as if "Remember Me" was checked |
| OIDC_REMEMBER_ME | False | Because redirects bypass the login screen, you can't tick the "Remember Me" checkbox. Setting this to true treats an OIDC login as if it had been checked, so the session survives closing the browser |
| OIDC_SIGNING_ALGORITHM | RS256 | The algorithm used to sign the id token (examples: RS256, HS256) |
| OIDC_USER_CLAIM | email | This is the claim which Mealie will use to look up an existing user by (e.g. "email", "preferred_username") |
| OIDC_NAME_CLAIM | name | This is the claim which Mealie will use for the users Full Name |
@@ -0,0 +1,212 @@
import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
// Reused rather than reimplemented: the production reader escapes the full set of regex
// metacharacters, and it has its own coverage in use-token-cookie.test.ts.
import { readTokenCookie } from "../use-token-cookie";
// Pulled in by use-auth-backend purely to wipe cached data on logout. They drag in most of the
// composable graph, none of which this file exercises.
vi.mock("~/composables/store", () => ({ clearAllStores: vi.fn() }));
vi.mock("~/composables/use-clear-composable-caches", () => ({ clearComposableCaches: vi.fn() }));
const TOKEN_NAME = "mealie.access_token";
function encodeToken(payload: Record<string, unknown>): string {
const body = btoa(JSON.stringify(payload)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
return `header.${body}.signature`;
}
/** A token that expires far enough out that no refresh is scheduled during the test. */
function validToken(): string {
return encodeToken({ sub: "abc", rme: true, exp: Math.floor(Date.now() / 1000) + 86_400 });
}
function unauthorized() {
return Object.assign(new Error("Unauthorized"), { response: { status: 401 } });
}
let axiosMock: { get: ReturnType<typeof vi.fn>; post: ReturnType<typeof vi.fn> };
let routerMock: { push: ReturnType<typeof vi.fn> };
let useAuthBackend: typeof import("../use-auth-backend").useAuthBackend;
beforeEach(async () => {
document.cookie = `${TOKEN_NAME}=; max-age=0`;
axiosMock = {
get: vi.fn().mockResolvedValue({ data: { id: "user-1" } }),
post: vi.fn(),
};
routerMock = { push: vi.fn() };
vi.stubGlobal("useNuxtApp", () => ({ $axios: axiosMock, $appInfo: { production: false } }));
vi.stubGlobal("useRouter", () => routerMock);
vi.stubGlobal("useRuntimeConfig", () => ({ public: { AUTH_TOKEN: TOKEN_NAME } }));
vi.stubGlobal("clearNuxtData", vi.fn());
vi.stubGlobal("useCookie", (name: string) => ({
get value() {
return readTokenCookie(name);
},
set value(next: string | null) {
document.cookie = next === null ? `${name}=; max-age=0` : `${name}=${encodeURIComponent(next)}`;
},
}));
// Module-level refresh state (the in-flight promise, the scheduled timer) would otherwise leak
// between tests, which is exactly the state these tests are about.
vi.resetModules();
({ useAuthBackend } = await import("../use-auth-backend"));
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe("refresh", () => {
test("shares one request between concurrent callers", async () => {
const auth = useAuthBackend();
auth.setToken(validToken());
let release: (value: unknown) => void = () => {};
axiosMock.post.mockReturnValue(new Promise(resolve => (release = resolve)));
const inFlight = [auth.refresh(), auth.refresh(), auth.refresh()];
release({ data: { access_token: validToken() } });
await Promise.all(inFlight);
// Three callers, one round trip — a page load can easily 401 several times at once, and each
// retrying separately would stampede the endpoint and race over the cookie.
expect(axiosMock.post).toHaveBeenCalledTimes(1);
expect(axiosMock.post).toHaveBeenCalledWith("/api/auth/refresh", null, { suppressAlert: true });
});
test("allows a new request once the previous one settles", async () => {
const auth = useAuthBackend();
auth.setToken(validToken());
axiosMock.post.mockResolvedValue({ data: { access_token: validToken() } });
await auth.refresh();
await auth.refresh();
expect(axiosMock.post).toHaveBeenCalledTimes(2);
});
test("releases the lock after a failure, so the session can still recover", async () => {
const auth = useAuthBackend();
auth.setToken(validToken());
axiosMock.post.mockRejectedValue(new Error("network down"));
await expect(auth.refresh()).rejects.toThrow("network down");
await expect(auth.refresh()).rejects.toThrow("network down");
// A failed refresh must not wedge the lock, or the session can never recover
expect(axiosMock.post).toHaveBeenCalledTimes(2);
});
test("adopts the new token", async () => {
const auth = useAuthBackend();
auth.setToken(validToken());
const replacement = encodeToken({ sub: "abc", rme: true, exp: Math.floor(Date.now() / 1000) + 172_800 });
axiosMock.post.mockResolvedValue({ data: { access_token: replacement } });
await auth.refresh();
expect(auth.token.value).toBe(replacement);
});
test("does not reload the session, which would re-enter the interceptor", async () => {
const auth = useAuthBackend();
auth.setToken(validToken());
axiosMock.post.mockResolvedValue({ data: { access_token: validToken() } });
await auth.refresh();
// getSession() runs on the same intercepted instance. A 401 there sends the interceptor back
// into refresh() carrying a fresh config, which the one-retry guard can't recognise, and the
// cycle starts over. Reloading the user belongs to callers who actually want fresh data.
expect(axiosMock.get).not.toHaveBeenCalled();
});
test("does nothing without a token", async () => {
const auth = useAuthBackend();
await auth.refresh();
expect(axiosMock.post).not.toHaveBeenCalled();
});
test("clears the session and redirects when the token is rejected", async () => {
const auth = useAuthBackend();
auth.setToken(validToken());
axiosMock.post.mockRejectedValue(unauthorized());
await expect(auth.refresh()).rejects.toBeDefined();
expect(auth.token.value).toBeNull();
expect(routerMock.push).toHaveBeenCalledWith("/login");
});
test("keeps the session on a network failure", async () => {
const auth = useAuthBackend();
const token = validToken();
auth.setToken(token);
axiosMock.post.mockRejectedValue(new Error("network down"));
await expect(auth.refresh()).rejects.toThrow();
// Only auth errors end a session; a blip of connectivity must not log anyone out
expect(auth.token.value).toBe(token);
expect(routerMock.push).not.toHaveBeenCalled();
});
});
describe("signIn", () => {
test("stores the token and loads the session", async () => {
const auth = useAuthBackend();
const token = validToken();
axiosMock.post.mockResolvedValue({ data: { access_token: token } });
await auth.signIn(new FormData());
expect(auth.token.value).toBe(token);
expect(axiosMock.get).toHaveBeenCalledWith("/api/users/self");
expect(auth.status.value).toBe("authenticated");
});
test("leaves the session unauthenticated when credentials are rejected", async () => {
const auth = useAuthBackend();
axiosMock.post.mockRejectedValue(unauthorized());
await expect(auth.signIn(new FormData())).rejects.toBeDefined();
expect(auth.status.value).toBe("unauthenticated");
expect(axiosMock.get).not.toHaveBeenCalled();
});
});
describe("signOut", () => {
test("clears the session even when the logout call fails", async () => {
const auth = useAuthBackend();
const token = validToken();
// The server owns this cookie now, so seed it the way a login response would
document.cookie = `${TOKEN_NAME}=${encodeURIComponent(token)}`;
auth.setToken(token);
// The token is often already dead by this point — expired, or invalidated by a password change
axiosMock.post.mockRejectedValue(unauthorized());
await auth.signOut();
expect(auth.token.value).toBeNull();
expect(readTokenCookie(TOKEN_NAME)).toBeNull();
expect(routerMock.push).toHaveBeenCalledWith("/login");
});
test("honors a callback url", async () => {
const auth = useAuthBackend();
auth.setToken(validToken());
axiosMock.post.mockResolvedValue({ data: {} });
await auth.signOut("/recipes");
expect(routerMock.push).toHaveBeenCalledWith("/recipes");
});
});
@@ -1,5 +1,5 @@
import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
import { getTokenCookieOptions } from "../use-token-cookie";
import { getTokenCookieOptions, getTokenExpiry, nextRefreshDelay, readTokenCookie } from "../use-token-cookie";
function setLocation(protocol: string) {
Object.defineProperty(window, "location", {
@@ -78,4 +78,106 @@ describe("getTokenCookieOptions", () => {
expect(options.sameSite).toBe("lax");
expect(options.partitioned).toBe(false);
});
test("carries no max-age, since the server owns the cookie's lifetime", () => {
stubNuxtApp(true);
setLocation("https:");
expect(getTokenCookieOptions()).not.toHaveProperty("maxAge");
});
});
function encodeToken(payload: Record<string, unknown>): string {
const body = btoa(JSON.stringify(payload)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
return `header.${body}.signature`;
}
describe("getTokenExpiry", () => {
test("reads exp as epoch milliseconds", () => {
const exp = Math.floor(Date.now() / 1000) + 3600;
expect(getTokenExpiry(encodeToken({ sub: "abc", exp }))).toBe(exp * 1000);
});
test("handles payloads whose base64url length needs padding", () => {
// "rme" toggles the payload length, so between them these cover the padded and unpadded cases
expect(getTokenExpiry(encodeToken({ exp: 1, rme: true }))).toBe(1000);
expect(getTokenExpiry(encodeToken({ exp: 12, rme: false }))).toBe(12000);
});
test("returns null for a token with no exp", () => {
expect(getTokenExpiry(encodeToken({ sub: "abc" }))).toBeNull();
});
test("returns null for a malformed token rather than throwing", () => {
expect(getTokenExpiry("not-a-jwt")).toBeNull();
expect(getTokenExpiry("header.@@@notbase64@@@.signature")).toBeNull();
expect(getTokenExpiry("")).toBeNull();
});
});
describe("readTokenCookie", () => {
afterEach(() => {
document.cookie = "mealie.access_token=; max-age=0";
document.cookie = "other=; max-age=0";
});
test("reads the named cookie", () => {
document.cookie = "mealie.access_token=abc123";
expect(readTokenCookie("mealie.access_token")).toBe("abc123");
});
test("does not match a different cookie whose name merely ends the same way", () => {
document.cookie = "other=nope";
expect(readTokenCookie("mealie.access_token")).toBeNull();
});
test("url-decodes the value", () => {
document.cookie = `mealie.access_token=${encodeURIComponent("a.b+c/d")}`;
expect(readTokenCookie("mealie.access_token")).toBe("a.b+c/d");
});
test("returns null when the cookie is absent", () => {
expect(readTokenCookie("mealie.access_token")).toBeNull();
});
});
const MAX_TIMEOUT_MS = 2 ** 31 - 1;
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
describe("nextRefreshDelay", () => {
test("waits 60% of the remaining life, so each refresh lands well before expiry", () => {
expect(nextRefreshDelay(10 * HOUR, 0)).toBe(6 * HOUR);
});
test("floors short delays, so a nearly-expired token can't spin the timer", () => {
// 60% of 10s is 6s, which would re-arm faster than a refresh round-trip completes
expect(nextRefreshDelay(10_000, 0)).toBe(30_000);
});
test("adds jitter on top, to spread simultaneous refreshes across tabs", () => {
const base = nextRefreshDelay(10 * HOUR, 0)!;
expect(nextRefreshDelay(10 * HOUR, 1)).toBe(base + 30_000);
expect(nextRefreshDelay(10 * HOUR, 0.5)).toBe(base + 15_000);
});
test("never exceeds the setTimeout ceiling, even at maximum jitter", () => {
// Regression: jitter used to be added *after* the clamp, so a long-lived token overflowed the
// 32-bit delay, fired immediately, refreshed, and looped. Reachable at TOKEN_TIME >= ~992h.
for (const remaining of [42 * DAY, 400 * DAY, Number.MAX_SAFE_INTEGER]) {
expect(nextRefreshDelay(remaining, 1)).toBeLessThanOrEqual(MAX_TIMEOUT_MS);
}
});
test("still schedules something for a very long-lived token", () => {
// Clamped rather than skipped: refreshing a 400-day token early is harmless and keeps it sliding
expect(nextRefreshDelay(400 * DAY, 0)).toBe(MAX_TIMEOUT_MS);
});
test("returns null once the token has expired, since there is nothing left to refresh with", () => {
expect(nextRefreshDelay(0, 0)).toBeNull();
expect(nextRefreshDelay(-1 * HOUR, 0)).toBeNull();
});
});
+176 -15
View File
@@ -1,8 +1,8 @@
import { ref, computed } from "vue";
import { ref, computed, watch } from "vue";
import type { UserOut } from "~/lib/api/types/user";
import { clearAllStores } from "~/composables/store";
import { clearComposableCaches } from "~/composables/use-clear-composable-caches";
import { getTokenCookieOptions } from "~/composables/use-token-cookie";
import { getTokenCookieOptions, getTokenExpiry, nextRefreshDelay, readTokenCookie } from "~/composables/use-token-cookie";
interface AuthData {
value: UserOut | null;
@@ -21,11 +21,27 @@ interface AuthState {
refresh: () => Promise<void>;
getSession: () => Promise<void>;
setToken: (token: string | null) => void;
/** Hydrates the token from the cookie and starts the refresh loop. Called once, by the auth plugin. */
initTokenRefresh: () => void;
}
/** Retry a refresh that failed for reasons other than auth (offline, server hiccup). */
const REFRESH_RETRY_DELAY_MS = 60_000;
/** Cap those retries, so a persistent server error doesn't become a poll for the life of the tab. */
const MAX_REFRESH_RETRIES = 5;
const authUser = ref<UserOut | null>(null);
const authStatus = ref<"loading" | "authenticated" | "unauthenticated">("loading");
// The cookie persists the token; this ref is the reactive view of it. Keeping a plain ref as the
// source of truth means writes are visible synchronously, which the cookie ref can't guarantee — it
// propagates between tabs over a BroadcastChannel, and those messages arrive a tick later.
const accessToken = ref<string | null>(null);
let refreshTimer: ReturnType<typeof setTimeout> | null = null;
let refreshInFlight: Promise<void> | null = null;
let refreshRetries = 0;
export function resetAuth() {
authUser.value = null;
authStatus.value = "unauthenticated";
@@ -37,10 +53,55 @@ export const useAuthBackend = function (): AuthState {
const runtimeConfig = useRuntimeConfig();
const tokenName = runtimeConfig.public.AUTH_TOKEN;
const tokenCookie = useCookie(tokenName, getTokenCookieOptions());
function clearScheduledRefresh() {
if (refreshTimer) {
clearTimeout(refreshTimer);
refreshTimer = null;
}
}
/**
* Queues the next refresh from the token's own expiry.
*
* Recomputing from the remaining time (rather than a fixed interval) means this self-corrects
* after the machine sleeps or the tab is backgrounded and the timer fires late.
*/
function scheduleTokenRefresh(token: string | null) {
clearScheduledRefresh();
if (!token) {
return;
}
const expiresAt = getTokenExpiry(token);
if (expiresAt === null) {
return;
}
const delay = nextRefreshDelay(expiresAt - Date.now());
if (delay === null) {
return;
}
refreshTimer = setTimeout(() => {
refreshTimer = null;
void refreshQuietly();
}, delay);
}
function setToken(token: string | null) {
tokenCookie.value = token;
if (!token) {
accessToken.value = null;
clearScheduledRefresh();
useCookie(tokenName, getTokenCookieOptions()).value = null;
return;
}
// Only the in-memory copy is set here. The cookie arrives on the response's Set-Cookie header —
// writing it again from script would re-apply Safari's seven-day cap to a cookie the server just
// set correctly, which is the bug this whole arrangement exists to avoid.
accessToken.value = token;
scheduleTokenRefresh(token);
}
function handleAuthError(error: any, redirect = false) {
@@ -55,7 +116,7 @@ export const useAuthBackend = function (): AuthState {
}
async function getSession(): Promise<void> {
if (!tokenCookie.value) {
if (!accessToken.value) {
authUser.value = null;
authStatus.value = "unauthenticated";
return;
@@ -84,8 +145,7 @@ export const useAuthBackend = function (): AuthState {
},
});
const { access_token } = response.data;
setToken(access_token);
setToken(response.data.access_token);
await getSession();
}
catch (error) {
@@ -119,29 +179,130 @@ export const useAuthBackend = function (): AuthState {
}
}
/**
* Trades the current token for a fresh one, and nothing else.
*
* Concurrent callers share a single request — a page load can easily fire several 401s at once,
* and each one retrying separately would stampede the endpoint and race over the cookie.
*
* It used to reload the user too, which is why callers reached for it when they wanted fresh
* session data. That request goes through the same intercepted axios instance, so a 401 on it sent
* the interceptor straight back into refresh() and restarted the cycle. Reloading the user is
* getSession's job.
*/
async function refresh(): Promise<void> {
if (!tokenCookie.value) return;
// The cookie is the real credential — the interceptor gates on it, and it is populated before
// initTokenRefresh() hydrates the ref. Gating only on the ref would make refresh a silent no-op
// during boot, turning a recoverable 401 into a logout.
if (!accessToken.value && !readTokenCookie(tokenName)) return;
if (refreshInFlight) return refreshInFlight;
refreshInFlight = (async () => {
try {
const response = await $axios.post("/api/auth/refresh", null, { suppressAlert: true });
setToken(response.data.access_token);
}
catch (error: any) {
handleAuthError(error, true);
throw error;
}
finally {
refreshInFlight = null;
}
})();
return refreshInFlight;
}
/** A background refresh, where there is no caller to surface a failure to. */
async function refreshQuietly(): Promise<void> {
try {
const response = await $axios.get("/api/auth/refresh");
const { access_token } = response.data;
setToken(access_token);
await getSession();
await refresh();
refreshRetries = 0;
}
catch (error: any) {
handleAuthError(error, true);
throw error;
// A 401 has already cleared the session and redirected. Anything else — offline, a restarting
// backend — is transient, so try again rather than letting the session lapse over a blip.
if (error?.response?.status === 401 || !accessToken.value) {
return;
}
if (refreshRetries >= MAX_REFRESH_RETRIES) {
return;
}
// Backing off, because a 500 that isn't going away shouldn't be retried at the same rate as a
// dropped connection. Attempts stop well before the token would have expired anyway.
refreshRetries += 1;
clearScheduledRefresh();
refreshTimer = setTimeout(() => {
refreshTimer = null;
void refreshQuietly();
}, REFRESH_RETRY_DELAY_MS * refreshRetries);
}
}
/**
* Starts keeping the session alive. Called once, from the auth plugin.
*
* Timers alone aren't enough: they don't run while the device sleeps, and a laptop reopened after
* a day would otherwise come back to an expired token. Re-scheduling on focus, visibility and
* reconnect recomputes the delay against the real clock without costing a request.
*/
function initTokenRefresh() {
accessToken.value = readTokenCookie(tokenName);
// Read-only, and deliberately without a max-age: a ref carrying one starts an expiry timer that
// clears the cookie when it elapses, which would cut a 14-day remembered session down to
// TOKEN_TIME. This ref exists only to observe, never to write.
const tokenCookie = useCookie<string | null>(tokenName, { readonly: true });
// Nuxt syncs cookie refs between tabs, so this also picks up a refresh performed elsewhere and
// re-schedules against the new expiry instead of duplicating the work.
watch(tokenCookie, (value) => {
if (!value) {
// Signed out in another tab. Drop this tab's session too, instead of holding a stale token
// and a live refresh timer while still rendering as authenticated.
//
// Cleared by hand rather than through setToken(null): that writes the cookie, which
// broadcasts, which lands back here — a loop between tabs.
accessToken.value = null;
clearScheduledRefresh();
resetAuth();
return;
}
if (value !== accessToken.value) {
accessToken.value = value;
scheduleTokenRefresh(value);
}
});
const reschedule = () => {
// The user is back, so give a session that exhausted its retries another chance
refreshRetries = 0;
scheduleTokenRefresh(accessToken.value);
};
window.addEventListener("focus", reschedule);
window.addEventListener("online", reschedule);
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
reschedule();
}
});
scheduleTokenRefresh(accessToken.value);
}
return {
data: computed(() => authUser.value),
status: computed(() => authStatus.value),
token: computed(() => tokenCookie.value),
token: computed(() => accessToken.value),
signIn,
signOut,
refresh,
getSession,
setToken,
initTokenRefresh,
};
};
+1 -1
View File
@@ -50,7 +50,7 @@ export const useMealieAuth = function () {
token: auth.token,
signIn: auth.signIn,
signOut: auth.signOut,
refresh: auth.refresh,
getSession: auth.getSession,
oauthSignIn,
};
};
+90 -1
View File
@@ -1,3 +1,10 @@
/**
* Cookie options used to clear the session token.
*
* The server sets the cookie; the client only ever removes it, on logout or a dead session. A cookie
* is matched for removal by name and path, but these have to line up with what the server sent for
* the embedded (partitioned, SameSite=None) case to clear reliably.
*/
export function getTokenCookieOptions() {
const { $appInfo } = useNuxtApp();
@@ -5,9 +12,91 @@ export function getTokenCookieOptions() {
const isEmbedded = isSecureConnection && window?.self !== window?.top;
return {
maxAge: $appInfo.tokenTime * 60 * 60,
secure: isSecureConnection,
sameSite: (isEmbedded ? "none" : "lax") as "none" | "lax",
partitioned: isEmbedded,
};
}
/**
* Reads a JWT's claims without verifying its signature.
*
* Only used for claims the server itself put there and the client needs to act on locally — when to
* refresh, and whether to persist the cookie. Nothing is trusted for authorization.
*/
function decodeTokenPayload(token: string): Record<string, unknown> | null {
const payload = token.split(".")[1];
if (!payload) {
return null;
}
try {
const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
const padded = base64 + "=".repeat((4 - (base64.length % 4)) % 4);
const claims = JSON.parse(atob(padded));
return typeof claims === "object" && claims !== null ? claims : null;
}
catch {
return null;
}
}
/** Epoch milliseconds at which a token expires, or null when it carries no readable `exp`. */
export function getTokenExpiry(token: string): number | null {
const exp = decodeTokenPayload(token)?.exp;
return typeof exp === "number" ? exp * 1000 : null;
}
/**
* Reads the token straight out of `document.cookie`.
*
* `useCookie` would allocate a BroadcastChannel and a watcher on every call, which is wasteful on
* hot paths like the axios request interceptor that only ever need the current value.
*/
export function readTokenCookie(name: string): string | null {
if (typeof document === "undefined") {
return null;
}
const match = document.cookie.match(new RegExp(`(?:^|; )${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}=([^;]*)`));
return match?.[1] ? decodeURIComponent(match[1]) : null;
}
/** Refresh once this fraction of the token's remaining life has elapsed. */
const REFRESH_AFTER_FRACTION = 0.6;
/** Never schedule a refresh tighter than this, so a near-expired token can't spin the timer. */
const MIN_REFRESH_DELAY_MS = 30_000;
/** Spread concurrent refreshes across tabs so they don't all fire on the same millisecond. */
const REFRESH_JITTER_MS = 30_000;
/**
* setTimeout stores its delay as a 32-bit signed integer, so anything longer overflows and fires
* straight away instead of waiting. There is no constant exposed for this — `Number.MAX_SAFE_INTEGER`
* is a different limit entirely — so the ceiling is spelled out. Waiting out a token longer than
* ~24.8 days just means refreshing it early, which costs one request and keeps the session sliding.
*/
const MAX_TIMEOUT_MS = 2 ** 31 - 1;
/**
* How long to wait before refreshing a token with `remainingMs` of life left, or null when there is
* nothing worth scheduling.
*
* Derived from the time remaining rather than a fixed interval, so it self-corrects when a timer
* fires late — after the device sleeps, or while the tab was backgrounded and throttled.
*
* `jitter` is injectable so the result can be asserted; callers should leave it to `Math.random`.
*/
export function nextRefreshDelay(remainingMs: number, jitter: number = Math.random()): number | null {
if (remainingMs <= 0) {
// Already expired. Refreshing needs a token the server still accepts, so there is nothing to be
// done here — the next request's 401 sends the user to the login page.
return null;
}
// Jitter goes on before the clamp, not after: adding it to an already-clamped delay can push the
// total past the 32-bit ceiling, which overflows to "fire now" and spins into a refresh loop.
const target = Math.max(remainingMs * REFRESH_AFTER_FRACTION, MIN_REFRESH_DELAY_MS)
+ jitter * REFRESH_JITTER_MS;
return Math.min(target, MAX_TIMEOUT_MS);
}
+1
View File
@@ -153,6 +153,7 @@ export interface PrivateUser {
password: string;
loginAttemps?: number;
lockedAt?: string | null;
tokensValidAfter?: string | null;
}
export interface LongLiveTokenOut {
name: string;
@@ -148,7 +148,7 @@ function deleteUser(id: string) {
deleteUserMixin(id);
if (isUserOwnAccount.value) {
auth.refresh();
auth.getSession();
}
}
+26 -3
View File
@@ -459,18 +459,38 @@ async function updateUser() {
alert.error(i18n.t("events.something-went-wrong"));
}
else {
auth.refresh();
auth.getSession();
}
}
async function updatePassword() {
// Read before updateUser can change it: the account is still identified by its current email at
// the point we have to sign back in.
const currentEmail = auth.user.value!.email;
const newPassword = credentials.password1.value;
const { response } = await userApi.users.changePassword({
currentPassword: "MyPassword",
newPassword: credentials.password1.value,
newPassword,
});
if (!response || response.status !== 200) {
alert.error(i18n.t("events.something-went-wrong"));
return;
}
// Changing the password invalidates this session, and setup has several authenticated steps left,
// so sign straight back in rather than letting the rest of the wizard 401.
const formData = new FormData();
formData.append("username", currentEmail);
formData.append("password", newPassword);
formData.append("remember_me", "true");
try {
await auth.signIn(formData);
}
catch {
alert.error(i18n.t("events.something-went-wrong"));
}
}
@@ -571,8 +591,11 @@ async function submitCommonSettings() {
}
async function submitAll() {
// Not part of the parallel batch: changing the password invalidates the session and establishes a
// new one, and any request landing in that window would 401 and bounce the admin out of setup.
await submitRegistration();
const tasks = [
submitRegistration(),
submitCommonSettings(),
groupActions.updateAIProviderSettings(),
];
+6 -1
View File
@@ -247,7 +247,12 @@ useSeoMeta({
const form = reactive({
email: "",
password: "",
remember: false,
// Defaults on: this is a self-hosted app people mostly reach from their own devices, and an
// unticked box now ends the session when the browser closes.
// Ideally this is off by default, but we've trained users for years to ignore this checkbox,
// so turning it off would cause a headache for the majority of users.
// Maybe we can revisit this in the future.
remember: true,
});
useAsyncData(useAsyncKey(), async () => {
@@ -140,7 +140,7 @@ function resetCreate() {
createdToken.value = "";
loading.value = false;
name.value = "";
auth.refresh();
auth.getSession();
}
async function createToken(name: string) {
@@ -164,7 +164,7 @@ async function createToken(name: string) {
async function deleteToken(id: number) {
const { data } = await api.users.deleteAPIToken(id);
auth.refresh();
auth.getSession();
return data;
}
</script>
+5 -3
View File
@@ -13,7 +13,7 @@
file-name="profile"
accept="image/*"
:url="`/api/users/${userCopy.id}/image`"
@uploaded="auth.refresh()"
@uploaded="auth.getSession()"
/>
</div>
</template>
@@ -286,7 +286,7 @@ async function updateUser() {
const { response } = await api.users.updateOne(userData.id, updatePayload);
if (response?.status === 200) {
auth.refresh();
auth.getSession();
}
}
@@ -300,7 +300,9 @@ async function updatePassword() {
});
if (response?.status === 200) {
console.log("Password Changed");
// The new password invalidates this session server-side, so end it here rather than letting the
// next request fail its way to the login page.
await auth.signOut();
}
}
</script>
@@ -0,0 +1,168 @@
import type { AxiosInstance, InternalAxiosRequestConfig } from "axios";
import { describe, expect, test, vi, beforeEach, afterEach } from "vitest";
const TOKEN_NAME = "mealie.access_token";
/** Rejects the way axios does, so the interceptor sees the config it needs in order to retry. */
function unauthorized(config: InternalAxiosRequestConfig) {
const error = new Error("Unauthorized") as Error & Record<string, unknown>;
error.config = config;
error.response = { status: 401, data: {}, config, headers: {}, statusText: "Unauthorized" };
error.isAxiosError = true;
return Promise.reject(error);
}
function ok(config: InternalAxiosRequestConfig) {
return Promise.resolve({ data: { ok: true }, status: 200, statusText: "OK", headers: {}, config });
}
let refreshMock: ReturnType<typeof vi.fn>;
let setTokenMock: ReturnType<typeof vi.fn>;
async function buildClient(adapter: (config: InternalAxiosRequestConfig) => Promise<unknown>) {
vi.resetModules();
const plugin = (await import("../axios")).default as unknown as (nuxtApp: {
runWithContext: <T>(fn: () => T) => T;
}) => { provide: { axios: AxiosInstance } };
const { provide } = plugin({ runWithContext: fn => fn() });
provide.axios.defaults.adapter = adapter as never;
return provide.axios;
}
beforeEach(() => {
document.cookie = `${TOKEN_NAME}=a.valid.token`;
refreshMock = vi.fn().mockResolvedValue(undefined);
setTokenMock = vi.fn();
vi.stubGlobal("defineNuxtPlugin", (fn: unknown) => fn);
vi.stubGlobal("useRuntimeConfig", () => ({ public: { AUTH_TOKEN: TOKEN_NAME } }));
vi.stubGlobal("useAuthBackend", () => ({ refresh: refreshMock, setToken: setTokenMock }));
// jsdom refuses real navigation, and the interceptor assigns to location.href on a dead session
Object.defineProperty(window, "location", {
value: { pathname: "/g/home/r/soup", search: "", href: "" },
writable: true,
configurable: true,
});
});
afterEach(() => {
document.cookie = `${TOKEN_NAME}=; max-age=0`;
vi.unstubAllGlobals();
});
describe("401 handling", () => {
test("refreshes and replays the original request", async () => {
const calls: string[] = [];
const client = await buildClient(async (config) => {
calls.push(config.url!);
return calls.length === 1 ? unauthorized(config) : ok(config);
});
const response = await client.get("/api/recipes");
// The whole point: an expiry mid-edit resolves itself instead of throwing the user at /login
expect(refreshMock).toHaveBeenCalledTimes(1);
expect(calls).toEqual(["/api/recipes", "/api/recipes"]);
expect(response.status).toBe(200);
expect(window.location.href).toBe("");
});
test("sends the replay with the refreshed token", async () => {
const sent: (string | undefined)[] = [];
refreshMock.mockImplementation(async () => {
document.cookie = `${TOKEN_NAME}=a.fresh.token`;
});
const client = await buildClient(async (config) => {
sent.push(config.headers.Authorization as string | undefined);
return sent.length === 1 ? unauthorized(config) : ok(config);
});
await client.get("/api/recipes");
expect(sent).toEqual(["Bearer a.valid.token", "Bearer a.fresh.token"]);
});
test("gives up after one retry rather than looping", async () => {
const client = await buildClient(async config => unauthorized(config));
await expect(client.get("/api/recipes")).rejects.toBeDefined();
expect(refreshMock).toHaveBeenCalledTimes(1);
});
test("logs out when the refresh itself fails", async () => {
refreshMock.mockRejectedValue(new Error("session is over"));
const client = await buildClient(async config => unauthorized(config));
await expect(client.get("/api/recipes")).rejects.toBeDefined();
expect(setTokenMock).toHaveBeenCalledWith(null);
expect(window.location.href).toBe("/login?redirect=%2Fg%2Fhome%2Fr%2Fsoup");
});
test.each([
["/api/auth/token", "a failed login"],
["/api/auth/refresh", "the refresh endpoint itself"],
])("never refreshes on %s", async (url) => {
const client = await buildClient(async config => unauthorized(config));
await expect(client.post(url)).rejects.toBeDefined();
expect(refreshMock).not.toHaveBeenCalled();
});
test("does not redirect when the logout call is the thing that 401s", async () => {
const client = await buildClient(async config => unauthorized(config));
await expect(client.post("/api/auth/logout")).rejects.toBeDefined();
// signOut does its own SPA redirect. Reloading the page over it would also wipe the toast the
// preceding request raised, which is how "password updated" used to vanish.
expect(window.location.href).toBe("");
expect(refreshMock).not.toHaveBeenCalled();
});
test("leaves anonymous callers alone", async () => {
document.cookie = `${TOKEN_NAME}=; max-age=0`;
const client = await buildClient(async config => unauthorized(config));
await expect(client.get("/api/recipes")).rejects.toBeDefined();
// No token means this is probably just an unauthenticated visitor hitting a guarded route
expect(refreshMock).not.toHaveBeenCalled();
expect(window.location.href).toBe("");
});
});
describe("request headers", () => {
test("attaches the token as a bearer header", async () => {
let seen: string | undefined;
const client = await buildClient(async (config) => {
seen = config.headers.Authorization as string | undefined;
return ok(config);
});
await client.get("/api/recipes");
expect(seen).toBe("Bearer a.valid.token");
});
test("flags embedded deployments, which the server cannot detect", async () => {
let seen: unknown;
const client = await buildClient(async (config) => {
seen = config.headers["X-Mealie-Embedded"];
return ok(config);
});
const top = window.top;
Object.defineProperty(window, "top", { value: {}, configurable: true });
await client.get("/api/recipes");
Object.defineProperty(window, "top", { value: top, configurable: true });
expect(seen).toBe("true");
});
});
+72 -15
View File
@@ -1,6 +1,7 @@
import axios from "axios";
import type { InternalAxiosRequestConfig } from "axios";
import { alert } from "~/composables/use-toast";
import { getTokenCookieOptions } from "~/composables/use-token-cookie";
import { readTokenCookie } from "~/composables/use-token-cookie";
import { isSafeRedirectTarget } from "~/lib/validators/redirect";
declare module "axios" {
@@ -9,7 +10,12 @@ declare module "axios" {
}
}
export default defineNuxtPlugin(() => {
/** Requests that must never trigger a refresh, or a failed login would retry itself forever. */
const NO_REFRESH_PATHS = ["/api/auth/token", "/api/auth/refresh", "/api/auth/logout"];
type RetriableConfig = InternalAxiosRequestConfig & { _retriedAfterRefresh?: boolean };
export default defineNuxtPlugin((nuxtApp) => {
const tokenName = useRuntimeConfig().public.AUTH_TOKEN;
const axiosInstance = axios.create({
// timeout removed to allow backend to handle timeouts
@@ -19,10 +25,15 @@ export default defineNuxtPlugin(() => {
axiosInstance.interceptors.request.use(
(config) => {
const token = useCookie(tokenName).value;
const token = readTokenCookie(tokenName);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// The server writes the session cookie now, but can't tell it's being framed — and an embedded
// deployment needs SameSite=None and a partitioned cookie. So the client flags it.
if (window.self !== window.top) {
config.headers["X-Mealie-Embedded"] = "true";
}
return config;
},
(error) => {
@@ -30,30 +41,76 @@ export default defineNuxtPlugin(() => {
},
);
function logOutAndRedirect() {
// Disable beforeunload warnings to prevent "Are you sure you want to leave?" popups
window.onbeforeunload = null;
const target = window.location.pathname + window.location.search;
const redirect = isSafeRedirectTarget(target) && target !== "/login" ? `?redirect=${encodeURIComponent(target)}` : "";
window.location.href = `/login${redirect}`;
}
// Add response interceptor
axiosInstance.interceptors.response.use(
(response) => {
if (response?.data?.message && !response.config?.suppressAlert) alert.info(response.data.message as string);
return response;
},
(error) => {
async (error) => {
const config = error?.config as RetriableConfig | undefined;
// A 401 usually just means the token aged out mid-session. Trade it for a fresh one and replay
// the request, so an expiry doesn't interrupt whatever the user was in the middle of. Only one
// attempt per request, and concurrent 401s share a single refresh.
if (
error?.response?.status === 401
&& config
&& !config._retriedAfterRefresh
&& !NO_REFRESH_PATHS.some(path => config.url?.startsWith(path))
&& readTokenCookie(tokenName)
) {
config._retriedAfterRefresh = true;
let refreshed = true;
try {
await nuxtApp.runWithContext(() => useAuthBackend().refresh());
}
catch {
// Refresh failed, so the session really is over. Fall through to the logout path.
refreshed = false;
}
if (refreshed) {
try {
return await axiosInstance(config);
}
catch (retryError: any) {
// The replay carried a good token, so anything other than a second 401 is the request's
// own problem — a 500, a dropped connection — and has to surface as itself. Treating it
// as a dead session would log the user out over an unrelated server error.
if (retryError?.response?.status !== 401) {
return Promise.reject(retryError);
}
}
}
}
if (error?.response?.data?.detail?.message) {
alert.error(error.response.data.detail.message as string);
};
// A 401 from the logout call itself only means the token was already dead — expired, or
// invalidated by a password change. We're on our way out regardless, so let signOut finish with
// its own SPA redirect instead of reloading the page over it. The reload would also wipe any
// toast the preceding request raised, which is how "password updated" used to vanish.
const isLoggingOut = config?.url?.startsWith("/api/auth/logout") ?? false;
// If we receive a 401 Unauthorized response, clear the token cookie and redirect to login
if (error?.response?.status === 401) {
if (error?.response?.status === 401 && !isLoggingOut) {
// If tokenCookie is not set, we may just be an unauthenticated user using the wrong API, so don't redirect
const tokenCookie = useCookie(tokenName, getTokenCookieOptions());
if (tokenCookie.value) {
tokenCookie.value = null;
// Disable beforeunload warnings to prevent "Are you sure you want to leave?" popups
window.onbeforeunload = null;
const target = window.location.pathname + window.location.search;
const redirect = isSafeRedirectTarget(target) && target !== "/login" ? `?redirect=${encodeURIComponent(target)}` : "";
window.location.href = `/login${redirect}`;
if (readTokenCookie(tokenName)) {
nuxtApp.runWithContext(() => useAuthBackend().setToken(null));
logOutAndRedirect();
}
}
+3
View File
@@ -3,6 +3,9 @@ export default defineNuxtPlugin({
const auth = useAuthBackend();
console.debug("Initializing auth plugin");
// Must come first: it hydrates the token from the cookie, which getSession checks before it
// will bother asking the server who we are.
auth.initTokenRefresh();
await auth.getSession();
console.debug("Auth plugin initialized");
},
@@ -0,0 +1,34 @@
"""add tokens valid after column to users
Revision ID: 69e942bab3aa
Revises: 2187537c52b8
Create Date: 2026-08-24 16:31:43.499467
"""
import sqlalchemy as sa
from alembic import op
import mealie.db.migration_types
# revision identifiers, used by Alembic.
revision = "69e942bab3aa"
down_revision: str | None = "2187537c52b8"
branch_labels: str | tuple[str, ...] | None = None
depends_on: str | tuple[str, ...] | None = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.add_column(sa.Column("tokens_valid_after", mealie.db.migration_types.NaiveDateTime(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table("users", schema=None) as batch_op:
batch_op.drop_column("tokens_valid_after")
# ### end Alembic commands ###
+33 -14
View File
@@ -14,6 +14,7 @@ from sqlalchemy.orm.session import Session
from mealie.core import root_logger
from mealie.core.config import get_app_dirs, get_app_settings
from mealie.core.security.tokens import ALGORITHM
from mealie.db.db_setup import generate_session
from mealie.repos.all_repositories import get_repositories
from mealie.schema.user import PrivateUser, TokenData
@@ -21,7 +22,6 @@ from mealie.schema.user.user import DEFAULT_INTEGRATION_ID, GroupInDB
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/token")
oauth2_scheme_soft_fail = OAuth2PasswordBearer(tokenUrl="/api/auth/token", auto_error=False)
ALGORITHM = "HS256"
app_dirs = get_app_dirs()
settings = get_app_settings()
logger = root_logger.get_logger("dependencies")
@@ -74,28 +74,36 @@ async def get_public_group(group_slug: str = fastapi.Path(...), session=Depends(
return group
async def try_get_current_user(
async def get_auth_token(
request: Request,
token: str = Depends(oauth2_scheme_soft_fail),
token: str | None = Depends(oauth2_scheme_soft_fail),
) -> str:
"""The raw bearer token for this request, from the Authorization header or the session cookie.
FastAPI caches dependency results per request, so routes that need the token itself as well as
the user it resolves to share a single extraction.
"""
if token is None and "mealie.access_token" in request.cookies:
# Try extract from cookie
return request.cookies.get("mealie.access_token", "")
return token or ""
async def try_get_current_user(
token: str = Depends(get_auth_token),
session=Depends(generate_session),
) -> PrivateUser | None:
try:
return await get_current_user(request, token, session)
return await get_current_user(token, session)
except Exception:
return None
async def get_current_user(
request: Request,
token: str | None = Depends(oauth2_scheme_soft_fail),
token: str = Depends(get_auth_token),
session=Depends(generate_session),
) -> PrivateUser:
if token is None and "mealie.access_token" in request.cookies:
# Try extract from cookie
token = request.cookies.get("mealie.access_token", "")
else:
token = token or ""
try:
payload = jwt.decode(token, settings.SECRET, algorithms=[ALGORITHM])
user_id: str | None = payload.get("sub")
@@ -120,6 +128,14 @@ async def get_current_user(
session.commit()
if user is None:
raise credentials_exception
# A password change invalidates everything issued before it. Tokens minted before `iat` existed
# carry no issue time, and since they necessarily predate any password change, they fail closed.
if user.tokens_valid_after is not None:
issued_at = payload.get("iat")
if issued_at is None or issued_at < user.tokens_valid_after.timestamp():
raise credentials_exception
return user
@@ -163,8 +179,11 @@ def validate_file_token(token: str | None = None) -> Path:
try:
payload = jwt.decode(token, settings.SECRET, algorithms=[ALGORITHM])
file_path = Path(payload.get("file"))
except PyJWTError as e:
# A valid signature isn't enough on its own: session and API tokens are signed with the same
# secret and decode fine here. Only tokens from create_file_token carry a path, so a missing
# or unusable claim is an invalid file token rather than a server error.
file_path = Path(payload["file"])
except (PyJWTError, KeyError, TypeError) as e:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="could not validate file token",
@@ -1,17 +1,12 @@
import abc
from datetime import UTC, datetime, timedelta
from datetime import timedelta
import jwt
from sqlalchemy.orm.session import Session
from mealie.core.config import get_app_settings
from mealie.core.security.tokens import create_access_token
from mealie.repos.all_repositories import get_repositories
from mealie.schema.user.user import PrivateUser
ALGORITHM = "HS256"
ISS = "mealie"
remember_me_duration = timedelta(days=14)
class AuthProvider[T](metaclass=abc.ABCMeta):
"""Base Authentication Provider interface"""
@@ -26,30 +21,14 @@ class AuthProvider[T](metaclass=abc.ABCMeta):
def __subclasshook__(cls, __subclass: type) -> bool:
return hasattr(__subclass, "authenticate") and callable(__subclass.authenticate)
def get_access_token(self, user: PrivateUser, remember_me=False) -> tuple[str, timedelta]:
settings = get_app_settings()
def get_access_token(self, user: PrivateUser, remember_me: bool = False) -> tuple[str, timedelta]:
"""Mints a session token for a user who has just been authenticated.
duration = timedelta(hours=settings.TOKEN_TIME)
if remember_me:
duration = max(remember_me_duration, duration)
return AuthProvider.create_access_token({"sub": str(user.id)}, duration)
@staticmethod
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> tuple[str, timedelta]:
settings = get_app_settings()
to_encode = data.copy()
expires_delta = expires_delta or timedelta(hours=settings.TOKEN_TIME)
expire = datetime.now(UTC) + expires_delta
to_encode["exp"] = expire
to_encode["iss"] = ISS
return (
jwt.encode(to_encode, settings.SECRET, algorithm=ALGORITHM),
expires_delta,
)
Every session lasts `TOKEN_TIME`. Remember-me decides whether the client keeps the token past
the end of the browser session, not how long it is valid for, so it travels on the token as
the `rme` claim for the client to act on — and survives refreshes intact.
"""
return create_access_token({"sub": str(user.id), "rme": remember_me})
def try_get_user(self, username: str) -> PrivateUser | None:
"""Try to get a user from the database, first trying username, then trying email"""
+13 -17
View File
@@ -1,8 +1,7 @@
import secrets
from datetime import UTC, datetime, timedelta
from datetime import timedelta
from pathlib import Path
import jwt
from sqlalchemy.orm.session import Session
from mealie.core import root_logger
@@ -11,9 +10,18 @@ from mealie.core.security.hasher import get_hasher
from mealie.core.security.providers.auth_provider import AuthProvider
from mealie.core.security.providers.credentials_provider import CredentialsProvider
from mealie.core.security.providers.ldap_provider import LDAPProvider
from mealie.core.security.tokens import ALGORITHM, ISS, create_access_token
from mealie.schema.user.auth import CredentialsRequest, CredentialsRequestForm
ALGORITHM = "HS256"
__all__ = [
"ALGORITHM",
"ISS",
"create_access_token",
"create_file_token",
"get_auth_provider",
"hash_password",
"url_safe_token",
]
logger = root_logger.get_logger("security")
@@ -28,21 +36,9 @@ def get_auth_provider(session: Session, data: CredentialsRequestForm) -> AuthPro
return CredentialsProvider(session, credentials_request)
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
settings = get_app_settings()
to_encode = data.copy()
expires_delta = expires_delta or timedelta(hours=settings.TOKEN_TIME)
expire = datetime.now(UTC) + expires_delta
to_encode["exp"] = expire
return jwt.encode(to_encode, settings.SECRET, algorithm=ALGORITHM)
def create_file_token(file_path: Path) -> str:
token_data = {"file": str(file_path)}
return create_access_token(token_data, expires_delta=timedelta(minutes=30))
token, _ = create_access_token({"file": str(file_path)}, timedelta(minutes=30))
return token
def hash_password(password: str) -> str:
+30
View File
@@ -0,0 +1,30 @@
from datetime import UTC, datetime, timedelta
import jwt
from mealie.core.config import get_app_settings
ALGORITHM = "HS256"
ISS = "mealie"
def create_access_token(
data: dict,
expires_delta: timedelta | None = None,
) -> tuple[str, timedelta]:
"""Signs a JWT, returning it alongside the lifetime it was granted.
Callers need the lifetime to tell the client when to refresh, so it is returned rather than left
for the client to recover by decoding the token itself.
"""
settings = get_app_settings()
expires_delta = expires_delta or timedelta(hours=settings.TOKEN_TIME)
issued_at = datetime.now(UTC)
to_encode = data.copy()
to_encode["iss"] = ISS
to_encode["iat"] = issued_at
to_encode["exp"] = issued_at + expires_delta
return jwt.encode(to_encode, settings.SECRET, algorithm=ALGORITHM), expires_delta
+12 -1
View File
@@ -1,5 +1,5 @@
import enum
from datetime import datetime
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Optional
from pydantic import ConfigDict
@@ -70,6 +70,9 @@ class User(SqlAlchemyBase, BaseMixins):
cache_key: Mapped[str | None] = mapped_column(String, default="1234")
login_attemps: Mapped[int | None] = mapped_column(Integer, default=0)
locked_at: Mapped[datetime | None] = mapped_column(NaiveDateTime, default=None)
tokens_valid_after: Mapped[datetime | None] = mapped_column(NaiveDateTime, default=None)
"""Tokens issued before this are rejected. Set when the password changes, so that changing it
actually evicts whoever was already signed in."""
# Announcements
show_announcements: Mapped[bool] = mapped_column(Boolean, default=True)
@@ -203,6 +206,14 @@ class User(SqlAlchemyBase, BaseMixins):
def update_password(self, password):
self.password = password
# Changing a password is how people evict someone who got into their account, so every token
# issued before now stops working. Stamped here rather than at the call sites so the password
# reset flow can't forget it.
#
# Floored to the second because JWT `iat` is whole seconds: against a sub-second watermark, a
# token minted in the same second as the change would have a lower `iat` and be rejected,
# locking the user out until the clock ticked over.
self.tokens_valid_after = datetime.now(UTC).replace(microsecond=0)
def _set_permissions(
self, admin, can_manage_household=False, can_manage=False, can_invite=False, can_organize=False, **_
+127 -18
View File
@@ -1,15 +1,18 @@
from datetime import timedelta
from typing import Annotated, Any
import jwt
from fastapi import APIRouter, Depends, Header, Request, Response, status
from fastapi.exceptions import HTTPException
from fastapi.responses import RedirectResponse
from jwt.exceptions import PyJWTError
from pydantic import BaseModel
from sqlalchemy.orm.session import Session
from starlette.datastructures import URLPath
from mealie.core import root_logger, security
from mealie.core.config import get_app_settings
from mealie.core.dependencies import get_current_user
from mealie.core.dependencies import get_auth_token, get_current_user
from mealie.core.exceptions import MissingClaimException, UserLockedOut
from mealie.core.security.security import get_auth_provider
from mealie.db.db_setup import generate_session
@@ -53,17 +56,88 @@ if settings.OIDC_READY:
)
SESSION_COOKIE_NAME = "mealie.access_token"
def request_is_https(request: Request) -> bool:
"""Whether the browser reached Mealie over HTTPS.
`request.url.scheme` only reflects the browser's own connection when uvicorn's proxy-header
handling trusted the proxy, which it stops doing as soon as an admin narrows `HOST_IP` from its
default. Falling back to the header keeps `Secure` — and with it the embedded `SameSite=None`
path — working behind a proxy Mealie hasn't been told to trust.
Reading it unverified is safe here in a way it wouldn't be for authorization: it only alters
attributes on the sender's own cookie in the same response, so forging it achieves nothing beyond
breaking your own session.
"""
if request.url.scheme == "https":
return True
forwarded_proto = request.headers.get("x-forwarded-proto", "")
# a chain of proxies appends to this, and the client's own protocol is the first entry
return forwarded_proto.split(",")[0].strip().lower() == "https"
def session_cookie_attrs(request: Request) -> dict:
"""Cookie attributes that have to match between setting and clearing the session cookie.
Mealie is sometimes embedded in another site, which needs `SameSite=None` and a partitioned
cookie. The server can't detect embedding, so the client flags it — and we only honour the flag
over HTTPS, since browsers reject `SameSite=None` without `Secure`.
"""
secure = request_is_https(request)
embedded = secure and request.headers.get("x-mealie-embedded", "").lower() == "true"
return {
"path": "/",
"secure": secure,
"samesite": "none" if embedded else "lax",
"partitioned": embedded,
}
def set_session_cookie(response: Response, request: Request, token: str, expires_in: timedelta, remember_me: bool):
"""Sends the session cookie from the server instead of letting the client write it.
Safari caps any cookie created through `document.cookie` at seven days, whatever max-age it asks
for, which silently truncated every iOS session regardless of TOKEN_TIME. Cookies that arrive on
a Set-Cookie header aren't subject to that cap.
"""
response.set_cookie(
SESSION_COOKIE_NAME,
token,
# Remember-me decides whether the cookie outlives the browser session. Omitting max-age makes
# it a session cookie; the token is valid for TOKEN_TIME either way.
max_age=int(expires_in.total_seconds()) if remember_me else None,
# The SPA reads this to set its Authorization header, so it can't be HttpOnly yet.
httponly=False,
**session_cookie_attrs(request),
)
class MealieAuthToken(BaseModel):
access_token: str
token_type: str = "bearer"
expires_in: int
"""seconds until the token expires, so clients can refresh before it does"""
@classmethod
def respond(cls, token: str, token_type: str = "bearer") -> dict:
return cls(access_token=token, token_type=token_type).model_dump()
def respond(cls, token: str, expires_in: timedelta, token_type: str = "bearer") -> dict:
return cls(
access_token=token,
token_type=token_type,
expires_in=int(expires_in.total_seconds()),
).model_dump()
@public_router.post("/token")
def get_token(request: Request, data: CredentialsRequestForm = Depends(), session: Session = Depends(generate_session)):
def get_token(
request: Request,
response: Response,
data: CredentialsRequestForm = Depends(),
session: Session = Depends(generate_session),
):
if "x-forwarded-for" in request.headers:
ip = request.headers["x-forwarded-for"]
if "," in ip: # if there are multiple IPs, the first one is canonically the true client
@@ -85,8 +159,9 @@ def get_token(request: Request, data: CredentialsRequestForm = Depends(), sessio
status_code=status.HTTP_401_UNAUTHORIZED,
)
access_token, _ = auth
return MealieAuthToken.respond(access_token)
access_token, duration = auth
set_session_cookie(response, request, access_token, duration, data.remember_me)
return MealieAuthToken.respond(access_token, duration)
@public_router.get("/oauth")
@@ -114,7 +189,7 @@ async def oauth_login(request: Request):
@public_router.get("/oauth/callback")
async def oauth_callback(request: Request, session: Session = Depends(generate_session)):
async def oauth_callback(request: Request, response: Response, session: Session = Depends(generate_session)):
if not oauth:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
@@ -143,8 +218,9 @@ async def oauth_callback(request: Request, session: Session = Depends(generate_s
if not auth:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
access_token, _ = auth
return MealieAuthToken.respond(access_token)
access_token, duration = auth
set_session_cookie(response, request, access_token, duration, settings.OIDC_REMEMBER_ME)
return MealieAuthToken.respond(access_token, duration)
@public_router.get("/oauth/native/config", response_model=OIDCNativeConfig)
@@ -166,7 +242,12 @@ async def oauth_native_config():
@public_router.post("/oauth/native/token")
async def oauth_native_token(data: NativeOIDCTokenRequest, session: Session = Depends(generate_session)):
async def oauth_native_token(
request: Request,
response: Response,
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
@@ -212,23 +293,51 @@ async def oauth_native_token(data: NativeOIDCTokenRequest, session: Session = De
if not auth:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
access_token, _ = auth
return MealieAuthToken.respond(access_token)
access_token, duration = auth
set_session_cookie(response, request, access_token, duration, settings.OIDC_REMEMBER_ME)
return MealieAuthToken.respond(access_token, duration)
@user_router.get("/refresh")
async def refresh_token(current_user: PrivateUser = Depends(get_current_user)):
"""Use a valid token to get another token"""
access_token = security.create_access_token(data={"sub": str(current_user.id)})
return MealieAuthToken.respond(access_token)
@user_router.post("/refresh")
async def refresh_token(
request: Request,
response: Response,
current_user: PrivateUser = Depends(get_current_user),
token: str = Depends(get_auth_token),
):
"""Exchange a valid session token for a fresh one.
The new token carries over the remember-me choice recorded on the old one, so refreshing doesn't
downgrade a remembered session to one that dies with the browser.
"""
try:
payload = jwt.decode(token, settings.SECRET, algorithms=[security.ALGORITHM])
except PyJWTError as e:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) from e
if payload.get("long_token"):
# A long-lived API token is revocable by its owner; exchanging one for a session token would
# produce a credential that survives that revocation.
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="API tokens cannot be exchanged for a session token",
)
remember_me = bool(payload.get("rme", False))
access_token, duration = security.create_access_token({"sub": str(current_user.id), "rme": remember_me})
set_session_cookie(response, request, access_token, duration, remember_me)
return MealieAuthToken.respond(access_token, duration)
@user_router.post("/logout")
async def logout(
request: Request,
response: Response,
accept_language: Annotated[str | None, Header()] = None,
):
response.delete_cookie("mealie.access_token")
# Clearing a cookie only works when the attributes match the ones it was set with, which the old
# bare delete_cookie() call didn't manage for embedded (partitioned, SameSite=None) deployments.
response.set_cookie(SESSION_COOKIE_NAME, "", max_age=0, expires=0, **session_cookie_attrs(request))
translator = get_locale_provider(accept_language)
return {"message": translator.t("notifications.logged-out")}
+4 -2
View File
@@ -33,7 +33,7 @@ class UserApiTokensController(BaseUserController):
}
five_years = timedelta(1825)
token = create_access_token(token_data, five_years)
token, _ = create_access_token(token_data, five_years)
token_model = CreateToken(
name=token_params.name,
@@ -54,7 +54,9 @@ class UserApiTokensController(BaseUserController):
if not token:
raise HTTPException(status.HTTP_404_NOT_FOUND, f"Could not locate token with id '{token_id}' in database")
if token.user.email == self.user.email:
# Ownership is by user id. Comparing emails happened to work since they're unique, but it
# keys authorization on a mutable field and loads the user relationship to do it.
if token.user_id == self.user.id:
deleted_token = self.repos.api_tokens.delete(token_id)
return DeleteTokenResponse(token_delete=deleted_token.name)
else:
+1
View File
@@ -209,6 +209,7 @@ class PrivateUser(UserOut):
password: str
login_attemps: int = 0
locked_at: datetime | None = None
tokens_valid_after: datetime | None = None
model_config = ConfigDict(from_attributes=True)
@field_validator("login_attemps", mode="before")
+14 -1
View File
@@ -56,7 +56,20 @@ class AlchemyExporter(BaseService):
engine: base.Engine
meta: MetaData
look_for_datetime = {"created_at", "update_at", "date_updated", "timestamp", "expires_at", "locked_at", "last_made"}
look_for_datetime = {
"created_at",
"update_at",
"date_updated",
"timestamp",
"expires_at",
"locked_at",
"last_made",
"completed_date",
"tokens_valid_after",
}
"""Column names restored back into datetimes. Anything stored as a `NaiveDateTime` and missing
here comes back from a backup as a string; `test_every_datetime_column_survives_a_backup` guards
against forgetting to add one."""
look_for_date = {"date_added", "date"}
look_for_time = {"scheduled_time"}
+17
View File
@@ -53,6 +53,23 @@ def api_client():
settings.DB_PROVIDER.db_path.unlink() # Handle SQLite Provider
@fixture(autouse=True)
def isolate_session_cookies(api_client: TestClient):
"""Stops one test's login from authenticating the next test's requests.
`api_client` is session-scoped, and the server sets a session cookie on every login, so its jar
accumulates real credentials as the suite runs. Without this, a request that deliberately sends
no Authorization header is still authenticated by whoever logged in last — which silently turns
an anonymous-access test into an authenticated one and hides the very thing it was checking.
Fixtures that log in during setup are higher-scoped, so their cookies are cleared here too. That
is safe: every fixture hands back an Authorization header, never a cookie.
"""
api_client.cookies.clear()
yield
api_client.cookies.clear()
@fixture(scope="session")
def test_image_jpg():
return test_data.images_test_image_1
@@ -4,6 +4,7 @@ from fastapi.testclient import TestClient
from pytest import fixture
from tests.utils import api_routes
from tests.utils.fixture_schemas import TestUser
@fixture
@@ -50,3 +51,21 @@ def test_delete_token(api_client: TestClient, admin_token):
response = api_client.delete(api_routes.users_api_tokens_token_id(2), headers=admin_token)
assert response.status_code == 200
def test_delete_token_denies_other_users(api_client: TestClient, unique_user: TestUser, unique_admin: TestUser):
"""Another user's token isn't yours to revoke, even when you share a group.
Both users have to be in one group: repositories are group-scoped, so a token belonging to an
outsider 404s on lookup and never reaches the ownership check at all.
"""
response = api_client.post(api_routes.users_api_tokens, json={"name": "Not Yours"}, headers=unique_admin.token)
assert response.status_code == 201
token_id = response.json()["id"]
response = api_client.delete(api_routes.users_api_tokens_token_id(token_id), headers=unique_user.token)
assert response.status_code == 403
# still there, and still the owner's to delete
response = api_client.delete(api_routes.users_api_tokens_token_id(token_id), headers=unique_admin.token)
assert response.status_code == 200
@@ -1,15 +1,43 @@
import os
import time
import jwt
import pytest
from fastapi.testclient import TestClient
from mealie.core.config import get_app_settings
from mealie.core.security import ALGORITHM
from mealie.services.user_services.user_service import UserService
from tests.utils import api_routes
from tests.utils.factories import random_string
from tests.utils.fixture_schemas import TestUser
def decode_token(token: str) -> dict:
return jwt.decode(token, get_app_settings().SECRET, algorithms=[ALGORITHM])
def auth_header(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def log_in_for_token(api_client: TestClient, user: TestUser, remember_me: bool = False) -> str:
"""Logs in and returns the raw token.
`utils.login` returns ready-made headers and drops the token itself, which these tests need in
order to read the claims back out of it.
"""
form_data = {
"username": user.email,
"password": user.password,
"remember_me": str(remember_me).lower(),
}
response = api_client.post(api_routes.auth_token, data=form_data)
assert response.status_code == 200
return response.json()["access_token"]
def test_failed_login(api_client: TestClient):
settings = get_app_settings()
@@ -31,11 +59,175 @@ def test_superuser_login(api_client: TestClient, admin_token):
assert response.status_code == 200
def test_user_token_refresh(api_client: TestClient, admin_user: TestUser):
response = api_client.post(api_routes.auth_refresh, headers=admin_user.token)
response = api_client.get(api_routes.users_self, headers=admin_user.token)
def test_login_response_reports_the_token_lifetime(api_client: TestClient, unique_user: TestUser):
"""Clients schedule their refresh off `expires_in`; without it they have to decode the token."""
form_data = {"username": unique_user.email, "password": unique_user.password}
response = api_client.post(api_routes.auth_token, data=form_data)
assert response.status_code == 200
body = response.json()
assert body["token_type"] == "bearer"
assert body["expires_in"] == get_app_settings().TOKEN_TIME * 60 * 60
payload = decode_token(body["access_token"])
assert payload["exp"] - payload["iat"] == body["expires_in"]
def test_remember_me_does_not_change_the_session_length(api_client: TestClient, unique_user: TestUser):
"""Remember-me decides whether the client persists the token, not how long it stays valid.
It used to widen the token's lifetime instead, which made the checkbox a no-op whenever
TOKEN_TIME was already longer than the remember-me window.
"""
remembered = decode_token(log_in_for_token(api_client, unique_user, remember_me=True))
plain = decode_token(log_in_for_token(api_client, unique_user, remember_me=False))
expected = get_app_settings().TOKEN_TIME * 60 * 60
assert remembered["exp"] - remembered["iat"] == expected
assert plain["exp"] - plain["iat"] == expected
# ...and the choice still travels on the token, for the client to act on
assert remembered["rme"] is True
assert plain["rme"] is False
@pytest.mark.parametrize("remember_me", [True, False], ids=["remembered", "not remembered"])
def test_login_sets_the_session_cookie(api_client: TestClient, unique_user: TestUser, remember_me: bool):
"""The server owns the cookie now.
Safari caps anything written through `document.cookie` at seven days regardless of max-age, so a
client-written cookie silently truncated every iOS session. Persistence still follows remember-me:
a max-age when it's ticked, a session cookie when it isn't.
"""
form_data = {
"username": unique_user.email,
"password": unique_user.password,
"remember_me": str(remember_me).lower(),
}
response = api_client.post(api_routes.auth_token, data=form_data)
assert response.status_code == 200
cookie = response.headers["set-cookie"]
assert cookie.startswith("mealie.access_token=")
assert "Path=/" in cookie
assert ("Max-Age" in cookie) is remember_me
def test_refresh_renews_the_session_cookie(api_client: TestClient, unique_user: TestUser):
"""Refreshing has to re-send the cookie, or the browser keeps serving the superseded token."""
token = log_in_for_token(api_client, unique_user, remember_me=True)
response = api_client.post(api_routes.auth_refresh, headers=auth_header(token))
assert response.status_code == 200
cookie = response.headers["set-cookie"]
assert f"mealie.access_token={response.json()['access_token']}" in cookie
assert "Max-Age" in cookie
def test_logout_clears_the_session_cookie(api_client: TestClient, unique_user: TestUser):
response = api_client.post(api_routes.auth_logout, headers=unique_user.token)
assert response.status_code == 200
cookie = response.headers["set-cookie"]
assert cookie.startswith("mealie.access_token=")
assert "Max-Age=0" in cookie
def test_user_token_refresh(api_client: TestClient, unique_user: TestUser):
response = api_client.post(api_routes.auth_refresh, headers=unique_user.token)
assert response.status_code == 200
refreshed = response.json()
assert refreshed["token_type"] == "bearer"
# clients schedule their refresh off this, so it has to be the lifetime actually granted
assert refreshed["expires_in"] == get_app_settings().TOKEN_TIME * 60 * 60
# the point of refreshing is a token that works, so check it rather than just its shape
response = api_client.get(api_routes.users_self, headers=auth_header(refreshed["access_token"]))
assert response.status_code == 200
assert response.json()["id"] == str(unique_user.user_id)
@pytest.mark.parametrize("remember_me", [True, False], ids=["remembered", "not remembered"])
def test_token_refresh_preserves_remember_me(api_client: TestClient, unique_user: TestUser, remember_me: bool):
"""A refreshed session must keep the remember-me choice, or it silently becomes a shorter one."""
token = log_in_for_token(api_client, unique_user, remember_me=remember_me)
assert decode_token(token)["rme"] is remember_me
response = api_client.post(api_routes.auth_refresh, headers=auth_header(token))
assert response.status_code == 200
assert decode_token(response.json()["access_token"])["rme"] is remember_me
def test_api_tokens_cannot_be_refreshed(api_client: TestClient, admin_token):
"""An API token is revocable; exchanging one for a session token would outlive its revocation."""
response = api_client.post(api_routes.users_api_tokens, json={"name": "Refresh Test Token"}, headers=admin_token)
assert response.status_code == 201
response = api_client.post(api_routes.auth_refresh, headers=auth_header(response.json()["token"]))
assert response.status_code == 400
def test_password_change_invalidates_sessions_but_not_api_tokens(
api_client: TestClient, unique_user_fn_scoped: TestUser
):
"""Changing a password is how you evict someone from your account, so sessions have to die.
API tokens deliberately survive: they're explicitly created and separately revocable, and killing
them would break a user's integrations every time they rotated a password. Uses the
function-scoped fixture because it leaves the user's password changed.
"""
user = unique_user_fn_scoped
session_token = log_in_for_token(api_client, user)
# JWT `iat` is whole seconds and the watermark is floored to match, so a token minted in the same
# second as the change survives it. Real sessions are hours old; this one needs a moment.
time.sleep(1)
response = api_client.post(api_routes.users_api_tokens, json={"name": "Survivor"}, headers=user.token)
assert response.status_code == 201
api_token = response.json()["token"]
assert api_client.get(api_routes.users_self, headers=auth_header(session_token)).status_code == 200
assert api_client.get(api_routes.users_self, headers=auth_header(api_token)).status_code == 200
response = api_client.put(
api_routes.users_password,
json={"currentPassword": user.password, "newPassword": random_string(15)},
headers=auth_header(session_token),
)
assert response.status_code == 200
assert api_client.get(api_routes.users_self, headers=auth_header(session_token)).status_code == 401
assert api_client.get(api_routes.users_self, headers=auth_header(api_token)).status_code == 200
def test_tokens_issued_after_a_password_change_still_work(api_client: TestClient, unique_user_fn_scoped: TestUser):
"""The watermark must not lock the user out of the account they just secured."""
user = unique_user_fn_scoped
new_password = random_string(15)
response = api_client.put(
api_routes.users_password,
json={"currentPassword": user.password, "newPassword": new_password},
headers=user.token,
)
assert response.status_code == 200
form_data = {"username": user.email, "password": new_password}
response = api_client.post(api_routes.auth_token, data=form_data)
assert response.status_code == 200
fresh = response.json()["access_token"]
assert api_client.get(api_routes.users_self, headers=auth_header(fresh)).status_code == 200
@pytest.mark.parametrize("use_token", [True, False], ids=["invalid token", "no token"])
def test_token_refresh_rejects_unauthenticated(api_client: TestClient, use_token: bool):
headers = auth_header(random_string()) if use_token else {}
response = api_client.post(api_routes.auth_refresh, headers=headers)
assert response.status_code == 401
@pytest.mark.parametrize("use_token", [True, False], ids=["with token", "without token"])
def test_get_logged_in_user_invalid_token(api_client: TestClient, use_token: bool):
@@ -0,0 +1,46 @@
import pytest
from starlette.requests import Request
from mealie.core.dependencies.dependencies import get_auth_token
def build_request(cookie: str | None = None) -> Request:
headers = [(b"cookie", cookie.encode())] if cookie else []
return Request({"type": "http", "headers": headers})
@pytest.mark.asyncio
async def test_auth_token_comes_from_the_authorization_header():
token = await get_auth_token(build_request(), "from-header")
assert token == "from-header"
@pytest.mark.asyncio
async def test_auth_token_falls_back_to_the_session_cookie():
"""Downloads and exports opened outside the SPA carry no Authorization header, only the cookie."""
token = await get_auth_token(build_request("mealie.access_token=from-cookie"), None)
assert token == "from-cookie"
@pytest.mark.asyncio
async def test_authorization_header_wins_over_the_cookie():
"""A caller who bothered to send a header meant that credential, however stale the cookie is."""
token = await get_auth_token(build_request("mealie.access_token=from-cookie"), "from-header")
assert token == "from-header"
@pytest.mark.asyncio
async def test_unrelated_cookies_are_ignored():
token = await get_auth_token(build_request("some_other_cookie=nope"), None)
assert token == ""
@pytest.mark.asyncio
async def test_no_credential_yields_an_empty_token():
token = await get_auth_token(build_request(), None)
assert token == ""
@@ -1,6 +1,8 @@
import json
from mealie.core.config import get_app_settings
from mealie.db.models._model_base import SqlAlchemyBase
from mealie.db.models._model_utils.datetime import NaiveDateTime
from mealie.services.backups_v2.alchemy_exporter import AlchemyExporter
from tests.utils.alembic_reader import alembic_versions
@@ -12,3 +14,23 @@ def test_alchemy_exporter():
assert data["alembic_version"] == alembic_versions()
assert json.dumps(data, indent=4) # Make sure data is json-serializable
def test_every_datetime_column_survives_a_backup():
"""Restores rebuild datetimes by column name, so an unregistered one comes back as a string.
The failure is silent at backup time and only shows up on restore, so this asserts the two stay
in step rather than waiting for someone to notice a broken restore.
"""
datetime_columns = {
column.name
for table in SqlAlchemyBase.metadata.tables.values()
for column in table.columns
if isinstance(column.type, NaiveDateTime)
}
unregistered = datetime_columns - AlchemyExporter.look_for_datetime
assert not unregistered, (
f"datetime columns missing from AlchemyExporter.look_for_datetime: {sorted(unregistered)}. "
"Add them, or they will restore as strings."
)
+52
View File
@@ -1,5 +1,7 @@
from datetime import timedelta
from pathlib import Path
import jwt
import ldap
import pytest
from fastapi import HTTPException
@@ -117,6 +119,42 @@ def setup_env(monkeypatch: MonkeyPatch, **kwargs):
return user, mail, name, password, query_bind, query_password
def decode_token(token: str) -> dict:
return jwt.decode(token, get_app_settings().SECRET, algorithms=[security.ALGORITHM])
def test_create_access_token_defaults_to_token_time():
settings = get_app_settings()
token, duration = security.create_access_token({"sub": "abc"})
assert duration == timedelta(hours=settings.TOKEN_TIME)
payload = decode_token(token)
assert payload["sub"] == "abc"
# the returned duration is what clients schedule against, so it must match the token's own claims
assert payload["exp"] - payload["iat"] == duration.total_seconds()
def test_create_access_token_honors_an_explicit_lifetime():
token, duration = security.create_access_token({"sub": "abc"}, timedelta(minutes=5))
assert duration == timedelta(minutes=5)
payload = decode_token(token)
assert payload["exp"] - payload["iat"] == 5 * 60
def test_every_token_is_stamped_with_issuer_and_issued_at():
"""One factory signs session, API and file tokens, so all three carry the same base claims."""
session_token, _ = security.create_access_token({"sub": "abc"})
file_token = security.create_file_token(Path(__file__))
for token in (session_token, file_token):
payload = decode_token(token)
assert payload["iss"] == security.ISS
assert payload["iat"]
def test_create_file_token():
file_path = Path(__file__).parent
file_token = security.create_file_token(file_path)
@@ -124,6 +162,20 @@ def test_create_file_token():
assert file_path == validate_file_token(file_token)
def test_validate_file_token_rejects_a_token_without_a_file_claim():
"""Session and API tokens share the signing secret, so they decode here — the claim is the check.
Previously these raised TypeError on `Path(None)`, surfacing as a 500 instead of the documented
401.
"""
session_token, _ = security.create_access_token({"sub": "abc"})
with pytest.raises(HTTPException) as exc_info:
validate_file_token(session_token)
assert exc_info.value.status_code == 401
@pytest.mark.asyncio
async def test_download_file_security_restrictions():
dirs = get_app_dirs()
+67
View File
@@ -0,0 +1,67 @@
from starlette.requests import Request
from mealie.routes.auth.auth import session_cookie_attrs
def build_request(scheme: str = "http", headers: dict[str, str] | None = None) -> Request:
return Request(
{
"type": "http",
"scheme": scheme,
"path": "/",
"raw_path": b"/",
"query_string": b"",
"server": ("testserver", 80),
"headers": [(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()],
}
)
def test_plain_http_gets_an_insecure_lax_cookie():
attrs = session_cookie_attrs(build_request())
assert attrs["secure"] is False
assert attrs["samesite"] == "lax"
assert attrs["partitioned"] is False
def test_https_gets_a_secure_cookie():
attrs = session_cookie_attrs(build_request(scheme="https"))
assert attrs["secure"] is True
def test_forwarded_proto_is_honoured_when_the_proxy_is_not_trusted():
"""uvicorn only rewrites the scheme for proxies HOST_IP trusts; narrowing it dropped `Secure`."""
attrs = session_cookie_attrs(build_request(headers={"x-forwarded-proto": "https"}))
assert attrs["secure"] is True
def test_the_first_hop_of_a_forwarded_chain_decides():
"""Proxies append, so the browser's own protocol is the first entry rather than the last."""
assert session_cookie_attrs(build_request(headers={"x-forwarded-proto": "https, http"}))["secure"] is True
assert session_cookie_attrs(build_request(headers={"x-forwarded-proto": "http, https"}))["secure"] is False
def test_embedded_over_https_relaxes_samesite_and_partitions():
attrs = session_cookie_attrs(build_request(scheme="https", headers={"x-mealie-embedded": "true"}))
assert attrs["samesite"] == "none"
assert attrs["partitioned"] is True
def test_embedded_behind_an_untrusted_proxy_still_relaxes_samesite():
"""The regression this guards: degrading to Lax silently breaks cross-site iframe embedding."""
attrs = session_cookie_attrs(build_request(headers={"x-forwarded-proto": "https", "x-mealie-embedded": "true"}))
assert attrs["samesite"] == "none"
assert attrs["partitioned"] is True
def test_embedded_over_plain_http_stays_lax():
"""Browsers reject `SameSite=None` without `Secure`, so it must not be emitted over HTTP."""
attrs = session_cookie_attrs(build_request(headers={"x-mealie-embedded": "true"}))
assert attrs["samesite"] == "lax"
assert attrs["partitioned"] is False