Openverse is a search engine for openly-licensed media. This monorepo includes all application code.
Allow feature flags to use `sessionStorage` and ignore `ff_` query params (#2121)
Dhruv Bhanushali937baed4d1f2
diff --git a/documentation/frontend/reference/feature_flags.md b/documentation/frontend/reference/feature_flags.mdindex 9da58d876..3167e91ac 100644--- a/documentation/frontend/reference/feature_flags.md+++ b/documentation/frontend/reference/feature_flags.md@@ -101,6 +101,20 @@ page.should [populate `en.json5`](#key-title) if the feature is switchable andvisible to the user.+##### `storage`++This determines whether the feature is stored in a cookie (`'cookie'`) or in+`sessionStorage` (`'session'`). By default all feature flags are stored in+cookies but certain preferences that should only be applicable for a single+session can be stored in `sessionStorage` instead.++##### `supportsQuery`++By default, all switchable flags can be set per-request using the `ff_<flag>`+query parameters. This is useful for testing and debugging. However, some flags+dealing with sensitivity can be used to make malicious URLs, so they can avoid+being set via query parameters by setting this to `false`.+### `groups`This setting pertains to how feature flags can serve as user-level preferences.diff --git a/frontend/feat/feature-flags.json b/frontend/feat/feature-flags.jsonindex 54c7ff4db..d265c9351 100644--- a/frontend/feat/feature-flags.json+++ b/frontend/feat/feature-flags.json@@ -6,7 +6,8 @@"production": "disabled"},"description": "Mark 50% of results as mature to test content safety.",- "defaultState": "off"+ "defaultState": "off",+ "storage": "cookie"},"external_sources": {"status": {@@ -14,14 +15,32 @@"production": "disabled"},"description": "Toggle the external sources in the header's search type switcher.",- "defaultState": "off"+ "defaultState": "off",+ "storage": "cookie"},"analytics": {"status": {"staging": "switchable","production": "disabled"},- "description": "Record custom events and page views."+ "description": "Record custom events and page views.",+ "storage": "cookie"+ },+ "sensitive_content": {+ "status": {+ "staging": "switchable",+ "production": "disabled"+ },+ "description": "Turn on sensitive content fetching and blurring.",+ "defaultState": "off",+ "storage": "cookie"+ },+ "fetch_sensitive": {+ "status": "switchable",+ "defaultState": "off",+ "description": "Show results marked as sensitive in the results area.",+ "supportsQuery": false,+ "storage": "session"}},"groups": [diff --git a/frontend/src/constants/feature-flag.ts b/frontend/src/constants/feature-flag.tsindex ec626b3cd..aca99ada9 100644--- a/frontend/src/constants/feature-flag.ts+++ b/frontend/src/constants/feature-flag.ts@@ -12,3 +12,10 @@ export const OFF = "off"export const FEATURE_STATES = [ON, OFF] as constexport type FeatureState = typeof FEATURE_STATES[number]++export const SESSION = "session"+export const COOKIE = "cookie"++export const STORAGES = [SESSION, COOKIE] as const++export type Storage = typeof STORAGES[number]diff --git a/frontend/src/layouts/content-layout.vue b/frontend/src/layouts/content-layout.vueindex d0de52baa..ed0dd44c4 100644--- a/frontend/src/layouts/content-layout.vue+++ b/frontend/src/layouts/content-layout.vue@@ -54,6 +54,7 @@ import { useLayout } from "~/composables/use-layout"import { useUiStore } from "~/stores/ui"import { useSearchStore } from "~/stores/search"+import { useFeatureFlagStore } from "~/stores/feature-flag"import { IsHeaderScrolledKey, IsSidebarVisibleKey } from "~/types/provides"@@ -87,6 +88,11 @@ export default defineComponent({const uiStore = useUiStore()const searchStore = useSearchStore()+ const featureStore = useFeatureFlagStore()+ onMounted(() => {+ featureStore.initFromSession()+ })+const { updateBreakpoint } = useLayout()/**diff --git a/frontend/src/layouts/default.vue b/frontend/src/layouts/default.vueindex d20ee9123..93a1b42a5 100644--- a/frontend/src/layouts/default.vue+++ b/frontend/src/layouts/default.vue@@ -22,6 +22,7 @@ import { PortalTarget as VTeleportTarget } from "portal-vue"import { useLayout } from "~/composables/use-layout"import { useUiStore } from "~/stores/ui"+import { useFeatureFlagStore } from "~/stores/feature-flag"import VBanners from "~/components/VBanner/VBanners.vue"import VFooter from "~/components/VFooter/VFooter.vue"@@ -45,6 +46,11 @@ export default defineComponent({setup() {const uiStore = useUiStore()+ const featureStore = useFeatureFlagStore()+ onMounted(() => {+ featureStore.initFromSession()+ })+const { updateBreakpoint } = useLayout()/**diff --git a/frontend/src/stores/feature-flag.ts b/frontend/src/stores/feature-flag.tsindex c50a368fb..59eb8f94a 100644--- a/frontend/src/stores/feature-flag.ts+++ b/frontend/src/stores/feature-flag.ts@@ -1,5 +1,5 @@+import Vue from "vue"import { defineStore } from "pinia"-import { useStorage } from "@vueuse/core"import featureData from "~~/feat/feature-flags.json"@@ -15,9 +15,13 @@ import {ON,OFF,DISABLED,+ COOKIE,+ SESSION,} from "~/constants/feature-flag"import { LOCAL, DEPLOY_ENVS, DeployEnv } from "~/constants/deploy-env"+import type { Context } from "@nuxt/types"+import type { Dictionary } from "vue-router/types/router"type FlagName = keyof typeof featureData["features"]@@ -93,14 +97,16 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {/*** Get the mapping of switchable features to their preferred states.*/- flagStateMap: (state: FeatureFlagState): Record<string, FeatureState> => {- const featureMap: Record<string, FeatureState> = {}- Object.entries(state.flags).forEach(([name, flag]) => {- if (getFlagStatus(flag) === SWITCHABLE)- featureMap[name] = getFeatureState(flag)- })- return featureMap- },+ flagStateMap:+ (state: FeatureFlagState) =>+ (dest: string): Record<string, FeatureState> => {+ const featureMap: Record<string, FeatureState> = {}+ Object.entries(state.flags).forEach(([name, flag]) => {+ if (getFlagStatus(flag) === SWITCHABLE && flag.storage === dest)+ featureMap[name] = getFeatureState(flag)+ })+ return featureMap+ },},actions: {/**@@ -114,8 +120,33 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {*/initFromCookies(cookies: Record<string, FeatureState>) {Object.entries(this.flags).forEach(([name, flag]) => {- if (getFlagStatus(flag) === SWITCHABLE)- flag.preferredState = cookies[name]+ if (getFlagStatus(flag) === SWITCHABLE && flag.storage === COOKIE)+ Vue.set(flag, "preferredState", cookies[name])+ })+ },+ /**+ * Write the current state of the switchable flags to the cookie.+ *+ * @param cookies - the Nuxt cookies module+ */+ writeToCookies(cookies: Context["$cookies"]) {+ cookies.set("features", this.flagStateMap(COOKIE))+ },+ /**+ * Initialize the state of the switchable flags from the session storage.+ * `Vue.set` is used to ensure reactivity is maintained.+ */+ initFromSession() {+ if (typeof window === "undefined") return+ const features = useStorage<Record<string, FeatureState>>(+ "features",+ {},+ sessionStorage+ )+ Object.entries(this.flags).forEach(([name, flag]) => {+ if (getFlagStatus(flag) === SWITCHABLE && flag.storage === SESSION) {+ Vue.set(flag, "preferredState", features.value[name])+ }})},/**@@ -123,7 +154,19 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {* are read in the corresponding `initFromCookies` method.*/writeToCookie() {- this.$nuxt.$cookies.set("features", this.flagStateMap)+ this.$nuxt.$cookies.set("features", this.flagStateMap(COOKIE))+ },+ /**+ * Write the current state of the switchable flags to the session storage.+ */+ writeToSession() {+ if (typeof window === "undefined") return+ const features = useStorage<Record<string, FeatureState>>(+ "features",+ {},+ sessionStorage+ )+ features.value = this.flagStateMap(SESSION)},/*** Set the value of flag entries from the query parameters. Only those@@ -152,8 +195,11 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {// TODO: type `FlagName` should be inferred by TSconst flagName = name.substring(3) as FlagNameconst flag = this.flags[flagName]- if (getFlagStatus(flag) === SWITCHABLE) {- flag.preferredState = state+ if (+ getFlagStatus(flag) === SWITCHABLE &&+ flag.supportsQuery !== false+ ) {+ Vue.set(flag, "preferredState", state)}})},@@ -168,6 +214,7 @@ export const useFeatureFlagStore = defineStore(FEATURE_FLAG, {if (getFlagStatus(flag) === SWITCHABLE) {flag.preferredState = targetStatethis.writeToCookie()+ this.writeToSession()if (name === "analytics") this.syncAnalyticsWithLocalStorage()} else warn(`Cannot set preferred state for non-switchable flag: ${name}`)},diff --git a/frontend/src/types/feature-flag.ts b/frontend/src/types/feature-flag.tsindex f45736d9d..8fe6ab4e4 100644--- a/frontend/src/types/feature-flag.ts+++ b/frontend/src/types/feature-flag.ts@@ -1,4 +1,8 @@-import type { FeatureState, FlagStatus } from "~/constants/feature-flag"+import type {+ FeatureState,+ FlagStatus,+ Storage,+} from "~/constants/feature-flag"import type { DeployEnv } from "~/constants/deploy-env"export interface FeatureFlag {@@ -8,4 +12,8 @@ export interface FeatureFlag {defaultState?: FeatureStatepreferredState?: FeatureState // only set for switchable flag with known preference++ supportsQuery?: boolean // default: true++ storage: Storage}diff --git a/frontend/test/unit/specs/stores/feature-flag-store.spec.js b/frontend/test/unit/specs/stores/feature-flag-store.spec.jsindex bc5b0863f..ace9e971e 100644--- a/frontend/test/unit/specs/stores/feature-flag-store.spec.js+++ b/frontend/test/unit/specs/stores/feature-flag-store.spec.js@@ -1,7 +1,7 @@import { setActivePinia, createPinia } from "~~/test/unit/test-utils/pinia"import { useFeatureFlagStore, getFlagStatus } from "~/stores/feature-flag"-import { OFF, ON } from "~/constants/feature-flag"+import { OFF, ON, COOKIE, SESSION } from "~/constants/feature-flag"jest.mock("~~/feat/feature-flags.json",@@ -10,20 +10,30 @@ jest.mock(feat_enabled: {status: "enabled",description: "Will always be enabled",+ storage: "cookie",},feat_disabled: {status: "disabled",description: "Will always be disabled",+ storage: "cookie",},feat_switchable_optout: {status: "switchable",description: "Can be switched between on and off",defaultState: "on",+ storage: "cookie",},feat_switchable_optin: {status: "switchable",description: "Can be switched between on and off",defaultState: "off",+ storage: "session",+ },+ feat_no_query: {+ status: "switchable",+ description: "Cannot be flipped by ff_ query params",+ defaultState: "off",+ supportsQuery: false,},feat_env_specific: {status: {@@ -33,6 +43,7 @@ jest.mock(},description: "Depends on the environment",defaultState: "off",+ storage: "cookie",},},}),@@ -46,7 +57,7 @@ describe("Feature flag store", () => {it("initialises state from JSON", () => {const featureFlagStore = useFeatureFlagStore()- expect(Object.keys(featureFlagStore.flags).length).toBe(5)+ expect(Object.keys(featureFlagStore.flags).length).toBe(6)})it.each`@@ -63,25 +74,44 @@ describe("Feature flag store", () => {)it.each`- flagName | doCookieInit | featureState- ${"feat_switchable_optout"} | ${false} | ${"on"}- ${"feat_switchable_optin"} | ${false} | ${"off"}- ${"feat_switchable_optout"} | ${true} | ${"off"}- ${"feat_switchable_optin"} | ${true} | ${"on"}+ doCookieInit | featureState+ ${false} | ${"on"}+ ${true} | ${"off"}`(- "cascades flag $flagName from cookies",- ({ flagName, doCookieInit, featureState }) => {+ "cascades cookie-storage flag from cookies",+ ({ doCookieInit, featureState }) => {+ const flagName = "feat_switchable_optout"const featureFlagStore = useFeatureFlagStore()if (doCookieInit)featureFlagStore.initFromCookies({feat_switchable_optout: OFF,- feat_switchable_optin: ON,})expect(featureFlagStore.featureState(flagName)).toEqual(featureState)expect(featureFlagStore.isOn(flagName)).toEqual(featureState === "on")})+ it.each`+ doSessionInit | featureState+ ${false} | ${"off"}+ ${true} | ${"on"}+ `(+ "cascades session-storage flag from sessionStorage",+ ({ doSessionInit, featureState }) => {+ const flagName = "feat_switchable_optin"+ const featureFlagStore = useFeatureFlagStore()++ window.sessionStorage.setItem(+ "features",+ JSON.stringify({ feat_switchable_optin: ON })+ )+ if (doSessionInit) featureFlagStore.initFromSession()++ expect(featureFlagStore.featureState(flagName)).toEqual(featureState)+ expect(featureFlagStore.isOn(flagName)).toEqual(featureState === "on")+ }+ )+it.each`cookieState | queryState | finalState${"off"} | ${"on"} | ${"on"}@@ -118,6 +148,15 @@ describe("Feature flag store", () => {})+ it("does not cascade query-unsupporting flags from query params", () => {+ const featureFlagStore = useFeatureFlagStore()+ expect(featureFlagStore.featureState("feat_no_query")).toEqual(OFF)+ featureFlagStore.initFromQuery({+ feat_no_query: "on",+ })+ expect(featureFlagStore.featureState("feat_no_query")).toEqual(OFF)+ })+it.each`environment | featureState${"local"} | ${"on"}@@ -164,12 +203,15 @@ describe("Feature flag store", () => {})- it("returns mapping of switchable flags", () => {+ it.each`+ storage | flagName+ ${COOKIE} | ${"feat_switchable_optout"}+ ${SESSION} | ${"feat_switchable_optin"}+ `("returns mapping of switchable flags", ({ storage, flagName }) => {const featureFlagStore = useFeatureFlagStore()- const flagStateMap = featureFlagStore.flagStateMap+ const flagStateMap = featureFlagStore.flagStateMap(storage)- expect(flagStateMap).toHaveProperty("feat_switchable_optout")- expect(flagStateMap).toHaveProperty("feat_switchable_optin")+ expect(flagStateMap).toHaveProperty(flagName)expect(flagStateMap).not.toHaveProperty("feat_enabled")expect(flagStateMap).not.toHaveProperty("feat_disabled")