Repository navigation
Expand file tree
/
Copy pathpython.ae
More file actions
51 lines (47 loc) · 1.79 KB
/
Copy pathpython.ae
File metadata and controls
51 lines (47 loc) · 1.79 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
// Hosting Python: Python code run inside an Aether program, sandboxed.
//
// contrib.host.python embeds CPython in the program. `python.run(code)`
// runs a script; `python.run_sandboxed(grants, code)` runs one with the
// Aether permission checker installed, so the libc calls Python makes
// (opening a file, reading the environment, connecting) are checked
// against the grants, and what they do not allow fails inside Python as
// if it were not there. Each returns 0 when the script ran to its end.
// CPython reads `os.environ` once at start, before any grant applies, so
// a sandboxed script asks libc through ctypes; docs/containment-sandbox.md
// has each interpreter's caveats.
//
// Run: ae run examples/04-interop/05-hosts/python.ae
// Needs: Python 3 development files, built in with
// CFLAGS="-DAETHER_HAS_PYTHON $(python3-config --includes)"
// LDFLAGS="$(python3-config --ldflags --embed)"; without them the bridge
// is a stub that reports itself unavailable. CI's contrib/host job builds
// and runs it.
// See: docs/containment-sandbox.md
import std.sandbox
import contrib.host.python
main() {
python.run("print('hello from Python', 6 * 7)")
reader = sandbox.new("reader") {
grant_env("HOME")
grant_fs_read("/etc/*")
}
defer sandbox.free(reader)
nothing = sandbox.new("nothing") {
grant_env("TERM")
}
defer sandbox.free(nothing)
script = <<PY
import ctypes
libc = ctypes.CDLL(None)
libc.getenv.restype = ctypes.c_char_p
print('HOME visible:', libc.getenv(b'HOME') is not None)
open('/etc/hostname').read()
PY
if python.run_sandboxed(reader, script) == 0 {
println("reader: read /etc/hostname")
}
if python.run_sandboxed(nothing, script) != 0 {
println("nothing: /etc/hostname refused")
}
python.finalize()
}