Skip to content

Commit 29ca36b

Browse files
committed
fix: policy line parsing for nested expressions and quoted values
1 parent a511954 commit 29ca36b

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

src/persist/helper.ts

+23-8
Original file line numberDiff line numberDiff line change
@@ -14,22 +14,32 @@ export class Helper {
1414
for (let i = 0; i < line.length; i++) {
1515
const char = line[i];
1616

17-
if (char === '"' && (i === 0 || line[i - 1] !== '\\')) {
18-
inQuotes = !inQuotes;
19-
} else if (char === '(' && !inQuotes) {
17+
if (char === '(') {
2018
bracketCount++;
21-
} else if (char === ')' && !inQuotes) {
19+
} else if (char === ')') {
2220
bracketCount--;
2321
}
2422

23+
if (char === '"' && (i === 0 || line[i - 1] !== '\\')) {
24+
inQuotes = !inQuotes;
25+
currentToken += char;
26+
continue;
27+
}
28+
2529
if (char === ',' && !inQuotes && bracketCount === 0) {
26-
tokens.push(currentToken.trim());
27-
currentToken = '';
30+
if (currentToken) {
31+
tokens.push(currentToken.trim());
32+
currentToken = '';
33+
}
2834
} else {
2935
currentToken += char;
3036
}
3137
}
3238

39+
if (bracketCount !== 0) {
40+
throw new Error(`Unmatched brackets in policy line: ${line}`);
41+
}
42+
3343
if (currentToken) {
3444
tokens.push(currentToken.trim());
3545
}
@@ -38,7 +48,11 @@ export class Helper {
3848
return;
3949
}
4050

41-
const key = tokens[0];
51+
let key = tokens[0].trim();
52+
if (key.startsWith('"') && key.endsWith('"')) {
53+
key = key.slice(1, -1);
54+
}
55+
4256
const sec = key.substring(0, 1);
4357
const item = model.model.get(sec);
4458
if (!item) {
@@ -51,10 +65,11 @@ export class Helper {
5165
}
5266

5367
const values = tokens.slice(1).map((v) => {
68+
v = v.trim();
5469
if (v.startsWith('"') && v.endsWith('"')) {
5570
v = v.slice(1, -1);
5671
}
57-
return v.replace(/""/g, '"');
72+
return v.replace(/""/g, '"').trim();
5873
});
5974

6075
policy.policy.push(values);

test/persist/helper.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
4545
['admin', '/', 'POST'],
4646
['admin', '/', 'PUT'],
4747
['admin', '/', 'DELETE'],
48-
[' admin', '/ ', 'PATCH'],
48+
['admin', '/', 'PATCH'],
4949
];
5050

5151
testdata.forEach((n) => {

0 commit comments

Comments
 (0)