mirror of
https://github.com/bitwarden/clients.git
synced 2026-11-16 07:03:29 +00:00
(B6) Vault: restricted ciphers in the browser popup (#24596)
* Vault: show restricted ciphers in the browser popup The popup lists restricted (partial) ciphers and swaps in a cipher's revealed view while one exists. The edit, clone and assign-collections routes send a blocked restricted cipher back to its view, and the view page, more-options menu, copy actions, password history and add-edit respect the restricted-cipher rule. A host can provide VAULT_ROW_ACCESS for each row's access status and overflow actions, and contribute list table filters with coloured tiles. Unprovided, rows show no status and the popup behaves as before. * Vault: replace the popup's row access seam with neutral slots Addresses review feedback on #24596. - Replace VAULT_ROW_ACCESS with VAULT_ROW_ICON (a component slot) and VAULT_ROW_SUBTITLE (a text provider). item-more-options renders VAULT_ROW_ACTIONS after View, checked against its own built-in IDs. - Add an optional `disabled` to row actions, honoured by web's menu too, and export the contributed action ID check from CipherRowMenuService. - Drop accessActive from the more-options menu, so edit under a live reveal follows the restricted-cipher policy. Clone checks the policy. - Name the list table's contributed filter generically, key it by the provider's `key`, and persist selections as contributedFilterIds. - Move gating into the row actions (showCopyActions) and launchCipher, and drop the separate revealed-ID stream: the list already swaps revealed views in for their restricted rows. - Lift the view footer's edit and restore conditions into the component. - Drop the five browser strings, which Vault no longer uses.
This commit is contained in:
@@ -45,6 +45,7 @@ import {
|
||||
} from "@bitwarden/auth/angular";
|
||||
import { canAccessAutoConfirmSettings } from "@bitwarden/auto-confirm/angular";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { RestrictedCipherAction } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import { AnonLayoutWrapperComponent, AnonLayoutWrapperData } from "@bitwarden/components";
|
||||
import { canActivateImportType, IMPORT_DESTINATION_ROUTE_PATH } from "@bitwarden/importer-ui";
|
||||
import {
|
||||
@@ -114,6 +115,7 @@ import {
|
||||
import { clearVaultStateGuard } from "../vault/popup/guards/clear-vault-state.guard";
|
||||
import { IntroCarouselGuard } from "../vault/popup/guards/intro-carousel.guard";
|
||||
import { restoreVaultScopeGuard } from "../vault/popup/guards/restore-vault-scope.guard";
|
||||
import { restrictedCipherGuard } from "../vault/popup/guards/restricted-cipher.guard";
|
||||
import { AdminSettingsComponent } from "../vault/popup/settings/admin-settings.component";
|
||||
import { AppearanceComponent } from "../vault/popup/settings/appearance.component";
|
||||
import { ArchiveComponent } from "../vault/popup/settings/archive.component";
|
||||
@@ -271,7 +273,11 @@ const routes: Routes = [
|
||||
{
|
||||
path: "edit-cipher",
|
||||
component: AddEditComponent,
|
||||
canActivate: [authGuard, debounceNavigationGuard()],
|
||||
canActivate: [
|
||||
authGuard,
|
||||
debounceNavigationGuard(),
|
||||
restrictedCipherGuard(RestrictedCipherAction.Edit),
|
||||
],
|
||||
data: {
|
||||
// Above "trash"
|
||||
elevation: 3,
|
||||
@@ -425,7 +431,7 @@ const routes: Routes = [
|
||||
{
|
||||
path: "clone-cipher",
|
||||
component: AddEditComponent,
|
||||
canActivate: [authGuard],
|
||||
canActivate: [authGuard, restrictedCipherGuard(RestrictedCipherAction.Clone)],
|
||||
data: { elevation: 1 } satisfies RouteDataProperties,
|
||||
},
|
||||
{
|
||||
@@ -735,7 +741,7 @@ const routes: Routes = [
|
||||
{
|
||||
path: "assign-collections",
|
||||
component: AssignCollections,
|
||||
canActivate: [authGuard],
|
||||
canActivate: [authGuard, restrictedCipherGuard(RestrictedCipherAction.AssignCollections)],
|
||||
data: { elevation: 1 } satisfies RouteDataProperties,
|
||||
},
|
||||
{
|
||||
|
||||
@@ -17,6 +17,7 @@ import { mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
@@ -55,6 +56,7 @@ describe("AddEditComponent", () => {
|
||||
let vaultPopupAutofillService: MockProxy<VaultPopupAutofillService>;
|
||||
|
||||
const buildConfigResponse = { originalCipher: {} } as CipherFormConfig;
|
||||
const revealedCipherService = mock<RevealedCipherService>();
|
||||
const buildConfig = jest.fn((mode) => Promise.resolve({ ...buildConfigResponse, mode }));
|
||||
const queryParams$ = new BehaviorSubject({});
|
||||
const disable = jest.fn();
|
||||
@@ -68,6 +70,7 @@ describe("AddEditComponent", () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
buildConfig.mockClear();
|
||||
revealedCipherService.refresh.mockClear();
|
||||
disable.mockClear();
|
||||
navigate.mockClear();
|
||||
back.mockClear();
|
||||
@@ -102,6 +105,7 @@ describe("AddEditComponent", () => {
|
||||
{ provide: Router, useValue: { navigate } },
|
||||
{ provide: ActivatedRoute, useValue: { queryParams: queryParams$ } },
|
||||
{ provide: I18nService, useValue: { t: (key: string) => key } },
|
||||
{ provide: RevealedCipherService, useValue: revealedCipherService },
|
||||
{ provide: CipherService, useValue: cipherServiceMock },
|
||||
{ provide: EventCollectionService, useValue: { collect } },
|
||||
{ provide: LogService, useValue: mock<LogService>() },
|
||||
@@ -406,6 +410,25 @@ describe("AddEditComponent", () => {
|
||||
expect(back).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reads the revealed view again after saving a restricted cipher", async () => {
|
||||
component.config.mode = "edit";
|
||||
component.config.originalCipher = Object.assign(new Cipher(), { partialData: {} });
|
||||
|
||||
await component.onCipherSaved({ id: "123-456-789" } as CipherView);
|
||||
|
||||
expect(revealedCipherService.refresh).toHaveBeenCalledWith(expect.anything(), "123-456-789");
|
||||
expect(back).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not read a revealed view after saving a cipher that is not restricted", async () => {
|
||||
component.config.mode = "edit";
|
||||
component.config.originalCipher = new Cipher();
|
||||
|
||||
await component.onCipherSaved({ id: "123-456-789" } as CipherView);
|
||||
|
||||
expect(revealedCipherService.refresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each<CipherFormMode>(["add", "edit", "partial-edit"])(
|
||||
"sends the addEditCipherSubmitted message when a cipher is edited, added or partially edited",
|
||||
async (mode) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import { CommonModule } from "@angular/common";
|
||||
import { Component, OnInit, OnDestroy, viewChild } from "@angular/core";
|
||||
import { Component, inject, OnInit, OnDestroy, viewChild } from "@angular/core";
|
||||
import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop";
|
||||
import { FormsModule } from "@angular/forms";
|
||||
import { ActivatedRoute, Params, Router } from "@angular/router";
|
||||
@@ -21,10 +21,12 @@ import { CipherId, CollectionId, OrganizationId, UserId } from "@bitwarden/commo
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { PremiumUpgradePromptService } from "@bitwarden/common/vault/abstractions/premium-upgrade-prompt.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { CipherType, toCipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { AddEditCipherInfo } from "@bitwarden/common/vault/types/add-edit-cipher-info";
|
||||
import { RestrictedCipherPolicy } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import {
|
||||
AsyncActionsModule,
|
||||
ButtonModule,
|
||||
@@ -218,6 +220,7 @@ export class AddEditComponent implements OnInit, OnDestroy {
|
||||
private fido2PopoutSessionData: Fido2SessionData;
|
||||
|
||||
protected userId$ = this.accountService.activeAccount$.pipe(getUserId);
|
||||
private readonly revealedCipherService = inject(RevealedCipherService);
|
||||
protected userCanArchive$ = this.userId$.pipe(
|
||||
switchMap((userId) => this.archiveService.userCanArchive$(userId)),
|
||||
);
|
||||
@@ -370,6 +373,16 @@ export class AddEditComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
// The revealed view of a restricted cipher is a separate copy. Read it again, so the view shows
|
||||
// the save.
|
||||
if (
|
||||
this.config.originalCipher != null &&
|
||||
RestrictedCipherPolicy.isRestricted(this.config.originalCipher)
|
||||
) {
|
||||
const userId = await firstValueFrom(this.userId$);
|
||||
await this.revealedCipherService.refresh(userId, cipher.id as CipherId);
|
||||
}
|
||||
|
||||
// When the cipher is in edit / partial edit, the previous page was the view-cipher page.
|
||||
// In the case of creating a new cipher, the user should go view-cipher page but we need to also
|
||||
// remove it from the history stack. This avoids the user having to click back twice on the
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<vault-item-copy-actions
|
||||
[cipher]="cipher()"
|
||||
[showQuickCopyActions]="(showQuickCopyActions$ | async) ?? false"
|
||||
></vault-item-copy-actions>
|
||||
@if (!restricted()) {
|
||||
<vault-item-copy-actions
|
||||
[cipher]="cipher()"
|
||||
[showQuickCopyActions]="(showQuickCopyActions$ | async) ?? false"
|
||||
></vault-item-copy-actions>
|
||||
}
|
||||
|
||||
@@ -65,6 +65,16 @@ describe("ItemCopyActionsComponent", () => {
|
||||
expect(sharedComponent.showQuickCopyActions()).toBe(true);
|
||||
});
|
||||
|
||||
it("renders no copy actions for a restricted cipher without a revealed view", () => {
|
||||
fixture.componentRef.setInput("cipher", {
|
||||
name: "Restricted",
|
||||
partial: true,
|
||||
} as CipherViewLike);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.query(By.directive(VaultItemCopyActionsComponent))).toBeNull();
|
||||
});
|
||||
|
||||
it("passes quick copy mode through when disabled by the popup service", () => {
|
||||
showQuickCopyActionsSubject.next(false);
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { AsyncPipe } from "@angular/common";
|
||||
import { Component, input, inject } from "@angular/core";
|
||||
import { Component, computed, input, inject } from "@angular/core";
|
||||
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { RestrictedCipherPolicy } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import { VaultCopyButtonsService, VaultItemCopyActionsComponent } from "@bitwarden/vault";
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
@@ -15,4 +16,9 @@ export class ItemCopyActionsComponent {
|
||||
protected showQuickCopyActions$ = inject(VaultCopyButtonsService).showQuickCopyActions$;
|
||||
|
||||
readonly cipher = input.required<CipherViewLike>();
|
||||
|
||||
/** A restricted cipher without a revealed view has nothing to copy. */
|
||||
protected readonly restricted = computed(() =>
|
||||
RestrictedCipherPolicy.isRestricted(this.cipher()),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,6 +18,19 @@
|
||||
{{ "view" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@for (action of contributedActions; track action.id) {
|
||||
@if (action.show?.(cipher) ?? true) {
|
||||
<button
|
||||
type="button"
|
||||
bitMenuItem
|
||||
[variant]="action.variant ?? 'primary'"
|
||||
[disabled]="action.disabled?.(cipher) ?? false"
|
||||
(click)="action.run(cipher)"
|
||||
>
|
||||
{{ action.label }}
|
||||
</button>
|
||||
}
|
||||
}
|
||||
<button type="button" bitMenuItem (click)="toggleFavorite()">
|
||||
{{ favoriteText | i18n }}
|
||||
</button>
|
||||
@@ -27,20 +40,22 @@
|
||||
</button>
|
||||
}
|
||||
@if (canEdit && canViewPassword) {
|
||||
@if (canClone$ | async) {
|
||||
@if ((canClone$ | async) && allows(RestrictedCipherAction.Clone)) {
|
||||
<a bitMenuItem (click)="clone()">
|
||||
{{ "clone" | i18n }}
|
||||
</a>
|
||||
}
|
||||
@if (canAssignCollections$ | async) {
|
||||
@if ((canAssignCollections$ | async) && allows(RestrictedCipherAction.AssignCollections)) {
|
||||
<a bitMenuItem (click)="conditionallyNavigateToAssignCollections()">
|
||||
{{ "assignToCollections" | vfo1I18n: "addToSharedFolder" }}
|
||||
</a>
|
||||
}
|
||||
}
|
||||
<a bitMenuItem *appShareLinkMenuItem="cipher; let share = share" (click)="share()">
|
||||
{{ "shareViaLink" | i18n }}
|
||||
</a>
|
||||
@if (!isLocked && allows(RestrictedCipherAction.Share)) {
|
||||
<a bitMenuItem *appShareLinkMenuItem="cipher; let share = share" (click)="share()">
|
||||
{{ "shareViaLink" | i18n }}
|
||||
</a>
|
||||
}
|
||||
@if (canArchive$ | async) {
|
||||
<button type="button" bitMenuItem (click)="archive()">
|
||||
{{ "archiveVerb" | i18n }}
|
||||
@@ -61,7 +76,7 @@
|
||||
</button>
|
||||
}
|
||||
}
|
||||
@if (canDelete$ | async) {
|
||||
@if ((canDelete$ | async) && allows(RestrictedCipherAction.Delete)) {
|
||||
<button type="button" bitMenuItem variant="danger" (click)="delete()">
|
||||
{{ "delete" | i18n }}
|
||||
</button>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { OverlayContainer } from "@angular/cdk/overlay";
|
||||
import { CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";
|
||||
import { ComponentFixture, TestBed, waitForAsync } from "@angular/core/testing";
|
||||
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
|
||||
@@ -15,14 +16,23 @@ import {
|
||||
} from "@bitwarden/common/models/domain/domain-service";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { CipherId } from "@bitwarden/common/types/guid";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { RestrictedItemTypesService } from "@bitwarden/common/vault/services/restricted-item-types.service";
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { RestrictedCipherAction } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import { DialogService, ToastService } from "@bitwarden/components";
|
||||
import { ShareLinkService } from "@bitwarden/tools-share";
|
||||
import { PasswordRepromptService } from "@bitwarden/vault";
|
||||
import {
|
||||
PasswordRepromptService,
|
||||
VAULT_ROW_ACTIONS,
|
||||
type VaultItemsTableRowAction,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { VaultPopupAutofillService } from "../../../services/vault-popup-autofill.service";
|
||||
import { VaultPopupItemsService } from "../../../services/vault-popup-items.service";
|
||||
@@ -42,6 +52,8 @@ describe("ItemMoreOptionsComponent", () => {
|
||||
open: jest.fn(),
|
||||
};
|
||||
const cipherService = {
|
||||
get: jest.fn(),
|
||||
decrypt: jest.fn(),
|
||||
getFullCipherView: jest.fn(),
|
||||
encrypt: jest.fn(),
|
||||
updateWithServer: jest.fn(),
|
||||
@@ -65,6 +77,11 @@ describe("ItemMoreOptionsComponent", () => {
|
||||
getUrlEquivalentDomains: jest.fn().mockReturnValue(of(new Set<string>())),
|
||||
};
|
||||
|
||||
const revealedCipherService = mock<RevealedCipherService>();
|
||||
let revealed$: BehaviorSubject<ReadonlyMap<CipherId, CipherView>>;
|
||||
/** Contributed menu actions (`VAULT_ROW_ACTIONS`), read when the component is created. */
|
||||
let rowActions: VaultItemsTableRowAction<CipherViewLike>[];
|
||||
|
||||
const baseCipher = {
|
||||
id: "cipher-1",
|
||||
login: {
|
||||
@@ -85,12 +102,22 @@ describe("ItemMoreOptionsComponent", () => {
|
||||
|
||||
beforeEach(waitForAsync(async () => {
|
||||
jest.clearAllMocks();
|
||||
rowActions = [];
|
||||
await setup();
|
||||
}));
|
||||
|
||||
/** Builds the testing module and the component. Call again after a reset to change its inputs. */
|
||||
async function setup() {
|
||||
revealed$ = new BehaviorSubject<ReadonlyMap<CipherId, CipherView>>(new Map());
|
||||
revealedCipherService.revealed$.mockReturnValue(revealed$);
|
||||
|
||||
cipherService.getFullCipherView.mockImplementation(async (c) => ({ ...baseCipher, ...c }));
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [ItemMoreOptionsComponent, NoopAnimationsModule],
|
||||
providers: [
|
||||
{ provide: RevealedCipherService, useValue: revealedCipherService },
|
||||
{ provide: VAULT_ROW_ACTIONS, useFactory: () => rowActions },
|
||||
{ provide: CipherService, useValue: cipherService },
|
||||
{ provide: VaultPopupAutofillService, useValue: autofillSvc },
|
||||
|
||||
@@ -134,7 +161,7 @@ describe("ItemMoreOptionsComponent", () => {
|
||||
fixture = TestBed.createComponent(ItemMoreOptionsComponent);
|
||||
component = fixture.componentInstance;
|
||||
component.cipher = baseCipher;
|
||||
}));
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
@@ -399,6 +426,78 @@ describe("ItemMoreOptionsComponent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("restricted ciphers", () => {
|
||||
it("offers only the user fields for a restricted cipher without a revealed view", () => {
|
||||
component.cipher = { ...baseCipher, partial: true };
|
||||
|
||||
expect(component.canEdit).toBe(false);
|
||||
expect(component.canAutofill).toBe(false);
|
||||
expect(component["allows"](RestrictedCipherAction.Share)).toBe(false);
|
||||
expect(component["allows"](RestrictedCipherAction.UserFields)).toBe(true);
|
||||
});
|
||||
|
||||
it("allows edit, but not clone or delete, while a reveal of its restricted cipher is live", () => {
|
||||
const restricted = { ...baseCipher, partial: true } as CipherView;
|
||||
component.cipher = restricted;
|
||||
expect(component["isLocked"]).toBe(true);
|
||||
|
||||
revealed$.next(
|
||||
new Map([["cipher-1" as CipherId, { ...baseCipher, partial: false } as CipherView]]),
|
||||
);
|
||||
|
||||
expect(component["isLocked"]).toBe(false);
|
||||
expect(component.canEdit).toBe(true);
|
||||
expect(component["allows"](RestrictedCipherAction.Delete)).toBe(false);
|
||||
expect(component["allows"](RestrictedCipherAction.Clone)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows edit of a revealed view, but not share or assign collections", () => {
|
||||
const revealed = { ...baseCipher, partial: false } as CipherView;
|
||||
revealed$.next(new Map([["cipher-1" as CipherId, revealed]]));
|
||||
component.cipher = revealed;
|
||||
|
||||
expect(component.canEdit).toBe(true);
|
||||
expect(component.canAutofill).toBe(true);
|
||||
expect(component["allows"](RestrictedCipherAction.Share)).toBe(false);
|
||||
expect(component["allows"](RestrictedCipherAction.AssignCollections)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toggleFavorite", () => {
|
||||
beforeEach(() => {
|
||||
cipherService.get.mockResolvedValue({ id: "cipher-1" });
|
||||
});
|
||||
|
||||
it("saves the stored copy of a revealed row and reads the reveal again", async () => {
|
||||
const revealed = { ...baseCipher, partial: false } as CipherView;
|
||||
revealed$.next(new Map([["cipher-1" as CipherId, revealed]]));
|
||||
component.cipher = revealed;
|
||||
cipherService.decrypt.mockResolvedValue({ ...baseCipher, partial: true });
|
||||
|
||||
await component.toggleFavorite();
|
||||
|
||||
expect(cipherService.get).toHaveBeenCalledWith("cipher-1", "UserId");
|
||||
expect(cipherService.updateWithServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ partial: true, favorite: true }),
|
||||
"UserId",
|
||||
);
|
||||
expect(revealed.favorite).toBe(false);
|
||||
expect(revealedCipherService.refresh).toHaveBeenCalledWith("UserId", "cipher-1");
|
||||
});
|
||||
|
||||
it("does not read a reveal again for a row without one", async () => {
|
||||
cipherService.decrypt.mockResolvedValue({ ...baseCipher });
|
||||
|
||||
await component.toggleFavorite();
|
||||
|
||||
expect(cipherService.updateWithServer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ favorite: true }),
|
||||
"UserId",
|
||||
);
|
||||
expect(revealedCipherService.refresh).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("canAssignCollections$", () => {
|
||||
it("emits true when user has organizations and editable collections", (done) => {
|
||||
jest.spyOn(component["organizationService"], "hasOrganizations").mockReturnValue(of(true));
|
||||
@@ -436,4 +535,155 @@ describe("ItemMoreOptionsComponent", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("restricted cipher menu", () => {
|
||||
let overlayContainer: OverlayContainer;
|
||||
|
||||
const restrictedCipher = { ...baseCipher, partial: true, favorite: false };
|
||||
|
||||
function menuTrigger(): HTMLButtonElement | null {
|
||||
return fixture.nativeElement.querySelector('button[biticonbutton="bwi-ellipsis-v"]');
|
||||
}
|
||||
|
||||
function openMenu(): HTMLElement {
|
||||
fixture.detectChanges();
|
||||
menuTrigger()!.click();
|
||||
fixture.detectChanges();
|
||||
return overlayContainer.getContainerElement();
|
||||
}
|
||||
|
||||
function menuItems(): string[] {
|
||||
return Array.from(
|
||||
openMenu().querySelectorAll<HTMLElement>("[bitmenuitem]"),
|
||||
(item) => item.textContent?.trim() ?? "",
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
overlayContainer = TestBed.inject(OverlayContainer);
|
||||
fixture.componentRef.setInput("showAutofill", true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
overlayContainer.ngOnDestroy();
|
||||
});
|
||||
|
||||
it("offers Favorite and Archive, but not Autofill, Edit, Clone or Delete, without a reveal", () => {
|
||||
component.cipher = restrictedCipher;
|
||||
|
||||
expect(menuItems()).toEqual(["favorite", "archiveVerb"]);
|
||||
});
|
||||
|
||||
it("offers Edit, but not Clone or Delete, on a revealed row", () => {
|
||||
const revealed = { ...baseCipher, partial: false } as CipherView;
|
||||
revealed$.next(new Map([["cipher-1" as CipherId, revealed]]));
|
||||
component.cipher = revealed;
|
||||
|
||||
const items = menuItems();
|
||||
|
||||
expect(items).toContain("edit");
|
||||
expect(items).not.toContain("clone");
|
||||
expect(items).not.toContain("delete");
|
||||
});
|
||||
|
||||
it("keeps the overflow trigger for a restricted row", () => {
|
||||
component.cipher = restrictedCipher;
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(menuTrigger()).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("contributed actions", () => {
|
||||
let overlayContainer: OverlayContainer;
|
||||
|
||||
const action = (
|
||||
id: string,
|
||||
overrides: Partial<VaultItemsTableRowAction<CipherViewLike>> = {},
|
||||
): VaultItemsTableRowAction<CipherViewLike> => ({
|
||||
id,
|
||||
label: id,
|
||||
icon: "bwi-lock",
|
||||
run: jest.fn(),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
async function provideActions(actions: VaultItemsTableRowAction<CipherViewLike>[]) {
|
||||
TestBed.resetTestingModule();
|
||||
rowActions = actions;
|
||||
await setup();
|
||||
overlayContainer = TestBed.inject(OverlayContainer);
|
||||
}
|
||||
|
||||
function openMenu(): HTMLElement {
|
||||
fixture.detectChanges();
|
||||
fixture.nativeElement.querySelector('button[biticonbutton="bwi-ellipsis-v"]')!.click();
|
||||
fixture.detectChanges();
|
||||
return overlayContainer.getContainerElement();
|
||||
}
|
||||
|
||||
function menuItem(label: string): HTMLButtonElement | undefined {
|
||||
return Array.from(openMenu().querySelectorAll<HTMLButtonElement>("[bitmenuitem]")).find(
|
||||
(item) => item.textContent?.trim() === label,
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
overlayContainer?.ngOnDestroy();
|
||||
});
|
||||
|
||||
it("shows contributed actions after View and before Favorite, in order", async () => {
|
||||
await provideActions([action("first"), action("second")]);
|
||||
fixture.componentRef.setInput("showViewOption", true);
|
||||
|
||||
const labels = Array.from(openMenu().querySelectorAll<HTMLElement>("[bitmenuitem]"), (item) =>
|
||||
item.textContent?.trim(),
|
||||
);
|
||||
|
||||
expect(labels.slice(0, 4)).toEqual(["view", "first", "second", "favorite"]);
|
||||
});
|
||||
|
||||
it("hides an action whose show returns false for the row", async () => {
|
||||
const show = jest.fn().mockReturnValue(false);
|
||||
await provideActions([action("hidden", { show })]);
|
||||
|
||||
expect(menuItem("hidden")).toBeUndefined();
|
||||
expect(show).toHaveBeenCalledWith(baseCipher);
|
||||
});
|
||||
|
||||
it("disables an action whose disabled returns true for the row", async () => {
|
||||
await provideActions([action("disabled", { disabled: () => true }), action("enabled")]);
|
||||
|
||||
const items = Array.from(openMenu().querySelectorAll<HTMLButtonElement>("[bitmenuitem]"));
|
||||
const item = (label: string) => items.find((i) => i.textContent?.trim() === label);
|
||||
|
||||
expect(item("disabled")?.disabled).toBe(true);
|
||||
expect(item("enabled")?.disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("runs the action with the row's cipher", async () => {
|
||||
const run = jest.fn();
|
||||
await provideActions([action("run", { run })]);
|
||||
|
||||
menuItem("run")!.click();
|
||||
|
||||
expect(run).toHaveBeenCalledWith(baseCipher);
|
||||
});
|
||||
|
||||
it("shows contributed actions on a restricted row", async () => {
|
||||
await provideActions([action("request")]);
|
||||
component.cipher = { ...baseCipher, partial: true };
|
||||
|
||||
expect(menuItem("request")).toBeDefined();
|
||||
});
|
||||
|
||||
it("throws in dev mode when an action ID matches a built-in action", async () => {
|
||||
TestBed.resetTestingModule();
|
||||
rowActions = [action("edit")];
|
||||
|
||||
await expect(setup()).rejects.toThrow(
|
||||
'VAULT_ROW_ACTIONS action ID "edit" is already in use.',
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { CommonModule } from "@angular/common";
|
||||
import { booleanAttribute, Component, input, Input } from "@angular/core";
|
||||
import { booleanAttribute, Component, inject, input, Input } from "@angular/core";
|
||||
import { toSignal } from "@angular/core/rxjs-interop";
|
||||
import { Router, RouterModule } from "@angular/router";
|
||||
import { BehaviorSubject, combineLatest, firstValueFrom, map, Observable, switchMap } from "rxjs";
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
firstValueFrom,
|
||||
map,
|
||||
Observable,
|
||||
of,
|
||||
switchMap,
|
||||
} from "rxjs";
|
||||
import { filter } from "rxjs/operators";
|
||||
|
||||
import { CollectionService } from "@bitwarden/admin-console/common";
|
||||
@@ -13,10 +22,12 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { CipherId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { uuidAsString } from "@bitwarden/common/platform/abstractions/sdk/sdk.service";
|
||||
import { CipherId } from "@bitwarden/common/types/guid";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { PremiumUpgradePromptService } from "@bitwarden/common/vault/abstractions/premium-upgrade-prompt.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { RestrictedItemTypesService } from "@bitwarden/common/vault/services/restricted-item-types.service";
|
||||
@@ -24,6 +35,10 @@ import {
|
||||
CipherViewLike,
|
||||
CipherViewLikeUtils,
|
||||
} from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import {
|
||||
RestrictedCipherAction,
|
||||
RestrictedCipherPolicy,
|
||||
} from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import {
|
||||
DialogService,
|
||||
IconButtonModule,
|
||||
@@ -33,7 +48,12 @@ import {
|
||||
IconModule,
|
||||
} from "@bitwarden/components";
|
||||
import { ShareLinkMenuItemDirective } from "@bitwarden/tools-share";
|
||||
import { PasswordRepromptService, Vfo1I18nPipe } from "@bitwarden/vault";
|
||||
import {
|
||||
PasswordRepromptService,
|
||||
uniqueContributedActions,
|
||||
VAULT_ROW_ACTIONS,
|
||||
Vfo1I18nPipe,
|
||||
} from "@bitwarden/vault";
|
||||
|
||||
import { VaultPopupAutofillService } from "../../../services/vault-popup-autofill.service";
|
||||
import { AddEditQueryParams } from "../add-edit/add-edit.component";
|
||||
@@ -42,6 +62,20 @@ import {
|
||||
AutofillConfirmationDialogResult,
|
||||
} from "../autofill-confirmation-dialog/autofill-confirmation-dialog.component";
|
||||
|
||||
/** IDs of the menu's own actions. Contributed action IDs must differ. */
|
||||
const BUILT_IN_ACTION_IDS: ReadonlySet<string> = new Set([
|
||||
"autofill",
|
||||
"view",
|
||||
"addFavorite",
|
||||
"removeFavorite",
|
||||
"edit",
|
||||
"clone",
|
||||
"addToSharedFolder",
|
||||
"shareViaLink",
|
||||
"archive",
|
||||
"delete",
|
||||
]);
|
||||
|
||||
// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush
|
||||
// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection
|
||||
@Component({
|
||||
@@ -94,6 +128,29 @@ export class ItemMoreOptionsComponent {
|
||||
|
||||
protected autofillAllowed$ = this.vaultPopupAutofillService.autofillAllowed$;
|
||||
|
||||
protected readonly RestrictedCipherAction = RestrictedCipherAction;
|
||||
private readonly revealedCipherService = inject(RevealedCipherService);
|
||||
|
||||
/** Actions another feature adds (`VAULT_ROW_ACTIONS`), shown after View. */
|
||||
protected readonly contributedActions = uniqueContributedActions(
|
||||
inject(VAULT_ROW_ACTIONS, { optional: true }) ?? [],
|
||||
BUILT_IN_ACTION_IDS,
|
||||
);
|
||||
|
||||
/** The live revealed view of this row's restricted cipher, if any. */
|
||||
private readonly revealedView = toSignal(
|
||||
combineLatest([this._cipher$, this.accountService.activeAccount$.pipe(getUserId)]).pipe(
|
||||
switchMap(([cipher, userId]) =>
|
||||
cipher?.id == null
|
||||
? of(undefined)
|
||||
: this.revealedCipherService
|
||||
.revealed$(userId)
|
||||
.pipe(map((revealed) => revealed.get(cipher.id as CipherId))),
|
||||
),
|
||||
),
|
||||
{ initialValue: undefined },
|
||||
);
|
||||
|
||||
/**
|
||||
* Observable that emits a boolean value indicating if the user is authorized to clone the cipher.
|
||||
* @protected
|
||||
@@ -157,8 +214,29 @@ export class ItemMoreOptionsComponent {
|
||||
private domainSettingsService: DomainSettingsService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* A restricted item arrives as a reduced partial envelope: there is nothing to edit or fill until
|
||||
* it is revealed, and the form and autofill paths do not exclude partials themselves.
|
||||
*/
|
||||
get isPartial() {
|
||||
return RestrictedCipherPolicy.isRestricted(this.cipher);
|
||||
}
|
||||
|
||||
/**
|
||||
* True for a restricted item with no live revealed view: only the view option remains. While a
|
||||
* reveal is live, the restricted-cipher policy decides each action instead.
|
||||
*/
|
||||
protected get isLocked() {
|
||||
return this.isPartial && this.revealedView() == null;
|
||||
}
|
||||
|
||||
get canEdit() {
|
||||
return this.cipher.edit;
|
||||
return this.cipher.edit && this.allows(RestrictedCipherAction.Edit);
|
||||
}
|
||||
|
||||
/** False when the restricted-cipher rule blocks the action. */
|
||||
protected allows(action: RestrictedCipherAction): boolean {
|
||||
return RestrictedCipherPolicy.allows(this.cipher, action, this.revealedView());
|
||||
}
|
||||
|
||||
get canViewPassword() {
|
||||
@@ -173,9 +251,13 @@ export class ItemMoreOptionsComponent {
|
||||
* Determines if the cipher can be autofilled.
|
||||
*/
|
||||
get canAutofill() {
|
||||
// A restricted cipher without a revealed view has nothing to fill.
|
||||
return (
|
||||
[CipherType.Login, CipherType.Card, CipherType.Identity, CipherType.SshKey] as CipherType[]
|
||||
).includes(CipherViewLikeUtils.getType(this.cipher));
|
||||
!this.isLocked &&
|
||||
(
|
||||
[CipherType.Login, CipherType.Card, CipherType.Identity, CipherType.SshKey] as CipherType[]
|
||||
).includes(CipherViewLikeUtils.getType(this.cipher))
|
||||
);
|
||||
}
|
||||
|
||||
get isLogin() {
|
||||
@@ -226,7 +308,11 @@ export class ItemMoreOptionsComponent {
|
||||
data: {
|
||||
currentUrl: currentTab?.url || "",
|
||||
savedUris: cipher.login?.uris?.filter((u) => u.uri) ?? [],
|
||||
viewOnly: !this.cipher.edit,
|
||||
// Adding the URL saves the cipher outside the edit form, which a restricted cipher refuses.
|
||||
viewOnly:
|
||||
!this.cipher.edit ||
|
||||
RestrictedCipherPolicy.isRestricted(this.cipher) ||
|
||||
this.revealedView() != null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -269,14 +355,18 @@ export class ItemMoreOptionsComponent {
|
||||
* Toggles the favorite status of the cipher and updates it on the server.
|
||||
*/
|
||||
async toggleFavorite() {
|
||||
const cipher = await this.cipherService.getFullCipherView(this.cipher);
|
||||
const activeUserId = await firstValueFrom(this.accountService.activeAccount$.pipe(getUserId));
|
||||
// Change the stored copy, not the row: a revealed row is the shared revealed view.
|
||||
const stored = await this.cipherService.get(uuidAsString(this.cipher.id!), activeUserId);
|
||||
const cipher = await this.cipherService.decrypt(stored, activeUserId);
|
||||
|
||||
cipher.favorite = !cipher.favorite;
|
||||
const activeUserId = (await firstValueFrom(
|
||||
this.accountService.activeAccount$.pipe(map((a) => a?.id)),
|
||||
)) as UserId;
|
||||
|
||||
await this.cipherService.updateWithServer(cipher, activeUserId);
|
||||
|
||||
if (this.revealedView() != null) {
|
||||
await this.revealedCipherService.refresh(activeUserId, cipher.id as CipherId);
|
||||
}
|
||||
|
||||
this.toastService.showToast({
|
||||
variant: "success",
|
||||
message: this.i18nService.t(
|
||||
|
||||
@@ -11,6 +11,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
|
||||
import { mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
|
||||
@@ -31,6 +32,7 @@ describe("PasswordHistoryComponent", () => {
|
||||
const mockCipher = {} as unknown as Cipher;
|
||||
|
||||
const back = jest.fn().mockResolvedValue(undefined);
|
||||
const revealedCipherService = mock<RevealedCipherService>();
|
||||
const cipherView$ = jest
|
||||
.fn()
|
||||
.mockReturnValue(new BehaviorSubject<Cipher | undefined>(mockCipher));
|
||||
@@ -45,6 +47,7 @@ describe("PasswordHistoryComponent", () => {
|
||||
{ provide: WINDOW, useValue: window },
|
||||
{ provide: PlatformUtilsService, useValue: mock<PlatformUtilsService>() },
|
||||
{ provide: ConfigService, useValue: mock<ConfigService>() },
|
||||
{ provide: RevealedCipherService, useValue: revealedCipherService },
|
||||
{
|
||||
provide: CipherService,
|
||||
useValue: mock<CipherService>({
|
||||
@@ -73,6 +76,18 @@ describe("PasswordHistoryComponent", () => {
|
||||
expect(cipherView$).toHaveBeenCalledWith(mockUserId, mockCipherView.id);
|
||||
}));
|
||||
|
||||
it("falls back to the revealed view of a restricted cipher", fakeAsync(() => {
|
||||
const revealed = { id: mockCipherView.id, name: "revealed" } as CipherView;
|
||||
cipherView$.mockReturnValueOnce(new BehaviorSubject<CipherView | undefined>(undefined));
|
||||
revealedCipherService.get.mockReturnValueOnce(revealed);
|
||||
|
||||
params$.next({ cipherId: mockCipherView.id });
|
||||
tick(100);
|
||||
|
||||
expect(revealedCipherService.get).toHaveBeenCalledWith(mockUserId, mockCipherView.id);
|
||||
expect(fixture.componentInstance["cipher"]).toBe(revealed);
|
||||
}));
|
||||
|
||||
it("navigates back when a cipherId is not in the params", () => {
|
||||
params$.next({});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// FIXME: Update this file to be type safe and remove this and next line
|
||||
// @ts-strict-ignore
|
||||
import { Component, OnInit } from "@angular/core";
|
||||
import { Component, inject, OnInit } from "@angular/core";
|
||||
import { ActivatedRoute } from "@angular/router";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
import { first, map } from "rxjs/operators";
|
||||
@@ -9,6 +9,7 @@ import { JslibModule } from "@bitwarden/angular/jslib.module";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { CipherId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { PasswordHistoryViewComponent } from "@bitwarden/vault";
|
||||
|
||||
@@ -32,6 +33,7 @@ import { PopupRouterCacheService } from "../../../../../platform/popup/view-cach
|
||||
})
|
||||
export class PasswordHistoryComponent implements OnInit {
|
||||
protected cipher: CipherView;
|
||||
private readonly revealedCipherService = inject(RevealedCipherService);
|
||||
|
||||
constructor(
|
||||
private browserRouterHistory: PopupRouterCacheService,
|
||||
@@ -67,8 +69,9 @@ export class PasswordHistoryComponent implements OnInit {
|
||||
|
||||
const activeUserId = activeAccount.id as UserId;
|
||||
|
||||
this.cipher = await firstValueFrom(
|
||||
this.cipherService.cipherView$(activeUserId, cipherId as CipherId),
|
||||
);
|
||||
// A restricted cipher's history exists only in its revealed view.
|
||||
this.cipher =
|
||||
(await firstValueFrom(this.cipherService.cipherView$(activeUserId, cipherId as CipherId))) ??
|
||||
this.revealedCipherService.get(activeUserId, cipherId as CipherId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,6 +91,24 @@
|
||||
[options]="nestedFolderOptions()"
|
||||
></bit-filter-menu>
|
||||
}
|
||||
|
||||
@if (itemFilter != null && contributedFilterOptions().length) {
|
||||
<bit-filter-menu
|
||||
[key]="itemFilter.key"
|
||||
[placeholderText]="itemFilter.label"
|
||||
multiple
|
||||
[icon]="itemFilter.icon"
|
||||
>
|
||||
@for (option of contributedFilterOptions(); track option.id) {
|
||||
<bit-filter-option
|
||||
[value]="option.id"
|
||||
[iconTile]="contributedFilterTiles().get(option.id)"
|
||||
[count]="contributedFilterCount(option.id)"
|
||||
>{{ option.name }}</bit-filter-option
|
||||
>
|
||||
}
|
||||
</bit-filter-menu>
|
||||
}
|
||||
</bit-table-toolbar>
|
||||
<app-vault-filters-tour [toolbar]="toolbar" />
|
||||
<!--
|
||||
@@ -166,10 +184,13 @@
|
||||
[appA11yTitle]="'attachments' | i18n"
|
||||
></bit-icon>
|
||||
}
|
||||
@if (rowIcon) {
|
||||
<ng-container *ngComponentOutlet="rowIcon; inputs: { cipher: row.cipher }" />
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<span class="tw-text-muted tw-text-xs tw-truncate">
|
||||
{{ CipherViewLikeUtils.subtitle(row.cipher, i18nService) }}
|
||||
<app-vault-row-subtitle [cipher]="row.cipher"></app-vault-row-subtitle>
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
@@ -193,7 +214,9 @@
|
||||
[label]="'launchWebsiteForName' | i18n: row.cipher.name"
|
||||
></button>
|
||||
}
|
||||
<app-item-copy-actions [cipher]="row.cipher"></app-item-copy-actions>
|
||||
@if (row.actions.showCopyActions) {
|
||||
<app-item-copy-actions [cipher]="row.cipher"></app-item-copy-actions>
|
||||
}
|
||||
<app-item-more-options
|
||||
[cipher]="row.cipher"
|
||||
[showAutofill]="row.actions.showAutofillInMenu"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { LiveAnnouncer } from "@angular/cdk/a11y";
|
||||
import { signal } from "@angular/core";
|
||||
import { ChangeDetectionStrategy, Component, input, signal } from "@angular/core";
|
||||
import { ComponentFixture, TestBed, fakeAsync, tick } from "@angular/core/testing";
|
||||
import { By } from "@angular/platform-browser";
|
||||
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
|
||||
@@ -22,15 +22,18 @@ import { ConfigService } from "@bitwarden/common/platform/abstractions/config/co
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { CipherId, OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { FolderView } from "@bitwarden/common/vault/models/view/folder.view";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { NoopRevealedCipherService } from "@bitwarden/common/vault/services/noop-revealed-cipher.service";
|
||||
import { RestrictedItemTypesService } from "@bitwarden/common/vault/services/restricted-item-types.service";
|
||||
import { SearchTextDebounceInterval } from "@bitwarden/common/vault/services/search.service";
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import {
|
||||
ChipFilterOption,
|
||||
CompactModeService,
|
||||
@@ -47,7 +50,9 @@ import {
|
||||
CoachmarkService,
|
||||
NO_FOLDER,
|
||||
PasswordRepromptService,
|
||||
VAULT_ITEM_FILTER,
|
||||
VaultCopyButtonsService,
|
||||
VaultItemFilter,
|
||||
VaultNavItemType,
|
||||
VaultNavService,
|
||||
VaultScopeType,
|
||||
@@ -63,6 +68,7 @@ import { VaultPopupLoadingService } from "../../../services/vault-popup-loading.
|
||||
import { VaultPopupSectionService } from "../../../services/vault-popup-section.service";
|
||||
import { VaultPopupTourService } from "../../../services/vault-popup-tour.service";
|
||||
import { PopupCipherViewLike } from "../../../views/popup-cipher.view";
|
||||
import { VAULT_ROW_ICON, VaultRowIcon } from "../vault-row-slots/vault-row-icon.token";
|
||||
|
||||
import { VaultPopupListTableComponent } from "./vault-popup-list-table.component";
|
||||
|
||||
@@ -89,6 +95,18 @@ const makeRow = (
|
||||
overrides: Partial<PopupCipherViewLike> = {},
|
||||
) => ({ cipher: makeCipher(overrides), _section: section, actions: {} }) as any;
|
||||
|
||||
/** A contributed filter key unlike any built-in one, so the table must use the provider's key. */
|
||||
const FILTER_KEY = "accessStatus";
|
||||
|
||||
@Component({
|
||||
selector: "test-row-icon",
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `<span data-testid="row-icon">{{ cipher()?.id }}</span>`,
|
||||
})
|
||||
class TestRowIconComponent {
|
||||
readonly cipher = input<CipherViewLike | null>(null);
|
||||
}
|
||||
|
||||
describe("VaultPopupListTableComponent", () => {
|
||||
let fixture: ComponentFixture<VaultPopupListTableComponent>;
|
||||
let component: VaultPopupListTableComponent;
|
||||
@@ -156,6 +174,17 @@ describe("VaultPopupListTableComponent", () => {
|
||||
const suspendedVault$ = new BehaviorSubject<boolean>(false);
|
||||
const organizationNames$ = new BehaviorSubject<Map<string, string>>(new Map());
|
||||
|
||||
/** The contributed filter chip. Null leaves the seam unprovided, as in OSS builds. */
|
||||
let itemFilter: VaultItemFilter | null = null;
|
||||
/** The row icon slot. Null leaves it unprovided. */
|
||||
let rowIcon: VaultRowIcon | null = null;
|
||||
const contributedOptions$ = new BehaviorSubject<
|
||||
{ id: string; name: string; icon: "bwi-lock"; tileVariant?: "danger" }[]
|
||||
>([]);
|
||||
const contributedMatches$ = new BehaviorSubject<
|
||||
ReadonlyMap<string, ReadonlySet<CipherId>> | undefined
|
||||
>(undefined);
|
||||
|
||||
const vaultPopupListTableFiltersService = {
|
||||
restoreFilters$: jest.fn().mockReturnValue(of({})),
|
||||
saveFilters: jest.fn(),
|
||||
@@ -240,11 +269,21 @@ describe("VaultPopupListTableComponent", () => {
|
||||
collections$.next([]);
|
||||
folders$.next([]);
|
||||
vaultPopupListTableFiltersService.filterDialogOpen.set(false);
|
||||
vaultPopupListTableFiltersService.restoreFilters$.mockReturnValue(of({}));
|
||||
itemFilter = null;
|
||||
rowIcon = null;
|
||||
contributedOptions$.next([]);
|
||||
contributedMatches$.next(undefined);
|
||||
viewCacheSnapshot = {};
|
||||
nav$.next({ vaults: [], organizationDataOwnership: false });
|
||||
vaultNavService.viewModel$.mockReturnValue(nav$.asObservable());
|
||||
liveAnnouncer.announce.mockClear();
|
||||
|
||||
await createFixture();
|
||||
});
|
||||
|
||||
/** Builds the testing module and the component; `itemFilter` is read when it is first injected. */
|
||||
async function createFixture() {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VaultPopupListTableComponent, NoopAnimationsModule, RouterTestingModule],
|
||||
providers: [
|
||||
@@ -263,6 +302,8 @@ describe("VaultPopupListTableComponent", () => {
|
||||
},
|
||||
},
|
||||
{ provide: ConfigService, useValue: configService },
|
||||
{ provide: VAULT_ITEM_FILTER, useFactory: () => itemFilter },
|
||||
{ provide: VAULT_ROW_ICON, useFactory: () => rowIcon },
|
||||
{ provide: ImportUpgradeNavigationService, useValue: importUpgradeNavigationService },
|
||||
{ provide: VaultPopupAutofillService, useValue: vaultPopupAutofillService },
|
||||
{ provide: VaultPopupItemsService, useValue: vaultPopupItemsService },
|
||||
@@ -276,6 +317,7 @@ describe("VaultPopupListTableComponent", () => {
|
||||
{ provide: VaultNavService, useValue: vaultNavService },
|
||||
{ provide: I18nService, useValue: mock<I18nService>({ t: (k: string) => k }) },
|
||||
{ provide: LiveAnnouncer, useValue: liveAnnouncer },
|
||||
{ provide: RevealedCipherService, useClass: NoopRevealedCipherService },
|
||||
{ provide: CipherService, useValue: mock<CipherService>() },
|
||||
{ provide: AccountService, useValue: { activeAccount$: of({ id: "test-user-id" }) } },
|
||||
{ provide: PasswordRepromptService, useValue: mock<PasswordRepromptService>() },
|
||||
@@ -325,7 +367,7 @@ describe("VaultPopupListTableComponent", () => {
|
||||
component = fixture.componentInstance;
|
||||
router = TestBed.inject(Router);
|
||||
jest.spyOn(router, "navigate").mockResolvedValue(true);
|
||||
});
|
||||
}
|
||||
|
||||
describe("collapsible sections", () => {
|
||||
const headerToggle = (label: string): HTMLButtonElement | undefined =>
|
||||
@@ -574,6 +616,216 @@ describe("VaultPopupListTableComponent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("row icon slot", () => {
|
||||
const render = async () => {
|
||||
filteredCiphers$.next([makeCipher({ id: "all-1" })]);
|
||||
fixture.nativeElement.style.height = "600px";
|
||||
fixture.detectChanges();
|
||||
await fixture.whenStable();
|
||||
fixture.detectChanges();
|
||||
};
|
||||
const icons = (): HTMLElement[] =>
|
||||
Array.from(fixture.nativeElement.querySelectorAll("[data-testid='row-icon']"));
|
||||
|
||||
it("renders no extra icon when the slot is not provided", async () => {
|
||||
await render();
|
||||
|
||||
expect(icons()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("renders the provided component with the row's cipher", async () => {
|
||||
rowIcon = TestRowIconComponent;
|
||||
TestBed.resetTestingModule();
|
||||
await createFixture();
|
||||
await render();
|
||||
|
||||
expect(icons().map((icon) => icon.textContent)).toEqual(["all-1"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("contributed filter chip", () => {
|
||||
const matchesFor = jest.fn();
|
||||
const chipFor = (key: string) =>
|
||||
fixture.debugElement
|
||||
.queryAll(By.directive(FilterMenuComponent))
|
||||
.find((chip) => chip.componentInstance.key() === key)?.componentInstance;
|
||||
|
||||
const OPTIONS = [
|
||||
{ id: "privileged", name: "Privileged", icon: "bwi-lock" as const },
|
||||
{ id: "pending", name: "Pending approval", icon: "bwi-lock" as const },
|
||||
];
|
||||
|
||||
async function provideFilter() {
|
||||
matchesFor.mockImplementation(() => contributedMatches$.asObservable());
|
||||
itemFilter = {
|
||||
key: FILTER_KEY,
|
||||
label: "Controlled access",
|
||||
icon: "bwi-lock-encrypted",
|
||||
options$: contributedOptions$.asObservable(),
|
||||
matches$: matchesFor,
|
||||
};
|
||||
contributedOptions$.next(OPTIONS);
|
||||
// The component reads the provider at construction, and the module caches it.
|
||||
TestBed.resetTestingModule();
|
||||
return createFixture();
|
||||
}
|
||||
|
||||
const rowFor = (id: string) => makeRow("allItems", { id });
|
||||
|
||||
it("is absent when the seam is not provided", () => {
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(chipFor(FILTER_KEY)).toBeUndefined();
|
||||
expect(component["filterPredicate"](rowFor("a"), { [FILTER_KEY]: ["pending"] })).toBe(true);
|
||||
});
|
||||
|
||||
it("throws in dev mode when the provider's key matches a built-in chip key", async () => {
|
||||
itemFilter = {
|
||||
key: "folder",
|
||||
label: "Clash",
|
||||
options$: contributedOptions$.asObservable(),
|
||||
matches$: matchesFor,
|
||||
};
|
||||
TestBed.resetTestingModule();
|
||||
|
||||
await expect(createFixture()).rejects.toThrow(
|
||||
'VAULT_ITEM_FILTER key "folder" matches a built-in popup filter key.',
|
||||
);
|
||||
});
|
||||
|
||||
it("is absent while the provider offers no options, and reads no matches", async () => {
|
||||
await provideFilter();
|
||||
contributedOptions$.next([]);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(chipFor(FILTER_KEY)).toBeUndefined();
|
||||
expect(matchesFor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("renders a multi-select chip with the provider's label and icon", async () => {
|
||||
await provideFilter();
|
||||
fixture.detectChanges();
|
||||
|
||||
const chip = chipFor(FILTER_KEY) as FilterMenuComponent;
|
||||
expect(chip).toBeDefined();
|
||||
expect(chip.placeholderText()).toBe("Controlled access");
|
||||
expect(chip.icon()).toBe("bwi-lock-encrypted");
|
||||
expect(chip.multiple()).toBe(true);
|
||||
expect((chip["allOptions"]() as FilterOptionRow[]).map((o) => o.value())).toEqual([
|
||||
"privileged",
|
||||
"pending",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads matches off the unsearched list", async () => {
|
||||
const gated = makeCipher({ id: "a" });
|
||||
await provideFilter();
|
||||
activeCiphers$.next([gated]);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(matchesFor).toHaveBeenCalledWith([gated]);
|
||||
});
|
||||
|
||||
it("counts each option from the matches once they land, and not before", async () => {
|
||||
await provideFilter();
|
||||
filteredCiphers$.next([makeCipher({ id: "a" }), makeCipher({ id: "b" })]);
|
||||
fixture.nativeElement.style.height = "600px";
|
||||
fixture.detectChanges();
|
||||
const counts = () =>
|
||||
(chipFor(FILTER_KEY)["allOptions"]() as FilterOptionRow[]).map((o) => o.count());
|
||||
|
||||
expect(counts()).toEqual([undefined, undefined]);
|
||||
|
||||
contributedMatches$.next(
|
||||
new Map([
|
||||
["privileged", new Set(["a" as CipherId, "b" as CipherId])],
|
||||
["pending", new Set(["b" as CipherId])],
|
||||
]),
|
||||
);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(counts()).toEqual([2, 1]);
|
||||
});
|
||||
|
||||
describe("predicate", () => {
|
||||
beforeEach(async () => {
|
||||
await provideFilter();
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it("passes every row until the matches land", () => {
|
||||
expect(component["filterPredicate"](rowFor("a"), { [FILTER_KEY]: ["pending"] })).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps a row in any selected option and drops the rest", () => {
|
||||
contributedMatches$.next(
|
||||
new Map([
|
||||
["privileged", new Set(["a" as CipherId])],
|
||||
["pending", new Set(["b" as CipherId])],
|
||||
]),
|
||||
);
|
||||
const pass = (id: string, selected: string[]) =>
|
||||
component["filterPredicate"](rowFor(id), { [FILTER_KEY]: selected });
|
||||
|
||||
expect(pass("a", ["pending"])).toBe(false);
|
||||
expect(pass("b", ["pending"])).toBe(true);
|
||||
expect(pass("a", ["pending", "privileged"])).toBe(true);
|
||||
expect(pass("c", ["pending", "privileged"])).toBe(false);
|
||||
expect(pass("c", [])).toBe(true);
|
||||
});
|
||||
|
||||
it("passes every row for an option the provider does not offer", () => {
|
||||
contributedMatches$.next(new Map([["pending", new Set<CipherId>()]]));
|
||||
|
||||
expect(component["filterPredicate"](rowFor("a"), { [FILTER_KEY]: ["old-link"] })).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("ANDs with the other chips", () => {
|
||||
contributedMatches$.next(new Map([["pending", new Set(["a" as CipherId])]]));
|
||||
|
||||
expect(
|
||||
component["filterPredicate"](rowFor("a"), {
|
||||
[FILTER_KEY]: ["pending"],
|
||||
cipherType: CipherType.Card,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("lets the empty state see a selection as a filter", () => {
|
||||
(component as any).tableEl = () => ({
|
||||
filterValues: () => ({ [FILTER_KEY]: ["pending"] }),
|
||||
});
|
||||
|
||||
expect(component["emptyStateFilterValues"]()).toMatchObject({
|
||||
[FILTER_KEY]: ["pending"],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("restoring a cached selection", () => {
|
||||
it("seeds the chip from the selection cached under its key", async () => {
|
||||
vaultPopupListTableFiltersService.restoreFilters$.mockReturnValue(
|
||||
of({ contributed: { [FILTER_KEY]: ["pending"], other: ["x"] } }),
|
||||
);
|
||||
await provideFilter();
|
||||
|
||||
expect(component["filtersToRestore"]()).toEqual({ [FILTER_KEY]: ["pending"] });
|
||||
});
|
||||
|
||||
it("drops it when the seam is not provided", async () => {
|
||||
vaultPopupListTableFiltersService.restoreFilters$.mockReturnValue(
|
||||
of({ contributed: { [FILTER_KEY]: ["pending"] }, cipherType: CipherType.Login }),
|
||||
);
|
||||
TestBed.resetTestingModule();
|
||||
await createFixture();
|
||||
|
||||
expect(component["filtersToRestore"]()).toEqual({ cipherType: CipherType.Login });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("group predicates", () => {
|
||||
it("isAutofill returns true only for autofill-tagged rows", () => {
|
||||
const row = makeRow("autofill");
|
||||
|
||||
@@ -11,12 +11,13 @@ import {
|
||||
effect,
|
||||
inject,
|
||||
Injector,
|
||||
isDevMode,
|
||||
viewChild,
|
||||
} from "@angular/core";
|
||||
import { takeUntilDestroyed, toObservable, toSignal } from "@angular/core/rxjs-interop";
|
||||
import { FormsModule } from "@angular/forms";
|
||||
import { Router } from "@angular/router";
|
||||
import { distinctUntilChanged, filter, map, skip, Subject, switchMap } from "rxjs";
|
||||
import { catchError, distinctUntilChanged, filter, map, of, skip, Subject, switchMap } from "rxjs";
|
||||
|
||||
import { JslibModule } from "@bitwarden/angular/jslib.module";
|
||||
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
|
||||
@@ -28,6 +29,7 @@ import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { CipherId } from "@bitwarden/common/types/guid";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { FolderView } from "@bitwarden/common/vault/models/view/folder.view";
|
||||
import {
|
||||
@@ -51,6 +53,7 @@ import {
|
||||
FilterOptionNode,
|
||||
IconButtonModule,
|
||||
IconComponent,
|
||||
IconTileOptions,
|
||||
ScrollCollapseSourceDirective,
|
||||
SearchModule,
|
||||
StatusLockupComponent,
|
||||
@@ -67,6 +70,9 @@ import {
|
||||
NO_FOLDER,
|
||||
organizationNameForScope,
|
||||
OrgIconDirective,
|
||||
VAULT_ITEM_FILTER,
|
||||
type VaultItemFilter,
|
||||
type VaultItemFilterOption,
|
||||
type VaultItemsTableFilters,
|
||||
VaultNavService,
|
||||
VaultScopeType,
|
||||
@@ -91,12 +97,37 @@ import { PopupCipherViewLike } from "../../../views/popup-cipher.view";
|
||||
import { ItemCopyActionsComponent } from "../item-copy-action/item-copy-actions.component";
|
||||
import { ItemMoreOptionsComponent } from "../item-more-options/item-more-options.component";
|
||||
import { VaultFiltersTourComponent } from "../vault-filters-tour/vault-filters-tour.component";
|
||||
import { VAULT_ROW_ICON, VaultRowIcon } from "../vault-row-slots/vault-row-icon.token";
|
||||
import { VaultRowSubtitleComponent } from "../vault-row-slots/vault-row-subtitle.component";
|
||||
|
||||
/** Collects every value in a {@link FilterOptionNode} subtree, depth-first. */
|
||||
function subtreeValues(nodes: readonly FilterOptionNode<string>[]): string[] {
|
||||
return nodes.flatMap((n) => [n.value, ...subtreeValues(n.options ?? [])]);
|
||||
}
|
||||
|
||||
/** The built-in chips' selection keys. A contributed filter's key must differ. */
|
||||
const BUILT_IN_FILTER_KEYS: ReadonlySet<string> = new Set([
|
||||
"cipherType",
|
||||
"organization",
|
||||
"collection",
|
||||
"folder",
|
||||
"search",
|
||||
]);
|
||||
|
||||
/**
|
||||
* The host's contributed filter, or `null` when its key matches a built-in chip key. Throws in dev
|
||||
* mode instead.
|
||||
*/
|
||||
function contributedFilter(filter: VaultItemFilter | null): VaultItemFilter | null {
|
||||
if (filter == null || !BUILT_IN_FILTER_KEYS.has(filter.key)) {
|
||||
return filter;
|
||||
}
|
||||
if (isDevMode()) {
|
||||
throw new Error(`VAULT_ITEM_FILTER key "${filter.key}" matches a built-in popup filter key.`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Component({
|
||||
selector: "app-vault-popup-list-table",
|
||||
templateUrl: "vault-popup-list-table.component.html",
|
||||
@@ -133,6 +164,7 @@ function subtreeValues(nodes: readonly FilterOptionNode<string>[]): string[] {
|
||||
EmptyVaultComponent,
|
||||
ItemCopyActionsComponent,
|
||||
ItemMoreOptionsComponent,
|
||||
VaultRowSubtitleComponent,
|
||||
OrgIconDirective,
|
||||
Vfo1I18nPipe,
|
||||
ButtonModule,
|
||||
@@ -166,6 +198,12 @@ export class VaultPopupListTableComponent {
|
||||
protected readonly i18nService = inject(I18nService);
|
||||
private readonly window = inject<Window>(WINDOW);
|
||||
|
||||
/** The host's contributed filter chip. Unprovided, the table has no such chip. */
|
||||
protected readonly itemFilter = contributedFilter(inject(VAULT_ITEM_FILTER, { optional: true }));
|
||||
|
||||
/** The host's icon after a row's name. Unprovided, rows show no extra icon. */
|
||||
protected readonly rowIcon: VaultRowIcon | null = inject(VAULT_ROW_ICON, { optional: true });
|
||||
|
||||
/** The projected `bit-table-v2`, used to seed and observe chip selections. */
|
||||
private readonly tableEl = viewChild(BitTableV2Component);
|
||||
|
||||
@@ -229,12 +267,38 @@ export class VaultPopupListTableComponent {
|
||||
organization?: string[];
|
||||
collection?: string[];
|
||||
folder?: string[];
|
||||
[contributedKey: string]: unknown;
|
||||
},
|
||||
): boolean =>
|
||||
matchesType(row.cipher, values.cipherType) &&
|
||||
matchesVault(row.cipher, values.organization) &&
|
||||
matchesSharedFolder(row.cipher, values.collection) &&
|
||||
matchesFolder(row.cipher, values.folder);
|
||||
matchesFolder(row.cipher, values.folder) &&
|
||||
this.matchesContributedFilter(row.cipher, this.contributedSelection(values));
|
||||
|
||||
/** The contributed chip's selected option IDs in `values`, keyed by the filter's own key. */
|
||||
private contributedSelection(values: Record<string, unknown>): string[] | undefined {
|
||||
return this.itemFilter == null
|
||||
? undefined
|
||||
: (values[this.itemFilter.key] as string[] | undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the cipher is among any selected contributed option's matches: OR within the chip, AND
|
||||
* with the others. Unresolved matches let every row pass, and so does an option the provider does
|
||||
* not offer (a stale cached selection).
|
||||
*/
|
||||
private matchesContributedFilter(cipher: PopupCipherViewLike, selected?: string[]): boolean {
|
||||
const byOption = this.contributedFilterMatches();
|
||||
if (!selected?.length || byOption === undefined) {
|
||||
return true;
|
||||
}
|
||||
const id = String(cipher.id) as CipherId;
|
||||
return selected.some((optionId) => {
|
||||
const matches = byOption.get(optionId);
|
||||
return matches === undefined || matches.has(id);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The table's live chip/search selection, reshaped for `EmptyVaultComponent` — its `vault`/
|
||||
@@ -256,8 +320,10 @@ export class VaultPopupListTableComponent {
|
||||
collection?: string[];
|
||||
folder?: string[];
|
||||
search?: string;
|
||||
[contributedKey: string]: unknown;
|
||||
}
|
||||
| undefined;
|
||||
const contributed = values == null ? undefined : this.contributedSelection(values);
|
||||
|
||||
return {
|
||||
search: this.hasSearchText() ? values?.search : undefined,
|
||||
@@ -265,6 +331,10 @@ export class VaultPopupListTableComponent {
|
||||
vault: values?.organization,
|
||||
sharedFolder: values?.collection,
|
||||
folder: values?.folder,
|
||||
// No such key in the empty state's shape; carried so a selection alone reads as "filtered".
|
||||
...(this.itemFilter != null && contributed?.length
|
||||
? { [this.itemFilter.key]: contributed }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -296,7 +366,16 @@ export class VaultPopupListTableComponent {
|
||||
/**
|
||||
* Cached filter state to seed the table's chips on load.
|
||||
*/
|
||||
protected readonly filtersToRestore = toSignal(this.listFiltersService.restoreFilters$());
|
||||
protected readonly filtersToRestore = toSignal(
|
||||
this.listFiltersService.restoreFilters$().pipe(
|
||||
// Only the provided chip's cached selection is restored: any other has no control.
|
||||
map(({ contributed, ...rest }) => {
|
||||
const key = this.itemFilter?.key;
|
||||
const selected = key == null ? undefined : contributed?.[key];
|
||||
return key == null || selected == null ? rest : { ...rest, [key]: selected };
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
/** Whether the user left the toolbar's filter dialog open; restored when the popup reopens. */
|
||||
private readonly filterDialogOpen = this.listFiltersService.filterDialogOpen;
|
||||
@@ -346,6 +425,55 @@ export class VaultPopupListTableComponent {
|
||||
initialValue: [] as PopupCipherViewLike[],
|
||||
});
|
||||
|
||||
/** The contributed chip's options, already localized by the host. Empty hides the chip. */
|
||||
protected readonly contributedFilterOptions = toSignal(
|
||||
this.itemFilter?.options$ ?? of<readonly VaultItemFilterOption[]>([]),
|
||||
{ initialValue: [] as readonly VaultItemFilterOption[] },
|
||||
);
|
||||
|
||||
/** Icon tile per option, so each option's binding keeps a stable identity across checks. */
|
||||
protected readonly contributedFilterTiles = computed(() => {
|
||||
const tiles = new Map<string, IconTileOptions>();
|
||||
for (const option of this.contributedFilterOptions()) {
|
||||
tiles.set(option.id, { icon: option.icon, variant: option.tileVariant });
|
||||
}
|
||||
return tiles;
|
||||
});
|
||||
|
||||
/**
|
||||
* Row IDs each option admits, read off the unsearched list so typing does not re-read. Read as
|
||||
* soon as the chip is offered, since every option shows a count. Until it lands every row passes
|
||||
* and counts are blank, and so after a failed read.
|
||||
*/
|
||||
private readonly contributedFilterMatches = toSignal(
|
||||
toObservable(
|
||||
computed(() => ({
|
||||
options: this.contributedFilterOptions(),
|
||||
ciphers: this.activeCiphers(),
|
||||
})),
|
||||
).pipe(
|
||||
switchMap(({ options, ciphers }) =>
|
||||
this.itemFilter == null || options.length === 0
|
||||
? of<ReadonlyMap<string, ReadonlySet<CipherId>> | undefined>(undefined)
|
||||
: this.itemFilter
|
||||
.matches$(ciphers)
|
||||
.pipe(
|
||||
catchError(() =>
|
||||
of<ReadonlyMap<string, ReadonlySet<CipherId>> | undefined>(undefined),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ initialValue: undefined },
|
||||
);
|
||||
|
||||
/** An option's count, blank until its matches have landed. */
|
||||
protected contributedFilterCount(optionId: string): number | undefined {
|
||||
return this.itemFilter == null || this.contributedFilterMatches() === undefined
|
||||
? undefined
|
||||
: this.optionCount(this.itemFilter.key, [optionId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrowed like {@link collectionOptions}, against the unsearched list: an option that vanished
|
||||
* as the user typed could not widen the results again.
|
||||
@@ -592,7 +720,14 @@ export class VaultPopupListTableComponent {
|
||||
takeUntilDestroyed(this.destroyRef),
|
||||
)
|
||||
.subscribe((values: any) => {
|
||||
this.listFiltersService.saveFilters(values);
|
||||
const contributed = this.contributedSelection(values);
|
||||
this.listFiltersService.saveFilters({
|
||||
...values,
|
||||
contributed:
|
||||
this.itemFilter == null || contributed == null
|
||||
? {}
|
||||
: { [this.itemFilter.key]: contributed },
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
|
||||
import { CollectionId, OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { AttachmentView } from "@bitwarden/common/vault/models/view/attachment.view";
|
||||
@@ -48,6 +49,7 @@ import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { FolderView } from "@bitwarden/common/vault/models/view/folder.view";
|
||||
import { LoginUriView } from "@bitwarden/common/vault/models/view/login-uri.view";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { NoopRevealedCipherService } from "@bitwarden/common/vault/services/noop-revealed-cipher.service";
|
||||
import { RestrictedItemTypesService } from "@bitwarden/common/vault/services/restricted-item-types.service";
|
||||
import {
|
||||
CalloutModule,
|
||||
@@ -695,6 +697,7 @@ const buildProviders = (args: StoryArgs) => {
|
||||
getUser: () => ({ update: async () => {} }),
|
||||
},
|
||||
},
|
||||
{ provide: RevealedCipherService, useClass: NoopRevealedCipherService },
|
||||
{
|
||||
provide: RestrictedItemTypesService,
|
||||
useValue: { restricted$: of([]) },
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { InputSignal, Type } from "@angular/core";
|
||||
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { SafeInjectionToken } from "@bitwarden/ui-common";
|
||||
|
||||
export type VaultRowIcon = Type<{ cipher: InputSignal<CipherViewLike | null> }>;
|
||||
|
||||
/**
|
||||
* Optional icon after the name in a popup vault row, such as a status icon for an item another
|
||||
* feature governs. Rendered once per row with `cipher` as its only input; it renders nothing for a
|
||||
* row it has no icon for. Unprovided, rows show no extra icon.
|
||||
*/
|
||||
export const VAULT_ROW_ICON = new SafeInjectionToken<VaultRowIcon>("VaultRowIcon");
|
||||
@@ -0,0 +1,66 @@
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { BehaviorSubject } from "rxjs";
|
||||
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
|
||||
import { VaultRowSubtitleComponent } from "./vault-row-subtitle.component";
|
||||
import { VAULT_ROW_SUBTITLE } from "./vault-row-subtitle.token";
|
||||
|
||||
describe("VaultRowSubtitleComponent", () => {
|
||||
let fixture: ComponentFixture<VaultRowSubtitleComponent>;
|
||||
let subtitle$: BehaviorSubject<string | null>;
|
||||
|
||||
const cipher = { id: "c1", name: "Company Facebook", subTitle: "frodo@shire.com" };
|
||||
|
||||
const text = () => fixture.nativeElement.textContent.trim();
|
||||
|
||||
async function create(provided: boolean) {
|
||||
subtitle$ = new BehaviorSubject<string | null>(null);
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [VaultRowSubtitleComponent],
|
||||
providers: [
|
||||
{ provide: I18nService, useValue: { t: (k: string) => k } },
|
||||
...(provided
|
||||
? [{ provide: VAULT_ROW_SUBTITLE, useValue: { subtitle$: () => subtitle$ } }]
|
||||
: []),
|
||||
],
|
||||
}).compileComponents();
|
||||
fixture = TestBed.createComponent(VaultRowSubtitleComponent);
|
||||
fixture.componentRef.setInput("cipher", cipher as unknown as CipherViewLike);
|
||||
fixture.detectChanges();
|
||||
}
|
||||
|
||||
it("shows the cipher's own subtitle when nothing is provided", async () => {
|
||||
await create(false);
|
||||
|
||||
expect(text()).toBe("frodo@shire.com");
|
||||
});
|
||||
|
||||
it("shows the cipher's own subtitle while the provider returns null", async () => {
|
||||
await create(true);
|
||||
|
||||
expect(text()).toBe("frodo@shire.com");
|
||||
});
|
||||
|
||||
it("shows the provider's subtitle and follows its updates", async () => {
|
||||
await create(true);
|
||||
|
||||
subtitle$.next("8h left");
|
||||
fixture.detectChanges();
|
||||
expect(text()).toBe("8h left");
|
||||
|
||||
subtitle$.next("7h left");
|
||||
fixture.detectChanges();
|
||||
expect(text()).toBe("7h left");
|
||||
});
|
||||
|
||||
it("renders nothing without a cipher", async () => {
|
||||
await create(true);
|
||||
|
||||
fixture.componentRef.setInput("cipher", null);
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(text()).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ChangeDetectionStrategy, Component, computed, inject, input } from "@angular/core";
|
||||
import { toObservable, toSignal } from "@angular/core/rxjs-interop";
|
||||
import { of, switchMap } from "rxjs";
|
||||
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import {
|
||||
CipherViewLike,
|
||||
CipherViewLikeUtils,
|
||||
} from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
|
||||
import { VAULT_ROW_SUBTITLE, VaultRowSubtitle } from "./vault-row-subtitle.token";
|
||||
|
||||
/** A popup row's subtitle: the {@link VAULT_ROW_SUBTITLE} provider's text, else the cipher's own. */
|
||||
@Component({
|
||||
selector: "app-vault-row-subtitle",
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
template: `{{ text() }}`,
|
||||
})
|
||||
export class VaultRowSubtitleComponent {
|
||||
readonly cipher = input<CipherViewLike | null>(null);
|
||||
|
||||
private readonly i18nService = inject(I18nService);
|
||||
private readonly provider: VaultRowSubtitle | null = inject(VAULT_ROW_SUBTITLE, {
|
||||
optional: true,
|
||||
});
|
||||
|
||||
private readonly contributed = toSignal(
|
||||
toObservable(this.cipher).pipe(
|
||||
switchMap((cipher) =>
|
||||
cipher == null || this.provider == null ? of(null) : this.provider.subtitle$(cipher),
|
||||
),
|
||||
),
|
||||
{ initialValue: null },
|
||||
);
|
||||
|
||||
protected readonly text = computed(() => {
|
||||
const cipher = this.cipher();
|
||||
if (cipher == null) {
|
||||
return "";
|
||||
}
|
||||
return this.contributed() ?? CipherViewLikeUtils.subtitle(cipher, this.i18nService) ?? "";
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Observable } from "rxjs";
|
||||
|
||||
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { SafeInjectionToken } from "@bitwarden/ui-common";
|
||||
|
||||
/** Replaces a popup vault row's subtitle for the items the provider governs. */
|
||||
export interface VaultRowSubtitle {
|
||||
/**
|
||||
* The already-translated subtitle for `cipher`, or `null` for the row's default subtitle. Live:
|
||||
* the row re-renders on each emission.
|
||||
*/
|
||||
subtitle$(cipher: CipherViewLike): Observable<string | null>;
|
||||
}
|
||||
|
||||
/** Optional subtitle provider for popup vault rows. Unprovided, rows show their default subtitle. */
|
||||
export const VAULT_ROW_SUBTITLE = new SafeInjectionToken<VaultRowSubtitle>("VaultRowSubtitle");
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
} from "@bitwarden/common/types/guid";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { SearchService } from "@bitwarden/common/vault/abstractions/search.service";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service";
|
||||
@@ -50,6 +51,7 @@ import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { FolderView } from "@bitwarden/common/vault/models/view/folder.view";
|
||||
import { LoginUriView } from "@bitwarden/common/vault/models/view/login-uri.view";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { NoopRevealedCipherService } from "@bitwarden/common/vault/services/noop-revealed-cipher.service";
|
||||
import { RestrictedItemTypesService } from "@bitwarden/common/vault/services/restricted-item-types.service";
|
||||
import {
|
||||
SecurityTask,
|
||||
@@ -635,6 +637,7 @@ const buildProviders = (args: StoryArgs) => {
|
||||
},
|
||||
},
|
||||
{ provide: RestrictedItemTypesService, useValue: { restricted$: of([]) } },
|
||||
{ provide: RevealedCipherService, useClass: NoopRevealedCipherService },
|
||||
{
|
||||
provide: EnvironmentService,
|
||||
useValue: { environment$: of({ getIconsUrl: () => "https://icons.bitwarden.net" }) },
|
||||
|
||||
@@ -23,23 +23,31 @@
|
||||
{{ "autofillVerb" | i18n }}
|
||||
</button>
|
||||
}
|
||||
<app-share-button
|
||||
[cipher]="cipher"
|
||||
class="tw-mt-4"
|
||||
slot="button"
|
||||
[skipPasswordPrompt]="true"
|
||||
></app-share-button>
|
||||
@if (allows(RestrictedCipherAction.Share)) {
|
||||
<app-share-button
|
||||
[cipher]="cipher"
|
||||
class="tw-mt-4"
|
||||
slot="button"
|
||||
[skipPasswordPrompt]="true"
|
||||
></app-share-button>
|
||||
}
|
||||
</app-cipher-view>
|
||||
}
|
||||
|
||||
@if (showFooter$ | async) {
|
||||
<popup-footer slot="footer">
|
||||
@if (!cipher.isDeleted) {
|
||||
<button buttonType="primary" type="button" bitButton (click)="editCipher()">
|
||||
<button
|
||||
buttonType="primary"
|
||||
type="button"
|
||||
bitButton
|
||||
[disabled]="!canEdit()"
|
||||
(click)="editCipher()"
|
||||
>
|
||||
{{ "edit" | i18n }}
|
||||
</button>
|
||||
}
|
||||
@if (cipher.isDeleted && cipher.permissions.restore) {
|
||||
@if (canRestore()) {
|
||||
<button buttonType="primary" type="button" bitButton [bitAction]="restore">
|
||||
{{ "restore" | i18n }}
|
||||
</button>
|
||||
|
||||
@@ -2,7 +2,7 @@ import { ComponentFixture, fakeAsync, flush, TestBed, tick } from "@angular/core
|
||||
import { By } from "@angular/platform-browser";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { mock } from "jest-mock-extended";
|
||||
import { BehaviorSubject, of, Subject } from "rxjs";
|
||||
import { BehaviorSubject, firstValueFrom, of, Subject } from "rxjs";
|
||||
|
||||
import { CollectionService } from "@bitwarden/admin-console/common";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
@@ -31,6 +31,7 @@ import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/ciphe
|
||||
import { CipherRiskService } from "@bitwarden/common/vault/abstractions/cipher-risk.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { VaultSettingsService } from "@bitwarden/common/vault/abstractions/vault-settings/vault-settings.service";
|
||||
import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data";
|
||||
@@ -38,6 +39,7 @@ import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { LoginUriView } from "@bitwarden/common/vault/models/view/login-uri.view";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { TaskService } from "@bitwarden/common/vault/tasks";
|
||||
import { RestrictedCipherAction } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import { DialogService, ToastService } from "@bitwarden/components";
|
||||
import { ShareLinkService } from "@bitwarden/tools-share";
|
||||
import {
|
||||
@@ -114,13 +116,22 @@ describe("ViewComponent", () => {
|
||||
|
||||
const mockCipherService = {
|
||||
cipherViews$: jest.fn().mockImplementation((userId) => of([mockCipher])),
|
||||
// Reads through `cipherViews$`, so each test's `cipherViews$` override still applies.
|
||||
getAllDecryptedForIdsIncludingRestricted: jest
|
||||
.fn()
|
||||
.mockImplementation(async (userId: UserId, ids: string[]) => {
|
||||
const ciphers: CipherView[] = await firstValueFrom(mockCipherService.cipherViews$(userId));
|
||||
return ciphers.filter((c) => ids.includes(c.id));
|
||||
}),
|
||||
deleteWithServer: jest.fn().mockResolvedValue(undefined),
|
||||
softDeleteWithServer: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
const cipherArchiveService = mock<CipherArchiveService>();
|
||||
const revealedCipherService = mock<RevealedCipherService>();
|
||||
|
||||
beforeEach(async () => {
|
||||
revealedCipherService.displayView$.mockImplementation((_userId, stored) => of(stored));
|
||||
mockCipherService.cipherViews$.mockClear();
|
||||
mockCipherService.deleteWithServer.mockClear();
|
||||
mockCipherService.softDeleteWithServer.mockClear();
|
||||
@@ -143,6 +154,7 @@ describe("ViewComponent", () => {
|
||||
imports: [ViewComponent],
|
||||
providers: [
|
||||
{ provide: Router, useValue: { navigate: mockNavigate } },
|
||||
{ provide: RevealedCipherService, useValue: revealedCipherService },
|
||||
{ provide: CipherService, useValue: mockCipherService },
|
||||
{ provide: LogService, useValue: mock<LogService>() },
|
||||
{
|
||||
@@ -479,6 +491,72 @@ describe("ViewComponent", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
describe("restricted ciphers", () => {
|
||||
const stored = { ...mockCipher, partial: true } as CipherView;
|
||||
const revealed = { ...mockCipher, partial: false, edit: true } as CipherView;
|
||||
let display$: BehaviorSubject<CipherView>;
|
||||
|
||||
beforeEach(() => {
|
||||
display$ = new BehaviorSubject<CipherView>(revealed);
|
||||
mockCipherService.cipherViews$.mockImplementation(() => of([stored]));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockCipherService.cipherViews$.mockImplementation(() => of([mockCipher]));
|
||||
});
|
||||
|
||||
it("shows the revealed view and allows edit, but not share, clone, or delete", fakeAsync(() => {
|
||||
revealedCipherService.displayView$.mockReturnValue(display$);
|
||||
|
||||
params$.next({ cipherId: mockCipher.id });
|
||||
flush();
|
||||
|
||||
expect(component.cipher).toBe(revealed);
|
||||
expect(component["allows"](RestrictedCipherAction.Edit)).toBe(true);
|
||||
expect(component["allows"](RestrictedCipherAction.Share)).toBe(false);
|
||||
expect(component["allows"](RestrictedCipherAction.Clone)).toBe(false);
|
||||
expect(component["allows"](RestrictedCipherAction.Delete)).toBe(false);
|
||||
expect(component.showAutofillButton()).toBe(true);
|
||||
}));
|
||||
|
||||
it("shows a restricted cipher without a revealed view read-only, with nothing to fill", fakeAsync(() => {
|
||||
params$.next({ cipherId: mockCipher.id });
|
||||
flush();
|
||||
|
||||
expect(component.cipher).toEqual(stored);
|
||||
expect(component["allows"](RestrictedCipherAction.Edit)).toBe(false);
|
||||
expect(component["allows"](RestrictedCipherAction.UserFields)).toBe(true);
|
||||
expect(component.showAutofillButton()).toBe(false);
|
||||
}));
|
||||
|
||||
it("shows the Edit button disabled while the restricted cipher is not revealed", fakeAsync(() => {
|
||||
params$.next({ cipherId: mockCipher.id });
|
||||
flush();
|
||||
fixture.detectChanges();
|
||||
|
||||
const edit = fixture.debugElement
|
||||
.queryAll(By.css("popup-footer button[bitbutton]"))
|
||||
.find((button) => button.nativeElement.textContent.trim() === "edit");
|
||||
expect(edit).toBeTruthy();
|
||||
expect(
|
||||
edit!.nativeElement.disabled || edit!.nativeElement.getAttribute("aria-disabled"),
|
||||
).toBeTruthy();
|
||||
}));
|
||||
|
||||
it("falls back to the stored view in place when the reveal ends", fakeAsync(() => {
|
||||
revealedCipherService.displayView$.mockReturnValue(display$);
|
||||
params$.next({ cipherId: mockCipher.id });
|
||||
flush();
|
||||
|
||||
display$.next(stored);
|
||||
flush();
|
||||
|
||||
expect(component.cipher).toEqual(stored);
|
||||
expect(component["allows"](RestrictedCipherAction.Edit)).toBe(false);
|
||||
expect(collect).toHaveBeenCalledTimes(1);
|
||||
}));
|
||||
});
|
||||
|
||||
describe("archive button", () => {
|
||||
it("shows the archive button when the user can archive and the cipher can be archived", fakeAsync(() => {
|
||||
jest.spyOn(component["archiveService"], "userCanArchive$").mockReturnValueOnce(of(true));
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Component, inject } from "@angular/core";
|
||||
import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop";
|
||||
import { FormsModule } from "@angular/forms";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { firstValueFrom, Observable, switchMap, of, map } from "rxjs";
|
||||
import { firstValueFrom, Observable, switchMap, of } from "rxjs";
|
||||
|
||||
import { JslibModule } from "@bitwarden/angular/jslib.module";
|
||||
import { BrowserPremiumUpgradePromptService } from "@bitwarden/browser/billing/popup/services/browser-premium-upgrade-prompt.service";
|
||||
@@ -31,12 +31,17 @@ import { UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherArchiveService } from "@bitwarden/common/vault/abstractions/cipher-archive.service";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { PremiumUpgradePromptService } from "@bitwarden/common/vault/abstractions/premium-upgrade-prompt.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { ViewPasswordHistoryService } from "@bitwarden/common/vault/abstractions/view-password-history.service";
|
||||
import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service";
|
||||
import { CipherViewLikeUtils } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { filterOutNullish } from "@bitwarden/common/vault/utils/observable-utilities";
|
||||
import {
|
||||
RestrictedCipherAction,
|
||||
RestrictedCipherPolicy,
|
||||
} from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import {
|
||||
AsyncActionsModule,
|
||||
ButtonModule,
|
||||
@@ -120,7 +125,12 @@ export class ViewComponent {
|
||||
private activeUserId: UserId;
|
||||
|
||||
headerText: string;
|
||||
/** The shown view: the revealed view of a restricted cipher while one exists, else the stored one. */
|
||||
cipher: CipherView;
|
||||
/** The stored copy, which stays restricted while {@link cipher} is its revealed view. */
|
||||
private storedCipher: CipherView;
|
||||
protected readonly RestrictedCipherAction = RestrictedCipherAction;
|
||||
private readonly revealedCipherService = inject(RevealedCipherService);
|
||||
organization$: Observable<Organization>;
|
||||
canDeleteCipher$: Observable<boolean>;
|
||||
collections$: Observable<CollectionView[]>;
|
||||
@@ -175,7 +185,10 @@ export class ViewComponent {
|
||||
this.accountService.activeAccount$.pipe(getUserId),
|
||||
);
|
||||
|
||||
const cipher = await this.getCipherData(params.cipherId, this.activeUserId);
|
||||
const stored = await this.getCipherData(params.cipherId, this.activeUserId);
|
||||
const cipher = await firstValueFrom(
|
||||
this.revealedCipherService.displayView$(this.activeUserId, stored),
|
||||
);
|
||||
this.headerText = this.setHeader(cipher.type);
|
||||
|
||||
// Handling the load action needs to take place before setting `this.cipher`,
|
||||
@@ -198,26 +211,33 @@ export class ViewComponent {
|
||||
}
|
||||
}
|
||||
|
||||
return cipher;
|
||||
}),
|
||||
filterOutNullish(),
|
||||
switchMap(async (cipher) => {
|
||||
this.cipher = cipher;
|
||||
|
||||
this.canDeleteCipher$ = this.cipherAuthorizationService.canDeleteCipher$(cipher);
|
||||
|
||||
this.showFooter$ = of(
|
||||
cipher &&
|
||||
(!cipher.isDeleted ||
|
||||
(cipher.isDeleted && (cipher.permissions.restore || cipher.permissions.delete))),
|
||||
);
|
||||
|
||||
await this.eventCollectionService.collect(
|
||||
EventType.Cipher_ClientViewed,
|
||||
cipher.id,
|
||||
false,
|
||||
cipher.organizationId,
|
||||
);
|
||||
|
||||
return stored;
|
||||
}),
|
||||
filterOutNullish(),
|
||||
// Swaps the revealed view in and out in place as a lease on a restricted cipher starts or ends.
|
||||
switchMap((stored) => {
|
||||
this.storedCipher = stored;
|
||||
return this.revealedCipherService.displayView$(this.activeUserId, stored);
|
||||
}),
|
||||
switchMap(async (cipher) => {
|
||||
this.cipher = cipher;
|
||||
|
||||
this.canDeleteCipher$ = this.cipherAuthorizationService.canDeleteCipher$(
|
||||
this.storedCipher,
|
||||
);
|
||||
|
||||
this.showFooter$ = of(
|
||||
cipher &&
|
||||
(!cipher.isDeleted ||
|
||||
(cipher.isDeleted && (cipher.permissions.restore || cipher.permissions.delete))),
|
||||
);
|
||||
}),
|
||||
takeUntilDestroyed(),
|
||||
)
|
||||
@@ -242,14 +262,32 @@ export class ViewComponent {
|
||||
}
|
||||
|
||||
async getCipherData(id: string, userId: UserId) {
|
||||
return await firstValueFrom(
|
||||
this.cipherService.cipherViews$(userId).pipe(
|
||||
filterOutNullish(),
|
||||
map((ciphers) => ciphers.find((c) => c.id === id)),
|
||||
),
|
||||
const [cipher] = await this.cipherService.getAllDecryptedForIdsIncludingRestricted(userId, [
|
||||
id,
|
||||
]);
|
||||
return cipher;
|
||||
}
|
||||
|
||||
/** Edit shows disabled while the restricted-cipher rule blocks it. */
|
||||
protected canEdit(): boolean {
|
||||
return this.allows(RestrictedCipherAction.Edit);
|
||||
}
|
||||
|
||||
protected canRestore(): boolean {
|
||||
return (
|
||||
this.cipher.isDeleted &&
|
||||
this.cipher.permissions.restore &&
|
||||
this.allows(RestrictedCipherAction.Restore)
|
||||
);
|
||||
}
|
||||
|
||||
/** False when the restricted-cipher rule blocks the action. */
|
||||
protected allows(action: RestrictedCipherAction): boolean {
|
||||
const stored = this.storedCipher ?? this.cipher;
|
||||
const revealedView = this.cipher === stored ? undefined : this.cipher;
|
||||
return RestrictedCipherPolicy.allows(stored, action, revealedView);
|
||||
}
|
||||
|
||||
async editCipher() {
|
||||
if (this.cipher.isDeleted) {
|
||||
return false;
|
||||
@@ -351,7 +389,12 @@ export class ViewComponent {
|
||||
[CipherType.Login, CipherType.Card, CipherType.Identity, CipherType.SshKey] as CipherType[]
|
||||
).includes(CipherViewLikeUtils.getType(this.cipher));
|
||||
|
||||
return validAutofillType && !(this.cipher.isArchived || this.cipher.isDeleted);
|
||||
// A restricted cipher without a revealed view has nothing to fill.
|
||||
return (
|
||||
validAutofillType &&
|
||||
!RestrictedCipherPolicy.isRestricted(this.cipher) &&
|
||||
!(this.cipher.isArchived || this.cipher.isDeleted)
|
||||
);
|
||||
}
|
||||
|
||||
async doAutofill() {
|
||||
@@ -383,7 +426,10 @@ export class ViewComponent {
|
||||
data: {
|
||||
currentUrl: currentTab?.url || "",
|
||||
savedUris: this.cipher.login?.uris?.filter((u) => u.uri) ?? [],
|
||||
viewOnly: !this.cipher.edit,
|
||||
// Adding the URL saves the cipher outside the edit form, which a restricted cipher refuses.
|
||||
viewOnly:
|
||||
!this.cipher.edit ||
|
||||
RestrictedCipherPolicy.isRestricted(this.storedCipher ?? this.cipher),
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import { TestBed } from "@angular/core/testing";
|
||||
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree } from "@angular/router";
|
||||
import { mock } from "jest-mock-extended";
|
||||
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
import { CipherId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { RestrictedCipherAction } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
|
||||
import { restrictedCipherGuard } from "./restricted-cipher.guard";
|
||||
|
||||
describe("restrictedCipherGuard", () => {
|
||||
const userId = "user-id" as UserId;
|
||||
const cipherService = mock<CipherService>();
|
||||
const revealedCipherService = mock<RevealedCipherService>();
|
||||
const createUrlTree = jest.fn().mockReturnValue(new UrlTree());
|
||||
|
||||
const storedCipher = (restricted: boolean) =>
|
||||
Object.assign(new Cipher(), {
|
||||
id: "cipher-1",
|
||||
partialData: restricted ? {} : undefined,
|
||||
}) as Cipher;
|
||||
|
||||
const runGuard = (action: RestrictedCipherAction, queryParams: Record<string, string>) =>
|
||||
TestBed.runInInjectionContext(() =>
|
||||
restrictedCipherGuard(action)(
|
||||
{ queryParams } as unknown as ActivatedRouteSnapshot,
|
||||
{} as RouterStateSnapshot,
|
||||
),
|
||||
);
|
||||
|
||||
const expectRedirectToView = (result: unknown) => {
|
||||
expect(createUrlTree).toHaveBeenCalledWith(["/view-cipher"], {
|
||||
queryParams: { cipherId: "cipher-1", type: "1" },
|
||||
});
|
||||
expect(result).toBeInstanceOf(UrlTree);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
revealedCipherService.getOrReveal.mockResolvedValue(null);
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{ provide: AccountService, useValue: mockAccountServiceWith(userId) },
|
||||
{ provide: CipherService, useValue: cipherService },
|
||||
{ provide: RevealedCipherService, useValue: revealedCipherService },
|
||||
{ provide: Router, useValue: { createUrlTree } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("allows a cipher that is not restricted", async () => {
|
||||
cipherService.get.mockResolvedValue(storedCipher(false));
|
||||
|
||||
await expect(
|
||||
runGuard(RestrictedCipherAction.Clone, { cipherId: "cipher-1", type: "1" }),
|
||||
).resolves.toBe(true);
|
||||
expect(cipherService.get).toHaveBeenCalledWith("cipher-1", userId);
|
||||
expect(revealedCipherService.getOrReveal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows editing a restricted cipher while its revealed view is live", async () => {
|
||||
cipherService.get.mockResolvedValue(storedCipher(true));
|
||||
revealedCipherService.getOrReveal.mockResolvedValue(
|
||||
Object.assign(new CipherView(), { id: "cipher-1" }),
|
||||
);
|
||||
|
||||
await expect(
|
||||
runGuard(RestrictedCipherAction.Edit, { cipherId: "cipher-1", type: "1" }),
|
||||
).resolves.toBe(true);
|
||||
expect(revealedCipherService.getOrReveal).toHaveBeenCalledWith(userId, "cipher-1" as CipherId);
|
||||
});
|
||||
|
||||
it("redirects editing a restricted cipher without a revealed view to its view", async () => {
|
||||
cipherService.get.mockResolvedValue(storedCipher(true));
|
||||
|
||||
expectRedirectToView(
|
||||
await runGuard(RestrictedCipherAction.Edit, { cipherId: "cipher-1", type: "1" }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([RestrictedCipherAction.Clone, RestrictedCipherAction.AssignCollections])(
|
||||
"redirects %s of a restricted cipher to its view without revealing it",
|
||||
async (action) => {
|
||||
cipherService.get.mockResolvedValue(storedCipher(true));
|
||||
|
||||
expectRedirectToView(await runGuard(action, { cipherId: "cipher-1", type: "1" }));
|
||||
expect(revealedCipherService.getOrReveal).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("allows a route without a cipher id", async () => {
|
||||
await expect(runGuard(RestrictedCipherAction.Edit, {})).resolves.toBe(true);
|
||||
expect(cipherService.get).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { inject } from "@angular/core";
|
||||
import { CanActivateFn, Router } from "@angular/router";
|
||||
import { firstValueFrom } from "rxjs";
|
||||
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getOptionalUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { CipherId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import {
|
||||
RestrictedCipherAction,
|
||||
RestrictedCipherPolicy,
|
||||
} from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
|
||||
/**
|
||||
* Sends a route for a restricted cipher to the item's view when the restricted-cipher rule blocks
|
||||
* `action`. For edit, it reveals first, so an edit under a live lease goes through.
|
||||
*/
|
||||
export const restrictedCipherGuard =
|
||||
(action: RestrictedCipherAction): CanActivateFn =>
|
||||
async (route) => {
|
||||
const accountService = inject(AccountService);
|
||||
const cipherService = inject(CipherService);
|
||||
const revealedCipherService = inject(RevealedCipherService);
|
||||
const router = inject(Router);
|
||||
|
||||
const { cipherId, type } = route.queryParams;
|
||||
const userId = await firstValueFrom(accountService.activeAccount$.pipe(getOptionalUserId));
|
||||
if (!cipherId || !userId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const cipher = await cipherService.get(cipherId, userId);
|
||||
if (cipher == null || !RestrictedCipherPolicy.isRestricted(cipher)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const revealedView =
|
||||
action === RestrictedCipherAction.Edit
|
||||
? await revealedCipherService.getOrReveal(userId, cipherId as CipherId)
|
||||
: undefined;
|
||||
if (RestrictedCipherPolicy.allows(cipher, action, revealedView ?? undefined)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return router.createUrlTree(["/view-cipher"], { queryParams: { cipherId, type } });
|
||||
};
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "@bitwarden/common/spec";
|
||||
import { CipherId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { SearchService } from "@bitwarden/common/vault/abstractions/search.service";
|
||||
import { VaultSettingsService } from "@bitwarden/common/vault/abstractions/vault-settings/vault-settings.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
@@ -85,12 +86,17 @@ describe("VaultPopupItemsService", () => {
|
||||
const userId = Utils.newGuid() as UserId;
|
||||
const accountServiceMock = mockAccountServiceWith(userId);
|
||||
|
||||
const revealedCipherService = mock<RevealedCipherService>();
|
||||
let revealed$: BehaviorSubject<ReadonlyMap<CipherId, CipherView>>;
|
||||
|
||||
const restrictedItemTypesService = {
|
||||
restricted$: new BehaviorSubject<RestrictedCipherType[]>([]),
|
||||
isCipherRestricted: jest.fn().mockReturnValue(false),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
revealed$ = new BehaviorSubject<ReadonlyMap<CipherId, CipherView>>(new Map());
|
||||
revealedCipherService.revealed$.mockReturnValue(revealed$);
|
||||
allCiphers = cipherFactory(10);
|
||||
const cipherList = Object.values(allCiphers);
|
||||
// First 2 ciphers are autofill
|
||||
@@ -105,7 +111,9 @@ describe("VaultPopupItemsService", () => {
|
||||
|
||||
const cipherList$ = new BehaviorSubject<CipherView[]>(cipherList);
|
||||
|
||||
cipherServiceMock.cipherListViews$.mockReturnValue(cipherList$.asObservable());
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
cipherList$.asObservable(),
|
||||
);
|
||||
|
||||
ciphersSubject = new BehaviorSubject<Record<CipherId, CipherData>>({});
|
||||
localDataSubject = new BehaviorSubject<Record<CipherId, LocalData>>({});
|
||||
@@ -178,6 +186,7 @@ describe("VaultPopupItemsService", () => {
|
||||
|
||||
testBed = TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{ provide: RevealedCipherService, useValue: revealedCipherService },
|
||||
{ provide: CipherService, useValue: cipherServiceMock },
|
||||
{ provide: VaultSettingsService, useValue: vaultSettingsServiceMock },
|
||||
{ provide: SearchService, useValue: searchService },
|
||||
@@ -362,6 +371,55 @@ describe("VaultPopupItemsService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("restricted ciphers", () => {
|
||||
const restrictedRow = () =>
|
||||
Object.assign(new CipherView(), { id: "restricted" as CipherId, partial: true });
|
||||
|
||||
beforeEach(() => {
|
||||
searchService.searchCiphers.mockImplementation(
|
||||
async (_userId, _filter, _text, ciphers) => ciphers,
|
||||
);
|
||||
});
|
||||
|
||||
it("lists restricted ciphers", async () => {
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(of([restrictedRow()]));
|
||||
ciphersSubject.next({});
|
||||
|
||||
const ciphers = await firstValueFrom(service.filteredCiphers$);
|
||||
|
||||
expect(ciphers.map((c) => c.id)).toEqual(["restricted"]);
|
||||
expect(cipherServiceMock.cipherListViewsIncludingRestricted$).toHaveBeenCalled();
|
||||
expect(cipherServiceMock.cipherListViews$).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("swaps the revealed view in for its restricted row, keeping the row's organization", async () => {
|
||||
const row = Object.assign(restrictedRow(), { organizationId: "org1" });
|
||||
const revealed = Object.assign(new CipherView(), { id: "restricted" as CipherId });
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(of([row]));
|
||||
revealed$.next(new Map([["restricted" as CipherId, revealed]]));
|
||||
ciphersSubject.next({});
|
||||
|
||||
const [shown] = await firstValueFrom(service.filteredCiphers$);
|
||||
|
||||
expect(shown).toBe(revealed);
|
||||
expect(shown.organization).toEqual(mockOrg);
|
||||
});
|
||||
|
||||
it("leaves restricted ciphers out of the trash", async () => {
|
||||
const deletedRow = Object.assign(restrictedRow(), { deletedDate: new Date() });
|
||||
const deleted = Object.assign(new CipherView(), { deletedDate: new Date() });
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
of([deletedRow, deleted]),
|
||||
);
|
||||
ciphersSubject.next({});
|
||||
|
||||
const deletedCiphers = await firstValueFrom(service.deletedCiphers$);
|
||||
|
||||
expect(deletedCiphers).toHaveLength(1);
|
||||
expect(deletedCiphers[0].id).not.toBe("restricted");
|
||||
});
|
||||
});
|
||||
|
||||
describe("favoriteCiphers$", () => {
|
||||
it("should exclude autofill ciphers", (done) => {
|
||||
service.favoriteCiphers$.subscribe((ciphers) => {
|
||||
@@ -391,7 +449,7 @@ describe("VaultPopupItemsService", () => {
|
||||
|
||||
describe("emptyVault$", () => {
|
||||
it("should return true if there are no ciphers", (done) => {
|
||||
cipherServiceMock.cipherListViews$.mockReturnValue(of([]));
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(of([]));
|
||||
service.emptyVault$.pipe(take(1)).subscribe((empty) => {
|
||||
expect(empty).toBe(true);
|
||||
done();
|
||||
@@ -399,7 +457,7 @@ describe("VaultPopupItemsService", () => {
|
||||
});
|
||||
|
||||
it("should return false if there are ciphers", (done) => {
|
||||
cipherServiceMock.cipherListViews$.mockReturnValue(
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
of([{ id: "1", type: CipherType.Login, name: "Login 1" }] as CipherView[]),
|
||||
);
|
||||
|
||||
@@ -410,7 +468,7 @@ describe("VaultPopupItemsService", () => {
|
||||
});
|
||||
|
||||
it("should return true when all ciphers are deleted/archived", (done) => {
|
||||
cipherServiceMock.cipherListViews$.mockReturnValue(
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
of([
|
||||
{ id: "1", type: CipherType.Login, name: "Login 1", isDeleted: true },
|
||||
{ id: "2", type: CipherType.Login, name: "Login 2", isDeleted: true },
|
||||
@@ -448,7 +506,7 @@ describe("VaultPopupItemsService", () => {
|
||||
deletedCipher.deletedDate = new Date();
|
||||
const ciphers = [new CipherView(), new CipherView(), new CipherView(), deletedCipher];
|
||||
|
||||
cipherServiceMock.cipherListViews$.mockReturnValue(of(ciphers));
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(of(ciphers));
|
||||
ciphersSubject.next({});
|
||||
|
||||
const deletedCiphers = await firstValueFrom(service.deletedCiphers$);
|
||||
@@ -465,7 +523,7 @@ describe("VaultPopupItemsService", () => {
|
||||
revokedOrgCipher.deletedDate = new Date();
|
||||
revokedOrgCipher.organizationId = "revokedOrg";
|
||||
|
||||
cipherServiceMock.cipherListViews$.mockReturnValue(
|
||||
cipherServiceMock.cipherListViewsIncludingRestricted$.mockReturnValue(
|
||||
of([personalCipher, memberOrgCipher, revokedOrgCipher]),
|
||||
);
|
||||
ciphersSubject.next({});
|
||||
|
||||
@@ -27,16 +27,19 @@ import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { SyncService } from "@bitwarden/common/platform/sync";
|
||||
import { CollectionId, OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherId, CollectionId, OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
|
||||
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
|
||||
import { SearchService } from "@bitwarden/common/vault/abstractions/search.service";
|
||||
import { VaultSettingsService } from "@bitwarden/common/vault/abstractions/vault-settings/vault-settings.service";
|
||||
import { CipherType } from "@bitwarden/common/vault/enums";
|
||||
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
|
||||
import { RestrictedItemTypesService } from "@bitwarden/common/vault/services/restricted-item-types.service";
|
||||
import {
|
||||
CipherViewLike,
|
||||
CipherViewLikeUtils,
|
||||
} from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { RestrictedCipherPolicy } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
|
||||
import { runInsideAngular } from "../../../platform/browser/run-inside-angular.operator";
|
||||
import { PopupViewCacheService } from "../../../platform/popup/view-cache/popup-view-cache.service";
|
||||
@@ -54,6 +57,8 @@ import { VaultPopupListTableFiltersService } from "./vault-popup-list-table-filt
|
||||
providedIn: "root",
|
||||
})
|
||||
export class VaultPopupItemsService {
|
||||
private readonly revealedCipherService = inject(RevealedCipherService);
|
||||
|
||||
/** The legacy (VFO1 off) search text. It lives in the popup view cache, never on disk. */
|
||||
private cachedSearchText = inject(PopupViewCacheService).signal<string>({
|
||||
key: "vault-search-text",
|
||||
@@ -139,7 +144,7 @@ export class VaultPopupItemsService {
|
||||
switchMap(() =>
|
||||
combineLatest([
|
||||
this.cipherService
|
||||
.cipherListViews$(userId)
|
||||
.cipherListViewsIncludingRestricted$(userId)
|
||||
.pipe(filter((ciphers) => ciphers != null)),
|
||||
this.cipherService.failedToDecryptCiphers$(userId).pipe(startWith([])),
|
||||
this.restrictedItemTypesService.restricted$,
|
||||
@@ -214,12 +219,16 @@ export class VaultPopupItemsService {
|
||||
UserId,
|
||||
] => [vfo1Enabled ? ciphers : filterFunction(ciphers), searchText, userId],
|
||||
),
|
||||
switchMap(
|
||||
([ciphers, searchText, userId]) =>
|
||||
// Revealed views replace their rows after the search, so search sees only what the row shows.
|
||||
switchMap(([ciphers, searchText, userId]) =>
|
||||
combineLatest([
|
||||
this.searchService.searchCiphers(userId, null, searchText, ciphers) as Promise<
|
||||
PopupCipherViewLike[]
|
||||
>,
|
||||
this.revealedCipherService.revealed$(userId),
|
||||
]),
|
||||
),
|
||||
map(([ciphers, revealed]) => withRevealedViews(ciphers, revealed)),
|
||||
shareReplay({ refCount: true, bufferSize: 1 }),
|
||||
);
|
||||
|
||||
@@ -357,19 +366,24 @@ export class VaultPopupItemsService {
|
||||
map(([organizations, collections]) => {
|
||||
const orgMap = Object.fromEntries(organizations.map((org) => [org.id, org]));
|
||||
const collectionMap = Object.fromEntries(collections.map((col) => [col.id, col]));
|
||||
return ciphers
|
||||
.filter((c) => CipherViewLikeUtils.isDeleted(c))
|
||||
.filter((c) => hasAccessibleOrganization(c, orgMap))
|
||||
.map(
|
||||
(cipher) =>
|
||||
({
|
||||
...cipher,
|
||||
collections: cipher.collectionIds?.map(
|
||||
(colId) => collectionMap[colId as CollectionId],
|
||||
),
|
||||
organization: orgMap[cipher.organizationId as OrganizationId],
|
||||
}) as PopupCipherViewLike,
|
||||
);
|
||||
return (
|
||||
ciphers
|
||||
// The restricted-cipher rule blocks restore and delete, so the trash leaves them out.
|
||||
.filter(
|
||||
(c) => CipherViewLikeUtils.isDeleted(c) && !RestrictedCipherPolicy.isRestricted(c),
|
||||
)
|
||||
.filter((c) => hasAccessibleOrganization(c, orgMap))
|
||||
.map(
|
||||
(cipher) =>
|
||||
({
|
||||
...cipher,
|
||||
collections: cipher.collectionIds?.map(
|
||||
(colId) => collectionMap[colId as CollectionId],
|
||||
),
|
||||
organization: orgMap[cipher.organizationId as OrganizationId],
|
||||
}) as PopupCipherViewLike,
|
||||
)
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -450,6 +464,28 @@ const hasAccessibleOrganization = (
|
||||
orgMap: Record<string, Organization>,
|
||||
): boolean => !cipher.organizationId || orgMap[cipher.organizationId as OrganizationId] != null;
|
||||
|
||||
/**
|
||||
* Replaces each restricted row that has a live revealed view with that view. The view keeps the
|
||||
* row's collections and organization. It stays the same object, so row components can match it
|
||||
* against {@link RevealedCipherService.revealed$}.
|
||||
*/
|
||||
const withRevealedViews = (
|
||||
ciphers: PopupCipherViewLike[],
|
||||
revealed: ReadonlyMap<CipherId, CipherView>,
|
||||
): PopupCipherViewLike[] =>
|
||||
revealed.size === 0
|
||||
? ciphers
|
||||
: ciphers.map((cipher) => {
|
||||
const view =
|
||||
RestrictedCipherPolicy.isRestricted(cipher) && revealed.get(cipher.id as CipherId);
|
||||
return view
|
||||
? Object.assign(view, {
|
||||
collections: cipher.collections,
|
||||
organization: cipher.organization,
|
||||
})
|
||||
: cipher;
|
||||
});
|
||||
|
||||
/**
|
||||
* Operator that waits until the active account has synced at least once before allowing the source to continue emission.
|
||||
* @param syncService
|
||||
|
||||
@@ -187,6 +187,47 @@ describe("VaultPopupListTableFiltersService — cipherTypes$", () => {
|
||||
const types = await firstValueFrom(service.cipherTypes$);
|
||||
expect(types.map((t) => t.value)).toContain(CipherType.BankAccount);
|
||||
});
|
||||
|
||||
describe("contributed filter selection", () => {
|
||||
/** Saves land in state asynchronously, so let them settle before reading back. */
|
||||
const save = async (
|
||||
values: Parameters<VaultPopupListTableFiltersService["saveFilters"]>[0],
|
||||
) => {
|
||||
service.saveFilters(values);
|
||||
await new Promise((resolve) => setTimeout(resolve));
|
||||
};
|
||||
|
||||
it("persists the selection under the filter's key and reports a filter applied", async () => {
|
||||
await save({ contributed: { status: ["pending", "ready"] } });
|
||||
|
||||
expect(service.cachedFilters().contributedFilterIds).toEqual({
|
||||
status: ["pending", "ready"],
|
||||
});
|
||||
expect(service.hasFilterApplied()).toBe(true);
|
||||
});
|
||||
|
||||
it("reports no filter once the selection is cleared", async () => {
|
||||
await save({ contributed: { status: ["pending"] } });
|
||||
await save({ contributed: { status: [] } });
|
||||
|
||||
expect(service.hasFilterApplied()).toBe(false);
|
||||
});
|
||||
|
||||
it("restores the selection under the filter's key", async () => {
|
||||
await save({ contributed: { status: ["pending"] }, cipherType: CipherType.Login });
|
||||
|
||||
expect(await firstValueFrom(service.restoreFilters$())).toMatchObject({
|
||||
contributed: { status: ["pending"] },
|
||||
cipherType: CipherType.Login,
|
||||
});
|
||||
});
|
||||
|
||||
it("restores nothing for an empty selection", async () => {
|
||||
await save({ contributed: { status: [] } });
|
||||
|
||||
expect(await firstValueFrom(service.restoreFilters$())).not.toHaveProperty("contributed");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("VaultPopupListTableFiltersService — per-vault filters", () => {
|
||||
@@ -231,6 +272,7 @@ describe("VaultPopupListTableFiltersService — per-vault filters", () => {
|
||||
collectionIds: [],
|
||||
folderIds: ["folder-1"],
|
||||
cipherType: CipherType.Card,
|
||||
contributedFilterIds: {},
|
||||
});
|
||||
expect(service.hasFilterApplied()).toBe(true);
|
||||
});
|
||||
|
||||
@@ -65,6 +65,8 @@ interface CachedTableFilterState {
|
||||
collectionIds?: string[];
|
||||
folderIds?: string[];
|
||||
cipherType?: CipherType | null;
|
||||
/** Selected option IDs of each contributed chip (`VAULT_ITEM_FILTER`), keyed by its `key`. */
|
||||
contributedFilterIds?: Record<string, string[]>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -271,6 +273,7 @@ export class VaultPopupListTableFiltersService {
|
||||
filters.organizationIds?.length ||
|
||||
filters.collectionIds?.length ||
|
||||
filters.folderIds?.length ||
|
||||
Object.values(filters.contributedFilterIds ?? {}).some((ids) => ids.length) ||
|
||||
filters.cipherType != null
|
||||
);
|
||||
});
|
||||
@@ -345,6 +348,7 @@ export class VaultPopupListTableFiltersService {
|
||||
organization?: string[];
|
||||
collection?: string[];
|
||||
folder?: string[];
|
||||
contributed?: Record<string, string[]>;
|
||||
}): void {
|
||||
const userId = this.activeUserId();
|
||||
if (userId == null) {
|
||||
@@ -360,6 +364,7 @@ export class VaultPopupListTableFiltersService {
|
||||
collectionIds: values.collection ?? [],
|
||||
folderIds: values.folder ?? [],
|
||||
cipherType: values.cipherType ?? null,
|
||||
contributedFilterIds: values.contributed ?? {},
|
||||
},
|
||||
}));
|
||||
}
|
||||
@@ -377,6 +382,7 @@ export class VaultPopupListTableFiltersService {
|
||||
organization?: string[];
|
||||
collection?: string[];
|
||||
folder?: string[];
|
||||
contributed?: Record<string, string[]>;
|
||||
}> {
|
||||
return combineLatest([
|
||||
this.organizations$,
|
||||
@@ -395,6 +401,7 @@ export class VaultPopupListTableFiltersService {
|
||||
organization?: string[];
|
||||
collection?: string[];
|
||||
folder?: string[];
|
||||
contributed?: Record<string, string[]>;
|
||||
} = {};
|
||||
|
||||
if (state.organizationIds?.length) {
|
||||
@@ -426,6 +433,15 @@ export class VaultPopupListTableFiltersService {
|
||||
result.cipherType = state.cipherType;
|
||||
}
|
||||
|
||||
// Not validated here: the service does not know the options, and the table passes every
|
||||
// row for an ID the provider does not offer.
|
||||
const contributed = Object.entries(state.contributedFilterIds ?? {}).filter(
|
||||
([, ids]) => ids.length,
|
||||
);
|
||||
if (contributed.length) {
|
||||
result.contributed = Object.fromEntries(contributed);
|
||||
}
|
||||
|
||||
return result;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -481,6 +481,41 @@ describe("VaultPopupListTableService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a restricted row", () => {
|
||||
const gatedAutofillRow = () => {
|
||||
autoFillCiphers$.next([makeCipher({ id: "gated", partial: true })]);
|
||||
return latestRows()[0].actions;
|
||||
};
|
||||
const gatedAllItemsRow = () => {
|
||||
filteredCiphers$.next([makeCipher({ id: "gated", partial: true })]);
|
||||
return latestRows().find((r) => r._section === "allItems")!.actions;
|
||||
};
|
||||
|
||||
it("never autofills, even in the autofill section where a normal row would", async () => {
|
||||
currentTabIsOnBlocklist$.next(false);
|
||||
|
||||
expect(autofillRow()).toMatchObject({ primaryAutofill: true });
|
||||
expect(gatedAutofillRow()).toMatchObject({
|
||||
primaryAutofill: false,
|
||||
showFillOnHover: false,
|
||||
showAutofillInMenu: false,
|
||||
titleKey: expect.stringMatching(/^viewItemTitle/),
|
||||
});
|
||||
});
|
||||
|
||||
it("offers no copy actions", async () => {
|
||||
expect(sectionRow("allItems")).toMatchObject({ showCopyActions: true });
|
||||
expect(gatedAllItemsRow()).toMatchObject({ showCopyActions: false });
|
||||
});
|
||||
|
||||
it("never offers launch", async () => {
|
||||
currentTabIsOnBlocklist$.next(false);
|
||||
|
||||
expect(sectionRow("allItems")).toMatchObject({ showLaunch: true });
|
||||
expect(gatedAllItemsRow()).toMatchObject({ showLaunch: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("titleKey", () => {
|
||||
it("uses the autofill title (named field when a username is present) for fill-on-click rows", async () => {
|
||||
jest.spyOn(CipherViewLikeUtils, "getLogin").mockReturnValue({ username: "user" } as any);
|
||||
@@ -678,5 +713,16 @@ describe("VaultPopupListTableService", () => {
|
||||
expect(cipherService.updateLastLaunchedDate).toHaveBeenCalledWith("c1", "user-1");
|
||||
expect(newTab).toHaveBeenCalledWith("https://example.com");
|
||||
});
|
||||
|
||||
it("does nothing for a restricted cipher", async () => {
|
||||
jest.spyOn(CipherViewLikeUtils, "canLaunch").mockReturnValue(true);
|
||||
jest.spyOn(CipherViewLikeUtils, "getLaunchUri").mockReturnValue("https://example.com");
|
||||
const newTab = jest.spyOn(BrowserApi, "createNewTab").mockResolvedValue({} as any);
|
||||
|
||||
await service.launchCipher(makeCipher({ id: "c1", partial: true }));
|
||||
|
||||
expect(cipherService.updateLastLaunchedDate).not.toHaveBeenCalled();
|
||||
expect(newTab).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
CipherViewLike,
|
||||
CipherViewLikeUtils,
|
||||
} from "@bitwarden/common/vault/utils/cipher-view-like-utils";
|
||||
import { RestrictedCipherPolicy } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
import {
|
||||
ALL_ITEMS_SCOPE,
|
||||
@@ -65,6 +66,8 @@ export interface VaultRowActions {
|
||||
showFillOnHover: boolean;
|
||||
/** Show the launch-in-new-tab button (still gated on the cipher being launchable). */
|
||||
showLaunch: boolean;
|
||||
/** Show the quick copy actions. */
|
||||
showCopyActions: boolean;
|
||||
/** Offer "Autofill" in the more-options menu. */
|
||||
showAutofillInMenu: boolean;
|
||||
/** Offer "View" in the more-options menu. */
|
||||
@@ -290,9 +293,12 @@ export class VaultPopupListTableService {
|
||||
{ currentUriIsBlocked }: RowActionContext,
|
||||
): VaultRowActions {
|
||||
const isAutofill = section === "autofill";
|
||||
// The list swaps a revealed view in for its restricted row, so a restricted row has nothing
|
||||
// revealed: the server withholds its credentials.
|
||||
const gated = RestrictedCipherPolicy.isRestricted(cipher as CipherViewLike);
|
||||
|
||||
// Whether clicking the row autofills: the autofill section fills unless the URI is blocked.
|
||||
const primaryAutofill = isAutofill && !currentUriIsBlocked;
|
||||
const primaryAutofill = !gated && isAutofill && !currentUriIsBlocked;
|
||||
|
||||
const login = CipherViewLikeUtils.getLogin(cipher as CipherViewLike);
|
||||
const titleBase = primaryAutofill ? "autofillTitle" : "viewItemTitle";
|
||||
@@ -300,8 +306,9 @@ export class VaultPopupListTableService {
|
||||
return {
|
||||
primaryAutofill,
|
||||
showFillOnHover: primaryAutofill,
|
||||
showLaunch: !isAutofill,
|
||||
showAutofillInMenu: !primaryAutofill,
|
||||
showLaunch: !isAutofill && !gated,
|
||||
showCopyActions: !gated,
|
||||
showAutofillInMenu: !gated && !primaryAutofill,
|
||||
showViewInMenu: primaryAutofill,
|
||||
// Name the login's username field in the label when it has one.
|
||||
titleKey: login?.username != null ? `${titleBase}WithField` : titleBase,
|
||||
@@ -343,7 +350,11 @@ export class VaultPopupListTableService {
|
||||
*/
|
||||
async launchCipher(cipher: CipherViewLike) {
|
||||
const launchURI = CipherViewLikeUtils.getLaunchUri(cipher);
|
||||
if (!CipherViewLikeUtils.canLaunch(cipher) || !launchURI) {
|
||||
if (
|
||||
!CipherViewLikeUtils.canLaunch(cipher) ||
|
||||
!launchURI ||
|
||||
RestrictedCipherPolicy.isRestricted(cipher)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@
|
||||
bitMenuItem
|
||||
[attr.id]="'vault-items-table_menu-item_' + rowAction.id + '-' + row.id"
|
||||
[variant]="rowAction.variant ?? 'primary'"
|
||||
[disabled]="rowAction.disabled?.(row) ?? false"
|
||||
(click)="handleAction(rowAction, row)"
|
||||
>
|
||||
<bit-icon slot="start" fixedWidth [name]="rowAction.icon" />
|
||||
|
||||
@@ -319,6 +319,23 @@ describe("VaultItemsTableActionsColumnComponent", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("disabled actions", () => {
|
||||
it("disables the menu item when disabled returns true for the row", () => {
|
||||
const run = jest.fn();
|
||||
host.ciphers.set([loginCipher()]);
|
||||
host.rowActions.set([
|
||||
{ id: "disabled", label: "Disabled", icon: "bwi-lock", disabled: () => true, run },
|
||||
{ id: "enabled", label: "Enabled", icon: "bwi-lock", run },
|
||||
]);
|
||||
fixture.detectChanges();
|
||||
|
||||
const [disabled, enabled] = openMenu(0);
|
||||
|
||||
expect(disabled.disabled).toBe(true);
|
||||
expect(enabled.disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the launch button", () => {
|
||||
it("offers Launch for a cipher with a launchable uri", () => {
|
||||
host.ciphers.set([withUri("https://example.com")]);
|
||||
|
||||
@@ -31,6 +31,9 @@ export type VaultItemsTableRowAction<C extends CipherViewLike> = {
|
||||
/** Whether the action shows for `item`. Omit for always-shown. */
|
||||
show?: (item: C) => boolean;
|
||||
|
||||
/** Whether the shown action is disabled for `item`. Omit for always-enabled. */
|
||||
disabled?: (item: C) => boolean;
|
||||
|
||||
/**
|
||||
* Whether the action is gated behind a premium upgrade for `item` — Archive, for one, is only
|
||||
* available to premium users. When it returns `true` the menu item carries the Upgrade badge and
|
||||
|
||||
@@ -3,7 +3,11 @@ export {
|
||||
AtRiskPasswordCalloutService,
|
||||
AtRiskPasswordCalloutData,
|
||||
} from "./services/at-risk-password-callout.service";
|
||||
export { CipherRowMenuHandlers, CipherRowMenuService } from "./services/cipher-row-menu.service";
|
||||
export {
|
||||
CipherRowMenuHandlers,
|
||||
CipherRowMenuService,
|
||||
uniqueContributedActions,
|
||||
} from "./services/cipher-row-menu.service";
|
||||
export { CipherActionService } from "./services/cipher-action.service";
|
||||
export { PasswordRepromptService } from "./services/password-reprompt.service";
|
||||
export { PinnedSharedFoldersService } from "./services/pinned-shared-folders.service";
|
||||
|
||||
@@ -25,7 +25,7 @@ import { CIPHER_SHARE_ACCESS, CipherShareAccess } from "../tokens/cipher-share-a
|
||||
import { VAULT_ROW_ACTIONS } from "../tokens/vault-row-actions.token";
|
||||
|
||||
import { CipherActionService } from "./cipher-action.service";
|
||||
import { CipherRowMenuService } from "./cipher-row-menu.service";
|
||||
import { CipherRowMenuService, uniqueContributedActions } from "./cipher-row-menu.service";
|
||||
|
||||
const userId = "test-user-id" as UserId;
|
||||
|
||||
@@ -696,6 +696,17 @@ describe("CipherRowMenuService", () => {
|
||||
expect(run).toHaveBeenCalledWith(cipher);
|
||||
});
|
||||
|
||||
it("checks a host's own built-in IDs when called directly", () => {
|
||||
const kept = inProduction(() =>
|
||||
uniqueContributedActions(
|
||||
[contributed("view"), contributed("delete"), contributed("request")],
|
||||
new Set(["view"]),
|
||||
),
|
||||
);
|
||||
|
||||
expect(kept.map((a) => a.id)).toEqual(["delete", "request"]);
|
||||
});
|
||||
|
||||
it("throws in dev mode when an ID matches a built-in action", () => {
|
||||
expect(() => serviceWith([contributed("delete")])).toThrow(/"delete"/);
|
||||
});
|
||||
|
||||
@@ -56,13 +56,14 @@ const BUILT_IN_ACTION_IDS: ReadonlySet<string> = new Set([
|
||||
]);
|
||||
|
||||
/**
|
||||
* Drops each contributed action whose ID matches a built-in ID or an earlier contributed ID.
|
||||
* Drops each contributed action whose ID matches one of `builtInIds` or an earlier contributed ID.
|
||||
* Throws in dev mode instead.
|
||||
*/
|
||||
function uniqueContributedActions(
|
||||
export function uniqueContributedActions(
|
||||
actions: readonly VaultItemsTableRowAction<CipherViewLike>[],
|
||||
builtInIds: ReadonlySet<string>,
|
||||
): readonly VaultItemsTableRowAction<CipherViewLike>[] {
|
||||
const seen = new Set(BUILT_IN_ACTION_IDS);
|
||||
const seen = new Set(builtInIds);
|
||||
return actions.filter((action) => {
|
||||
if (seen.has(action.id)) {
|
||||
if (isDevMode()) {
|
||||
@@ -99,6 +100,7 @@ export class CipherRowMenuService {
|
||||
});
|
||||
private readonly contributedActions = uniqueContributedActions(
|
||||
inject(VAULT_ROW_ACTIONS, { optional: true }) ?? [],
|
||||
BUILT_IN_ACTION_IDS,
|
||||
);
|
||||
|
||||
private readonly userId$ = this.accountService.activeAccount$.pipe(
|
||||
|
||||
@@ -13,7 +13,9 @@ import { VaultItemsTableRowAction } from "../components/vault-items-table/vault-
|
||||
* drops the action in production.
|
||||
* - `label` is fixed. For a label that depends on the row, add one action per label and pick
|
||||
* with `show`.
|
||||
* - Contributed actions go after the built-in actions and before the Delete group.
|
||||
* - Web and desktop place contributed actions after the built-in actions and before the Delete
|
||||
* group. The browser popup places them at the top of the menu, after View.
|
||||
* - The browser popup's menu has no icons or upgrade badge, so it ignores `icon` and `premiumGated`.
|
||||
* - Contributed actions do not reach the bulk action bar.
|
||||
*
|
||||
* Single token for now. Widen to `multi` when a second feature contributes.
|
||||
|
||||
Reference in New Issue
Block a user