[PAM-575] Browser: PAM in the extension (#24667)

This commit is contained in:
Patrik Svensson
2026-11-11 12:15:03 +01:00
committed by GitHub
parent 88fa09626a
commit d86602439c
31 changed files with 3529 additions and 5 deletions

1
.github/CODEOWNERS vendored
View File

@@ -254,6 +254,7 @@ apps/desktop/src/services/biometric-message-handler.service.ts @bitwarden/team-
## PAM
apps/web/src/app/pam @bitwarden/team-pam-dev
bitwarden_license/bit-browser/src/pam @bitwarden/team-pam-dev
bitwarden_license/bit-pam @bitwarden/team-pam-dev
bitwarden_license/bit-pam-components @bitwarden/team-pam-dev
bitwarden_license/bit-web/src/app/pam @bitwarden/team-pam-dev

View File

@@ -8902,9 +8902,27 @@
"pamStartLeaseErrorNotApproved": {
"message": "This request has not been approved yet."
},
"pamStartLeaseErrorNoLongerActivatable": {
"message": "This request can no longer be activated."
},
"pamStartLeaseErrorAlreadyUsed": {
"message": "This request's access has already been used and is no longer active."
},
"pamStartLeaseErrorSingleActiveAccess": {
"message": "Only 1 user can have active access to this item at a time. Try again once the current access ends."
},
"pamStartLeaseErrorNetworkNotPermitted": {
"message": "Access to this item is not permitted from your current network."
},
"pamStartLeaseErrorTimeNotPermitted": {
"message": "Access to this item is not permitted at this time."
},
"pamStartLeaseErrorNotPermitted": {
"message": "Access to this item is not permitted right now."
},
"requestAccessModalAlreadyApproved": {
"message": "You already have an approved request for this item."
},
"requestAccessModalAlreadyPending": {
"message": "You already have a pending request for this item."
},
@@ -8972,6 +8990,9 @@
"pamExtendLeaseEnded": {
"message": "Your access ended before it could be extended. The request is in your history."
},
"pamAccessBadgePrivileged": {
"message": "Privileged"
},
"pamAccessBadgePending": {
"message": "Pending approval"
},
@@ -8981,6 +9002,27 @@
"pamAccessBadgeReady": {
"message": "Ready to use"
},
"pamAccessBadgeTimeLeft": {
"message": "$DURATION$ left",
"placeholders": {
"duration": {
"content": "$1",
"example": "18m"
}
}
},
"pamAccessBadgeEndingSoon": {
"message": "Ending soon • $DURATION$ left",
"placeholders": {
"duration": {
"content": "$1",
"example": "4m"
}
}
},
"pamAccessBadgeEnded": {
"message": "Session ended"
},
"pamActiveLeaseBannerTitleV2": {
"message": "Access active • $DURATION$ left",
"placeholders": {
@@ -9024,6 +9066,18 @@
"pamRequestToUse": {
"message": "Request to use"
},
"pamUnavailableToRequest": {
"message": "Unavailable to request",
"description": "Subtitle of a vault row for a privileged item that cannot be requested right now, for example because another member holds it."
},
"pamExtendAccessMenuItem": {
"message": "Extend access",
"description": "Overflow menu action on a vault row that extends the member's active access to a privileged item."
},
"pamAccessBadgeLessThanMinuteLeft": {
"message": "<1m left",
"description": "Badge for a vault item whose access ends in under a minute."
},
"controlledAccess": {
"message": "Controlled access"
},
@@ -9128,9 +9182,24 @@
"pendingStateCancelRequest": {
"message": "Cancel request"
},
"pamKeepRequest": {
"message": "Keep request"
},
"pamCancelRequestTitle": {
"message": "Cancel access request"
},
"pamCancelRequestPendingConfirm": {
"message": "This withdraws your request before an approver has decided on it. You can submit a new request at any time."
},
"pamCancelRequestApprovedConfirm": {
"message": "This gives up access that has already been approved. You can submit a new request, but it will need to be approved again."
},
"pamCancelRequestCanceledToast": {
"message": "Request canceled"
},
"pendingStateCancelError": {
"message": "Couldn't cancel the request."
},
"requestAccessModalSubmitV2": {
"message": "Send request"
},
@@ -9239,6 +9308,9 @@
"requestAccessModalGenericError": {
"message": "Could not request access. Try again."
},
"requestAccessModalAlreadyActive": {
"message": "You already have active access to this item."
},
"requestAccessModalApprovedSuccessV2": {
"message": "Access approved. Select Start access to begin."
},

View File

@@ -549,8 +549,8 @@ export default class MainBackground {
// an erased annotation would leave the channel ambient
readonly #intraprocessMessageSender: IntraprocessMessageSender;
// Retained because `OverlayBackground` is constructed lazily, outside this constructor's scope.
// `private` suffices here: a listener only reads, so reaching it grants no way to publish.
private messageListener: MessageListener;
// Public, unlike the sender: a listener only reads, so reaching it grants no way to publish.
readonly messageListener: MessageListener;
scriptInjectorService: BrowserScriptInjectorService;
kdfConfigService: KdfConfigService;
offscreenDocumentService: OffscreenDocumentService;
@@ -626,6 +626,14 @@ export default class MainBackground {
/** @param overrides Services the commercial build supplies in place of the OSS defaults. */
constructor(overrides?: {
revealedCipherService?: (deps: {
stateProvider: StateProvider;
accountService: AccountServiceAbstraction;
authService: AuthServiceAbstraction;
cipherService: CipherServiceAbstraction;
messageSender: MessageSender;
logService: LogServiceAbstraction;
}) => RevealedCipherService;
fillCipherPolicy?: (deps: {
cipherService: CipherServiceAbstraction;
revealedCipherService: RevealedCipherService;
@@ -990,7 +998,6 @@ export default class MainBackground {
this.stateService,
this.tokenService,
);
this.revealedCipherService = new NoopRevealedCipherService();
this.configApiService = new ConfigApiService(this.apiService);
@@ -1228,6 +1235,15 @@ export default class MainBackground {
this.cipherEncryptionService,
this.cipherSdkService,
);
this.revealedCipherService =
overrides?.revealedCipherService?.({
stateProvider: this.stateProvider,
accountService: this.accountService,
authService: this.authService,
cipherService: this.cipherService,
messageSender: this.messagingService,
logService: this.logService,
}) ?? new NoopRevealedCipherService();
this.fillCipherPolicy =
overrides?.fillCipherPolicy?.({
cipherService: this.cipherService,

View File

@@ -1,9 +1,50 @@
import { AccessLeasesSdkService } from "@bitwarden/bit-pam";
import OssMainBackground from "@bitwarden/browser/background/main.background";
import { PamLeaseRefreshService } from "../pam/background/pam-lease-refresh.service";
import { BrowserRevealedCipherService } from "../pam/browser-revealed-cipher.service";
import { PamFillCipherPolicy } from "../pam/pam-fill-cipher-policy";
export default class MainBackground {
private ossMain = new OssMainBackground();
private ossMain = new OssMainBackground({
revealedCipherService: ({
stateProvider,
authService,
cipherService,
messageSender,
logService,
}) =>
new BrowserRevealedCipherService(
stateProvider,
authService,
cipherService,
messageSender,
logService,
),
fillCipherPolicy: ({ cipherService, revealedCipherService }) =>
new PamFillCipherPolicy(cipherService, revealedCipherService),
});
private pamLeaseRefreshService = new PamLeaseRefreshService(
this.ossMain.stateProvider,
this.ossMain.authService,
this.ossMain.configService,
this.ossMain.organizationService,
new AccessLeasesSdkService(
this.ossMain.sdkService,
this.ossMain.accountService,
this.ossMain.logService,
),
this.ossMain.apiService,
this.ossMain.serverNotificationsService,
this.ossMain.syncService,
this.ossMain.messageListener,
this.ossMain.taskSchedulerService,
this.ossMain.logService,
);
async bootstrap() {
await this.ossMain.bootstrap();
this.pamLeaseRefreshService.start();
}
}

View File

@@ -0,0 +1,323 @@
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject, firstValueFrom, map, of, Subject, Subscription } from "rxjs";
import { AccessLeaseSdkService } from "@bitwarden/bit-pam";
import { BrowserTaskSchedulerService } from "@bitwarden/browser/platform/services/abstractions/browser-task-scheduler.service";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { NotificationType } from "@bitwarden/common/enums";
import { NotificationResponse } from "@bitwarden/common/models/response/notification.response";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { Message, MessageListener } from "@bitwarden/common/platform/messaging";
import { ScheduledTaskNames } from "@bitwarden/common/platform/scheduling";
import { ServerNotificationsService } from "@bitwarden/common/platform/server-notifications";
import { SyncService } from "@bitwarden/common/platform/sync";
import { awaitAsync, FakeStateProvider, mockAccountServiceWith } from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data";
import { CipherResponse } from "@bitwarden/common/vault/models/response/cipher.response";
import type { AccessLeaseView } from "@bitwarden/sdk-internal";
import { PAM_REFRESH_LEASES } from "../lease-messages";
import { LEASED_CIPHERS } from "../leased-cipher.state";
import { at, IN_AN_HOUR, leaseEntry, NOW, seedLeases } from "../leased-cipher.state.spec-util";
import { PamLeaseRefreshService } from "./pam-lease-refresh.service";
describe("PamLeaseRefreshService", () => {
const userId = "3f5a3c8a-3b1e-4c8a-9b1e-3b1e4c8a9b1e" as UserId;
let stateProvider: FakeStateProvider;
let authStatuses$: BehaviorSubject<Record<UserId, AuthenticationStatus>>;
let configService: MockProxy<ConfigService>;
let accessLeaseSdkService: MockProxy<AccessLeaseSdkService>;
let apiService: MockProxy<ApiService>;
let notifications$: Subject<readonly [NotificationResponse, UserId]>;
let lastSync$: BehaviorSubject<Date | null>;
let messages$: Subject<Message<Record<string, unknown>>>;
let taskSchedulerService: MockProxy<BrowserTaskSchedulerService>;
let service: PamLeaseRefreshService;
const lease = (cipherId: string, overrides: Partial<AccessLeaseView> = {}) =>
({
id: `lease-${cipherId}`,
cipherId,
status: "active",
notAfter: IN_AN_HOUR,
...overrides,
}) as unknown as AccessLeaseView;
const push = (type: NotificationType, payload?: unknown) =>
notifications$.next([{ type, payload } as NotificationResponse, userId]);
const stored = () => firstValueFrom(stateProvider.getUser(userId, LEASED_CIPHERS).state$);
const storedIds = async () => Object.keys((await stored())?.leases ?? {});
beforeEach(() => {
jest.spyOn(Date, "now").mockReturnValue(NOW);
stateProvider = new FakeStateProvider(mockAccountServiceWith(userId));
authStatuses$ = new BehaviorSubject<Record<UserId, AuthenticationStatus>>({
[userId]: AuthenticationStatus.Unlocked,
});
const authService = mock<AuthService>();
authService.authStatuses$ = authStatuses$;
authService.authStatusFor$.mockImplementation((id) =>
authStatuses$.pipe(map((statuses) => statuses[id])),
);
configService = mock<ConfigService>();
configService.userCachedFeatureFlag$.mockReturnValue(of(true));
const organizationService = mock<OrganizationService>();
organizationService.organizations$.mockReturnValue(
of([{ canAccessPrivilegedAccess: true } as Organization]),
);
accessLeaseSdkService = mock<AccessLeaseSdkService>();
accessLeaseSdkService.listMyLeases.mockResolvedValue([]);
apiService = mock<ApiService>();
apiService.getFullCipherDetails.mockImplementation(
async (id) => ({ id, type: CipherType.Login, name: "2.encrypted" }) as CipherResponse,
);
notifications$ = new Subject();
const serverNotificationsService = mock<ServerNotificationsService>();
serverNotificationsService.notifications$ = notifications$;
lastSync$ = new BehaviorSubject<Date | null>(new Date(0));
const syncService = mock<SyncService>();
syncService.lastSync$.mockReturnValue(lastSync$);
messages$ = new Subject();
taskSchedulerService = mock<BrowserTaskSchedulerService>();
taskSchedulerService.setTimeout.mockReturnValue(new Subscription());
taskSchedulerService.clearScheduledAlarm.mockResolvedValue();
service = new PamLeaseRefreshService(
stateProvider,
authService,
configService,
organizationService,
accessLeaseSdkService,
apiService,
serverNotificationsService,
syncService,
new MessageListener(messages$),
taskSchedulerService,
mock<LogService>(),
);
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
describe("refresh", () => {
it("stores a full copy for each live active lease of the user", async () => {
accessLeaseSdkService.listMyLeases.mockResolvedValue([
lease("live"),
lease("lapsed", { notAfter: at(-1) }),
lease("revoked", { status: "revoked" }),
]);
await service.refresh(userId);
const state = await stored();
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledWith(userId);
expect(await storedIds()).toEqual(["live"]);
expect(state?.leases.live).toMatchObject({ leaseId: "lease-live", notAfter: IN_AN_HOUR });
expect(state?.leases.live.cipher).toBeInstanceOf(CipherData);
expect(state?.refreshedAt).toBe(NOW);
expect(apiService.getFullCipherDetails).toHaveBeenCalledTimes(1);
});
it("skips a cipher whose details are still partial", async () => {
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("gated")]);
apiService.getFullCipherDetails.mockResolvedValue({
id: "gated",
partialData: "{}",
} as CipherResponse);
await service.refresh(userId);
expect((await stored())?.leases).toEqual({});
});
it("reuses a held copy and drops copies whose lease ended", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("kept"), leaseEntry("ended")]);
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("kept")]);
await service.refresh(userId);
expect(await storedIds()).toEqual(["kept"]);
expect(apiService.getFullCipherDetails).not.toHaveBeenCalled();
});
it("clears copies when PAM is off for the user", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("kept")]);
configService.userCachedFeatureFlag$.mockReturnValue(of(false));
await service.refresh(userId);
expect(await stored()).toBeNull();
expect(accessLeaseSdkService.listMyLeases).not.toHaveBeenCalled();
});
it("writes nothing once the user has locked", async () => {
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("live")]);
authStatuses$.next({ [userId]: AuthenticationStatus.Locked });
await service.refresh(userId);
expect(await stored()).toBeNull();
});
});
describe("start", () => {
let subscription: Subscription;
afterEach(() => subscription?.unsubscribe());
it("refreshes at once, on an access-request push and when the popup asks", async () => {
subscription = service.start();
await awaitAsync();
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledTimes(1);
push(NotificationType.RefreshAccessRequest);
await awaitAsync();
messages$.next({ command: PAM_REFRESH_LEASES.command, userId });
await awaitAsync();
push(NotificationType.RefreshSecurityTasks);
messages$.next({ command: PAM_REFRESH_LEASES.command, userId: "someone-else" });
await awaitAsync();
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledTimes(3);
});
it("refreshes after a full sync, not after every sync message", async () => {
subscription = service.start();
await awaitAsync();
lastSync$.next(new Date(NOW));
await awaitAsync();
lastSync$.next(new Date(NOW));
messages$.next({ command: "syncCompleted", successfully: true, userId });
await awaitAsync();
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledTimes(2);
});
it("re-fetches a held copy when its cipher is edited", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("kept"), leaseEntry("other")]);
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("kept"), lease("other")]);
subscription = service.start();
await awaitAsync();
expect(apiService.getFullCipherDetails).not.toHaveBeenCalled();
apiService.getFullCipherDetails.mockResolvedValue({
id: "kept",
revisionDate: at(0),
} as CipherResponse);
push(NotificationType.SyncCipherUpdate, { id: "kept" });
await awaitAsync();
expect(apiService.getFullCipherDetails).toHaveBeenCalledTimes(1);
expect(apiService.getFullCipherDetails).toHaveBeenCalledWith("kept");
expect((await stored())?.leases.kept.cipher.revisionDate).toBe(at(0));
});
it("re-fetches a held copy when the popup asks for its cipher", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("kept")]);
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("kept")]);
subscription = service.start();
await awaitAsync();
expect(apiService.getFullCipherDetails).not.toHaveBeenCalled();
messages$.next({ command: PAM_REFRESH_LEASES.command, userId, cipherId: "kept" });
await awaitAsync();
expect(apiService.getFullCipherDetails).toHaveBeenCalledTimes(1);
expect(apiService.getFullCipherDetails).toHaveBeenCalledWith("kept");
});
it("fetches a new lease when the popup asks for a cipher it holds no copy of", async () => {
subscription = service.start();
await awaitAsync();
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("new")]);
messages$.next({ command: PAM_REFRESH_LEASES.command, userId, cipherId: "new" });
await awaitAsync();
expect(await storedIds()).toEqual(["new"]);
});
it("ignores an edit push for a cipher it holds no copy of", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("kept")]);
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("kept")]);
subscription = service.start();
await awaitAsync();
push(NotificationType.SyncCipherUpdate, { id: "unleased" });
await awaitAsync();
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledTimes(1);
expect(apiService.getFullCipherDetails).not.toHaveBeenCalled();
});
it("drops a revoked lease on refresh", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("kept"), leaseEntry("revoked")]);
accessLeaseSdkService.listMyLeases.mockResolvedValue([lease("kept")]);
subscription = service.start();
await awaitAsync();
expect(await storedIds()).toEqual(["kept"]);
});
it("prunes a lapsed lease when the expiry task runs, and reschedules", async () => {
jest.useFakeTimers({ now: NOW });
await seedLeases(stateProvider, userId, [
leaseEntry("first", at(60_000)),
leaseEntry("second"),
]);
accessLeaseSdkService.listMyLeases.mockResolvedValue([
lease("first", { notAfter: at(60_000) }),
lease("second"),
]);
subscription = service.start();
await jest.advanceTimersByTimeAsync(0);
expect(taskSchedulerService.clearScheduledAlarm).toHaveBeenCalled();
expect(taskSchedulerService.setTimeout).toHaveBeenCalledTimes(1);
expect(taskSchedulerService.setTimeout).toHaveBeenCalledWith(
ScheduledTaskNames.pamLeaseExpiry,
60_000,
);
await jest.advanceTimersByTimeAsync(60_000);
const [[, expiryTask]] = taskSchedulerService.registerTaskHandler.mock.calls;
expiryTask();
await jest.advanceTimersByTimeAsync(0);
expect(await storedIds()).toEqual(["second"]);
expect(taskSchedulerService.setTimeout).toHaveBeenLastCalledWith(
ScheduledTaskNames.pamLeaseExpiry,
60 * 60_000 - 60_000,
);
});
it("retries a failed list once, then keeps the live copies", async () => {
jest.useFakeTimers({ now: NOW });
await seedLeases(stateProvider, userId, [leaseEntry("kept"), leaseEntry("lapsed", at(-1))]);
accessLeaseSdkService.listMyLeases.mockRejectedValue(new Error("offline"));
subscription = service.start();
await jest.advanceTimersByTimeAsync(0);
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledTimes(1);
await jest.advanceTimersByTimeAsync(30_000);
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledTimes(2);
expect(await storedIds()).toEqual(["kept"]);
await jest.advanceTimersByTimeAsync(5 * 60_000);
expect(accessLeaseSdkService.listMyLeases).toHaveBeenCalledTimes(2);
});
});
});

View File

@@ -0,0 +1,266 @@
import {
combineLatest,
concatMap,
defaultIfEmpty,
defer,
distinctUntilChanged,
filter,
firstValueFrom,
map,
merge,
Observable,
of,
retry,
skip,
Subscription,
switchMap,
} from "rxjs";
import { AccessLeaseSdkService, isLeaseLive } from "@bitwarden/bit-pam";
import { BrowserTaskSchedulerService } from "@bitwarden/browser/platform/services/abstractions/browser-task-scheduler.service";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { NotificationType } from "@bitwarden/common/enums";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
import { SyncCipherNotification } from "@bitwarden/common/models/response/notification.response";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { uuidAsString } from "@bitwarden/common/platform/abstractions/sdk/sdk.service";
import { MessageListener } from "@bitwarden/common/platform/messaging";
import { ScheduledTaskNames } from "@bitwarden/common/platform/scheduling";
import { ServerNotificationsService } from "@bitwarden/common/platform/server-notifications";
import { StateProvider } from "@bitwarden/common/platform/state";
import { SyncService } from "@bitwarden/common/platform/sync";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data";
import type { AccessLeaseView } from "@bitwarden/sdk-internal";
import { PAM_REFRESH_LEASES } from "../lease-messages";
import { LEASED_CIPHERS, LeasedCipherEntry, liveLeasedCiphers } from "../leased-cipher.state";
type RefreshRequest = { refetch?: string; onlyIfHeld?: boolean };
/** One more try after a failed lease list, so a revocation push is not lost to it. */
const LIST_RETRY_MS = 30_000;
/**
* Keeps an encrypted full copy of each cipher the user holds a live lease on, for the
* background's autofill surfaces and the popup to join. Background only.
*/
export class PamLeaseRefreshService {
private expiryTimer?: Subscription;
constructor(
private stateProvider: StateProvider,
private authService: AuthService,
private configService: ConfigService,
private organizationService: OrganizationService,
private accessLeaseSdkService: AccessLeaseSdkService,
private apiService: ApiService,
private serverNotificationsService: ServerNotificationsService,
private syncService: SyncService,
private messageListener: MessageListener,
private taskSchedulerService: BrowserTaskSchedulerService,
private logService: LogService,
) {
// Registered during construction, so an alarm that wakes the worker finds its handler.
this.taskSchedulerService.registerTaskHandler(ScheduledTaskNames.pamLeaseExpiry, () =>
this.pruneLapsed(),
);
}
start(): Subscription {
return this.authService.authStatuses$
.pipe(
map(unlockedUserIds),
distinctUntilChanged((a, b) => a.join() === b.join()),
switchMap((userIds) =>
merge(this.expiryAlarm$(userIds), ...userIds.map((userId) => this.refreshes$(userId))),
),
)
.subscribe();
}
/**
* Re-reads the user's leases and stores a full copy of each newly leased cipher. `refetch` also
* re-fetches that cipher's copy; with `onlyIfHeld`, nothing happens when no copy is held.
*/
async refresh(userId: UserId, refetch?: string, onlyIfHeld = false): Promise<void> {
try {
const stored = (await firstValueFrom(this.leaseState(userId).state$))?.leases ?? {};
if (onlyIfHeld && refetch != null && !(refetch in stored)) {
return;
}
const leases = (await this.allowed(userId))
? await this.reconcile(userId, stored, refetch)
: null;
if (leases == null && Object.keys(stored).length === 0) {
return;
}
// A lock clears this state; writing after it would outlive the lock.
const status = await firstValueFrom(this.authService.authStatusFor$(userId));
if (status !== AuthenticationStatus.Unlocked) {
return;
}
await this.leaseState(userId).update(() =>
leases == null ? null : { refreshedAt: Date.now(), leases },
);
} catch (error) {
this.logService.error(`[PAM] Failed to refresh leased ciphers: ${error}`);
}
}
/** Refreshes at once too, since a worker start or an unlock may have missed a push. */
private refreshes$(userId: UserId): Observable<void> {
const notifications$ = this.serverNotificationsService.notifications$.pipe(
filter(([, id]) => id === userId),
map(([notification]) => notification),
);
return merge(
merge(
of(null),
notifications$.pipe(filter((n) => n.type === NotificationType.RefreshAccessRequest)),
// Full syncs only; `syncCompleted` also follows each single-cipher push.
this.syncService.lastSync$(userId).pipe(
map((date) => date?.getTime()),
distinctUntilChanged(),
skip(1),
),
).pipe(map((): RefreshRequest => ({}))),
this.messageListener.messages$(PAM_REFRESH_LEASES).pipe(
filter((msg) => msg.userId === userId),
map((msg): RefreshRequest => ({ refetch: msg.cipherId })),
),
// Core sync keeps the restricted row (PAM-318), so an edit never reaches the held copy.
notifications$.pipe(
filter((n) => n.type === NotificationType.SyncCipherUpdate),
map((n): RefreshRequest => ({
refetch: (n.payload as SyncCipherNotification).id,
onlyIfHeld: true,
})),
),
).pipe(concatMap(({ refetch, onlyIfHeld }) => this.refresh(userId, refetch, onlyIfHeld)));
}
/** Backstop alarm at the earliest lease end, which wakes the worker to prune session storage. */
private expiryAlarm$(userIds: UserId[]): Observable<void> {
return combineLatest(userIds.map((userId) => this.leaseState(userId).state$)).pipe(
defaultIfEmpty([]),
map((states) => {
const now = Date.now();
const ends = states
.flatMap((state) => Object.values(liveLeasedCiphers(state?.leases, now)))
.map((entry) => Date.parse(entry.notAfter));
return ends.length === 0 ? null : Math.min(...ends);
}),
distinctUntilChanged(),
concatMap(async (end) => {
try {
this.expiryTimer?.unsubscribe();
// Also clears an alarm left by an earlier worker, which `setTimeout` would keep instead.
await this.taskSchedulerService.clearScheduledAlarm(ScheduledTaskNames.pamLeaseExpiry);
this.expiryTimer =
end == null
? undefined
: this.taskSchedulerService.setTimeout(
ScheduledTaskNames.pamLeaseExpiry,
end - Date.now(),
);
} catch (error) {
this.logService.error(`[PAM] Failed to schedule lease expiry: ${error}`);
}
}),
);
}
private async allowed(userId: UserId): Promise<boolean> {
const [flag, organizations] = await Promise.all([
firstValueFrom(this.configService.userCachedFeatureFlag$(FeatureFlag.Pam, userId)),
firstValueFrom(this.organizationService.organizations$(userId)),
]);
return flag && organizations.some((organization) => organization.canAccessPrivilegedAccess);
}
private async reconcile(
userId: UserId,
stored: Record<string, LeasedCipherEntry>,
refetch?: string,
): Promise<Record<string, LeasedCipherEntry>> {
let leases: AccessLeaseView[];
try {
leases = await firstValueFrom(
defer(() => this.accessLeaseSdkService.listMyLeases(userId)).pipe(
retry({ count: 1, delay: LIST_RETRY_MS }),
),
);
} catch {
// Kept copies still lapse on their own `notAfter`.
return liveLeasedCiphers(stored, Date.now());
}
const now = Date.now();
const entries = await Promise.all(
leases
.filter((lease) => lease.status === "active" && isLeaseLive(lease, now))
.map(async (lease): Promise<[string, LeasedCipherEntry] | null> => {
const cipherId = uuidAsString(lease.cipherId);
const leaseId = uuidAsString(lease.id);
const held = stored[cipherId];
if (
cipherId !== refetch &&
held?.leaseId === leaseId &&
held.notAfter === lease.notAfter
) {
return [cipherId, held];
}
const cipher = await this.fetchFullCopy(cipherId);
return cipher && [cipherId, { leaseId, notAfter: lease.notAfter, cipher }];
}),
);
return Object.fromEntries(entries.filter((entry) => entry != null));
}
/** A still-partial response means the lease lapsed after the list read. */
private async fetchFullCopy(cipherId: string): Promise<CipherData | null> {
try {
const cipher = new CipherData(await this.apiService.getFullCipherDetails(cipherId));
return cipher.partialData == null ? cipher : null;
} catch (error) {
this.logService.error(`[PAM] Failed to fetch a leased cipher: ${error}`);
return null;
}
}
/** Drops lapsed copies from session storage; `start`'s streams then reschedule. */
private async pruneLapsed(): Promise<void> {
try {
const now = Date.now();
const userIds = Object.keys(await firstValueFrom(this.authService.authStatuses$)) as UserId[];
for (const userId of userIds) {
await this.leaseState(userId).update(
(state) => state && { ...state, leases: liveLeasedCiphers(state.leases, now) },
{
shouldUpdate: (state) =>
Object.values(state?.leases ?? {}).some((entry) => !isLeaseLive(entry, now)),
},
);
}
} catch (error) {
this.logService.error(`[PAM] Failed to prune lapsed leases: ${error}`);
}
}
private leaseState(userId: UserId) {
return this.stateProvider.getUser(userId, LEASED_CIPHERS);
}
}
function unlockedUserIds(statuses: Record<UserId, AuthenticationStatus>): UserId[] {
return (Object.keys(statuses ?? {}) as UserId[])
.filter((userId) => statuses[userId] === AuthenticationStatus.Unlocked)
.sort();
}

View File

@@ -0,0 +1,209 @@
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject, firstValueFrom } from "rxjs";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { MessageSender } from "@bitwarden/common/platform/messaging";
import { FakeStateProvider, mockAccountServiceWith } from "@bitwarden/common/spec";
import { CipherId, UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { Cipher } from "@bitwarden/common/vault/models/domain/cipher";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { BrowserRevealedCipherService } from "./browser-revealed-cipher.service";
import { PAM_REFRESH_LEASES } from "./lease-messages";
import { at, leaseEntry, NOW, seedLeases } from "./leased-cipher.state.spec-util";
describe("BrowserRevealedCipherService", () => {
const userId = "user-id" as UserId;
const otherUserId = "other-user-id" as UserId;
const cipherId = "leased" as CipherId;
let stateProvider: FakeStateProvider;
let authStatuses$: BehaviorSubject<Record<UserId, AuthenticationStatus>>;
let cipherService: MockProxy<CipherService>;
let messageSender: MockProxy<MessageSender>;
let service: BrowserRevealedCipherService;
const view = (id: string, partial = false) =>
Object.assign(new CipherView(), { id, partial, name: id });
const ids = (views: ReadonlyMap<CipherId, CipherView>) => [...views.keys()];
/** Settles promises and timers due now, under fake timers. */
const flush = () => jest.advanceTimersByTimeAsync(0);
beforeEach(() => {
jest.useFakeTimers({ now: NOW });
stateProvider = new FakeStateProvider(mockAccountServiceWith(userId));
authStatuses$ = new BehaviorSubject<Record<UserId, AuthenticationStatus>>({
[userId]: AuthenticationStatus.Unlocked,
});
const authService = mock<AuthService>();
authService.authStatuses$ = authStatuses$;
cipherService = mock<CipherService>();
cipherService.decrypt.mockImplementation(async (cipher: Cipher) => view(cipher.id));
messageSender = mock<MessageSender>();
service = new BrowserRevealedCipherService(
stateProvider,
authService,
cipherService,
messageSender,
mock<LogService>(),
);
});
afterEach(() => {
jest.useRealTimers();
});
describe("revealed$", () => {
it("emits the decrypted live copies of an unlocked user", async () => {
await seedLeases(stateProvider, userId, [
leaseEntry("leased", at(60_000)),
leaseEntry("lapsed", at(-1)),
]);
await flush();
const revealed = await firstValueFrom(service.revealed$(userId));
expect(ids(revealed)).toEqual(["leased"]);
expect(cipherService.decrypt).toHaveBeenCalledWith(expect.any(Cipher), userId);
});
it("emits nothing for a user who is not unlocked", async () => {
await seedLeases(stateProvider, otherUserId, [leaseEntry("theirs")]);
await flush();
expect(ids(await firstValueFrom(service.revealed$(otherUserId)))).toEqual([]);
});
it("drops a copy that decrypts to a partial view or another cipher", async () => {
cipherService.decrypt.mockImplementation(async (cipher: Cipher) =>
cipher.id === "partial" ? view("partial", true) : view("someone-else"),
);
await seedLeases(stateProvider, userId, [leaseEntry("partial"), leaseEntry("mismatch")]);
await flush();
expect(ids(await firstValueFrom(service.revealed$(userId)))).toEqual([]);
});
it("drops a copy that fails to decrypt", async () => {
cipherService.decrypt.mockRejectedValue(new Error("boom"));
await seedLeases(stateProvider, userId, [leaseEntry("leased")]);
await flush();
expect(ids(await firstValueFrom(service.revealed$(userId)))).toEqual([]);
});
it("clears the user's views in this process when the user locks", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("leased")]);
await flush();
authStatuses$.next({ [userId]: AuthenticationStatus.Locked });
await flush();
expect(ids(await firstValueFrom(service.revealed$(userId)))).toEqual([]);
expect(service.isRevealed(userId, cipherId)).toBe(false);
});
it("drops a view once its lease lapses", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("leased", at(60_000))]);
await flush();
expect(service.isRevealed(userId, cipherId)).toBe(true);
await jest.advanceTimersByTimeAsync(60_000);
expect(service.isRevealed(userId, cipherId)).toBe(false);
expect(ids(await firstValueFrom(service.revealed$(userId)))).toEqual([]);
});
});
describe("get", () => {
it("returns the live view synchronously", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("leased")]);
await flush();
expect(service.get(userId, cipherId)?.id).toBe("leased");
expect(service.get(otherUserId, cipherId)).toBeUndefined();
});
});
describe("displayView$", () => {
it("returns a view that is not restricted as it is", async () => {
const stored = view("leased");
expect(await firstValueFrom(service.displayView$(userId, stored))).toBe(stored);
});
it("swaps in the revealed view of a restricted cipher, and the stored view without one", async () => {
const stored = view("leased", true);
const emissions: CipherView[] = [];
const subscription = service
.displayView$(userId, stored)
.subscribe((shown) => emissions.push(shown));
await seedLeases(stateProvider, userId, [leaseEntry("leased", at(60_000))]);
await flush();
await jest.advanceTimersByTimeAsync(60_000);
subscription.unsubscribe();
expect(emissions.map((shown) => shown.partial)).toEqual([true, false, true]);
expect(emissions[2]).toBe(stored);
});
});
describe("getOrReveal", () => {
it("returns the live view without asking the background", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("leased")]);
await flush();
const revealed = await service.getOrReveal(userId, cipherId);
expect(revealed?.id).toBe("leased");
expect(messageSender.send).not.toHaveBeenCalled();
});
it("asks the background for the cipher and returns its copy once written", async () => {
messageSender.send.mockImplementation(() => {
void seedLeases(stateProvider, userId, [leaseEntry("leased")], NOW);
});
const revealed = await service.getOrReveal(userId, cipherId);
expect(messageSender.send).toHaveBeenCalledWith(PAM_REFRESH_LEASES, { userId, cipherId });
expect(revealed?.id).toBe("leased");
});
it("returns null when the background writes no copy for the cipher", async () => {
messageSender.send.mockImplementation(() => {
void seedLeases(stateProvider, userId, [], NOW);
});
expect(await service.getOrReveal(userId, cipherId)).toBeNull();
});
it("returns null when the background does not answer in time", async () => {
const revealed = service.getOrReveal(userId, cipherId);
await jest.advanceTimersByTimeAsync(10_000);
expect(await revealed).toBeNull();
});
});
describe("refresh", () => {
it("asks the background to re-fetch the cipher and waits for the write", async () => {
let written = false;
messageSender.send.mockImplementation(() => {
void seedLeases(stateProvider, userId, [leaseEntry("leased")], NOW).then(
() => (written = true),
);
});
await service.refresh(userId, cipherId);
expect(messageSender.send).toHaveBeenCalledWith(PAM_REFRESH_LEASES, { userId, cipherId });
expect(written).toBe(true);
});
});
});

View File

@@ -0,0 +1,183 @@
import {
BehaviorSubject,
combineLatest,
concatMap,
defaultIfEmpty,
distinctUntilChanged,
filter,
firstValueFrom,
map,
Observable,
of,
switchMap,
timeout,
} from "rxjs";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { MessageSender } from "@bitwarden/common/platform/messaging";
import { StateProvider } from "@bitwarden/common/platform/state";
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 { RestrictedCipherPolicy } from "@bitwarden/common/vault/utils/restricted-cipher-policy";
import { PAM_REFRESH_LEASES } from "./lease-messages";
import {
LEASED_CIPHERS,
LeasedCipherEntry,
liveLeasedCiphers,
liveLeases$,
} from "./leased-cipher.state";
/** How long a reveal waits for the background to write the user's leases. */
const REFRESH_WAIT_MS = 10_000;
/** A revealed view and the end of its lease, in ms. */
type Entry = { view: CipherView; endsAt: number };
/**
* Serves the leased copies that the background's `PamLeaseRefreshService` keeps in session memory
* state. Each process decrypts them into its own memory. The worker and the popup each run one.
*/
export class BrowserRevealedCipherService implements RevealedCipherService {
private readonly entries$ = new BehaviorSubject<
ReadonlyMap<UserId, ReadonlyMap<CipherId, Entry>>
>(new Map());
constructor(
private readonly stateProvider: StateProvider,
authService: AuthService,
private readonly cipherService: CipherService,
private readonly messageSender: MessageSender,
private readonly logService: LogService,
) {
// A root singleton, so the subscription never ends. A user who leaves Unlocked drops out here,
// which clears that user's views in this process; `clearOn` clears the shared copies.
authService.authStatuses$
.pipe(
map(unlockedUserIds),
distinctUntilChanged((a, b) => a.join() === b.join()),
switchMap((userIds) =>
combineLatest(
userIds.map((userId) =>
liveLeases$(this.stateProvider, userId).pipe(
concatMap(async (live) => [userId, await this.decryptAll(userId, live)] as const),
),
),
).pipe(defaultIfEmpty([])),
),
)
.subscribe((pairs) => this.entries$.next(new Map(pairs)));
}
revealed$(userId: UserId): Observable<ReadonlyMap<CipherId, CipherView>> {
return this.entries$.pipe(
map((all) => {
const nowMs = Date.now();
const views = new Map<CipherId, CipherView>();
all.get(userId)?.forEach((entry, cipherId) => {
if (entry.endsAt > nowMs) {
views.set(cipherId, entry.view);
}
});
return views;
}),
distinctUntilChanged(
(a, b) => a.size === b.size && [...a].every(([id, view]) => b.get(id) === view),
),
);
}
isRevealed(userId: UserId, cipherId: CipherId): boolean {
return this.get(userId, cipherId) != null;
}
get(userId: UserId, cipherId: CipherId): CipherView | undefined {
const entry = this.entries$.value.get(userId)?.get(cipherId);
return entry != null && entry.endsAt > Date.now() ? entry.view : undefined;
}
async getOrReveal(userId: UserId, cipherId: CipherId): Promise<CipherView | null> {
const live = this.get(userId, cipherId);
if (live != null) {
return live;
}
await this.requestRefresh(userId, cipherId);
return this.readView(userId, cipherId);
}
async refresh(userId: UserId, cipherId: CipherId): Promise<void> {
await this.requestRefresh(userId, cipherId);
}
displayView$(userId: UserId, storedView: CipherView): Observable<CipherView> {
if (!RestrictedCipherPolicy.isRestricted(storedView)) {
return of(storedView);
}
return this.revealed$(userId).pipe(
map((revealed) => revealed.get(storedView.id as CipherId) ?? storedView),
distinctUntilChanged(),
);
}
/** Asks the background to re-read the leases, then waits for its write or gives up. */
private async requestRefresh(userId: UserId, cipherId: CipherId): Promise<void> {
const sentAt = Date.now();
const written = firstValueFrom(
this.stateProvider.getUser(userId, LEASED_CIPHERS).state$.pipe(
filter((state) => (state?.refreshedAt ?? 0) >= sentAt),
timeout({ first: REFRESH_WAIT_MS, with: () => of(null) }),
),
);
this.messageSender.send(PAM_REFRESH_LEASES, { userId, cipherId });
await written;
}
/** Reads the copy from state, since the decrypted entries can lag the write by a tick. */
private async readView(userId: UserId, cipherId: CipherId): Promise<CipherView | null> {
const state = await firstValueFrom(this.stateProvider.getUser(userId, LEASED_CIPHERS).state$);
const entry = liveLeasedCiphers(state?.leases, Date.now())[cipherId];
return entry == null ? null : ((await this.decrypt(userId, cipherId, entry))?.view ?? null);
}
private async decryptAll(
userId: UserId,
live: Record<string, LeasedCipherEntry>,
): Promise<ReadonlyMap<CipherId, Entry>> {
const entries = await Promise.all(
Object.entries(live).map(async ([cipherId, entry]) => {
const decrypted = await this.decrypt(userId, cipherId as CipherId, entry);
return decrypted == null ? null : ([cipherId as CipherId, decrypted] as const);
}),
);
return new Map(entries.filter((entry) => entry != null));
}
/** Only a full view of the requested cipher; anything else is dropped. */
private async decrypt(
userId: UserId,
cipherId: CipherId,
entry: LeasedCipherEntry,
): Promise<Entry | null> {
try {
const view = await this.cipherService.decrypt(new Cipher(entry.cipher), userId);
if (view?.id !== cipherId || view.partial !== false) {
return null;
}
return { view, endsAt: Date.parse(entry.notAfter) };
} catch (error) {
this.logService.error(`[PAM] Failed to decrypt a leased cipher: ${error}`);
return null;
}
}
}
function unlockedUserIds(statuses: Record<UserId, AuthenticationStatus>): UserId[] {
return (Object.keys(statuses ?? {}) as UserId[])
.filter((userId) => statuses[userId] === AuthenticationStatus.Unlocked)
.sort();
}

View File

@@ -0,0 +1,24 @@
import { firstValueFrom } from "rxjs";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getOptionalUserId } from "@bitwarden/common/auth/services/account.service";
import { CommandDefinition, MessageSender } from "@bitwarden/common/platform/messaging";
import { CipherId, UserId } from "@bitwarden/common/types/guid";
/**
* Asks the background to re-read the user's leases, since the popup receives no pushes. With
* `cipherId`, it also re-fetches that cipher's copy (after a save) or fetches it if it is new.
*/
export const PAM_REFRESH_LEASES = new CommandDefinition<{ userId: UserId; cipherId?: CipherId }>(
"pamRefreshLeases",
);
export async function requestLeaseRefresh(
accountService: AccountService,
messageSender: MessageSender,
): Promise<void> {
const userId = await firstValueFrom(accountService.activeAccount$.pipe(getOptionalUserId));
if (userId != null) {
messageSender.send(PAM_REFRESH_LEASES, { userId });
}
}

View File

@@ -0,0 +1,30 @@
import { StateProvider } from "@bitwarden/common/platform/state";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data";
import { LEASED_CIPHERS, LeasedCipherEntry } from "./leased-cipher.state";
export const NOW = new Date("2026-10-15T12:00:00.000Z").getTime();
/** ISO timestamp `offsetMs` from {@link NOW}. */
export const at = (offsetMs: number) => new Date(NOW + offsetMs).toISOString();
export const IN_AN_HOUR = at(60 * 60 * 1000);
export const leaseEntry = (cipherId: string, notAfter = IN_AN_HOUR): LeasedCipherEntry => ({
leaseId: `lease-${cipherId}`,
notAfter,
cipher: Object.assign(new CipherData(), { id: cipherId }),
});
export const seedLeases = (
stateProvider: StateProvider,
userId: UserId,
entries: LeasedCipherEntry[],
refreshedAt = NOW,
) =>
stateProvider.setUserState(
LEASED_CIPHERS,
{ refreshedAt, leases: Object.fromEntries(entries.map((e) => [e.cipher.id, e])) },
userId,
);

View File

@@ -0,0 +1,81 @@
import { firstValueFrom } from "rxjs";
import { FakeStateProvider, mockAccountServiceWith } from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { LEASED_CIPHERS, liveLeases$ } from "./leased-cipher.state";
import { at, leaseEntry, NOW, seedLeases } from "./leased-cipher.state.spec-util";
describe("LEASED_CIPHERS", () => {
it("lives in session memory state, never in large-object or disk storage", () => {
const definition = LEASED_CIPHERS.stateDefinition;
expect(definition.defaultStorageLocation).toBe("memory");
expect(definition.storageLocationOverrides).toEqual({});
});
it("clears on lock and logout", () => {
expect(LEASED_CIPHERS.clearOn).toEqual(["lock", "logout"]);
});
});
describe("liveLeases$", () => {
const userId = "user-id" as UserId;
let stateProvider: FakeStateProvider;
beforeEach(() => {
jest.useFakeTimers({ now: NOW });
stateProvider = new FakeStateProvider(mockAccountServiceWith(userId));
});
afterEach(() => {
jest.useRealTimers();
});
it("emits only copies whose lease is still live", async () => {
await seedLeases(stateProvider, userId, [
leaseEntry("live", at(60_000)),
leaseEntry("lapsed", at(-1)),
leaseEntry("garbled", "not-a-date"),
]);
const live = await firstValueFrom(liveLeases$(stateProvider, userId));
expect(Object.keys(live)).toEqual(["live"]);
});
it("emits no copies when there is no state", async () => {
const live = await firstValueFrom(liveLeases$(stateProvider, userId));
expect(live).toEqual({});
});
it("re-emits without the copy once its lease lapses", async () => {
await seedLeases(stateProvider, userId, [
leaseEntry("first", at(60_000)),
leaseEntry("second", at(120_000)),
]);
const emissions: string[][] = [];
const subscription = liveLeases$(stateProvider, userId).subscribe((live) =>
emissions.push(Object.keys(live)),
);
jest.advanceTimersByTime(60_000);
jest.advanceTimersByTime(60_000);
subscription.unsubscribe();
expect(emissions).toEqual([["first", "second"], ["second"], []]);
});
it("does not re-emit for a refresh that changes no copy", async () => {
await seedLeases(stateProvider, userId, [leaseEntry("live", at(60_000))]);
let emissions = 0;
const subscription = liveLeases$(stateProvider, userId).subscribe(() => emissions++);
await seedLeases(stateProvider, userId, [leaseEntry("live", at(60_000))], NOW + 1);
subscription.unsubscribe();
expect(emissions).toBe(1);
});
});

View File

@@ -0,0 +1,98 @@
import { concat, defer, distinctUntilChanged, Observable, of, switchMap, timer } from "rxjs";
import { Jsonify } from "type-fest";
import { isLeaseLive } from "@bitwarden/bit-pam";
import {
PAM_LEASED_CIPHERS_MEMORY,
StateProvider,
UserKeyDefinition,
} from "@bitwarden/common/platform/state";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data";
export type LeasedCipherEntry = {
leaseId: string;
/** ISO timestamp the lease ends. */
notAfter: string;
/** Encrypted full copy. */
cipher: CipherData;
};
export type LeasedCipherState = {
refreshedAt: number;
/** Keyed by cipher id. */
leases: Record<string, LeasedCipherEntry>;
};
/** RAM-only: "memory" is `chrome.storage.session` on MV3, shared by the worker and the popup. */
export const LEASED_CIPHERS = new UserKeyDefinition<LeasedCipherState>(
PAM_LEASED_CIPHERS_MEMORY,
"leasedCiphers",
{
deserializer: (obj: Jsonify<LeasedCipherState>) => {
if (obj?.leases == null) {
return null;
}
const leases: Record<string, LeasedCipherEntry> = {};
for (const [cipherId, entry] of Object.entries(obj.leases)) {
if (entry?.cipher != null) {
leases[cipherId] = { ...entry, cipher: CipherData.fromJSON(entry.cipher) };
}
}
return { refreshedAt: obj.refreshedAt, leases };
},
clearOn: ["lock", "logout"],
},
);
/** Longer timer delays overflow and fire at once. */
const MAX_TIMER_MS = 2 ** 31 - 1;
type LeasedCiphers = Record<string, LeasedCipherEntry>;
export function liveLeasedCiphers(leases: LeasedCiphers | undefined, nowMs: number): LeasedCiphers {
return Object.fromEntries(
Object.entries(leases ?? {}).filter(([, entry]) => isLeaseLive(entry, nowMs)),
);
}
/**
* The user's live copies. Re-emits as each lease lapses, since natural expiry sends no push, but
* not for a rewrite that changes no copy.
*/
export function liveLeases$(
stateProvider: StateProvider,
userId: UserId,
): Observable<LeasedCiphers> {
return stateProvider.getUser(userId, LEASED_CIPHERS).state$.pipe(
switchMap((state) => liveUntilEachLapse$(state?.leases)),
distinctUntilChanged(sameEntries),
);
}
function liveUntilEachLapse$(leases: LeasedCiphers | undefined): Observable<LeasedCiphers> {
return defer(() => {
const now = Date.now();
const live = liveLeasedCiphers(leases, now);
const ends = Object.values(live).map((entry) => Date.parse(entry.notAfter));
if (ends.length === 0) {
return of(live);
}
const delay = Math.min(Math.min(...ends) - now, MAX_TIMER_MS);
return concat(of(live), timer(delay).pipe(switchMap(() => liveUntilEachLapse$(leases))));
});
}
function sameEntries(a: LeasedCiphers, b: LeasedCiphers): boolean {
const ids = Object.keys(a);
return (
ids.length === Object.keys(b).length &&
ids.every(
(id) =>
b[id] != null &&
a[id].leaseId === b[id].leaseId &&
a[id].notAfter === b[id].notAfter &&
a[id].cipher.revisionDate === b[id].cipher.revisionDate,
)
);
}

View File

@@ -0,0 +1,298 @@
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject, firstValueFrom, Observable, Subject, take, toArray } from "rxjs";
import { CipherUse } from "@bitwarden/browser/autofill/services/abstractions/fill-cipher-policy";
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 { CipherType } from "@bitwarden/common/vault/enums";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { PamFillCipherPolicy } from "./pam-fill-cipher-policy";
describe("PamFillCipherPolicy", () => {
const userId = "user-id" as UserId;
const url = "https://example.com";
let cipherService: MockProxy<CipherService>;
let revealed$: BehaviorSubject<ReadonlyMap<CipherId, CipherView>>;
let policy: PamFillCipherPolicy;
const view = (id: string, revisionDate = new Date(0)) =>
Object.assign(new CipherView(), { id, revisionDate });
const reveal = (...views: CipherView[]) =>
revealed$.next(new Map(views.map((v) => [v.id as CipherId, v])));
const otherUses = Object.values(CipherUse).filter((use) => use !== CipherUse.UserFill);
beforeEach(() => {
cipherService = mock<CipherService>();
cipherService.getAllDecrypted.mockResolvedValue([view("stored")]);
cipherService.getAllDecryptedForUrl.mockResolvedValue([view("stored")]);
cipherService.filterCiphersForUrl.mockImplementation(async (ciphers) =>
ciphers.filter((c) => c.id !== "other-site"),
);
cipherService.sortCiphersByLastUsed.mockReturnValue(0);
revealed$ = new BehaviorSubject<ReadonlyMap<CipherId, CipherView>>(new Map());
const revealedCipherService = mock<RevealedCipherService>();
revealedCipherService.revealed$.mockReturnValue(revealed$);
policy = new PamFillCipherPolicy(cipherService, revealedCipherService);
});
describe("changed$", () => {
it("emits for decrypted stored cipher changes and revealed view changes", async () => {
const cipherViews$ = new Subject<CipherView[] | null>();
cipherService.cipherViews$.mockReturnValue(cipherViews$ as Observable<CipherView[]>);
const emitted = firstValueFrom(policy.changed$(userId).pipe(take(3), toArray()));
cipherViews$.next(null);
cipherViews$.next([view("stored")]);
reveal(view("revealed"));
expect(await emitted).toEqual([undefined, undefined, undefined]);
});
});
describe("ciphers", () => {
it("appends the revealed views to the stored ciphers for a user fill", async () => {
reveal(view("revealed"));
const ciphers = await policy.ciphers(userId, CipherUse.UserFill);
expect(ciphers.map((c) => c.id)).toEqual(["stored", "revealed"]);
});
it("keeps the stored copy over an old revealed view of the same cipher", async () => {
const stored = view("stored");
cipherService.getAllDecrypted.mockResolvedValue([stored]);
reveal(view("stored"));
const ciphers = await policy.ciphers(userId, CipherUse.UserFill);
expect(ciphers).toEqual([stored]);
expect(ciphers[0]).toBe(stored);
});
it.each(otherUses)("returns only the stored ciphers for %s", async (use) => {
reveal(view("revealed"));
const ciphers = await policy.ciphers(userId, use);
expect(ciphers.map((c) => c.id)).toEqual(["stored"]);
});
});
describe("ciphersForUrl", () => {
it("appends only the revealed views that match the URL for a user fill", async () => {
reveal(view("revealed"), view("other-site"));
const ciphers = await policy.ciphersForUrl(url, userId, CipherUse.UserFill, {
includeOtherTypes: [CipherType.Card],
});
expect(ciphers.map((c) => c.id)).toEqual(["stored", "revealed"]);
expect(cipherService.getAllDecryptedForUrl).toHaveBeenCalledWith(
url,
userId,
[CipherType.Card],
undefined,
);
expect(cipherService.filterCiphersForUrl).toHaveBeenCalledWith(
expect.any(Array),
url,
[CipherType.Card],
undefined,
);
});
it("returns the stored lookup as it is without revealed views", async () => {
const ciphers = await policy.ciphersForUrl(url, userId, CipherUse.UserFill);
expect(ciphers.map((c) => c.id)).toEqual(["stored"]);
expect(cipherService.filterCiphersForUrl).not.toHaveBeenCalled();
});
it.each(otherUses)("returns only the stored ciphers for %s", async (use) => {
reveal(view("revealed"));
const ciphers = await policy.ciphersForUrl(url, userId, use);
expect(ciphers.map((c) => c.id)).toEqual(["stored"]);
expect(cipherService.filterCiphersForUrl).not.toHaveBeenCalled();
});
});
describe("lastLaunchedForUrl and lastUsedForUrl", () => {
it("return the stored cipher, not a revealed view", async () => {
reveal(view("revealed"));
const stored = view("stored");
cipherService.getLastLaunchedForUrl.mockResolvedValue(stored);
cipherService.getLastUsedForUrl.mockResolvedValue(stored);
expect(await policy.lastLaunchedForUrl(url, userId, true)).toBe(stored);
expect(await policy.lastUsedForUrl(url, userId, true)).toBe(stored);
});
});
describe("nextCipherForUrl", () => {
it("uses the CipherService rotation without revealed views", async () => {
const next = view("next");
cipherService.getNextCipherForUrl.mockResolvedValue(next);
expect(await policy.nextCipherForUrl(url, userId)).toBe(next);
expect(cipherService.getAllDecryptedForUrl).not.toHaveBeenCalled();
});
it("rotates through the stored ciphers and the revealed views", async () => {
reveal(view("revealed"));
const picked: string[] = [];
for (let i = 0; i < 3; i++) {
picked.push((await policy.nextCipherForUrl(url, userId))!.id);
policy.advanceRotation(url);
}
expect(picked).toEqual(["stored", "revealed", "stored"]);
expect(cipherService.getNextCipherForUrl).not.toHaveBeenCalled();
expect(cipherService.updateLastUsedIndexForUrl).toHaveBeenCalledWith(url);
});
it("restarts the rotation when a revealed view ends", async () => {
reveal(view("revealed"), view("second"));
await policy.nextCipherForUrl(url, userId);
policy.advanceRotation(url);
reveal(view("second"));
const next = await policy.nextCipherForUrl(url, userId);
expect(next?.id).toBe("stored");
});
it("returns undefined when nothing matches the URL", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([]);
reveal(view("other-site"));
expect(await policy.nextCipherForUrl(url, userId)).toBeUndefined();
});
});
describe("nextCardCipher and nextIdentityCipher", () => {
const typed = (id: string, type: CipherType, fields: Partial<CipherView> = {}) =>
Object.assign(view(id), { type }, fields);
beforeEach(() => {
cipherService.getAllDecrypted.mockResolvedValue([
typed("stored-card", CipherType.Card),
typed("stored-identity", CipherType.Identity),
typed("stored-login", CipherType.Login),
]);
});
it("uses the CipherService rotation without revealed views", async () => {
const card = typed("next-card", CipherType.Card);
const identity = typed("next-identity", CipherType.Identity);
cipherService.getNextCardCipher.mockResolvedValue(card);
cipherService.getNextIdentityCipher.mockResolvedValue(identity);
expect(await policy.nextCardCipher(userId)).toBe(card);
expect(await policy.nextIdentityCipher(userId)).toBe(identity);
expect(cipherService.getAllDecrypted).not.toHaveBeenCalled();
});
it("rotates through the stored cards and the revealed cards", async () => {
reveal(typed("revealed-card", CipherType.Card));
const picked: string[] = [];
for (let i = 0; i < 3; i++) {
picked.push((await policy.nextCardCipher(userId))!.id);
policy.advanceRotation("cardCiphers");
}
expect(picked).toEqual(["stored-card", "revealed-card", "stored-card"]);
expect(cipherService.getNextCardCipher).not.toHaveBeenCalled();
});
it("rotates through the stored identities and the revealed identities", async () => {
reveal(typed("revealed-identity", CipherType.Identity));
const picked: string[] = [];
for (let i = 0; i < 3; i++) {
picked.push((await policy.nextIdentityCipher(userId))!.id);
policy.advanceRotation("identityCiphers");
}
expect(picked).toEqual(["stored-identity", "revealed-identity", "stored-identity"]);
expect(cipherService.getNextIdentityCipher).not.toHaveBeenCalled();
});
it("leaves out other types and deleted or archived cards", async () => {
reveal(
typed("revealed-login", CipherType.Login),
typed("deleted-card", CipherType.Card, { deletedDate: new Date() }),
typed("archived-card", CipherType.Card, { archivedDate: new Date() }),
);
const picked: string[] = [];
for (let i = 0; i < 2; i++) {
picked.push((await policy.nextCardCipher(userId))!.id);
policy.advanceRotation("cardCiphers");
}
expect(picked).toEqual(["stored-card", "stored-card"]);
});
it("restarts the rotation when a revealed card ends", async () => {
reveal(typed("revealed-card", CipherType.Card), typed("second", CipherType.Login));
await policy.nextCardCipher(userId);
policy.advanceRotation("cardCiphers");
reveal(typed("second", CipherType.Login));
const next = await policy.nextCardCipher(userId);
expect(next?.id).toBe("stored-card");
});
it("returns undefined when no card is available", async () => {
cipherService.getAllDecrypted.mockResolvedValue([]);
reveal(typed("revealed-login", CipherType.Login));
expect(await policy.nextCardCipher(userId)).toBeUndefined();
});
});
describe("canOfferSave", () => {
beforeEach(() => {
reveal(
Object.assign(view("revealed"), {
login: { username: "Admin", password: "revealed" },
}),
);
cipherService.filterCiphersForUrl.mockImplementation(async (ciphers, ciphersUrl) =>
ciphersUrl === url ? ciphers : [],
);
});
it.each([
[false, "the revealed username, in any case", { username: "ADMIN", password: "other" }],
[false, "a password-only form", { username: "", password: "revealed" }],
[
false,
"a change-password form with no username",
{ password: "old", newPassword: "revealed" },
],
[true, "another username and password", { username: "other", password: "other" }],
[true, "another site", { username: "Admin", password: "revealed", uri: "https://other.com" }],
])("is %s for %s", async (expected, _, form) => {
const data = { uri: url, username: "", ...form };
expect(await policy.canOfferSave(data, userId)).toBe(expected);
});
it("is true without revealed views", async () => {
reveal();
expect(await policy.canOfferSave({ uri: url, username: "Admin" }, userId)).toBe(true);
});
});
});

View File

@@ -0,0 +1,162 @@
import { firstValueFrom, map, merge, Observable } from "rxjs";
import {
CipherUse,
SaveCandidate,
} from "@bitwarden/browser/autofill/services/abstractions/fill-cipher-policy";
import { DefaultFillCipherPolicy } from "@bitwarden/browser/autofill/services/default-fill-cipher-policy";
import { UriMatchStrategySetting } from "@bitwarden/common/models/domain/domain-service";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { SortedCiphersCache } from "@bitwarden/common/vault/models/domain/sorted-ciphers-cache";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
/**
* Adds the revealed views (see {@link RevealedCipherService}) to user fills only. Every other use
* gets the stored ciphers. Blocks a save prompt for a form that holds a revealed login.
*/
export class PamFillCipherPolicy extends DefaultFillCipherPolicy {
/** The keyboard shortcut rotations, used only while the user has revealed views. */
private readonly sortedCiphersCache: SortedCiphersCache;
/** The ciphers each cached URL or type key was built from, so a change rebuilds the rotation. */
private readonly cachedSignatures = new Map<string, string>();
constructor(
cipherService: CipherService,
private readonly revealedCipherService: RevealedCipherService,
) {
super(cipherService);
this.sortedCiphersCache = new SortedCiphersCache((a, b) =>
this.cipherService.sortCiphersByLastUsed(a, b),
);
}
override changed$(userId: UserId): Observable<void> {
return merge(
super.changed$(userId),
this.revealedCipherService.revealed$(userId).pipe(map((): void => undefined)),
);
}
override async ciphers(userId: UserId, use: CipherUse): Promise<CipherView[]> {
if (use !== CipherUse.UserFill) {
return super.ciphers(userId, use);
}
const [ciphers, revealed] = await Promise.all([
super.ciphers(userId, use),
this.getRevealed(userId),
]);
return withRevealed(ciphers, revealed);
}
override async ciphersForUrl(
url: string,
userId: UserId,
use: CipherUse,
options?: { includeOtherTypes?: CipherType[]; defaultMatch?: UriMatchStrategySetting },
): Promise<CipherView[]> {
if (use !== CipherUse.UserFill) {
return super.ciphersForUrl(url, userId, use, options);
}
const [ciphers, revealed] = await Promise.all([
super.ciphersForUrl(url, userId, use, options),
this.getRevealed(userId),
]);
if (revealed.length === 0) {
return ciphers;
}
const matching = await this.cipherService.filterCiphersForUrl(
revealed,
url,
options?.includeOtherTypes,
options?.defaultMatch,
);
return withRevealed(ciphers, matching);
}
override async nextCipherForUrl(url: string, userId: UserId): Promise<CipherView | undefined> {
if ((await this.getRevealed(userId)).length === 0) {
return super.nextCipherForUrl(url, userId);
}
return this.nextInRotation(url, await this.ciphersForUrl(url, userId, CipherUse.UserFill));
}
override async nextCardCipher(userId: UserId): Promise<CipherView | undefined> {
if ((await this.getRevealed(userId)).length === 0) {
return super.nextCardCipher(userId);
}
return this.nextOfType(userId, CipherType.Card, "cardCiphers");
}
override async nextIdentityCipher(userId: UserId): Promise<CipherView | undefined> {
if ((await this.getRevealed(userId)).length === 0) {
return super.nextIdentityCipher(userId);
}
return this.nextOfType(userId, CipherType.Identity, "identityCiphers");
}
/** Advances both the stored and the revealed rotation. */
override advanceRotation(url: string): void {
super.advanceRotation(url);
this.sortedCiphersCache.updateLastUsedIndex(url);
}
/** False when the username, password, or new password of the form is a revealed login for its URL. */
override async canOfferSave(form: SaveCandidate, userId: UserId): Promise<boolean> {
const username = form.username?.toLowerCase();
const passwords = [form.password, form.newPassword].filter((p) => !!p);
const matches = (await this.getRevealed(userId)).filter((c) => {
const usernameMatches = !!username && c.login?.username?.toLowerCase() === username;
const passwordMatches = !!c.login?.password && passwords.includes(c.login.password);
return usernameMatches || passwordMatches;
});
return (
matches.length === 0 ||
(await this.cipherService.filterCiphersForUrl(matches, form.uri)).length === 0
);
}
/** The next card or identity rotation entry, from the stored ciphers and the revealed views. */
private async nextOfType(
userId: UserId,
type: CipherType,
key: string,
): Promise<CipherView | undefined> {
const ciphers = (await this.ciphers(userId, CipherUse.UserFill)).filter(
(c) => c.type === type && c.deletedDate == null && !c.isArchived,
);
return this.nextInRotation(key, ciphers);
}
private nextInRotation(key: string, ciphers: CipherView[]): CipherView | undefined {
if (ciphers.length === 0) {
return undefined;
}
// A revealed view that ends, or a stored cipher that changes, rebuilds the rotation.
const signature = ciphers
.map((c) => `${c.id}:${c.partial}:${c.revisionDate?.getTime()}`)
.sort()
.join();
if (!this.sortedCiphersCache.isCached(key) || this.cachedSignatures.get(key) !== signature) {
this.sortedCiphersCache.addCiphers(key, ciphers);
this.cachedSignatures.set(key, signature);
}
return this.sortedCiphersCache.getNext(key) ?? undefined;
}
private async getRevealed(userId: UserId): Promise<CipherView[]> {
return [...(await firstValueFrom(this.revealedCipherService.revealed$(userId))).values()];
}
}
/**
* Appends the revealed views. The stored lookups exclude restricted ciphers, so a stored copy of
* the same ID is no longer restricted and wins over its old revealed view.
*/
function withRevealed(ciphers: CipherView[], revealed: CipherView[]): CipherView[] {
const ids = new Set(ciphers.map((cipher) => cipher.id));
return ciphers.concat(revealed.filter((view) => !ids.has(view.id)));
}

View File

@@ -0,0 +1,85 @@
import { Subscription } from "rxjs";
import {
FakeAccountService,
FakeStateProvider,
mockAccountServiceWith,
} from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { seedLeases } from "../leased-cipher.state.spec-util";
import { BrowserAccessEventService } from "./browser-access-event.service";
describe("BrowserAccessEventService", () => {
const userId = "user-id" as UserId;
const otherUserId = "other-user-id" as UserId;
let accountService: FakeAccountService;
let stateProvider: FakeStateProvider;
let service: BrowserAccessEventService;
let subscription: Subscription | undefined;
let ticks: number;
const refresh = (refreshedAt: number, forUserId = userId) =>
seedLeases(stateProvider, forUserId, [], refreshedAt);
const listen = () => {
subscription = service.accessChanged$().subscribe(() => ticks++);
};
beforeEach(() => {
ticks = 0;
accountService = mockAccountServiceWith(userId);
stateProvider = new FakeStateProvider(accountService);
service = new BrowserAccessEventService(stateProvider, accountService);
});
afterEach(() => {
subscription?.unsubscribe();
});
it("does not tick for the state stored when it subscribes", async () => {
await refresh(1);
listen();
expect(ticks).toBe(0);
});
it("ticks each time the background refreshes", async () => {
await refresh(1);
listen();
await refresh(2);
await refresh(3);
expect(ticks).toBe(2);
});
it("does not tick for a rewrite without a refresh", async () => {
await refresh(1);
listen();
await refresh(1);
expect(ticks).toBe(0);
});
it("ignores another user's refresh", async () => {
listen();
await refresh(2, otherUserId);
expect(ticks).toBe(0);
});
it("does not tick for the stored state of an account switched to", async () => {
await refresh(1, otherUserId);
listen();
await accountService.switchAccount(otherUserId);
expect(ticks).toBe(0);
await refresh(2, otherUserId);
expect(ticks).toBe(1);
});
});

View File

@@ -0,0 +1,44 @@
import { distinctUntilChanged, map, NEVER, Observable, share, skip, switchMap } from "rxjs";
import { AccessEventService } from "@bitwarden/bit-pam";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { getOptionalUserId } from "@bitwarden/common/auth/services/account.service";
import { StateProvider } from "@bitwarden/common/platform/state";
import { LEASED_CIPHERS } from "../leased-cipher.state";
/**
* The popup hears no pushes, so it ticks when the background rewrites the leased copies, which it
* does after every push, sync, and lease refresh.
*/
export class BrowserAccessEventService implements AccessEventService {
private readonly changed$: Observable<void>;
constructor(stateProvider: StateProvider, accountService: AccountService) {
this.changed$ = accountService.activeAccount$.pipe(
getOptionalUserId,
distinctUntilChanged(),
switchMap((userId) =>
userId == null
? NEVER
: stateProvider.getUser(userId, LEASED_CIPHERS).state$.pipe(
map((state) => state?.refreshedAt),
distinctUntilChanged(),
// The stored value on subscribe is not a change.
skip(1),
),
),
map((): void => undefined),
share(),
);
}
accessChanged$(): Observable<void> {
return this.changed$;
}
/** The popup has no approver surfaces. */
approverInboxChanged$(): Observable<void> {
return NEVER;
}
}

View File

@@ -0,0 +1,65 @@
import { mock, MockProxy } from "jest-mock-extended";
import { Subject } from "rxjs";
import { AccessEventService } from "@bitwarden/bit-pam";
import { MessageSender } from "@bitwarden/common/platform/messaging";
import { awaitAsync, FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { PAM_REFRESH_LEASES } from "../lease-messages";
import { BrowserAccessRefreshService } from "./browser-access-refresh.service";
describe("BrowserAccessRefreshService", () => {
const userId = "user-id" as UserId;
let accountService: FakeAccountService;
let messageSender: MockProxy<MessageSender>;
let accessEvents$: Subject<void>;
let service: BrowserAccessRefreshService;
beforeEach(() => {
accountService = mockAccountServiceWith(userId);
messageSender = mock<MessageSender>();
accessEvents$ = new Subject<void>();
const accessEventService = mock<AccessEventService>();
accessEventService.accessChanged$.mockReturnValue(accessEvents$);
service = new BrowserAccessRefreshService(accessEventService, accountService, messageSender);
});
it("asks the background to refresh the active user's leases", async () => {
service.notifyAccessChanged("cipher-id");
await awaitAsync();
expect(messageSender.send).toHaveBeenCalledWith(PAM_REFRESH_LEASES, { userId });
});
it("still ticks the cipher's readers at once", () => {
let ticks = 0;
const subscription = service.accessChanged$("cipher-id").subscribe(() => ticks++);
service.notifyAccessChanged("cipher-id");
subscription.unsubscribe();
expect(ticks).toBe(1);
});
it("merges the popup's access events", () => {
let ticks = 0;
const subscription = service.accessChanged$("cipher-id").subscribe(() => ticks++);
accessEvents$.next();
subscription.unsubscribe();
expect(ticks).toBe(1);
});
it("sends nothing without an active account", async () => {
accountService.activeAccountSubject.next(null);
service.notifyAccessChanged("cipher-id");
await awaitAsync();
expect(messageSender.send).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,24 @@
import { AccessEventService, DefaultAccessRefreshService } from "@bitwarden/bit-pam";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { MessageSender } from "@bitwarden/common/platform/messaging";
import { requestLeaseRefresh } from "../lease-messages";
/**
* Also asks the background to re-read leases after a popup action, so it fetches or drops the
* leased copy the item view swaps in without waiting for the push.
*/
export class BrowserAccessRefreshService extends DefaultAccessRefreshService {
constructor(
accessEventService: AccessEventService,
private readonly accountService: AccountService,
private readonly messageSender: MessageSender,
) {
super(accessEventService);
}
override notifyAccessChanged(cipherId?: string): void {
super.notifyAccessChanged(cipherId);
void requestLeaseRefresh(this.accountService, this.messageSender);
}
}

View File

@@ -0,0 +1,31 @@
import { NgZone } from "@angular/core";
import { Observable } from "rxjs";
import { runInsideAngular } from "@bitwarden/browser/platform/browser/run-inside-angular.operator";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { MessageSender } from "@bitwarden/common/platform/messaging";
import { StateProvider } from "@bitwarden/common/platform/state";
import { CipherId, UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { BrowserRevealedCipherService } from "../browser-revealed-cipher.service";
/** Lease updates arrive as `chrome.storage` events outside the zone, so every reader re-enters it here. */
export class PopupRevealedCipherService extends BrowserRevealedCipherService {
constructor(
stateProvider: StateProvider,
authService: AuthService,
cipherService: CipherService,
messageSender: MessageSender,
logService: LogService,
private readonly ngZone: NgZone,
) {
super(stateProvider, authService, cipherService, messageSender, logService);
}
override revealed$(userId: UserId): Observable<ReadonlyMap<CipherId, CipherView>> {
return super.revealed$(userId).pipe(runInsideAngular(this.ngZone));
}
}

View File

@@ -0,0 +1,160 @@
import { APP_INITIALIZER, NgZone } from "@angular/core";
import {
AccessEventService,
AccessLeaseSdkService,
AccessRefreshService,
AccessRequestSdkService,
LeasingErrorService,
AccessLeasesSdkService,
AccessRequestsSdkService,
DefaultLeasingErrorService,
} from "@bitwarden/bit-pam";
import {
CipherViewBannerComponent,
ItemDetailsStateBadgeComponent,
AccessRequestCancelService,
controlledAccessItemFilter,
ControlledAccessVaultFilterService,
MyLeasesService,
CIPHER_VIEW_BANNER_LAYOUT,
} from "@bitwarden/bit-pam-components";
import { FillCipherPolicy } from "@bitwarden/browser/autofill/services/abstractions/fill-cipher-policy";
import { VAULT_ROW_ICON } from "@bitwarden/browser/vault/popup/components/vault/vault-row-slots/vault-row-icon.token";
import { VAULT_ROW_SUBTITLE } from "@bitwarden/browser/vault/popup/components/vault/vault-row-slots/vault-row-subtitle.token";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service";
import { MessageSender } from "@bitwarden/common/platform/messaging";
import { StateProvider } from "@bitwarden/common/platform/state";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
import { DialogService, ToastService } from "@bitwarden/components";
import { SafeInjectionToken, SafeProvider, safeProvider } from "@bitwarden/ui-common";
import {
CIPHER_VIEW_BANNER,
ITEM_DETAILS_BADGE,
VAULT_ITEM_FILTER,
VAULT_ROW_ACTIONS,
} from "@bitwarden/vault";
import { requestLeaseRefresh } from "../lease-messages";
import { PamFillCipherPolicy } from "../pam-fill-cipher-policy";
import { BrowserAccessEventService } from "./browser-access-event.service";
import { BrowserAccessRefreshService } from "./browser-access-refresh.service";
import { PopupRevealedCipherService } from "./popup-revealed-cipher.service";
import { BrowserVaultRowAccessService } from "./vault-row-access/browser-vault-row-access.service";
import { VaultRowAccessIconComponent } from "./vault-row-access/vault-row-access-icon.component";
/** PAM providers for the commercial popup. */
export function providePam(): SafeProvider[] {
return [
safeProvider({
provide: RevealedCipherService,
useClass: PopupRevealedCipherService,
deps: [StateProvider, AuthService, CipherService, MessageSender, LogService, NgZone],
}),
safeProvider({
provide: FillCipherPolicy,
useClass: PamFillCipherPolicy,
deps: [CipherService, RevealedCipherService],
}),
safeProvider({
// The popup receives no pushes, so it asks the background to re-read on open.
provide: APP_INITIALIZER as SafeInjectionToken<() => Promise<void>>,
useFactory: (accountService: AccountService, messageSender: MessageSender) => () =>
requestLeaseRefresh(accountService, messageSender),
deps: [AccountService, MessageSender],
multi: true,
}),
safeProvider({
provide: AccessRequestSdkService,
useClass: AccessRequestsSdkService,
deps: [SdkService, AccountService, LogService],
}),
safeProvider({
provide: AccessLeaseSdkService,
useClass: AccessLeasesSdkService,
deps: [SdkService, AccountService, LogService],
}),
safeProvider({
provide: LeasingErrorService,
useClass: DefaultLeasingErrorService,
deps: [],
}),
// Only the banner reads it; `RevealedCipherService` stays on the background's leased copies.
safeProvider({
provide: MyLeasesService,
useClass: MyLeasesService,
deps: [AccessLeaseSdkService, LogService],
}),
safeProvider({
provide: AccessEventService,
useClass: BrowserAccessEventService,
deps: [StateProvider, AccountService],
}),
safeProvider({
provide: AccessRefreshService,
useClass: BrowserAccessRefreshService,
deps: [AccessEventService, AccountService, MessageSender],
}),
safeProvider({
provide: AccessRequestCancelService,
useClass: AccessRequestCancelService,
deps: [
AccessRequestSdkService,
AccessRefreshService,
DialogService,
ToastService,
I18nService,
LogService,
],
}),
safeProvider({
provide: CIPHER_VIEW_BANNER,
useValue: CipherViewBannerComponent,
}),
safeProvider({
provide: ITEM_DETAILS_BADGE,
useValue: ItemDetailsStateBadgeComponent,
}),
// The popup's item view has no room to fold the request form out in place.
safeProvider({
provide: CIPHER_VIEW_BANNER_LAYOUT,
useValue: "popup",
}),
// One per-row state read per list, shared by every option's count and the selection.
safeProvider({
provide: ControlledAccessVaultFilterService,
useClass: ControlledAccessVaultFilterService,
deps: [],
}),
safeProvider({
provide: VAULT_ITEM_FILTER,
useFactory: controlledAccessItemFilter,
deps: [I18nService, ControlledAccessVaultFilterService],
}),
// One instance behind the row's icon, subtitle and menu, so all three read the same statuses.
safeProvider({
provide: BrowserVaultRowAccessService,
useClass: BrowserVaultRowAccessService,
deps: [],
}),
safeProvider({
provide: VAULT_ROW_ICON,
useValue: VaultRowAccessIconComponent,
}),
safeProvider({
provide: VAULT_ROW_SUBTITLE,
useExisting: BrowserVaultRowAccessService,
}),
safeProvider({
provide: VAULT_ROW_ACTIONS,
useFactory: (rowAccess: BrowserVaultRowAccessService) => rowAccess.rowActions(),
deps: [BrowserVaultRowAccessService],
}),
];
}

View File

@@ -0,0 +1,122 @@
import { TestBed } from "@angular/core/testing";
import { BehaviorSubject, firstValueFrom, Subject } from "rxjs";
import { AccessRefreshService, AccessRequestSdkService } from "@bitwarden/bit-pam";
import type { CipherAccessStateView } from "@bitwarden/bit-pam";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { VaultRowAccessStateService } from "./vault-row-access-state.service";
function flushMicrotasks(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
describe("VaultRowAccessStateService", () => {
let service: VaultRowAccessStateService;
let accessRequestSdkService: {
getCipherAccessState: jest.Mock<Promise<CipherAccessStateView>, [string]>;
};
let accessChanged: Subject<void>;
let activeAccount$: BehaviorSubject<{ id: string } | null>;
beforeEach(() => {
accessRequestSdkService = { getCipherAccessState: jest.fn() };
accessChanged = new Subject<void>();
activeAccount$ = new BehaviorSubject<{ id: string } | null>({ id: "user-1" });
TestBed.configureTestingModule({
providers: [
{ provide: AccessRequestSdkService, useValue: accessRequestSdkService },
{ provide: AccountService, useValue: { activeAccount$ } },
{ provide: AccessRefreshService, useValue: { accessChanged$: () => accessChanged } },
],
});
service = TestBed.inject(VaultRowAccessStateService);
});
it("reads a cipher's access state once for two subscribers", async () => {
accessRequestSdkService.getCipherAccessState.mockResolvedValue({
badgeState: "privileged",
} as unknown as CipherAccessStateView);
const first = await firstValueFrom(service.state$("cipher-1"));
const second = await firstValueFrom(service.state$("cipher-1"));
expect(first).toEqual({ badgeState: "privileged" });
expect(second).toEqual({ badgeState: "privileged" });
expect(accessRequestSdkService.getCipherAccessState).toHaveBeenCalledTimes(1);
});
it("drops the cache on an account switch rather than replaying the previous account's state", async () => {
accessRequestSdkService.getCipherAccessState
.mockResolvedValueOnce({
badgeState: "active-for-user-1",
} as unknown as CipherAccessStateView)
.mockResolvedValueOnce({ badgeState: "privileged" } as unknown as CipherAccessStateView);
const first = await firstValueFrom(service.state$("cipher-1"));
activeAccount$.next({ id: "user-2" });
const second = await firstValueFrom(service.state$("cipher-1"));
expect(first).toEqual({ badgeState: "active-for-user-1" });
expect(second).toEqual({ badgeState: "privileged" });
expect(accessRequestSdkService.getCipherAccessState).toHaveBeenCalledTimes(2);
});
it("reads different ciphers separately", async () => {
accessRequestSdkService.getCipherAccessState.mockResolvedValue({
badgeState: "privileged",
} as unknown as CipherAccessStateView);
await firstValueFrom(service.state$("cipher-1"));
await firstValueFrom(service.state$("cipher-2"));
expect(accessRequestSdkService.getCipherAccessState).toHaveBeenCalledTimes(2);
expect(accessRequestSdkService.getCipherAccessState).toHaveBeenCalledWith("cipher-1");
expect(accessRequestSdkService.getCipherAccessState).toHaveBeenCalledWith("cipher-2");
});
it("re-reads a cipher after it is invalidated", async () => {
accessRequestSdkService.getCipherAccessState
.mockResolvedValueOnce({ badgeState: "privileged" } as unknown as CipherAccessStateView)
.mockResolvedValueOnce({ badgeState: "pending" } as unknown as CipherAccessStateView);
const values: (CipherAccessStateView | null)[] = [];
const subscription = service.state$("cipher-1").subscribe((value) => values.push(value));
await flushMicrotasks();
service.invalidate("cipher-1");
await flushMicrotasks();
subscription.unsubscribe();
expect(values).toEqual([{ badgeState: "privileged" }, { badgeState: "pending" }]);
expect(accessRequestSdkService.getCipherAccessState).toHaveBeenCalledTimes(2);
});
it("re-reads every cached cipher when access changes anywhere", async () => {
accessRequestSdkService.getCipherAccessState.mockResolvedValue({} as CipherAccessStateView);
const a = service.state$("a").subscribe();
const b = service.state$("b").subscribe();
await flushMicrotasks();
accessChanged.next();
await flushMicrotasks();
expect(accessRequestSdkService.getCipherAccessState).toHaveBeenCalledTimes(4);
a.unsubscribe();
b.unsubscribe();
});
it("resolves null when the read fails", async () => {
accessRequestSdkService.getCipherAccessState.mockRejectedValue(new Error("boom"));
expect(await firstValueFrom(service.state$("cipher-1"))).toBeNull();
});
it("invalidating an unread cipher does not read it", () => {
service.invalidate("cipher-1");
expect(accessRequestSdkService.getCipherAccessState).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,88 @@
import { Injectable, inject } from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import {
Observable,
Subject,
catchError,
distinctUntilChanged,
from,
map,
of,
shareReplay,
startWith,
switchMap,
} from "rxjs";
import {
AccessRefreshService,
AccessRequestSdkService,
type CipherAccessStateView,
} from "@bitwarden/bit-pam";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
/**
* One cached access-state read per gated cipher in the popup vault list, re-read on
* {@link invalidate}. The cache belongs to the active account: the popup document survives an
* account switch, so it is dropped on one rather than replaying the previous account's state.
*/
@Injectable({ providedIn: "root" })
export class VaultRowAccessStateService {
private readonly accessRequestSdkService = inject(AccessRequestSdkService);
constructor() {
inject(AccountService)
.activeAccount$.pipe(
map((account) => account?.id ?? null),
distinctUntilChanged(),
takeUntilDestroyed(),
)
.subscribe(() => this.reset());
inject(AccessRefreshService)
.accessChanged$()
.pipe(takeUntilDestroyed())
.subscribe(() => this.refresh.forEach((subject) => subject.next()));
}
private readonly refresh = new Map<string, Subject<void>>();
private readonly state = new Map<string, Observable<CipherAccessStateView | null>>();
/** `cipherId`'s access state, read once and replayed to every subscriber until {@link invalidate}. */
state$(cipherId: string): Observable<CipherAccessStateView | null> {
let state$ = this.state.get(cipherId);
if (state$ == null) {
state$ = this.refreshSubject(cipherId).pipe(
startWith(undefined),
switchMap(() =>
from(this.accessRequestSdkService.getCipherAccessState(cipherId)).pipe(
catchError(() => of(null)),
),
),
shareReplay({ bufferSize: 1, refCount: false }),
);
this.state.set(cipherId, state$);
}
return state$;
}
private reset(): void {
// Completing the triggers lets the old accounts' shared reads wind down.
this.refresh.forEach((subject) => subject.complete());
this.refresh.clear();
this.state.clear();
}
/** Forces the next read of `cipherId` to hit the SDK again. */
invalidate(cipherId: string): void {
this.refreshSubject(cipherId).next();
}
private refreshSubject(cipherId: string): Subject<void> {
let subject = this.refresh.get(cipherId);
if (subject == null) {
subject = new Subject<void>();
this.refresh.set(cipherId, subject);
}
return subject;
}
}

View File

@@ -0,0 +1,467 @@
import { TestBed } from "@angular/core/testing";
import { Router } from "@angular/router";
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject, firstValueFrom, of, Subject } from "rxjs";
import {
AccessLeaseSdkService,
AccessRefreshService,
AccessRequestSdkService,
} from "@bitwarden/bit-pam";
import {
AccessBadgeTickerService,
ExtendLeaseDialogComponent,
} from "@bitwarden/bit-pam-components";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
import { DialogService, ToastService } from "@bitwarden/components";
import { VaultRowAccessStateService } from "../vault-row-access-state/vault-row-access-state.service";
import { BrowserVaultRowAccessService } from "./browser-vault-row-access.service";
describe("BrowserVaultRowAccessService", () => {
let service: BrowserVaultRowAccessService;
let state$: BehaviorSubject<unknown>;
let rowState: MockProxy<VaultRowAccessStateService>;
let accessRequestSdk: MockProxy<AccessRequestSdkService>;
let accessLeaseSdk: MockProxy<AccessLeaseSdkService>;
let accessRefresh: MockProxy<AccessRefreshService>;
let dialogService: MockProxy<DialogService>;
let router: MockProxy<Router>;
let toastService: MockProxy<ToastService>;
let ticks$: Subject<number>;
let pamEnabled$: BehaviorSubject<boolean>;
let revealed$: BehaviorSubject<ReadonlyMap<string, unknown>>;
let account$: BehaviorSubject<{ id: string }>;
const gated = { id: "c1", name: "Amazon", partial: true } as unknown as CipherViewLike;
const normal = { id: "c2", name: "Plain" } as unknown as CipherViewLike;
const latest = () => firstValueFrom(service.status$(gated));
const activeState = (extensionsAllowed = false) => ({
badgeState: { active: { expiresAt: new Date(Date.now() + 8 * 3_600_000 - 500).toISOString() } },
extensionsAllowed,
});
beforeEach(() => {
state$ = new BehaviorSubject<unknown>({ badgeState: "privileged" });
rowState = mock<VaultRowAccessStateService>();
rowState.state$.mockReturnValue(state$ as any);
accessRequestSdk = mock<AccessRequestSdkService>();
accessLeaseSdk = mock<AccessLeaseSdkService>();
accessRefresh = mock<AccessRefreshService>();
dialogService = mock<DialogService>();
router = mock<Router>();
toastService = mock<ToastService>();
ticks$ = new Subject<number>();
pamEnabled$ = new BehaviorSubject(true);
revealed$ = new BehaviorSubject<ReadonlyMap<string, unknown>>(new Map());
account$ = new BehaviorSubject({ id: "u1" });
TestBed.configureTestingModule({
providers: [
BrowserVaultRowAccessService,
{ provide: ConfigService, useValue: { getFeatureFlag$: () => pamEnabled$ } },
{ provide: AccountService, useValue: { activeAccount$: account$ } },
{ provide: OrganizationService, useValue: { organizations$: () => of([]) } },
{ provide: DialogService, useValue: dialogService },
{ provide: Router, useValue: router },
{ provide: VaultRowAccessStateService, useValue: rowState },
{ provide: AccessRequestSdkService, useValue: accessRequestSdk },
{ provide: AccessLeaseSdkService, useValue: accessLeaseSdk },
{ provide: AccessRefreshService, useValue: accessRefresh },
{ provide: AccessBadgeTickerService, useValue: { ticks$ } },
{ provide: ToastService, useValue: toastService },
{ provide: I18nService, useValue: { t: (k: string, p?: string) => (p ? `${k}:${p}` : k) } },
{ provide: LogService, useValue: mock<LogService>() },
{ provide: RevealedCipherService, useValue: { revealed$: () => revealed$ } },
],
});
service = TestBed.inject(BrowserVaultRowAccessService);
});
describe("status$", () => {
it.each([
["privileged", "request", "pamRequestToUse"],
["pending", "pending", "pamAccessBadgePending"],
["unavailable", "unavailable", "pamUnavailableToRequest"],
["ready", "ready", "pamAccessBadgeReady"],
])("maps the %s badge to the %s row status", async (badge, kind, label) => {
state$.next({ badgeState: badge });
expect(await latest()).toEqual({ kind, label, canExtend: false });
});
it("counts down an active lease and reports whether it can be extended", async () => {
state$.next({
badgeState: { active: { expiresAt: new Date(Date.now() + 8 * 3_600_000).toISOString() } },
extensionsAllowed: true,
});
const status = await latest();
expect(status?.kind).toBe("active");
expect(status?.label).toMatch(/^pamAccessBadgeTimeLeft:/);
expect(status?.canExtend).toBe(true);
});
it("re-reads the state once the lease has lapsed", async () => {
state$.next({
badgeState: { active: { expiresAt: new Date(Date.now() - 1000).toISOString() } },
});
const emissions: unknown[] = [];
service.status$(gated).subscribe((s) => emissions.push(s));
expect(emissions).toEqual([]);
expect(rowState.invalidate).toHaveBeenCalledWith("c1");
});
describe("an unrestricted item held through a lease", () => {
const leasedState = (ms: number) => ({
badgeState: { active: { expiresAt: new Date(Date.now() + ms).toISOString() } },
});
it("counts down once its revealed copy is live", async () => {
state$.next(leasedState(8 * 3_600_000));
revealed$.next(new Map([["c2", {}]]));
const status = await firstValueFrom(service.status$(normal));
expect(status?.kind).toBe("active");
expect(rowState.state$).toHaveBeenCalledWith("c2");
});
it("drops back to nothing when the reveal ends", () => {
state$.next(leasedState(8 * 3_600_000));
revealed$.next(new Map([["c2", {}]]));
const emissions: unknown[] = [];
service.status$(normal).subscribe((s) => emissions.push(s));
revealed$.next(new Map());
expect(emissions[emissions.length - 1]).toBeNull();
});
});
describe("the countdown label", () => {
const labelAt = async (ms: number) => {
state$.next({
badgeState: { active: { expiresAt: new Date(Date.now() + ms).toISOString() } },
});
return (await latest())?.label;
};
it("shows whole hours", async () => {
expect(await labelAt(8 * 3_600_000 - 500)).toBe("pamAccessBadgeTimeLeft:8h");
});
it("shows minutes under an hour", async () => {
expect(await labelAt(14 * 60_000 - 500)).toBe("pamAccessBadgeTimeLeft:14m");
});
it("shows less than a minute under a minute", async () => {
expect(await labelAt(30_000)).toBe("pamAccessBadgeLessThanMinuteLeft");
});
it("ticks the label down as time passes", () => {
state$.next({
badgeState: { active: { expiresAt: new Date(Date.now() + 125_000).toISOString() } },
});
const labels: string[] = [];
service.status$(gated).subscribe((s) => s && labels.push(s.label));
ticks$.next(Date.now() + 10_000);
expect(labels).toEqual(["pamAccessBadgeTimeLeft:3m", "pamAccessBadgeTimeLeft:2m"]);
});
});
it("reports nothing for an item that is not restricted, without reading its state", async () => {
expect(await firstValueFrom(service.status$(normal))).toBeNull();
expect(rowState.state$).not.toHaveBeenCalled();
});
it("reports nothing while the Pam flag is off", async () => {
pamEnabled$.next(false);
expect(await latest()).toBeNull();
});
});
describe("subtitle$", () => {
const subtitle = (cipher = gated) => firstValueFrom(service.subtitle$(cipher));
it.each([
["privileged", "pamRequestToUse"],
["pending", "pamAccessBadgePending"],
["unavailable", "pamUnavailableToRequest"],
["ready", "pamAccessBadgeReady"],
])("shows only the status of a %s row, hiding the username", async (badge, label) => {
state$.next({ badgeState: badge });
expect(await subtitle()).toBe(label);
});
it("shows the status before the username once access is active", async () => {
state$.next(activeState());
revealed$.next(new Map([["c1", { id: "c1", subTitle: "frodo@shire.com" }]]));
expect(await subtitle()).toBe("pamAccessBadgeTimeLeft:8h • frodo@shire.com");
});
it("shows just the countdown while the revealed username is not yet available", async () => {
state$.next(activeState());
expect(await subtitle()).toBe("pamAccessBadgeTimeLeft:8h");
});
it("leaves an ungoverned row its own subtitle", async () => {
expect(await subtitle(normal)).toBeNull();
});
});
describe("rowActions", () => {
const action = (id: string) => service.rowActions().find((a) => a.id === id)!;
const shown = (cipher: CipherViewLike) =>
service
.rowActions()
.filter((a) => a.show?.(cipher) ?? true)
.map((a) => a.id);
// A row reports its status once its icon or subtitle subscribes.
const report = (cipher: CipherViewLike) => service.status$(cipher).subscribe();
it("labels the actions", () => {
expect(service.rowActions().map((a) => a.label)).toEqual([
"pamStartLeaseButton",
"pamRequestAccessButton",
"pamExtendAccessMenuItem",
"pamEndLeaseButton",
]);
});
it("offers nothing before the row reports a status", () => {
expect(shown(gated)).toEqual([]);
});
it("offers an enabled Request access on a requestable gated row", () => {
report(gated);
expect(shown(gated)).toEqual(["pamRequestAccess"]);
expect(action("pamRequestAccess").disabled?.(gated)).toBe(false);
});
it.each(["pending", "unavailable"])("disables Request access on a %s gated row", (badge) => {
state$.next({ badgeState: badge });
report(gated);
expect(shown(gated)).toEqual(["pamRequestAccess"]);
expect(action("pamRequestAccess").disabled?.(gated)).toBe(true);
});
it("offers Start access instead of Request access once the request is ready", () => {
state$.next({ badgeState: "ready" });
report(gated);
expect(shown(gated)).toEqual(["pamStartAccess"]);
});
it("offers Extend and End access on the revealed row while access is active", () => {
state$.next(activeState(true));
revealed$.next(new Map([["c2", {}]]));
report(normal);
expect(shown(normal)).toEqual(["pamExtendAccess", "pamEndAccess"]);
});
it("omits Extend access when the lease cannot be extended", () => {
state$.next(activeState(false));
revealed$.next(new Map([["c2", {}]]));
report(normal);
expect(shown(normal)).toEqual(["pamEndAccess"]);
});
it("offers nothing on an ungoverned row", () => {
report(normal);
expect(shown(normal)).toEqual([]);
});
it("forgets the reported statuses when the account switches", () => {
report(gated);
account$.next({ id: "u2" });
expect(shown(gated)).toEqual([]);
});
describe("a row that renders no icon or subtitle", () => {
const afterMicrotask = () => Promise.resolve();
it("reads its status once the menu asks", async () => {
expect(shown(gated)).toEqual([]);
await afterMicrotask();
expect(shown(gated)).toEqual(["pamRequestAccess"]);
});
it("starts one read however often the menu asks", async () => {
shown(gated);
shown(gated);
await afterMicrotask();
shown(gated);
expect(rowState.state$).toHaveBeenCalledTimes(1);
});
it("stops the read when the account switches", async () => {
shown(gated);
await afterMicrotask();
account$.next({ id: "u2" });
expect(state$.observed).toBe(false);
});
});
it("requests access from the menu item", async () => {
const row = { ...gated, type: { login: {} } } as unknown as CipherViewLike;
await action("pamRequestAccess").run(row);
expect(router.navigate).toHaveBeenCalledWith(["/view-cipher"], {
queryParams: { cipherId: "c1", type: CipherType.Login },
});
});
});
describe("requestAccess", () => {
it("opens the item, whose banner carries the request form", async () => {
await service.requestAccess({ ...gated, type: { login: {} } } as unknown as CipherViewLike);
expect(router.navigate).toHaveBeenCalledWith(["/view-cipher"], {
queryParams: { cipherId: "c1", type: CipherType.Login },
});
});
it("does nothing for a row without an id", async () => {
await service.requestAccess({ name: "No id" } as unknown as CipherViewLike);
expect(router.navigate).not.toHaveBeenCalled();
});
});
describe("endAccess", () => {
beforeEach(() => {
accessRequestSdk.getCipherAccessState.mockResolvedValue({
activeLease: { id: "lease-1" },
} as any);
});
it("ends the lease after confirmation and announces the change", async () => {
dialogService.openSimpleDialog.mockResolvedValue(true);
await service.endAccess(gated);
expect(accessLeaseSdk.endLease).toHaveBeenCalledWith("lease-1", { reason: undefined });
expect(accessRefresh.notifyAccessChanged).toHaveBeenCalledWith("c1");
});
it("does nothing when the member declines", async () => {
dialogService.openSimpleDialog.mockResolvedValue(false);
await service.endAccess(gated);
expect(accessLeaseSdk.endLease).not.toHaveBeenCalled();
});
it("does nothing without an active lease", async () => {
accessRequestSdk.getCipherAccessState.mockResolvedValue({ activeLease: undefined } as any);
await service.endAccess(gated);
expect(dialogService.openSimpleDialog).not.toHaveBeenCalled();
});
});
describe("extendAccess", () => {
beforeEach(() => {
accessRequestSdk.getCipherAccessState.mockResolvedValue({
activeLease: { id: "lease-1" },
maxExtensionDurationSeconds: 3600,
} as any);
});
it("extends the lease with the dialog's request", async () => {
const request = { durationSeconds: 900, reason: "audit" };
const open = jest
.spyOn(ExtendLeaseDialogComponent, "open")
.mockReturnValue({ closed: of(request) } as any);
accessLeaseSdk.extendLease.mockResolvedValue({ status: "approved" } as any);
await service.extendAccess(gated);
expect(open.mock.lastCall?.[1]).toEqual({ maxDurationSeconds: 3600 });
expect(accessLeaseSdk.extendLease).toHaveBeenCalledWith("lease-1", request);
expect(toastService.showToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "success", message: "pamExtendLeaseSuccess" }),
);
expect(accessRefresh.notifyAccessChanged).toHaveBeenCalledWith("c1");
});
it("warns when the extension is denied", async () => {
jest
.spyOn(ExtendLeaseDialogComponent, "open")
.mockReturnValue({ closed: of({ durationSeconds: 900, reason: "r" }) } as any);
accessLeaseSdk.extendLease.mockResolvedValue({ status: "denied" } as any);
await service.extendAccess(gated);
expect(toastService.showToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "warning", message: "pamExtendLeaseEnded" }),
);
});
it("does nothing when the state carries no extension cap", async () => {
accessRequestSdk.getCipherAccessState.mockResolvedValue({
activeLease: { id: "lease-1" },
} as any);
const open = jest.spyOn(ExtendLeaseDialogComponent, "open");
open.mockClear();
await service.extendAccess(gated);
expect(open).not.toHaveBeenCalled();
});
it("does nothing when the dialog is dismissed", async () => {
jest
.spyOn(ExtendLeaseDialogComponent, "open")
.mockReturnValue({ closed: of(undefined) } as any);
await service.extendAccess(gated);
expect(accessLeaseSdk.extendLease).not.toHaveBeenCalled();
});
});
describe("startAccess", () => {
it("does nothing without an approved request", async () => {
accessRequestSdk.getCipherAccessState.mockResolvedValue({ badgeState: "ready" } as any);
await service.startAccess(gated);
expect(accessRequestSdk.activateAccessRequest).not.toHaveBeenCalled();
});
});
});

View File

@@ -0,0 +1,458 @@
import { DestroyRef, Injectable, LOCALE_ID, inject, signal } from "@angular/core";
import { takeUntilDestroyed } from "@angular/core/rxjs-interop";
import { Router } from "@angular/router";
import {
EMPTY,
Observable,
Subscription,
combineLatest,
concat,
defer,
distinctUntilChanged,
firstValueFrom,
map,
of,
shareReplay,
startWith,
switchMap,
takeWhile,
tap,
} from "rxjs";
import {
AccessBadgeState,
AccessLeaseSdkService,
AccessRefreshService,
AccessRequestSdkService,
type CipherAccessStateView,
activateAccessErrorMessageKey,
callerOrganizations$,
cipherAccessBadgeState,
formatRemaining,
isUnlicensedError,
unactivatedApprovedRequest,
unlicensedForPam,
} from "@bitwarden/bit-pam";
import {
AccessBadgeTickerService,
ExtendLeaseDialogComponent,
} from "@bitwarden/bit-pam-components";
import { VaultRowSubtitle } from "@bitwarden/browser/vault/popup/components/vault/vault-row-slots/vault-row-subtitle.token";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
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 { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { CipherId } from "@bitwarden/common/types/guid";
import { RevealedCipherService } from "@bitwarden/common/vault/abstractions/revealed-cipher.service";
import {
CipherViewLike,
CipherViewLikeUtils,
} from "@bitwarden/common/vault/utils/cipher-view-like-utils";
import { DialogService, ToastService } from "@bitwarden/components";
import { VaultItemsTableRowAction } from "@bitwarden/vault";
import { VaultRowAccessStateService } from "../vault-row-access-state/vault-row-access-state.service";
import { VaultRowAccessStatus } from "./vault-row-access-status";
/** Separates the status from the username in a row's subtitle, as in "8h left • frodo@shire.com". */
const SUBTITLE_SEPARATOR = " • ";
/**
* The status each popup vault row shows for a privileged-control item, off the SDK's badge
* ranking, and the request, start, extend and end actions its overflow menu offers. Binds
* `VAULT_ROW_SUBTITLE` and backs `VAULT_ROW_ICON` and `VAULT_ROW_ACTIONS`. Nothing is reported until
* the member is known to be licensed.
*/
@Injectable()
export class BrowserVaultRowAccessService implements VaultRowSubtitle {
private readonly configService = inject(ConfigService);
private readonly accountService = inject(AccountService);
private readonly organizationService = inject(OrganizationService);
private readonly dialogService = inject(DialogService);
private readonly router = inject(Router);
private readonly rowState = inject(VaultRowAccessStateService);
private readonly accessRequestSdkService = inject(AccessRequestSdkService);
private readonly accessLeaseSdkService = inject(AccessLeaseSdkService);
private readonly accessRefreshService = inject(AccessRefreshService);
private readonly ticker = inject(AccessBadgeTickerService);
private readonly toastService = inject(ToastService);
private readonly i18nService = inject(I18nService);
private readonly logService = inject(LogService);
private readonly locale = inject(LOCALE_ID);
private readonly revealedCipherService = inject(RevealedCipherService);
private readonly organizations$ = callerOrganizations$(
this.accountService,
this.organizationService,
);
private readonly pamEnabled$ = this.configService.getFeatureFlag$(FeatureFlag.Pam);
/** The latest status each row reported, by cipher id, for the menu's synchronous checks. */
private readonly statuses = signal<ReadonlyMap<string, VaultRowAccessStatus>>(new Map());
/** Status reads the menu started for rows that render no icon or subtitle, by cipher id. */
private readonly watched = new Map<string, Subscription>();
constructor() {
// The popup document survives an account switch, so the previous account's statuses go.
this.accountService.activeAccount$
.pipe(
map((account) => account?.id ?? null),
distinctUntilChanged(),
takeUntilDestroyed(),
)
.subscribe(() => {
this.unwatchAll();
this.statuses.set(new Map());
});
inject(DestroyRef).onDestroy(() => this.unwatchAll());
}
/**
* A restricted item is always governed. An unrestricted one is governed only while a live
* revealed copy exists, which is how a leased item that the list no longer marks restricted
* still shows its countdown. Nothing else costs an access-state read.
*/
status$(cipher: CipherViewLike): Observable<VaultRowAccessStatus | null> {
const cipherId = cipher.id == null ? null : String(cipher.id);
if (cipherId == null) {
return of(null);
}
const restricted = CipherViewLikeUtils.isRestricted(cipher);
const governed$ = restricted ? of(true) : this.isRevealed$(cipherId);
const unlicensed$ =
cipher.organizationId == null
? of(false)
: this.organizations$.pipe(
map((organizations) =>
unlicensedForPam(organizations.find((o) => o.id === cipher.organizationId)),
),
);
return combineLatest([this.pamEnabled$, unlicensed$, governed$]).pipe(
distinctUntilChanged(([a, b, c], [d, e, f]) => a === d && b === e && c === f),
switchMap(([enabled, unlicensed, governed]) =>
!enabled || unlicensed || !governed
? of(null)
: this.rowState
.state$(cipherId)
.pipe(switchMap((state) => this.toStatus$(cipherId, state))),
),
tap((status) => this.record(cipherId, status)),
shareReplay({ bufferSize: 1, refCount: true }),
);
}
/** The status, then the revealed username once access is active. `null` for an ungoverned item. */
subtitle$(cipher: CipherViewLike): Observable<string | null> {
return this.status$(cipher).pipe(
switchMap((status) =>
status?.kind !== "active"
? of(status?.label ?? null)
: this.revealedSubtitle$(cipher).pipe(
map((username) =>
username ? `${status.label}${SUBTITLE_SEPARATOR}${username}` : status.label,
),
),
),
);
}
/**
* The row menu's access actions: Request access (disabled unless requestable) or Start access on
* a gated row, Extend and End access while active. Each reads the status its row last reported.
*/
rowActions(): readonly VaultItemsTableRowAction<CipherViewLike>[] {
const statusOf = (cipher: CipherViewLike) => this.reportedStatus(cipher);
// The list swaps a revealed view in for its restricted row, so a restricted row is not in use.
const gated = (cipher: CipherViewLike) => CipherViewLikeUtils.isRestricted(cipher);
return [
{
id: "pamStartAccess",
label: this.i18nService.t("pamStartLeaseButton"),
icon: "bwi-unlock",
show: (cipher) => gated(cipher) && statusOf(cipher)?.kind === "ready",
run: (cipher) => this.startAccess(cipher),
},
{
id: "pamRequestAccess",
label: this.i18nService.t("pamRequestAccessButton"),
icon: "bwi-lock-encrypted",
show: (cipher) => {
const kind = statusOf(cipher)?.kind;
return gated(cipher) && kind != null && kind !== "ready";
},
disabled: (cipher) => statusOf(cipher)?.kind !== "request",
run: (cipher) => this.requestAccess(cipher),
},
{
id: "pamExtendAccess",
label: this.i18nService.t("pamExtendAccessMenuItem"),
icon: "bwi-clock",
show: (cipher) => {
const status = statusOf(cipher);
return !gated(cipher) && status?.kind === "active" && status.canExtend;
},
run: (cipher) => this.extendAccess(cipher),
},
{
id: "pamEndAccess",
label: this.i18nService.t("pamEndLeaseButton"),
icon: "bwi-lock",
show: (cipher) => !gated(cipher) && statusOf(cipher)?.kind === "active",
run: (cipher) => this.endAccess(cipher),
},
];
}
/**
* The row's last reported status. A row with no icon or subtitle (the list without VFO1) never
* reports one, so the first ask starts a read. `show` may not write a signal: it starts after.
*/
private reportedStatus(cipher: CipherViewLike): VaultRowAccessStatus | undefined {
if (cipher.id == null) {
return undefined;
}
const cipherId = String(cipher.id);
const status = this.statuses().get(cipherId);
if (status == null && !this.watched.has(cipherId)) {
this.watched.set(cipherId, Subscription.EMPTY);
queueMicrotask(() => {
if (this.watched.has(cipherId)) {
this.watched.set(cipherId, this.status$(cipher).subscribe());
}
});
}
return status;
}
private unwatchAll(): void {
this.watched.forEach((subscription) => subscription.unsubscribe());
this.watched.clear();
}
private record(cipherId: string, status: VaultRowAccessStatus | null): void {
const statuses = new Map(this.statuses());
if (status == null) {
statuses.delete(cipherId);
} else {
statuses.set(cipherId, status);
}
this.statuses.set(statuses);
}
/** The subtitle of the live revealed copy, which a stripped list entry lacks. */
private revealedSubtitle$(cipher: CipherViewLike): Observable<string | undefined> {
return this.accountService.activeAccount$.pipe(
getUserId,
switchMap((userId) => this.revealedCipherService.revealed$(userId)),
map((revealed) => {
const view = cipher.id == null ? undefined : revealed.get(cipher.id as CipherId);
return view == null ? undefined : CipherViewLikeUtils.subtitle(view, this.i18nService);
}),
distinctUntilChanged(),
);
}
/** Whether the active user holds a live revealed copy of the cipher, off the shared reveals stream. */
private isRevealed$(cipherId: string): Observable<boolean> {
return this.accountService.activeAccount$.pipe(
getUserId,
switchMap((userId) => this.revealedCipherService.revealed$(userId)),
map((revealed) => revealed.has(cipherId as CipherId)),
distinctUntilChanged(),
);
}
private toStatus$(
cipherId: string,
state: CipherAccessStateView | null,
): Observable<VaultRowAccessStatus | null> {
const badge = cipherAccessBadgeState(state);
if (badge == null) {
return of(null);
}
if (badge.kind === "active") {
return this.activeStatus$(cipherId, badge.expiresAt, state?.extensionsAllowed === true);
}
return of(this.staticStatus(badge));
}
private staticStatus(badge: Exclude<AccessBadgeState, { kind: "active" }>): VaultRowAccessStatus {
const status = (kind: VaultRowAccessStatus["kind"], key: string): VaultRowAccessStatus => ({
kind,
label: this.i18nService.t(key),
canExtend: false,
});
switch (badge.kind) {
case "pending":
return status("pending", "pamAccessBadgePending");
case "unavailable":
return status("unavailable", "pamUnavailableToRequest");
case "ready":
return status("ready", "pamAccessBadgeReady");
default:
return status("request", "pamRequestToUse");
}
}
/** Counts down to `expiresAt`, then re-reads the state so a lapsed or extended lease is picked up. */
private activeStatus$(
cipherId: string,
expiresAt: Date,
canExtend: boolean,
): Observable<VaultRowAccessStatus> {
const locale = this.locale;
return concat(
this.ticker.ticks$.pipe(
startWith(Date.now()),
map((now) => expiresAt.getTime() - now),
takeWhile((remainingMs) => remainingMs > 0),
map((remainingMs) => this.countdownLabel(locale, remainingMs)),
distinctUntilChanged(),
map((label): VaultRowAccessStatus => ({ kind: "active", label, canExtend })),
),
defer(() => {
this.rowState.invalidate(cipherId);
return EMPTY;
}),
);
}
/** Whole hours ("8h"), then minutes ("14m"), then "<1m": a row needs no finer than a minute. */
private countdownLabel(locale: string, remainingMs: number): string {
if (remainingMs < 60_000) {
return this.i18nService.t("pamAccessBadgeLessThanMinuteLeft");
}
const totalMinutes = Math.ceil(remainingMs / 60_000);
const duration =
totalMinutes < 60
? formatRemaining(locale, totalMinutes * 60_000)
: formatRemaining(locale, Math.floor(totalMinutes / 60) * 3_600_000);
return this.i18nService.t("pamAccessBadgeTimeLeft", duration);
}
/**
* Opens the item, whose banner carries the request form, so a row never shows a second copy of it.
*/
async requestAccess(cipher: CipherViewLike): Promise<void> {
if (cipher.id == null) {
return;
}
await this.router.navigate(["/view-cipher"], {
queryParams: { cipherId: cipher.id, type: CipherViewLikeUtils.getType(cipher) },
});
}
async startAccess(cipher: CipherViewLike): Promise<void> {
if (cipher.id == null) {
return;
}
const cipherId = String(cipher.id);
try {
const state = await this.accessRequestSdkService.getCipherAccessState(cipherId);
const request = unactivatedApprovedRequest(state);
if (request == null) {
return;
}
await this.accessRequestSdkService.activateAccessRequest(request.id);
this.toastService.showToast({
variant: "success",
message: this.i18nService.t("pamStartLeaseSuccess"),
});
this.rowState.invalidate(cipherId);
this.accessRefreshService.notifyAccessChanged(cipherId);
} catch (e) {
this.logService.error(e);
this.toastService.showToast({
variant: "error",
message: this.i18nService.t(activateAccessErrorMessageKey(e)),
});
this.rowState.invalidate(cipherId);
}
}
/** A denied extension resolves rather than throws, so the returned status picks the toast. */
async extendAccess(cipher: CipherViewLike): Promise<void> {
const cipherId = cipher.id == null ? null : String(cipher.id);
const state =
cipherId == null ? null : await this.accessRequestSdkService.getCipherAccessState(cipherId);
const lease = state?.activeLease;
// The server sends a cap whenever extensions are allowed.
const maxDurationSeconds = state?.maxExtensionDurationSeconds;
if (cipherId == null || lease == null || maxDurationSeconds == null) {
return;
}
const request = await firstValueFrom(
ExtendLeaseDialogComponent.open(this.dialogService, { maxDurationSeconds }).closed,
);
if (request == null) {
return;
}
try {
const extension = await this.accessLeaseSdkService.extendLease(lease.id, request);
const denied = extension.status === "denied";
this.toastService.showToast({
variant: denied ? "warning" : "success",
message: this.i18nService.t(denied ? "pamExtendLeaseEnded" : "pamExtendLeaseSuccess"),
});
} catch (e) {
this.logService.error(e);
this.toastService.showToast({
variant: "error",
message: this.i18nService.t(
isUnlicensedError(e) ? "pamLeaseErrorUnlicensed" : "pamExtendLeaseError",
),
});
} finally {
this.changed(cipherId);
}
}
async endAccess(cipher: CipherViewLike): Promise<void> {
const cipherId = cipher.id == null ? null : String(cipher.id);
const lease = cipherId == null ? undefined : await this.activeLease(cipherId);
if (cipherId == null || lease == null) {
return;
}
const confirmed = await this.dialogService.openSimpleDialog({
title: { key: "pamEndLeaseTitle" },
content: { key: "pamEndLeaseConfirm" },
acceptButtonText: { key: "pamEndLeaseButton" },
type: "warning",
});
if (!confirmed) {
return;
}
try {
await this.accessLeaseSdkService.endLease(lease.id, { reason: undefined });
this.toastService.showToast({
variant: "success",
message: this.i18nService.t("pamEndLeaseSuccess"),
});
} catch (e) {
this.logService.error(e);
this.toastService.showToast({
variant: "error",
message: this.i18nService.t("errorOccurred"),
});
} finally {
this.changed(cipherId);
}
}
/** The live lease read fresh, since the menu may have sat open past a change elsewhere. */
private async activeLease(cipherId: string) {
const state = await this.accessRequestSdkService.getCipherAccessState(cipherId);
return state?.activeLease ?? undefined;
}
private changed(cipherId: string): void {
this.rowState.invalidate(cipherId);
this.accessRefreshService.notifyAccessChanged(cipherId);
}
}

View File

@@ -0,0 +1,59 @@
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 { BrowserVaultRowAccessService } from "./browser-vault-row-access.service";
import { VaultRowAccessIconComponent } from "./vault-row-access-icon.component";
import { VaultRowAccessStatus } from "./vault-row-access-status";
describe("VaultRowAccessIconComponent", () => {
let fixture: ComponentFixture<VaultRowAccessIconComponent>;
let status$: BehaviorSubject<VaultRowAccessStatus | null>;
const cipher = { id: "c1", name: "Amazon", partial: true } as unknown as CipherViewLike;
function iconClasses(): string[] {
const icon = fixture.nativeElement.querySelector("bit-icon");
return icon == null ? [] : Array.from(icon.classList);
}
beforeEach(async () => {
status$ = new BehaviorSubject<VaultRowAccessStatus | null>(null);
await TestBed.configureTestingModule({
imports: [VaultRowAccessIconComponent],
providers: [
{ provide: I18nService, useValue: { t: (k: string) => k } },
{ provide: BrowserVaultRowAccessService, useValue: { status$: () => status$ } },
],
}).compileComponents();
fixture = TestBed.createComponent(VaultRowAccessIconComponent);
fixture.componentRef.setInput("cipher", cipher);
fixture.detectChanges();
});
it.each([
["request", "bwi-lock-encrypted"],
["unavailable", "bwi-lock-encrypted"],
["pending", "bwi-clock"],
["ready", "bwi-lock"],
["active", "bwi-unlock"],
] as const)("shows %s as %s", (kind, icon) => {
status$.next({ kind, label: kind, canExtend: false });
fixture.detectChanges();
expect(iconClasses()).toContain(icon);
});
it("titles the icon Privileged", () => {
status$.next({ kind: "request", label: "request", canExtend: false });
fixture.detectChanges();
expect(fixture.nativeElement.querySelector("bit-icon").title).toBe("pamAccessBadgePrivileged");
});
it("renders nothing for an item privileged control does not govern", () => {
expect(iconClasses()).toEqual([]);
});
});

View File

@@ -0,0 +1,62 @@
import { ChangeDetectionStrategy, Component, computed, inject, input } from "@angular/core";
import { toObservable, toSignal } from "@angular/core/rxjs-interop";
import { of, switchMap } from "rxjs";
import { CipherViewLike } from "@bitwarden/common/vault/utils/cipher-view-like-utils";
import { BitwardenIcon, IconComponent } from "@bitwarden/components";
import { I18nPipe } from "@bitwarden/ui-common";
import { BrowserVaultRowAccessService } from "./browser-vault-row-access.service";
import { VaultRowAccessStatus } from "./vault-row-access-status";
/**
* Binds `VAULT_ROW_ICON`: the privileged-control status icon in a popup row's name line. The
* privileged-control lock for a request or unavailable item, a clock while pending, a closed lock
* when ready and an open lock in use. Renders nothing for an item privileged control does not
* govern.
*/
@Component({
selector: "pam-vault-row-access-icon",
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [IconComponent, I18nPipe],
// `tw-block`: inline, the icon would sit on a line of the row's font and outgrow the name.
template: `
@if (icon(); as icon) {
<bit-icon
[name]="icon"
class="tw-block bwi-sm tw-text-muted"
[title]="'pamAccessBadgePrivileged' | i18n"
[attr.data-testid]="'vault-row-access-icon-' + status()?.kind"
aria-hidden="true"
></bit-icon>
}
`,
})
export class VaultRowAccessIconComponent {
readonly cipher = input<CipherViewLike | null>(null);
private readonly rowAccess = inject(BrowserVaultRowAccessService);
protected readonly status = toSignal(
toObservable(this.cipher).pipe(
switchMap((cipher) => (cipher == null ? of(null) : this.rowAccess.status$(cipher))),
),
{ initialValue: null as VaultRowAccessStatus | null },
);
protected readonly icon = computed((): BitwardenIcon | null => {
switch (this.status()?.kind) {
case "request":
case "unavailable":
return "bwi-lock-encrypted";
case "pending":
return "bwi-clock";
case "ready":
return "bwi-lock";
case "active":
return "bwi-unlock";
default:
return null;
}
});
}

View File

@@ -0,0 +1,14 @@
/**
* Where a privileged-control item stands for the member, as a popup vault row shows it. `request`
* and `unavailable` are gated, `pending` waits on an approver, `ready` is approved but not started
* and `active` is a live lease.
*/
export type VaultRowAccessStatusKind = "request" | "pending" | "unavailable" | "ready" | "active";
export interface VaultRowAccessStatus {
readonly kind: VaultRowAccessStatusKind;
/** The localized status text, such as "Request to use" or "8h left". Ticks while active. */
readonly label: string;
/** Whether the live lease may be extended. Only meaningful while `active`. */
readonly canExtend: boolean;
}

View File

@@ -9,6 +9,8 @@ import { AppRoutingModule as OssRoutingModule } from "@bitwarden/browser/popup/a
import { AppModule as OssModule } from "@bitwarden/browser/popup/app.module";
// import { WildcardRoutingModule } from "@bitwarden/browser/popup/wildcard-routing.module";
import { providePam } from "../pam/popup/provide-pam";
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
/**
@@ -35,6 +37,6 @@ import { AppComponent } from "./app.component";
],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [],
providers: [...providePam()],
})
export class AppModule {}

View File

@@ -0,0 +1,26 @@
import type { CipherAccessStateView } from "../abstractions/access-lease";
import { unactivatedApprovedRequest } from "./unactivated-approved-request";
function state(approvedRequest: unknown): CipherAccessStateView {
return { approvedRequest } as unknown as CipherAccessStateView;
}
describe("unactivatedApprovedRequest", () => {
it("returns an approved request that has not minted a lease", () => {
const approved = { id: "request-1" };
expect(unactivatedApprovedRequest(state(approved))).toBe(approved);
});
it("ignores an approved request that already produced a lease", () => {
expect(
unactivatedApprovedRequest(state({ id: "request-1", producedLeaseId: "lease-1" })),
).toBeUndefined();
});
it("returns undefined without a state or an approved request", () => {
expect(unactivatedApprovedRequest(null)).toBeUndefined();
expect(unactivatedApprovedRequest(state(undefined))).toBeUndefined();
});
});

View File

@@ -0,0 +1,12 @@
import type { AccessRequestView, CipherAccessStateView } from "../abstractions/access-lease";
/**
* The approved request still awaiting Start. An activated request stays `approved` and carries
* `producedLeaseId`, so activation is never read from the status.
*/
export function unactivatedApprovedRequest(
state: CipherAccessStateView | null | undefined,
): AccessRequestView | undefined {
const approved = state?.approvedRequest;
return approved?.producedLeaseId == null ? approved : undefined;
}

View File

@@ -66,6 +66,7 @@ export { liveActiveLease, rereadOnLapse } from "./helpers/lease-liveness";
export { findHumanDecision, humanApprover } from "./helpers/find-human-decision";
export { requestedWindowSeconds } from "./helpers/requested-window";
export { isActionableRequest } from "./helpers/actionable-requests";
export { unactivatedApprovedRequest } from "./helpers/unactivated-approved-request";
export { canApprove } from "./helpers/can-approve";
export type { AccessRequestForApproval, UserForApproval } from "./helpers/can-approve";
export { elapsedLabel } from "./date/elapsed";