[PS-1265] fix on install hook (#3278)

* Create service factories

* Add onInstall hook to service worker

* Add factory helper and common options structure

* Use factories in main.background

* simplify common factory options

* Split factory service cache and options.

Improve factory method base type handling.

* Add dev flag for managed environment.
This commit is contained in:
Matt Gibson 2022-08-18 08:23:16 -06:00 committed by GitHub
parent 89b69f4bc6
commit 179a3b3726
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 448 additions and 52 deletions

View File

@ -1,6 +1,9 @@
{
"devFlags": {
"storeSessionDecrypted": false
"storeSessionDecrypted": false,
"managedEnvironment": {
"base": "https://localhost:8080"
}
},
"flags": {}
}

View File

@ -1,10 +1,12 @@
import MainBackground from "./background/main.background";
import { onCommandListener } from "./listeners/onCommandListener";
import { onInstallListener } from "./listeners/onInstallListener";
const manifest = chrome.runtime.getManifest();
if (manifest.manifest_version === 3) {
chrome.commands.onCommand.addListener(onCommandListener);
chrome.runtime.onInstalled.addListener(onInstallListener);
} else {
const bitwardenMain = ((window as any).bitwardenMain = new MainBackground());
bitwardenMain.bootstrap().then(() => {

View File

@ -47,7 +47,6 @@ import { AuditService } from "@bitwarden/common/services/audit.service";
import { AuthService } from "@bitwarden/common/services/auth.service";
import { CipherService } from "@bitwarden/common/services/cipher.service";
import { CollectionService } from "@bitwarden/common/services/collection.service";
import { ConsoleLogService } from "@bitwarden/common/services/consoleLog.service";
import { ContainerService } from "@bitwarden/common/services/container.service";
import { EncryptService } from "@bitwarden/common/services/encrypt.service";
import { EventService } from "@bitwarden/common/services/event.service";
@ -55,7 +54,6 @@ import { ExportService } from "@bitwarden/common/services/export.service";
import { FileUploadService } from "@bitwarden/common/services/fileUpload.service";
import { FolderApiService } from "@bitwarden/common/services/folder/folder-api.service";
import { KeyConnectorService } from "@bitwarden/common/services/keyConnector.service";
import { MemoryStorageService } from "@bitwarden/common/services/memoryStorage.service";
import { NotificationsService } from "@bitwarden/common/services/notifications.service";
import { OrganizationService } from "@bitwarden/common/services/organization.service";
import { PasswordGenerationService } from "@bitwarden/common/services/passwordGeneration.service";
@ -74,7 +72,6 @@ import { TwoFactorService } from "@bitwarden/common/services/twoFactor.service";
import { UserVerificationApiService } from "@bitwarden/common/services/userVerification/userVerification-api.service";
import { UserVerificationService } from "@bitwarden/common/services/userVerification/userVerification.service";
import { UsernameGenerationService } from "@bitwarden/common/services/usernameGeneration.service";
import { WebCryptoFunctionService } from "@bitwarden/common/services/webCryptoFunction.service";
import { BrowserApi } from "../browser/browserApi";
import { SafariApp } from "../browser/safariApp";
@ -85,15 +82,11 @@ import { StateService as StateServiceAbstraction } from "../services/abstraction
import AutofillService from "../services/autofill.service";
import { BrowserEnvironmentService } from "../services/browser-environment.service";
import { BrowserCryptoService } from "../services/browserCrypto.service";
import BrowserLocalStorageService from "../services/browserLocalStorage.service";
import BrowserMessagingService from "../services/browserMessaging.service";
import BrowserMessagingPrivateModeBackgroundService from "../services/browserMessagingPrivateModeBackground.service";
import BrowserPlatformUtilsService from "../services/browserPlatformUtils.service";
import { FolderService } from "../services/folders/folder.service";
import I18nService from "../services/i18n.service";
import { KeyGenerationService } from "../services/keyGeneration.service";
import { LocalBackedSessionStorageService } from "../services/localBackedSessionStorage.service";
import { StateService } from "../services/state.service";
import { VaultFilterService } from "../services/vaultFilter.service";
import VaultTimeoutService from "../services/vaultTimeout.service";
@ -104,6 +97,17 @@ import IconDetails from "./models/iconDetails";
import { NativeMessagingBackground } from "./nativeMessaging.background";
import NotificationBackground from "./notification.background";
import RuntimeBackground from "./runtime.background";
import { cryptoFunctionServiceFactory } from "./service_factories/crypto-function-service.factory";
import { encryptServiceFactory } from "./service_factories/encrypt-service.factory";
import { environmentServiceFactory } from "./service_factories/environment-service.factory";
import { logServiceFactory } from "./service_factories/log-service.factory";
import { stateMigrationServiceFactory } from "./service_factories/state-migration-service.factory";
import { stateServiceFactory } from "./service_factories/state-service.factory";
import {
diskStorageServiceFactory,
memoryStorageServiceFactory,
secureStorageServiceFactory,
} from "./service_factories/storage-service.factory";
import TabsBackground from "./tabs.background";
import WebRequestBackground from "./webRequest.background";
@ -195,33 +199,40 @@ export default class MainBackground {
const logoutCallback = async (expired: boolean, userId?: string) =>
await this.logout(expired, userId);
const services: Record<string, unknown> = {};
const factoryOptions = {
logServiceOptions: {
isDev: false,
},
cryptoFunctionServiceOptions: {
win: window,
},
stateMigrationServiceOptions: {
stateFactory: new StateFactory(GlobalState, Account),
},
stateServiceOptions: {
stateFactory: new StateFactory(GlobalState, Account),
},
};
this.messagingService = isPrivateMode
? new BrowserMessagingPrivateModeBackgroundService()
: new BrowserMessagingService();
this.logService = new ConsoleLogService(false);
this.cryptoFunctionService = new WebCryptoFunctionService(window);
this.storageService = new BrowserLocalStorageService();
this.secureStorageService = new BrowserLocalStorageService();
this.memoryStorageService =
chrome.runtime.getManifest().manifest_version == 3
? new LocalBackedSessionStorageService(
new EncryptService(this.cryptoFunctionService, this.logService, false),
new KeyGenerationService(this.cryptoFunctionService)
)
: new MemoryStorageService();
this.stateMigrationService = new StateMigrationService(
this.storageService,
this.secureStorageService,
new StateFactory(GlobalState, Account)
);
this.stateService = new StateService(
this.storageService,
this.secureStorageService,
this.memoryStorageService,
this.logService,
this.stateMigrationService,
new StateFactory(GlobalState, Account)
);
this.logService = logServiceFactory(services, factoryOptions);
this.cryptoFunctionService = cryptoFunctionServiceFactory(services, factoryOptions);
this.storageService = diskStorageServiceFactory(services, factoryOptions);
this.secureStorageService = secureStorageServiceFactory(services, factoryOptions);
this.memoryStorageService = memoryStorageServiceFactory(services, {
...factoryOptions,
encryptServiceOptions: {
logMacFailures: false,
},
});
this.stateMigrationService = stateMigrationServiceFactory(services, factoryOptions);
this.stateService = stateServiceFactory(services, {
...factoryOptions,
encryptServiceOptions: { logMacFailures: false },
});
this.platformUtilsService = new BrowserPlatformUtilsService(
this.messagingService,
this.stateService,
@ -245,7 +256,13 @@ export default class MainBackground {
}
);
this.i18nService = new I18nService(BrowserApi.getUILanguage(window));
this.encryptService = new EncryptService(this.cryptoFunctionService, this.logService, true);
this.encryptService = encryptServiceFactory(services, {
...factoryOptions,
encryptServiceOptions: {
logMacFailures: true,
},
alwaysInitializeNewService: true,
}); // Update encrypt service with new instances
this.cryptoService = new BrowserCryptoService(
this.cryptoFunctionService,
this.encryptService,
@ -255,7 +272,12 @@ export default class MainBackground {
);
this.tokenService = new TokenService(this.stateService);
this.appIdService = new AppIdService(this.storageService);
this.environmentService = new BrowserEnvironmentService(this.stateService, this.logService);
this.environmentService = environmentServiceFactory(services, {
...factoryOptions,
encryptServiceOptions: {
logMacFailures: false,
},
});
this.apiService = new ApiService(
this.tokenService,
this.platformUtilsService,

View File

@ -0,0 +1,24 @@
import { CryptoFunctionService } from "@bitwarden/common/abstractions/cryptoFunction.service";
import { WebCryptoFunctionService } from "@bitwarden/common/services/webCryptoFunction.service";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
type CryptoFunctionServiceFactoryOptions = FactoryOptions & {
cryptoFunctionServiceOptions: {
win: Window | typeof global;
};
};
export type CryptoFunctionServiceInitOptions = CryptoFunctionServiceFactoryOptions;
export function cryptoFunctionServiceFactory(
cache: { cryptoFunctionService?: CryptoFunctionService } & CachedServices,
opts: CryptoFunctionServiceFactoryOptions
): CryptoFunctionService {
return factory(
cache,
"cryptoFunctionService",
opts,
() => new WebCryptoFunctionService(opts.cryptoFunctionServiceOptions.win)
);
}

View File

@ -0,0 +1,35 @@
import { EncryptService } from "@bitwarden/common/services/encrypt.service";
import {
cryptoFunctionServiceFactory,
CryptoFunctionServiceInitOptions,
} from "./crypto-function-service.factory";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
import { LogServiceInitOptions, logServiceFactory } from "./log-service.factory";
type EncryptServiceFactoryOptions = FactoryOptions & {
encryptServiceOptions: {
logMacFailures: boolean;
};
};
export type EncryptServiceInitOptions = EncryptServiceFactoryOptions &
CryptoFunctionServiceInitOptions &
LogServiceInitOptions;
export function encryptServiceFactory(
cache: { encryptService?: EncryptService } & CachedServices,
opts: EncryptServiceInitOptions
): EncryptService {
return factory(
cache,
"encryptService",
opts,
() =>
new EncryptService(
cryptoFunctionServiceFactory(cache, opts),
logServiceFactory(cache, opts),
opts.encryptServiceOptions.logMacFailures
)
);
}

View File

@ -0,0 +1,30 @@
import { BrowserEnvironmentService } from "../../services/browser-environment.service";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
import { logServiceFactory, LogServiceInitOptions } from "./log-service.factory";
import {
stateServiceFactory as stateServiceFactory,
StateServiceInitOptions,
} from "./state-service.factory";
type EnvironmentServiceFactoryOptions = FactoryOptions;
export type EnvironmentServiceInitOptions = EnvironmentServiceFactoryOptions &
StateServiceInitOptions &
LogServiceInitOptions;
export function environmentServiceFactory(
cache: { environmentService?: BrowserEnvironmentService } & CachedServices,
opts: EnvironmentServiceInitOptions
): BrowserEnvironmentService {
return factory(
cache,
"environmentService",
opts,
() =>
new BrowserEnvironmentService(
stateServiceFactory(cache, opts),
logServiceFactory(cache, opts)
)
);
}

View File

@ -0,0 +1,24 @@
export type CachedServices = Record<string, any>;
export type FactoryOptions = {
alwaysInitializeNewService?: boolean;
doNotStoreInitializedService?: boolean;
[optionsKey: string]: unknown;
};
export function factory<
TCache extends CachedServices,
TName extends keyof TCache,
TOpts extends FactoryOptions
>(cachedServices: TCache, name: TName, opts: TOpts, factory: () => TCache[TName]): TCache[TName] {
let instance = cachedServices[name];
if (opts.alwaysInitializeNewService || !instance) {
instance = factory();
}
if (!opts.doNotStoreInitializedService) {
cachedServices[name] = instance;
}
return instance as TCache[TName];
}

View File

@ -0,0 +1,24 @@
import { KeyGenerationService } from "../../services/keyGeneration.service";
import {
cryptoFunctionServiceFactory,
CryptoFunctionServiceInitOptions,
} from "./crypto-function-service.factory";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
type KeyGenerationServiceFactoryOptions = FactoryOptions;
export type KeyGenerationServiceInitOptions = KeyGenerationServiceFactoryOptions &
CryptoFunctionServiceInitOptions;
export function keyGenerationServiceFactory(
cache: { keyGenerationService?: KeyGenerationService } & CachedServices,
opts: KeyGenerationServiceInitOptions
): KeyGenerationService {
return factory(
cache,
"keyGenerationService",
opts,
() => new KeyGenerationService(cryptoFunctionServiceFactory(cache, opts))
);
}

View File

@ -0,0 +1,26 @@
import { LogService } from "@bitwarden/common/abstractions/log.service";
import { LogLevelType } from "@bitwarden/common/enums/logLevelType";
import { ConsoleLogService } from "@bitwarden/common/services/consoleLog.service";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
type LogServiceFactoryOptions = FactoryOptions & {
logServiceOptions: {
isDev: boolean;
filter?: (level: LogLevelType) => boolean;
};
};
export type LogServiceInitOptions = LogServiceFactoryOptions;
export function logServiceFactory(
cache: { logService?: LogService } & CachedServices,
opts: LogServiceInitOptions
): LogService {
return factory(
cache,
"logService",
opts,
() => new ConsoleLogService(opts.logServiceOptions.isDev, opts.logServiceOptions.filter)
);
}

View File

@ -0,0 +1,40 @@
import { StateFactory } from "@bitwarden/common/factories/stateFactory";
import { GlobalState } from "@bitwarden/common/models/domain/globalState";
import { StateMigrationService } from "@bitwarden/common/services/stateMigration.service";
import { Account } from "../../models/account";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
import {
diskStorageServiceFactory,
DiskStorageServiceInitOptions,
secureStorageServiceFactory,
SecureStorageServiceInitOptions,
} from "./storage-service.factory";
type StateMigrationServiceFactoryOptions = FactoryOptions & {
stateMigrationServiceOptions: {
stateFactory: StateFactory<GlobalState, Account>;
};
};
export type StateMigrationServiceInitOptions = StateMigrationServiceFactoryOptions &
DiskStorageServiceInitOptions &
SecureStorageServiceInitOptions;
export function stateMigrationServiceFactory(
cache: { stateMigrationService?: StateMigrationService } & CachedServices,
opts: StateMigrationServiceInitOptions
): StateMigrationService {
return factory(
cache,
"stateMigrationService",
opts,
() =>
new StateMigrationService(
diskStorageServiceFactory(cache, opts),
secureStorageServiceFactory(cache, opts),
opts.stateMigrationServiceOptions.stateFactory
)
);
}

View File

@ -0,0 +1,55 @@
import { StateFactory } from "@bitwarden/common/factories/stateFactory";
import { GlobalState } from "@bitwarden/common/models/domain/globalState";
import { Account } from "../../models/account";
import { StateService } from "../../services/state.service";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
import { logServiceFactory, LogServiceInitOptions } from "./log-service.factory";
import {
stateMigrationServiceFactory,
StateMigrationServiceInitOptions,
} from "./state-migration-service.factory";
import {
diskStorageServiceFactory,
secureStorageServiceFactory,
memoryStorageServiceFactory,
DiskStorageServiceInitOptions,
SecureStorageServiceInitOptions,
MemoryStorageServiceInitOptions,
} from "./storage-service.factory";
type StateServiceFactoryOptions = FactoryOptions & {
stateServiceOptions: {
useAccountCache?: boolean;
stateFactory: StateFactory<GlobalState, Account>;
};
};
export type StateServiceInitOptions = StateServiceFactoryOptions &
DiskStorageServiceInitOptions &
SecureStorageServiceInitOptions &
MemoryStorageServiceInitOptions &
LogServiceInitOptions &
StateMigrationServiceInitOptions;
export function stateServiceFactory(
cache: { stateService?: StateService } & CachedServices,
opts: StateServiceInitOptions
): StateService {
return factory(
cache,
"stateService",
opts,
() =>
new StateService(
diskStorageServiceFactory(cache, opts),
secureStorageServiceFactory(cache, opts),
memoryStorageServiceFactory(cache, opts),
logServiceFactory(cache, opts),
stateMigrationServiceFactory(cache, opts),
opts.stateServiceOptions.stateFactory,
opts.stateServiceOptions.useAccountCache
)
);
}

View File

@ -0,0 +1,49 @@
import { AbstractStorageService } from "@bitwarden/common/abstractions/storage.service";
import { MemoryStorageService } from "@bitwarden/common/services/memoryStorage.service";
import BrowserLocalStorageService from "../../services/browserLocalStorage.service";
import { LocalBackedSessionStorageService } from "../../services/localBackedSessionStorage.service";
import { encryptServiceFactory, EncryptServiceInitOptions } from "./encrypt-service.factory";
import { CachedServices, factory, FactoryOptions } from "./factory-options";
import {
keyGenerationServiceFactory,
KeyGenerationServiceInitOptions,
} from "./key-generation-service.factory";
type StorageServiceFactoryOptions = FactoryOptions;
export type DiskStorageServiceInitOptions = StorageServiceFactoryOptions;
export type SecureStorageServiceInitOptions = StorageServiceFactoryOptions;
export type MemoryStorageServiceInitOptions = StorageServiceFactoryOptions &
EncryptServiceInitOptions &
KeyGenerationServiceInitOptions;
export function diskStorageServiceFactory(
cache: { diskStorageService?: AbstractStorageService } & CachedServices,
opts: DiskStorageServiceInitOptions
): AbstractStorageService {
return factory(cache, "diskStorageService", opts, () => new BrowserLocalStorageService());
}
export function secureStorageServiceFactory(
cache: { secureStorageService?: AbstractStorageService } & CachedServices,
opts: SecureStorageServiceInitOptions
): AbstractStorageService {
return factory(cache, "secureStorageService", opts, () => new BrowserLocalStorageService());
}
export function memoryStorageServiceFactory(
cache: { memoryStorageService?: AbstractStorageService } & CachedServices,
opts: MemoryStorageServiceInitOptions
): AbstractStorageService {
return factory(cache, "memoryStorageService", opts, () => {
if (chrome.runtime.getManifest().manifest_version == 3) {
return new LocalBackedSessionStorageService(
encryptServiceFactory(cache, opts),
keyGenerationServiceFactory(cache, opts)
);
}
return new MemoryStorageService();
});
}

View File

@ -1,3 +1,5 @@
import { GroupPolicyEnvironment } from "./types/group-policy-environment";
function getFlags<T>(envFlags: string | T): T {
if (typeof envFlags === "string") {
return JSON.parse(envFlags) as T;
@ -21,11 +23,13 @@ export function flagEnabled(flag: FlagName): boolean {
*/
export type DevFlags = {
storeSessionDecrypted?: boolean;
managedEnvironment?: GroupPolicyEnvironment;
};
export type DevFlagName = keyof DevFlags;
/**
* Gets whether the given dev flag is truthy.
* Gets the value of a dev flag from environment.
* Will always return false unless in development.
* @param flag The name of the dev flag to check
@ -37,5 +41,21 @@ export function devFlagEnabled(flag: DevFlagName): boolean {
}
const devFlags = getFlags<DevFlags>(process.env.DEV_FLAGS);
return devFlags[flag] == null || devFlags[flag];
return devFlags[flag] == null || !!devFlags[flag];
}
/**
* Gets the value of a dev flag from environment.
* Will always return false unless in development.
* @param flag The name of the dev flag to check
* @returns The value of the flag
* @throws Error if the flag is not enabled
*/
export function devFlagValue<K extends DevFlagName>(flag: K): DevFlags[K] {
if (!devFlagEnabled(flag)) {
throw new Error(`This method should not be called, it is protected by a disabled dev flag.`);
}
const devFlags = getFlags<DevFlags>(process.env.DEV_FLAGS);
return devFlags[flag];
}

View File

@ -0,0 +1,38 @@
import { StateFactory } from "@bitwarden/common/factories/stateFactory";
import { GlobalState } from "@bitwarden/common/models/domain/globalState";
import { environmentServiceFactory } from "../background/service_factories/environment-service.factory";
import { BrowserApi } from "../browser/browserApi";
import { Account } from "../models/account";
export function onInstallListener(details: chrome.runtime.InstalledDetails) {
const cache = {};
const opts = {
encryptServiceOptions: {
logMacFailures: false,
},
cryptoFunctionServiceOptions: {
win: self,
},
logServiceOptions: {
isDev: false,
},
stateServiceOptions: {
stateFactory: new StateFactory(GlobalState, Account),
},
stateMigrationServiceOptions: {
stateFactory: new StateFactory(GlobalState, Account),
},
};
const environmentService = environmentServiceFactory(cache, opts);
setTimeout(async () => {
if (details.reason != null && details.reason === "install") {
BrowserApi.createNewTab("https://bitwarden.com/browser-start/");
if (await environmentService.hasManagedEnvironment()) {
await environmentService.setUrlsToManagedEnvironment();
}
}
}, 100);
}

View File

@ -2,15 +2,8 @@ import { LogService } from "@bitwarden/common/abstractions/log.service";
import { StateService } from "@bitwarden/common/abstractions/state.service";
import { EnvironmentService } from "@bitwarden/common/services/environment.service";
type GroupPolicyEnvironment = {
base?: string;
webVault?: string;
api?: string;
identity?: string;
icons?: string;
notifications?: string;
events?: string;
};
import { devFlagEnabled, devFlagValue } from "../flags";
import { GroupPolicyEnvironment } from "../types/group-policy-environment";
export class BrowserEnvironmentService extends EnvironmentService {
constructor(stateService: StateService, private logService: LogService) {
@ -41,15 +34,17 @@ export class BrowserEnvironmentService extends EnvironmentService {
}
getManagedEnvironment(): Promise<GroupPolicyEnvironment> {
return new Promise((resolve, reject) => {
chrome.storage.managed.get("environment", (result) => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
return devFlagEnabled("managedEnvironment")
? new Promise((resolve) => resolve(devFlagValue("managedEnvironment")))
: new Promise((resolve, reject) => {
chrome.storage.managed.get("environment", (result) => {
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
resolve(result.environment);
});
});
resolve(result.environment);
});
});
}
async setUrlsToManagedEnvironment() {

View File

@ -0,0 +1,9 @@
export type GroupPolicyEnvironment = {
base?: string;
webVault?: string;
api?: string;
identity?: string;
icons?: string;
notifications?: string;
events?: string;
};