amberjs 1.17.0

JavaScript/TypeScript runtime built with Rust and V8
Documentation
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Amber v1.6.0: Enterprise Capability-Based Security (`amber:security` / `amber:permissions`)
//
// Provides JavaScript runtime introspection and enforcement of fine-grained capabilities:
// - Query and test permissions (fs, net, env, run)
// - Introspect active allow/deny rule sets and sandbox mode
// - Dynamic revocation of permissions for defense-in-depth
// - Capability policy construction and attenuation for multi-tenant workers

use std::path::PathBuf;

use rusty_v8 as v8;
use serde::{Deserialize, Serialize};

use crate::permissions::{
    global_resource_broker, has_restrictions, sandbox_strict_env, PermissionAction, PermissionKind,
    ResourceId,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionQueryDescriptor {
    pub name: String,
    pub path: Option<String>,
    pub host: Option<String>,
    pub var_name: Option<String>,
    pub command: Option<String>,
}

fn parse_descriptor_to_parts(
    name: &str,
    path: Option<String>,
    host: Option<String>,
    var_name: Option<String>,
    command: Option<String>,
) -> (PermissionKind, PermissionAction, ResourceId) {
    match name.to_lowercase().as_str() {
        "read" => {
            let res = path
                .map(|p| ResourceId::Path(PathBuf::from(p)))
                .unwrap_or(ResourceId::Any);
            (PermissionKind::FileSystem, PermissionAction::Read, res)
        }
        "write" => {
            let res = path
                .map(|p| ResourceId::Path(PathBuf::from(p)))
                .unwrap_or(ResourceId::Any);
            (PermissionKind::FileSystem, PermissionAction::Write, res)
        }
        "fs" | "filesystem" => {
            let res = path
                .map(|p| ResourceId::Path(PathBuf::from(p)))
                .unwrap_or(ResourceId::Any);
            (PermissionKind::FileSystem, PermissionAction::Read, res)
        }
        "net" | "network" | "connect" => {
            let res = host
                .map(|h| {
                    if h.starts_with("http://") || h.starts_with("https://") {
                        ResourceId::Url(h)
                    } else {
                        ResourceId::Url(format!("https://{}", h))
                    }
                })
                .unwrap_or(ResourceId::Any);
            (PermissionKind::Network, PermissionAction::Connect, res)
        }
        "listen" => {
            let res = host.map(ResourceId::Name).unwrap_or(ResourceId::Any);
            (PermissionKind::Network, PermissionAction::Listen, res)
        }
        "env" | "environment" => {
            let res = var_name.map(ResourceId::Name).unwrap_or(ResourceId::Any);
            (PermissionKind::Environment, PermissionAction::Read, res)
        }
        "run" | "exec" | "process" => {
            let res = command.map(ResourceId::Name).unwrap_or(ResourceId::Any);
            (PermissionKind::Process, PermissionAction::Execute, res)
        }
        _ => (
            PermissionKind::FileSystem,
            PermissionAction::Read,
            ResourceId::Any,
        ),
    }
}

/// Sets up `amber:security` / `amber:permissions` inside V8 context
pub fn setup_security_api(
    scope: &mut v8::PinScope,
    context: &v8::Local<v8::Context>,
) -> anyhow::Result<()> {
    let security_obj = v8::Object::new(scope);
    let permissions_obj = v8::Object::new(scope);

    // 1. permissions.query({ name, path, host, varName, command })
    let query_fn = v8::Function::new(
        scope,
        |scope: &mut v8::PinScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| {
            if args.length() == 0 || !args.get(0).is_object() {
                let msg = v8::String::new(scope, "permissions.query requires a descriptor object")
                    .unwrap();
                let exc = v8::Exception::type_error(scope, msg);
                scope.throw_exception(exc);
                return;
            }

            let obj = args.get(0).to_object(scope).unwrap();
            let name_key = v8::String::new(scope, "name").unwrap();
            let name_val = obj
                .get(scope, name_key.into())
                .map(|v| v.to_rust_string_lossy(scope))
                .unwrap_or_else(|| "read".to_string());

            let path_key = v8::String::new(scope, "path").unwrap();
            let path_val = obj.get(scope, path_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let host_key = v8::String::new(scope, "host").unwrap();
            let host_val = obj.get(scope, host_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let var_key = v8::String::new(scope, "varName").unwrap();
            let var_val = obj.get(scope, var_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let cmd_key = v8::String::new(scope, "command").unwrap();
            let cmd_val = obj.get(scope, cmd_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let (kind, action, resource) =
                parse_descriptor_to_parts(&name_val, path_val, host_val, var_val, cmd_val);

            let broker = global_resource_broker().read().unwrap();
            let decision = broker.check(kind, action, resource);
            let state_str = if decision.is_allowed() {
                "granted"
            } else {
                "denied"
            };

            let res_obj = v8::Object::new(scope);
            let state_key = v8::String::new(scope, "state").unwrap();
            let state_val = v8::String::new(scope, state_str).unwrap();
            res_obj.set(scope, state_key.into(), state_val.into());

            let name_prop = v8::String::new(scope, &name_val).unwrap();
            res_obj.set(scope, name_key.into(), name_prop.into());

            rv.set(res_obj.into());
        },
    )
    .unwrap();
    let query_key = v8::String::new(scope, "query").unwrap();
    permissions_obj.set(scope, query_key.into(), query_fn.into());

    // 2. permissions.has(descriptor) -> boolean
    let has_fn = v8::Function::new(
        scope,
        |scope: &mut v8::PinScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| {
            if args.length() == 0 || !args.get(0).is_object() {
                rv.set(v8::Boolean::new(scope, false).into());
                return;
            }

            let obj = args.get(0).to_object(scope).unwrap();
            let name_key = v8::String::new(scope, "name").unwrap();
            let name_val = obj
                .get(scope, name_key.into())
                .map(|v| v.to_rust_string_lossy(scope))
                .unwrap_or_else(|| "read".to_string());

            let path_key = v8::String::new(scope, "path").unwrap();
            let path_val = obj.get(scope, path_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let host_key = v8::String::new(scope, "host").unwrap();
            let host_val = obj.get(scope, host_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let var_key = v8::String::new(scope, "varName").unwrap();
            let var_val = obj.get(scope, var_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let cmd_key = v8::String::new(scope, "command").unwrap();
            let cmd_val = obj.get(scope, cmd_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let (kind, action, resource) =
                parse_descriptor_to_parts(&name_val, path_val, host_val, var_val, cmd_val);

            let broker = global_resource_broker().read().unwrap();
            let decision = broker.check(kind, action, resource);
            rv.set(v8::Boolean::new(scope, decision.is_allowed()).into());
        },
    )
    .unwrap();
    let has_key = v8::String::new(scope, "has").unwrap();
    permissions_obj.set(scope, has_key.into(), has_fn.into());

    // 3. permissions.list()
    let list_fn = v8::Function::new(
        scope,
        |scope: &mut v8::PinScope,
         _args: v8::FunctionCallbackArguments,
         mut rv: v8::ReturnValue| {
            let broker = global_resource_broker().read().unwrap();
            let has_res = has_restrictions();
            let strict_env = sandbox_strict_env();

            let res_obj = v8::Object::new(scope);

            let has_res_key = v8::String::new(scope, "hasRestrictions").unwrap();
            let has_res_val = v8::Boolean::new(scope, has_res);
            res_obj.set(scope, has_res_key.into(), has_res_val.into());

            let strict_env_key = v8::String::new(scope, "sandboxStrictEnv").unwrap();
            let strict_env_val = v8::Boolean::new(scope, strict_env);
            res_obj.set(scope, strict_env_key.into(), strict_env_val.into());

            // Allow rules
            let allow_rules = broker.allow_rules();
            let allow_arr = v8::Array::new(scope, allow_rules.len() as i32);
            for (i, rule) in allow_rules.iter().enumerate() {
                let rule_obj = v8::Object::new(scope);
                let k_key = v8::String::new(scope, "kind").unwrap();
                let k_val = v8::String::new(scope, rule.kind.as_str()).unwrap();
                rule_obj.set(scope, k_key.into(), k_val.into());

                let a_key = v8::String::new(scope, "action").unwrap();
                let a_val = v8::String::new(scope, rule.action.as_str()).unwrap();
                rule_obj.set(scope, a_key.into(), a_val.into());

                let r_key = v8::String::new(scope, "resource").unwrap();
                let r_val = v8::String::new(scope, &rule.resource.display_for_audit()).unwrap();
                rule_obj.set(scope, r_key.into(), r_val.into());

                allow_arr.set_index(scope, i as u32, rule_obj.into());
            }
            let allow_key = v8::String::new(scope, "allowRules").unwrap();
            res_obj.set(scope, allow_key.into(), allow_arr.into());

            // Deny rules
            let deny_rules = broker.deny_rules();
            let deny_arr = v8::Array::new(scope, deny_rules.len() as i32);
            for (i, rule) in deny_rules.iter().enumerate() {
                let rule_obj = v8::Object::new(scope);
                let k_key = v8::String::new(scope, "kind").unwrap();
                let k_val = v8::String::new(scope, rule.kind.as_str()).unwrap();
                rule_obj.set(scope, k_key.into(), k_val.into());

                let a_key = v8::String::new(scope, "action").unwrap();
                let a_val = v8::String::new(scope, rule.action.as_str()).unwrap();
                rule_obj.set(scope, a_key.into(), a_val.into());

                let r_key = v8::String::new(scope, "resource").unwrap();
                let r_val = v8::String::new(scope, &rule.resource.display_for_audit()).unwrap();
                rule_obj.set(scope, r_key.into(), r_val.into());

                deny_arr.set_index(scope, i as u32, rule_obj.into());
            }
            let deny_key = v8::String::new(scope, "denyRules").unwrap();
            res_obj.set(scope, deny_key.into(), deny_arr.into());

            rv.set(res_obj.into());
        },
    )
    .unwrap();
    let list_key = v8::String::new(scope, "list").unwrap();
    permissions_obj.set(scope, list_key.into(), list_fn.into());

    // 4. permissions.revoke(descriptor)
    let revoke_fn = v8::Function::new(
        scope,
        |scope: &mut v8::PinScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| {
            if args.length() == 0 || !args.get(0).is_object() {
                let msg = v8::String::new(scope, "permissions.revoke requires a descriptor object")
                    .unwrap();
                let exc = v8::Exception::type_error(scope, msg);
                scope.throw_exception(exc);
                return;
            }

            let obj = args.get(0).to_object(scope).unwrap();
            let name_key = v8::String::new(scope, "name").unwrap();
            let name_val = obj
                .get(scope, name_key.into())
                .map(|v| v.to_rust_string_lossy(scope))
                .unwrap_or_else(|| "read".to_string());

            let path_key = v8::String::new(scope, "path").unwrap();
            let path_val = obj.get(scope, path_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let host_key = v8::String::new(scope, "host").unwrap();
            let host_val = obj.get(scope, host_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let var_key = v8::String::new(scope, "varName").unwrap();
            let var_val = obj.get(scope, var_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let cmd_key = v8::String::new(scope, "command").unwrap();
            let cmd_val = obj.get(scope, cmd_key.into()).and_then(|v| {
                if v.is_string() {
                    Some(v.to_rust_string_lossy(scope))
                } else {
                    None
                }
            });

            let (kind, action, resource) =
                parse_descriptor_to_parts(&name_val, path_val, host_val, var_val, cmd_val);

            let mut broker = global_resource_broker().write().unwrap();
            broker.deny(kind, action, resource);
            rv.set(v8::Boolean::new(scope, true).into());
        },
    )
    .unwrap();
    let revoke_key = v8::String::new(scope, "revoke").unwrap();
    permissions_obj.set(scope, revoke_key.into(), revoke_fn.into());

    // 5. createSandboxPolicy(rules)
    let create_policy_fn = v8::Function::new(
        scope,
        |scope: &mut v8::PinScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| {
            let policy_obj = if args.length() > 0 && args.get(0).is_object() {
                args.get(0)
            } else {
                v8::Object::new(scope).into()
            };
            rv.set(policy_obj);
        },
    )
    .unwrap();
    let cp_key = v8::String::new(scope, "createSandboxPolicy").unwrap();
    security_obj.set(scope, cp_key.into(), create_policy_fn.into());

    // 6. attenuate(parentPolicy, restrictions)
    let attenuate_fn = v8::Function::new(
        scope,
        |scope: &mut v8::PinScope, args: v8::FunctionCallbackArguments, mut rv: v8::ReturnValue| {
            let base_obj = if args.length() > 0 && args.get(0).is_object() {
                args.get(0).to_object(scope).unwrap()
            } else {
                v8::Object::new(scope)
            };

            let rest_obj = if args.length() > 1 && args.get(1).is_object() {
                args.get(1).to_object(scope).unwrap()
            } else {
                v8::Object::new(scope)
            };

            // Merge rest_obj properties into new result object
            let merged = v8::Object::new(scope);

            if let Some(prop_names) = base_obj.get_property_names(scope, Default::default()) {
                let len = prop_names.length();
                for i in 0..len {
                    if let Some(k) = prop_names.get_index(scope, i) {
                        if let Some(v) = base_obj.get(scope, k) {
                            merged.set(scope, k, v);
                        }
                    }
                }
            }

            if let Some(prop_names) = rest_obj.get_property_names(scope, Default::default()) {
                let len = prop_names.length();
                for i in 0..len {
                    if let Some(k) = prop_names.get_index(scope, i) {
                        if let Some(v) = rest_obj.get(scope, k) {
                            merged.set(scope, k, v);
                        }
                    }
                }
            }

            rv.set(merged.into());
        },
    )
    .unwrap();
    let att_key = v8::String::new(scope, "attenuate").unwrap();
    security_obj.set(scope, att_key.into(), attenuate_fn.into());

    let perm_key = v8::String::new(scope, "permissions").unwrap();
    security_obj.set(scope, perm_key.into(), permissions_obj.into());

    // Register globally as `__amber_security`, `security`, `__amber_permissions`, `permissions`
    let global = context.global(scope);
    let sec_global_key = v8::String::new(scope, "__amber_security").unwrap();
    global.set(scope, sec_global_key.into(), security_obj.into());
    let sec_plain_key = v8::String::new(scope, "security").unwrap();
    global.set(scope, sec_plain_key.into(), security_obj.into());

    let perm_global_key = v8::String::new(scope, "__amber_permissions").unwrap();
    global.set(scope, perm_global_key.into(), permissions_obj.into());
    let perm_plain_key = v8::String::new(scope, "permissions").unwrap();
    global.set(scope, perm_plain_key.into(), permissions_obj.into());

    Ok(())
}