Skip to content

Commit e7119e2

Browse files
validate property types of feature flags (#17)
* resovle conflicts * update validation * update * update * update * update * update * update --------- Co-authored-by: Lingling Ye (from Dev Box) <[email protected]>
1 parent 5733f56 commit e7119e2

File tree

7 files changed

+246
-29
lines changed

7 files changed

+246
-29
lines changed

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/featureManager.ts

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import { TimeWindowFilter } from "./filter/TimeWindowFilter.js";
55
import { IFeatureFilter } from "./filter/FeatureFilter.js";
6-
import { RequirementType } from "./model.js";
6+
import { RequirementType } from "./schema/model.js";
77
import { IFeatureFlagProvider } from "./featureProvider.js";
88
import { TargetingFilter } from "./filter/TargetingFilter.js";
99

@@ -30,15 +30,12 @@ export class FeatureManager {
3030

3131
// If multiple feature flags are found, the first one takes precedence.
3232
async isEnabled(featureName: string, context?: unknown): Promise<boolean> {
33-
const featureFlag = await this.#provider.getFeatureFlag(featureName);
33+
const featureFlag = await this.#getFeatureFlag(featureName);
3434
if (featureFlag === undefined) {
3535
// If the feature is not found, then it is disabled.
3636
return false;
3737
}
3838

39-
// Ensure that the feature flag is in the correct format. Feature providers should validate the feature flags, but we do it here as a safeguard.
40-
validateFeatureFlagFormat(featureFlag);
41-
4239
if (featureFlag.enabled !== true) {
4340
// If the feature is not explicitly enabled, then it is disabled by default.
4441
return false;
@@ -75,14 +72,14 @@ export class FeatureManager {
7572
return !shortCircuitEvaluationResult;
7673
}
7774

75+
async #getFeatureFlag(featureName: string): Promise<any> {
76+
const featureFlag = await this.#provider.getFeatureFlag(featureName);
77+
return featureFlag;
78+
}
79+
7880
}
7981

8082
interface FeatureManagerOptions {
8183
customFilters?: IFeatureFilter[];
8284
}
8385

84-
function validateFeatureFlagFormat(featureFlag: any): void {
85-
if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== "boolean") {
86-
throw new Error(`Feature flag ${featureFlag.id} has an invalid 'enabled' value.`);
87-
}
88-
}

src/featureProvider.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
// Licensed under the MIT license.
33

44
import { IGettable } from "./gettable.js";
5-
import { FeatureFlag, FeatureManagementConfiguration, FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from "./model.js";
5+
import { FeatureFlag, FeatureManagementConfiguration, FEATURE_MANAGEMENT_KEY, FEATURE_FLAGS_KEY } from "./schema/model.js";
6+
import { validateFeatureFlag } from "./schema/validator.js";
67

78
export interface IFeatureFlagProvider {
89
/**
@@ -28,12 +29,16 @@ export class ConfigurationMapFeatureFlagProvider implements IFeatureFlagProvider
2829
}
2930
async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {
3031
const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);
31-
return featureConfig?.[FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);
32+
const featureFlag = featureConfig?.[FEATURE_FLAGS_KEY]?.findLast((feature) => feature.id === featureName);
33+
validateFeatureFlag(featureFlag);
34+
return featureFlag;
3235
}
3336

3437
async getFeatureFlags(): Promise<FeatureFlag[]> {
3538
const featureConfig = this.#configuration.get<FeatureManagementConfiguration>(FEATURE_MANAGEMENT_KEY);
36-
return featureConfig?.[FEATURE_FLAGS_KEY] ?? [];
39+
const featureFlag = featureConfig?.[FEATURE_FLAGS_KEY] ?? [];
40+
validateFeatureFlag(featureFlag);
41+
return featureFlag;
3742
}
3843
}
3944

@@ -49,10 +54,14 @@ export class ConfigurationObjectFeatureFlagProvider implements IFeatureFlagProvi
4954

5055
async getFeatureFlag(featureName: string): Promise<FeatureFlag | undefined> {
5156
const featureFlags = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY];
52-
return featureFlags?.findLast((feature: FeatureFlag) => feature.id === featureName);
57+
const featureFlag = featureFlags?.findLast((feature: FeatureFlag) => feature.id === featureName);
58+
validateFeatureFlag(featureFlag);
59+
return featureFlag;
5360
}
5461

5562
async getFeatureFlags(): Promise<FeatureFlag[]> {
56-
return this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];
63+
const featureFlag = this.#configuration[FEATURE_MANAGEMENT_KEY]?.[FEATURE_FLAGS_KEY] ?? [];
64+
validateFeatureFlag(featureFlag);
65+
return featureFlag;
5766
}
5867
}

src/model.ts renamed to src/schema/model.ts

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,6 @@ export interface FeatureFlag {
1212
* An ID used to uniquely identify and reference the feature.
1313
*/
1414
id: string;
15-
/**
16-
* A description of the feature.
17-
*/
18-
description?: string;
19-
/**
20-
* A display name for the feature to use for display rather than the ID.
21-
*/
22-
display_name?: string;
2315
/**
2416
* A feature is OFF if enabled is false. If enabled is true, then the feature is ON if there are no conditions (null or empty) or if the conditions are satisfied.
2517
*/
@@ -78,10 +70,6 @@ interface Variant {
7870
* The configuration value for this feature variant.
7971
*/
8072
configuration_value?: unknown;
81-
/**
82-
* The path to a configuration section used as the configuration value for this feature variant.
83-
*/
84-
configuration_reference?: string;
8573
/**
8674
* Overrides the enabled state of the feature if the given variant is assigned. Does not override the state if value is None.
8775
*/

src/schema/validator.ts

Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT license.
3+
4+
/**
5+
* Validates a feature flag object, checking if it conforms to the schema.
6+
* @param featureFlag The feature flag object to validate.
7+
*/
8+
export function validateFeatureFlag(featureFlag: any): void {
9+
if (featureFlag === undefined) {
10+
return; // no-op if feature flag is undefined, indicating that the feature flag is not found
11+
}
12+
if (featureFlag === null || typeof featureFlag !== "object") { // Note: typeof null = "object"
13+
throw new TypeError("Feature flag must be an object.");
14+
}
15+
if (typeof featureFlag.id !== "string") {
16+
throw new TypeError("Feature flag 'id' must be a string.");
17+
}
18+
if (featureFlag.enabled !== undefined && typeof featureFlag.enabled !== "boolean") {
19+
throw new TypeError("Feature flag 'enabled' must be a boolean.");
20+
}
21+
if (featureFlag.conditions !== undefined) {
22+
validateFeatureEnablementConditions(featureFlag.conditions);
23+
}
24+
if (featureFlag.variants !== undefined) {
25+
validateVariants(featureFlag.variants);
26+
}
27+
if (featureFlag.allocation !== undefined) {
28+
validateVariantAllocation(featureFlag.allocation);
29+
}
30+
if (featureFlag.telemetry !== undefined) {
31+
validateTelemetryOptions(featureFlag.telemetry);
32+
}
33+
}
34+
35+
function validateFeatureEnablementConditions(conditions: any) {
36+
if (typeof conditions !== "object") {
37+
throw new TypeError("Feature flag 'conditions' must be an object.");
38+
}
39+
if (conditions.requirement_type !== undefined && conditions.requirement_type !== "Any" && conditions.requirement_type !== "All") {
40+
throw new TypeError("'requirement_type' must be 'Any' or 'All'.");
41+
}
42+
if (conditions.client_filters !== undefined) {
43+
validateClientFilters(conditions.client_filters);
44+
}
45+
}
46+
47+
function validateClientFilters(client_filters: any) {
48+
if (!Array.isArray(client_filters)) {
49+
throw new TypeError("Feature flag conditions 'client_filters' must be an array.");
50+
}
51+
52+
for (const filter of client_filters) {
53+
if (typeof filter.name !== "string") {
54+
throw new TypeError("Client filter 'name' must be a string.");
55+
}
56+
if (filter.parameters !== undefined && typeof filter.parameters !== "object") {
57+
throw new TypeError("Client filter 'parameters' must be an object.");
58+
}
59+
}
60+
}
61+
62+
function validateVariants(variants: any) {
63+
if (!Array.isArray(variants)) {
64+
throw new TypeError("Feature flag 'variants' must be an array.");
65+
}
66+
67+
for (const variant of variants) {
68+
if (typeof variant.name !== "string") {
69+
throw new TypeError("Variant 'name' must be a string.");
70+
}
71+
// skip configuration_value validation as it accepts any type
72+
if (variant.status_override !== undefined && typeof variant.status_override !== "string") {
73+
throw new TypeError("Variant 'status_override' must be a string.");
74+
}
75+
if (variant.status_override !== undefined && variant.status_override !== "None" && variant.status_override !== "Enabled" && variant.status_override !== "Disabled") {
76+
throw new TypeError("Variant 'status_override' must be 'None', 'Enabled', or 'Disabled'.");
77+
}
78+
}
79+
}
80+
81+
function validateVariantAllocation(allocation: any) {
82+
if (typeof allocation !== "object") {
83+
throw new TypeError("Variant 'allocation' must be an object.");
84+
}
85+
86+
if (allocation.default_when_disabled !== undefined && typeof allocation.default_when_disabled !== "string") {
87+
throw new TypeError("Variant allocation 'default_when_disabled' must be a string.");
88+
}
89+
if (allocation.default_when_enabled !== undefined && typeof allocation.default_when_enabled !== "string") {
90+
throw new TypeError("Variant allocation 'default_when_enabled' must be a string.");
91+
}
92+
if (allocation.user !== undefined) {
93+
validateUserVariantAllocation(allocation.user);
94+
}
95+
if (allocation.group !== undefined) {
96+
validateGroupVariantAllocation(allocation.group);
97+
}
98+
if (allocation.percentile !== undefined) {
99+
validatePercentileVariantAllocation(allocation.percentile);
100+
}
101+
if (allocation.seed !== undefined && typeof allocation.seed !== "string") {
102+
throw new TypeError("Variant allocation 'seed' must be a string.");
103+
}
104+
}
105+
106+
function validateUserVariantAllocation(UserAllocations: any) {
107+
if (!Array.isArray(UserAllocations)) {
108+
throw new TypeError("Variant 'user' allocation must be an array.");
109+
}
110+
111+
for (const allocation of UserAllocations) {
112+
if (typeof allocation !== "object") {
113+
throw new TypeError("Elements in variant 'user' allocation must be an object.");
114+
}
115+
if (typeof allocation.variant !== "string") {
116+
throw new TypeError("User allocation 'variant' must be a string.");
117+
}
118+
if (!Array.isArray(allocation.users)) {
119+
throw new TypeError("User allocation 'users' must be an array.");
120+
}
121+
for (const user of allocation.users) {
122+
if (typeof user !== "string") {
123+
throw new TypeError("Elements in user allocation 'users' must be strings.");
124+
}
125+
}
126+
}
127+
}
128+
129+
function validateGroupVariantAllocation(groupAllocations: any) {
130+
if (!Array.isArray(groupAllocations)) {
131+
throw new TypeError("Variant 'group' allocation must be an array.");
132+
}
133+
134+
for (const allocation of groupAllocations) {
135+
if (typeof allocation !== "object") {
136+
throw new TypeError("Elements in variant 'group' allocation must be an object.");
137+
}
138+
if (typeof allocation.variant !== "string") {
139+
throw new TypeError("Group allocation 'variant' must be a string.");
140+
}
141+
if (!Array.isArray(allocation.groups)) {
142+
throw new TypeError("Group allocation 'groups' must be an array.");
143+
}
144+
for (const group of allocation.groups) {
145+
if (typeof group !== "string") {
146+
throw new TypeError("Elements in group allocation 'groups' must be strings.");
147+
}
148+
}
149+
}
150+
}
151+
152+
function validatePercentileVariantAllocation(percentileAllocations: any) {
153+
if (!Array.isArray(percentileAllocations)) {
154+
throw new TypeError("Variant 'percentile' allocation must be an array.");
155+
}
156+
157+
for (const allocation of percentileAllocations) {
158+
if (typeof allocation !== "object") {
159+
throw new TypeError("Elements in variant 'percentile' allocation must be an object.");
160+
}
161+
if (typeof allocation.variant !== "string") {
162+
throw new TypeError("Percentile allocation 'variant' must be a string.");
163+
}
164+
if (typeof allocation.from !== "number" || allocation.from < 0 || allocation.from > 100) {
165+
throw new TypeError("Percentile allocation 'from' must be a number between 0 and 100.");
166+
}
167+
if (typeof allocation.to !== "number" || allocation.to < 0 || allocation.to > 100) {
168+
throw new TypeError("Percentile allocation 'to' must be a number between 0 and 100.");
169+
}
170+
}
171+
}
172+
// #endregion
173+
174+
// #region Telemetry
175+
function validateTelemetryOptions(telemetry: any) {
176+
if (typeof telemetry !== "object") {
177+
throw new TypeError("Feature flag 'telemetry' must be an object.");
178+
}
179+
if (telemetry.enabled !== undefined && typeof telemetry.enabled !== "boolean") {
180+
throw new TypeError("Telemetry 'enabled' must be a boolean.");
181+
}
182+
if (telemetry.metadata !== undefined && typeof telemetry.metadata !== "object") {
183+
throw new TypeError("Telemetry 'metadata' must be an object.");
184+
}
185+
}
186+
// #endregion

test/featureManager.test.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,43 @@ describe("feature manager", () => {
7272
]);
7373
});
7474

75+
it("should evaluate features with conditions", () => {
76+
const dataSource = new Map();
77+
dataSource.set("feature_management", {
78+
feature_flags: [
79+
{
80+
"id": "Gamma",
81+
"description": "",
82+
"enabled": true,
83+
"conditions": {
84+
"requirement_type": "invalid type",
85+
"client_filters": [
86+
{ "name": "Microsoft.Targeting", "parameters": { "Audience": { "DefaultRolloutPercentage": 50 } } }
87+
]
88+
}
89+
},
90+
{
91+
"id": "Delta",
92+
"description": "",
93+
"enabled": true,
94+
"conditions": {
95+
"requirement_type": "Any",
96+
"client_filters": [
97+
{ "name": "Microsoft.Targeting", "parameters": "invalid parameter" }
98+
]
99+
}
100+
}
101+
],
102+
});
103+
104+
const provider = new ConfigurationMapFeatureFlagProvider(dataSource);
105+
const featureManager = new FeatureManager(provider);
106+
return Promise.all([
107+
expect(featureManager.isEnabled("Gamma")).eventually.rejectedWith("'requirement_type' must be 'Any' or 'All'."),
108+
expect(featureManager.isEnabled("Delta")).eventually.rejectedWith("Client filter 'parameters' must be an object.")
109+
]);
110+
});
111+
75112
it("should let the last feature flag win", () => {
76113
const jsonObject = {
77114
"feature_management": {

test/noFilters.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ describe("feature flags with no filters", () => {
6161
return Promise.all([
6262
expect(featureManager.isEnabled("BooleanTrue")).eventually.eq(true),
6363
expect(featureManager.isEnabled("BooleanFalse")).eventually.eq(false),
64-
expect(featureManager.isEnabled("InvalidEnabled")).eventually.rejectedWith("Feature flag InvalidEnabled has an invalid 'enabled' value."),
64+
expect(featureManager.isEnabled("InvalidEnabled")).eventually.rejectedWith("Feature flag 'enabled' must be a boolean."),
6565
expect(featureManager.isEnabled("Minimal")).eventually.eq(true),
6666
expect(featureManager.isEnabled("NoEnabled")).eventually.eq(false),
6767
expect(featureManager.isEnabled("EmptyConditions")).eventually.eq(true)

0 commit comments

Comments
 (0)