From 51cd60b2117fca990d575809b96e744c7e49a324 Mon Sep 17 00:00:00 2001 From: Mradul Singh Date: Thu, 3 Dec 2026 05:33:27 +0530 Subject: [PATCH] fix: keep policy fields with unbalanced brackets in one field --- src/persist/fileAdapter.ts | 14 ++++++++++++-- src/persist/helper.ts | 33 ++++++++++++++++++++++++++------ test/persist/fileAdapter.test.ts | 18 +++++++++++++++++ test/persist/helper.test.ts | 6 ++++++ 4 files changed, 63 insertions(+), 8 deletions(-) diff --git a/src/persist/fileAdapter.ts b/src/persist/fileAdapter.ts index 10d518dc..c1158ed1 100644 --- a/src/persist/fileAdapter.ts +++ b/src/persist/fileAdapter.ts @@ -99,13 +99,23 @@ export class FileAdapter implements Adapter { if (/[\r\n]/.test(value)) { throw new Error(`invalid policy field ${JSON.stringify(value)}: line breaks are not allowed`); } - // If the value contains a comma or a double quote, wrap it in double quotes and escape any existing double quotes - if (value.includes(',') || value.includes('"')) { + // If the value contains a comma, a double quote or unbalanced brackets, wrap it in double quotes + // and escape any existing double quotes. The loader joins unquoted fields until their brackets balance. + if (value.includes(',') || value.includes('"') || !this.bracketsBalanced(value)) { return `"${value.replace(/"/g, '""')}"`; } return value; } + private bracketsBalanced(value: string): boolean { + let depth = 0; + for (const char of value) { + if (char === '(') depth++; + else if (char === ')' && --depth < 0) return false; + } + return depth === 0; + } + private async savePolicyFile(text: string): Promise { (this.fs ? this.fs : mustGetDefaultFileSystem()).writeFileSync(this.filePath, text); } diff --git a/src/persist/helper.ts b/src/persist/helper.ts index 9b6747b7..f7435e8f 100644 --- a/src/persist/helper.ts +++ b/src/persist/helper.ts @@ -21,18 +21,33 @@ export interface IPolicyParser { parse(line: string): string[][] | null; } +/** + * PolicyField is one field of a policy line and whether it was written in double quotes. + */ +export interface PolicyField { + value: string; + quoted: boolean; +} + export class BasicCsvParser implements IPolicyParser { parse(line: string): string[][] | null { + const rows = this.parseFields(line); + return rows ? rows.map((row) => row.map((field) => field.value)) : null; + } + + parseFields(line: string): PolicyField[][] | null { if (!line || line.trimStart().charAt(0) === '#') { return null; } + // cast turns each field into a PolicyField, the typings still say string. return parse(line, { delimiter: ',', skip_empty_lines: true, trim: true, relax_quotes: true, - }); + cast: (value, context): PolicyField => ({ value, quoted: context.quoting }), + }) as unknown as PolicyField[][]; } } @@ -44,7 +59,10 @@ export class BracketAwareCsvParser implements IPolicyParser { } parse(line: string): string[][] | null { - const rawTokens = this.baseParser.parse(line); + const rawTokens = + this.baseParser instanceof BasicCsvParser + ? this.baseParser.parseFields(line) + : this.baseParser.parse(line)?.map((row) => row.map((value) => ({ value, quoted: false }))); if (!rawTokens || !rawTokens[0]) { return null; } @@ -54,10 +72,13 @@ export class BracketAwareCsvParser implements IPolicyParser { let currentToken = ''; let bracketCount = 0; - for (const token of tokens) { - for (const char of token) { - if (char === '(') bracketCount++; - else if (char === ')') bracketCount--; + for (const { value: token, quoted } of tokens) { + // A quoted field is one field, so its brackets do not join it with the next fields. + if (!quoted) { + for (const char of token) { + if (char === '(') bracketCount++; + else if (char === ')') bracketCount--; + } } currentToken += (currentToken ? ',' : '') + token; diff --git a/test/persist/fileAdapter.test.ts b/test/persist/fileAdapter.test.ts index 143ff6d1..d12c9b01 100644 --- a/test/persist/fileAdapter.test.ts +++ b/test/persist/fileAdapter.test.ts @@ -73,6 +73,24 @@ test('savePolicy keeps the double quotes of a field', async () => { ]); }); +test('savePolicy keeps fields with unbalanced brackets', async () => { + const files = new Map([['policy.csv', '']]); + const e = await newEnforcer(newModel(modelText), new FileAdapter('policy.csv', memoryFileSystem(files))); + await e.addPolicy('alice', 'data(', 'read'); + await e.addPolicy('bob', 'a)', '(b'); + await e.addPolicy('dave', 'keyMatch(/a, /b)', 'read'); + await e.addGroupingPolicy('carol', ':)'); + await e.savePolicy(); + + const e2 = await newEnforcer(newModel(modelText), new FileAdapter('policy.csv', memoryFileSystem(files))); + expect(await e2.getPolicy()).toEqual([ + ['alice', 'data(', 'read'], + ['bob', 'a)', '(b'], + ['dave', 'keyMatch(/a, /b)', 'read'], + ]); + expect(await e2.getGroupingPolicy()).toEqual([['carol', ':)']]); +}); + test('savePolicy rejects fields with line breaks', async () => { const files = new Map([['policy.csv', 'p, alice, data1, read']]); const e = await newEnforcer(newModel(modelText), new FileAdapter('policy.csv', memoryFileSystem(files))); diff --git a/test/persist/helper.test.ts b/test/persist/helper.test.ts index db6d4b6b..cf83635b 100644 --- a/test/persist/helper.test.ts +++ b/test/persist/helper.test.ts @@ -42,6 +42,9 @@ m = r.sub == p.sub && r.obj == p.obj && r.act == p.act `"p","admin",/, "DELETE"`, `p, " admin","/ ", "PATCH"`, `p, admin, """quoted""", "a""b"`, + `p, admin, "data(", "read)"`, + `p, admin, "a(", ")"`, + `p, admin, keyMatch(/a, /b), GET`, ]; const expectedPolicy = [ @@ -51,6 +54,9 @@ m = r.sub == p.sub && r.obj == p.obj && r.act == p.act ['admin', '/', 'DELETE'], ['admin', '/', 'PATCH'], ['admin', '"quoted"', 'a"b'], + ['admin', 'data(', 'read)'], + ['admin', 'a(', ')'], + ['admin', 'keyMatch(/a,/b)', 'GET'], ]; testdata.forEach((n) => {