diff --git a/bitwarden_license/bit-common/src/dirt/access-intelligence/report-flow-instrumentation.md b/bitwarden_license/bit-common/src/dirt/access-intelligence/report-flow-instrumentation.md index 1f12d1aede4..ae052cdb8f9 100644 --- a/bitwarden_license/bit-common/src/dirt/access-intelligence/report-flow-instrumentation.md +++ b/bitwarden_license/bit-common/src/dirt/access-intelligence/report-flow-instrumentation.md @@ -247,9 +247,7 @@ step encodes as part of the existing work and reads `byteLength` off the result. serialize would also have allocated a second copy of the largest artifact in the flow, which is the memory behavior under investigation. -This applies to the file storage path only. With that flag off the report is encrypted inline as a -single string instead, and that path carries no instrumentation at all, so nothing measures or -re-encodes the large report there either. +Reports are always persisted through the file storage path, so this applies to every save. #### The health checks are measured as one batch @@ -312,9 +310,6 @@ save returns as soon as the upload resolves, and no read path checks the validat **A page open that migrates legacy blobs is not separable from one that does not.** Both emit `Load: page initialized`, but the migrating run also performs a full save inside that window. -**The inline persistence path is not instrumented.** Only the file storage path carries -measurements. This gap closes when the inline path is removed. - --- **Document Version:** 1.0 diff --git a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/default-report-persistence.service.spec.ts b/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/default-report-persistence.service.spec.ts deleted file mode 100644 index 39b1672a6e1..00000000000 --- a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/default-report-persistence.service.spec.ts +++ /dev/null @@ -1,492 +0,0 @@ -import { mock, MockProxy } from "jest-mock-extended"; -import { firstValueFrom, of, throwError } from "rxjs"; - -import { Account, AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { makeEncString } from "@bitwarden/common/spec"; -import { OrganizationId, OrganizationReportId, UserId } from "@bitwarden/common/types/guid"; -import { LogService } from "@bitwarden/logging"; - -import { - AccessReport, - AccessReportSettingsView, - AccessReportSummaryView, - AccessReportView, -} from "../../../../access-intelligence/models"; -import { - GetRiskInsightsReportResponse, - SaveRiskInsightsReportResponse, -} from "../../../../reports/risk-insights/models/api-models.types"; -import { RiskInsightsApiService } from "../../../../reports/risk-insights/services/api/risk-insights-api.service"; -import { - createRiskInsights, - createAccessReportMetrics, - createRiskInsightsSummary, -} from "../../../../reports/risk-insights/testing/test-helpers"; -import { - AccessReportEncryptionService, - DecryptedAccessReportData, -} from "../../abstractions/access-report-encryption.service"; - -import { DefaultReportPersistenceService } from "./default-report-persistence.service"; - -describe("DefaultReportPersistenceService", () => { - let service: DefaultReportPersistenceService; - let mockApiService: MockProxy; - let mockEncryptionService: MockProxy; - let mockAccountService: MockProxy; - let mockLogService: MockProxy; - - const organizationId = "org-123" as OrganizationId; - const reportId = "report-456" as OrganizationReportId; - const userId = "user-789" as UserId; - - beforeEach(() => { - mockApiService = mock(); - mockEncryptionService = mock(); - mockAccountService = mock(); - mockLogService = mock(); - - const mockAccount = { id: userId } as Account; - mockAccountService.activeAccount$ = of(mockAccount); - - service = new DefaultReportPersistenceService( - mockApiService, - mockEncryptionService, - mockAccountService, - mockLogService, - ); - }); - - afterEach(() => { - jest.restoreAllMocks(); - }); - - describe("saveReport", () => { - it("should save report and return report ID", async () => { - // Create view model using helper - const view = createRiskInsights({ - organizationId, - creationDate: new Date(), - }); - - // Mock AccessReport.fromView$() to return domain model with encrypted data - const mockDomain = new AccessReport(); - mockDomain.organizationId = organizationId; - mockDomain.reports = makeEncString("encrypted-reports"); - mockDomain.summary = makeEncString("encrypted-summary"); - mockDomain.applications = makeEncString("encrypted-applications"); - mockDomain.contentEncryptionKey = makeEncString("encryption-key"); - mockDomain.creationDate = new Date(); - - jest.spyOn(AccessReport, "fromView$").mockReturnValue(of(mockDomain)); - - const saveResponse = new SaveRiskInsightsReportResponse({ id: reportId }); - mockApiService.saveRiskInsightsReport$.mockReturnValue(of(saveResponse)); - - const result = await firstValueFrom(service.saveReport$(view, organizationId)); - - expect(result.id).toBe(reportId); - expect(result.contentEncryptionKey).toBeDefined(); - expect(AccessReport.fromView$).toHaveBeenCalledWith(view, mockEncryptionService, { - organizationId, - userId, - }); - expect(mockApiService.saveRiskInsightsReport$).toHaveBeenCalledWith( - expect.objectContaining({ - data: expect.objectContaining({ - organizationId, - reportData: expect.any(String), - summaryData: expect.any(String), - applicationData: expect.any(String), - contentEncryptionKey: expect.any(String), - }), - }), - organizationId, - ); - expect(mockLogService.debug).toHaveBeenCalledWith( - "[DefaultReportPersistenceService] Saving report", - { organizationId }, - ); - }); - - it("should throw error if report has no encryption key", async () => { - const view = createRiskInsights({ organizationId }); - - // Mock domain model without encryption key - const mockDomain = new AccessReport(); - mockDomain.organizationId = organizationId; - mockDomain.contentEncryptionKey = undefined; - - jest.spyOn(AccessReport, "fromView$").mockReturnValue(of(mockDomain)); - - await expect(firstValueFrom(service.saveReport$(view, organizationId))).rejects.toThrow( - "Report encryption key not found", - ); - }); - - it("should handle API errors gracefully", async () => { - const view = createRiskInsights({ - organizationId, - creationDate: new Date(), - }); - - const mockDomain = new AccessReport(); - mockDomain.organizationId = organizationId; - mockDomain.contentEncryptionKey = makeEncString("key"); - mockDomain.reports = makeEncString("reports"); - mockDomain.summary = makeEncString("summary"); - mockDomain.applications = makeEncString("apps"); - mockDomain.creationDate = new Date(); - - jest.spyOn(AccessReport, "fromView$").mockReturnValue(of(mockDomain)); - - mockApiService.saveRiskInsightsReport$.mockReturnValue( - throwError(() => new Error("API error")), - ); - - await expect(firstValueFrom(service.saveReport$(view, organizationId))).rejects.toThrow( - "API error", - ); - }); - }); - - describe("saveApplicationMetadata", () => { - it("should save application metadata and summary", async () => { - const app1 = new AccessReportSettingsView(); - app1.applicationName = "github.com"; - app1.isCritical = true; - app1.reviewedDate = new Date(); - - const app2 = new AccessReportSettingsView(); - app2.applicationName = "gitlab.com"; - app2.isCritical = false; - app2.reviewedDate = undefined; - - const summary = createRiskInsightsSummary({ - totalApplicationCount: 2, - totalAtRiskApplicationCount: 1, - totalMemberCount: 10, - totalAtRiskMemberCount: 3, - }); - - // Create full view model using helper - const view = createRiskInsights({ - id: reportId, - organizationId, - applications: [app1, app2], - summary, - }); - - // Mock toMetrics() to return proper RiskInsightsMetrics instance - const mockMetrics = createAccessReportMetrics({ - totalApplicationCount: 2, - totalAtRiskApplicationCount: 1, - totalMemberCount: 10, - totalAtRiskMemberCount: 3, - }); - jest.spyOn(view, "toMetrics").mockReturnValue(mockMetrics); - - // Mock AccessReport.fromView$() to return domain model - const mockDomain = new AccessReport(); - mockDomain.reports = makeEncString("encrypted-reports"); - mockDomain.summary = makeEncString("encrypted-summary"); - mockDomain.applications = makeEncString("encrypted-apps"); - mockDomain.contentEncryptionKey = makeEncString("key"); - - jest.spyOn(AccessReport, "fromView$").mockReturnValue(of(mockDomain)); - - // Using {} as any for mock response (acceptable per testing standards for mock objects) - mockApiService.updateRiskInsightsApplicationData$.mockReturnValue(of({} as any)); - mockApiService.updateRiskInsightsSummary$.mockReturnValue(of(undefined)); - - await firstValueFrom(service.saveApplicationMetadata$(view)); - - expect(AccessReport.fromView$).toHaveBeenCalledWith(view, mockEncryptionService, { - organizationId, - userId, - }); - - expect(mockApiService.updateRiskInsightsApplicationData$).toHaveBeenCalledWith( - reportId, - organizationId, - expect.objectContaining({ - data: { - applicationData: expect.any(String), - }, - }), - ); - - expect(mockApiService.updateRiskInsightsSummary$).toHaveBeenCalledWith( - reportId, - organizationId, - expect.objectContaining({ - data: { - summaryData: expect.any(String), - metrics: expect.objectContaining({ - totalApplicationCount: 2, - totalAtRiskApplicationCount: 1, - }), - }, - }), - ); - - expect(view.toMetrics).toHaveBeenCalled(); - }); - - it("should throw error if user ID not found", async () => { - mockAccountService.activeAccount$ = of(null as any); - - const view = createRiskInsights({ - id: reportId, - organizationId, - }); - - await expect(firstValueFrom(service.saveApplicationMetadata$(view))).rejects.toThrow( - "Null or undefined account", - ); - }); - - it("should handle encryption errors", async () => { - const view = createRiskInsights({ - id: reportId, - organizationId, - }); - - jest - .spyOn(AccessReport, "fromView$") - .mockReturnValue(throwError(() => new Error("Encryption failed"))); - - await expect(firstValueFrom(service.saveApplicationMetadata$(view))).rejects.toThrow( - "Encryption failed", - ); - }); - - it("should handle API update failures", async () => { - const view = createRiskInsights({ - id: reportId, - organizationId, - }); - - const mockDomain = new AccessReport(); - mockDomain.reports = makeEncString("encrypted-reports"); - mockDomain.summary = makeEncString("encrypted-summary"); - mockDomain.applications = makeEncString("encrypted-apps"); - mockDomain.contentEncryptionKey = makeEncString("key"); - - jest.spyOn(AccessReport, "fromView$").mockReturnValue(of(mockDomain)); - - mockApiService.updateRiskInsightsApplicationData$.mockReturnValue( - throwError(() => new Error("Update failed")), - ); - - await expect(firstValueFrom(service.saveApplicationMetadata$(view))).rejects.toThrow( - "Update failed", - ); - }); - }); - - describe("loadReport", () => { - it("should load and decrypt report successfully", async () => { - const apiResponse = new GetRiskInsightsReportResponse({ - id: reportId, - organizationId, - creationDate: new Date().toISOString(), - reportData: "encrypted-reports", - summaryData: "encrypted-summary", - applicationData: "encrypted-apps", - contentEncryptionKey: "encryption-key", - }); - - const decryptedData: DecryptedAccessReportData = { - reportData: { - reports: [ - { - applicationName: "github.com", - passwordCount: 2, - atRiskPasswordCount: 1, - memberCount: 1, - atRiskMemberCount: 1, - cipherRefs: { "cipher-1": true, "cipher-2": false }, - memberRefs: { "member-1": true }, - }, - ], - memberRegistry: { - "member-1": { id: "member-1", userName: "John Doe", email: "john@example.com" }, - }, - }, - summaryData: AccessReportSummaryView.fromJSON({ - totalMemberCount: 10, - totalAtRiskMemberCount: 3, - totalApplicationCount: 5, - totalAtRiskApplicationCount: 2, - totalCriticalMemberCount: 2, - totalCriticalAtRiskMemberCount: 1, - totalCriticalApplicationCount: 1, - totalCriticalAtRiskApplicationCount: 1, - totalPasswordCount: 0, - totalAtRiskPasswordCount: 0, - totalCriticalPasswordCount: 0, - totalCriticalAtRiskPasswordCount: 0, - }), - applicationData: [ - { - applicationName: "github.com", - isCritical: true, - reviewedDate: "2024-01-15T10:30:00.000Z", - }, - ], - }; - - mockApiService.getRiskInsightsReport$.mockReturnValue(of(apiResponse)); - mockEncryptionService.decryptReport$.mockReturnValue(of(decryptedData)); - - const result = await firstValueFrom(service.loadLastReport$(organizationId)); - - expect(result!.report).toBeInstanceOf(AccessReportView); - expect(result!.report.id).toBe(reportId); - expect(result!.report.organizationId).toBe(organizationId); - expect(result!.report.reports).toHaveLength(1); - expect(result!.report.applications).toHaveLength(1); - expect(result!.report.summary.totalApplicationCount).toBe(5); - - expect(mockLogService.debug).toHaveBeenCalledWith( - "[DefaultReportPersistenceService] Loading report", - { organizationId }, - ); - }); - - it("should return null if no report exists", async () => { - mockApiService.getRiskInsightsReport$.mockReturnValue(of(null)); - - const result = await firstValueFrom(service.loadLastReport$(organizationId)); - - expect(result).toBeNull(); - expect(mockEncryptionService.decryptReport$).not.toHaveBeenCalled(); - }); - - it("should throw error if encryption key missing", async () => { - const apiResponse = new GetRiskInsightsReportResponse({ - id: reportId, - organizationId, - creationDate: new Date().toISOString(), - reportData: "encrypted-reports", - summaryData: "encrypted-summary", - applicationData: "encrypted-apps", - contentEncryptionKey: "", - }); - - mockApiService.getRiskInsightsReport$.mockReturnValue(of(apiResponse)); - - await expect(firstValueFrom(service.loadLastReport$(organizationId))).rejects.toThrow( - "Report encryption key not found", - ); - }); - - it("should throw error if user ID not found", async () => { - mockAccountService.activeAccount$ = of(null as any); - - await expect(firstValueFrom(service.loadLastReport$(organizationId))).rejects.toThrow( - "Null or undefined account", - ); - }); - - it("should handle decryption errors", async () => { - const apiResponse = new GetRiskInsightsReportResponse({ - id: reportId, - organizationId, - creationDate: new Date().toISOString(), - reportData: "encrypted-reports", - summaryData: "encrypted-summary", - applicationData: "encrypted-apps", - contentEncryptionKey: "encryption-key", - }); - - mockApiService.getRiskInsightsReport$.mockReturnValue(of(apiResponse)); - mockEncryptionService.decryptReport$.mockReturnValue( - throwError(() => new Error("Decryption failed")), - ); - - await expect(firstValueFrom(service.loadLastReport$(organizationId))).rejects.toThrow( - "Decryption failed", - ); - }); - - it("should convert report data to view models correctly", async () => { - const apiResponse = new GetRiskInsightsReportResponse({ - id: reportId, - organizationId, - creationDate: new Date().toISOString(), - reportData: "encrypted-reports", - summaryData: "encrypted-summary", - applicationData: "encrypted-apps", - contentEncryptionKey: "encryption-key", - }); - - const decryptedData: DecryptedAccessReportData = { - reportData: { - reports: [ - { - applicationName: "gitlab.com", - passwordCount: 3, - atRiskPasswordCount: 1, - memberCount: 2, - atRiskMemberCount: 1, - cipherRefs: { c1: false, c2: true, c3: false }, - memberRefs: { m1: true, m2: false }, - }, - ], - memberRegistry: { - m1: { id: "m1", userName: "Alice", email: "alice@example.com" }, - m2: { id: "m2", userName: "Bob", email: "bob@example.com" }, - }, - }, - summaryData: AccessReportSummaryView.fromJSON({ - totalMemberCount: 20, - totalAtRiskMemberCount: 5, - totalApplicationCount: 10, - totalAtRiskApplicationCount: 3, - totalCriticalMemberCount: 4, - totalCriticalAtRiskMemberCount: 2, - totalCriticalApplicationCount: 2, - totalCriticalAtRiskApplicationCount: 1, - totalPasswordCount: 0, - totalAtRiskPasswordCount: 0, - totalCriticalPasswordCount: 0, - totalCriticalAtRiskPasswordCount: 0, - }), - applicationData: [ - { - applicationName: "gitlab.com", - isCritical: false, - reviewedDate: undefined, - }, - ], - }; - - mockApiService.getRiskInsightsReport$.mockReturnValue(of(apiResponse)); - mockEncryptionService.decryptReport$.mockReturnValue(of(decryptedData)); - - const result = await firstValueFrom(service.loadLastReport$(organizationId)); - - expect(result!.report.reports[0].applicationName).toBe("gitlab.com"); - expect(result!.report.reports[0].passwordCount).toBe(3); - expect(result!.report.reports[0].atRiskPasswordCount).toBe(1); - expect(result!.report.reports[0].memberCount).toBe(2); - expect(result!.report.reports[0].atRiskMemberCount).toBe(1); - - expect(result!.report.reports[0].cipherRefs["c1"]).toBe(false); - expect(result!.report.reports[0].cipherRefs["c2"]).toBe(true); - expect(result!.report.reports[0].cipherRefs["c3"]).toBe(false); - - expect(result!.report.reports[0].memberRefs["m1"]).toBe(true); - expect(result!.report.reports[0].memberRefs["m2"]).toBe(false); - - expect(result!.report.applications[0].applicationName).toBe("gitlab.com"); - expect(result!.report.applications[0].isCritical).toBe(false); - expect(result!.report.applications[0].reviewedDate).toBeUndefined(); - - expect(result!.report.summary.totalMemberCount).toBe(20); - expect(result!.report.summary.totalAtRiskMemberCount).toBe(5); - }); - }); -}); diff --git a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/default-report-persistence.service.ts b/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/default-report-persistence.service.ts deleted file mode 100644 index b0bbd7117d9..00000000000 --- a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/default-report-persistence.service.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { forkJoin, map, Observable, of, switchMap, take, throwError } from "rxjs"; - -import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { getUserId } from "@bitwarden/common/auth/services/account.service"; -import { OrganizationId, OrganizationReportId } from "@bitwarden/common/types/guid"; -// eslint-disable-next-line no-restricted-imports -import { EncString } from "@bitwarden/legacy-crypto"; -import { LogService } from "@bitwarden/logging"; - -import { RiskInsightsApiService } from "../../../../reports/risk-insights/services/api/risk-insights-api.service"; -import { AccessReportData, AccessReport, AccessReportView } from "../../../models"; -import { AccessReportEncryptionService } from "../../abstractions/access-report-encryption.service"; -import { ReportPersistenceService } from "../../abstractions/report-persistence.service"; - -/** - * Default implementation of ReportPersistenceService using current DB backend. - * - * Delegates encryption/decryption to domain model. - * Orchestrates API calls for persistence operations. - */ -export class DefaultReportPersistenceService extends ReportPersistenceService { - constructor( - private riskInsightsApiService: RiskInsightsApiService, - private riskInsightsEncryptionService: AccessReportEncryptionService, - private accountService: AccountService, - private logService: LogService, - ) { - super(); - } - - saveReport$( - view: AccessReportView, - organizationId: OrganizationId, - ): Observable<{ id: OrganizationReportId; contentEncryptionKey: EncString }> { - this.logService.debug("[DefaultReportPersistenceService] Saving report", { - organizationId, - }); - - return getUserId(this.accountService.activeAccount$).pipe( - take(1), - switchMap((userId) => - AccessReport.fromView$(view, this.riskInsightsEncryptionService, { - organizationId, - userId, - }).pipe( - switchMap((domain) => { - if (!domain.contentEncryptionKey) { - return throwError(() => new Error("Report encryption key not found")); - } - - // Extract encrypted data and compute metrics from view - const data = domain.toData(); - const metrics = view.toMetrics(); - - const requestPayload = { - data: { - organizationId, - creationDate: data.creationDate, - reportData: data.reports, - summaryData: data.summary, - applicationData: data.applications, - contentEncryptionKey: data.contentEncryptionKey, - metrics: metrics.toAccessReportMetricsData(), - }, - }; - - return this.riskInsightsApiService - .saveRiskInsightsReport$(requestPayload, organizationId) - .pipe( - map((response) => ({ - id: response.id, - contentEncryptionKey: domain.contentEncryptionKey!, - })), - ); - }), - ), - ), - ); - } - - saveApplicationMetadata$(view: AccessReportView): Observable { - this.logService.debug("[DefaultReportPersistenceService] Saving application metadata", { - reportId: view.id, - organizationId: view.organizationId, - applicationCount: view.applications.length, - }); - - return getUserId(this.accountService.activeAccount$).pipe( - take(1), - switchMap((userId) => - AccessReport.fromView$(view, this.riskInsightsEncryptionService, { - organizationId: view.organizationId, - userId, - }).pipe( - switchMap((domain) => { - const data = domain.toData(); - const metrics = view.toMetrics(); - - const updateApplicationsCall = - this.riskInsightsApiService.updateRiskInsightsApplicationData$( - view.id, - view.organizationId, - { - data: { - applicationData: data.applications, - }, - }, - ); - - const updateSummaryCall = this.riskInsightsApiService.updateRiskInsightsSummary$( - view.id, - view.organizationId, - { - data: { - summaryData: data.summary, - metrics: metrics.toAccessReportMetricsData(), - }, - }, - ); - - return forkJoin([updateApplicationsCall, updateSummaryCall]).pipe( - map(() => undefined as void), - ); - }), - ), - ), - ); - } - - loadLastReport$( - organizationId: OrganizationId, - ): Observable<{ report: AccessReportView; hadLegacyBlobs: boolean } | null> { - this.logService.debug("[DefaultReportPersistenceService] Loading report", { organizationId }); - - return getUserId(this.accountService.activeAccount$).pipe( - take(1), - switchMap((userId) => - this.riskInsightsApiService.getRiskInsightsReport$(organizationId).pipe( - switchMap((apiResponse) => { - if (!apiResponse) { - return of(null); - } - - if ( - !apiResponse.contentEncryptionKey || - !apiResponse.contentEncryptionKey.encryptedString || - apiResponse.contentEncryptionKey.encryptedString === "" - ) { - throw new Error("Report encryption key not found"); - } - - // Convert API → Data → Domain → View (following 4-layer architecture) - const data = new AccessReportData(); - data.id = apiResponse.id; - data.organizationId = apiResponse.organizationId; - data.reports = apiResponse.reportData.encryptedString ?? ""; - data.summary = apiResponse.summaryData.encryptedString ?? ""; - data.applications = apiResponse.applicationData.encryptedString ?? ""; - data.creationDate = apiResponse.creationDate.toISOString(); - data.contentEncryptionKey = apiResponse.contentEncryptionKey.encryptedString ?? ""; - - const domain = new AccessReport(data); - - // Domain handles its own decryption - return domain - .decrypt$(this.riskInsightsEncryptionService, { organizationId, userId }) - .pipe(map(({ view, hadLegacyBlobs }) => ({ report: view, hadLegacyBlobs }))); - }), - ), - ), - ); - } -} diff --git a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/report-persistence-feature-flag.service.spec.ts b/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/report-persistence-feature-flag.service.spec.ts deleted file mode 100644 index 07949461511..00000000000 --- a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/report-persistence-feature-flag.service.spec.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { mock, MockProxy } from "jest-mock-extended"; -import { firstValueFrom, of } from "rxjs"; - -import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { OrganizationId, OrganizationReportId } from "@bitwarden/common/types/guid"; - -import { AccessReportView } from "../../../models"; - -import { DefaultReportPersistenceService } from "./default-report-persistence.service"; -import { FileReportPersistenceService } from "./file-report-persistence.service"; -import { ReportPersistenceFeatureFlagService } from "./report-persistence-feature-flag.service"; - -describe("ReportPersistenceFeatureFlagService", () => { - let service: ReportPersistenceFeatureFlagService; - let fileService: MockProxy; - let defaultService: MockProxy; - let configService: MockProxy; - - const orgId = "org-123" as OrganizationId; - const reportId = "report-456" as OrganizationReportId; - const view = mock(); - - beforeEach(() => { - fileService = mock(); - defaultService = mock(); - configService = mock(); - - service = new ReportPersistenceFeatureFlagService(fileService, defaultService, configService); - }); - - describe("loadLastReport$", () => { - it("always delegates to fileService", async () => { - const expected = { report: view, hadLegacyBlobs: false }; - fileService.loadLastReport$.mockReturnValue(of(expected)); - - const result = await firstValueFrom(service.loadLastReport$(orgId)); - - expect(fileService.loadLastReport$).toHaveBeenCalledWith(orgId); - expect(defaultService.loadLastReport$).not.toHaveBeenCalled(); - expect(result).toBe(expected); - }); - - it("does not read the file-storage flag for loads", async () => { - fileService.loadLastReport$.mockReturnValue(of(null)); - - await firstValueFrom(service.loadLastReport$(orgId)); - - expect(configService.getFeatureFlag$).not.toHaveBeenCalled(); - }); - }); - - describe("saveApplicationMetadata$", () => { - it("delegates to fileService when flag is enabled", async () => { - configService.getFeatureFlag$.mockReturnValue(of(true)); - fileService.saveApplicationMetadata$.mockReturnValue(of(undefined)); - - await firstValueFrom(service.saveApplicationMetadata$(view)); - - expect(fileService.saveApplicationMetadata$).toHaveBeenCalledWith(view); - expect(defaultService.saveApplicationMetadata$).not.toHaveBeenCalled(); - }); - - it("delegates to defaultService when flag is disabled", async () => { - configService.getFeatureFlag$.mockReturnValue(of(false)); - defaultService.saveApplicationMetadata$.mockReturnValue(of(undefined)); - - await firstValueFrom(service.saveApplicationMetadata$(view)); - - expect(defaultService.saveApplicationMetadata$).toHaveBeenCalledWith(view); - expect(fileService.saveApplicationMetadata$).not.toHaveBeenCalled(); - }); - }); - - describe("saveReport$", () => { - it("delegates to fileService when flag is enabled", async () => { - const encString = {} as any; - const expected = { id: reportId, contentEncryptionKey: encString }; - configService.getFeatureFlag$.mockReturnValue(of(true)); - fileService.saveReport$.mockReturnValue(of(expected)); - - const result = await firstValueFrom(service.saveReport$(view, orgId)); - - expect(fileService.saveReport$).toHaveBeenCalledWith(view, orgId); - expect(defaultService.saveReport$).not.toHaveBeenCalled(); - expect(result).toBe(expected); - }); - - it("delegates to defaultService when flag is disabled", async () => { - const encString = {} as any; - const expected = { id: reportId, contentEncryptionKey: encString }; - configService.getFeatureFlag$.mockReturnValue(of(false)); - defaultService.saveReport$.mockReturnValue(of(expected)); - - const result = await firstValueFrom(service.saveReport$(view, orgId)); - - expect(defaultService.saveReport$).toHaveBeenCalledWith(view, orgId); - expect(fileService.saveReport$).not.toHaveBeenCalled(); - expect(result).toBe(expected); - }); - }); -}); diff --git a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/report-persistence-feature-flag.service.ts b/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/report-persistence-feature-flag.service.ts deleted file mode 100644 index 7fec062b156..00000000000 --- a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/implementations/persistence/report-persistence-feature-flag.service.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { first, Observable, switchMap } from "rxjs"; - -import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; -import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { OrganizationId, OrganizationReportId } from "@bitwarden/common/types/guid"; -// eslint-disable-next-line no-restricted-imports -import { EncString } from "@bitwarden/legacy-crypto"; - -import { AccessReportView } from "../../../models"; -import { ReportPersistenceService } from "../../abstractions/report-persistence.service"; - -import { DefaultReportPersistenceService } from "./default-report-persistence.service"; -import { FileReportPersistenceService } from "./file-report-persistence.service"; - -export class ReportPersistenceFeatureFlagService extends ReportPersistenceService { - constructor( - private filePersistenceService: FileReportPersistenceService, - private defaultPersistenceService: DefaultReportPersistenceService, - private configService: ConfigService, - ) { - super(); - } - - loadLastReport$( - organizationId: OrganizationId, - ): Observable<{ report: AccessReportView; hadLegacyBlobs: boolean } | null> { - // Unlike the save methods, loads are not gated on the file-storage flag: the flag governs - // write format only. FileReportPersistenceService handles both the file-download path and an - // inline fallback, so it reads back reports in either format regardless of the flag's value. - return this.filePersistenceService.loadLastReport$(organizationId); - } - - saveApplicationMetadata$(view: AccessReportView): Observable { - return this.configService.getFeatureFlag$(FeatureFlag.AccessIntelligenceReportFileStorage).pipe( - first(), - switchMap((useFileStorage) => - useFileStorage - ? this.filePersistenceService.saveApplicationMetadata$(view) - : this.defaultPersistenceService.saveApplicationMetadata$(view), - ), - ); - } - - saveReport$( - view: AccessReportView, - organizationId: OrganizationId, - ): Observable<{ id: OrganizationReportId; contentEncryptionKey: EncString }> { - return this.configService.getFeatureFlag$(FeatureFlag.AccessIntelligenceReportFileStorage).pipe( - first(), - switchMap((useFileStorage) => - useFileStorage - ? this.filePersistenceService.saveReport$(view, organizationId) - : this.defaultPersistenceService.saveReport$(view, organizationId), - ), - ); - } -} diff --git a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/index.ts b/bitwarden_license/bit-common/src/dirt/access-intelligence/services/index.ts index 7a58e03d6bf..c315b7a1868 100644 --- a/bitwarden_license/bit-common/src/dirt/access-intelligence/services/index.ts +++ b/bitwarden_license/bit-common/src/dirt/access-intelligence/services/index.ts @@ -19,11 +19,9 @@ export * from "./implementations/domain/default-report-generation.service"; // Persistence implementations export * from "./implementations/persistence/default-access-report-encryption.service"; -export * from "./implementations/persistence/default-report-persistence.service"; export * from "./implementations/persistence/versioning/application-versioning.service"; export * from "./implementations/persistence/versioning/report-versioning.service"; export * from "./implementations/persistence/versioning/summary-versioning.service"; -export * from "./implementations/persistence/report-persistence-feature-flag.service"; export * from "./implementations/persistence/file-report-persistence.service"; // View implementations diff --git a/bitwarden_license/bit-web/src/app/dirt/access-intelligence/access-intelligence-routing.module.ts b/bitwarden_license/bit-web/src/app/dirt/access-intelligence/access-intelligence-routing.module.ts index ccbd725c283..eb5e7375a03 100644 --- a/bitwarden_license/bit-web/src/app/dirt/access-intelligence/access-intelligence-routing.module.ts +++ b/bitwarden_license/bit-web/src/app/dirt/access-intelligence/access-intelligence-routing.module.ts @@ -16,13 +16,11 @@ import { DefaultDrawerStateService, DefaultMemberCipherMappingService, DefaultReportGenerationService, - DefaultReportPersistenceService, DrawerStateService, FileReportPersistenceService, LegacyRiskInsightsEncryptionService, MemberCipherMappingService, ReportGenerationService, - ReportPersistenceFeatureFlagService, ReportPersistenceService, } from "@bitwarden/bit-common/dirt/access-intelligence/services"; import { CriticalAppsService } from "@bitwarden/bit-common/dirt/reports/risk-insights"; @@ -163,16 +161,8 @@ const v2Providers = [ deps: [ApiService], }), safeProvider({ - provide: DefaultReportPersistenceService, - deps: [ - RiskInsightsApiService, - AccessReportEncryptionService, - AccountServiceAbstraction, - LogService, - ], - }), - safeProvider({ - provide: FileReportPersistenceService, + provide: ReportPersistenceService, + useClass: FileReportPersistenceService, deps: [ AccessIntelligenceApiService, AccessReportEncryptionService, @@ -181,11 +171,6 @@ const v2Providers = [ FileUploadService, ], }), - safeProvider({ - provide: ReportPersistenceService, - useClass: ReportPersistenceFeatureFlagService, - deps: [FileReportPersistenceService, DefaultReportPersistenceService, ConfigService], - }), safeProvider({ provide: AccessIntelligenceDataService, useClass: DefaultAccessIntelligenceDataService, diff --git a/libs/common/src/enums/feature-flag.enum.ts b/libs/common/src/enums/feature-flag.enum.ts index a3af0db697b..c34e7637f86 100644 --- a/libs/common/src/enums/feature-flag.enum.ts +++ b/libs/common/src/enums/feature-flag.enum.ts @@ -81,7 +81,6 @@ export enum FeatureFlag { Milestone11AppPageImprovements = "pm-30538-dirt-milestone-11-app-page-improvements", AccessIntelligenceNewArchitecture = "pm-31936-access-intelligence-new-architecture", PasskeyLoginReport = "inno-passkey-directory-report", - AccessIntelligenceReportFileStorage = "pm-31920-access-intelligence-azure-file-storage", AccessIntelligenceAdoptionUxImprovements = "pm-34723-access-intelligence-adoption-ux-improvements", BrowserExtensionHealthReport = "pm-35928-premium-user-health-reports", HealthReportExclusions = "pm-39196-health-report-exclusions", @@ -160,7 +159,6 @@ export const DefaultFeatureFlagValue = { [FeatureFlag.Milestone11AppPageImprovements]: FALSE, [FeatureFlag.AccessIntelligenceNewArchitecture]: FALSE, [FeatureFlag.PasskeyLoginReport]: FALSE, - [FeatureFlag.AccessIntelligenceReportFileStorage]: FALSE, [FeatureFlag.AccessIntelligenceAdoptionUxImprovements]: FALSE, [FeatureFlag.BrowserExtensionHealthReport]: FALSE, [FeatureFlag.HealthReportExclusions]: FALSE,