[PM-45264] Wire data backing for HTTP auth cipher-level setting (#24507)

* wire data backing for HTTP auth cipher-level setting

* refactor feature availability check
This commit is contained in:
Jonathan Prusik
2026-11-10 17:43:44 -05:00
committed by GitHub
parent 93ef9aecd1
commit b2471b526b
9 changed files with 575 additions and 128 deletions

View File

@@ -12,6 +12,7 @@ import {
} from "@bitwarden/common/models/domain/domain-service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { devFlagEnabled } from "@bitwarden/common/platform/misc/flags";
import { mockAccountInfoWith } from "@bitwarden/common/spec";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service";
@@ -29,6 +30,13 @@ import WebRequestBackground, {
shouldAnswerAuthChallenge,
} from "./web-request.background";
jest.mock("@bitwarden/common/platform/misc/flags", () => ({
...jest.requireActual("@bitwarden/common/platform/misc/flags"),
devFlagEnabled: jest.fn(),
}));
const mockDevFlagEnabled = devFlagEnabled as jest.Mock;
type WebRequestEventMock = {
addListener: jest.Mock;
removeListener: jest.Mock;
@@ -52,7 +60,8 @@ describe("WebRequestBackground", () => {
let eventCollectionService: ReturnType<typeof mock<EventCollectionService>>;
let logService: ReturnType<typeof mock<LogService>>;
let activeAccount$: BehaviorSubject<Account | null>;
let resolvedSetting$: BehaviorSubject<boolean>;
let httpAuthenticationAvailable$: BehaviorSubject<boolean>;
let globalSetting$: BehaviorSubject<boolean>;
let webRequest: {
onAuthRequired: WebRequestEventMock;
onCompleted: WebRequestEventMock;
@@ -98,9 +107,16 @@ describe("WebRequestBackground", () => {
accountService = mock<AccountService>();
accountService.activeAccount$ = activeAccount$;
resolvedSetting$ = new BehaviorSubject<boolean>(true);
// By default only the login-level setting applies: the global setting is off and the
// login-level controls are shown.
mockDevFlagEnabled.mockImplementation(
(flag: string) => flag === "httpAuthenticationCipherControls",
);
httpAuthenticationAvailable$ = new BehaviorSubject<boolean>(true);
globalSetting$ = new BehaviorSubject<boolean>(false);
autofillSettingsService = mock<AutofillSettingsServiceAbstraction>();
autofillSettingsService.resolvedEnableBasicAuthResponse$ = resolvedSetting$;
autofillSettingsService.httpAuthenticationAvailable$ = httpAuthenticationAvailable$;
autofillSettingsService.resolvedEnableBasicAuthResponse$ = globalSetting$;
eventCollectionService = mock<EventCollectionService>();
eventCollectionService.collect.mockResolvedValue(undefined);
@@ -120,7 +136,7 @@ describe("WebRequestBackground", () => {
});
describe("startListening", () => {
it("registers listeners when the resolved setting is enabled", () => {
it("registers listeners when HTTP authentication is available", () => {
webRequestBackground.startListening();
expectListenersRegistered(1);
@@ -144,10 +160,10 @@ describe("WebRequestBackground", () => {
);
});
it("does not register listeners or resolve the setting on Safari", () => {
let resolvedSettingSubscribed = false;
autofillSettingsService.resolvedEnableBasicAuthResponse$ = defer(() => {
resolvedSettingSubscribed = true;
it("does not register listeners or resolve availability on Safari", () => {
let availabilitySubscribed = false;
autofillSettingsService.httpAuthenticationAvailable$ = defer(() => {
availabilitySubscribed = true;
return of(true);
});
platformUtilsService.isSafari.mockReturnValue(true);
@@ -156,11 +172,11 @@ describe("WebRequestBackground", () => {
webRequestBackground.startListening();
expectListenersRegistered(0);
expect(resolvedSettingSubscribed).toBe(false);
expect(availabilitySubscribed).toBe(false);
});
it("does not register listeners when the resolved setting is disabled", () => {
resolvedSetting$.next(false);
it("does not register listeners when HTTP authentication is unavailable", () => {
httpAuthenticationAvailable$.next(false);
webRequestBackground.startListening();
@@ -175,32 +191,32 @@ describe("WebRequestBackground", () => {
expectListenersRegistered(0);
});
it("does not register listeners when resolving the setting errors", () => {
const erroringResolvedSetting$ = new Subject<boolean>();
autofillSettingsService.resolvedEnableBasicAuthResponse$ = erroringResolvedSetting$;
it("does not register listeners when resolving availability errors", () => {
const erroringAvailability$ = new Subject<boolean>();
autofillSettingsService.httpAuthenticationAvailable$ = erroringAvailability$;
webRequestBackground.startListening();
erroringResolvedSetting$.error(new Error("config unavailable"));
erroringAvailability$.error(new Error("config unavailable"));
expectListenersRegistered(0);
});
it("keeps reacting to account changes after resolving the setting errors", () => {
const erroringResolvedSetting$ = new Subject<boolean>();
autofillSettingsService.resolvedEnableBasicAuthResponse$ = erroringResolvedSetting$;
it("keeps reacting to account changes after resolving availability errors", () => {
const erroringAvailability$ = new Subject<boolean>();
autofillSettingsService.httpAuthenticationAvailable$ = erroringAvailability$;
webRequestBackground.startListening();
erroringResolvedSetting$.error(new Error("config unavailable"));
autofillSettingsService.resolvedEnableBasicAuthResponse$ = resolvedSetting$;
erroringAvailability$.error(new Error("config unavailable"));
autofillSettingsService.httpAuthenticationAvailable$ = httpAuthenticationAvailable$;
activeAccount$.next({ ...account });
expectListenersRegistered(1);
});
it("removes the same listeners it registered when the resolved setting is disabled", () => {
it("removes the same listeners it registered when HTTP authentication is unavailable", () => {
webRequestBackground.startListening();
resolvedSetting$.next(false);
httpAuthenticationAvailable$.next(false);
expectListenersUnregistered(1);
expect(webRequest.onAuthRequired.removeListener).toHaveBeenCalledWith(
@@ -214,11 +230,11 @@ describe("WebRequestBackground", () => {
);
});
it("removes listeners when the active user changes to one with the setting disabled", () => {
it("removes listeners when the active user changes to one without HTTP authentication available", () => {
const otherUserId = "other-user-id" as UserId;
webRequestBackground.startListening();
autofillSettingsService.resolvedEnableBasicAuthResponse$ = of(false);
autofillSettingsService.httpAuthenticationAvailable$ = of(false);
activeAccount$.next({ id: otherUserId, ...mockAccountInfoWith() });
expectListenersUnregistered(1);
@@ -232,27 +248,27 @@ describe("WebRequestBackground", () => {
expectListenersUnregistered(1);
});
it("re-registers listeners when the resolved setting is re-enabled", () => {
it("re-registers listeners when HTTP authentication becomes available again", () => {
webRequestBackground.startListening();
resolvedSetting$.next(false);
resolvedSetting$.next(true);
httpAuthenticationAvailable$.next(false);
httpAuthenticationAvailable$.next(true);
expectListenersRegistered(2);
expectListenersUnregistered(1);
});
it("does not register listeners more than once for repeated enabled emissions", () => {
it("does not register listeners more than once for repeated available emissions", () => {
webRequestBackground.startListening();
resolvedSetting$.next(true);
httpAuthenticationAvailable$.next(true);
activeAccount$.next({ ...account });
expectListenersRegistered(1);
});
it("does not remove listeners that were never registered", () => {
resolvedSetting$.next(false);
httpAuthenticationAvailable$.next(false);
webRequestBackground.startListening();
activeAccount$.next(null);
@@ -264,11 +280,68 @@ describe("WebRequestBackground", () => {
webRequestBackground.startListening();
webRequestBackground.startListening();
resolvedSetting$.next(false);
httpAuthenticationAvailable$.next(false);
expectListenersRegistered(1);
expectListenersUnregistered(1);
});
describe("with the global setting", () => {
it("keeps listeners registered while either setting applies", () => {
globalSetting$.next(true);
webRequestBackground.startListening();
httpAuthenticationAvailable$.next(false);
expectListenersUnregistered(0);
globalSetting$.next(false);
expectListenersUnregistered(1);
});
it("registers listeners when only the global setting is on", () => {
httpAuthenticationAvailable$.next(false);
globalSetting$.next(true);
webRequestBackground.startListening();
expectListenersRegistered(1);
});
it("registers listeners from the global setting when the login-level controls are hidden", () => {
mockDevFlagEnabled.mockReturnValue(false);
globalSetting$.next(true);
webRequestBackground = createWebRequestBackground();
webRequestBackground.startListening();
expectListenersRegistered(1);
});
it("does not register listeners or read availability when only the login-level setting would apply and its controls are hidden", () => {
let availabilitySubscribed = false;
autofillSettingsService.httpAuthenticationAvailable$ = defer(() => {
availabilitySubscribed = true;
return of(true);
});
mockDevFlagEnabled.mockReturnValue(false);
webRequestBackground = createWebRequestBackground();
webRequestBackground.startListening();
expectListenersRegistered(0);
expect(availabilitySubscribed).toBe(false);
});
it("does not register listeners when resolving the global setting errors", () => {
const erroringGlobalSetting$ = new Subject<boolean>();
autofillSettingsService.resolvedEnableBasicAuthResponse$ = erroringGlobalSetting$;
webRequestBackground.startListening();
erroringGlobalSetting$.error(new Error("state unavailable"));
expectListenersRegistered(0);
});
});
});
describe("handling auth challenges", () => {
@@ -290,7 +363,12 @@ describe("WebRequestBackground", () => {
{
reprompt = CipherRepromptType.None,
uris = [createLoginUri(url, UriMatchStrategy.Host)],
}: { reprompt?: CipherRepromptType; uris?: LoginUriView[] } = {},
httpAuthenticationEnabled = true,
}: {
reprompt?: CipherRepromptType;
uris?: LoginUriView[];
httpAuthenticationEnabled?: boolean;
} = {},
) => {
const cipher = new CipherView();
cipher.id = id;
@@ -301,6 +379,7 @@ describe("WebRequestBackground", () => {
cipher.login.username = username ?? undefined;
cipher.login.password = password ?? undefined;
cipher.login.uris = uris;
cipher.login.httpAuthenticationEnabled = httpAuthenticationEnabled;
return cipher;
};
@@ -447,7 +526,7 @@ describe("WebRequestBackground", () => {
expect(callback).toHaveBeenCalledWith({});
});
it("does not look up ciphers when the active user changes while the setting is read", async () => {
it("does not look up ciphers when the active user changes while availability is read", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password"),
]);
@@ -456,7 +535,7 @@ describe("WebRequestBackground", () => {
...mockAccountInfoWith(),
};
let accountSwitched = false;
autofillSettingsService.resolvedEnableBasicAuthResponse$ = defer(() => {
autofillSettingsService.httpAuthenticationAvailable$ = defer(() => {
if (!accountSwitched) {
accountSwitched = true;
activeAccount$.next(otherAccount);
@@ -470,9 +549,9 @@ describe("WebRequestBackground", () => {
expect(callback).toHaveBeenCalledWith({});
});
it("declines without waiting when the active user logs out while the setting is read", async () => {
it("declines without waiting when the active user logs out while availability is read", async () => {
let loggedOut = false;
autofillSettingsService.resolvedEnableBasicAuthResponse$ = defer(() => {
autofillSettingsService.httpAuthenticationAvailable$ = defer(() => {
if (!loggedOut) {
loggedOut = true;
activeAccount$.next(null);
@@ -487,11 +566,11 @@ describe("WebRequestBackground", () => {
expect(callback).toHaveBeenCalledWith({});
});
it("does not look up ciphers when the resolved setting is disabled before the listeners are removed", async () => {
it("does not look up ciphers when HTTP authentication becomes unavailable before the listeners are removed", async () => {
// The handler is captured from the registration while enabled, then
// invoked as a challenge already in flight would be.
const handleAuthRequired = webRequest.onAuthRequired.addListener.mock.calls[0][0];
autofillSettingsService.resolvedEnableBasicAuthResponse$ = of(false);
autofillSettingsService.httpAuthenticationAvailable$ = of(false);
await handleAuthRequired(buildAuthRequiredDetails({ url, requestId: "request-1" }), callback);
@@ -499,12 +578,12 @@ describe("WebRequestBackground", () => {
expect(callback).toHaveBeenCalledWith({});
});
it("does not look up ciphers when resolving the setting errors", async () => {
const erroringResolvedSetting$ = new Subject<boolean>();
autofillSettingsService.resolvedEnableBasicAuthResponse$ = erroringResolvedSetting$;
it("does not look up ciphers when resolving availability errors", async () => {
const erroringAvailability$ = new Subject<boolean>();
autofillSettingsService.httpAuthenticationAvailable$ = erroringAvailability$;
const challenge = triggerAuthRequired();
erroringResolvedSetting$.error(new Error("state unavailable"));
erroringAvailability$.error(new Error("state unavailable"));
await challenge;
expect(cipherService.getAllDecryptedForUrl).not.toHaveBeenCalled();
@@ -567,8 +646,8 @@ describe("WebRequestBackground", () => {
]);
await triggerAuthRequired();
resolvedSetting$.next(false);
resolvedSetting$.next(true);
httpAuthenticationAvailable$.next(false);
httpAuthenticationAvailable$.next(true);
callback.mockClear();
await triggerAuthRequired();
@@ -584,16 +663,45 @@ describe("WebRequestBackground", () => {
expect(eventCollectionService.collect).not.toHaveBeenCalled();
};
it("declines a login with master password reprompt on, even when it is the only match", async () => {
it("answers with an opted-in organization login", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password", "cipher-id", "organization-id", {
reprompt: CipherRepromptType.Password,
}),
createCipher("jane.doe@example.com", "fake-password", "cipher-id", "organization-id"),
]);
await triggerAuthRequired();
expectAnswered();
});
it.each([false, undefined])(
"declines a login that has not opted in (%s), even when it is the only match",
async (httpAuthenticationEnabled) => {
const cipher = createCipher("jane.doe@example.com", "fake-password");
cipher.login.httpAuthenticationEnabled = httpAuthenticationEnabled;
cipherService.getAllDecryptedForUrl.mockResolvedValue([cipher]);
await triggerAuthRequired();
expectDeclined();
},
);
it("declines a login stored with both HTTP authentication and master password reprompt on, and leaves it unchanged", async () => {
const cipher = createCipher(
"jane.doe@example.com",
"fake-password",
"cipher-id",
"organization-id",
{ reprompt: CipherRepromptType.Password },
);
cipherService.getAllDecryptedForUrl.mockResolvedValue([cipher]);
await triggerAuthRequired();
expectDeclined();
expect(cipher.login.httpAuthenticationEnabled).toBe(true);
expect(cipher.reprompt).toBe(CipherRepromptType.Password);
expect(cipherService.updateWithServer).not.toHaveBeenCalled();
});
it("declines a login whose only URI uses the default match strategy", async () => {
@@ -719,6 +827,9 @@ describe("WebRequestBackground", () => {
createCipher("default@example.com", "default-password", "default-id", null, {
uris: [createLoginUri(url, null)],
}),
createCipher("opted-out@example.com", "opted-out-password", "opted-out-id", null, {
httpAuthenticationEnabled: false,
}),
createCipher("jane.doe@example.com", "fake-password", "eligible-id", null),
]);
@@ -740,6 +851,107 @@ describe("WebRequestBackground", () => {
expectDeclined();
});
describe("with the global setting on", () => {
beforeEach(() => {
globalSetting$.next(true);
});
it("answers with a login that has HTTP authentication off in its own settings", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password", "cipher-id", null, {
httpAuthenticationEnabled: false,
}),
]);
await triggerAuthRequired();
expectAnswered();
});
it("still declines a login with master password reprompt on", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password", "cipher-id", null, {
reprompt: CipherRepromptType.Password,
httpAuthenticationEnabled: false,
}),
]);
await triggerAuthRequired();
expectDeclined();
});
it("still declines a login whose URI uses the default match strategy", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password", "cipher-id", null, {
uris: [createLoginUri(url, null)],
httpAuthenticationEnabled: false,
}),
]);
await triggerAuthRequired();
expectDeclined();
});
it("declines when a login with its own setting on and one without both match", async () => {
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password", "opted-in-id", null),
createCipher("john.doe@example.com", "other-fake-password", "opted-out-id", null, {
httpAuthenticationEnabled: false,
}),
]);
await triggerAuthRequired();
expectDeclined();
});
});
describe("when the login-level controls are hidden", () => {
/** Starts a handler built while the dev flag for the login-level controls is off. */
const startListeningWithLoginControlsHidden = () => {
mockDevFlagEnabled.mockReturnValue(false);
webRequest.onAuthRequired.addListener.mockClear();
webRequestBackground = createWebRequestBackground();
webRequestBackground.startListening();
};
it("answers with any eligible login while the global setting is on", async () => {
globalSetting$.next(true);
startListeningWithLoginControlsHidden();
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password", "cipher-id", null, {
httpAuthenticationEnabled: false,
}),
]);
await triggerAuthRequired();
expectAnswered();
});
it("ignores a login's own setting while the global setting is off", async () => {
globalSetting$.next(true);
startListeningWithLoginControlsHidden();
// The handler is captured from the registration while the global setting was on,
// then invoked as a challenge already in flight would be.
const handleAuthRequired = webRequest.onAuthRequired.addListener.mock.calls[0][0];
globalSetting$.next(false);
cipherService.getAllDecryptedForUrl.mockResolvedValue([
createCipher("jane.doe@example.com", "fake-password"),
]);
await handleAuthRequired(
buildAuthRequiredDetails({ url, requestId: "request-1" }),
callback,
);
expect(cipherService.getAllDecryptedForUrl).not.toHaveBeenCalled();
expectDeclined();
});
});
});
describe("on Firefox", () => {

View File

@@ -1,7 +1,9 @@
import {
catchError,
combineLatest,
distinctUntilChanged,
firstValueFrom,
map,
Observable,
of,
Subscription,
@@ -13,11 +15,15 @@ import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { getOptionalUserId } from "@bitwarden/common/auth/services/account.service";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { isEligibleForHTTPAuthentication } from "@bitwarden/common/autofill/utils/http-authentication-eligibility";
import {
hasOptedInToHTTPAuthentication,
isEligibleForHTTPAuthentication,
} from "@bitwarden/common/autofill/utils/http-authentication-eligibility";
import { EventCollectionService, EventType } from "@bitwarden/common/dirt/event-logs";
import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { devFlagEnabled } from "@bitwarden/common/platform/misc/flags";
import { UserId } from "@bitwarden/common/types/guid";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
@@ -207,12 +213,37 @@ export function shouldAnswerAuthChallenge(
return isTopLevelNavigationOrSameOriginSubresource(details, requestUrl);
}
/** The settings that let a login answer an HTTP auth challenge for the active user. */
interface HTTPAuthenticationResponseSettings {
/** The user's global setting is on, so every eligible login may answer. */
globalSettingEnabled: boolean;
/** Eligible logins with HTTP authentication turned on in their own settings may answer. */
loginSettingEnabled: boolean;
}
const NO_HTTP_AUTHENTICATION_RESPONSE_SETTINGS: HTTPAuthenticationResponseSettings = Object.freeze({
globalSettingEnabled: false,
loginSettingEnabled: false,
});
function anyHTTPAuthenticationResponseSettingEnabled(
settings: HTTPAuthenticationResponseSettings,
): boolean {
return settings.globalSettingEnabled || settings.loginSettingEnabled;
}
export default class WebRequestBackground {
private pendingAuthRequests: Set<string> = new Set<string>([]);
private isFirefox: boolean;
private isSafari: boolean;
private listenersRegistered = false;
private basicAuthResponseEnabledSubscription?: Subscription;
private responseSettingsSubscription?: Subscription;
/**
* The login-level setting is honored only in builds that show its cipher form controls, so a value
* stored by another client has no effect where the user can't see or change it.
*/
private readonly loginSettingHonored = devFlagEnabled("httpAuthenticationCipherControls");
constructor(
platformUtilsService: PlatformUtilsService,
@@ -230,7 +261,9 @@ export default class WebRequestBackground {
/**
* Keeps the handler that answers HTTP auth challenges with a matching vault credential
* registered only while both the feature flag and the active user's setting allow it.
* registered only while the active user's global setting is on, or while logins can turn
* HTTP authentication on in their own settings. Which logins may answer is checked when a
* challenge arrives.
*
* While registered, `webRequest.onAuthRequired` fires for any request that receives a 401.
*/
@@ -242,60 +275,84 @@ export default class WebRequestBackground {
return;
}
this.basicAuthResponseEnabledSubscription?.unsubscribe();
this.basicAuthResponseEnabledSubscription = this.basicAuthResponseEnabled$().subscribe(
(basicAuthResponseEnabled) => {
if (basicAuthResponseEnabled) {
this.responseSettingsSubscription?.unsubscribe();
this.responseSettingsSubscription = this.responseSettings$()
.pipe(map(anyHTTPAuthenticationResponseSettingEnabled), distinctUntilChanged())
.subscribe((anyResponseSettingEnabled) => {
if (anyResponseSettingEnabled) {
this.registerListeners();
} else {
this.unregisterListeners();
}
},
);
});
}
/**
* Emits `true` only when the resolved setting is enabled for the active user.
* Emits the settings that let a login answer an HTTP auth challenge for the active user: the
* user's global setting, and whether the login-level setting is honored, which needs HTTP
* authentication to be available and the login-level controls to be shown in this build.
*
* Fails closed: no active user, or an error resolving the setting, emits `false`.
* Fails closed: no active user, or an error resolving either setting, emits both as off.
*/
private basicAuthResponseEnabled$(): Observable<boolean> {
// The setting is resolved inside a `switchMap` on the active account so that an
// error is caught for that account alone and the setting is resolved again on
private responseSettings$(): Observable<HTTPAuthenticationResponseSettings> {
// The settings are resolved inside a `switchMap` on the active account so that an
// error is caught for that account alone and the settings are resolved again on
// the next account change; catching downstream would end the subscription and
// leave the listeners unregistered for the life of the background context.
return this.accountService.activeAccount$.pipe(
getOptionalUserId,
switchMap((userId) =>
userId == null
? of(false)
: this.autofillSettingsService.resolvedEnableBasicAuthResponse$.pipe(
catchError(() => of(false)),
? of(NO_HTTP_AUTHENTICATION_RESPONSE_SETTINGS)
: combineLatest([
this.autofillSettingsService.resolvedEnableBasicAuthResponse$,
this.loginSettingHonored
? this.autofillSettingsService.httpAuthenticationAvailable$
: of(false),
]).pipe(
map(
([
globalSettingEnabled,
loginSettingEnabled,
]): HTTPAuthenticationResponseSettings => ({
globalSettingEnabled: globalSettingEnabled === true,
loginSettingEnabled: loginSettingEnabled === true,
}),
),
catchError(() => of(NO_HTTP_AUTHENTICATION_RESPONSE_SETTINGS)),
),
),
catchError(() => of(false)),
distinctUntilChanged(),
catchError(() => of(NO_HTTP_AUTHENTICATION_RESPONSE_SETTINGS)),
distinctUntilChanged(
(previous, current) =>
previous.globalSettingEnabled === current.globalSettingEnabled &&
previous.loginSettingEnabled === current.loginSettingEnabled,
),
);
}
/**
* Whether the resolved setting is enabled for the active user, and that user is
* still the given one once the setting has been read. The resolved setting
* follows whichever user is active, so a change of active user during the read
* would otherwise apply one user's opt-in to another user's vault.
* The settings that let a login answer an HTTP auth challenge for the active user, when that
* user is still the given one once the settings have been read. The settings follow whichever
* user is active, so a change of active user during the read would otherwise apply one user's
* settings to another user's vault.
*
* Fails closed on error.
*/
private async basicAuthResponseEnabledForUser(userId: UserId): Promise<boolean> {
private async responseSettingsForUser(
userId: UserId,
): Promise<HTTPAuthenticationResponseSettings> {
try {
const enabled = await firstValueFrom(this.basicAuthResponseEnabled$());
const settings = await firstValueFrom(this.responseSettings$());
const activeUserIdAfterCheck = await firstValueFrom(
this.accountService.activeAccount$.pipe(getOptionalUserId),
);
return enabled === true && activeUserIdAfterCheck === userId;
return activeUserIdAfterCheck === userId
? settings
: NO_HTTP_AUTHENTICATION_RESPONSE_SETTINGS;
} catch {
return false;
return NO_HTTP_AUTHENTICATION_RESPONSE_SETTINGS;
}
}
@@ -373,8 +430,10 @@ export default class WebRequestBackground {
}
// Listener removal trails the state it reacts to, so a challenge can arrive
// after the active account changes to one that has not opted in.
if (!(await this.basicAuthResponseEnabledForUser(activeUserId))) {
// after the active account changes to one with no response setting enabled.
const responseSettings = await this.responseSettingsForUser(activeUserId);
if (!anyHTTPAuthenticationResponseSettingEnabled(responseSettings)) {
return {};
}
@@ -387,7 +446,9 @@ export default class WebRequestBackground {
try {
// The Host strategy is only applied to URIs using "Default", and logins with any such URI are
// removed by the eligibility filter below, so each remaining URI matched by its own strategy.
// Host is still passed so that a "Default" URI is never matched more loosely.
// Host is still passed so that a "Default" URI is never matched more loosely. The filter also
// removes logins with reprompt on, and, unless the global setting is on, logins without HTTP
// authentication turned on in their own settings, before the single-match check.
const ciphers = await this.fillCipherPolicy.ciphersForUrl(
details.url,
activeUserId,
@@ -395,7 +456,12 @@ export default class WebRequestBackground {
{ defaultMatch: UriMatchStrategy.Host },
);
const eligibleCiphers = (ciphers ?? []).filter(isEligibleForHTTPAuthentication);
const eligibleCiphers = (ciphers ?? []).filter(
(cipher) =>
isEligibleForHTTPAuthentication(cipher) &&
(responseSettings.globalSettingEnabled ||
(responseSettings.loginSettingEnabled && hasOptedInToHTTPAuthentication(cipher))),
);
if (eligibleCiphers.length !== 1) {
return {};

View File

@@ -22,6 +22,12 @@ describe("AutofillSettingsService", () => {
let enableBasicAuthResponseByUser: Map<UserId, Observable<boolean | null>>;
let autofillSettingsService: AutofillSettingsService;
const collectEmissions = (observable$: Observable<boolean>) => {
const emissions: boolean[] = [];
const subscription = observable$.subscribe((value) => emissions.push(value));
return { emissions, subscription };
};
beforeEach(() => {
accountService = mockAccountServiceWith(userId);
stateProvider = new FakeStateProvider(accountService);
@@ -59,12 +65,6 @@ describe("AutofillSettingsService", () => {
});
describe("resolvedEnableBasicAuthResponse$", () => {
const collectEmissions = (observable$: Observable<boolean>) => {
const emissions: boolean[] = [];
const subscription = observable$.subscribe((value) => emissions.push(value));
return { emissions, subscription };
};
it("emits true when the feature flag and the user setting are both enabled", async () => {
await expect(
firstValueFrom(autofillSettingsService.resolvedEnableBasicAuthResponse$),
@@ -146,6 +146,19 @@ describe("AutofillSettingsService", () => {
subscription.unsubscribe();
});
it("follows HTTP authentication availability", () => {
const resolved = collectEmissions(autofillSettingsService.resolvedEnableBasicAuthResponse$);
const available = collectEmissions(autofillSettingsService.httpAuthenticationAvailable$);
featureFlag$.next(false);
featureFlag$.next(true);
expect(resolved.emissions).toEqual([true, false, true]);
expect(available.emissions).toEqual([true, false, true]);
resolved.subscription.unsubscribe();
available.subscription.unsubscribe();
});
it("does not give a new subscriber the previous user's value before the active user's setting is read", async () => {
// Stands in for a newly active user whose setting is still being read from storage.
const pendingOtherUserSetting$ = new Subject<boolean | null>();
@@ -168,4 +181,72 @@ describe("AutofillSettingsService", () => {
newSubscriber.subscription.unsubscribe();
});
});
describe("httpAuthenticationAvailable$", () => {
it("emits true when there is an active user and the feature flag is on", async () => {
await expect(
firstValueFrom(autofillSettingsService.httpAuthenticationAvailable$),
).resolves.toBe(true);
});
it("emits true when the user setting is off", async () => {
enableBasicAuthResponseByUser.set(userId, new BehaviorSubject<boolean | null>(false));
await expect(
firstValueFrom(autofillSettingsService.httpAuthenticationAvailable$),
).resolves.toBe(true);
});
it("emits false when the feature flag is off", async () => {
featureFlag$.next(false);
await expect(
firstValueFrom(autofillSettingsService.httpAuthenticationAvailable$),
).resolves.toBe(false);
});
it("emits false when there is no active user", async () => {
await accountService.switchAccount(null);
await expect(
firstValueFrom(autofillSettingsService.httpAuthenticationAvailable$),
).resolves.toBe(false);
});
it("follows a change of active user", async () => {
const { emissions, subscription } = collectEmissions(
autofillSettingsService.httpAuthenticationAvailable$,
);
await accountService.switchAccount(null);
await accountService.switchAccount(otherUserId);
expect(emissions).toEqual([true, false, true]);
subscription.unsubscribe();
});
it("updates when the feature flag changes", () => {
const { emissions, subscription } = collectEmissions(
autofillSettingsService.httpAuthenticationAvailable$,
);
featureFlag$.next(false);
featureFlag$.next(true);
expect(emissions).toEqual([true, false, true]);
subscription.unsubscribe();
});
it("does not re-emit an unchanged value", async () => {
const { emissions, subscription } = collectEmissions(
autofillSettingsService.httpAuthenticationAvailable$,
);
featureFlag$.next(true);
await accountService.switchAccount(otherUserId);
expect(emissions).toEqual([true]);
subscription.unsubscribe();
});
});
});

View File

@@ -182,13 +182,24 @@ export abstract class AutofillSettingsServiceAbstraction {
setEnableBasicAuthResponse: (newValue: boolean) => Promise<void>;
/**
* Resolved state for answering HTTP auth challenges for the active user: the
* user setting, gated on the {@link FeatureFlag.EnableBasicAuthResponse} flag.
* user setting, gated on HTTP authentication being available
* ({@link httpAuthenticationAvailable$}).
*
* Emits `false` while there is no active user. Each subscription resolves the
* setting of the user active when it subscribes, and follows later changes of
* active user.
*/
resolvedEnableBasicAuthResponse$: Observable<boolean>;
/**
* Whether HTTP authentication challenges may be answered from the active user's vault, gated on
* the {@link FeatureFlag.EnableBasicAuthResponse} flag. This reports availability only; it does
* not make any login eligible. A login is answered when the user setting
* ({@link resolvedEnableBasicAuthResponse$}) is on, or when the login itself has opted in; both
* are gated on availability.
*
* Emits `false` while there is no active user, and follows changes of active user.
*/
httpAuthenticationAvailable$: Observable<boolean>;
enableContextMenu$: Observable<boolean>;
setEnableContextMenu: (newValue: boolean) => Promise<void>;
clearClipboardDelay$: Observable<ClearClipboardDelaySetting>;
@@ -238,6 +249,7 @@ export class AutofillSettingsService implements AutofillSettingsServiceAbstracti
private enableBasicAuthResponseState: ActiveUserState<boolean>;
readonly enableBasicAuthResponse$: Observable<boolean>;
readonly resolvedEnableBasicAuthResponse$: Observable<boolean>;
readonly httpAuthenticationAvailable$: Observable<boolean>;
private enableContextMenuState: GlobalState<boolean>;
readonly enableContextMenu$: Observable<boolean>;
@@ -355,12 +367,17 @@ export class AutofillSettingsService implements AutofillSettingsServiceAbstracti
userId == null
? of(false)
: combineLatest([
// A future org policy would also be resolved here
this.stateProvider.getUser(userId, ENABLE_BASIC_AUTH_RESPONSE).state$,
this.configService.getFeatureFlag$(FeatureFlag.EnableBasicAuthResponse),
]).pipe(
map(([userSetting, featureFlag]) => featureFlag === true && userSetting === true),
),
this.httpAuthenticationFeatureEnabled$(),
]).pipe(map(([userSetting, available]) => available && userSetting === true)),
),
distinctUntilChanged(),
);
this.httpAuthenticationAvailable$ = this.accountService.activeAccount$.pipe(
getOptionalUserId,
switchMap((userId) =>
userId == null ? of(false) : this.httpAuthenticationFeatureEnabled$(),
),
distinctUntilChanged(),
);
@@ -444,6 +461,16 @@ export class AutofillSettingsService implements AutofillSettingsServiceAbstracti
await this.honorBitwardenAutofillAttributeState.update(() => newValue);
}
/**
* Whether the {@link FeatureFlag.EnableBasicAuthResponse} flag is on. Both the user setting
* ({@link resolvedEnableBasicAuthResponse$}) and logins' own settings are gated on this.
*/
private httpAuthenticationFeatureEnabled$(): Observable<boolean> {
return this.configService
.getFeatureFlag$(FeatureFlag.EnableBasicAuthResponse)
.pipe(map((featureFlag) => featureFlag === true));
}
async setEnableBasicAuthResponse(newValue: boolean): Promise<void> {
await this.enableBasicAuthResponseState.update(() => newValue);
}

View File

@@ -6,6 +6,7 @@ import { LoginView } from "../../vault/models/view/login.view";
import {
everyUriHasExplicitMatchStrategy,
hasOptedInToHTTPAuthentication,
isEligibleForHTTPAuthentication,
isRepromptOff,
} from "./http-authentication-eligibility";
@@ -71,6 +72,31 @@ describe("isEligibleForHTTPAuthentication", () => {
).toBe(true);
});
it("returns true for an organization login", () => {
const cipher = createLoginCipher();
cipher.organizationId = "organization-id";
expect(isEligibleForHTTPAuthentication(cipher)).toBe(true);
});
it.each([true, false, undefined])(
"does not depend on the login's own HTTP authentication setting (%s)",
(httpAuthenticationEnabled) => {
const cipher = createLoginCipher();
cipher.login.httpAuthenticationEnabled = httpAuthenticationEnabled;
expect(isEligibleForHTTPAuthentication(cipher)).toBe(true);
},
);
it("returns false when the login has HTTP authentication on and master password reprompt is on", () => {
const cipher = createLoginCipher([UriMatchStrategy.Host], CipherRepromptType.Password);
cipher.login.httpAuthenticationEnabled = true;
expect(isEligibleForHTTPAuthentication(cipher)).toBe(false);
expect(cipher.login.httpAuthenticationEnabled).toBe(true);
});
it("returns false when master password reprompt is on", () => {
expect(
isEligibleForHTTPAuthentication(
@@ -96,3 +122,33 @@ describe("isEligibleForHTTPAuthentication", () => {
expect(isEligibleForHTTPAuthentication(cipher)).toBe(false);
});
});
describe("hasOptedInToHTTPAuthentication", () => {
const createLoginCipher = (httpAuthenticationEnabled: boolean | undefined) => {
const cipher = new CipherView();
cipher.type = CipherType.Login;
cipher.login = new LoginView();
cipher.login.httpAuthenticationEnabled = httpAuthenticationEnabled;
return cipher;
};
it("returns true when the login has HTTP authentication on", () => {
expect(hasOptedInToHTTPAuthentication(createLoginCipher(true))).toBe(true);
});
it.each([false, undefined])(
"returns false when the login has HTTP authentication off (%s)",
(httpAuthenticationEnabled) => {
expect(hasOptedInToHTTPAuthentication(createLoginCipher(httpAuthenticationEnabled))).toBe(
false,
);
},
);
it("returns false for a cipher that is not a login", () => {
const cipher = createLoginCipher(true);
cipher.type = CipherType.Card;
expect(hasOptedInToHTTPAuthentication(cipher)).toBe(false);
});
});

View File

@@ -25,7 +25,8 @@ export function isRepromptOff(reprompt: CipherRepromptType): boolean {
/**
* Whether a cipher may answer an HTTP authentication challenge: a login with at least one URI, every URI
* with an explicit match strategy, and master password reprompt off.
* with an explicit match strategy, and master password reprompt off. This does not check whether HTTP
* authentication is turned on for the login; see {@link hasOptedInToHTTPAuthentication}.
*/
export function isEligibleForHTTPAuthentication(cipher: CipherView): boolean {
if (cipher.type !== CipherType.Login || !cipher.login?.hasUris) {
@@ -37,3 +38,14 @@ export function isEligibleForHTTPAuthentication(cipher: CipherView): boolean {
isRepromptOff(cipher.reprompt)
);
}
/**
* Whether a login has HTTP authentication turned on in its own settings.
*
* A login stored with both this setting and master password reprompt on still fails
* {@link isEligibleForHTTPAuthentication}. The stored value is left as it is; the cipher form corrects
* it the next time the login is saved.
*/
export function hasOptedInToHTTPAuthentication(cipher: CipherView): boolean {
return cipher.type === CipherType.Login && cipher.login?.httpAuthenticationEnabled === true;
}

View File

@@ -226,6 +226,7 @@ export default {
provide: AutofillSettingsServiceAbstraction,
useValue: {
autofillOnPageLoadDefault$: new BehaviorSubject(true),
httpAuthenticationAvailable$: new BehaviorSubject(false),
},
},
{
@@ -396,16 +397,14 @@ export const WithSubmitButton: Story = {
},
};
/** Provides a `ConfigService` with only the HTTP authentication feature flag turned on */
const withHTTPAuthenticationFeatureFlag = moduleMetadata({
/** Provides an `AutofillSettingsServiceAbstraction` with HTTP authentication available */
const withHTTPAuthenticationAvailable = moduleMetadata({
providers: [
{
provide: ConfigService,
provide: AutofillSettingsServiceAbstraction,
useValue: {
getFeatureFlag: (flag: FeatureFlag) =>
Promise.resolve(flag === FeatureFlag.EnableBasicAuthResponse),
getFeatureFlag$: (flag: FeatureFlag) =>
new BehaviorSubject(flag === FeatureFlag.EnableBasicAuthResponse),
autofillOnPageLoadDefault$: new BehaviorSubject(true),
httpAuthenticationAvailable$: new BehaviorSubject(true),
},
},
],
@@ -414,13 +413,13 @@ const withHTTPAuthenticationFeatureFlag = moduleMetadata({
/** Editing a login with no URIs, so the HTTP authentication setting can be turned on */
export const HTTPAuthentication: Story = {
...Edit,
decorators: [withHTTPAuthenticationFeatureFlag],
decorators: [withHTTPAuthenticationAvailable],
};
/** Adding a login whose URI uses the default match strategy, so the HTTP authentication setting is disabled */
export const HTTPAuthenticationRequiresMatchDetection: Story = {
...Add,
decorators: [withHTTPAuthenticationFeatureFlag],
decorators: [withHTTPAuthenticationAvailable],
};
export const OrganizationDataOwnershipEnabled: Story = {

View File

@@ -3,10 +3,9 @@ import { ComponentFixture, TestBed } from "@angular/core/testing";
import { mock, MockProxy } from "jest-mock-extended";
import { BehaviorSubject } from "rxjs";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { ClientType } from "@bitwarden/common/enums";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { devFlagEnabled } from "@bitwarden/common/platform/misc/flags";
@@ -48,8 +47,8 @@ describe("AdditionalOptionsSectionComponent", () => {
let cipherFormProvider: MockProxy<CipherFormContainer>;
let passwordRepromptService: MockProxy<PasswordRepromptService>;
let passwordRepromptEnabled$: BehaviorSubject<boolean>;
let configService: MockProxy<ConfigService>;
let httpAuthenticationFeatureFlag$: BehaviorSubject<boolean>;
let autofillSettingsService: MockProxy<AutofillSettingsServiceAbstraction>;
let httpAuthenticationAvailable$: BehaviorSubject<boolean>;
let dialogService: MockProxy<DialogService>;
let platformUtilsService: MockProxy<PlatformUtilsService>;
let httpAuthenticationService: CipherFormHTTPAuthenticationService;
@@ -68,16 +67,12 @@ describe("AdditionalOptionsSectionComponent", () => {
passwordRepromptService = mock<PasswordRepromptService>();
passwordRepromptEnabled$ = new BehaviorSubject(true);
passwordRepromptService.enabled$ = passwordRepromptEnabled$;
httpAuthenticationFeatureFlag$ = new BehaviorSubject(true);
httpAuthenticationAvailable$ = new BehaviorSubject(true);
mockDevFlagEnabled.mockImplementation(
(flag: string) => flag === "httpAuthenticationCipherControls",
);
configService = mock<ConfigService>();
configService.getFeatureFlag$.mockImplementation((flag: FeatureFlag) =>
flag === FeatureFlag.EnableBasicAuthResponse
? httpAuthenticationFeatureFlag$
: new BehaviorSubject(false),
);
autofillSettingsService = mock<AutofillSettingsServiceAbstraction>();
autofillSettingsService.httpAuthenticationAvailable$ = httpAuthenticationAvailable$;
dialogService = mock<DialogService>();
dialogService.openSimpleDialog.mockResolvedValue(true);
platformUtilsService = mock<PlatformUtilsService>();
@@ -90,7 +85,7 @@ describe("AdditionalOptionsSectionComponent", () => {
{ provide: CipherFormContainer, useValue: cipherFormProvider },
{ provide: PasswordRepromptService, useValue: passwordRepromptService },
{ provide: I18nService, useValue: mock<I18nService>() },
{ provide: ConfigService, useValue: configService },
{ provide: AutofillSettingsServiceAbstraction, useValue: autofillSettingsService },
{ provide: PlatformUtilsService, useValue: platformUtilsService },
{ provide: DialogService, useValue: dialogService },
CipherFormHTTPAuthenticationService,
@@ -190,14 +185,14 @@ describe("AdditionalOptionsSectionComponent", () => {
const flushPromises = () => fixture.whenStable();
it("shows the HTTP authentication setting for login items when the feature flag and dev flag are on", () => {
it("shows the HTTP authentication setting for login items when HTTP authentication is available and the dev flag is on", () => {
fixture.detectChanges();
expect(getHTTPAuthenticationCheckbox()).not.toBeNull();
});
it("hides the HTTP authentication setting when the HTTP authentication feature flag is off", () => {
httpAuthenticationFeatureFlag$.next(false);
it("hides the HTTP authentication setting when HTTP authentication is unavailable", () => {
httpAuthenticationAvailable$.next(false);
fixture.detectChanges();
expect(getHTTPAuthenticationCheckbox()).toBeNull();
@@ -335,7 +330,7 @@ describe("AdditionalOptionsSectionComponent", () => {
});
it("turns HTTP authentication off without telling the user when the setting is hidden", async () => {
httpAuthenticationFeatureFlag$.next(false);
httpAuthenticationAvailable$.next(false);
loadCipher(true, true);
await flushPromises();

View File

@@ -7,8 +7,7 @@ import { FormBuilder, ReactiveFormsModule } from "@angular/forms";
import { combineLatest, concatMap, filter, firstValueFrom, map, shareReplay } from "rxjs";
import { JslibModule } from "@bitwarden/angular/jslib.module";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { devFlagEnabled } from "@bitwarden/common/platform/misc/flags";
import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums";
@@ -53,7 +52,7 @@ export class AdditionalOptionsSectionComponent implements OnInit {
@ViewChild(CustomFieldsComponent) customFieldsComponent: CustomFieldsComponent;
private httpAuthenticationService = inject(CipherFormHTTPAuthenticationService);
private configService = inject(ConfigService);
private autofillSettingsService = inject(AutofillSettingsServiceAbstraction);
private platformUtilsService = inject(PlatformUtilsService);
additionalOptionsForm = this.formBuilder.group({
@@ -67,16 +66,16 @@ export class AdditionalOptionsSectionComponent implements OnInit {
);
/**
* Emits true when the HTTP authentication setting is shown. It is shown on every client that edits logins,
* including the Safari extension, which can't answer HTTP authentication challenges itself. The
* cipher-level controls are also gated behind a dev flag until the challenge handler reads the setting.
* Emits true when the HTTP authentication setting is shown: for logins, while HTTP authentication is
* available. It is shown on every client that edits logins, including the Safari extension, which can't
* answer HTTP authentication challenges itself. The cipher-level controls are also gated behind a dev
* flag until every cipher format saves the setting.
*/
private readonly showHTTPAuthenticationCipherSetting$ = this.configService
.getFeatureFlag$(FeatureFlag.EnableBasicAuthResponse)
.pipe(
private readonly showHTTPAuthenticationCipherSetting$ =
this.autofillSettingsService.httpAuthenticationAvailable$.pipe(
map(
(httpAuthenticationEnabled) =>
httpAuthenticationEnabled &&
(httpAuthenticationAvailable) =>
httpAuthenticationAvailable &&
devFlagEnabled("httpAuthenticationCipherControls") &&
this.cipherFormContainer.config.cipherType === CipherType.Login,
),