Fix Firefox account consent for 4.0.6

This commit is contained in:
Anarios committed 2026-09-07 19:10:02 +02:00
1 parent e500088e65
commit ee20c7437c
20 files changed
+606 -331

No files matched your search

+51 -13
View File
@@ -2,13 +2,6 @@
const fs = require("fs");
const path = require("path");
jest.mock("./src/data-collection-permissions", () => ({
hasAuthenticationDataPermission: jest.fn(),
onAuthenticationDataPermissionRemoved: jest.fn(),
requestAuthenticationDataPermission: jest.fn(),
usesFirefoxDataCollectionConsent: jest.fn(),
}));
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
const cachedUser = { fullName: "Test User", imageUrl: "https://example.org/avatar", membershipTier: "none" };
@@ -21,14 +14,19 @@ describe("popup account consent lifecycle", () => {
jest.resetModules();
consent = true;
document.documentElement.innerHTML = fs.readFileSync(path.join(__dirname, "popup.html"), "utf8");
const permissions = require("./src/data-collection-permissions");
permissions.usesFirefoxDataCollectionConsent.mockReturnValue(true);
permissions.hasAuthenticationDataPermission.mockImplementation(() => Promise.resolve(consent));
permissions.requestAuthenticationDataPermission.mockImplementation(() => Promise.resolve(consent));
permissions.onAuthenticationDataPermissionRemoved.mockImplementation((listener) => (removeConsent = listener));
global.chrome = {
i18n: { getMessage: () => "" },
runtime: { getManifest: () => ({ version: "4.0.5" }), sendMessage: jest.fn() },
runtime: { getManifest: () => require("./manifest-firefox.json"), sendMessage: jest.fn() },
permissions: {
getAll: jest.fn(() => Promise.resolve({ data_collection: consent ? ["authenticationInfo"] : [] })),
contains: jest.fn().mockResolvedValue(true),
request: jest.fn(() => Promise.resolve(consent)),
onRemoved: {
addListener: (listener) => {
removeConsent = () => listener({ data_collection: ["authenticationInfo"] });
},
},
},
identity: { getRedirectURL: jest.fn() },
storage: {
sync: {
@@ -41,6 +39,7 @@ describe("popup account consent lifecycle", () => {
onChanged: { addListener: jest.fn() },
},
};
global.browser = global.chrome;
global.fetch = jest.fn();
require("./popup");
});
@@ -48,6 +47,7 @@ describe("popup account consent lifecycle", () => {
afterEach(() => {
jest.restoreAllMocks();
delete global.chrome;
delete global.browser;
delete global.fetch;
});
@@ -82,6 +82,44 @@ describe("popup account consent lifecycle", () => {
expect(document.getElementById("patreon-user-avatar").hasAttribute("src")).toBe(false);
}
test.each([[], undefined])("does not verify or display cached account data without a grant: %j", async (granted) => {
chrome.permissions.getAll.mockResolvedValue({ permissions: ["identity"], data_collection: granted });
readCachedSession({ patreonUser: cachedUser, patreonSessionToken: "test-token" });
await flushPromises();
expect(fetch).not.toHaveBeenCalled();
expect(chrome.storage.sync.remove).toHaveBeenCalledWith([
"patreonAuthenticated",
"patreonUser",
"patreonSessionToken",
]);
expectLoggedOut();
});
test.each(["patreon-login-btn", "github-login-btn"])(
"does not start %s when Firefox denies authentication consent",
async (button) => {
consent = false;
jest.spyOn(window, "alert").mockImplementation(() => {});
document.getElementById(button).click();
expect(chrome.permissions.request).toHaveBeenCalledWith({ data_collection: ["authenticationInfo"] });
await flushPromises();
expect(chrome.runtime.sendMessage).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
},
);
test.each(["patreon-login-btn", "github-login-btn"])(
"does not start %s after a request succeeds without a recorded grant",
async (button) => {
chrome.permissions.getAll.mockResolvedValue({ permissions: ["identity"], data_collection: [] });
jest.spyOn(window, "alert").mockImplementation(() => {});
document.getElementById(button).click();
await flushPromises();
expect(chrome.runtime.sendMessage).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
},
);
test("does not verify or show a cached session whose storage read completes after revocation", async () => {
revoke();
readCachedSession({ patreonUser: cachedUser, patreonSessionToken: "test-token" });
+23 -10
View File
@@ -1,9 +1,4 @@
jest.mock("../common/vote-client", () => ({ createVoteClient: jest.fn() }));
jest.mock("./src/data-collection-permissions", () => ({
hasAuthenticationDataPermission: jest.fn(),
onAuthenticationDataPermissionRemoved: jest.fn(),
usesFirefoxDataCollectionConsent: jest.fn(),
}));
const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0));
const startData = () => {
@@ -45,18 +40,23 @@ describe("background account consent lifecycle", () => {
},
},
});
const permissions = require("./src/data-collection-permissions");
permissions.usesFirefoxDataCollectionConsent.mockReturnValue(true);
permissions.hasAuthenticationDataPermission.mockImplementation(() => Promise.resolve(consent));
permissions.onAuthenticationDataPermissionRemoved.mockImplementation((listener) => (removeConsent = listener));
require("../common/vote-client").createVoteClient.mockReturnValue({ ensureRegistered: () => Promise.resolve({}) });
global.__RYD_LIVE_TEST_BUILD__ = false;
global.chrome = {
runtime: {
getManifest: () => ({ version: "4.0.5" }),
getManifest: () => require("./manifest-firefox.json"),
onMessage: { addListener: (listener) => (messageListener = listener) },
onInstalled: { addListener: jest.fn() },
},
permissions: {
getAll: jest.fn(() => Promise.resolve({ data_collection: consent ? ["authenticationInfo"] : [] })),
contains: jest.fn().mockResolvedValue(true),
onRemoved: {
addListener: (listener) => {
removeConsent = () => listener({ data_collection: ["authenticationInfo"] });
},
},
},
identity: {
getRedirectURL: () => "https://extension.example/callback",
launchWebAuthFlow: jest.fn(() => Promise.resolve("https://extension.example/callback?code=test&state=test")),
@@ -108,6 +108,19 @@ describe("background account consent lifecycle", () => {
},
);
test.each(["patreon_oauth_login", "github_oauth_login"])(
"%s sends nothing when Firefox does not expose built-in data consent",
async (message) => {
chrome.permissions.getAll.mockResolvedValue({ permissions: ["identity"], origins: [] });
const response = jest.fn();
messageListener({ message }, {}, response);
await flushPromises();
expect(fetch).not.toHaveBeenCalled();
expect(chrome.identity.launchWebAuthFlow).not.toHaveBeenCalled();
expect(response).toHaveBeenCalledWith(expect.objectContaining({ success: false }));
},
);
test.each(["patreon_oauth_login", "github_oauth_login"])(
"%s does not open OAuth after consent is revoked during startup",
async (message) => {
@@ -21,18 +21,6 @@ function usesFirefoxDataCollectionConsent() {
return Boolean(manifest?.browser_specific_settings?.gecko?.data_collection_permissions);
}
function callFirefoxPermissionMethod(methodName) {
const permissions = getPermissionsApi();
const method = permissions?.[methodName];
if (typeof method !== "function") return Promise.resolve(false);
try {
return Promise.resolve(method.call(permissions, AUTHENTICATION_DATA_DESCRIPTOR)).then(Boolean, () => false);
} catch (_) {
return Promise.resolve(false);
}
}
function queryBackgroundForAuthenticationDataPermission() {
const runtime = getRuntimeApi();
if (typeof runtime?.sendMessage !== "function") return Promise.resolve(false);
@@ -64,8 +52,22 @@ function queryBackgroundForAuthenticationDataPermission() {
function hasAuthenticationDataPermission({ queryBackground = true } = {}) {
if (!usesFirefoxDataCollectionConsent()) return Promise.resolve(true);
if (typeof getPermissionsApi()?.contains === "function") return callFirefoxPermissionMethod("contains");
return queryBackground ? queryBackgroundForAuthenticationDataPermission() : Promise.resolve(false);
const permissions = getPermissionsApi();
if (!permissions) {
return queryBackground ? queryBackgroundForAuthenticationDataPermission() : Promise.resolve(false);
}
if (typeof permissions.getAll !== "function") return Promise.resolve(false);
try {
return Promise.resolve(permissions.getAll()).then(
(granted) =>
Array.isArray(granted?.data_collection) &&
ACCOUNT_DATA_PERMISSIONS.every((permission) => granted.data_collection.includes(permission)),
() => false,
);
} catch (_) {
return Promise.resolve(false);
}
}
function requestAuthenticationDataPermission() {
@@ -73,7 +75,17 @@ function requestAuthenticationDataPermission() {
// Keep this direct request as the first operation in the login click stack.
// Firefox requires optional data-collection consent requests to originate from a user gesture.
return callFirefoxPermissionMethod("request");
const permissions = getPermissionsApi();
if (typeof permissions?.request !== "function") return Promise.resolve(false);
try {
return Promise.resolve(permissions.request(AUTHENTICATION_DATA_DESCRIPTOR)).then(
(granted) => granted === true && hasAuthenticationDataPermission({ queryBackground: false }),
() => false,
);
} catch (_) {
return Promise.resolve(false);
}
}
function authenticationDataPermissionWasRemoved(removedPermissions) {
@@ -31,7 +31,7 @@ describe("Firefox data-collection permissions", () => {
});
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: { request },
permissions: { request, getAll: jest.fn().mockResolvedValue({ data_collection: ["authenticationInfo"] }) },
};
const result = requestAuthenticationDataPermission();
@@ -42,18 +42,76 @@ describe("Firefox data-collection permissions", () => {
});
it("checks the existing Firefox grant without requesting it", async () => {
const contains = jest.fn(() => Promise.resolve(false));
const getAll = jest.fn().mockResolvedValue({ permissions: ["identity"], origins: [], data_collection: [] });
const contains = jest.fn().mockResolvedValue(true);
const request = jest.fn();
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: { contains, request },
permissions: { getAll, contains, request },
};
await expect(hasAuthenticationDataPermission()).resolves.toBe(false);
expect(contains).toHaveBeenCalledWith({ data_collection: ["authenticationInfo"] });
expect(getAll).toHaveBeenCalledWith();
expect(contains).not.toHaveBeenCalled();
expect(request).not.toHaveBeenCalled();
});
it.each([{}, { data_collection: [] }, { data_collection: ["financialAndPaymentInfo"] }])(
"does not accept a successful request without a recorded authentication grant: %j",
async (grantedPermissions) => {
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: {
request: jest.fn().mockResolvedValue(true),
getAll: jest.fn().mockResolvedValue(grantedPermissions),
contains: jest.fn().mockResolvedValue(true),
},
};
await expect(requestAuthenticationDataPermission()).resolves.toBe(false);
},
);
it("does not let an existing grant override the user's denied request", async () => {
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: {
request: jest.fn().mockResolvedValue(false),
getAll: jest.fn().mockResolvedValue({ data_collection: ["authenticationInfo"] }),
},
};
await expect(requestAuthenticationDataPermission()).resolves.toBe(false);
expect(browser.permissions.getAll).not.toHaveBeenCalled();
});
it("reads the current grant again after it is revoked without a cached result", async () => {
const getAll = jest
.fn()
.mockResolvedValueOnce({ data_collection: ["authenticationInfo"] })
.mockResolvedValueOnce({ data_collection: [] });
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: { getAll, contains: jest.fn().mockResolvedValue(true) },
};
await expect(hasAuthenticationDataPermission()).resolves.toBe(true);
await expect(hasAuthenticationDataPermission()).resolves.toBe(false);
});
it("fails closed when getAll throws synchronously", async () => {
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: {
getAll: () => {
throw new Error("unavailable");
},
},
};
await expect(hasAuthenticationDataPermission()).resolves.toBe(false);
});
it("leaves Chrome behavior unchanged", async () => {
const request = jest.fn();
global.chrome = {
@@ -78,19 +136,20 @@ describe("Firefox data-collection permissions", () => {
it.each([
{ granted: ["authenticationInfo"], expected: true },
{ granted: ["financialAndPaymentInfo"], expected: false },
])(
"checks authentication consent independently of obsolete financial grants: $granted",
async ({ granted, expected }) => {
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: {
contains: ({ data_collection }) =>
Promise.resolve(data_collection.every((permission) => granted.includes(permission))),
},
};
await expect(hasAuthenticationDataPermission()).resolves.toBe(expected);
},
);
{ granted: [], expected: false },
{ granted: undefined, expected: false },
{ granted: null, expected: false },
{ granted: "authenticationInfo", expected: false },
])("requires an explicit authentication grant in getAll: $granted", async ({ granted, expected }) => {
global.browser = {
runtime: { getManifest: () => firefoxManifest },
permissions: {
contains: jest.fn().mockResolvedValue(true),
getAll: jest.fn().mockResolvedValue({ permissions: ["identity"], origins: [], data_collection: granted }),
},
};
await expect(hasAuthenticationDataPermission()).resolves.toBe(expected);
});
it("does not end the account session when only an obsolete financial grant is removed", () => {
let removedListener;
@@ -124,6 +183,30 @@ describe("Firefox data-collection permissions", () => {
await expect(hasAuthenticationDataPermission({ queryBackground: false })).resolves.toBe(false);
});
it("does not fall back to contains or the background when getAll is unavailable", async () => {
const sendMessage = jest.fn().mockResolvedValue({ granted: true });
const contains = jest.fn().mockResolvedValue(true);
global.browser = {
runtime: { getManifest: () => firefoxManifest, sendMessage },
permissions: { contains },
};
await expect(hasAuthenticationDataPermission()).resolves.toBe(false);
expect(contains).not.toHaveBeenCalled();
expect(sendMessage).not.toHaveBeenCalled();
});
it("does not fall back to a positive background result after getAll fails", async () => {
const sendMessage = jest.fn().mockResolvedValue({ granted: true });
global.browser = {
runtime: { getManifest: () => firefoxManifest, sendMessage },
permissions: { getAll: jest.fn().mockRejectedValue(new Error("unavailable")) },
};
await expect(hasAuthenticationDataPermission()).resolves.toBe(false);
expect(sendMessage).not.toHaveBeenCalled();
});
it("fails closed on permission API and background failures", async () => {
global.browser = {
runtime: { getManifest: () => firefoxManifest, sendMessage: () => Promise.reject(new Error("unavailable")) },
@@ -131,7 +214,7 @@ describe("Firefox data-collection permissions", () => {
await expect(hasAuthenticationDataPermission()).resolves.toBe(false);
await expect(requestAuthenticationDataPermission()).resolves.toBe(false);
global.browser.permissions = {
contains: () => Promise.reject(new Error("unavailable")),
getAll: () => Promise.reject(new Error("unavailable")),
request: () => {
throw new Error("outside gesture");
},
@@ -255,6 +255,23 @@ describe("premiumAnalytics", () => {
expect(analyticsState.sessionActive).toBe(false);
});
it.each([[], undefined])("does not send a bearer token without an explicit Firefox grant: %j", async (granted) => {
const actualConsent = jest.requireActual("../data-collection-permissions");
chrome.runtime = { getManifest: () => require("../../manifest-firefox.json") };
chrome.permissions = {
contains: jest.fn().mockResolvedValue(true),
getAll: jest.fn().mockResolvedValue({ permissions: ["identity"], data_collection: granted }),
};
mockUsesFirefoxDataCollectionConsent.mockImplementationOnce(actualConsent.usesFirefoxDataCollectionConsent);
mockHasAuthenticationDataPermission.mockImplementationOnce(actualConsent.hasAuthenticationDataPermission);
await requestAnalytics();
expect(fetch).not.toHaveBeenCalled();
expect(analyticsState.sessionToken).toBeNull();
expect(analyticsState.sessionActive).toBe(false);
});
it("ignores an analytics response from a session that was signed out", async () => {
let completeRequest;
const response = await fetch();