-
Notifications
You must be signed in to change notification settings - Fork 152
/
index.js
54 lines (40 loc) · 1.42 KB
/
index.js
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
const Rego = require("@open-policy-agent/opa-wasm")
// REGO_WASM is the resource the compiled policy is loaded into
var policy_wasm = REGO_WASM
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
// Load WASM compiled policy, the loading is done asynchronously.
var rego = new Rego()
var loaded_policy = null
rego.load_policy(policy_wasm).then(policy => {
loaded_policy = policy
}, error => {
console.error("failed to load policy: " + error)
})
async function handleRequest(request) {
//console.time("eval")
// The policy may not have been loaded yet..
// until then deny everything
if (loaded_policy == null) {
return new Response('{"error": "Policy not ready yet."}',
{ status: 503, statusText: "Service Unavailable" })
}
// the Request object doesn't have a "path"
// field, only "url". So we add it ourselves
url = new URL(request.url)
request.path = url.pathname
input_json = JSON.stringify(request)
//console.log(input_json)
allow = loaded_policy.eval_bool(input_json)
//console.log("allow = " + allow)
if (!allow) {
// Short circuit the request here.
return new Response('{"error": "Not allowed by policy"}',
{ status: 403, statusText: "Forbidden" })
}
// Allowed request
const response = await fetch(request)
//console.timeEnd("eval")
return response
}