1
0
mirror of https://github.com/bitwarden/browser synced 2024-12-24 00:54:30 +01:00
bitwarden-estensione-browser/libs/common/spec/services/policy.service.spec.ts
Shane Melton 07c2c2af20
[AC-1070] Enforce master password policy on login (#4795)
* [EC-1070] Introduce flag for enforcing master password policy on login

* [EC-1070] Update master password policy form

Add the ability to toggle enforceOnLogin flag in web

* [EC-1070] Add API method to retrieve all policies for the current user

* [EC-1070] Refactor forcePasswordReset in state service to support more options

- Use an options class to provide a reason and optional organization id
- Use the OnDiskMemory storage location so the option persists between the same auth session

* [AC-1070] Retrieve single master password policy from identity token response

Additionally, store the policy in the login strategy for future use

* [EC-1070] Introduce master password evaluation in the password login strategy

- If a master password policy is returned from the identity result, evaluate the password.
- If the password does not meet the requirements, save the forcePasswordReset options
- Add support for 2FA by storing the results of the password evaluation on the login strategy instance
- Add unit tests to password login strategy

* [AC-1070] Modify admin password reset component to support update master password on login

- Modify the warning message to depend on the reason

- Use the forcePasswordResetOptions in the update temp password component

* [EC-1070] Require current master password when updating weak mp on login

- Inject user verification service to verify the user
- Conditionally show the current master password field only when updating a weak mp. Admin reset does not require the current master password.

* [EC-1070] Implement password policy check during vault unlock

Checking the master password during unlock is the only applicable place to enforce the master password policy check for SSO users.

* [EC-1070] CLI - Add ability to load MP policies on login

Inject policyApi and organization services into the login command

* [EC-1070] CLI - Refactor update temp password logic to support updating weak passwords

- Introduce new shared method for collecting a valid and confirmed master password from the CLI and generating a new encryption key
- Add separate methods for updating temp passwords and weak passwords.
- Utilize those methods during login flow if not using an API key

* [EC-1070] Add route guard to force password reset when required

* [AC-1070] Use master password policy from verify password response in lock component

* [EC-1070] Update labels in update password component

* [AC-1070] Fix policy service tests

* [AC-1070] CLI - Force sync before any password reset flow

Move up the call to sync the vault before attempting to collect a new master password. Ensures the master password policies are available.

* [AC-1070] Remove unused getAllPolicies method from policy api service

* [AC-1070] Fix missing enforceOnLogin copy in policy service

* [AC-1070] Include current master password on desktop/browser update password page templates

* [AC-1070] Check for forced password reset on account switch in Desktop

* [AC-1070] Rename WeakMasterPasswordOnLogin to WeakMasterPassword

* [AC-1070] Update AuthServiceInitOptions

* [AC-1070] Add None force reset password reason

* [AC-1070] Remove redundant ForcePasswordResetOptions class and replace with ForcePasswordResetReason enum

* [AC-1070] Rename ForceResetPasswordReason file

* [AC-1070] Simplify conditional

* [AC-1070] Refactor logic that saves password reset flag

* [AC-1070] Remove redundant constructors

* [AC-1070] Remove unnecessary state service call

* [AC-1070] Update master password policy component

- Use typed reactive form
- Use CL form components
- Remove bootstrap
- Update error component to support min/max
- Use Utils.minimumPasswordLength value for min value form validation

* [AC-1070] Cleanup leftover html comment

* [AC-1070] Remove overridden default values from MasterPasswordPolicyResponse

* [AC-1070] Hide current master password input in browser for admin password reset

* [AC-1070] Remove clientside user verification

* [AC-1070] Update temp password web component to use CL

- Use CL for form inputs in the Web component template
- Remove most of the bootstrap classes in the Web component template
- Use userVerificationService to build the password request
- Remove redundant current master password null check

* [AC-1070] Replace repeated user inputs email parsing helpers

- Update passwordStrength() method to accept an optional email argument that will be parsed into separate user inputs for use with zxcvbn
- Remove all other repeated getUserInput helper methods that parsed user emails and use the new passwordStrength signature

* [AC-1070] Fix broken login command after forcePasswordReset enum refactor

* [AC-1070] Reduce side effects in base login strategy

- Remove masterPasswordPolicy property from base login.strategy.ts
- Include an IdentityResponse in base startLogin() in addition to AuthResult
- Use the new IdentityResponse to parse the master password policy info only in the PasswordLoginStrategy

* [AC-1070] Cleanup password login strategy tests

* [AC-1070] Remove unused field

* [AC-1070] Strongly type postAccountVerifyPassword API service method

- Remove redundant verify master password response
- Use MasterPasswordPolicyResponse instead

* [AC-1070] Use ForceResetPassword.None during account switch check

* [AC-1070] Fix check for forcePasswordReset reason after addition of None

* [AC-1070] Redirect a user home if on the update temp password page without a reason

* [AC-1070] Use bit-select and bit-option

* [AC-1070] Reduce explicit form control definitions for readability

* [AC-1070] Import SelectModule in Shared web module

* [AC-1070] Add check for missing 'at' symbol

* [AC-1070] Remove redundant unpacking and null coalescing

* [AC-1070] Update passwordStrength signature and add jsdocs

* [AC-1070] Remove variable abbreviation

* [AC-1070] Restore Id attributes on form inputs

* [AC-1070] Clarify input value min/max error messages

* [AC-1070] Add input min/max value example to storybook

* [AC-1070] Add missing spinner to update temp password form

* [AC-1070] Add missing ids to form elements

* [AC-1070] Remove duplicate force sync and update comment

* [AC-1070] Switch backticks to quotation marks

---------

Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2023-04-17 07:35:37 -07:00

415 lines
13 KiB
TypeScript

// eslint-disable-next-line no-restricted-imports
import { Arg, Substitute, SubstituteOf } from "@fluffy-spoon/substitute";
import { BehaviorSubject, firstValueFrom } from "rxjs";
import { CryptoService } from "@bitwarden/common/abstractions/crypto.service";
import { EncryptService } from "@bitwarden/common/abstractions/encrypt.service";
import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction";
import { OrganizationUserStatusType, PolicyType } from "@bitwarden/common/admin-console/enums";
import { PermissionsApi } from "@bitwarden/common/admin-console/models/api/permissions.api";
import { OrganizationData } from "@bitwarden/common/admin-console/models/data/organization.data";
import { PolicyData } from "@bitwarden/common/admin-console/models/data/policy.data";
import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/models/domain/master-password-policy-options";
import { Organization } from "@bitwarden/common/admin-console/models/domain/organization";
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
import { ResetPasswordPolicyOptions } from "@bitwarden/common/admin-console/models/domain/reset-password-policy-options";
import { PolicyResponse } from "@bitwarden/common/admin-console/models/response/policy.response";
import { PolicyService } from "@bitwarden/common/admin-console/services/policy/policy.service";
import { ListResponse } from "@bitwarden/common/models/response/list.response";
import { ContainerService } from "@bitwarden/common/services/container.service";
import { StateService } from "@bitwarden/common/services/state.service";
describe("PolicyService", () => {
let policyService: PolicyService;
let cryptoService: SubstituteOf<CryptoService>;
let stateService: SubstituteOf<StateService>;
let organizationService: SubstituteOf<OrganizationService>;
let encryptService: SubstituteOf<EncryptService>;
let activeAccount: BehaviorSubject<string>;
let activeAccountUnlocked: BehaviorSubject<boolean>;
beforeEach(() => {
stateService = Substitute.for();
organizationService = Substitute.for();
organizationService
.getAll("user")
.resolves([
new Organization(
organizationData(
"test-organization",
true,
true,
OrganizationUserStatusType.Accepted,
false
)
),
]);
organizationService.getAll(undefined).resolves([]);
organizationService.getAll(null).resolves([]);
activeAccount = new BehaviorSubject("123");
activeAccountUnlocked = new BehaviorSubject(true);
stateService.getDecryptedPolicies({ userId: "user" }).resolves(null);
stateService.getEncryptedPolicies({ userId: "user" }).resolves({
"1": policyData("1", "test-organization", PolicyType.MaximumVaultTimeout, true, {
minutes: 14,
}),
});
stateService.getEncryptedPolicies().resolves({
"1": policyData("1", "test-organization", PolicyType.MaximumVaultTimeout, true, {
minutes: 14,
}),
});
stateService.activeAccount$.returns(activeAccount);
stateService.activeAccountUnlocked$.returns(activeAccountUnlocked);
stateService.getUserId().resolves("user");
(window as any).bitwardenContainerService = new ContainerService(cryptoService, encryptService);
policyService = new PolicyService(stateService, organizationService);
});
afterEach(() => {
activeAccount.complete();
activeAccountUnlocked.complete();
});
it("upsert", async () => {
await policyService.upsert(policyData("99", "test-organization", PolicyType.DisableSend, true));
expect(await firstValueFrom(policyService.policies$)).toEqual([
{
id: "1",
organizationId: "test-organization",
type: PolicyType.MaximumVaultTimeout,
enabled: true,
data: { minutes: 14 },
},
{
id: "99",
organizationId: "test-organization",
type: PolicyType.DisableSend,
enabled: true,
},
]);
});
it("replace", async () => {
await policyService.replace({
"2": policyData("2", "test-organization", PolicyType.DisableSend, true),
});
expect(await firstValueFrom(policyService.policies$)).toEqual([
{
id: "2",
organizationId: "test-organization",
type: PolicyType.DisableSend,
enabled: true,
},
]);
});
it("locking should clear", async () => {
activeAccountUnlocked.next(false);
// Sleep for 100ms to avoid timing issues
await new Promise((r) => setTimeout(r, 100));
expect((await firstValueFrom(policyService.policies$)).length).toBe(0);
});
describe("clear", () => {
it("null userId", async () => {
await policyService.clear();
stateService.received(1).setEncryptedPolicies(Arg.any(), Arg.any());
expect((await firstValueFrom(policyService.policies$)).length).toBe(0);
});
it("matching userId", async () => {
await policyService.clear("user");
stateService.received(1).setEncryptedPolicies(Arg.any(), Arg.any());
expect((await firstValueFrom(policyService.policies$)).length).toBe(0);
});
it("mismatching userId", async () => {
await policyService.clear("12");
stateService.received(1).setEncryptedPolicies(Arg.any(), Arg.any());
expect((await firstValueFrom(policyService.policies$)).length).toBe(1);
});
});
describe("masterPasswordPolicyOptions", () => {
it("returns default policy options", async () => {
const data: any = {
minComplexity: 5,
minLength: 20,
requireUpper: true,
};
const model = [
new Policy(policyData("1", "test-organization-3", PolicyType.MasterPassword, true, data)),
];
const result = await firstValueFrom(policyService.masterPasswordPolicyOptions$(model));
expect(result).toEqual({
minComplexity: 5,
minLength: 20,
requireLower: false,
requireNumbers: false,
requireSpecial: false,
requireUpper: true,
enforceOnLogin: false,
});
});
it("returns null", async () => {
const data: any = {};
const model = [
new Policy(
policyData("3", "test-organization-3", PolicyType.DisablePersonalVaultExport, true, data)
),
new Policy(
policyData("4", "test-organization-3", PolicyType.MaximumVaultTimeout, true, data)
),
];
const result = await firstValueFrom(policyService.masterPasswordPolicyOptions$(model));
expect(result).toEqual(null);
});
it("returns specified policy options", async () => {
const data: any = {
minLength: 14,
};
const model = [
new Policy(
policyData("3", "test-organization-3", PolicyType.DisablePersonalVaultExport, true, data)
),
new Policy(policyData("4", "test-organization-3", PolicyType.MasterPassword, true, data)),
];
const result = await firstValueFrom(policyService.masterPasswordPolicyOptions$(model));
expect(result).toEqual({
minComplexity: 0,
minLength: 14,
requireLower: false,
requireNumbers: false,
requireSpecial: false,
requireUpper: false,
enforceOnLogin: false,
});
});
});
describe("evaluateMasterPassword", () => {
it("false", async () => {
const enforcedPolicyOptions = new MasterPasswordPolicyOptions();
enforcedPolicyOptions.minLength = 14;
const result = policyService.evaluateMasterPassword(10, "password", enforcedPolicyOptions);
expect(result).toEqual(false);
});
it("true", async () => {
const enforcedPolicyOptions = new MasterPasswordPolicyOptions();
const result = policyService.evaluateMasterPassword(0, "password", enforcedPolicyOptions);
expect(result).toEqual(true);
});
});
describe("getResetPasswordPolicyOptions", () => {
it("default", async () => {
const result = policyService.getResetPasswordPolicyOptions(null, null);
expect(result).toEqual([new ResetPasswordPolicyOptions(), false]);
});
it("returns autoEnrollEnabled true", async () => {
const data: any = {
autoEnrollEnabled: true,
};
const policies = [
new Policy(policyData("5", "test-organization-3", PolicyType.ResetPassword, true, data)),
];
const result = policyService.getResetPasswordPolicyOptions(policies, "test-organization-3");
expect(result).toEqual([{ autoEnrollEnabled: true }, true]);
});
});
describe("mapPoliciesFromToken", () => {
it("null", async () => {
const result = policyService.mapPoliciesFromToken(null);
expect(result).toEqual(null);
});
it("null data", async () => {
const model = new ListResponse(null, PolicyResponse);
model.data = null;
const result = policyService.mapPoliciesFromToken(model);
expect(result).toEqual(null);
});
it("empty array", async () => {
const model = new ListResponse(null, PolicyResponse);
const result = policyService.mapPoliciesFromToken(model);
expect(result).toEqual([]);
});
it("success", async () => {
const policyResponse: any = {
Data: [
{
Id: "1",
OrganizationId: "organization-1",
Type: PolicyType.DisablePersonalVaultExport,
Enabled: true,
Data: { requireUpper: true },
},
{
Id: "2",
OrganizationId: "organization-2",
Type: PolicyType.DisableSend,
Enabled: false,
Data: { minComplexity: 5, minLength: 20 },
},
],
};
const model = new ListResponse(policyResponse, PolicyResponse);
const result = policyService.mapPoliciesFromToken(model);
expect(result).toEqual([
new Policy(
policyData("1", "organization-1", PolicyType.DisablePersonalVaultExport, true, {
requireUpper: true,
})
),
new Policy(
policyData("2", "organization-2", PolicyType.DisableSend, false, {
minComplexity: 5,
minLength: 20,
})
),
]);
});
});
describe("policyAppliesToActiveUser$", () => {
it("MasterPassword does not apply", async () => {
const result = await firstValueFrom(
policyService.policyAppliesToActiveUser$(PolicyType.MasterPassword)
);
expect(result).toEqual(false);
});
it("MaximumVaultTimeout applies", async () => {
const result = await firstValueFrom(
policyService.policyAppliesToActiveUser$(PolicyType.MaximumVaultTimeout)
);
expect(result).toEqual(true);
});
it("PolicyFilter filters result", async () => {
const result = await firstValueFrom(
policyService.policyAppliesToActiveUser$(PolicyType.MaximumVaultTimeout, (p) => false)
);
expect(result).toEqual(false);
});
it("DisablePersonalVaultExport does not apply", async () => {
const result = await firstValueFrom(
policyService.policyAppliesToActiveUser$(PolicyType.DisablePersonalVaultExport)
);
expect(result).toEqual(false);
});
});
describe("policyAppliesToUser", () => {
it("MasterPassword does not apply", async () => {
const result = await policyService.policyAppliesToUser(
PolicyType.MasterPassword,
null,
"user"
);
expect(result).toEqual(false);
});
it("MaximumVaultTimeout applies", async () => {
const result = await policyService.policyAppliesToUser(
PolicyType.MaximumVaultTimeout,
null,
"user"
);
expect(result).toEqual(true);
});
it("PolicyFilter filters result", async () => {
const result = await policyService.policyAppliesToUser(
PolicyType.MaximumVaultTimeout,
(p) => false,
"user"
);
expect(result).toEqual(false);
});
it("DisablePersonalVaultExport does not apply", async () => {
const result = await policyService.policyAppliesToUser(
PolicyType.DisablePersonalVaultExport,
null,
"user"
);
expect(result).toEqual(false);
});
});
function policyData(
id: string,
organizationId: string,
type: PolicyType,
enabled: boolean,
data?: any
) {
const policyData = new PolicyData({} as any);
policyData.id = id;
policyData.organizationId = organizationId;
policyData.type = type;
policyData.enabled = enabled;
policyData.data = data;
return policyData;
}
function organizationData(
id: string,
enabled: boolean,
usePolicies: boolean,
status: OrganizationUserStatusType,
managePolicies: boolean
) {
const organizationData = new OrganizationData({} as any, {} as any);
organizationData.id = id;
organizationData.enabled = enabled;
organizationData.usePolicies = usePolicies;
organizationData.status = status;
organizationData.permissions = new PermissionsApi({ managePolicies: managePolicies } as any);
return organizationData;
}
});