PAM (3-B4): route Autofill's cipher lookups through FillCipherPolicy (#24615)

Extracts FillCipherPolicy from pam/uat. Autofill reads ciphers only
through the policy with a CipherUse. The OSS DefaultFillCipherPolicy
wraps CipherService and changes no behaviour; a commercial build can
supply its own through MainBackground's new overrides argument.

Every user-started fill, the save prompt, the badge, the context menu
and the inline menu go through the policy, and refresh when it reports a
change. An eslint no-restricted-syntax rule blocks direct CipherService
lookups in Autofill.

main.background.ts takes only the policy's hunks. CipherService keeps
its messagingService argument (B5), and the revealedCipherService
override and the public messageListener stay out (A10).
This commit is contained in:
Oscar Hinton
2026-11-10 19:16:01 +01:00
committed by GitHub
parent 8b60b3d94f
commit 1416af6867
28 changed files with 1221 additions and 149 deletions

View File

@@ -269,13 +269,6 @@ export type OverlayBackgroundExtensionMessageHandlers = {
sender,
}: BackgroundOnMessageHandlerParams) => void;
collectPageDetailsResponse: ({ message, sender }: BackgroundOnMessageHandlerParams) => void;
doFullSync: () => void;
addedCipher: () => void;
addEditCipherSubmitted: () => void;
editedCipher: () => void;
deletedCipher: () => void;
bgSaveCipher: () => void;
updateOverlayCiphers: () => void;
fido2AbortRequest: ({ sender }: BackgroundSenderParam) => void;
routeTargetedFieldsToFrame: ({ message, sender }: BackgroundOnMessageHandlerParams) => void;
};

View File

@@ -19,6 +19,7 @@ import {
PageTransitionResolved,
} from "../services/abstractions/autofill-lifecycle.service";
import { AutofillService, PageDetail } from "../services/abstractions/autofill.service";
import { DefaultFillCipherPolicy } from "../services/default-fill-cipher-policy";
import {
createAutofillFieldMock,
createAutofillPageDetailsMock,
@@ -43,6 +44,7 @@ describe("DefaultAutofillOrchestrator", () => {
let accountService: MockProxy<AccountService>;
let platformUtilsService: MockProxy<PlatformUtilsService>;
let updateOverlayCiphers: jest.Mock<Promise<void>, []>;
let fillCipherPolicy: DefaultFillCipherPolicy;
const logService = mock<LogService>();
let pageTransitionResolved$: Subject<PageTransitionResolved>;
@@ -121,12 +123,12 @@ describe("DefaultAutofillOrchestrator", () => {
new DefaultAutofillOrchestrator(
lifecycleService,
autofillService,
cipherService,
autofillSettingsService,
accountService,
platformUtilsService,
updateOverlayCiphers,
logService,
fillCipherPolicy,
now,
);
@@ -185,6 +187,9 @@ describe("DefaultAutofillOrchestrator", () => {
platformUtilsService = mock<PlatformUtilsService>();
updateOverlayCiphers = jest.fn().mockResolvedValue(undefined);
fillCipherPolicy = new DefaultFillCipherPolicy(cipherService);
jest.spyOn(fillCipherPolicy, "nextCipherForUrl");
jest.spyOn(fillCipherPolicy, "advanceRotation");
autofillOrchestrator = construct();
autofillOrchestrator.init();
@@ -640,8 +645,8 @@ describe("DefaultAutofillOrchestrator", () => {
});
it.each([
["card", CipherType.Card, "cardCiphers", "getNextCardCipher"],
["identity", CipherType.Identity, "identityCiphers", "getNextIdentityCipher"],
["card", CipherType.Card, "cardCiphers", "nextCardCipher"],
["identity", CipherType.Identity, "identityCiphers", "nextIdentityCipher"],
] as const)(
"collects the tab and fills a %s with no page-load/keyboard side effects",
async (_label, cipherType, cacheKey, selector) => {
@@ -650,7 +655,7 @@ describe("DefaultAutofillOrchestrator", () => {
autofillService.collectPageDetailsFromTab$.mockReturnValue(of([pd]));
// The row names the selection method for its type, so the case's cipher is wired without a
// branch on cipherType.
cipherService[selector].mockResolvedValue(cipher);
jest.spyOn(fillCipherPolicy, selector).mockResolvedValue(cipher);
autofillService.doAutoFill.mockResolvedValue({ outcome: AutofillOutcome.Filled });
autofillOrchestrator.autofillActiveTabForCipherType(pd.tab, cipherType);
@@ -1275,4 +1280,43 @@ describe("DefaultAutofillOrchestrator", () => {
expect(accountService.setAccountActivity).not.toHaveBeenCalled();
});
});
describe("fill cipher policy", () => {
it("selects the next cipher from the policy for a keyboard command", async () => {
const pd = pageDetail(1, 0);
const cipher = makeCipher(CipherType.Login, { id: "from-policy" });
jest.spyOn(fillCipherPolicy, "nextCipherForUrl").mockResolvedValue(cipher);
autofillService.collectPageDetailsFromTab$.mockReturnValue(of([pd]));
autofillService.doAutoFill.mockResolvedValue({ outcome: AutofillOutcome.Filled });
autofillOrchestrator.autofillActiveTabFromCommand(pd.tab);
await flushPromises();
expect(fillCipherPolicy.nextCipherForUrl).toHaveBeenCalledWith(DEFAULT_URL, "user-1");
expect(autofillService.doAutoFill).toHaveBeenCalledWith(expect.objectContaining({ cipher }));
expect(fillCipherPolicy.advanceRotation).toHaveBeenCalledWith(DEFAULT_URL);
});
it("never uses the user fill rotation for a page-load fill", async () => {
const pd = pageDetail(1, 0);
autofillService.collectPageDetailsFromTab$.mockReturnValue(of([pd]));
emitPageTransition(pd);
await flushPromises();
expect(fillCipherPolicy.nextCipherForUrl).not.toHaveBeenCalled();
expect(cipherService.getLastUsedForUrl).toHaveBeenCalled();
});
it("never uses the user fill rotation for an auto-submit fill", async () => {
const pd = pageDetail(1, 0);
autofillService.collectPageDetailsFromTab$.mockReturnValue(of([pd]));
emitAutomatedLoginStep(pd);
await flushPromises();
expect(fillCipherPolicy.nextCipherForUrl).not.toHaveBeenCalled();
expect(cipherService.getLastUsedForUrl).toHaveBeenCalled();
});
});
});

View File

@@ -20,7 +20,6 @@ import { LogService } from "@bitwarden/common/platform/abstractions/log.service"
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { withLatestReady } from "@bitwarden/common/tools/rx";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherRepromptType } from "@bitwarden/common/vault/enums/cipher-reprompt-type";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
@@ -36,6 +35,7 @@ import {
AutofillService,
PageDetail,
} from "../services/abstractions/autofill.service";
import { FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import { AutofillTriageResponse } from "../types/autofill-triage";
import {
AUTOFILL_ABSENT,
@@ -154,12 +154,12 @@ export class DefaultAutofillOrchestrator implements AutofillOrchestrator {
constructor(
private lifecycleService: AutofillLifecycleService,
private autofillService: AutofillService,
private cipherService: CipherService,
private autofillSettingsService: AutofillSettingsServiceAbstraction,
private accountService: AccountService,
private platformUtilsService: PlatformUtilsService,
private updateOverlayCiphers: () => Promise<void>,
private logService: LogService,
private fillCipherPolicy: FillCipherPolicy,
/** Injected wall-clock source (epoch ms), overridable so time-dependent selection is testable. */
private now: () => number = () => Date.now(),
) {}
@@ -504,10 +504,10 @@ export class DefaultAutofillOrchestrator implements AutofillOrchestrator {
reason: FillReason,
): Promise<CipherView | undefined> {
if (reason === FillReason.userCommand) {
return (await this.cipherService.getNextCipherForUrl(tabUrl, activeUserId)) ?? undefined;
return this.fillCipherPolicy.nextCipherForUrl(tabUrl, activeUserId);
}
const isAutomatic = reason === FillReason.automatic;
const lastLaunchedCipher = await this.cipherService.getLastLaunchedForUrl(
const lastLaunchedCipher = await this.fillCipherPolicy.lastLaunchedForUrl(
tabUrl,
activeUserId,
isAutomatic,
@@ -520,8 +520,7 @@ export class DefaultAutofillOrchestrator implements AutofillOrchestrator {
) {
return lastLaunchedCipher;
}
const cipher = await this.cipherService.getLastUsedForUrl(tabUrl, activeUserId, isAutomatic);
return cipher ?? undefined;
return this.fillCipherPolicy.lastUsedForUrl(tabUrl, activeUserId, isAutomatic);
}
/** Selects the next card or identity cipher and the cache key its rotation index advances under. */
@@ -532,8 +531,8 @@ export class DefaultAutofillOrchestrator implements AutofillOrchestrator {
const cacheKey = cipherType === CipherType.Card ? "cardCiphers" : "identityCiphers";
const cipher =
cipherType === CipherType.Card
? await this.cipherService.getNextCardCipher(activeUserId)
: await this.cipherService.getNextIdentityCipher(activeUserId);
? await this.fillCipherPolicy.nextCardCipher(activeUserId)
: await this.fillCipherPolicy.nextIdentityCipher(activeUserId);
return cipher ? { cipher, cacheKey } : undefined;
}
@@ -613,11 +612,11 @@ export class DefaultAutofillOrchestrator implements AutofillOrchestrator {
/**
* Advances the rotation cursor for a URL (or card/identity cache key) so the *next* fill for it
* offers the next matching cipher. `updateLastUsedIndexForUrl` is that cursor — a way to cycle
* offers the next matching cipher. `advanceRotation` is that cursor — a way to cycle
* through the ciphers that fit a page across repeated fills — not a record that a cipher was used.
*/
private cycleFillableCipher(key: string): void {
this.cipherService.updateLastUsedIndexForUrl(key);
this.fillCipherPolicy.advanceRotation(key);
}
private activeUserId(): Promise<UserId | null> {

View File

@@ -39,7 +39,9 @@ import { BrowserApi } from "../../platform/browser/browser-api";
import { NotificationType } from "../enums/notification-type.enum";
import { Fido2Background } from "../fido2/background/abstractions/fido2.background";
import { FormData } from "../services/abstractions/autofill.service";
import { CipherUse, FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import AutofillService from "../services/autofill.service";
import { DefaultFillCipherPolicy } from "../services/default-fill-cipher-policy";
import { createAutofillPageDetailsMock, createChromeTabMock } from "../spec/autofill-mocks";
import {
crossContextBoundary,
@@ -79,6 +81,7 @@ describe("NotificationBackground", () => {
let externalMessages: Subject<Message<Record<string, unknown>>>;
const autofillService = mock<AutofillService>();
const cipherService = mock<CipherService>();
const fillCipherPolicy = mock<FillCipherPolicy>();
const collectionService = mock<CollectionService>();
let activeAccountStatusMock$: BehaviorSubject<AuthenticationStatus>;
let authService: MockProxy<AuthService>;
@@ -126,6 +129,12 @@ describe("NotificationBackground", () => {
authService = mock<AuthService>();
authService.activeAccountStatus$ = activeAccountStatusMock$;
accountService.activeAccount$ = activeAccountSubject;
const storedCipherPolicy = new DefaultFillCipherPolicy(cipherService);
fillCipherPolicy.ciphers.mockImplementation((...args) => storedCipherPolicy.ciphers(...args));
fillCipherPolicy.ciphersForUrl.mockImplementation((...args) =>
storedCipherPolicy.ciphersForUrl(...args),
);
fillCipherPolicy.canOfferSave.mockResolvedValue(true);
notificationBackground = new NotificationBackground(
accountService,
authService,
@@ -148,6 +157,7 @@ describe("NotificationBackground", () => {
intraprocessMessageSender,
// Wired as `MainBackground` wires it, so ingest tagging is exercised rather than faked.
new MessageListener(intraprocessMessageSender.messages$({ external$: externalMessages })),
fillCipherPolicy,
);
});
@@ -592,7 +602,11 @@ describe("NotificationBackground", () => {
sendMockExtensionMessage({ command: "bgOpenChangePasswordUrl" }, sender);
await flushPromises();
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(tabUrl, userId);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
tabUrl,
userId,
CipherUse.SecurityTask,
);
expect(changeLoginPasswordService.getChangePasswordUrl).toHaveBeenCalledWith(cipher);
expect(createNewTabSpy).toHaveBeenCalledWith(
"https://jest-testing-website.com/.well-known/change-password",
@@ -639,7 +653,11 @@ describe("NotificationBackground", () => {
sendMockExtensionMessage({ command: "bgOpenChangePasswordUrl" }, sender);
await flushPromises();
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(tabUrl, userId);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
tabUrl,
userId,
CipherUse.SecurityTask,
);
expect(createNewTabSpy).not.toHaveBeenCalled();
});
@@ -985,6 +1003,12 @@ describe("NotificationBackground", () => {
await notificationBackground.triggerCipherNotification(formEntryData, tab);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
formEntryData.uri,
userId,
CipherUse.SavePrompt,
);
expect(pushChangePasswordToQueueSpy).not.toHaveBeenCalled();
expect(pushAddLoginToQueueSpy).toHaveBeenCalledWith(
mockFormattedURI,
@@ -2609,6 +2633,98 @@ describe("NotificationBackground", () => {
);
});
it("drops an AddLogin save the fill cipher policy does not offer", async () => {
const tab = createChromeTabMock({ id: 1, url: "https://example.com" });
const sender = mock<chrome.runtime.MessageSender>({ tab });
const data = { username: "test", password: "revealed", uri: "https://example.com" };
notificationBackground["notificationQueue"] = [
mock<AddLoginQueueMessage>({
type: NotificationType.AddLogin,
tab,
domain: "example.com",
data,
wasVaultLocked: false,
}),
];
fillCipherPolicy.canOfferSave.mockResolvedValueOnce(false);
sendMockExtensionMessage({ command: "bgSaveCipher", edit: false }, sender);
await flushPromises();
expect(fillCipherPolicy.canOfferSave).toHaveBeenCalledWith(data, userId);
expect(notificationBackground["notificationQueue"]).toHaveLength(0);
expect(createWithServerSpy).not.toHaveBeenCalled();
expect(updatePasswordSpy).not.toHaveBeenCalled();
expect(editItemSpy).not.toHaveBeenCalled();
expect(tabSendMessageDataSpy).toHaveBeenCalledWith(tab, "closeNotificationBar", {
closedByUser: false,
});
expect(tabSendMessageDataSpy).not.toHaveBeenCalledWith(
tab,
"saveCipherAttemptCompleted",
expect.anything(),
);
});
it("drops a ChangePassword update the fill cipher policy does not offer", async () => {
const tab = createChromeTabMock({ id: 1, url: "https://example.com" });
const sender = mock<chrome.runtime.MessageSender>({ tab });
notificationBackground["notificationQueue"] = [
mock<AddChangePasswordNotificationQueueMessage>({
type: NotificationType.ChangePassword,
tab,
domain: "example.com",
data: { newPassword: "revealed" },
wasVaultLocked: true,
}),
];
fillCipherPolicy.canOfferSave.mockResolvedValueOnce(false);
sendMockExtensionMessage(
{ command: "bgSaveCipher", edit: false, cipherId: "testId" },
sender,
);
await flushPromises();
expect(fillCipherPolicy.canOfferSave).toHaveBeenCalledWith(
{ uri: "https://example.com", newPassword: "revealed" },
userId,
);
expect(notificationBackground["notificationQueue"]).toHaveLength(0);
expect(getDecryptedCipherByIdSpy).not.toHaveBeenCalled();
expect(updatePasswordSpy).not.toHaveBeenCalled();
expect(updateWithServerSpy).not.toHaveBeenCalled();
expect(createWithServerSpy).not.toHaveBeenCalled();
expect(tabSendMessageDataSpy).toHaveBeenCalledWith(tab, "closeNotificationBar", {
closedByUser: false,
});
});
it("saves an AddLogin the fill cipher policy offers", async () => {
const tab = createChromeTabMock({ id: 1, url: "https://example.com" });
const sender = mock<chrome.runtime.MessageSender>({ tab });
const data = { username: "test", password: "password", uri: "https://example.com" };
notificationBackground["notificationQueue"] = [
mock<AddLoginQueueMessage>({
type: NotificationType.AddLogin,
tab,
domain: "example.com",
data,
wasVaultLocked: false,
}),
];
createWithServerSpy.mockResolvedValueOnce(mock<CipherView>({ id: "testId" }));
sendMockExtensionMessage({ command: "bgSaveCipher", edit: false }, sender);
await flushPromises();
expect(fillCipherPolicy.canOfferSave).toHaveBeenCalledWith(data, userId);
expect(createWithServerSpy).toHaveBeenCalled();
expect(tabSendMessageDataSpy).not.toHaveBeenCalledWith(tab, "closeNotificationBar", {
closedByUser: false,
});
});
it("updates the cipher password if the queue message was locked and an existing cipher has the same username as the message", async () => {
const tab = createChromeTabMock({ id: 1, url: "https://example.com" });
const sender = mock<chrome.runtime.MessageSender>({ tab });
@@ -2637,6 +2753,11 @@ describe("NotificationBackground", () => {
sendMockExtensionMessage(message, sender);
await flushPromises();
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
queueMessage.data.uri,
userId,
CipherUse.SavePrompt,
);
expect(updatePasswordSpy).toHaveBeenCalledWith(
cipherView,
queueMessage.data.password,
@@ -2880,6 +3001,56 @@ describe("NotificationBackground", () => {
});
});
describe("bgOpenAddEditVaultItemPopout message handler", () => {
const data = { username: "test", password: "revealed", uri: "https://example.com" };
let tab: chrome.tabs.Tab;
let sender: chrome.runtime.MessageSender;
let setAddEditCipherInfoSpy: jest.SpyInstance;
let openAddEditVaultItemPopoutSpy: jest.SpyInstance;
beforeEach(() => {
tab = createChromeTabMock({ id: 1, url: "https://example.com" });
sender = mock<chrome.runtime.MessageSender>({ tab });
notificationBackground["notificationQueue"] = [
mock<AddLoginQueueMessage>({
type: NotificationType.AddLogin,
tab,
domain: "example.com",
data,
}),
];
accountService.activeAccount$ = activeAccountSubject;
setAddEditCipherInfoSpy = jest
.spyOn(cipherService, "setAddEditCipherInfo")
.mockResolvedValue(undefined);
openAddEditVaultItemPopoutSpy = jest
.spyOn(notificationBackground as any, "openAddEditVaultItemPopout")
.mockResolvedValue(undefined);
});
it("leaves the password out of the draft when the fill cipher policy does not offer the form", async () => {
fillCipherPolicy.canOfferSave.mockResolvedValueOnce(false);
sendMockExtensionMessage({ command: "bgOpenAddEditVaultItemPopout" }, sender);
await flushPromises();
expect(fillCipherPolicy.canOfferSave).toHaveBeenCalledWith(data, userId);
const { cipher } = setAddEditCipherInfoSpy.mock.calls[0][0];
expect(cipher.login.username).toBe("test");
expect(cipher.login.password).toBe("");
expect(openAddEditVaultItemPopoutSpy).toHaveBeenCalledWith(tab);
});
it("keeps the password in the draft when the fill cipher policy offers the form", async () => {
sendMockExtensionMessage({ command: "bgOpenAddEditVaultItemPopout" }, sender);
await flushPromises();
const { cipher } = setAddEditCipherInfoSpy.mock.calls[0][0];
expect(cipher.login.password).toBe("revealed");
expect(openAddEditVaultItemPopoutSpy).toHaveBeenCalledWith(tab);
});
});
describe("bgNeverSave message handler", () => {
let tabSendMessageDataSpy: jest.SpyInstance;

View File

@@ -66,6 +66,11 @@ import { CollectionView } from "../content/components/common-types";
import { NotificationType } from "../enums/notification-type.enum";
import { Fido2Background } from "../fido2/background/abstractions/fido2.background";
import { AutofillService } from "../services/abstractions/autofill.service";
import {
CipherUse,
FillCipherPolicy,
SaveCandidate,
} from "../services/abstractions/fill-cipher-policy";
import {
AddChangePasswordNotificationQueueMessage,
@@ -111,6 +116,17 @@ type CiphersByInputMatchCategory = {
usernamePasswordMatches: CipherView["id"][];
};
/** The form values a save of this queue message would write to a cipher. */
function saveCandidateFor(
queueMessage: AddLoginQueueMessage | AddChangePasswordNotificationQueueMessage,
tab: chrome.tabs.Tab,
): SaveCandidate {
if (queueMessage.type === NotificationType.AddLogin) {
return queueMessage.data;
}
return { uri: tab.url ?? "", newPassword: queueMessage.data.newPassword };
}
export default class NotificationBackground {
private openUnlockPopout = openUnlockPopout;
private openAddEditVaultItemPopout = openAddEditVaultItemPopout;
@@ -179,6 +195,7 @@ export default class NotificationBackground {
private fido2Background: Fido2Background,
private intraprocessMessageSender: IntraprocessMessageSender,
private messageListener: MessageListener,
private fillCipherPolicy: FillCipherPolicy,
) {}
init() {
@@ -249,7 +266,7 @@ export default class NotificationBackground {
}
const [decryptedCiphers, organizations] = await Promise.all([
this.cipherService.getAllDecryptedForUrl(currentTab.url, activeUserId),
this.fillCipherPolicy.ciphersForUrl(currentTab.url, activeUserId, CipherUse.SavePrompt),
firstValueFrom(this.organizationService.organizations$(activeUserId)),
]);
@@ -273,7 +290,7 @@ export default class NotificationBackground {
const {
data: { cipherIds },
} = cipherQueueMessage;
const cipherViews = await this.cipherService.getAllDecrypted(activeUserId);
const cipherViews = await this.fillCipherPolicy.ciphers(activeUserId, CipherUse.SavePrompt);
return cipherViews
.filter((cipher) => cipherIds.includes(cipher.id))
.map((cipherView) => {
@@ -369,9 +386,10 @@ export default class NotificationBackground {
return null;
}
const urlCiphers: CipherView[] = await this.cipherService.getAllDecryptedForUrl(
const urlCiphers: CipherView[] = await this.fillCipherPolicy.ciphersForUrl(
modifyLoginData.uri,
activeUserId,
CipherUse.SecurityTask,
);
if (!(urlCiphers?.length > 0)) {
return null;
@@ -756,9 +774,10 @@ export default class NotificationBackground {
return true;
}
const ciphersForURL: CipherView[] = await this.cipherService.getAllDecryptedForUrl(
const ciphersForURL: CipherView[] = await this.fillCipherPolicy.ciphersForUrl(
data.uri,
activeUserId,
CipherUse.SavePrompt,
);
// Reducer structured to avoid subsequent array iterations
@@ -1259,6 +1278,17 @@ export default class NotificationBackground {
continue;
}
if (
!(await this.fillCipherPolicy.canOfferSave(
saveCandidateFor(queueMessage, tab),
activeUserId,
))
) {
this.notificationQueue.splice(i, 1);
await BrowserApi.tabSendMessageData(tab, "closeNotificationBar", { closedByUser: false });
return;
}
if (queueMessage.type === NotificationType.ChangePassword) {
const {
data: { newPassword },
@@ -1283,9 +1313,10 @@ export default class NotificationBackground {
// If the vault was locked, check if a cipher needs updating instead of creating a new one
if (queueMessage.wasVaultLocked) {
const allCiphers = await this.cipherService.getAllDecryptedForUrl(
const allCiphers = await this.fillCipherPolicy.ciphersForUrl(
queueMessage.data.uri,
activeUserId,
CipherUse.SavePrompt,
);
const existingCipher = allCiphers.find(
(c) =>
@@ -1448,6 +1479,9 @@ export default class NotificationBackground {
const cipherView = this.convertAddLoginQueueMessageToCipherView(queueItem);
cipherView.organizationId = organizationId;
cipherView.folderId = folder;
if (userId && !(await this.fillCipherPolicy.canOfferSave(queueItem.data, userId))) {
cipherView.login.password = "";
}
if (userId) {
await this.cipherService.setAddEditCipherInfo({ cipher: cipherView }, userId);
@@ -1749,7 +1783,7 @@ export default class NotificationBackground {
return EMPTY;
}
return Promise.all([
this.cipherService.getAllDecryptedForUrl(tab.url!, userId),
this.fillCipherPolicy.ciphersForUrl(tab.url!, userId, CipherUse.SecurityTask),
this.getSecurityTasks(userId),
]);
}),

View File

@@ -1,5 +1,7 @@
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject } from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { CLEAR_NOTIFICATION_LOGIN_DATA_DURATION } from "@bitwarden/common/autofill/constants";
import { ServerConfig } from "@bitwarden/common/platform/abstractions/config/server-config";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
@@ -8,6 +10,7 @@ import { EnvironmentServerConfigData } from "@bitwarden/common/platform/models/d
import { BrowserApi } from "../../platform/browser/browser-api";
import AutofillField from "../models/autofill-field";
import AutofillPageDetails from "../models/autofill-page-details";
import { FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import {
flushPromises,
sendMockExtensionMessage,
@@ -24,6 +27,9 @@ import { OverlayNotificationsBackground } from "./overlay-notifications.backgrou
describe("OverlayNotificationsBackground", () => {
let logService: MockProxy<LogService>;
let notificationBackground: NotificationBackground;
let accountService: MockProxy<AccountService>;
let activeAccount$: BehaviorSubject<{ id: string } | null>;
let fillCipherPolicy: MockProxy<FillCipherPolicy>;
let getEnableChangedPasswordPromptSpy: jest.SpyInstance;
let getEnableAddedLoginPromptSpy: jest.SpyInstance;
let overlayNotificationsBackground: OverlayNotificationsBackground;
@@ -38,9 +44,16 @@ describe("OverlayNotificationsBackground", () => {
getEnableAddedLoginPromptSpy = jest
.spyOn(notificationBackground, "getEnableAddedLoginPrompt")
.mockResolvedValue(true);
activeAccount$ = new BehaviorSubject<{ id: string } | null>({ id: "user-1" });
accountService = mock<AccountService>();
(accountService as any).activeAccount$ = activeAccount$;
fillCipherPolicy = mock<FillCipherPolicy>();
fillCipherPolicy.canOfferSave.mockResolvedValue(true);
overlayNotificationsBackground = new OverlayNotificationsBackground(
logService,
notificationBackground,
accountService,
fillCipherPolicy,
);
await overlayNotificationsBackground.init();
});
@@ -742,6 +755,47 @@ describe("OverlayNotificationsBackground", () => {
expect(cipherNotificationSpy).toHaveBeenCalled();
});
it("triggers no notification for a form the fill cipher policy does not offer", async () => {
fillCipherPolicy.canOfferSave.mockResolvedValueOnce(false);
chrome.tabs.get = jest.fn().mockImplementationOnce((tabId, callback) => {
callback(mock<chrome.tabs.Tab>({ status: "complete", url: sender.url }));
});
triggerWebRequestOnCompletedEvent(
mock<chrome.webRequest.OnCompletedDetails>({
url: sender.url,
tabId: sender.tab.id,
requestId,
}),
);
await flushPromises();
expect(fillCipherPolicy.canOfferSave).toHaveBeenCalledWith(
expect.objectContaining({ username: "username", password: "password" }),
"user-1",
);
expect(cipherNotificationSpy).not.toHaveBeenCalled();
});
it("does not block the notification when no user is active", async () => {
activeAccount$.next(null);
chrome.tabs.get = jest.fn().mockImplementationOnce((tabId, callback) => {
callback(mock<chrome.tabs.Tab>({ status: "complete", url: sender.url }));
});
triggerWebRequestOnCompletedEvent(
mock<chrome.webRequest.OnCompletedDetails>({
url: sender.url,
tabId: sender.tab.id,
requestId,
}),
);
await flushPromises();
expect(fillCipherPolicy.canOfferSave).not.toHaveBeenCalled();
expect(cipherNotificationSpy).toHaveBeenCalled();
});
it("initializes the notification immediately when the tab's navigation is complete", async () => {
sendMockExtensionMessage(
{

View File

@@ -1,9 +1,12 @@
import { Subject, switchMap, timer } from "rxjs";
import { firstValueFrom, Subject, switchMap, timer } from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getOptionalUserId } from "@bitwarden/common/auth/services/account.service";
import { CLEAR_NOTIFICATION_LOGIN_DATA_DURATION } from "@bitwarden/common/autofill/constants";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { BrowserApi } from "../../platform/browser/browser-api";
import { FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import { generateDomainMatchPatterns, isInvalidResponseStatusCode } from "../utils";
import {
@@ -36,6 +39,8 @@ export class OverlayNotificationsBackground implements OverlayNotificationsBackg
constructor(
private logService: LogService,
private notificationBackground: NotificationBackground,
private accountService: AccountService,
private fillCipherPolicy: FillCipherPolicy,
) {}
/**
@@ -490,6 +495,11 @@ export class OverlayNotificationsBackground implements OverlayNotificationsBackg
tab: chrome.tabs.Tab,
config: { skippable: NotificationScenario[] } = { skippable: [] },
) => {
if (!(await this.canOfferSave(modifyLoginData))) {
this.clearCompletedWebRequest(requestId, tab.id);
return "";
}
const notificationCandidates = [
{
type: NotificationScenarios.Cipher,
@@ -521,6 +531,15 @@ export class OverlayNotificationsBackground implements OverlayNotificationsBackg
return results.join(" ");
};
/**
* Asks the {@link FillCipherPolicy} whether the form may get an add or update prompt. With no
* active user, the prompt is not blocked.
*/
private async canOfferSave(modifyLoginData: ModifyLoginCipherFormData): Promise<boolean> {
const userId = await firstValueFrom(this.accountService.activeAccount$.pipe(getOptionalUserId));
return userId == null || this.fillCipherPolicy.canOfferSave(modifyLoginData, userId);
}
/**
* Determines if the add login notification should be attempted based on the modified login form data.
* @param modifyLoginData modified login form data

View File

@@ -61,6 +61,8 @@ import {
RedirectFocusDirection,
} from "../enums/autofill-overlay.enum";
import { AutofillService } from "../services/abstractions/autofill.service";
import { CipherUse } from "../services/abstractions/fill-cipher-policy";
import { DefaultFillCipherPolicy } from "../services/default-fill-cipher-policy";
import { InlineMenuFieldQualificationService } from "../services/inline-menu-field-qualification.service";
import {
createAutofillFieldMock,
@@ -112,6 +114,7 @@ describe("OverlayBackground", () => {
let domainSettingsService: DomainSettingsService;
let logService: MockProxy<LogService>;
let cipherService: MockProxy<CipherService>;
let fillCipherPolicy: DefaultFillCipherPolicy;
let autofillService: MockProxy<AutofillService>;
let configService: MockProxy<ConfigService>;
let activeAccountStatusMock$: BehaviorSubject<AuthenticationStatus>;
@@ -262,6 +265,8 @@ describe("OverlayBackground", () => {
// The overlay routes fills through the orchestrator; default to a filled-without-TOTP outcome so
// handlers that destructure the result do not choke on the mock's undefined default.
autofillOrchestrator.fillCipher.mockResolvedValue({ outcome: AutofillOutcome.Filled });
fillCipherPolicy = new DefaultFillCipherPolicy(cipherService);
jest.spyOn(fillCipherPolicy, "ciphersForUrl");
overlayBackground = new OverlayBackground(
logService,
cipherService,
@@ -285,6 +290,7 @@ describe("OverlayBackground", () => {
intraprocessMessageSender,
// Wired as `MainBackground` wires it, so ingest tagging is exercised rather than faked.
new MessageListener(intraprocessMessageSender.messages$({ external$: externalMessages })),
fillCipherPolicy,
);
portKeyForTabSpy = overlayBackground["portKeyForTab"];
pageDetailsForTabSpy = overlayBackground["pageDetailsForTab"];
@@ -1141,11 +1147,12 @@ describe("OverlayBackground", () => {
await flushPromises();
expect(BrowserApi.getTabFromCurrentWindowId).toHaveBeenCalled();
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(url, mockUserId, [
CipherType.Card,
CipherType.Identity,
CipherType.SshKey,
]);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
url,
mockUserId,
CipherUse.UserFill,
{ includeOtherTypes: [CipherType.Card, CipherType.Identity, CipherType.SshKey] },
);
expect(cipherService.sortCiphersByLastUsedThenName).toHaveBeenCalled();
expect(overlayBackground["inlineMenuCiphers"]).toStrictEqual(
new Map([
@@ -1165,7 +1172,11 @@ describe("OverlayBackground", () => {
await flushPromises();
expect(BrowserApi.getTabFromCurrentWindowId).toHaveBeenCalled();
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(url, mockUserId);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
url,
mockUserId,
CipherUse.UserFill,
);
expect(cipherService.sortCiphersByLastUsedThenName).toHaveBeenCalled();
expect(overlayBackground["inlineMenuCiphers"]).toStrictEqual(
new Map([
@@ -1184,11 +1195,12 @@ describe("OverlayBackground", () => {
await flushPromises();
expect(BrowserApi.getTabFromCurrentWindowId).toHaveBeenCalled();
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(url, mockUserId, [
CipherType.Card,
CipherType.Identity,
CipherType.SshKey,
]);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
url,
mockUserId,
CipherUse.UserFill,
{ includeOtherTypes: [CipherType.Card, CipherType.Identity, CipherType.SshKey] },
);
expect(cipherService.sortCiphersByLastUsedThenName).toHaveBeenCalled();
expect(overlayBackground["inlineMenuCiphers"]).toStrictEqual(
new Map([
@@ -1900,6 +1912,57 @@ describe("OverlayBackground", () => {
expect(openAddEditVaultItemPopoutSpy).toHaveBeenCalled();
});
it("leaves the password out of a new login draft the fill cipher policy does not offer", async () => {
jest.spyOn(fillCipherPolicy, "canOfferSave").mockResolvedValueOnce(false);
sendMockExtensionMessage(
{
command: "autofillOverlayAddNewVaultItem",
addNewCipherType: CipherType.Login,
login: {
uri: "https://tacos.com",
hostname: "",
username: "username",
password: "revealed",
},
},
sender,
);
jest.advanceTimersByTime(100);
await flushPromises();
expect(fillCipherPolicy.canOfferSave).toHaveBeenCalledWith(
{ uri: "https://tacos.com", username: "username", password: "revealed" },
expect.anything(),
);
const { cipher } = jest.mocked(cipherService.setAddEditCipherInfo).mock.calls[0][0];
expect(cipher.login.username).toBe("username");
expect(cipher.login.password).toBe("");
expect(openAddEditVaultItemPopoutSpy).toHaveBeenCalled();
});
it("keeps the password in a new login draft the fill cipher policy offers", async () => {
sendMockExtensionMessage(
{
command: "autofillOverlayAddNewVaultItem",
addNewCipherType: CipherType.Login,
login: {
uri: "https://tacos.com",
hostname: "",
username: "username",
password: "password",
},
},
sender,
);
jest.advanceTimersByTime(100);
await flushPromises();
const { cipher } = jest.mocked(cipherService.setAddEditCipherInfo).mock.calls[0][0];
expect(cipher.login.password).toBe("password");
expect(openAddEditVaultItemPopoutSpy).toHaveBeenCalled();
});
it("creates a new card cipher", async () => {
overlayBackground["currentAddNewItemData"].addNewCipherType = CipherType.Card;
@@ -3252,24 +3315,25 @@ describe("OverlayBackground", () => {
});
});
describe("extension messages that trigger an update of the inline menu ciphers", () => {
describe("cipher change messages", () => {
const extensionMessages = [
"doFullSync",
"addedCipher",
"addEditCipherSubmitted",
"editedCipher",
"deletedCipher",
"bgSaveCipher",
"updateOverlayCiphers",
];
beforeEach(() => {
jest.spyOn(overlayBackground, "updateOverlayCiphers").mockImplementation();
});
extensionMessages.forEach((message) => {
it(`triggers an update of the overlay ciphers when the ${message} message is received`, () => {
sendMockExtensionMessage({ command: message });
expect(overlayBackground.updateOverlayCiphers).toHaveBeenCalled();
});
// `TabsBackground` refreshes the inline menu ciphers on `FillCipherPolicy.changed$`.
it.each(extensionMessages)("does not update the overlay ciphers for %s", (message) => {
sendMockExtensionMessage({ command: message });
expect(overlayBackground.updateOverlayCiphers).not.toHaveBeenCalled();
});
});

View File

@@ -87,6 +87,7 @@ import {
} from "../enums/autofill-overlay.enum";
import AutofillField from "../models/autofill-field";
import { AutofillService, PageDetail } from "../services/abstractions/autofill.service";
import { CipherUse, FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import { InlineMenuFieldQualificationService } from "../services/abstractions/inline-menu-field-qualifications.service";
import { didFillOccur, shouldAutoCopyTotp } from "../types/fill-result";
import {
@@ -233,13 +234,6 @@ export class OverlayBackground implements OverlayBackgroundInterface {
this.triggerDestroyInlineMenuListeners(tab, message.subFrameData?.frameId),
),
collectPageDetailsResponse: ({ message, sender }) => this.storePageDetails(message, sender),
doFullSync: () => this.updateOverlayCiphers(),
addedCipher: () => this.updateOverlayCiphers(),
addEditCipherSubmitted: () => this.updateOverlayCiphers(),
editedCipher: () => this.updateOverlayCiphers(),
deletedCipher: () => this.updateOverlayCiphers(),
bgSaveCipher: () => this.updateOverlayCiphers(),
updateOverlayCiphers: () => this.updateOverlayCiphers(),
fido2AbortRequest: ({ sender }) =>
void this.withSenderTab(sender, (tab) => this.abortFido2ActiveRequest(tab.id)),
routeTargetedFieldsToFrame: ({ message, sender }) =>
@@ -292,6 +286,7 @@ export class OverlayBackground implements OverlayBackgroundInterface {
/** Publishes the retry queued for after the unlock. */
private intraprocessMessageSender: IntraprocessMessageSender,
private messageListener: MessageListener,
private fillCipherPolicy: FillCipherPolicy,
) {
this.initOverlayEventObservables();
}
@@ -584,7 +579,11 @@ export class OverlayBackground implements OverlayBackgroundInterface {
}
const cipherViews = (
await this.cipherService.getAllDecryptedForUrl(currentTab.url || "", activeUserId)
await this.fillCipherPolicy.ciphersForUrl(
currentTab.url || "",
activeUserId,
CipherUse.UserFill,
)
).sort((a, b) => this.cipherService.sortCiphersByLastUsedThenName(a, b));
return this.cardAndIdentityCiphers
@@ -608,11 +607,9 @@ export class OverlayBackground implements OverlayBackgroundInterface {
this.cardAndIdentityCiphers.clear();
const cipherViews = (
await this.cipherService.getAllDecryptedForUrl(currentTab.url || "", userId, [
CipherType.Card,
CipherType.Identity,
CipherType.SshKey,
])
await this.fillCipherPolicy.ciphersForUrl(currentTab.url || "", userId, CipherUse.UserFill, {
includeOtherTypes: [CipherType.Card, CipherType.Identity, CipherType.SshKey],
})
).sort((a, b) => this.cipherService.sortCiphersByLastUsedThenName(a, b));
if (!this.cardAndIdentityCiphers) {
@@ -2999,6 +2996,20 @@ export class OverlayBackground implements OverlayBackgroundInterface {
try {
this.closeInlineMenu(sender);
const activeUserId = await firstValueFrom(this.accountService.activeAccount$.pipe(getUserId));
if (
login &&
cipherView.type === CipherType.Login &&
!(await this.fillCipherPolicy.canOfferSave(
{
uri: login.uri || sender.tab?.url || "",
username: login.username,
password: login.password,
},
activeUserId,
))
) {
cipherView.login.password = "";
}
await this.cipherService.setAddEditCipherInfo(
{
cipher: cipherView,

View File

@@ -1,6 +1,13 @@
import { mock } from "jest-mock-extended";
import { BehaviorSubject, map, Subject } from "rxjs";
import { Account, AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { UserId } from "@bitwarden/common/types/guid";
import MainBackground from "../../background/main.background";
import { FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import {
flushPromises,
triggerTabOnActivatedEvent,
@@ -15,7 +22,14 @@ import { OverlayBackground } from "./overlay.background";
import TabsBackground from "./tabs.background";
describe("TabsBackground", () => {
const userId = "user-1" as UserId;
const otherUserId = "user-2" as UserId;
let tabsBackground: TabsBackground;
let activeAccount$: BehaviorSubject<Account | null>;
let authStatuses$: BehaviorSubject<Record<UserId, AuthenticationStatus>>;
let changed: Record<UserId, Subject<void>>;
const fillCipherPolicy = mock<FillCipherPolicy>();
const mainBackground = mock<MainBackground>({
messagingService: {
send: jest.fn(),
@@ -25,6 +39,23 @@ describe("TabsBackground", () => {
const overlayBackground = mock<OverlayBackground>();
beforeEach(() => {
activeAccount$ = new BehaviorSubject<Account | null>({ id: userId } as Account);
authStatuses$ = new BehaviorSubject<Record<UserId, AuthenticationStatus>>({
[userId]: AuthenticationStatus.Unlocked,
[otherUserId]: AuthenticationStatus.Unlocked,
});
changed = { [userId]: new Subject<void>(), [otherUserId]: new Subject<void>() };
fillCipherPolicy.changed$.mockImplementation((id) => changed[id]);
const accountService = mock<AccountService>();
accountService.activeAccount$ = activeAccount$;
mainBackground.accountService = accountService;
const authService = mock<AuthService>();
authService.authStatusFor$.mockImplementation((id) =>
authStatuses$.pipe(map((statuses) => statuses[id])),
);
mainBackground.authService = authService;
mainBackground.fillCipherPolicy = fillCipherPolicy;
mainBackground.logService = mock<MainBackground["logService"]>();
tabsBackground = new TabsBackground(mainBackground, notificationBackground, overlayBackground);
});
@@ -47,6 +78,82 @@ describe("TabsBackground", () => {
});
});
describe("fill cipher changes", () => {
beforeEach(async () => {
jest.useFakeTimers();
void tabsBackground.init();
await jest.advanceTimersByTimeAsync(0);
jest.clearAllMocks();
});
afterEach(() => {
jest.useRealTimers();
});
const settle = () => jest.advanceTimersByTimeAsync(0);
it("refreshes the context menu and all inline menu ciphers on the first emission", async () => {
changed[userId].next();
await settle();
expect(mainBackground.refreshMenu).toHaveBeenCalledTimes(1);
expect(overlayBackground.updateOverlayCiphers).toHaveBeenCalledTimes(1);
expect(overlayBackground.updateOverlayCiphers).toHaveBeenCalledWith();
});
it("refreshes once for the emissions of one tick", async () => {
changed[userId].next();
changed[userId].next();
await settle();
expect(mainBackground.refreshMenu).toHaveBeenCalledTimes(1);
expect(overlayBackground.updateOverlayCiphers).toHaveBeenCalledTimes(1);
});
it("refreshes again for a later change", async () => {
changed[userId].next();
await settle();
changed[userId].next();
await settle();
expect(mainBackground.refreshMenu).toHaveBeenCalledTimes(2);
expect(overlayBackground.updateOverlayCiphers).toHaveBeenCalledTimes(2);
});
it("follows the active account", async () => {
activeAccount$.next({ id: otherUserId } as Account);
changed[userId].next();
await settle();
expect(mainBackground.refreshMenu).not.toHaveBeenCalled();
changed[otherUserId].next();
await settle();
expect(mainBackground.refreshMenu).toHaveBeenCalledTimes(1);
});
it("drops a change pending when the user locks", async () => {
changed[userId].next();
authStatuses$.next({ [userId]: AuthenticationStatus.Locked });
await settle();
expect(mainBackground.refreshMenu).not.toHaveBeenCalled();
expect(overlayBackground.updateOverlayCiphers).not.toHaveBeenCalled();
});
it("keeps refreshing after a refresh fails", async () => {
mainBackground.refreshMenu.mockRejectedValueOnce(new Error("failed"));
changed[userId].next();
await settle();
changed[userId].next();
await settle();
expect(mainBackground.logService.error).toHaveBeenCalledTimes(1);
expect(mainBackground.refreshMenu).toHaveBeenCalledTimes(2);
});
});
describe("tab event listeners", () => {
beforeEach(() => {
tabsBackground["setupTabEventListeners"]();

View File

@@ -1,3 +1,7 @@
import { concatMap, debounceTime, distinctUntilChanged, EMPTY, map, switchMap } from "rxjs";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import MainBackground from "../../background/main.background";
import { OverlayBackground } from "./abstractions/overlay.background";
@@ -22,6 +26,45 @@ export default class TabsBackground {
void this.updateCurrentTabData();
void this.setupTabEventListeners();
this.refreshOnFillCiphersChanged();
}
/**
* Rebuilds the context menu and the inline menu ciphers when the active user's fill ciphers
* change. This is the only refresh for cipher changes; it also fills both menus after an unlock
* and an account switch.
*/
private refreshOnFillCiphersChanged() {
this.main.accountService.activeAccount$
.pipe(
switchMap((account) =>
account == null
? EMPTY
: this.main.authService.authStatusFor$(account.id).pipe(
map((status) => status === AuthenticationStatus.Unlocked),
distinctUntilChanged(),
switchMap((unlocked) =>
unlocked
? this.main.fillCipherPolicy.changed$(account.id).pipe(
// Merges the emissions of one tick, such as the replays on subscribe.
debounceTime(0),
)
: EMPTY,
),
),
),
concatMap(async () => {
try {
await Promise.all([
this.main.refreshMenu(),
this.overlayBackground.updateOverlayCiphers(),
]);
} catch (error) {
this.main.logService.error(error);
}
}),
)
.subscribe();
}
/**

View File

@@ -20,6 +20,8 @@ import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { LoginUriView } from "@bitwarden/common/vault/models/view/login-uri.view";
import { LoginView } from "@bitwarden/common/vault/models/view/login.view";
import { CipherUse } from "../services/abstractions/fill-cipher-policy";
import { DefaultFillCipherPolicy } from "../services/default-fill-cipher-policy";
import { flushPromises } from "../spec/testing-utils";
import WebRequestBackground, {
@@ -43,6 +45,7 @@ describe("WebRequestBackground", () => {
let platformUtilsService: ReturnType<typeof mock<PlatformUtilsService>>;
let cipherService: ReturnType<typeof mock<CipherService>>;
let fillCipherPolicy: DefaultFillCipherPolicy;
let authService: ReturnType<typeof mock<AuthService>>;
let accountService: ReturnType<typeof mock<AccountService>>;
let autofillSettingsService: ReturnType<typeof mock<AutofillSettingsServiceAbstraction>>;
@@ -60,7 +63,7 @@ describe("WebRequestBackground", () => {
const createWebRequestBackground = () =>
new WebRequestBackground(
platformUtilsService,
cipherService,
fillCipherPolicy,
authService,
accountService,
webRequest as unknown as typeof chrome.webRequest,
@@ -86,6 +89,8 @@ describe("WebRequestBackground", () => {
platformUtilsService.isFirefox.mockReturnValue(false);
platformUtilsService.isSafari.mockReturnValue(false);
cipherService = mock<CipherService>();
fillCipherPolicy = new DefaultFillCipherPolicy(cipherService);
jest.spyOn(fillCipherPolicy, "ciphersForUrl");
authService = mock<AuthService>();
authService.authStatusFor$.mockReturnValue(of(AuthenticationStatus.Unlocked));
@@ -333,6 +338,12 @@ describe("WebRequestBackground", () => {
await triggerAuthRequired();
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
url,
userId,
CipherUse.AutomaticFill,
{ defaultMatch: UriMatchStrategy.Host },
);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(
url,
userId,

View File

@@ -19,9 +19,10 @@ import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { CipherUse, FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
const webRequestUrlFilter: chrome.webRequest.RequestFilter = {
urls: ["http://*/*", "https://*/*"],
};
@@ -215,7 +216,7 @@ export default class WebRequestBackground {
constructor(
platformUtilsService: PlatformUtilsService,
private cipherService: CipherService,
private fillCipherPolicy: FillCipherPolicy,
private authService: AuthService,
private accountService: AccountService,
private readonly webRequest: typeof chrome.webRequest,
@@ -387,11 +388,11 @@ export default class WebRequestBackground {
// The Host strategy is only applied to URIs using "Default", and logins with any such URI are
// removed by the eligibility filter below, so each remaining URI matched by its own strategy.
// Host is still passed so that a "Default" URI is never matched more loosely.
const ciphers = await this.cipherService.getAllDecryptedForUrl(
const ciphers = await this.fillCipherPolicy.ciphersForUrl(
details.url,
activeUserId,
undefined,
UriMatchStrategy.Host,
CipherUse.AutomaticFill,
{ defaultMatch: UriMatchStrategy.Host },
);
const eligibleCiphers = (ciphers ?? []).filter(isEligibleForHTTPAuthentication);

View File

@@ -8,6 +8,8 @@ import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.servi
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherRepromptType } from "@bitwarden/common/vault/enums/cipher-reprompt-type";
import { CipherUse, FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import { CipherContextMenuHandler } from "./cipher-context-menu-handler";
import { MainContextMenuHandler } from "./main-context-menu-handler";
@@ -15,6 +17,7 @@ describe("CipherContextMenuHandler", () => {
let mainContextMenuHandler: MockProxy<MainContextMenuHandler>;
let authService: MockProxy<AuthService>;
let cipherService: MockProxy<CipherService>;
let fillCipherPolicy: MockProxy<FillCipherPolicy>;
const mockUserId = "UserId" as UserId;
const accountService = mockAccountServiceWith(mockUserId);
@@ -26,6 +29,7 @@ describe("CipherContextMenuHandler", () => {
mainContextMenuHandler.initRunning = false;
authService = mock();
cipherService = mock();
fillCipherPolicy = mock();
jest.spyOn(MainContextMenuHandler, "removeAll").mockResolvedValue();
@@ -34,6 +38,7 @@ describe("CipherContextMenuHandler", () => {
authService,
cipherService,
accountService,
fillCipherPolicy,
);
});
@@ -81,7 +86,7 @@ describe("CipherContextMenuHandler", () => {
mainContextMenuHandler.init.mockResolvedValue(true);
cipherService.getAllDecryptedForUrl.mockResolvedValue([]);
fillCipherPolicy.ciphersForUrl.mockResolvedValue([]);
await sut.update("https://test.com");
@@ -116,7 +121,7 @@ describe("CipherContextMenuHandler", () => {
card: { username: "Test Username" },
};
cipherService.getAllDecryptedForUrl.mockResolvedValue([
fillCipherPolicy.ciphersForUrl.mockResolvedValue([
null, // invalid cipher
undefined, // invalid cipher
{ type: CipherType.SecureNote }, // invalid cipher
@@ -127,12 +132,13 @@ describe("CipherContextMenuHandler", () => {
await sut.update("https://test.com");
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledTimes(1);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledTimes(1);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
"https://test.com",
mockUserId,
[CipherType.Card, CipherType.Identity],
CipherUse.UserFill,
{ includeOtherTypes: [CipherType.Card, CipherType.Identity] },
);
expect(mainContextMenuHandler.loadOptions).toHaveBeenCalledTimes(3);

View File

@@ -9,6 +9,7 @@ import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.servi
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { CipherUse, FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import { AutofillCipherTypeId } from "../types";
import { MainContextMenuHandler } from "./main-context-menu-handler";
@@ -19,6 +20,7 @@ export class CipherContextMenuHandler {
private authService: AuthService,
private cipherService: CipherService,
private accountService: AccountService,
private fillCipherPolicy: FillCipherPolicy,
) {}
async update(url: string, currentUriIsBlocked: boolean = false) {
@@ -47,10 +49,14 @@ export class CipherContextMenuHandler {
return;
}
const ciphers = await this.cipherService.getAllDecryptedForUrl(url, activeUserId, [
CipherType.Card,
CipherType.Identity,
]);
const ciphers = await this.fillCipherPolicy.ciphersForUrl(
url,
activeUserId,
CipherUse.UserFill,
{
includeOtherTypes: [CipherType.Card, CipherType.Identity],
},
);
ciphers.sort((a, b) => this.cipherService.sortCiphersByLastUsedThenName(a, b));
const groupedCiphers: Record<AutofillCipherTypeId, CipherView[]> = ciphers.reduce(

View File

@@ -18,7 +18,6 @@ import { EventCollectionService } from "@bitwarden/common/dirt/event-logs";
import { IntraprocessMessageSender } from "@bitwarden/common/platform/messaging";
import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherRepromptType } from "@bitwarden/common/vault/enums/cipher-reprompt-type";
@@ -29,6 +28,7 @@ import { BrowserApi } from "../../platform/browser/browser-api";
import BrowserPopupUtils from "../../platform/browser/browser-popup-utils";
import AutofillPageDetails from "../models/autofill-page-details";
import { AutofillTriageService } from "../services/abstractions/autofill-triage.service";
import { CipherUse, FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import { WebmapperDraftService } from "../services/webmapper-draft.service";
import { AutofillTriageFieldResult } from "../types/autofill-triage";
import { emptyDraft, WebmapperDraft } from "../webmapper/draft";
@@ -87,7 +87,7 @@ describe("ContextMenuClickedHandler", () => {
let autofill: AutofillAction;
let collectAutofillTriage: jest.Mock<ReturnType<CollectAutofillTriageAction>, [number, number?]>;
let authService: MockProxy<AuthService>;
let cipherService: MockProxy<CipherService>;
let fillCipherPolicy: MockProxy<FillCipherPolicy>;
let accountService: FakeAccountService;
let totpService: MockProxy<TotpService>;
let eventCollectionService: MockProxy<EventCollectionService>;
@@ -104,7 +104,7 @@ describe("ContextMenuClickedHandler", () => {
autofill = jest.fn<Promise<void>, [tab: chrome.tabs.Tab, cipher: CipherView]>();
collectAutofillTriage = jest.fn<ReturnType<CollectAutofillTriageAction>, [number, number?]>();
authService = mock();
cipherService = mock();
fillCipherPolicy = mock();
accountService = mockAccountServiceWith(mockUserId as UserId);
totpService = mock();
eventCollectionService = mock();
@@ -119,7 +119,6 @@ describe("ContextMenuClickedHandler", () => {
autofill,
collectAutofillTriage,
authService,
cipherService,
totpService,
eventCollectionService,
userVerificationService,
@@ -127,6 +126,7 @@ describe("ContextMenuClickedHandler", () => {
triageService,
webmapperDrafts,
intraprocessMessageSender,
fillCipherPolicy,
);
});
@@ -154,7 +154,7 @@ describe("ContextMenuClickedHandler", () => {
data: createData(`${COPY_USERNAME_ID}_${NOOP_COMMAND_SUFFIX}`, COPY_USERNAME_ID),
tab: {} as any,
expectNotCalled: () => {
expect(cipherService.getAllDecryptedForUrl).not.toHaveBeenCalled();
expect(fillCipherPolicy.ciphersForUrl).not.toHaveBeenCalled();
expect(copyToClipboard).not.toHaveBeenCalled();
},
},
@@ -179,7 +179,7 @@ describe("ContextMenuClickedHandler", () => {
extra: () => expect(totpService.getCode$).not.toHaveBeenCalled(),
},
])("breaks silently when cipher is missing for $label", async ({ parentId, extra }) => {
cipherService.getAllDecrypted.mockResolvedValue([]);
fillCipherPolicy.ciphers.mockResolvedValue([]);
await expect(runWithUrl(createData(`${parentId}_1`, parentId))).resolves.toBeUndefined();
@@ -209,7 +209,7 @@ describe("ContextMenuClickedHandler", () => {
])("breaks silently when $label property is missing", async ({ parentId, unset, isTotp }) => {
const cipher = createCipher();
unset(cipher);
cipherService.getAllDecrypted.mockResolvedValue([cipher]);
fillCipherPolicy.ciphers.mockResolvedValue([cipher]);
await expect(runWithUrl(createData(`${parentId}_1`, parentId))).resolves.toBeUndefined();
@@ -232,7 +232,7 @@ describe("ContextMenuClickedHandler", () => {
it("attempts to autofill the correct cipher", async () => {
const cipher = createCipher();
cipherService.getAllDecrypted.mockResolvedValue([cipher]);
fillCipherPolicy.ciphers.mockResolvedValue([cipher]);
await sut.run(createData(`${AUTOFILL_ID}_1`, AUTOFILL_ID), { id: 5 } as any);
@@ -241,10 +241,16 @@ describe("ContextMenuClickedHandler", () => {
expect(autofill).toHaveBeenCalledWith({ id: 5 }, cipher);
});
it("looks up the cipher the user picked by id as a user fill", async () => {
fillCipherPolicy.ciphers.mockResolvedValue([createCipher()]);
await sut.run(createData(`${AUTOFILL_ID}_1`, AUTOFILL_ID), { id: 5 } as any);
expect(fillCipherPolicy.ciphers).toHaveBeenCalledWith(mockUserId, CipherUse.UserFill);
});
it("copies username to clipboard", async () => {
cipherService.getAllDecrypted.mockResolvedValue([
createCipher({ username: "TEST_USERNAME" }),
]);
fillCipherPolicy.ciphers.mockResolvedValue([createCipher({ username: "TEST_USERNAME" })]);
await sut.run(createData(`${COPY_USERNAME_ID}_1`, COPY_USERNAME_ID), {
url: "https://test.com",
@@ -259,9 +265,7 @@ describe("ContextMenuClickedHandler", () => {
});
it("copies password to clipboard", async () => {
cipherService.getAllDecrypted.mockResolvedValue([
createCipher({ password: "TEST_PASSWORD" }),
]);
fillCipherPolicy.ciphers.mockResolvedValue([createCipher({ password: "TEST_PASSWORD" })]);
await sut.run(createData(`${COPY_PASSWORD_ID}_1`, COPY_PASSWORD_ID), {
url: "https://test.com",
@@ -276,7 +280,7 @@ describe("ContextMenuClickedHandler", () => {
});
it("copies totp code to clipboard", async () => {
cipherService.getAllDecrypted.mockResolvedValue([createCipher({ totp: "TEST_TOTP_SEED" })]);
fillCipherPolicy.ciphers.mockResolvedValue([createCipher({ totp: "TEST_TOTP_SEED" })]);
jest.spyOn(totpService, "getCode$").mockImplementation((seed: string) => {
if (seed === "TEST_TOTP_SEED") {
@@ -305,7 +309,7 @@ describe("ContextMenuClickedHandler", () => {
});
it("attempts to find a cipher when noop but unlocked", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
fillCipherPolicy.ciphersForUrl.mockResolvedValue([
{
...createCipher({ username: "NOOP_USERNAME" }),
reprompt: CipherRepromptType.None,
@@ -316,12 +320,13 @@ describe("ContextMenuClickedHandler", () => {
url: "https://test.com",
} as any);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledTimes(1);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledTimes(1);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
"https://test.com",
mockUserId,
[],
CipherUse.UserFill,
{ includeOtherTypes: [] },
);
expect(copyToClipboard).toHaveBeenCalledTimes(1);
@@ -333,7 +338,7 @@ describe("ContextMenuClickedHandler", () => {
});
it("attempts to find a cipher when noop but unlocked", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
fillCipherPolicy.ciphersForUrl.mockResolvedValue([
{
...createCipher({ username: "NOOP_USERNAME" }),
reprompt: CipherRepromptType.Password,
@@ -344,12 +349,13 @@ describe("ContextMenuClickedHandler", () => {
url: "https://test.com",
} as any);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledTimes(1);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledTimes(1);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(
"https://test.com",
mockUserId,
[],
CipherUse.UserFill,
{ includeOtherTypes: [] },
);
});

View File

@@ -23,7 +23,6 @@ import {
} from "@bitwarden/common/autofill/constants";
import { EventCollectionService, EventType } from "@bitwarden/common/dirt/event-logs";
import { IntraprocessMessageSender } from "@bitwarden/common/platform/messaging";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherRepromptType } from "@bitwarden/common/vault/enums/cipher-reprompt-type";
@@ -46,6 +45,7 @@ import {
RETRY_SENDER,
} from "../background/abstractions/notification.background";
import { AutofillTriageService } from "../services/abstractions/autofill-triage.service";
import { CipherUse, FillCipherPolicy } from "../services/abstractions/fill-cipher-policy";
import { WebmapperDraftService } from "../services/webmapper-draft.service";
import { AutofillCipherTypeId } from "../types";
import {
@@ -110,7 +110,6 @@ export class ContextMenuClickedHandler {
private autofillAction: AutofillAction,
private collectAutofillTriage: CollectAutofillTriageAction,
private authService: AuthService,
private cipherService: CipherService,
private totpService: TotpService,
private eventCollectionService: EventCollectionService,
private userVerificationService: UserVerificationService,
@@ -118,6 +117,7 @@ export class ContextMenuClickedHandler {
private triageService: AutofillTriageService,
private webmapperDrafts: WebmapperDraftService,
private intraprocessMessageSender: IntraprocessMessageSender,
private fillCipherPolicy: FillCipherPolicy,
) {}
async run(info: chrome.contextMenus.OnClickData, tab: chrome.tabs.Tab) {
@@ -202,15 +202,16 @@ export class ContextMenuClickedHandler {
// This NOOP item has come through which is generally only for no access state but since we got here
// we are actually unlocked we will do our best to find a good match of an item to autofill this is useful
// in scenarios like unlock on autofill
const ciphers = await this.cipherService.getAllDecryptedForUrl(
const ciphers = await this.fillCipherPolicy.ciphersForUrl(
tab.url,
activeUserId,
additionalCiphersToGet,
CipherUse.UserFill,
{ includeOtherTypes: additionalCiphersToGet },
);
cipher = ciphers[0];
} else {
const ciphers = await this.cipherService.getAllDecrypted(activeUserId);
const ciphers = await this.fillCipherPolicy.ciphers(activeUserId, CipherUse.UserFill);
cipher = ciphers.find(({ id }) => id === menuItemId);
}

View File

@@ -54,6 +54,7 @@ import {
BrowserFido2UserInterfaceSession,
BrowserFido2MessageTypes,
} from "../../fido2/services/browser-fido2-user-interface.service";
import { CipherUse, FillCipherPolicy } from "../../services/abstractions/fill-cipher-policy";
import { Fido2CipherRowComponent } from "./fido2-cipher-row.component";
import { Fido2UseBrowserLinkComponent } from "./fido2-use-browser-link.component";
@@ -126,6 +127,7 @@ export class Fido2Component implements OnInit, OnDestroy {
private browserMessagingApi: ZonedMessageListenerService,
private passwordRepromptService: PasswordRepromptService,
private accountService: AccountService,
private fillCipherPolicy: FillCipherPolicy,
) {}
ngOnInit() {
@@ -194,9 +196,9 @@ export class Fido2Component implements OnInit, OnDestroy {
const activeUserId = await firstValueFrom(
this.accountService.activeAccount$.pipe(getUserId),
);
this.ciphers = (await this.cipherService.getAllDecrypted(activeUserId)).filter(
(cipher) => cipher.type === CipherType.Login && !cipher.isDeleted,
);
this.ciphers = (
await this.fillCipherPolicy.ciphers(activeUserId, CipherUse.Passkey)
).filter((cipher) => cipher.type === CipherType.Login && !cipher.isDeleted);
this.displayedCiphers = this.ciphers.filter(
(cipher) =>

View File

@@ -0,0 +1,68 @@
import { Observable } from "rxjs";
import { UriMatchStrategySetting } from "@bitwarden/common/models/domain/domain-service";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
/** Why Autofill looks up ciphers. A policy can give each use a different set of ciphers. */
export const CipherUse = Object.freeze({
/** The user picked a cipher or ran a command: inline menu, context menu, keyboard shortcut, popup fill. */
UserFill: "userFill",
/** Bitwarden starts the fill: page-load fill, auto-submit, HTTP basic auth. */
AutomaticFill: "automaticFill",
/** An add or update prompt: match the submitted form, show the ciphers in the prompt. */
SavePrompt: "savePrompt",
/** At-risk password tasks for the URL. */
SecurityTask: "securityTask",
/** Passkey registration and selection. */
Passkey: "passkey",
/** The toolbar badge count. */
Badge: "badge",
} as const);
export type CipherUse = (typeof CipherUse)[keyof typeof CipherUse];
/** The login form Autofill would offer to save. */
export type SaveCandidate = {
uri: string;
username?: string;
password?: string;
newPassword?: string;
};
/** The ciphers Autofill may use. Every cipher lookup in Autofill goes through it. */
export abstract class FillCipherPolicy {
/** Emits when a lookup result can change. A cached result must recompute. */
abstract changed$(userId: UserId): Observable<void>;
abstract ciphers(userId: UserId, use: CipherUse): Promise<CipherView[]>;
abstract ciphersForUrl(
url: string,
userId: UserId,
use: CipherUse,
options?: { includeOtherTypes?: CipherType[]; defaultMatch?: UriMatchStrategySetting },
): Promise<CipherView[]>;
/** For automatic fills. */
abstract lastLaunchedForUrl(
url: string,
userId: UserId,
autofillOnPageLoad: boolean,
): Promise<CipherView | undefined>;
/** For automatic fills. */
abstract lastUsedForUrl(
url: string,
userId: UserId,
autofillOnPageLoad: boolean,
): Promise<CipherView | undefined>;
/** The next cipher in the keyboard shortcut rotation. Always a user fill. */
abstract nextCipherForUrl(url: string, userId: UserId): Promise<CipherView | undefined>;
/** The next card in the card keyboard shortcut rotation. Always a user fill. */
abstract nextCardCipher(userId: UserId): Promise<CipherView | undefined>;
/** The next identity in the identity keyboard shortcut rotation. Always a user fill. */
abstract nextIdentityCipher(userId: UserId): Promise<CipherView | undefined>;
abstract advanceRotation(url: string): void;
/**
* False when Autofill must not copy this form into a new or updated cipher. Call it before a
* save prompt, before a save, and before a draft that takes values from the page.
*/
abstract canOfferSave(form: SaveCandidate, userId: UserId): Promise<boolean>;
}

View File

@@ -0,0 +1,122 @@
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject, Observable, Subject, Subscription } from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { BadgeSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/badge-settings.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { Tab } from "../../platform/badge/badge-browser-api";
import { BadgeService } from "../../platform/badge/badge.service";
import { BadgeStatePriority } from "../../platform/badge/priority";
import { flushPromises } from "../spec/testing-utils";
import { CipherUse, FillCipherPolicy } from "./abstractions/fill-cipher-policy";
import { AutofillBadgeUpdaterService } from "./autofill-badge-updater.service";
describe("AutofillBadgeUpdaterService", () => {
const userId = "user-1" as UserId;
const tab: Tab = { tabId: 1, url: "https://example.com" };
let setState: jest.Mock;
let activeAccount$: BehaviorSubject<{ id: UserId } | null>;
let enableBadgeCounter$: BehaviorSubject<boolean>;
let changed$: Subject<void>;
let fillCipherPolicy: MockProxy<FillCipherPolicy>;
let emissions: unknown[];
let subscription: Subscription;
const subscribeToBadgeState = () => {
const stateFunction = setState.mock.calls[0][1] as (tab: Tab) => Observable<unknown>;
subscription = stateFunction(tab).subscribe((state) => emissions.push(state));
};
beforeEach(() => {
setState = jest.fn();
activeAccount$ = new BehaviorSubject<{ id: UserId } | null>({ id: userId });
enableBadgeCounter$ = new BehaviorSubject(true);
changed$ = new Subject<void>();
fillCipherPolicy = mock<FillCipherPolicy>();
fillCipherPolicy.changed$.mockReturnValue(changed$);
fillCipherPolicy.ciphersForUrl.mockResolvedValue([mock<CipherView>(), mock<CipherView>()]);
emissions = [];
new AutofillBadgeUpdaterService(
{ setState } as unknown as BadgeService,
{ activeAccount$ } as unknown as AccountService,
fillCipherPolicy,
{ enableBadgeCounter$ } as unknown as BadgeSettingsServiceAbstraction,
mock<LogService>(),
).init();
});
afterEach(() => {
subscription?.unsubscribe();
});
it("registers its state function on init", () => {
expect(setState).toHaveBeenCalledWith("autofill-badge-updater", expect.any(Function));
});
it("counts the badge ciphers for the tab URL when the policy reports a change", async () => {
subscribeToBadgeState();
changed$.next();
await flushPromises();
expect(fillCipherPolicy.changed$).toHaveBeenCalledWith(userId);
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledWith(tab.url, userId, CipherUse.Badge);
expect(emissions).toEqual([{ state: { text: "2" }, priority: BadgeStatePriority.Default }]);
});
it("recounts on every policy change", async () => {
subscribeToBadgeState();
changed$.next();
await flushPromises();
fillCipherPolicy.ciphersForUrl.mockResolvedValueOnce([]);
changed$.next();
await flushPromises();
expect(fillCipherPolicy.ciphersForUrl).toHaveBeenCalledTimes(2);
expect(emissions).toEqual([
{ state: { text: "2" }, priority: BadgeStatePriority.Default },
{ state: { text: undefined }, priority: BadgeStatePriority.Default },
]);
});
it("shows 9+ for more than nine ciphers", async () => {
fillCipherPolicy.ciphersForUrl.mockResolvedValue(
Array.from({ length: 10 }, () => mock<CipherView>()),
);
subscribeToBadgeState();
changed$.next();
await flushPromises();
expect(emissions).toEqual([{ state: { text: "9+" }, priority: BadgeStatePriority.Default }]);
});
it("does not count when the badge counter is disabled", async () => {
enableBadgeCounter$.next(false);
subscribeToBadgeState();
changed$.next();
await flushPromises();
expect(fillCipherPolicy.ciphersForUrl).not.toHaveBeenCalled();
expect(emissions).toEqual([undefined]);
});
it("does not ask the policy without an active account", async () => {
activeAccount$.next(null);
subscribeToBadgeState();
await flushPromises();
expect(fillCipherPolicy.changed$).not.toHaveBeenCalled();
expect(fillCipherPolicy.ciphersForUrl).not.toHaveBeenCalled();
expect(emissions).toEqual([undefined]);
});
});

View File

@@ -1,29 +1,32 @@
import { combineLatest, delay, distinctUntilChanged, mergeMap, of, switchMap } from "rxjs";
import { combineLatest, distinctUntilChanged, mergeMap, of, switchMap } from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { BadgeSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/badge-settings.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { Tab } from "../../platform/badge/badge-browser-api";
import { BadgeService } from "../../platform/badge/badge.service";
import { BadgeStatePriority } from "../../platform/badge/priority";
import { CipherUse, FillCipherPolicy } from "./abstractions/fill-cipher-policy";
const StateName = "autofill-badge-updater";
export class AutofillBadgeUpdaterService {
constructor(
private badgeService: BadgeService,
private accountService: AccountService,
private cipherService: CipherService,
private fillCipherPolicy: FillCipherPolicy,
private badgeSettingsService: BadgeSettingsServiceAbstraction,
private logService: LogService,
) {}
init() {
const ciphers$ = this.accountService.activeAccount$.pipe(
switchMap((account) => (account?.id ? this.cipherService.ciphers$(account?.id) : of([]))),
const ciphersChanged$ = this.accountService.activeAccount$.pipe(
switchMap((account) =>
account?.id ? this.fillCipherPolicy.changed$(account.id) : of(undefined),
),
);
this.badgeService.setState(StateName, (tab) => {
@@ -31,7 +34,7 @@ export class AutofillBadgeUpdaterService {
account: this.accountService.activeAccount$,
enableBadgeCounter:
this.badgeSettingsService.enableBadgeCounter$.pipe(distinctUntilChanged()),
ciphers: ciphers$.pipe(delay(100)), // Delay to allow cipherService.getAllDecryptedForUrl to pick up changes
ciphersChanged: ciphersChanged$,
}).pipe(
mergeMap(async ({ account, enableBadgeCounter }) => {
if (!account || !enableBadgeCounter) {
@@ -55,7 +58,9 @@ export class AutofillBadgeUpdaterService {
return;
}
const ciphers = tab.url ? await this.cipherService.getAllDecryptedForUrl(tab.url, userId) : [];
const ciphers = tab.url
? await this.fillCipherPolicy.ciphersForUrl(tab.url, userId, CipherUse.Badge)
: [];
const cipherCount = ciphers.length;
if (cipherCount === 0) {

View File

@@ -0,0 +1,121 @@
import { mock, MockProxy } from "jest-mock-extended";
import { firstValueFrom, Subject, toArray } from "rxjs";
import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { CipherUse } from "./abstractions/fill-cipher-policy";
import { DefaultFillCipherPolicy } from "./default-fill-cipher-policy";
describe("DefaultFillCipherPolicy", () => {
const userId = "user-id" as UserId;
const url = "https://example.com";
let cipherService: MockProxy<CipherService>;
let policy: DefaultFillCipherPolicy;
const view = (id: string) => Object.assign(new CipherView(), { id });
beforeEach(() => {
cipherService = mock<CipherService>();
policy = new DefaultFillCipherPolicy(cipherService);
});
it("emits changed$ after each decryption and not while decryption is in progress", async () => {
const cipherViews$ = new Subject<CipherView[] | null>();
cipherService.cipherViews$.mockReturnValue(cipherViews$);
const emitted = firstValueFrom(policy.changed$(userId).pipe(toArray()));
cipherViews$.next([view("a")]);
cipherViews$.next(null);
cipherViews$.next([view("b")]);
cipherViews$.complete();
expect(await emitted).toEqual([undefined, undefined]);
expect(cipherService.cipherViews$).toHaveBeenCalledWith(userId);
});
it.each(Object.values(CipherUse))("returns the stored ciphers for %s", async (use) => {
const stored = [view("stored")];
cipherService.getAllDecrypted.mockResolvedValue(stored);
expect(await policy.ciphers(userId, use)).toBe(stored);
});
it("passes the URL options to the stored lookup", async () => {
const stored = [view("stored")];
cipherService.getAllDecryptedForUrl.mockResolvedValue(stored);
const ciphers = await policy.ciphersForUrl(url, userId, CipherUse.AutomaticFill, {
includeOtherTypes: [CipherType.Card],
defaultMatch: UriMatchStrategy.Host,
});
expect(ciphers).toBe(stored);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(
url,
userId,
[CipherType.Card],
UriMatchStrategy.Host,
);
});
it.each([
["lastLaunchedForUrl", "getLastLaunchedForUrl"],
["lastUsedForUrl", "getLastUsedForUrl"],
] as const)("%s returns undefined for no match", async (method, delegate) => {
cipherService[delegate].mockResolvedValue(null);
expect(await policy[method](url, userId, true)).toBeUndefined();
expect(cipherService[delegate]).toHaveBeenCalledWith(url, userId, true);
});
it("returns the next cipher of the stored rotation", async () => {
const next = view("next");
cipherService.getNextCipherForUrl.mockResolvedValue(next);
expect(await policy.nextCipherForUrl(url, userId)).toBe(next);
});
it("returns undefined when the stored rotation is empty", async () => {
cipherService.getNextCipherForUrl.mockResolvedValue(null);
expect(await policy.nextCipherForUrl(url, userId)).toBeUndefined();
});
it.each([
["nextCardCipher", "getNextCardCipher"],
["nextIdentityCipher", "getNextIdentityCipher"],
] as const)("%s returns the next cipher of the stored rotation", async (method, delegate) => {
const next = view("next");
cipherService[delegate].mockResolvedValue(next);
expect(await policy[method](userId)).toBe(next);
expect(cipherService[delegate]).toHaveBeenCalledWith(userId);
});
it.each([
["nextCardCipher", "getNextCardCipher"],
["nextIdentityCipher", "getNextIdentityCipher"],
] as const)(
"%s returns undefined when the stored rotation is empty",
async (method, delegate) => {
cipherService[delegate].mockResolvedValue(null);
expect(await policy[method](userId)).toBeUndefined();
},
);
it("advances the stored rotation", () => {
policy.advanceRotation(url);
expect(cipherService.updateLastUsedIndexForUrl).toHaveBeenCalledWith(url);
});
it("always offers to save", async () => {
expect(await policy.canOfferSave({ uri: url, username: "user" }, userId)).toBe(true);
});
});

View File

@@ -0,0 +1,80 @@
import { filter, map, Observable } from "rxjs";
import { UriMatchStrategySetting } from "@bitwarden/common/models/domain/domain-service";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { CipherUse, FillCipherPolicy, SaveCandidate } from "./abstractions/fill-cipher-policy";
/** Gives every use the stored ciphers from {@link CipherService}. */
export class DefaultFillCipherPolicy implements FillCipherPolicy {
constructor(protected readonly cipherService: CipherService) {}
/** Emits after each decryption, so a lookup that follows reads the new ciphers. */
changed$(userId: UserId): Observable<void> {
return this.cipherService.cipherViews$(userId).pipe(
filter((views) => views != null),
map((): void => undefined),
);
}
ciphers(userId: UserId, use: CipherUse): Promise<CipherView[]> {
return this.cipherService.getAllDecrypted(userId);
}
ciphersForUrl(
url: string,
userId: UserId,
use: CipherUse,
options?: { includeOtherTypes?: CipherType[]; defaultMatch?: UriMatchStrategySetting },
): Promise<CipherView[]> {
return this.cipherService.getAllDecryptedForUrl(
url,
userId,
options?.includeOtherTypes,
options?.defaultMatch,
);
}
async lastLaunchedForUrl(
url: string,
userId: UserId,
autofillOnPageLoad: boolean,
): Promise<CipherView | undefined> {
return (
(await this.cipherService.getLastLaunchedForUrl(url, userId, autofillOnPageLoad)) ?? undefined
);
}
async lastUsedForUrl(
url: string,
userId: UserId,
autofillOnPageLoad: boolean,
): Promise<CipherView | undefined> {
return (
(await this.cipherService.getLastUsedForUrl(url, userId, autofillOnPageLoad)) ?? undefined
);
}
async nextCipherForUrl(url: string, userId: UserId): Promise<CipherView | undefined> {
return (await this.cipherService.getNextCipherForUrl(url, userId)) ?? undefined;
}
async nextCardCipher(userId: UserId): Promise<CipherView | undefined> {
return (await this.cipherService.getNextCardCipher(userId)) ?? undefined;
}
async nextIdentityCipher(userId: UserId): Promise<CipherView | undefined> {
return (await this.cipherService.getNextIdentityCipher(userId)) ?? undefined;
}
advanceRotation(url: string): void {
this.cipherService.updateLastUsedIndexForUrl(url);
}
async canOfferSave(form: SaveCandidate, userId: UserId): Promise<boolean> {
return true;
}
}

View File

@@ -367,11 +367,13 @@ import {
} from "../autofill/fido2/services/browser-fido2-user-interface.service";
import { AutofillLifecycleService } from "../autofill/services/abstractions/autofill-lifecycle.service";
import { AutofillService as AutofillServiceAbstraction } from "../autofill/services/abstractions/autofill.service";
import { FillCipherPolicy } from "../autofill/services/abstractions/fill-cipher-policy";
import { AutofillBadgeUpdaterService } from "../autofill/services/autofill-badge-updater.service";
import { DefaultAutofillLifecycleService } from "../autofill/services/autofill-lifecycle.service";
import { AutofillTriageService } from "../autofill/services/autofill-triage.service";
import AutofillService from "../autofill/services/autofill.service";
import { ClipboardNotificationBadgeUpdaterService } from "../autofill/services/clipboard-notification-badge-updater.service";
import { DefaultFillCipherPolicy } from "../autofill/services/default-fill-cipher-policy";
import { InlineMenuFieldQualificationService } from "../autofill/services/inline-menu-field-qualification.service";
import { TargetingRulesDataService } from "../autofill/services/targeting-rules-data.service";
import { WebmapperDraftService } from "../autofill/services/webmapper-draft.service";
@@ -452,6 +454,7 @@ export default class MainBackground {
environmentService: BrowserEnvironmentService;
cipherSdkService: CipherSdkService;
revealedCipherService: RevealedCipherService;
fillCipherPolicy: FillCipherPolicy;
cipherService: CipherServiceAbstraction;
folderService: InternalFolderServiceAbstraction;
userDecryptionOptionsService: InternalUserDecryptionOptionsServiceAbstraction;
@@ -621,7 +624,13 @@ export default class MainBackground {
private phishingDetectionSettingsService: PhishingDetectionSettingsServiceAbstraction;
private phishingDetectionService: PhishingDetectionService;
constructor() {
/** @param overrides Services the commercial build supplies in place of the OSS defaults. */
constructor(overrides?: {
fillCipherPolicy?: (deps: {
cipherService: CipherServiceAbstraction;
revealedCipherService: RevealedCipherService;
}) => FillCipherPolicy;
}) {
// Downstream services receive this callback and invoke it directly instead of
// going through LogoutService, so the log line that lives in DefaultLogoutService
// is mirrored here to cover this path.
@@ -1220,6 +1229,11 @@ export default class MainBackground {
this.messagingService,
this.cipherSdkService,
);
this.fillCipherPolicy =
overrides?.fillCipherPolicy?.({
cipherService: this.cipherService,
revealedCipherService: this.revealedCipherService,
}) ?? new DefaultFillCipherPolicy(this.cipherService);
this.folderService = new FolderService(
this.keyService,
this.encryptService,
@@ -1365,12 +1379,12 @@ export default class MainBackground {
this.autofillOrchestrator = new DefaultAutofillOrchestrator(
this.autofillLifecycleService,
this.autofillService,
this.cipherService,
this.autofillSettingsService,
this.accountService,
this.platformUtilsService,
() => this.updateOverlayCiphers(),
this.logService,
this.fillCipherPolicy,
);
this.auditService = new AuditService(
this.cryptoFunctionService,
@@ -1674,11 +1688,14 @@ export default class MainBackground {
this.fido2Background,
this.#intraprocessMessageSender,
this.messageListener,
this.fillCipherPolicy,
);
this.overlayNotificationsBackground = new OverlayNotificationsBackground(
this.logService,
this.notificationBackground,
this.accountService,
this.fillCipherPolicy,
);
this.autoSubmitLoginBackground = new AutoSubmitLoginBackground(
@@ -1715,7 +1732,6 @@ export default class MainBackground {
},
(tabId, frameId) => this.autofillOrchestrator.collectAutofillTriage(tabId, frameId),
this.authService,
this.cipherService,
this.totpService,
this.eventCollectionService,
this.userVerificationService,
@@ -1723,6 +1739,7 @@ export default class MainBackground {
this.autofillTriageService,
new WebmapperDraftService(this.stateProvider),
this.#intraprocessMessageSender,
this.fillCipherPolicy,
);
this.contextMenusBackground = new ContextMenusBackground(
@@ -1766,12 +1783,13 @@ export default class MainBackground {
this.authService,
this.cipherService,
this.accountService,
this.fillCipherPolicy,
);
if (chrome.webRequest != null && chrome.webRequest.onAuthRequired != null) {
this.webRequestBackground = new WebRequestBackground(
this.platformUtilsService,
this.cipherService,
this.fillCipherPolicy,
this.authService,
this.accountService,
chrome.webRequest,
@@ -2037,8 +2055,6 @@ export default class MainBackground {
this.messagingService.send("locked", { userId: userId });
} else {
this.messagingService.send("unlocked", { userId: userId });
await this.refreshMenu();
await this.updateOverlayCiphers();
await this.syncService.fullSync(false);
}
} finally {
@@ -2350,12 +2366,13 @@ export default class MainBackground {
this.configService,
this.#intraprocessMessageSender,
this.messageListener,
this.fillCipherPolicy,
);
this.autofillBadgeUpdaterService = new AutofillBadgeUpdaterService(
this.badgeService,
this.accountService,
this.cipherService,
this.fillCipherPolicy,
this.badgeSettingsService,
this.logService,
);

View File

@@ -14,7 +14,6 @@ import { LogService } from "@bitwarden/common/platform/abstractions/log.service"
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { Message, IntraprocessMessageSender } from "@bitwarden/common/platform/messaging";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { VaultMessages } from "@bitwarden/common/vault/enums/vault-messages.enum";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
@@ -40,6 +39,7 @@ import { AutofillMessageCommand } from "../autofill/enums/autofill-message.enums
import { AutofillOutcome } from "../autofill/enums/autofill-outcome.enum";
import { AutofillLifecycleService } from "../autofill/services/abstractions/autofill-lifecycle.service";
import { AutofillService, PageDetail } from "../autofill/services/abstractions/autofill.service";
import { CipherUse, FillCipherPolicy } from "../autofill/services/abstractions/fill-cipher-policy";
import { createChromeTabMock } from "../autofill/spec/autofill-mocks";
import { crossContextBoundary, tagAsExternalMessage } from "../autofill/spec/testing-utils";
import { BrowserApi } from "../platform/browser/browser-api";
@@ -215,13 +215,13 @@ describe("RuntimeBackground collection dispatch", () => {
describe("fillCipherForPopup", () => {
const cipher = Object.assign(new CipherView(), { id: "cipher-1" });
let cipherService: MockProxy<CipherService>;
let fillCipherPolicy: MockProxy<FillCipherPolicy>;
beforeEach(() => {
jest.spyOn(BrowserApi, "getTab").mockResolvedValue(tab);
cipherService = mock<CipherService>();
cipherService.getAllDecrypted.mockResolvedValue([cipher]);
(main as any).cipherService = cipherService;
fillCipherPolicy = mock<FillCipherPolicy>();
fillCipherPolicy.ciphers.mockResolvedValue([cipher]);
(main as any).fillCipherPolicy = fillCipherPolicy;
autofillOrchestrator.unsafeAutofillTabWithCipher.mockResolvedValue({
outcome: AutofillOutcome.Filled,
totp: "totp-123",
@@ -238,6 +238,15 @@ describe("RuntimeBackground collection dispatch", () => {
expect(result).toEqual({ outcome: AutofillOutcome.Filled, totp: "totp-123" });
});
it("looks up the cipher as a user fill", async () => {
await runtimeBackground.processMessageWithSender(
{ command: "fillCipherForPopup", tabId: 1, tabUrl: tab.url, cipherId: "cipher-1" },
popupSender,
);
expect(fillCipherPolicy.ciphers).toHaveBeenCalledWith("user-1", CipherUse.UserFill);
});
it("security: rejects a content-script sender without fetching or filling", async () => {
// Assert the handler consults `BrowserApi.senderIsInternal`, so that the boundary cannot be silently
// removed without this failing. The spy calls through to detect regressions inside the guard.
@@ -252,7 +261,7 @@ describe("RuntimeBackground collection dispatch", () => {
// Logging the rejection is part of the security requirement: the warning is the
// observable record that the boundary fired on this sender.
expect(logService.warning).toHaveBeenCalled();
expect(cipherService.getAllDecrypted).not.toHaveBeenCalled();
expect(fillCipherPolicy.ciphers).not.toHaveBeenCalled();
expect(autofillOrchestrator.unsafeAutofillTabWithCipher).not.toHaveBeenCalled();
});

View File

@@ -44,6 +44,7 @@ import { completePendingDefaultPasswordManagerApply } from "../autofill/default-
import { AutofillMessageCommand } from "../autofill/enums/autofill-message.enums";
import { AutofillLifecycleService } from "../autofill/services/abstractions/autofill-lifecycle.service";
import { AutofillService } from "../autofill/services/abstractions/autofill.service";
import { CipherUse } from "../autofill/services/abstractions/fill-cipher-policy";
import { FORCE_TARGETING_RULES_UPDATE_COMMAND } from "../autofill/services/targeting-rules-data.service";
import { AUTOFILL_DENIED } from "../autofill/types/fill-result";
import { getSubFrameUrlVariations } from "../autofill/utils/url-variations";
@@ -197,7 +198,7 @@ export default class RuntimeBackground {
if (activeUserId == null) {
return AUTOFILL_DENIED;
}
const ciphers = await this.main.cipherService.getAllDecrypted(activeUserId);
const ciphers = await this.main.fillCipherPolicy.ciphers(activeUserId, CipherUse.UserFill);
const cipher = ciphers.find((candidate) => candidate.id === msg.cipherId);
if (cipher == null) {
return AUTOFILL_DENIED;
@@ -495,12 +496,7 @@ export default class RuntimeBackground {
break;
case "syncCompleted":
if (msg.successfully) {
setTimeout(async () => {
await this.main.refreshMenu();
}, 2000);
await this.configService.ensureConfigFetched();
await this.main.updateOverlayCiphers();
await this.autofillService.setAutoFillOnPageLoadOrgPolicy();
}
break;
@@ -527,9 +523,6 @@ export default class RuntimeBackground {
break;
}
case "bgUpdateContextMenu":
case "editedCipher":
case "addedCipher":
case "deletedCipher":
await this.main.refreshMenu();
break;
case "bgReseedStorage": {

View File

@@ -213,7 +213,9 @@ import { ExtensionTwoFactorAuthDuoComponentService } from "../../auth/services/e
import { ExtensionTwoFactorAuthWebAuthnComponentService } from "../../auth/services/extension-two-factor-auth-webauthn-component.service";
import { AutofillLifecycleService } from "../../autofill/services/abstractions/autofill-lifecycle.service";
import { AutofillService as AutofillServiceAbstraction } from "../../autofill/services/abstractions/autofill.service";
import { FillCipherPolicy } from "../../autofill/services/abstractions/fill-cipher-policy";
import AutofillService from "../../autofill/services/autofill.service";
import { DefaultFillCipherPolicy } from "../../autofill/services/default-fill-cipher-policy";
import { InlineMenuFieldQualificationService } from "../../autofill/services/inline-menu-field-qualification.service";
import { NoopAutofillLifecycleService } from "../../autofill/services/noop-autofill-lifecycle.service";
import { WebmapperDraftService } from "../../autofill/services/webmapper-draft.service";
@@ -472,6 +474,11 @@ const safeProviders: SafeProvider[] = [
useClass: NoopAutofillLifecycleService,
deps: [LogService],
}),
safeProvider({
provide: FillCipherPolicy,
useClass: DefaultFillCipherPolicy,
deps: [CipherService],
}),
safeProvider({
provide: AutofillService,
deps: [

View File

@@ -294,20 +294,7 @@ export default tseslint.config(
rules: {
"no-restricted-syntax": [
"error",
{
message:
"Using addListener in the browser popup produces a memory leak in Safari, use `BrowserApi.addListener` instead",
// This selector covers events like chrome.storage.onChange & chrome.runtime.onMessage
selector:
"CallExpression > [object.object.object.name='chrome'][property.name='addListener']",
},
{
message:
"Using addListener in the browser popup produces a memory leak in Safari, use `BrowserApi.addListener` instead",
// This selector covers events like chrome.storage.local.onChange
selector:
"CallExpression > [object.object.object.object.name='chrome'][property.name='addListener']",
},
...safariAddListenerSyntaxRules(),
// This block owns the non-background browser files; the background block below covers the rest, so
// together they follow these methods everywhere without a third, colliding `no-restricted-syntax` block.
doAutoFillSyntaxRule(),
@@ -329,6 +316,52 @@ export default tseslint.config(
],
},
},
// Autofill reads ciphers only through `FillCipherPolicy`. A later block replaces the
// `no-restricted-syntax` options of an earlier one, so these blocks repeat the entries of the two
// blocks above for the same Autofill files and add `fillCipherPolicySyntaxRules`.
{
files: ["apps/browser/src/autofill/**/*.ts"],
ignores: [
"apps/browser/src/autofill/services/default-fill-cipher-policy.ts", // The policy wraps `CipherService`.
"apps/browser/src/**/*.spec.ts",
],
rules: {
"no-restricted-syntax": ["error", ...fillCipherPolicySyntaxRules()],
},
},
{
files: ["apps/browser/src/autofill/**/*.ts"],
ignores: [
"apps/browser/src/autofill/{deprecated/content,content,notification}/**/*.ts",
"apps/browser/src/**/background/**/*.ts",
"apps/browser/src/autofill/services/default-fill-cipher-policy.ts",
"apps/browser/src/**/*.spec.ts",
],
rules: {
"no-restricted-syntax": [
"error",
...safariAddListenerSyntaxRules(),
doAutoFillSyntaxRule(),
unsafeAutofillTabWithCipherSyntaxRule(),
...fillCipherPolicySyntaxRules(),
],
},
},
{
files: ["apps/browser/src/autofill/**/background/**/*.ts"],
ignores: [
"apps/browser/src/autofill/background/autofill-orchestrator.ts",
"apps/browser/src/**/*.spec.ts",
],
rules: {
"no-restricted-syntax": [
"error",
doAutoFillSyntaxRule(),
unsafeAutofillTabWithCipherSyntaxRule(),
...fillCipherPolicySyntaxRules(),
],
},
},
{
files: ["**/src/**/*.ts"],
rules: {
@@ -885,6 +918,51 @@ function buildNoRestrictedImports(
];
}
/**
* `no-restricted-syntax` entries that flag native `addListener` calls on `chrome` events.
* @returns {any[]}
*/
function safariAddListenerSyntaxRules() {
const message =
"Using addListener in the browser popup produces a memory leak in Safari, use `BrowserApi.addListener` instead";
return [
{
message,
// This selector covers events like chrome.storage.onChange & chrome.runtime.onMessage
selector:
"CallExpression > [object.object.object.name='chrome'][property.name='addListener']",
},
{
message,
// This selector covers events like chrome.storage.local.onChange
selector:
"CallExpression > [object.object.object.object.name='chrome'][property.name='addListener']",
},
];
}
/**
* `no-restricted-syntax` entries that flag `CipherService` lookups (`cipherService.x` and
* `this.cipherService.x`) that Autofill must make through `FillCipherPolicy`.
* @returns {any[]}
*/
function fillCipherPolicySyntaxRules() {
const lookups =
"/^(getAllDecrypted|getAllDecryptedForUrl|getNextCipherForUrl|getNextCardCipher|getNextIdentityCipher|getLastLaunchedForUrl|getLastUsedForUrl|updateLastUsedIndexForUrl|ciphers\\$|cipherViews\\$)$/";
const message =
"Autofill looks up ciphers through FillCipherPolicy with a CipherUse, not through CipherService. See fill-cipher-policy.ts.";
return [
{
selector: `MemberExpression[object.name='cipherService'][property.name=${lookups}]`,
message,
},
{
selector: `MemberExpression[object.type='MemberExpression'][object.property.name='cipherService'][property.name=${lookups}]`,
message,
},
];
}
/**
* A `no-restricted-syntax` entry that flags direct calls to the `AutofillService.doAutoFill*`
* methods.