Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix(tests): enhance permission boundary checks for glob patterns

Victor Hugo dos Santos3b36e7f7ed44
diff --git a/backend/src/lib/casl/boundary.test.ts b/backend/src/lib/casl/boundary.test.ts
index d8622b572e..fa22e0dfb0 100644
--- a/backend/src/lib/casl/boundary.test.ts
+++ b/backend/src/lib/casl/boundary.test.ts
@@ -683,7 +683,7 @@ describe("Validate Permission Boundary: Checking Parent $GLOB operator", () => {
}
])
}
- ])("Child $operator truthy cases", ({ childPermission }) => {
+ ])("Child $operator (parent /hello/** $GLOB) truthy cases", ({ childPermission }) => {
const permissionBoundary = validatePermissionBoundary(parentPermission, childPermission);
expect(permissionBoundary.isValid).toBeTruthy();
});
@@ -737,8 +737,193 @@ describe("Validate Permission Boundary: Checking Parent $GLOB operator", () => {
}
])
}
- ])("Child $operator falsy cases", ({ childPermission }) => {
+ ])("Child $operator (parent /hello/** $GLOB) falsy cases", ({ childPermission }) => {
const permissionBoundary = validatePermissionBoundary(parentPermission, childPermission);
expect(permissionBoundary.isValid).toBeFalsy();
});
});
+
+describe("Validate Permission Boundary: glob-subset of glob (positive parent)", () => {
+ // Regression for the literal-string-match flaw: `picomatch.isMatch('/apps/**', '/apps/*')`
+ // returns true because `**` is two literal characters with no `/`, so the previous boundary
+ // logic accepted `/apps/**` as a "subset" of `/apps/*` and let callers widen single-segment
+ // scope to recursive scope. The new check uses set containment over the two glob languages.
+ test("Child $glob broader than parent $glob is rejected ('/apps/*' parent, '/apps/**' child)", () => {
+ const parentPermission = createMongoAbility([
+ {
+ action: ["read"],
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/*" }
+ }
+ }
+ ]);
+ const childPermission = createMongoAbility([
+ {
+ action: ["read"],
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/**" }
+ }
+ }
+ ]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeFalsy();
+ });
+
+ test("Child $glob equally narrow than parent $glob is accepted ('/apps/*' parent, '/apps/foo' child)", () => {
+ const parentPermission = createMongoAbility([
+ {
+ action: ["read"],
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/*" }
+ }
+ }
+ ]);
+ const childPermission = createMongoAbility([
+ {
+ action: ["read"],
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/foo" }
+ }
+ }
+ ]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeTruthy();
+ });
+
+ test("Disjoint glob siblings ('/apps/*' parent, '/secret/*' child) is rejected", () => {
+ const parentPermission = createMongoAbility([
+ {
+ action: ["read"],
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/*" }
+ }
+ }
+ ]);
+ const childPermission = createMongoAbility([
+ {
+ action: ["read"],
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/secret/*" }
+ }
+ }
+ ]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeFalsy();
+ });
+});
+
+describe("Validate Permission Boundary: inverted (deny) rule overlap", () => {
+ // Regression for the inverted-rule bypass: a caller with positive `read` plus a deny rule
+ // scoped to `/secret/**` must not be able to mint a child rule scoped to `/**`, because the
+ // child grants exactly the access the parent's deny region forbids. The previous check only
+ // tested "child fully contained in deny region", missing the "child broader than deny region"
+ // case.
+ test("Child broader than parent's deny region is rejected (deny '/secret/**' + child '/**')", () => {
+ const parentPermission = createMongoAbility([
+ { action: "read", subject: "secrets" },
+ {
+ action: "read",
+ subject: "secrets",
+ inverted: true,
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/secret/**" }
+ }
+ }
+ ]);
+ const childPermission = createMongoAbility([
+ {
+ action: "read",
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/**" }
+ }
+ }
+ ]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeFalsy();
+ });
+
+ test("Child without the deny-region's constrained field is rejected (deny path='/secret/**' + child {})", () => {
+ const parentPermission = createMongoAbility([
+ { action: "read", subject: "secrets" },
+ {
+ action: "read",
+ subject: "secrets",
+ inverted: true,
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/secret/**" }
+ }
+ }
+ ]);
+ const childPermission = createMongoAbility([{ action: "read", subject: "secrets" }]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeFalsy();
+ });
+
+ test("Child fully outside the deny region is accepted (deny '/secret/**' + child '/apps/**')", () => {
+ const parentPermission = createMongoAbility([
+ { action: "read", subject: "secrets" },
+ {
+ action: "read",
+ subject: "secrets",
+ inverted: true,
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/secret/**" }
+ }
+ }
+ ]);
+ const childPermission = createMongoAbility([
+ {
+ action: "read",
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/**" }
+ }
+ }
+ ]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeTruthy();
+ });
+
+ test("Child disjoint from deny via a different field is accepted (deny env=dev path='/secret/**' + child env=prod)", () => {
+ const parentPermission = createMongoAbility([
+ { action: "read", subject: "secrets" },
+ {
+ action: "read",
+ subject: "secrets",
+ inverted: true,
+ conditions: {
+ environment: { [PermissionConditionOperators.$EQ]: "dev" },
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/secret/**" }
+ }
+ }
+ ]);
+ const childPermission = createMongoAbility([
+ {
+ action: "read",
+ subject: "secrets",
+ conditions: {
+ environment: { [PermissionConditionOperators.$EQ]: "prod" }
+ }
+ }
+ ]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeTruthy();
+ });
+
+ test("Unconditional inverted rule denies all subsets", () => {
+ const parentPermission = createMongoAbility([
+ { action: "read", subject: "secrets" },
+ { action: "read", subject: "secrets", inverted: true }
+ ]);
+ const childPermission = createMongoAbility([
+ {
+ action: "read",
+ subject: "secrets",
+ conditions: {
+ secretPath: { [PermissionConditionOperators.$EQ]: "/" }
+ }
+ }
+ ]);
+ expect(validatePermissionBoundary(parentPermission, childPermission).isValid).toBeFalsy();
+ });
+});
diff --git a/backend/src/lib/casl/boundary.ts b/backend/src/lib/casl/boundary.ts
index 80eb0a2885..6e62fccd60 100644
--- a/backend/src/lib/casl/boundary.ts
+++ b/backend/src/lib/casl/boundary.ts
@@ -2,6 +2,7 @@ import { MongoAbility } from "@casl/ability";
import { MongoQuery } from "@ucast/mongo2js";
import picomatch from "picomatch";
+import { haveDisjointLiteralPrefixes, isGlobSubsetOfGlob } from "./glob-subset";
import { PermissionConditionOperators } from "./index";
type TMissingPermission = {
@@ -132,9 +133,7 @@ const isOperatorsASubset = (parentSet: TPermissionConditionShape, subset: TPermi
}
if (
parentSet[PermissionConditionOperators.$GLOB] &&
- !picomatch.isMatch(subsetOperatorValue, parentSet[PermissionConditionOperators.$GLOB], {
- strictSlashes: false
- })
+ !isGlobSubsetOfGlob(parentSet[PermissionConditionOperators.$GLOB], subsetOperatorValue)
) {
return false;
}
@@ -142,13 +141,69 @@ const isOperatorsASubset = (parentSet: TPermissionConditionShape, subset: TPermi
return true;
};
+/**
+ * Returns true if we can prove the two operator constraints define disjoint match sets (share no
+ * elements). Returns false when uncertain — callers should treat that as "potentially overlapping"
+ * and behave conservatively. Used by the inverted (deny) rule overlap check.
+ */
+const areOperatorsDisjoint = (a: TPermissionConditionShape, b: TPermissionConditionShape): boolean => {
+ const aEq = a[PermissionConditionOperators.$EQ];
+ const aNeq = a[PermissionConditionOperators.$NEQ];
+ const aIn = a[PermissionConditionOperators.$IN];
+ const aGlob = a[PermissionConditionOperators.$GLOB];
+ const bEq = b[PermissionConditionOperators.$EQ];
+ const bNeq = b[PermissionConditionOperators.$NEQ];
+ const bIn = b[PermissionConditionOperators.$IN];
+ const bGlob = b[PermissionConditionOperators.$GLOB];
+
+ if (aEq !== undefined && bEq !== undefined) return aEq !== bEq;
+ if (aEq !== undefined && bNeq !== undefined) return aEq === bNeq;
+ if (bEq !== undefined && aNeq !== undefined) return bEq === aNeq;
+ if (aEq !== undefined && bIn !== undefined) return !bIn.includes(aEq);
+ if (bEq !== undefined && aIn !== undefined) return !aIn.includes(bEq);
+ if (aEq !== undefined && bGlob !== undefined) {
+ return !picomatch.isMatch(aEq, bGlob, { strictSlashes: false });
+ }
+ if (bEq !== undefined && aGlob !== undefined) {
+ return !picomatch.isMatch(bEq, aGlob, { strictSlashes: false });
+ }
+
+ if (aIn !== undefined && bIn !== undefined) {
+ return !aIn.some((v) => bIn.includes(v));
+ }
+ if (aIn !== undefined && bGlob !== undefined) {
+ return !aIn.some((v) => picomatch.isMatch(v, bGlob, { strictSlashes: false }));
+ }
+ if (bIn !== undefined && aGlob !== undefined) {
+ return !bIn.some((v) => picomatch.isMatch(v, aGlob, { strictSlashes: false }));
+ }
+ // $in vs $neq: disjoint if every $in value is excluded by $neq (i.e., equals the $neq value).
+ if (aIn !== undefined && bNeq !== undefined) return aIn.every((v) => v === bNeq);
+ if (bIn !== undefined && aNeq !== undefined) return bIn.every((v) => v === aNeq);
+
+ if (aGlob !== undefined && bGlob !== undefined) {
+ return haveDisjointLiteralPrefixes(aGlob, bGlob);
+ }
+
+ // $glob vs $neq: $glob covers a (typically infinite) set; $neq excludes one value. Probably
+ // disjoint only if the glob is exactly the excluded value as a literal string.
+ if (aGlob !== undefined && bNeq !== undefined) return aGlob === bNeq;
+ if (bGlob !== undefined && aNeq !== undefined) return bGlob === aNeq;
+
+ // Two $neq constraints almost always overlap over an infinite string domain.
+ return false;
+};
+
const isSubsetForSamePermissionSubjectAction = (
parentSetRules: ReturnType<MongoAbility["possibleRulesFor"]>,
subsetRules: ReturnType<MongoAbility["possibleRulesFor"]>,
appendToMissingPermission: (condition?: MongoQuery) => void
) => {
- const isMissingConditionInParent = parentSetRules.every((el) => !el.conditions);
- if (isMissingConditionInParent) return true;
+ // Fast path: if every NON-inverted parent rule is unconditional and there are no inverted
+ // rules, the parent grants the action universally
+ const hasOnlyUnconditionalNonInvertedRules =
+ parentSetRules.length > 0 && parentSetRules.every((el) => !el.inverted && !el.conditions);
+ if (hasOnlyUnconditionalNonInvertedRules) return true;
// all subset rules must pass in comparison to parent rul
return subsetRules.every((subsetRule) => {
@@ -173,27 +228,35 @@ const isSubsetForSamePermissionSubjectAction = (
});
const invertedParentSetRules = parentSetRules.filter((el) => el.inverted);
- const isNotSubsetOfInvertedParentSet = invertedParentSetRules.length
+ // A subset is invalid if it overlaps any inverted (deny) parent rule. Since conditions are
+ // AND-of-fields, proving any single field disjoint between the subset and the deny rule is
+ // enough to prove non-overlap.
+ const overlapsWithInvertedParent = (invertedConditions: Record<string, TPermissionConditionShape | string>) => {
+ const fields = Object.keys(invertedConditions);
+ for (const field of fields) {
+ const subsetField = subsetRuleConditions?.[field];
+ // If the subset doesn't constrain this field, it matches every value and inevitably
+ // overlaps the deny region for this field — leave the field unproven and check the next.
+ if (subsetField) {
+ const invertedOps = formatConditionOperator(invertedConditions[field]);
+ const subsetOps = formatConditionOperator(subsetField);
+ if (areOperatorsDisjoint(invertedOps, subsetOps)) return false;
+ }
+ }
+ return true;
+ };
+ const isNotInDeniedRegion = invertedParentSetRules.length
? !invertedParentSetRules.some((parentSetRule) => {
- // get conditions and iterate
const parentSetRuleConditions = parentSetRule?.conditions as Record<
string,
TPermissionConditionShape | string
>;
+ // Unconditional inverted rule denies everything; any subset overlaps it.
if (!parentSetRuleConditions) return true;
- return Object.keys(parentSetRuleConditions).every((parentConditionField) => {
- // if parent condition is missing then it's never a subset
- if (!subsetRuleConditions?.[parentConditionField]) return false;
-
- // standardize the conditions plain string operator => $eq function
- const parentRuleConditionOperators = formatConditionOperator(parentSetRuleConditions[parentConditionField]);
- const selectedSubsetRuleCondition = subsetRuleConditions?.[parentConditionField];
- const subsetRuleConditionOperators = formatConditionOperator(selectedSubsetRuleCondition);
- return isOperatorsASubset(parentRuleConditionOperators, subsetRuleConditionOperators);
- });
+ return overlapsWithInvertedParent(parentSetRuleConditions);
})
: true;
- const isSubset = isSubsetOfNonInvertedParentSet && isNotSubsetOfInvertedParentSet;
+ const isSubset = isSubsetOfNonInvertedParentSet && isNotInDeniedRegion;
if (!isSubset) {
appendToMissingPermission(subsetRule.conditions);
}
diff --git a/backend/src/lib/casl/glob-subset.test.ts b/backend/src/lib/casl/glob-subset.test.ts
new file mode 100644
index 0000000000..6ad6ae10f2
--- /dev/null
+++ b/backend/src/lib/casl/glob-subset.test.ts
@@ -0,0 +1,78 @@
+import { haveDisjointLiteralPrefixes, isGlobSubsetOfGlob, literalPrefix } from "./glob-subset";
+
+describe("isGlobSubsetOfGlob", () => {
+ describe("identical patterns", () => {
+ test.each([
+ ["/", "/"],
+ ["/apps", "/apps"],
+ ["/apps/**", "/apps/**"],
+ ["**", "**"]
+ ])("%s ⊆ %s is true", (a, b) => expect(isGlobSubsetOfGlob(a, b)).toBe(true));
+ });
+
+ describe("subset narrower than parent", () => {
+ test.each([
+ ["/apps/**", "/apps/foo"],
+ ["/apps/**", "/apps/foo/bar"],
+ ["/apps/**", "/apps/foo/bar/baz"],
+ ["/apps/*", "/apps/foo"],
+ ["/apps/**", "/apps/*"],
+ ["/**", "/apps/**"],
+ ["/**", "/apps/foo"],
+ ["**", "/apps/foo"],
+ ["/apps/**", "/apps/"],
+ ["/apps/**", "/apps"]
+ ])("parent=%s, subset=%s → true", (parent, subset) => expect(isGlobSubsetOfGlob(parent, subset)).toBe(true));
+ });
+
+ describe("subset broader than parent (the bug case)", () => {
+ test.each([
+ ["/apps/*", "/apps/**"],
+ ["/apps/*", "/apps/*/foo"],
+ ["/apps/foo", "/apps/*"],
+ ["/apps/foo", "/apps/**"],
+ ["/apps/**", "/**"],
+ ["/secret/**", "/**"]
+ ])("parent=%s, subset=%s → false", (parent, subset) => expect(isGlobSubsetOfGlob(parent, subset)).toBe(false));
+ });
+
+ describe("disjoint literal segments", () => {
+ test.each([
+ ["/apps/*", "/secret/*"],
+ ["/apps/**", "/secret/**"],
+ ["/foo/bar", "/foo/baz"]
+ ])("parent=%s, subset=%s → false", (parent, subset) => expect(isGlobSubsetOfGlob(parent, subset)).toBe(false));
+ });
+
+ describe("intra-segment wildcards (fall-back path)", () => {
+ test("parent /hello/** does not contain subset /hello** (broader pattern, intra-segment)", () => {
+ expect(isGlobSubsetOfGlob("/hello/**", "/hello**")).toBe(false);
+ });
+
+ test("subset matching exactly with intra-segment wildcards passes via reference equality", () => {
+ expect(isGlobSubsetOfGlob("/hello*", "/hello*")).toBe(true);
+ });
+ });
+});
+
+describe("literalPrefix", () => {
+ test.each([
+ ["/apps/foo", "/apps/foo"],
+ ["/apps/*", "/apps/"],
+ ["/apps/**", "/apps/"],
+ ["/**", "/"],
+ ["**", ""],
+ ["*foo", ""]
+ ])("literalPrefix(%s) === %s", (input, expected) => expect(literalPrefix(input)).toBe(expected));
+});
+
+describe("haveDisjointLiteralPrefixes", () => {
+ test.each([
+ ["/apps/*", "/secret/*", true],
+ ["/apps/**", "/secret/**", true],
+ ["/foo/bar", "/foo/baz", true],
+ ["/foo/bar", "/foo/bar", false],
+ ["/**", "/secret/**", false],
+ ["/apps/*", "/apps/**", false]
+ ])("disjoint(%s, %s) === %s", (a, b, expected) => expect(haveDisjointLiteralPrefixes(a, b)).toBe(expected));
+});
diff --git a/backend/src/lib/casl/glob-subset.ts b/backend/src/lib/casl/glob-subset.ts
new file mode 100644
index 0000000000..a4b5022217
--- /dev/null
+++ b/backend/src/lib/casl/glob-subset.ts
@@ -0,0 +1,121 @@
+import picomatch from "picomatch";
+
+/**
+ * Glob set-containment for permission boundary checks: answers "is every string matched by
+ * `subsetGlob` also matched by `parentGlob`?".
+ *
+ * `picomatch.isMatch(subsetGlob, parentGlob)` treats the subset as a literal
+ * value, so `/apps/**` appears to be a subset of `/apps/*` (the two chars `**` match `*`). This
+ * module instead compares segment sequences (literal, `*`, `**`) with proper containment semantics.
+ * Patterns with intra-segment wildcards (`foo*`, `?`, `[…]`, `{…}`) fall back to picomatch.
+ */
+
+type Segment = { type: "literal"; value: string } | { type: "star" } | { type: "globstar" };
+
+const SEGMENT_METACHARACTER = /[*?[\]{}!()]/;
+
+const parseSegments = (glob: string): Segment[] | null => {
+ const parts = glob.split("/");
+ const segments: Segment[] = [];
+ for (const part of parts) {
+ if (part === "") {
+ segments.push({ type: "literal", value: "" });
+ } else if (part === "*") {
+ segments.push({ type: "star" });
+ } else if (part === "**") {
+ segments.push({ type: "globstar" });
+ } else if (SEGMENT_METACHARACTER.test(part)) {
+ // Intra-segment wildcards or other glob features (e.g. `foo*`, `*foo`, `[abc]`, `{a,b}`).
+ // Signal the caller to fall back rather than guessing about containment.
+ return null;
+ } else {
+ segments.push({ type: "literal", value: part });
+ }
+ }
+ return segments;
+};
+
+const segmentMatch = (parent: Segment[], subset: Segment[], pi: number, si: number): boolean => {
+ if (pi >= parent.length && si >= subset.length) return true;
+
+ // A globstar in parent can consume zero or more subset segments — try both branches.
+ if (pi < parent.length && parent[pi].type === "globstar") {
+ if (segmentMatch(parent, subset, pi + 1, si)) return true;
+ if (si < subset.length) return segmentMatch(parent, subset, pi, si + 1);
+ return false;
+ }
+
+ // Parent exhausted but subset has more segments — parent cannot match those longer strings.
+ if (pi >= parent.length) return false;
+
+ // Subset exhausted but parent has more — only valid if every remaining parent segment is `**`
+ // (each can consume zero subset segments).
+ if (si >= subset.length) {
+ for (let i = pi; i < parent.length; i += 1) {
+ if (parent[i].type !== "globstar") return false;
+ }
+ return true;
+ }
+
+ const pSeg = parent[pi];
+ const sSeg = subset[si];
+
+ if (pSeg.type === "star") {
+ // `*` matches a single segment of any literal/star content, but not a globstar (which spans
+ // multiple segments and is therefore broader than `*`).
+ if (sSeg.type === "globstar") return false;
+ return segmentMatch(parent, subset, pi + 1, si + 1);
+ }
+
+ if (pSeg.type === "literal") {
+ // A literal segment in parent must be matched by an identical literal segment in subset; any
+ // wildcard in subset would make subset broader than parent.
+ if (sSeg.type !== "literal") return false;
+ if (sSeg.value !== pSeg.value) return false;
+ return segmentMatch(parent, subset, pi + 1, si + 1);
+ }
+
+ return false;
+};
+
+/**
+ * Returns true if every string matched by `subsetGlob` is also matched by `parentGlob`.
+ *
+ * Analyzes globs whose segments are literals, `*`, or `**`. For globs with other features
+ * (intra-segment wildcards, character classes, brace expansion), falls back to
+ * `picomatch.isMatch(subsetGlob, parentGlob)` — preserving the previous
+ * behavior so this change does not affect rules that rely on those patterns.
+ */
+export const isGlobSubsetOfGlob = (parentGlob: string, subsetGlob: string): boolean => {
+ if (parentGlob === subsetGlob) return true;
+ const parentSegs = parseSegments(parentGlob);
+ const subsetSegs = parseSegments(subsetGlob);
+ if (parentSegs && subsetSegs) {
+ return segmentMatch(parentSegs, subsetSegs, 0, 0);
+ }
+ return picomatch.isMatch(subsetGlob, parentGlob, { strictSlashes: false });
+};
+
+/**
+ * Returns the static text of a glob — the prefix up to (but not including) the first glob
+ * metacharacter. Used by callers that need a sound disjointness heuristic for two globs.
+ */
+export const literalPrefix = (glob: string): string => {
+ for (let i = 0; i < glob.length; i += 1) {
+ const c = glob[i];
+ if (c === "*" || c === "?" || c === "[" || c === "{") return glob.slice(0, i);
+ }
+ return glob;
+};
+
+/**
+ * Returns true if the literal prefixes of two globs definitively prove the patterns share no
+ * matches. This is sound but conservative: returns true only when neither prefix is a prefix of
+ * the other (so no string can begin with both), and false otherwise — including cases where the
+ * patterns may or may not actually overlap.
+ */
+export const haveDisjointLiteralPrefixes = (a: string, b: string): boolean => {
+ const pa = literalPrefix(a);
+ const pb = literalPrefix(b);
+ return !pa.startsWith(pb) && !pb.startsWith(pa);
+};
diff --git a/backend/src/services/service-token/service-token-service.test.ts b/backend/src/services/service-token/service-token-service.test.ts
index 1794e81cf4..7ad6ea18a4 100644
--- a/backend/src/services/service-token/service-token-service.test.ts
+++ b/backend/src/services/service-token/service-token-service.test.ts
@@ -7,7 +7,7 @@ import {
ProjectPermissionSet,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
-import { conditionsMatcher } from "@app/lib/casl";
+import { conditionsMatcher, PermissionConditionOperators } from "@app/lib/casl";
import { crypto } from "@app/lib/crypto";
import { serviceTokenServiceFactory } from "./service-token-service";
@@ -340,6 +340,119 @@ describe("createServiceToken authorization", () => {
).resolves.toBeDefined();
expect(serviceTokenDAL.create).toHaveBeenCalledTimes(1);
});
+
+ // Regression: glob → broader-glob widening was previously allowed because the boundary check
+ // used `picomatch.isMatch` to compare a subset glob against a parent glob as if the subset
+ // were a literal value, so `/apps/**` matched `/apps/*` (the literal `**` is two non-`/`
+ // characters and matches `*`). The fix in `boundary.ts` switched to a sound glob-set
+ // containment check.
+ test("caller with $glob:'/apps/*' cannot mint token with secretPath='/apps/**' (glob → broader glob)", async () => {
+ const conditions = {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/*" },
+ environment: ENV_SLUG
+ };
+ const permission = buildAbility((b) => grantV2ScopedPermissions(b, conditions));
+
+ const { service, serviceTokenDAL } = createService(permission);
+
+ await expect(
+ callCreate({
+ service,
+ scopes: [{ environment: ENV_SLUG, secretPath: "/apps/**" }],
+ permissions: ["read", "write"]
+ })
+ ).rejects.toThrow();
+ expect(serviceTokenDAL.create).not.toHaveBeenCalled();
+ });
+
+ test("caller with $glob:'/apps/**' can mint token with secretPath='/apps/foo' (narrower)", async () => {
+ const conditions = {
+ secretPath: { [PermissionConditionOperators.$GLOB]: "/apps/**" },
+ environment: ENV_SLUG
+ };
+ const permission = buildAbility((b) => grantV2ScopedPermissions(b, conditions));
+
+ const { service, serviceTokenDAL } = createService(permission);
+
+ await expect(
+ callCreate({
+ service,
+ scopes: [{ environment: ENV_SLUG, secretPath: "/apps/foo" }],
+ permissions: ["read", "write"]
+ })
+ ).resolves.toBeDefined();
+ expect(serviceTokenDAL.create).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression: a caller with a positive unconditional rule plus an inverted (deny) rule
+ // narrower than the requested token scope was previously allowed to mint, even though the
+ // resulting token grants access inside the deny region. Now overlap with the deny region —
+ // including the case where the subset is broader than the deny — fails the boundary check.
+ // The boundary check for a legacy "read" service token mints a token rule using
+ // `ProjectPermissionActions.Read` ("read") on each secret subject. To exercise the inverted-
+ // overlap path, the caller must have a deny rule on the SAME action — `Read` — at a narrower
+ // scope than the token's requested scope. Then the boundary check sees a positive rule plus
+ // a conditional inverted rule for action="read", and rejects the token because the requested
+ // glob (`/**`) overlaps the deny region (`/secret/**`).
+ const grantUnconditionalSecretActions = (b: AbilityBuilder<MongoAbility<ProjectPermissionSet>>) => {
+ grantServiceTokenCreate(b);
+ [ProjectPermissionSub.Secrets, ProjectPermissionSub.SecretImports, ProjectPermissionSub.SecretFolders].forEach(
+ (subj) => {
+ b.can(ProjectPermissionActions.Read, subj);
+ b.can(ProjectPermissionSecretActions.ReadValue, subj);
+ b.can(ProjectPermissionSecretActions.DescribeSecret, subj);
+ b.can(ProjectPermissionSecretActions.Create, subj);
+ }
+ );
+ };
+
+ test("caller with deny Read on '/secret/**' cannot mint token with secretPath='/**' (inverted overlap)", async () => {
+ const permission = buildAbility((b) => {
+ grantUnconditionalSecretActions(b);
+ [ProjectPermissionSub.Secrets, ProjectPermissionSub.SecretImports, ProjectPermissionSub.SecretFolders].forEach(
+ (subj) => {
+ // @ts-expect-error CASL's per-action condition schema doesn't expose $glob, but the
+ // conditionsMatcher resolves it at runtime; same pattern is used in production rules.
+ b.cannot(ProjectPermissionActions.Read, subj, { secretPath: { $glob: "/secret/**" } });
+ }
+ );
+ });
+
+ const { service, serviceTokenDAL } = createService(permission);
+
+ await expect(
+ callCreate({
+ service,
+ scopes: [{ environment: ENV_SLUG, secretPath: "/**" }],
+ permissions: ["read"]
+ })
+ ).rejects.toThrow();
+ expect(serviceTokenDAL.create).not.toHaveBeenCalled();
+ });
+
+ test("caller with deny Read on '/secret/**' can mint token with secretPath='/apps/**' (no overlap)", async () => {
+ const permission = buildAbility((b) => {
+ grantUnconditionalSecretActions(b);
+ [ProjectPermissionSub.Secrets, ProjectPermissionSub.SecretImports, ProjectPermissionSub.SecretFolders].forEach(
+ (subj) => {
+ // @ts-expect-error CASL's per-action condition schema doesn't expose $glob, but the
+ // conditionsMatcher resolves it at runtime; same pattern is used in production rules.
+ b.cannot(ProjectPermissionActions.Read, subj, { secretPath: { $glob: "/secret/**" } });
+ }
+ );
+ });
+
+ const { service, serviceTokenDAL } = createService(permission);
+
+ await expect(
+ callCreate({
+ service,
+ scopes: [{ environment: ENV_SLUG, secretPath: "/apps/**" }],
+ permissions: ["read"]
+ })
+ ).resolves.toBeDefined();
+ expect(serviceTokenDAL.create).toHaveBeenCalledTimes(1);
+ });
});
describe("admin-equivalent role (full unconditioned permissions)", () => {