-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolicy-validator.ts
More file actions
89 lines (77 loc) · 2.54 KB
/
policy-validator.ts
File metadata and controls
89 lines (77 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import { Ajv, ValidateFunction } from "ajv";
import jsonLogic from "json-logic-js";
import * as defaultSchema from "../../schemas/policy-2023-02.schema.json" with { type: "json" };
import { JsonLogicParser, JsonSchema, PolicyDocument } from "../types.js";
import { arrayify } from "../utils/arr.js";
import {
MalformedStatementDetail,
MalformedPolicyStatementError,
MalformedPolicyDocumentError,
} from "./errors.js";
interface ValidatorOptions {
schema?: JsonSchema;
validator?: ValidateFunction;
parser?: JsonLogicParser;
}
export class PolicyDocumentValidator {
static #instance: PolicyDocumentValidator;
static get instance(): PolicyDocumentValidator {
if (!this.#instance) {
this.#instance = new PolicyDocumentValidator();
}
return this.#instance;
}
private ajv: Ajv;
private validator: ValidateFunction;
private parser: JsonLogicParser;
constructor(
schema?: JsonSchema,
{ validator, parser }: ValidatorOptions = {},
) {
this.parser = parser ?? jsonLogic;
this.ajv = new Ajv({ allErrors: true });
if (validator) {
this.validator = validator;
} else {
this.validator = this.ajv.compile(schema ?? defaultSchema);
}
}
/**
* Checks a provided resource policy document for correctness
*
* A correct policy:
* - matches the schema
* - lists all possible actions in $.actions
* - has a parseable constraint
*
* @throws {MalformedResourcePolicyError} the document is not well formed
* @throws {MalformedActionPoliciesError} one or more action policies has an unparseable constraint
*/
validate(doc: PolicyDocument): void {
if (!this.validator(doc)) {
const details = this.ajv.errorsText(this.validator.errors);
console.error({ details });
console.dir({ doc }, { depth: 10 });
throw new MalformedPolicyDocumentError(doc, details);
}
this.validateConstraints(doc);
}
/**
* Checks that the document has listed all actions in its policy definitions, plus ensures
* that the constraints contained within each action policy definition are evaluatable by
* our parser (JsonLogic usually)
*/
private validateConstraints(doc: PolicyDocument): void {
const invalidStatements: MalformedStatementDetail[] = [];
arrayify(doc.statement).forEach((policy) => {
try {
this.parser.apply(policy.constraint);
} catch (error) {
invalidStatements.push({ policy, error });
}
});
if (invalidStatements.length) {
throw new MalformedPolicyStatementError(invalidStatements);
}
}
}