mirror of
https://github.com/bitwarden/browser
synced 2025-12-10 21:33:27 +00:00
[PM-26372] Add auto confirm service (#17001)
* add state definition for auto confirm * typo * refactor organziation user service * WIP create auto confirm service * add POST method, finish implementation * add missing userId param, jsdoc * fix DI * refactor organziation user service * WIP create auto confirm service * add POST method, finish implementation * add missing userId param, jsdoc * clean up, more DI fixes * remove @Injectable from service, fix tests * remove from libs/common, fix dir structure, add tests
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
import { Observable } from "rxjs";
|
||||
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { UserId } from "@bitwarden/user-core";
|
||||
|
||||
import { AutoConfirmState } from "../models/auto-confirm-state.model";
|
||||
|
||||
export abstract class AutomaticUserConfirmationService {
|
||||
/**
|
||||
* @param userId
|
||||
* @returns Observable<AutoConfirmState> an observable with the Auto Confirm user state for the provided userId.
|
||||
**/
|
||||
abstract configuration$(userId: UserId): Observable<AutoConfirmState>;
|
||||
/**
|
||||
* Upserts the existing user state with a new configuration.
|
||||
* @param userId
|
||||
* @param config The new AutoConfirmState to upsert into the user state for the provided userId.
|
||||
**/
|
||||
abstract upsert(userId: UserId, config: AutoConfirmState): Promise<void>;
|
||||
/**
|
||||
* This will check if the feature is enabled, the organization plan feature UseAutomaticUserConfirmation is enabled
|
||||
* and the the provided user has admin/owner/manage custom permission role.
|
||||
* @param userId
|
||||
* @returns Observable<boolean> an observable with a boolean telling us if the provided user may confgure the auto confirm feature.
|
||||
**/
|
||||
abstract canManageAutoConfirm$(
|
||||
userId: UserId,
|
||||
organizationId: OrganizationId,
|
||||
): Observable<boolean>;
|
||||
/**
|
||||
* Calls the API endpoint to initiate automatic user confirmation.
|
||||
* @param userId The userId of the logged in admin performing auto confirmation. This is neccesary to perform the key exchange and for permissions checks.
|
||||
* @param confirmingUserId The userId of the user being confirmed.
|
||||
* @param organization the organization the user is being auto confirmed to.
|
||||
**/
|
||||
abstract autoConfirmUser(
|
||||
userId: UserId,
|
||||
confirmingUserId: UserId,
|
||||
organization: Organization,
|
||||
): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./auto-confirm.service.abstraction";
|
||||
3
libs/admin-console/src/common/auto-confirm/index.ts
Normal file
3
libs/admin-console/src/common/auto-confirm/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export * from "./abstractions";
|
||||
export * from "./models";
|
||||
export * from "./services";
|
||||
@@ -0,0 +1,21 @@
|
||||
import { AUTO_CONFIRM, UserKeyDefinition } from "@bitwarden/state";
|
||||
|
||||
export class AutoConfirmState {
|
||||
enabled: boolean;
|
||||
showSetupDialog: boolean;
|
||||
showBrowserNotification: boolean | undefined;
|
||||
|
||||
constructor() {
|
||||
this.enabled = false;
|
||||
this.showSetupDialog = true;
|
||||
}
|
||||
}
|
||||
|
||||
export const AUTO_CONFIRM_STATE = UserKeyDefinition.record<AutoConfirmState>(
|
||||
AUTO_CONFIRM,
|
||||
"autoConfirm",
|
||||
{
|
||||
deserializer: (autoConfirmState) => autoConfirmState,
|
||||
clearOn: ["logout"],
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./auto-confirm-state.model";
|
||||
@@ -0,0 +1,382 @@
|
||||
import { TestBed } from "@angular/core/testing";
|
||||
import { BehaviorSubject, firstValueFrom, of, throwError } from "rxjs";
|
||||
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { InternalOrganizationServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { PermissionsApi } from "@bitwarden/common/admin-console/models/api/permissions.api";
|
||||
import { OrganizationData } from "@bitwarden/common/admin-console/models/data/organization.data";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { FakeStateProvider, mockAccountServiceWith } from "@bitwarden/common/spec";
|
||||
import { OrganizationId, UserId } from "@bitwarden/common/types/guid";
|
||||
|
||||
import {
|
||||
DefaultOrganizationUserService,
|
||||
OrganizationUserApiService,
|
||||
OrganizationUserConfirmRequest,
|
||||
} from "../../organization-user";
|
||||
import { AUTO_CONFIRM_STATE, AutoConfirmState } from "../models/auto-confirm-state.model";
|
||||
|
||||
import { DefaultAutomaticUserConfirmationService } from "./default-auto-confirm.service";
|
||||
|
||||
describe("DefaultAutomaticUserConfirmationService", () => {
|
||||
let service: DefaultAutomaticUserConfirmationService;
|
||||
let configService: jest.Mocked<ConfigService>;
|
||||
let apiService: jest.Mocked<ApiService>;
|
||||
let organizationUserService: jest.Mocked<DefaultOrganizationUserService>;
|
||||
let stateProvider: FakeStateProvider;
|
||||
let organizationService: jest.Mocked<InternalOrganizationServiceAbstraction>;
|
||||
let organizationUserApiService: jest.Mocked<OrganizationUserApiService>;
|
||||
|
||||
const mockUserId = Utils.newGuid() as UserId;
|
||||
const mockConfirmingUserId = Utils.newGuid() as UserId;
|
||||
const mockOrganizationId = Utils.newGuid() as OrganizationId;
|
||||
let mockOrganization: Organization;
|
||||
|
||||
beforeEach(() => {
|
||||
configService = {
|
||||
getFeatureFlag$: jest.fn(),
|
||||
} as any;
|
||||
|
||||
apiService = {
|
||||
getUserPublicKey: jest.fn(),
|
||||
} as any;
|
||||
|
||||
organizationUserService = {
|
||||
buildConfirmRequest: jest.fn(),
|
||||
} as any;
|
||||
|
||||
stateProvider = new FakeStateProvider(mockAccountServiceWith(mockUserId));
|
||||
|
||||
organizationService = {
|
||||
organizations$: jest.fn(),
|
||||
} as any;
|
||||
|
||||
organizationUserApiService = {
|
||||
postOrganizationUserConfirm: jest.fn(),
|
||||
} as any;
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
DefaultAutomaticUserConfirmationService,
|
||||
{ provide: ConfigService, useValue: configService },
|
||||
{ provide: ApiService, useValue: apiService },
|
||||
{ provide: DefaultOrganizationUserService, useValue: organizationUserService },
|
||||
{ provide: "StateProvider", useValue: stateProvider },
|
||||
{
|
||||
provide: InternalOrganizationServiceAbstraction,
|
||||
useValue: organizationService,
|
||||
},
|
||||
{ provide: OrganizationUserApiService, useValue: organizationUserApiService },
|
||||
],
|
||||
});
|
||||
|
||||
service = new DefaultAutomaticUserConfirmationService(
|
||||
configService,
|
||||
apiService,
|
||||
organizationUserService,
|
||||
stateProvider,
|
||||
organizationService,
|
||||
organizationUserApiService,
|
||||
);
|
||||
|
||||
const mockOrgData = new OrganizationData({} as any, {} as any);
|
||||
mockOrgData.id = mockOrganizationId;
|
||||
mockOrgData.useAutomaticUserConfirmation = true;
|
||||
|
||||
const permissions = new PermissionsApi();
|
||||
permissions.manageUsers = true;
|
||||
mockOrgData.permissions = permissions;
|
||||
|
||||
mockOrganization = new Organization(mockOrgData);
|
||||
});
|
||||
|
||||
describe("configuration$", () => {
|
||||
it("should return default AutoConfirmState when no state exists", async () => {
|
||||
const config$ = service.configuration$(mockUserId);
|
||||
const config = await firstValueFrom(config$);
|
||||
|
||||
expect(config).toBeInstanceOf(AutoConfirmState);
|
||||
expect(config.enabled).toBe(false);
|
||||
expect(config.showSetupDialog).toBe(true);
|
||||
});
|
||||
|
||||
it("should return stored AutoConfirmState when state exists", async () => {
|
||||
const expectedConfig = new AutoConfirmState();
|
||||
expectedConfig.enabled = true;
|
||||
expectedConfig.showSetupDialog = false;
|
||||
expectedConfig.showBrowserNotification = true;
|
||||
|
||||
await stateProvider.setUserState(
|
||||
AUTO_CONFIRM_STATE,
|
||||
{ [mockUserId]: expectedConfig },
|
||||
mockUserId,
|
||||
);
|
||||
|
||||
const config$ = service.configuration$(mockUserId);
|
||||
const config = await firstValueFrom(config$);
|
||||
|
||||
expect(config.enabled).toBe(true);
|
||||
expect(config.showSetupDialog).toBe(false);
|
||||
expect(config.showBrowserNotification).toBe(true);
|
||||
});
|
||||
|
||||
it("should emit updates when state changes", async () => {
|
||||
const config$ = service.configuration$(mockUserId);
|
||||
const configs: AutoConfirmState[] = [];
|
||||
|
||||
const subscription = config$.subscribe((config) => configs.push(config));
|
||||
|
||||
expect(configs[0].enabled).toBe(false);
|
||||
|
||||
const newConfig = new AutoConfirmState();
|
||||
newConfig.enabled = true;
|
||||
await stateProvider.setUserState(AUTO_CONFIRM_STATE, { [mockUserId]: newConfig }, mockUserId);
|
||||
|
||||
expect(configs.length).toBeGreaterThan(1);
|
||||
expect(configs[configs.length - 1].enabled).toBe(true);
|
||||
|
||||
subscription.unsubscribe();
|
||||
});
|
||||
});
|
||||
|
||||
describe("upsert", () => {
|
||||
it("should store new configuration for user", async () => {
|
||||
const newConfig = new AutoConfirmState();
|
||||
newConfig.enabled = true;
|
||||
newConfig.showSetupDialog = false;
|
||||
|
||||
await service.upsert(mockUserId, newConfig);
|
||||
|
||||
const storedState = await firstValueFrom(
|
||||
stateProvider.getUser(mockUserId, AUTO_CONFIRM_STATE).state$,
|
||||
);
|
||||
|
||||
expect(storedState != null);
|
||||
expect(storedState![mockUserId]).toEqual(newConfig);
|
||||
});
|
||||
|
||||
it("should update existing configuration for user", async () => {
|
||||
const initialConfig = new AutoConfirmState();
|
||||
initialConfig.enabled = false;
|
||||
|
||||
await service.upsert(mockUserId, initialConfig);
|
||||
|
||||
const updatedConfig = new AutoConfirmState();
|
||||
updatedConfig.enabled = true;
|
||||
updatedConfig.showSetupDialog = false;
|
||||
|
||||
await service.upsert(mockUserId, updatedConfig);
|
||||
|
||||
const storedState = await firstValueFrom(
|
||||
stateProvider.getUser(mockUserId, AUTO_CONFIRM_STATE).state$,
|
||||
);
|
||||
|
||||
expect(storedState != null);
|
||||
expect(storedState![mockUserId].enabled).toBe(true);
|
||||
expect(storedState![mockUserId].showSetupDialog).toBe(false);
|
||||
});
|
||||
|
||||
it("should preserve other user configurations when updating", async () => {
|
||||
const otherUserId = Utils.newGuid() as UserId;
|
||||
const otherConfig = new AutoConfirmState();
|
||||
otherConfig.enabled = true;
|
||||
|
||||
await stateProvider.setUserState(
|
||||
AUTO_CONFIRM_STATE,
|
||||
{ [otherUserId]: otherConfig },
|
||||
mockUserId,
|
||||
);
|
||||
|
||||
const newConfig = new AutoConfirmState();
|
||||
newConfig.enabled = false;
|
||||
|
||||
await service.upsert(mockUserId, newConfig);
|
||||
|
||||
const storedState = await firstValueFrom(
|
||||
stateProvider.getUser(mockUserId, AUTO_CONFIRM_STATE).state$,
|
||||
);
|
||||
|
||||
expect(storedState != null);
|
||||
expect(storedState![mockUserId]).toEqual(newConfig);
|
||||
expect(storedState![otherUserId]).toEqual(otherConfig);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canManageAutoConfirm$", () => {
|
||||
beforeEach(() => {
|
||||
const organizations$ = new BehaviorSubject<Organization[]>([mockOrganization]);
|
||||
organizationService.organizations$.mockReturnValue(organizations$);
|
||||
});
|
||||
|
||||
it("should return true when feature flag is enabled and organization allows management", async () => {
|
||||
configService.getFeatureFlag$.mockReturnValue(of(true));
|
||||
|
||||
const canManage$ = service.canManageAutoConfirm$(mockUserId, mockOrganizationId);
|
||||
const canManage = await firstValueFrom(canManage$);
|
||||
|
||||
expect(canManage).toBe(true);
|
||||
});
|
||||
|
||||
it("should return false when feature flag is disabled", async () => {
|
||||
configService.getFeatureFlag$.mockReturnValue(of(false));
|
||||
|
||||
const canManage$ = service.canManageAutoConfirm$(mockUserId, mockOrganizationId);
|
||||
const canManage = await firstValueFrom(canManage$);
|
||||
|
||||
expect(canManage).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when organization canManageUsers is false", async () => {
|
||||
configService.getFeatureFlag$.mockReturnValue(of(true));
|
||||
|
||||
// Create organization without manageUsers permission
|
||||
const mockOrgData = new OrganizationData({} as any, {} as any);
|
||||
mockOrgData.id = mockOrganizationId;
|
||||
mockOrgData.useAutomaticUserConfirmation = true;
|
||||
const permissions = new PermissionsApi();
|
||||
permissions.manageUsers = false;
|
||||
mockOrgData.permissions = permissions;
|
||||
const orgWithoutManageUsers = new Organization(mockOrgData);
|
||||
|
||||
const organizations$ = new BehaviorSubject<Organization[]>([orgWithoutManageUsers]);
|
||||
organizationService.organizations$.mockReturnValue(organizations$);
|
||||
|
||||
const canManage$ = service.canManageAutoConfirm$(mockUserId, mockOrganizationId);
|
||||
const canManage = await firstValueFrom(canManage$);
|
||||
|
||||
expect(canManage).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when organization useAutomaticUserConfirmation is false", async () => {
|
||||
configService.getFeatureFlag$.mockReturnValue(of(true));
|
||||
|
||||
// Create organization without useAutomaticUserConfirmation
|
||||
const mockOrgData = new OrganizationData({} as any, {} as any);
|
||||
mockOrgData.id = mockOrganizationId;
|
||||
mockOrgData.useAutomaticUserConfirmation = false;
|
||||
const permissions = new PermissionsApi();
|
||||
permissions.manageUsers = true;
|
||||
mockOrgData.permissions = permissions;
|
||||
const orgWithoutAutoConfirm = new Organization(mockOrgData);
|
||||
|
||||
const organizations$ = new BehaviorSubject<Organization[]>([orgWithoutAutoConfirm]);
|
||||
organizationService.organizations$.mockReturnValue(organizations$);
|
||||
|
||||
const canManage$ = service.canManageAutoConfirm$(mockUserId, mockOrganizationId);
|
||||
const canManage = await firstValueFrom(canManage$);
|
||||
|
||||
expect(canManage).toBe(false);
|
||||
});
|
||||
|
||||
it("should return false when organization is not found", async () => {
|
||||
configService.getFeatureFlag$.mockReturnValue(of(true));
|
||||
|
||||
const organizations$ = new BehaviorSubject<Organization[]>([]);
|
||||
organizationService.organizations$.mockReturnValue(organizations$);
|
||||
|
||||
const canManage$ = service.canManageAutoConfirm$(mockUserId, mockOrganizationId);
|
||||
const canManage = await firstValueFrom(canManage$);
|
||||
|
||||
expect(canManage).toBe(false);
|
||||
});
|
||||
|
||||
it("should use the correct feature flag", async () => {
|
||||
configService.getFeatureFlag$.mockReturnValue(of(true));
|
||||
|
||||
const canManage$ = service.canManageAutoConfirm$(mockUserId, mockOrganizationId);
|
||||
await firstValueFrom(canManage$);
|
||||
|
||||
expect(configService.getFeatureFlag$).toHaveBeenCalledWith(FeatureFlag.AutoConfirm);
|
||||
});
|
||||
});
|
||||
|
||||
describe("autoConfirmUser", () => {
|
||||
const mockPublicKey = "mock-public-key-base64";
|
||||
const mockPublicKeyArray = new Uint8Array([1, 2, 3, 4]);
|
||||
const mockConfirmRequest = {
|
||||
key: "encrypted-key",
|
||||
defaultUserCollectionName: "encrypted-collection",
|
||||
} as OrganizationUserConfirmRequest;
|
||||
|
||||
beforeEach(() => {
|
||||
const organizations$ = new BehaviorSubject<Organization[]>([mockOrganization]);
|
||||
organizationService.organizations$.mockReturnValue(organizations$);
|
||||
configService.getFeatureFlag$.mockReturnValue(of(true));
|
||||
|
||||
apiService.getUserPublicKey.mockResolvedValue({ publicKey: mockPublicKey } as any);
|
||||
jest.spyOn(Utils, "fromB64ToArray").mockReturnValue(mockPublicKeyArray);
|
||||
organizationUserService.buildConfirmRequest.mockReturnValue(of(mockConfirmRequest));
|
||||
organizationUserApiService.postOrganizationUserConfirm.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("should successfully auto-confirm a user", async () => {
|
||||
await service.autoConfirmUser(mockUserId, mockConfirmingUserId, mockOrganization);
|
||||
|
||||
expect(apiService.getUserPublicKey).toHaveBeenCalledWith(mockUserId);
|
||||
expect(organizationUserService.buildConfirmRequest).toHaveBeenCalledWith(
|
||||
mockOrganization,
|
||||
mockPublicKeyArray,
|
||||
);
|
||||
expect(organizationUserApiService.postOrganizationUserConfirm).toHaveBeenCalledWith(
|
||||
mockOrganizationId,
|
||||
mockConfirmingUserId,
|
||||
mockConfirmRequest,
|
||||
);
|
||||
});
|
||||
|
||||
it("should not confirm user when canManageAutoConfirm returns false", async () => {
|
||||
configService.getFeatureFlag$.mockReturnValue(of(false));
|
||||
|
||||
await expect(
|
||||
service.autoConfirmUser(mockUserId, mockConfirmingUserId, mockOrganization),
|
||||
).rejects.toThrow("Cannot automatically confirm user (insufficient permissions)");
|
||||
|
||||
expect(apiService.getUserPublicKey).not.toHaveBeenCalled();
|
||||
expect(organizationUserApiService.postOrganizationUserConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should build confirm request with organization and public key", async () => {
|
||||
await service.autoConfirmUser(mockUserId, mockConfirmingUserId, mockOrganization);
|
||||
|
||||
expect(organizationUserService.buildConfirmRequest).toHaveBeenCalledWith(
|
||||
mockOrganization,
|
||||
mockPublicKeyArray,
|
||||
);
|
||||
});
|
||||
|
||||
it("should call API with correct parameters", async () => {
|
||||
await service.autoConfirmUser(mockUserId, mockConfirmingUserId, mockOrganization);
|
||||
|
||||
expect(organizationUserApiService.postOrganizationUserConfirm).toHaveBeenCalledWith(
|
||||
mockOrganization.id,
|
||||
mockConfirmingUserId,
|
||||
mockConfirmRequest,
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle API errors gracefully", async () => {
|
||||
const apiError = new Error("API Error");
|
||||
apiService.getUserPublicKey.mockRejectedValue(apiError);
|
||||
|
||||
await expect(
|
||||
service.autoConfirmUser(mockUserId, mockConfirmingUserId, mockOrganization),
|
||||
).rejects.toThrow("API Error");
|
||||
|
||||
expect(organizationUserApiService.postOrganizationUserConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should handle buildConfirmRequest errors gracefully", async () => {
|
||||
const buildError = new Error("Build Error");
|
||||
organizationUserService.buildConfirmRequest.mockReturnValue(throwError(() => buildError));
|
||||
|
||||
await expect(
|
||||
service.autoConfirmUser(mockUserId, mockConfirmingUserId, mockOrganization),
|
||||
).rejects.toThrow("Build Error");
|
||||
|
||||
expect(organizationUserApiService.postOrganizationUserConfirm).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { combineLatest, firstValueFrom, map, Observable, switchMap } from "rxjs";
|
||||
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { InternalOrganizationServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { getById } from "@bitwarden/common/platform/misc";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { StateProvider } from "@bitwarden/state";
|
||||
import { UserId } from "@bitwarden/user-core";
|
||||
|
||||
import {
|
||||
DefaultOrganizationUserService,
|
||||
OrganizationUserApiService,
|
||||
} from "../../organization-user";
|
||||
import { AutomaticUserConfirmationService } from "../abstractions/auto-confirm.service.abstraction";
|
||||
import { AUTO_CONFIRM_STATE, AutoConfirmState } from "../models/auto-confirm-state.model";
|
||||
|
||||
export class DefaultAutomaticUserConfirmationService implements AutomaticUserConfirmationService {
|
||||
constructor(
|
||||
private configService: ConfigService,
|
||||
private apiService: ApiService,
|
||||
private organizationUserService: DefaultOrganizationUserService,
|
||||
private stateProvider: StateProvider,
|
||||
private organizationService: InternalOrganizationServiceAbstraction,
|
||||
private organizationUserApiService: OrganizationUserApiService,
|
||||
) {}
|
||||
private autoConfirmState(userId: UserId) {
|
||||
return this.stateProvider.getUser(userId, AUTO_CONFIRM_STATE);
|
||||
}
|
||||
|
||||
configuration$(userId: UserId): Observable<AutoConfirmState> {
|
||||
return this.autoConfirmState(userId).state$.pipe(
|
||||
map((records) => records?.[userId] ?? new AutoConfirmState()),
|
||||
);
|
||||
}
|
||||
|
||||
async upsert(userId: UserId, config: AutoConfirmState): Promise<void> {
|
||||
await this.autoConfirmState(userId).update((records) => {
|
||||
return {
|
||||
...records,
|
||||
[userId]: config,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
canManageAutoConfirm$(userId: UserId, organizationId: OrganizationId): Observable<boolean> {
|
||||
return combineLatest([
|
||||
this.configService.getFeatureFlag$(FeatureFlag.AutoConfirm),
|
||||
this.organizationService.organizations$(userId).pipe(getById(organizationId)),
|
||||
]).pipe(
|
||||
map(
|
||||
([enabled, organization]) =>
|
||||
(enabled && organization?.canManageUsers && organization?.useAutomaticUserConfirmation) ??
|
||||
false,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async autoConfirmUser(
|
||||
userId: UserId,
|
||||
confirmingUserId: UserId,
|
||||
organization: Organization,
|
||||
): Promise<void> {
|
||||
await firstValueFrom(
|
||||
this.canManageAutoConfirm$(userId, organization.id).pipe(
|
||||
map((canManage) => {
|
||||
if (!canManage) {
|
||||
throw new Error("Cannot automatically confirm user (insufficient permissions)");
|
||||
}
|
||||
return canManage;
|
||||
}),
|
||||
switchMap(() => this.apiService.getUserPublicKey(userId)),
|
||||
map((publicKeyResponse) => Utils.fromB64ToArray(publicKeyResponse.publicKey)),
|
||||
switchMap((publicKey) =>
|
||||
this.organizationUserService.buildConfirmRequest(organization, publicKey),
|
||||
),
|
||||
switchMap((request) =>
|
||||
this.organizationUserApiService.postOrganizationUserConfirm(
|
||||
organization.id,
|
||||
confirmingUserId,
|
||||
request,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./default-auto-confirm.service";
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./organization-user";
|
||||
export * from "./auto-confirm";
|
||||
export * from "./collections";
|
||||
export * from "./organization-user";
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export * from "./organization-user-api.service";
|
||||
export * from "./organization-user.service";
|
||||
|
||||
@@ -148,6 +148,19 @@ export abstract class OrganizationUserApiService {
|
||||
request: OrganizationUserConfirmRequest,
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Admin api for automatically confirming an organization user that
|
||||
* has accepted their invitation
|
||||
* @param organizationId - Identifier for the organization to confirm
|
||||
* @param id - Organization user identifier
|
||||
* @param request - Request details for confirming the user
|
||||
*/
|
||||
abstract postOrganizationUserAutoConfirm(
|
||||
organizationId: string,
|
||||
id: string,
|
||||
request: OrganizationUserConfirmRequest,
|
||||
): Promise<void>;
|
||||
|
||||
/**
|
||||
* Retrieve a list of the specified users' public keys
|
||||
* @param organizationId - Identifier for the organization to accept
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Observable } from "rxjs";
|
||||
|
||||
import {
|
||||
OrganizationUserConfirmRequest,
|
||||
OrganizationUserBulkResponse,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { ListResponse } from "@bitwarden/common/models/response/list.response";
|
||||
|
||||
export abstract class OrganizationUserService {
|
||||
/**
|
||||
* Builds a confirmation request for an organization user.
|
||||
* @param organization - The organization the user belongs to
|
||||
* @param publicKey - The user's public key
|
||||
* @returns An observable that emits the confirmation request
|
||||
*/
|
||||
abstract buildConfirmRequest(
|
||||
organization: Organization,
|
||||
publicKey: Uint8Array,
|
||||
): Observable<OrganizationUserConfirmRequest>;
|
||||
|
||||
/**
|
||||
* Confirms a user in an organization.
|
||||
* @param organization - The organization the user belongs to
|
||||
* @param userId - The ID of the user to confirm
|
||||
* @param publicKey - The user's public key
|
||||
* @returns An observable that completes when the user is confirmed
|
||||
*/
|
||||
abstract confirmUser(
|
||||
organization: Organization,
|
||||
userId: string,
|
||||
publicKey: Uint8Array,
|
||||
): Observable<void>;
|
||||
|
||||
/**
|
||||
* Confirms multiple users in an organization.
|
||||
* @param organization - The organization the users belong to
|
||||
* @param userIdsWithKeys - Array of user IDs with their encrypted keys
|
||||
* @returns An observable that emits the bulk confirmation response
|
||||
*/
|
||||
abstract bulkConfirmUsers(
|
||||
organization: Organization,
|
||||
userIdsWithKeys: { id: string; key: string }[],
|
||||
): Observable<ListResponse<OrganizationUserBulkResponse>>;
|
||||
}
|
||||
@@ -194,6 +194,20 @@ export class DefaultOrganizationUserApiService implements OrganizationUserApiSer
|
||||
);
|
||||
}
|
||||
|
||||
postOrganizationUserAutoConfirm(
|
||||
organizationId: string,
|
||||
id: string,
|
||||
request: OrganizationUserConfirmRequest,
|
||||
): Promise<void> {
|
||||
return this.apiService.send(
|
||||
"POST",
|
||||
"/organizations/" + organizationId + "/users/" + id + "/auto-confirm",
|
||||
request,
|
||||
true,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
async postOrganizationUsersPublicKey(
|
||||
organizationId: string,
|
||||
ids: string[],
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { TestBed } from "@angular/core/testing";
|
||||
import { of } from "rxjs";
|
||||
|
||||
import {
|
||||
OrganizationUserConfirmRequest,
|
||||
OrganizationUserBulkConfirmRequest,
|
||||
OrganizationUserApiService,
|
||||
OrganizationUserBulkResponse,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
|
||||
import { EncString } from "@bitwarden/common/key-management/crypto/models/enc-string";
|
||||
import { ListResponse } from "@bitwarden/common/models/response/list.response";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { CsprngArray } from "@bitwarden/common/types/csprng";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { OrgKey } from "@bitwarden/common/types/key";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
|
||||
import { DefaultOrganizationUserService } from "./default-organization-user.service";
|
||||
|
||||
describe("DefaultOrganizationUserService", () => {
|
||||
let service: DefaultOrganizationUserService;
|
||||
let keyService: jest.Mocked<KeyService>;
|
||||
let encryptService: jest.Mocked<EncryptService>;
|
||||
let organizationUserApiService: jest.Mocked<OrganizationUserApiService>;
|
||||
let accountService: jest.Mocked<AccountService>;
|
||||
let i18nService: jest.Mocked<I18nService>;
|
||||
|
||||
const mockOrganization = new Organization();
|
||||
mockOrganization.id = "org-123" as OrganizationId;
|
||||
|
||||
const mockUserId = "user-123";
|
||||
const mockPublicKey = new Uint8Array(64) as CsprngArray;
|
||||
const mockRandomBytes = new Uint8Array(64) as CsprngArray;
|
||||
const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey;
|
||||
const mockEncryptedKey = { encryptedString: "encrypted-key" } as EncString;
|
||||
const mockEncryptedCollectionName = { encryptedString: "encrypted-collection-name" } as EncString;
|
||||
const mockDefaultCollectionName = "My Items";
|
||||
|
||||
const setupCommonMocks = () => {
|
||||
keyService.orgKeys$.mockReturnValue(
|
||||
of({ [mockOrganization.id]: mockOrgKey } as Record<OrganizationId, OrgKey>),
|
||||
);
|
||||
encryptService.encryptString.mockResolvedValue(mockEncryptedCollectionName);
|
||||
i18nService.t.mockReturnValue(mockDefaultCollectionName);
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
keyService = {
|
||||
orgKeys$: jest.fn(),
|
||||
} as any;
|
||||
|
||||
encryptService = {
|
||||
encryptString: jest.fn(),
|
||||
encapsulateKeyUnsigned: jest.fn(),
|
||||
} as any;
|
||||
|
||||
organizationUserApiService = {
|
||||
postOrganizationUserConfirm: jest.fn(),
|
||||
postOrganizationUserBulkConfirm: jest.fn(),
|
||||
} as any;
|
||||
|
||||
accountService = {
|
||||
activeAccount$: of({ id: "user-123" }),
|
||||
} as any;
|
||||
|
||||
i18nService = {
|
||||
t: jest.fn(),
|
||||
} as any;
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
DefaultOrganizationUserService,
|
||||
{ provide: KeyService, useValue: keyService },
|
||||
{ provide: EncryptService, useValue: encryptService },
|
||||
{ provide: OrganizationUserApiService, useValue: organizationUserApiService },
|
||||
{ provide: AccountService, useValue: accountService },
|
||||
{ provide: I18nService, useValue: i18nService },
|
||||
],
|
||||
});
|
||||
|
||||
service = new DefaultOrganizationUserService(
|
||||
keyService,
|
||||
encryptService,
|
||||
organizationUserApiService,
|
||||
accountService,
|
||||
i18nService,
|
||||
);
|
||||
});
|
||||
|
||||
describe("confirmUser", () => {
|
||||
beforeEach(() => {
|
||||
setupCommonMocks();
|
||||
encryptService.encapsulateKeyUnsigned.mockResolvedValue(mockEncryptedKey);
|
||||
organizationUserApiService.postOrganizationUserConfirm.mockReturnValue(Promise.resolve());
|
||||
});
|
||||
|
||||
it("should confirm a user successfully", (done) => {
|
||||
service.confirmUser(mockOrganization, mockUserId, mockPublicKey).subscribe({
|
||||
next: () => {
|
||||
expect(i18nService.t).toHaveBeenCalledWith("myItems");
|
||||
|
||||
expect(encryptService.encryptString).toHaveBeenCalledWith(
|
||||
mockDefaultCollectionName,
|
||||
mockOrgKey,
|
||||
);
|
||||
expect(encryptService.encapsulateKeyUnsigned).toHaveBeenCalledWith(
|
||||
mockOrgKey,
|
||||
mockPublicKey,
|
||||
);
|
||||
|
||||
expect(organizationUserApiService.postOrganizationUserConfirm).toHaveBeenCalledWith(
|
||||
mockOrganization.id,
|
||||
mockUserId,
|
||||
{
|
||||
key: mockEncryptedKey.encryptedString,
|
||||
defaultUserCollectionName: mockEncryptedCollectionName.encryptedString,
|
||||
} as OrganizationUserConfirmRequest,
|
||||
);
|
||||
|
||||
done();
|
||||
},
|
||||
error: done,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("bulkConfirmUsers", () => {
|
||||
const mockUserIdsWithKeys = [
|
||||
{ id: "user-1", key: "key-1" },
|
||||
{ id: "user-2", key: "key-2" },
|
||||
];
|
||||
|
||||
const mockBulkResponse = {
|
||||
data: [
|
||||
{ id: "user-1", error: null } as OrganizationUserBulkResponse,
|
||||
{ id: "user-2", error: null } as OrganizationUserBulkResponse,
|
||||
],
|
||||
} as ListResponse<OrganizationUserBulkResponse>;
|
||||
|
||||
beforeEach(() => {
|
||||
setupCommonMocks();
|
||||
organizationUserApiService.postOrganizationUserBulkConfirm.mockReturnValue(
|
||||
Promise.resolve(mockBulkResponse),
|
||||
);
|
||||
});
|
||||
|
||||
it("should bulk confirm users successfully", (done) => {
|
||||
service.bulkConfirmUsers(mockOrganization, mockUserIdsWithKeys).subscribe({
|
||||
next: (response) => {
|
||||
expect(i18nService.t).toHaveBeenCalledWith("myItems");
|
||||
|
||||
expect(encryptService.encryptString).toHaveBeenCalledWith(
|
||||
mockDefaultCollectionName,
|
||||
mockOrgKey,
|
||||
);
|
||||
|
||||
expect(organizationUserApiService.postOrganizationUserBulkConfirm).toHaveBeenCalledWith(
|
||||
mockOrganization.id,
|
||||
new OrganizationUserBulkConfirmRequest(
|
||||
mockUserIdsWithKeys,
|
||||
mockEncryptedCollectionName.encryptedString,
|
||||
),
|
||||
);
|
||||
|
||||
expect(response).toEqual(mockBulkResponse);
|
||||
|
||||
done();
|
||||
},
|
||||
error: done,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { combineLatest, filter, map, Observable, switchMap } from "rxjs";
|
||||
|
||||
import {
|
||||
OrganizationUserConfirmRequest,
|
||||
OrganizationUserBulkConfirmRequest,
|
||||
OrganizationUserApiService,
|
||||
OrganizationUserBulkResponse,
|
||||
OrganizationUserService,
|
||||
} from "@bitwarden/admin-console/common";
|
||||
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
|
||||
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { getUserId } from "@bitwarden/common/auth/services/account.service";
|
||||
import { EncryptService } from "@bitwarden/common/key-management/crypto/abstractions/encrypt.service";
|
||||
import { ListResponse } from "@bitwarden/common/models/response/list.response";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { OrganizationId } from "@bitwarden/common/types/guid";
|
||||
import { KeyService } from "@bitwarden/key-management";
|
||||
|
||||
export class DefaultOrganizationUserService implements OrganizationUserService {
|
||||
constructor(
|
||||
protected keyService: KeyService,
|
||||
private encryptService: EncryptService,
|
||||
private organizationUserApiService: OrganizationUserApiService,
|
||||
private accountService: AccountService,
|
||||
private i18nService: I18nService,
|
||||
) {}
|
||||
|
||||
private orgKey$(organization: Organization) {
|
||||
return this.accountService.activeAccount$.pipe(
|
||||
getUserId,
|
||||
switchMap((userId) => this.keyService.orgKeys$(userId)),
|
||||
filter((orgKeys) => !!orgKeys),
|
||||
map((organizationKeysById) => organizationKeysById[organization.id as OrganizationId]),
|
||||
);
|
||||
}
|
||||
|
||||
buildConfirmRequest(
|
||||
organization: Organization,
|
||||
publicKey: Uint8Array,
|
||||
): Observable<OrganizationUserConfirmRequest> {
|
||||
const encryptedCollectionName$ = this.getEncryptedDefaultCollectionName$(organization);
|
||||
|
||||
const encryptedKey$ = this.orgKey$(organization).pipe(
|
||||
switchMap((orgKey) => this.encryptService.encapsulateKeyUnsigned(orgKey, publicKey)),
|
||||
);
|
||||
|
||||
return combineLatest([encryptedKey$, encryptedCollectionName$]).pipe(
|
||||
map(([key, collectionName]) => ({
|
||||
key: key.encryptedString,
|
||||
defaultUserCollectionName: collectionName.encryptedString,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
confirmUser(organization: Organization, userId: string, publicKey: Uint8Array): Observable<void> {
|
||||
return this.buildConfirmRequest(organization, publicKey).pipe(
|
||||
switchMap((request) =>
|
||||
this.organizationUserApiService.postOrganizationUserConfirm(
|
||||
organization.id,
|
||||
userId,
|
||||
request,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bulkConfirmUsers(
|
||||
organization: Organization,
|
||||
userIdsWithKeys: { id: string; key: string }[],
|
||||
): Observable<ListResponse<OrganizationUserBulkResponse>> {
|
||||
return this.getEncryptedDefaultCollectionName$(organization).pipe(
|
||||
switchMap((collectionName) => {
|
||||
const request = new OrganizationUserBulkConfirmRequest(
|
||||
userIdsWithKeys,
|
||||
collectionName.encryptedString,
|
||||
);
|
||||
|
||||
return this.organizationUserApiService.postOrganizationUserBulkConfirm(
|
||||
organization.id,
|
||||
request,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private getEncryptedDefaultCollectionName$(organization: Organization) {
|
||||
return this.orgKey$(organization).pipe(
|
||||
switchMap((orgKey) =>
|
||||
this.encryptService.encryptString(this.i18nService.t("myItems"), orgKey),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1 +1,2 @@
|
||||
export * from "./default-organization-user-api.service";
|
||||
export * from "./default-organization-user.service";
|
||||
|
||||
Reference in New Issue
Block a user