Skip to content

Commit

Permalink
fix: policy line parsing for nested expressions and quoted values
Browse files Browse the repository at this point in the history
  • Loading branch information
HashCookie committed Nov 19, 2024
1 parent a511954 commit 29ca36b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
31 changes: 23 additions & 8 deletions src/persist/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,32 @@ export class Helper {
for (let i = 0; i < line.length; i++) {
const char = line[i];

if (char === '"' && (i === 0 || line[i - 1] !== '\\')) {
inQuotes = !inQuotes;
} else if (char === '(' && !inQuotes) {
if (char === '(') {
bracketCount++;
} else if (char === ')' && !inQuotes) {
} else if (char === ')') {
bracketCount--;
}

if (char === '"' && (i === 0 || line[i - 1] !== '\\')) {
inQuotes = !inQuotes;
currentToken += char;
continue;
}

if (char === ',' && !inQuotes && bracketCount === 0) {
tokens.push(currentToken.trim());
currentToken = '';
if (currentToken) {
tokens.push(currentToken.trim());
currentToken = '';
}
} else {
currentToken += char;
}
}

if (bracketCount !== 0) {
throw new Error(`Unmatched brackets in policy line: ${line}`);
}

if (currentToken) {
tokens.push(currentToken.trim());
}
Expand All @@ -38,7 +48,11 @@ export class Helper {
return;
}

const key = tokens[0];
let key = tokens[0].trim();
if (key.startsWith('"') && key.endsWith('"')) {
key = key.slice(1, -1);
}

const sec = key.substring(0, 1);
const item = model.model.get(sec);
if (!item) {
Expand All @@ -51,10 +65,11 @@ export class Helper {
}

const values = tokens.slice(1).map((v) => {
v = v.trim();
if (v.startsWith('"') && v.endsWith('"')) {
v = v.slice(1, -1);
}
return v.replace(/""/g, '"');
return v.replace(/""/g, '"').trim();
});

policy.policy.push(values);
Expand Down
2 changes: 1 addition & 1 deletion test/persist/helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ m = r.sub == p.sub && r.obj == p.obj && r.act == p.act
['admin', '/', 'POST'],
['admin', '/', 'PUT'],
['admin', '/', 'DELETE'],
[' admin', '/ ', 'PATCH'],
['admin', '/', 'PATCH'],
];

testdata.forEach((n) => {
Expand Down

0 comments on commit 29ca36b

Please sign in to comment.