/
autofill.service.spec.ts
4705 lines (4034 loc) · 163 KB
/
autofill.service.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { mock, mockReset } from "jest-mock-extended";
import { of } from "rxjs";
import { UserVerificationService } from "@bitwarden/common/auth/services/user-verification/user-verification.service";
import { AutofillOverlayVisibility } from "@bitwarden/common/autofill/constants";
import { AutofillSettingsService } from "@bitwarden/common/autofill/services/autofill-settings.service";
import {
DefaultDomainSettingsService,
DomainSettingsService,
} from "@bitwarden/common/autofill/services/domain-settings.service";
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
import { EventType } from "@bitwarden/common/enums";
import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { Utils } from "@bitwarden/common/platform/misc/utils";
import { EventCollectionService } from "@bitwarden/common/services/event/event-collection.service";
import {
FakeStateProvider,
FakeAccountService,
mockAccountServiceWith,
} from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { FieldType, LinkedIdType, LoginLinkedId, CipherType } from "@bitwarden/common/vault/enums";
import { CipherRepromptType } from "@bitwarden/common/vault/enums/cipher-reprompt-type";
import { CardView } from "@bitwarden/common/vault/models/view/card.view";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { FieldView } from "@bitwarden/common/vault/models/view/field.view";
import { IdentityView } from "@bitwarden/common/vault/models/view/identity.view";
import { LoginUriView } from "@bitwarden/common/vault/models/view/login-uri.view";
import { LoginView } from "@bitwarden/common/vault/models/view/login.view";
import { CipherService } from "@bitwarden/common/vault/services/cipher.service";
import { TotpService } from "@bitwarden/common/vault/services/totp.service";
import { BrowserApi } from "../../platform/browser/browser-api";
import { BrowserStateService } from "../../platform/services/browser-state.service";
import { AutofillPort } from "../enums/autofill-port.enums";
import AutofillField from "../models/autofill-field";
import AutofillPageDetails from "../models/autofill-page-details";
import AutofillScript from "../models/autofill-script";
import {
createAutofillFieldMock,
createAutofillPageDetailsMock,
createAutofillScriptMock,
createChromeTabMock,
createGenerateFillScriptOptionsMock,
} from "../spec/autofill-mocks";
import { triggerTestFailure } from "../spec/testing-utils";
import {
AutoFillOptions,
GenerateFillScriptOptions,
PageDetail,
} from "./abstractions/autofill.service";
import { AutoFillConstants, IdentityAutoFillConstants } from "./autofill-constants";
import AutofillService from "./autofill.service";
const mockEquivalentDomains = [
["example.com", "exampleapp.com", "example.co.uk", "ejemplo.es"],
["bitwarden.com", "bitwarden.co.uk", "sm-bitwarden.com"],
["example.co.uk", "exampleapp.co.uk"],
];
describe("AutofillService", () => {
let autofillService: AutofillService;
const cipherService = mock<CipherService>();
const stateService = mock<BrowserStateService>();
const autofillSettingsService = mock<AutofillSettingsService>();
const mockUserId = Utils.newGuid() as UserId;
const accountService: FakeAccountService = mockAccountServiceWith(mockUserId);
const fakeStateProvider: FakeStateProvider = new FakeStateProvider(accountService);
let domainSettingsService: DomainSettingsService;
const totpService = mock<TotpService>();
const eventCollectionService = mock<EventCollectionService>();
const logService = mock<LogService>();
const userVerificationService = mock<UserVerificationService>();
const billingAccountProfileStateService = mock<BillingAccountProfileStateService>();
beforeEach(() => {
autofillService = new AutofillService(
cipherService,
stateService,
autofillSettingsService,
totpService,
eventCollectionService,
logService,
domainSettingsService,
userVerificationService,
billingAccountProfileStateService,
);
domainSettingsService = new DefaultDomainSettingsService(fakeStateProvider);
domainSettingsService.equivalentDomains$ = of(mockEquivalentDomains);
});
afterEach(() => {
jest.clearAllMocks();
mockReset(cipherService);
});
describe("loadAutofillScriptsOnInstall", () => {
let tab1: chrome.tabs.Tab;
let tab2: chrome.tabs.Tab;
let tab3: chrome.tabs.Tab;
beforeEach(() => {
tab1 = createChromeTabMock({ id: 1, url: "https://some-url.com" });
tab2 = createChromeTabMock({ id: 2, url: "http://some-url.com" });
tab3 = createChromeTabMock({ id: 3, url: "chrome-extension://some-extension-route" });
jest.spyOn(BrowserApi, "tabsQuery").mockResolvedValueOnce([tab1, tab2]);
jest
.spyOn(autofillService, "getOverlayVisibility")
.mockResolvedValue(AutofillOverlayVisibility.OnFieldFocus);
jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(true);
});
it("queries all browser tabs and injects the autofill scripts into them", async () => {
jest.spyOn(autofillService, "injectAutofillScripts");
await autofillService.loadAutofillScriptsOnInstall();
expect(BrowserApi.tabsQuery).toHaveBeenCalledWith({});
expect(autofillService.injectAutofillScripts).toHaveBeenCalledWith(tab1, 0, false);
expect(autofillService.injectAutofillScripts).toHaveBeenCalledWith(tab2, 0, false);
});
it("skips injecting scripts into tabs that do not have an http(s) protocol", async () => {
jest.spyOn(autofillService, "injectAutofillScripts");
await autofillService.loadAutofillScriptsOnInstall();
expect(BrowserApi.tabsQuery).toHaveBeenCalledWith({});
expect(autofillService.injectAutofillScripts).not.toHaveBeenCalledWith(tab3);
});
it("sets up an extension runtime onConnect listener", async () => {
await autofillService.loadAutofillScriptsOnInstall();
// eslint-disable-next-line no-restricted-syntax
expect(chrome.runtime.onConnect.addListener).toHaveBeenCalledWith(expect.any(Function));
});
});
describe("reloadAutofillScripts", () => {
it("disconnects and removes all autofill script ports", () => {
const port1 = mock<chrome.runtime.Port>({
disconnect: jest.fn(),
});
const port2 = mock<chrome.runtime.Port>({
disconnect: jest.fn(),
});
autofillService["autofillScriptPortsSet"] = new Set([port1, port2]);
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
autofillService.reloadAutofillScripts();
expect(port1.disconnect).toHaveBeenCalled();
expect(port2.disconnect).toHaveBeenCalled();
expect(autofillService["autofillScriptPortsSet"].size).toBe(0);
});
it("re-injects the autofill scripts in all tabs", () => {
autofillService["autofillScriptPortsSet"] = new Set([mock<chrome.runtime.Port>()]);
jest.spyOn(autofillService as any, "injectAutofillScriptsInAllTabs");
jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(true);
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
autofillService.reloadAutofillScripts();
expect(autofillService["injectAutofillScriptsInAllTabs"]).toHaveBeenCalled();
});
});
describe("injectAutofillScripts", () => {
const autofillBootstrapScript = "bootstrap-autofill.js";
const autofillOverlayBootstrapScript = "bootstrap-autofill-overlay.js";
const defaultAutofillScripts = ["autofiller.js", "notificationBar.js", "contextMenuHandler.js"];
const defaultExecuteScriptOptions = { runAt: "document_start" };
let tabMock: chrome.tabs.Tab;
let sender: chrome.runtime.MessageSender;
beforeEach(() => {
tabMock = createChromeTabMock();
sender = { tab: tabMock, frameId: 1 };
jest.spyOn(BrowserApi, "executeScriptInTab").mockImplementation();
jest
.spyOn(autofillService, "getOverlayVisibility")
.mockResolvedValue(AutofillOverlayVisibility.OnFieldFocus);
jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(true);
});
it("accepts an extension message sender and injects the autofill scripts into the tab of the sender", async () => {
await autofillService.injectAutofillScripts(sender.tab, sender.frameId, true);
[autofillOverlayBootstrapScript, ...defaultAutofillScripts].forEach((scriptName) => {
expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, {
file: `content/${scriptName}`,
frameId: sender.frameId,
...defaultExecuteScriptOptions,
});
});
});
it("skips injecting autofiller script when autofill on load setting is disabled", async () => {
jest.spyOn(autofillService, "getAutofillOnPageLoad").mockResolvedValue(false);
await autofillService.injectAutofillScripts(sender.tab, sender.frameId, true);
expect(BrowserApi.executeScriptInTab).not.toHaveBeenCalledWith(tabMock.id, {
file: "content/autofiller.js",
frameId: sender.frameId,
...defaultExecuteScriptOptions,
});
});
it("will inject the bootstrap-autofill-overlay script if the user has the autofill overlay enabled", async () => {
await autofillService.injectAutofillScripts(sender.tab, sender.frameId);
expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, {
file: `content/${autofillOverlayBootstrapScript}`,
frameId: sender.frameId,
...defaultExecuteScriptOptions,
});
expect(BrowserApi.executeScriptInTab).not.toHaveBeenCalledWith(tabMock.id, {
file: `content/${autofillBootstrapScript}`,
frameId: sender.frameId,
...defaultExecuteScriptOptions,
});
});
it("will inject the bootstrap-autofill script if the user does not have the autofill overlay enabled", async () => {
jest
.spyOn(autofillService, "getOverlayVisibility")
.mockResolvedValue(AutofillOverlayVisibility.Off);
await autofillService.injectAutofillScripts(sender.tab, sender.frameId);
expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, {
file: `content/${autofillBootstrapScript}`,
frameId: sender.frameId,
...defaultExecuteScriptOptions,
});
expect(BrowserApi.executeScriptInTab).not.toHaveBeenCalledWith(tabMock.id, {
file: `content/${autofillOverlayBootstrapScript}`,
frameId: sender.frameId,
...defaultExecuteScriptOptions,
});
});
it("injects the content-message-handler script if not injecting on page load", async () => {
await autofillService.injectAutofillScripts(sender.tab, sender.frameId, false);
expect(BrowserApi.executeScriptInTab).toHaveBeenCalledWith(tabMock.id, {
file: "content/content-message-handler.js",
...defaultExecuteScriptOptions,
});
});
});
describe("getFormsWithPasswordFields", () => {
let pageDetailsMock: AutofillPageDetails;
beforeEach(() => {
pageDetailsMock = createAutofillPageDetailsMock();
});
it("returns an empty FormData array if no password fields are found", () => {
jest.spyOn(AutofillService, "loadPasswordFields");
const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock);
expect(AutofillService.loadPasswordFields).toHaveBeenCalledWith(
pageDetailsMock,
true,
true,
false,
true,
);
expect(formData).toStrictEqual([]);
});
it("returns an FormData array containing a form with it's autofill data", () => {
const usernameInputField = createAutofillFieldMock({
opid: "username-field",
form: "validFormId",
elementNumber: 1,
});
const passwordInputField = createAutofillFieldMock({
opid: "password-field",
type: "password",
form: "validFormId",
elementNumber: 2,
});
pageDetailsMock.fields = [usernameInputField, passwordInputField];
const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock);
expect(formData).toStrictEqual([
{
form: pageDetailsMock.forms.validFormId,
password: pageDetailsMock.fields[1],
passwords: [pageDetailsMock.fields[1]],
username: pageDetailsMock.fields[0],
},
]);
});
it("narrows down three passwords that are present on a page to a single password field to autofill when only one form element is present on the page", () => {
const usernameInputField = createAutofillFieldMock({
opid: "username-field",
form: "validFormId",
elementNumber: 1,
});
const passwordInputField = createAutofillFieldMock({
opid: "password-field",
type: "password",
form: "validFormId",
elementNumber: 2,
});
const secondPasswordInputField = createAutofillFieldMock({
opid: "another-password-field",
type: "password",
form: undefined,
elementNumber: 3,
});
const thirdPasswordInputField = createAutofillFieldMock({
opid: "a-third-password-field",
type: "password",
form: undefined,
elementNumber: 4,
});
pageDetailsMock.fields = [
usernameInputField,
passwordInputField,
secondPasswordInputField,
thirdPasswordInputField,
];
const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock);
expect(formData).toStrictEqual([
{
form: pageDetailsMock.forms.validFormId,
password: pageDetailsMock.fields[1],
passwords: [
pageDetailsMock.fields[1],
{ ...pageDetailsMock.fields[2], form: pageDetailsMock.fields[1].form },
{ ...pageDetailsMock.fields[3], form: pageDetailsMock.fields[1].form },
],
username: pageDetailsMock.fields[0],
},
]);
});
it("will check for a hidden username field", () => {
const usernameInputField = createAutofillFieldMock({
opid: "username-field",
form: "validFormId",
elementNumber: 1,
isViewable: false,
readonly: true,
});
const passwordInputField = createAutofillFieldMock({
opid: "password-field",
type: "password",
form: "validFormId",
elementNumber: 2,
});
pageDetailsMock.fields = [usernameInputField, passwordInputField];
jest.spyOn(autofillService as any, "findUsernameField");
const formData = autofillService.getFormsWithPasswordFields(pageDetailsMock);
expect(autofillService["findUsernameField"]).toHaveBeenCalledWith(
pageDetailsMock,
passwordInputField,
true,
true,
false,
);
expect(formData).toStrictEqual([
{
form: pageDetailsMock.forms.validFormId,
password: pageDetailsMock.fields[1],
passwords: [pageDetailsMock.fields[1]],
username: pageDetailsMock.fields[0],
},
]);
});
});
describe("doAutoFill", () => {
let autofillOptions: AutoFillOptions;
const nothingToAutofillError = "Nothing to auto-fill.";
const didNotAutofillError = "Did not auto-fill.";
beforeEach(() => {
autofillOptions = {
cipher: mock<CipherView>({
id: "cipherId",
type: CipherType.Login,
}),
pageDetails: [
{
frameId: 1,
tab: createChromeTabMock(),
details: createAutofillPageDetailsMock({
fields: [
createAutofillFieldMock({
opid: "username-field",
form: "validFormId",
elementNumber: 1,
}),
createAutofillFieldMock({
opid: "password-field",
type: "password",
form: "validFormId",
elementNumber: 2,
}),
],
}),
},
],
tab: createChromeTabMock(),
};
autofillOptions.cipher.fields = [mock<FieldView>({ name: "username" })];
autofillOptions.cipher.login.matchesUri = jest.fn().mockReturnValue(true);
autofillOptions.cipher.login.username = "username";
autofillOptions.cipher.login.password = "password";
jest.spyOn(autofillService, "getDefaultUriMatchStrategy").mockResolvedValue(0);
});
describe("given a set of autofill options that are incomplete", () => {
it("throws an error if the tab is not provided", async () => {
autofillOptions.tab = undefined;
try {
await autofillService.doAutoFill(autofillOptions);
triggerTestFailure();
} catch (error) {
expect(error.message).toBe(nothingToAutofillError);
}
});
it("throws an error if the cipher is not provided", async () => {
autofillOptions.cipher = undefined;
try {
await autofillService.doAutoFill(autofillOptions);
triggerTestFailure();
} catch (error) {
expect(error.message).toBe(nothingToAutofillError);
}
});
it("throws an error if the page details are not provided", async () => {
autofillOptions.pageDetails = undefined;
try {
await autofillService.doAutoFill(autofillOptions);
triggerTestFailure();
} catch (error) {
expect(error.message).toBe(nothingToAutofillError);
}
});
it("throws an error if the page details are empty", async () => {
autofillOptions.pageDetails = [];
try {
await autofillService.doAutoFill(autofillOptions);
triggerTestFailure();
} catch (error) {
expect(error.message).toBe(nothingToAutofillError);
}
});
it("throws an error if an autofill did not occur for any of the passed pages", async () => {
autofillOptions.tab.url = "https://a-different-url.com";
billingAccountProfileStateService.hasPremiumFromAnySource$ = of(true);
try {
await autofillService.doAutoFill(autofillOptions);
triggerTestFailure();
} catch (error) {
expect(error.message).toBe(didNotAutofillError);
}
});
});
it("will autofill login data for a page", async () => {
jest.spyOn(autofillService as any, "generateFillScript");
jest.spyOn(autofillService as any, "generateLoginFillScript");
jest.spyOn(logService, "info");
jest.spyOn(cipherService, "updateLastUsedDate");
jest.spyOn(eventCollectionService, "collect");
const autofillResult = await autofillService.doAutoFill(autofillOptions);
const currentAutofillPageDetails = autofillOptions.pageDetails[0];
expect(autofillService["generateFillScript"]).toHaveBeenCalledWith(
currentAutofillPageDetails.details,
{
skipUsernameOnlyFill: autofillOptions.skipUsernameOnlyFill || false,
onlyEmptyFields: autofillOptions.onlyEmptyFields || false,
onlyVisibleFields: autofillOptions.onlyVisibleFields || false,
fillNewPassword: autofillOptions.fillNewPassword || false,
allowTotpAutofill: autofillOptions.allowTotpAutofill || false,
cipher: autofillOptions.cipher,
tabUrl: autofillOptions.tab.url,
defaultUriMatch: 0,
},
);
expect(autofillService["generateLoginFillScript"]).toHaveBeenCalled();
expect(logService.info).not.toHaveBeenCalled();
expect(cipherService.updateLastUsedDate).toHaveBeenCalledWith(autofillOptions.cipher.id);
expect(chrome.tabs.sendMessage).toHaveBeenCalledWith(
autofillOptions.pageDetails[0].tab.id,
{
command: "fillForm",
fillScript: {
autosubmit: null,
metadata: {},
properties: {
delay_between_operations: 20,
},
savedUrls: [],
script: [
["click_on_opid", "username-field"],
["focus_by_opid", "username-field"],
["fill_by_opid", "username-field", "username"],
["click_on_opid", "password-field"],
["focus_by_opid", "password-field"],
["fill_by_opid", "password-field", "password"],
["focus_by_opid", "password-field"],
],
untrustedIframe: false,
},
url: currentAutofillPageDetails.tab.url,
pageDetailsUrl: "url",
},
{
frameId: currentAutofillPageDetails.frameId,
},
expect.any(Function),
);
expect(eventCollectionService.collect).toHaveBeenCalledWith(
EventType.Cipher_ClientAutofilled,
autofillOptions.cipher.id,
);
expect(autofillResult).toBeNull();
});
it("will autofill card data for a page", async () => {
autofillOptions.cipher.type = CipherType.Card;
autofillOptions.cipher.card = mock<CardView>({
cardholderName: "cardholderName",
});
autofillOptions.pageDetails[0].details.fields = [
createAutofillFieldMock({
opid: "cardholderName",
form: "validFormId",
elementNumber: 2,
autoCompleteType: "cc-name",
}),
];
jest.spyOn(autofillService as any, "generateCardFillScript");
jest.spyOn(eventCollectionService, "collect");
await autofillService.doAutoFill(autofillOptions);
expect(autofillService["generateCardFillScript"]).toHaveBeenCalled();
expect(chrome.tabs.sendMessage).toHaveBeenCalled();
expect(eventCollectionService.collect).toHaveBeenCalledWith(
EventType.Cipher_ClientAutofilled,
autofillOptions.cipher.id,
);
});
it("will autofill identity data for a page", async () => {
autofillOptions.cipher.type = CipherType.Identity;
autofillOptions.cipher.identity = mock<IdentityView>({
firstName: "firstName",
middleName: "middleName",
lastName: "lastName",
});
autofillOptions.pageDetails[0].details.fields = [
createAutofillFieldMock({
opid: "full-name",
form: "validFormId",
elementNumber: 2,
autoCompleteType: "full-name",
}),
];
jest.spyOn(autofillService as any, "generateIdentityFillScript");
jest.spyOn(eventCollectionService, "collect");
await autofillService.doAutoFill(autofillOptions);
expect(autofillService["generateIdentityFillScript"]).toHaveBeenCalled();
expect(chrome.tabs.sendMessage).toHaveBeenCalled();
expect(eventCollectionService.collect).toHaveBeenCalledWith(
EventType.Cipher_ClientAutofilled,
autofillOptions.cipher.id,
);
});
it("blocks autofill on an untrusted iframe", async () => {
autofillOptions.allowUntrustedIframe = false;
autofillOptions.cipher.login.matchesUri = jest.fn().mockReturnValueOnce(false);
jest.spyOn(logService, "info");
try {
await autofillService.doAutoFill(autofillOptions);
triggerTestFailure();
} catch (error) {
expect(logService.info).toHaveBeenCalledWith(
"Auto-fill on page load was blocked due to an untrusted iframe.",
);
expect(error.message).toBe(didNotAutofillError);
}
});
it("allows autofill on an untrusted iframe if the passed option allowing untrusted iframes is set to true", async () => {
autofillOptions.allowUntrustedIframe = true;
autofillOptions.cipher.login.matchesUri = jest.fn().mockReturnValue(false);
jest.spyOn(logService, "info");
await autofillService.doAutoFill(autofillOptions);
expect(logService.info).not.toHaveBeenCalledWith(
"Auto-fill on page load was blocked due to an untrusted iframe.",
);
});
it("skips updating the cipher's last used date if the passed options indicate that we should skip the last used cipher", async () => {
autofillOptions.skipLastUsed = true;
jest.spyOn(cipherService, "updateLastUsedDate");
await autofillService.doAutoFill(autofillOptions);
expect(cipherService.updateLastUsedDate).not.toHaveBeenCalled();
});
it("returns early if the fillScript cannot be generated", async () => {
jest.spyOn(autofillService as any, "generateFillScript").mockReturnValueOnce(undefined);
jest.spyOn(BrowserApi, "tabSendMessage");
try {
await autofillService.doAutoFill(autofillOptions);
triggerTestFailure();
} catch (error) {
expect(autofillService["generateFillScript"]).toHaveBeenCalled();
expect(BrowserApi.tabSendMessage).not.toHaveBeenCalled();
expect(error.message).toBe(didNotAutofillError);
}
});
it("returns a TOTP value", async () => {
const totpCode = "123456";
autofillOptions.cipher.login.totp = "totp";
billingAccountProfileStateService.hasPremiumFromAnySource$ = of(true);
jest.spyOn(autofillService, "getShouldAutoCopyTotp").mockResolvedValue(true);
jest.spyOn(totpService, "getCode").mockResolvedValue(totpCode);
const autofillResult = await autofillService.doAutoFill(autofillOptions);
expect(autofillService.getShouldAutoCopyTotp).toHaveBeenCalled();
expect(totpService.getCode).toHaveBeenCalledWith(autofillOptions.cipher.login.totp);
expect(autofillResult).toBe(totpCode);
});
it("does not return a TOTP value if the user does not have premium features", async () => {
autofillOptions.cipher.login.totp = "totp";
billingAccountProfileStateService.hasPremiumFromAnySource$ = of(false);
jest.spyOn(autofillService, "getShouldAutoCopyTotp").mockResolvedValue(true);
const autofillResult = await autofillService.doAutoFill(autofillOptions);
expect(autofillService.getShouldAutoCopyTotp).not.toHaveBeenCalled();
expect(totpService.getCode).not.toHaveBeenCalled();
expect(autofillResult).toBeNull();
});
it("returns a null value if the cipher type is not for a Login", async () => {
autofillOptions.cipher.type = CipherType.Identity;
autofillOptions.cipher.identity = mock<IdentityView>();
const autofillResult = await autofillService.doAutoFill(autofillOptions);
expect(autofillResult).toBeNull();
});
it("returns a null value if the login does not contain a TOTP value", async () => {
autofillOptions.cipher.login.totp = undefined;
jest.spyOn(autofillService, "getShouldAutoCopyTotp");
jest.spyOn(totpService, "getCode");
const autofillResult = await autofillService.doAutoFill(autofillOptions);
expect(autofillService.getShouldAutoCopyTotp).not.toHaveBeenCalled();
expect(totpService.getCode).not.toHaveBeenCalled();
expect(autofillResult).toBeNull();
});
it("returns a null value if the user cannot access premium and the organization does not use TOTP", async () => {
autofillOptions.cipher.login.totp = "totp";
autofillOptions.cipher.organizationUseTotp = false;
billingAccountProfileStateService.hasPremiumFromAnySource$ = of(false);
const autofillResult = await autofillService.doAutoFill(autofillOptions);
expect(autofillResult).toBeNull();
});
it("returns a null value if the user has disabled `auto TOTP copy`", async () => {
autofillOptions.cipher.login.totp = "totp";
autofillOptions.cipher.organizationUseTotp = true;
billingAccountProfileStateService.hasPremiumFromAnySource$ = of(true);
jest.spyOn(autofillService, "getShouldAutoCopyTotp").mockResolvedValue(false);
jest.spyOn(totpService, "getCode");
const autofillResult = await autofillService.doAutoFill(autofillOptions);
expect(autofillService.getShouldAutoCopyTotp).toHaveBeenCalled();
expect(totpService.getCode).not.toHaveBeenCalled();
expect(autofillResult).toBeNull();
});
});
describe("doAutoFillOnTab", () => {
let pageDetails: PageDetail[];
let tab: chrome.tabs.Tab;
beforeEach(() => {
tab = createChromeTabMock();
pageDetails = [
{
frameId: 1,
tab: createChromeTabMock(),
details: createAutofillPageDetailsMock({
fields: [
createAutofillFieldMock({
opid: "username-field",
form: "validFormId",
elementNumber: 1,
}),
createAutofillFieldMock({
opid: "password-field",
type: "password",
form: "validFormId",
elementNumber: 2,
}),
],
}),
},
];
});
describe("given a tab url which does not match a cipher", () => {
it("will skip autofill and return a null value when triggering on page load", async () => {
jest.spyOn(autofillService, "doAutoFill");
jest.spyOn(cipherService, "getNextCipherForUrl");
jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(null);
jest.spyOn(cipherService, "getLastUsedForUrl").mockResolvedValueOnce(null);
const result = await autofillService.doAutoFillOnTab(pageDetails, tab, false);
expect(cipherService.getNextCipherForUrl).not.toHaveBeenCalled();
expect(cipherService.getLastLaunchedForUrl).toHaveBeenCalledWith(tab.url, true);
expect(cipherService.getLastUsedForUrl).toHaveBeenCalledWith(tab.url, true);
expect(autofillService.doAutoFill).not.toHaveBeenCalled();
expect(result).toBeNull();
});
it("will skip autofill and return a null value when triggering from a keyboard shortcut", async () => {
jest.spyOn(autofillService, "doAutoFill");
jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(null);
jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(null);
jest.spyOn(cipherService, "getLastUsedForUrl").mockResolvedValueOnce(null);
const result = await autofillService.doAutoFillOnTab(pageDetails, tab, true);
expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url);
expect(cipherService.getLastLaunchedForUrl).not.toHaveBeenCalled();
expect(cipherService.getLastUsedForUrl).not.toHaveBeenCalled();
expect(autofillService.doAutoFill).not.toHaveBeenCalled();
expect(result).toBeNull();
});
});
describe("given a tab url which matches a cipher", () => {
let cipher: CipherView;
beforeEach(() => {
cipher = mock<CipherView>({
reprompt: CipherRepromptType.None,
localData: {
lastLaunched: Date.now().valueOf(),
},
});
});
it("will autofill the last launched cipher and return a TOTP value when triggering on page load", async () => {
const totpCode = "123456";
const fromCommand = false;
jest.spyOn(autofillService, "doAutoFill").mockResolvedValueOnce(totpCode);
jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(cipher);
jest.spyOn(cipherService, "getLastUsedForUrl");
jest.spyOn(cipherService, "updateLastUsedIndexForUrl");
const result = await autofillService.doAutoFillOnTab(pageDetails, tab, fromCommand);
expect(cipherService.getLastLaunchedForUrl).toHaveBeenCalledWith(tab.url, true);
expect(cipherService.getLastUsedForUrl).not.toHaveBeenCalled();
expect(cipherService.updateLastUsedIndexForUrl).not.toHaveBeenCalled();
expect(autofillService.doAutoFill).toHaveBeenCalledWith({
tab: tab,
cipher: cipher,
pageDetails: pageDetails,
skipLastUsed: !fromCommand,
skipUsernameOnlyFill: !fromCommand,
onlyEmptyFields: !fromCommand,
onlyVisibleFields: !fromCommand,
fillNewPassword: fromCommand,
allowUntrustedIframe: fromCommand,
allowTotpAutofill: fromCommand,
});
expect(result).toBe(totpCode);
});
it("will autofill the last used cipher and return a TOTP value when triggering on page load ", async () => {
cipher.localData.lastLaunched = Date.now().valueOf() - 30001;
const totpCode = "123456";
const fromCommand = false;
jest.spyOn(autofillService, "doAutoFill").mockResolvedValueOnce(totpCode);
jest.spyOn(cipherService, "getLastLaunchedForUrl").mockResolvedValueOnce(cipher);
jest.spyOn(cipherService, "getLastUsedForUrl").mockResolvedValueOnce(cipher);
jest.spyOn(cipherService, "updateLastUsedIndexForUrl");
const result = await autofillService.doAutoFillOnTab(pageDetails, tab, fromCommand);
expect(cipherService.getLastLaunchedForUrl).toHaveBeenCalledWith(tab.url, true);
expect(cipherService.getLastUsedForUrl).toHaveBeenCalledWith(tab.url, true);
expect(cipherService.updateLastUsedIndexForUrl).not.toHaveBeenCalled();
expect(autofillService.doAutoFill).toHaveBeenCalledWith({
tab: tab,
cipher: cipher,
pageDetails: pageDetails,
skipLastUsed: !fromCommand,
skipUsernameOnlyFill: !fromCommand,
onlyEmptyFields: !fromCommand,
onlyVisibleFields: !fromCommand,
fillNewPassword: fromCommand,
allowUntrustedIframe: fromCommand,
allowTotpAutofill: fromCommand,
});
expect(result).toBe(totpCode);
});
it("will autofill the next cipher, update the last used cipher index, and return a TOTP value when triggering from a keyboard shortcut", async () => {
const totpCode = "123456";
const fromCommand = true;
jest.spyOn(autofillService, "doAutoFill").mockResolvedValueOnce(totpCode);
jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(cipher);
jest.spyOn(cipherService, "updateLastUsedIndexForUrl");
const result = await autofillService.doAutoFillOnTab(pageDetails, tab, fromCommand);
expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url);
expect(cipherService.updateLastUsedIndexForUrl).toHaveBeenCalledWith(tab.url);
expect(autofillService.doAutoFill).toHaveBeenCalledWith({
tab: tab,
cipher: cipher,
pageDetails: pageDetails,
skipLastUsed: !fromCommand,
skipUsernameOnlyFill: !fromCommand,
onlyEmptyFields: !fromCommand,
onlyVisibleFields: !fromCommand,
fillNewPassword: fromCommand,
allowUntrustedIframe: fromCommand,
allowTotpAutofill: fromCommand,
});
expect(result).toBe(totpCode);
});
it("will skip autofill, launch the password reprompt window, and return a null value if the cipher re-prompt type is not `None`", async () => {
cipher.reprompt = CipherRepromptType.Password;
jest.spyOn(autofillService, "doAutoFill");
jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(cipher);
jest
.spyOn(userVerificationService, "hasMasterPasswordAndMasterKeyHash")
.mockResolvedValueOnce(true);
jest
.spyOn(autofillService as any, "openVaultItemPasswordRepromptPopout")
.mockImplementation();
const result = await autofillService.doAutoFillOnTab(pageDetails, tab, true);
expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url);
expect(userVerificationService.hasMasterPasswordAndMasterKeyHash).toHaveBeenCalled();
expect(autofillService["openVaultItemPasswordRepromptPopout"]).toHaveBeenCalledWith(tab, {
cipherId: cipher.id,
action: "autofill",
});
expect(autofillService.doAutoFill).not.toHaveBeenCalled();
expect(result).toBeNull();
});
it("skips autofill and does not launch the password reprompt window if the password reprompt is currently debouncing", async () => {
cipher.reprompt = CipherRepromptType.Password;
jest.spyOn(autofillService, "doAutoFill");
jest.spyOn(cipherService, "getNextCipherForUrl").mockResolvedValueOnce(cipher);
jest
.spyOn(userVerificationService, "hasMasterPasswordAndMasterKeyHash")
.mockResolvedValueOnce(true);
jest
.spyOn(autofillService as any, "openVaultItemPasswordRepromptPopout")
.mockImplementation();
jest
.spyOn(autofillService as any, "isDebouncingPasswordRepromptPopout")
.mockReturnValueOnce(true);
const result = await autofillService.doAutoFillOnTab(pageDetails, tab, true);
expect(cipherService.getNextCipherForUrl).toHaveBeenCalledWith(tab.url);
expect(autofillService["openVaultItemPasswordRepromptPopout"]).not.toHaveBeenCalled();
expect(autofillService.doAutoFill).not.toHaveBeenCalled();
expect(result).toBeNull();
});
});
});
describe("doAutoFillActiveTab", () => {
let pageDetails: PageDetail[];
let tab: chrome.tabs.Tab;
beforeEach(() => {
tab = createChromeTabMock();
pageDetails = [
{
frameId: 1,
tab: createChromeTabMock(),
details: createAutofillPageDetailsMock({
fields: [
createAutofillFieldMock({
opid: "username-field",
form: "validFormId",
elementNumber: 1,
}),
createAutofillFieldMock({
opid: "password-field",
type: "password",
form: "validFormId",
elementNumber: 2,
}),
],
}),
},
];
});
it("returns a null vault without doing autofill if the page details does not contain fields ", async () => {
pageDetails[0].details.fields = [];
jest.spyOn(autofillService as any, "getActiveTab");
jest.spyOn(autofillService, "doAutoFill");
const result = await autofillService.doAutoFillActiveTab(pageDetails, false);
expect(autofillService["getActiveTab"]).not.toHaveBeenCalled();
expect(autofillService.doAutoFill).not.toHaveBeenCalled();
expect(result).toBeNull();
});
it("returns a null value without doing autofill if the active tab cannot be found", async () => {
jest.spyOn(autofillService as any, "getActiveTab").mockResolvedValueOnce(undefined);
jest.spyOn(autofillService, "doAutoFill");
const result = await autofillService.doAutoFillActiveTab(pageDetails, false);
expect(autofillService["getActiveTab"]).toHaveBeenCalled();
expect(autofillService.doAutoFill).not.toHaveBeenCalled();
expect(result).toBeNull();
});
it("returns a null value without doing autofill if the active tab url cannot be found", async () => {
jest.spyOn(autofillService as any, "getActiveTab").mockResolvedValueOnce({
id: 1,
url: undefined,
});
jest.spyOn(autofillService, "doAutoFill");
const result = await autofillService.doAutoFillActiveTab(pageDetails, false);
expect(autofillService["getActiveTab"]).toHaveBeenCalled();
expect(autofillService.doAutoFill).not.toHaveBeenCalled();
expect(result).toBeNull();
});