Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/persist/fileAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
(this.fs ? this.fs : mustGetDefaultFileSystem()).writeFileSync(this.filePath, text);
}
Expand Down
33 changes: 27 additions & 6 deletions src/persist/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[][];
}
}

Expand All @@ -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;
}
Expand All @@ -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;
Expand Down
18 changes: 18 additions & 0 deletions test/persist/fileAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>([['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<string, string>([['policy.csv', 'p, alice, data1, read']]);
const e = await newEnforcer(newModel(modelText), new FileAdapter('policy.csv', memoryFileSystem(files)));
Expand Down
6 changes: 6 additions & 0 deletions test/persist/helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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) => {
Expand Down