sandkiln 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sandkiln-0.1.0/.gitignore +40 -0
- sandkiln-0.1.0/AGENTS.md +141 -0
- sandkiln-0.1.0/PKG-INFO +145 -0
- sandkiln-0.1.0/README.md +127 -0
- sandkiln-0.1.0/pyproject.toml +29 -0
- sandkiln-0.1.0/src/sandkiln/__init__.py +23 -0
- sandkiln-0.1.0/src/sandkiln/_config.py +14 -0
- sandkiln-0.1.0/src/sandkiln/_http.py +50 -0
- sandkiln-0.1.0/src/sandkiln/drive.py +75 -0
- sandkiln-0.1.0/src/sandkiln/errors.py +7 -0
- sandkiln-0.1.0/src/sandkiln/image.py +87 -0
- sandkiln-0.1.0/src/sandkiln/pool.py +117 -0
- sandkiln-0.1.0/src/sandkiln/py.typed +0 -0
- sandkiln-0.1.0/src/sandkiln/sandbox.py +451 -0
- sandkiln-0.1.0/tests/test_preview_url.py +60 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Rust
|
|
2
|
+
target/
|
|
3
|
+
Cargo.lock
|
|
4
|
+
|
|
5
|
+
# Local benchmark history (scripts/bench-report.sh) -- dev-box-specific
|
|
6
|
+
# and directional, not meant to be committed or shared across machines.
|
|
7
|
+
scripts/bench-results/
|
|
8
|
+
|
|
9
|
+
# Node
|
|
10
|
+
node_modules/
|
|
11
|
+
dist/
|
|
12
|
+
*.tsbuildinfo
|
|
13
|
+
.turbo/
|
|
14
|
+
.astro/
|
|
15
|
+
|
|
16
|
+
# Python
|
|
17
|
+
__pycache__/
|
|
18
|
+
*.egg-info/
|
|
19
|
+
.venv/
|
|
20
|
+
build/
|
|
21
|
+
|
|
22
|
+
# Images / large build artifacts
|
|
23
|
+
images/build/
|
|
24
|
+
images/*.ext4
|
|
25
|
+
images/*.img
|
|
26
|
+
*.vmlinux
|
|
27
|
+
|
|
28
|
+
# Local env / secrets
|
|
29
|
+
.env
|
|
30
|
+
.env.*
|
|
31
|
+
*.pem
|
|
32
|
+
|
|
33
|
+
# OS / editor
|
|
34
|
+
.DS_Store
|
|
35
|
+
*.log
|
|
36
|
+
|
|
37
|
+
# Local tooling state
|
|
38
|
+
.claude/
|
|
39
|
+
.vercel
|
|
40
|
+
.env*
|
sandkiln-0.1.0/AGENTS.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# AGENTS.md — sandkiln (Python SDK)
|
|
2
|
+
|
|
3
|
+
Read the root `AGENTS.md` first for project-wide conventions. This file
|
|
4
|
+
is scoped to this one package.
|
|
5
|
+
|
|
6
|
+
## What this package is
|
|
7
|
+
|
|
8
|
+
The Python client, mirroring `packages/sdk` (the JS/TS SDK) exactly —
|
|
9
|
+
same operations, same daemon, Python-idiomatic naming (`run_command` not
|
|
10
|
+
`runCommand`, snake_case fields, a plain synchronous API — no `asyncio`).
|
|
11
|
+
If you're adding something here, check whether the JS SDK has it first;
|
|
12
|
+
these two should never drift apart in capability, only in the idioms of
|
|
13
|
+
each language.
|
|
14
|
+
|
|
15
|
+
Zero runtime dependencies on purpose — `urllib` from the standard
|
|
16
|
+
library, not `requests`. Match this if you add anything; don't introduce
|
|
17
|
+
a dependency the JS SDK's equivalent doesn't need either (it uses native
|
|
18
|
+
`fetch`).
|
|
19
|
+
|
|
20
|
+
## Files
|
|
21
|
+
|
|
22
|
+
- `sandbox.py` — the `Sandbox` class, `ExecResult`/`SandboxInfo`
|
|
23
|
+
dataclasses. Structurally mirrors `packages/sdk/src/sandbox.ts` — if
|
|
24
|
+
you change one, change the other the same way. `preview_url` is pure and
|
|
25
|
+
network-free like `attach` — it just builds the URL for the daemon's
|
|
26
|
+
`/sandboxes/:id/preview/:port` reverse proxy (see
|
|
27
|
+
`core/crates/daemon/src/routes_preview.rs`), appending the auth token as
|
|
28
|
+
a `?token=` query parameter rather than a header when one is configured,
|
|
29
|
+
since the caller is typically a browser tab or `<iframe>`. Unlike the JS
|
|
30
|
+
SDK's `previewUrl`, the sandbox id isn't URL-quoted here — matching this
|
|
31
|
+
file's own existing convention (`run_command`/`read_file`/etc. don't
|
|
32
|
+
quote it either), not an oversight. `Sandbox.create`'s `image_id`
|
|
33
|
+
boots from a registered image (see `image.py`) instead of the daemon's
|
|
34
|
+
configured default rootfs.
|
|
35
|
+
- `image.py` — the `Image` class, `ImageInfo` dataclass. Mirrors
|
|
36
|
+
`packages/sdk/src/image.ts`: `register`/`list`/`delete` are all
|
|
37
|
+
classmethods, no instance state — an image has no behavior besides
|
|
38
|
+
delete, and delete only ever needs an id.
|
|
39
|
+
- `drive.py` — the `Drive` class, `DriveInfo`/`DriveHolder` dataclasses.
|
|
40
|
+
Mirrors `packages/sdk/src/drive.ts` the same way `image.py` mirrors
|
|
41
|
+
`image.ts` — same static-classmethod shape, no instance state. Attach
|
|
42
|
+
a drive at create time via `Sandbox.create`'s `drives` argument
|
|
43
|
+
(`DriveAttachment` dataclass, defined in `sandbox.py` since it's
|
|
44
|
+
create-time input, not a `Drive`-class operation).
|
|
45
|
+
- `pool.py` — the `Pool` class, `PoolInfo` dataclass. Mirrors
|
|
46
|
+
`packages/sdk/src/pool.ts` — same static-classmethod shape, caller-given
|
|
47
|
+
`id` like `image.py`'s `register` (not a server-generated one like
|
|
48
|
+
`drive.py`'s `create`). No "claim from pool" method here at all —
|
|
49
|
+
claiming is entirely transparent, done by a plain `Sandbox.create()`
|
|
50
|
+
whose image/resources match a configured pool.
|
|
51
|
+
- `_http.py` — the one place `urllib.request` gets called. Leading
|
|
52
|
+
underscore: not part of the public API, same convention as `_config.py`.
|
|
53
|
+
- `_config.py` — env var fallback resolution
|
|
54
|
+
(`SANDKILN_DAEMON_URL`/`SANDKILN_AUTH_TOKEN`), matching the JS SDK's
|
|
55
|
+
`config.ts` exactly (same env var names, same default).
|
|
56
|
+
- `errors.py` — `SandkilnApiError(status, message)`, matching the JS
|
|
57
|
+
SDK's `SandkilnApiError` shape.
|
|
58
|
+
- `py.typed` — empty PEP 561 marker so downstream type checkers (mypy,
|
|
59
|
+
pyright) trust this package's type hints instead of treating it as
|
|
60
|
+
untyped. Ships in the wheel automatically — `python -m build` +
|
|
61
|
+
`unzip -l dist/*.whl` confirmed it, no `pyproject.toml` change needed;
|
|
62
|
+
hatchling's `[tool.hatch.build.targets.wheel]` `packages =
|
|
63
|
+
["src/sandkiln"]` already includes every file under that directory.
|
|
64
|
+
|
|
65
|
+
## The bug that already happened here — read before adding a method
|
|
66
|
+
|
|
67
|
+
**Never name a method the same as a builtin type you use in a type hint
|
|
68
|
+
elsewhere in the same class.** `Sandbox.list()` shadowed the builtin
|
|
69
|
+
`list` for the `list[str]` annotation on `run_command()` (defined later
|
|
70
|
+
in the class body) — this crashed at *import time* with `TypeError:
|
|
71
|
+
'classmethod' object is not subscriptable', but only on Python <3.14;
|
|
72
|
+
this session's local Python 3.14 defers annotation evaluation by default
|
|
73
|
+
(PEP 649) and didn't reproduce it, CI on 3.12 did. Fixed with `from
|
|
74
|
+
__future__ import annotations` at the top of every file using modern
|
|
75
|
+
union/generic syntax (`X | None`, `list[X]`, `dict[K, V]`) — this is
|
|
76
|
+
already present in every file here; **keep it** if you add a new file
|
|
77
|
+
with this kind of type hint, and remember that Python 3.14 will not
|
|
78
|
+
catch this class of bug locally even if you test there. This also
|
|
79
|
+
happens to be required for real 3.9 compatibility (`X | None` syntax is
|
|
80
|
+
a 3.10+ runtime feature without deferred annotations) — this package
|
|
81
|
+
declares `requires-python = ">=3.9"`.
|
|
82
|
+
|
|
83
|
+
## Testing
|
|
84
|
+
|
|
85
|
+
`tests/test_preview_url.py` covers `Sandbox.preview_url`'s pure
|
|
86
|
+
URL-building logic with stdlib `unittest` (mirrors
|
|
87
|
+
`packages/sdk/test/previewUrl.test.js` on the JS side, zero added
|
|
88
|
+
dependency — same reasoning as that package's `node:test` choice). Run:
|
|
89
|
+
`python packages/python/tests/test_preview_url.py` (a plain
|
|
90
|
+
`unittest.main()` invocation, not `unittest discover`, since there's no
|
|
91
|
+
`tests/__init__.py` to make the directory importable as a package for
|
|
92
|
+
discovery). Every other method needs a live daemon to test meaningfully,
|
|
93
|
+
which is why this is the only test file here today.
|
|
94
|
+
|
|
95
|
+
## Building and verifying
|
|
96
|
+
|
|
97
|
+
```
|
|
98
|
+
python3 -m venv /tmp/some-venv
|
|
99
|
+
/tmp/some-venv/bin/pip install -e .
|
|
100
|
+
/tmp/some-venv/bin/python3 -c "import sandkiln; sandkiln.Sandbox"
|
|
101
|
+
```
|
|
102
|
+
That import check is the minimum bar — it's exactly what caught the bug
|
|
103
|
+
above, and exactly what CI runs. Beyond that, **verify against a real
|
|
104
|
+
`sandkilnd`** the same way described in `packages/sdk/AGENTS.md` — swap
|
|
105
|
+
the Node script for a small Python one.
|
|
106
|
+
|
|
107
|
+
`python -m build` (needs `pip install build`) produces the actual sdist/
|
|
108
|
+
wheel CI and the publish workflow use — run it if you're touching
|
|
109
|
+
`pyproject.toml` specifically.
|
|
110
|
+
|
|
111
|
+
## Non-obvious things specific to this package
|
|
112
|
+
|
|
113
|
+
- `Sandbox.attach(id, ...)` exists for the same reason as the JS SDK's:
|
|
114
|
+
a fresh process reconstructing a handle to an existing sandbox without
|
|
115
|
+
a network round-trip.
|
|
116
|
+
|
|
117
|
+
## Publishing
|
|
118
|
+
|
|
119
|
+
Not yet published to PyPI. Code-side, this package is ready:
|
|
120
|
+
`pyproject.toml` is filled in with real values (no placeholders), the
|
|
121
|
+
package builds a clean wheel/sdist (`python -m build`), and it carries a
|
|
122
|
+
`py.typed` marker.
|
|
123
|
+
|
|
124
|
+
**Already automated** — `.github/workflows/publish-python-sdk.yml`:
|
|
125
|
+
triggers on a manual dispatch or a `py-v*.*.*` tag push, builds the
|
|
126
|
+
sdist/wheel, and on a tag push additionally checks the tag's version
|
|
127
|
+
against `pyproject.toml`'s `project.version` and fails the run if they
|
|
128
|
+
don't match. It then publishes via `pypa/gh-action-pypi-publish` using
|
|
129
|
+
PyPI's OIDC trusted publishing — no stored token, no 2FA-on-publish
|
|
130
|
+
friction (the workflow's own `id-token: write` permission is what makes
|
|
131
|
+
the OIDC exchange possible).
|
|
132
|
+
|
|
133
|
+
**Still manual, one-time, needs the account owner** — trusted publishing
|
|
134
|
+
has to be registered on pypi.org *before* the workflow above can
|
|
135
|
+
succeed: register the `sandkiln` project name on PyPI, then under its
|
|
136
|
+
"Publishing" settings add a trusted publisher pointing at owner
|
|
137
|
+
`SumitKumar-17`, repo `sandkiln`, workflow file
|
|
138
|
+
`publish-python-sdk.yml` (environment left blank unless one is added to
|
|
139
|
+
the workflow later). This needs the pypi.org account itself — no agent
|
|
140
|
+
or CI job can do it. Once registered, either push a `py-v0.1.0` tag or
|
|
141
|
+
run the workflow manually to publish.
|
sandkiln-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sandkiln
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Client SDK for sandkiln: hardware-isolated Firecracker microVM sandboxes for running untrusted code.
|
|
5
|
+
Project-URL: Homepage, https://github.com/SumitKumar-17/sandkiln
|
|
6
|
+
Project-URL: Repository, https://github.com/SumitKumar-17/sandkiln
|
|
7
|
+
Project-URL: Issues, https://github.com/SumitKumar-17/sandkiln/issues
|
|
8
|
+
Author: Sumit Kumar
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
Keywords: firecracker,isolation,microvm,sandbox,untrusted-code,vm
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# sandkiln
|
|
20
|
+
|
|
21
|
+
Client SDK for [sandkiln](https://github.com/SumitKumar-17/sandkiln) — a
|
|
22
|
+
compute primitive for safely running untrusted or AI-generated code in
|
|
23
|
+
hardware-isolated Firecracker microVMs. Each sandbox is a real microVM:
|
|
24
|
+
its own kernel, its own filesystem, its own network.
|
|
25
|
+
|
|
26
|
+
This package is the client. It talks to a `sandkilnd` daemon over HTTP —
|
|
27
|
+
you need one running somewhere reachable (see the main repo for how to
|
|
28
|
+
run one; there is no hosted service). Zero runtime dependencies —
|
|
29
|
+
`urllib` from the standard library is all it needs.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
Not published to PyPI yet — install from this repo:
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
pip install ./packages/python
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from sandkiln import Sandbox
|
|
43
|
+
|
|
44
|
+
sandbox = Sandbox.create(tags={"env": "ci"})
|
|
45
|
+
|
|
46
|
+
result = sandbox.run_command("python3", ["analyze.py"])
|
|
47
|
+
print(result.stdout, result.exit_code)
|
|
48
|
+
|
|
49
|
+
sandbox.write_file("/tmp/config.json", '{"ok": true}')
|
|
50
|
+
data = sandbox.read_file("/tmp/config.json")
|
|
51
|
+
|
|
52
|
+
running = Sandbox.list(tags={"env": "ci"})
|
|
53
|
+
|
|
54
|
+
sandbox.stop()
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Configuration
|
|
58
|
+
|
|
59
|
+
- **Daemon URL**: pass `base_url` to `Sandbox.create()`/`Sandbox.list()`,
|
|
60
|
+
or set `SANDKILN_DAEMON_URL`. Defaults to `http://127.0.0.1:7777`.
|
|
61
|
+
- **Auth**: pass `auth_token`, or set `SANDKILN_AUTH_TOKEN`, if the
|
|
62
|
+
daemon has `SANDKILN_AUTH_TOKEN` set. Omit entirely for an
|
|
63
|
+
unauthenticated local daemon.
|
|
64
|
+
|
|
65
|
+
## API
|
|
66
|
+
|
|
67
|
+
- `Sandbox.create(name=None, tags=None, base_url=None, auth_token=None, vcpu_count=None, mem_size_mib=None, image_id=None)` —
|
|
68
|
+
boots a sandbox. `name` is a caller-given identity, unique among live
|
|
69
|
+
sandboxes and held snapshots (409 if already taken) — see `by_name`/
|
|
70
|
+
`get_or_create` below to find it again later. `vcpu_count`/
|
|
71
|
+
`mem_size_mib` override the daemon's configured defaults for this one
|
|
72
|
+
sandbox, subject to the daemon's configured ceiling. `image_id` boots
|
|
73
|
+
from a registered image (see `Image.register` below) instead of the
|
|
74
|
+
daemon's configured default rootfs.
|
|
75
|
+
- `Sandbox.attach(id, base_url=None, auth_token=None)` — wraps an
|
|
76
|
+
existing sandbox id without a network round-trip.
|
|
77
|
+
- `Sandbox.by_name(name, base_url=None, auth_token=None)` — resolves a
|
|
78
|
+
name to a *live* sandbox and returns a handle to it. Raises
|
|
79
|
+
`SandkilnApiError` (409) if the name currently belongs to a stopped
|
|
80
|
+
(snapshotted) sandbox instead — use `get_or_create` if you want that
|
|
81
|
+
resumed automatically.
|
|
82
|
+
- `Sandbox.get_or_create(name, tags=None, base_url=None, auth_token=None, vcpu_count=None, mem_size_mib=None)`
|
|
83
|
+
— resolves `name` to a sandbox in one race-safe call: a live sandbox
|
|
84
|
+
with this name is returned as-is, a stopped one is resumed, otherwise a
|
|
85
|
+
fresh one is created and given this name. Returns `(sandbox, created)`.
|
|
86
|
+
- `Sandbox.list(tags=None, base_url=None, auth_token=None)` — lists
|
|
87
|
+
sandboxes; `tags` filters by exact match on every given key.
|
|
88
|
+
- `sandbox.run_command(command, args=None)` — returns an `ExecResult`
|
|
89
|
+
(`stdout`, `stderr`, `exit_code`).
|
|
90
|
+
- `sandbox.read_file(path)` — returns file contents as `bytes`.
|
|
91
|
+
- `sandbox.write_file(path, content)` — `content` is `str` or `bytes`.
|
|
92
|
+
- `sandbox.preview_url(port, path="/")` — the URL a browser can open
|
|
93
|
+
directly to reach a server listening on `port` inside this sandbox,
|
|
94
|
+
proxied through the daemon.
|
|
95
|
+
- `sandbox.stop(keep=None)` — stops the sandbox. By default (`keep`
|
|
96
|
+
omitted or `True`) this *preserves* its state as a resumable snapshot,
|
|
97
|
+
same as `snapshot()`, and returns a `StopResult(kept, snapshot_id)`.
|
|
98
|
+
Pass `keep=False` for the old "just destroy it" behavior — no
|
|
99
|
+
snapshot, nothing left to resume.
|
|
100
|
+
- `sandbox.snapshot()` — saves the sandbox's full state to disk and stops
|
|
101
|
+
it; returns a snapshot id. The daemon can also do this on its own, for
|
|
102
|
+
an idle sandbox, if the operator has `SANDKILN_AUTO_SUSPEND_TIMEOUT_SECS`
|
|
103
|
+
configured — see `Sandbox.list_snapshots` below for how to notice it and
|
|
104
|
+
find the resulting snapshot.
|
|
105
|
+
- `Sandbox.resume(snapshot_id, base_url=None, auth_token=None)` — boots a
|
|
106
|
+
new sandbox from a snapshot, **consuming** it (the snapshot is gone
|
|
107
|
+
afterward).
|
|
108
|
+
- `Sandbox.fork(snapshot_id, base_url=None, auth_token=None)` — boots a
|
|
109
|
+
new sandbox from a snapshot **without** consuming it, so it can be
|
|
110
|
+
forked or resumed again later. Only one live fork of a given snapshot
|
|
111
|
+
may run at a time — a second concurrent `fork()` raises
|
|
112
|
+
`SandkilnApiError` with status 409 until the first is stopped; see
|
|
113
|
+
`ROADMAP.md`'s "Persistence and snapshotting" section for why.
|
|
114
|
+
- `Sandbox.list_snapshots(source_sandbox_id=None, base_url=None, auth_token=None)`
|
|
115
|
+
— lists snapshots. `source_sandbox_id` narrows this to the (at most one)
|
|
116
|
+
snapshot taken from that original sandbox id — the way to find out
|
|
117
|
+
whether a sandbox id that dropped out of `Sandbox.list()` turned into a
|
|
118
|
+
snapshot (via a manual `snapshot()` or the daemon's auto-suspend) and
|
|
119
|
+
what its new id is.
|
|
120
|
+
- `Image.register(id, path, base_url=None, auth_token=None)` — registers
|
|
121
|
+
an already-built ext4 rootfs file at `path` on the daemon's own host
|
|
122
|
+
filesystem under `id`, for `Sandbox.create(image_id=...)` to boot from.
|
|
123
|
+
Not a file upload — the daemon can't verify the guest agent is baked
|
|
124
|
+
in without root access to loop-mount it (`ImageInfo.guest_agent_verified`
|
|
125
|
+
is always `False`); run `scripts/preflight-check.sh --root-checks
|
|
126
|
+
--rootfs-image <path>` out of band first.
|
|
127
|
+
- `Image.list(base_url=None, auth_token=None)` / `Image.delete(id, base_url=None, auth_token=None)`
|
|
128
|
+
— list registered images, or delete one (refused with 409 while any
|
|
129
|
+
live sandbox, in-flight boot, or held snapshot still references it).
|
|
130
|
+
|
|
131
|
+
This mirrors the [JS/TS SDK](https://www.npmjs.com/package/sandkiln)
|
|
132
|
+
exactly — same daemon, same operations, Python-idiomatic naming
|
|
133
|
+
(`run_command` not `runCommand`, snake_case fields).
|
|
134
|
+
|
|
135
|
+
## Status
|
|
136
|
+
|
|
137
|
+
This SDK matches the daemon's current HTTP API exactly — no more, no
|
|
138
|
+
less. Still open: publishing to PyPI, streamed command output, and
|
|
139
|
+
attaching persistent drives at create time (supported by the daemon and
|
|
140
|
+
CLI, not yet exposed here); see the
|
|
141
|
+
[roadmap](https://github.com/SumitKumar-17/sandkiln/blob/main/ROADMAP.md).
|
|
142
|
+
|
|
143
|
+
## License
|
|
144
|
+
|
|
145
|
+
MIT
|
sandkiln-0.1.0/README.md
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# sandkiln
|
|
2
|
+
|
|
3
|
+
Client SDK for [sandkiln](https://github.com/SumitKumar-17/sandkiln) — a
|
|
4
|
+
compute primitive for safely running untrusted or AI-generated code in
|
|
5
|
+
hardware-isolated Firecracker microVMs. Each sandbox is a real microVM:
|
|
6
|
+
its own kernel, its own filesystem, its own network.
|
|
7
|
+
|
|
8
|
+
This package is the client. It talks to a `sandkilnd` daemon over HTTP —
|
|
9
|
+
you need one running somewhere reachable (see the main repo for how to
|
|
10
|
+
run one; there is no hosted service). Zero runtime dependencies —
|
|
11
|
+
`urllib` from the standard library is all it needs.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
Not published to PyPI yet — install from this repo:
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
pip install ./packages/python
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Usage
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from sandkiln import Sandbox
|
|
25
|
+
|
|
26
|
+
sandbox = Sandbox.create(tags={"env": "ci"})
|
|
27
|
+
|
|
28
|
+
result = sandbox.run_command("python3", ["analyze.py"])
|
|
29
|
+
print(result.stdout, result.exit_code)
|
|
30
|
+
|
|
31
|
+
sandbox.write_file("/tmp/config.json", '{"ok": true}')
|
|
32
|
+
data = sandbox.read_file("/tmp/config.json")
|
|
33
|
+
|
|
34
|
+
running = Sandbox.list(tags={"env": "ci"})
|
|
35
|
+
|
|
36
|
+
sandbox.stop()
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Configuration
|
|
40
|
+
|
|
41
|
+
- **Daemon URL**: pass `base_url` to `Sandbox.create()`/`Sandbox.list()`,
|
|
42
|
+
or set `SANDKILN_DAEMON_URL`. Defaults to `http://127.0.0.1:7777`.
|
|
43
|
+
- **Auth**: pass `auth_token`, or set `SANDKILN_AUTH_TOKEN`, if the
|
|
44
|
+
daemon has `SANDKILN_AUTH_TOKEN` set. Omit entirely for an
|
|
45
|
+
unauthenticated local daemon.
|
|
46
|
+
|
|
47
|
+
## API
|
|
48
|
+
|
|
49
|
+
- `Sandbox.create(name=None, tags=None, base_url=None, auth_token=None, vcpu_count=None, mem_size_mib=None, image_id=None)` —
|
|
50
|
+
boots a sandbox. `name` is a caller-given identity, unique among live
|
|
51
|
+
sandboxes and held snapshots (409 if already taken) — see `by_name`/
|
|
52
|
+
`get_or_create` below to find it again later. `vcpu_count`/
|
|
53
|
+
`mem_size_mib` override the daemon's configured defaults for this one
|
|
54
|
+
sandbox, subject to the daemon's configured ceiling. `image_id` boots
|
|
55
|
+
from a registered image (see `Image.register` below) instead of the
|
|
56
|
+
daemon's configured default rootfs.
|
|
57
|
+
- `Sandbox.attach(id, base_url=None, auth_token=None)` — wraps an
|
|
58
|
+
existing sandbox id without a network round-trip.
|
|
59
|
+
- `Sandbox.by_name(name, base_url=None, auth_token=None)` — resolves a
|
|
60
|
+
name to a *live* sandbox and returns a handle to it. Raises
|
|
61
|
+
`SandkilnApiError` (409) if the name currently belongs to a stopped
|
|
62
|
+
(snapshotted) sandbox instead — use `get_or_create` if you want that
|
|
63
|
+
resumed automatically.
|
|
64
|
+
- `Sandbox.get_or_create(name, tags=None, base_url=None, auth_token=None, vcpu_count=None, mem_size_mib=None)`
|
|
65
|
+
— resolves `name` to a sandbox in one race-safe call: a live sandbox
|
|
66
|
+
with this name is returned as-is, a stopped one is resumed, otherwise a
|
|
67
|
+
fresh one is created and given this name. Returns `(sandbox, created)`.
|
|
68
|
+
- `Sandbox.list(tags=None, base_url=None, auth_token=None)` — lists
|
|
69
|
+
sandboxes; `tags` filters by exact match on every given key.
|
|
70
|
+
- `sandbox.run_command(command, args=None)` — returns an `ExecResult`
|
|
71
|
+
(`stdout`, `stderr`, `exit_code`).
|
|
72
|
+
- `sandbox.read_file(path)` — returns file contents as `bytes`.
|
|
73
|
+
- `sandbox.write_file(path, content)` — `content` is `str` or `bytes`.
|
|
74
|
+
- `sandbox.preview_url(port, path="/")` — the URL a browser can open
|
|
75
|
+
directly to reach a server listening on `port` inside this sandbox,
|
|
76
|
+
proxied through the daemon.
|
|
77
|
+
- `sandbox.stop(keep=None)` — stops the sandbox. By default (`keep`
|
|
78
|
+
omitted or `True`) this *preserves* its state as a resumable snapshot,
|
|
79
|
+
same as `snapshot()`, and returns a `StopResult(kept, snapshot_id)`.
|
|
80
|
+
Pass `keep=False` for the old "just destroy it" behavior — no
|
|
81
|
+
snapshot, nothing left to resume.
|
|
82
|
+
- `sandbox.snapshot()` — saves the sandbox's full state to disk and stops
|
|
83
|
+
it; returns a snapshot id. The daemon can also do this on its own, for
|
|
84
|
+
an idle sandbox, if the operator has `SANDKILN_AUTO_SUSPEND_TIMEOUT_SECS`
|
|
85
|
+
configured — see `Sandbox.list_snapshots` below for how to notice it and
|
|
86
|
+
find the resulting snapshot.
|
|
87
|
+
- `Sandbox.resume(snapshot_id, base_url=None, auth_token=None)` — boots a
|
|
88
|
+
new sandbox from a snapshot, **consuming** it (the snapshot is gone
|
|
89
|
+
afterward).
|
|
90
|
+
- `Sandbox.fork(snapshot_id, base_url=None, auth_token=None)` — boots a
|
|
91
|
+
new sandbox from a snapshot **without** consuming it, so it can be
|
|
92
|
+
forked or resumed again later. Only one live fork of a given snapshot
|
|
93
|
+
may run at a time — a second concurrent `fork()` raises
|
|
94
|
+
`SandkilnApiError` with status 409 until the first is stopped; see
|
|
95
|
+
`ROADMAP.md`'s "Persistence and snapshotting" section for why.
|
|
96
|
+
- `Sandbox.list_snapshots(source_sandbox_id=None, base_url=None, auth_token=None)`
|
|
97
|
+
— lists snapshots. `source_sandbox_id` narrows this to the (at most one)
|
|
98
|
+
snapshot taken from that original sandbox id — the way to find out
|
|
99
|
+
whether a sandbox id that dropped out of `Sandbox.list()` turned into a
|
|
100
|
+
snapshot (via a manual `snapshot()` or the daemon's auto-suspend) and
|
|
101
|
+
what its new id is.
|
|
102
|
+
- `Image.register(id, path, base_url=None, auth_token=None)` — registers
|
|
103
|
+
an already-built ext4 rootfs file at `path` on the daemon's own host
|
|
104
|
+
filesystem under `id`, for `Sandbox.create(image_id=...)` to boot from.
|
|
105
|
+
Not a file upload — the daemon can't verify the guest agent is baked
|
|
106
|
+
in without root access to loop-mount it (`ImageInfo.guest_agent_verified`
|
|
107
|
+
is always `False`); run `scripts/preflight-check.sh --root-checks
|
|
108
|
+
--rootfs-image <path>` out of band first.
|
|
109
|
+
- `Image.list(base_url=None, auth_token=None)` / `Image.delete(id, base_url=None, auth_token=None)`
|
|
110
|
+
— list registered images, or delete one (refused with 409 while any
|
|
111
|
+
live sandbox, in-flight boot, or held snapshot still references it).
|
|
112
|
+
|
|
113
|
+
This mirrors the [JS/TS SDK](https://www.npmjs.com/package/sandkiln)
|
|
114
|
+
exactly — same daemon, same operations, Python-idiomatic naming
|
|
115
|
+
(`run_command` not `runCommand`, snake_case fields).
|
|
116
|
+
|
|
117
|
+
## Status
|
|
118
|
+
|
|
119
|
+
This SDK matches the daemon's current HTTP API exactly — no more, no
|
|
120
|
+
less. Still open: publishing to PyPI, streamed command output, and
|
|
121
|
+
attaching persistent drives at create time (supported by the daemon and
|
|
122
|
+
CLI, not yet exposed here); see the
|
|
123
|
+
[roadmap](https://github.com/SumitKumar-17/sandkiln/blob/main/ROADMAP.md).
|
|
124
|
+
|
|
125
|
+
## License
|
|
126
|
+
|
|
127
|
+
MIT
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sandkiln"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Client SDK for sandkiln: hardware-isolated Firecracker microVM sandboxes for running untrusted code."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
authors = [{ name = "Sumit Kumar" }]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
dependencies = []
|
|
14
|
+
keywords = ["sandbox", "firecracker", "microvm", "isolation", "untrusted-code", "vm"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"License :: OSI Approved :: MIT License",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
19
|
+
"Topic :: Software Development :: Libraries",
|
|
20
|
+
"Typing :: Typed",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Homepage = "https://github.com/SumitKumar-17/sandkiln"
|
|
25
|
+
Repository = "https://github.com/SumitKumar-17/sandkiln"
|
|
26
|
+
Issues = "https://github.com/SumitKumar-17/sandkiln/issues"
|
|
27
|
+
|
|
28
|
+
[tool.hatch.build.targets.wheel]
|
|
29
|
+
packages = ["src/sandkiln"]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from .drive import Drive, DriveHolder, DriveInfo
|
|
2
|
+
from .errors import SandkilnApiError
|
|
3
|
+
from .image import Image, ImageInfo
|
|
4
|
+
from .pool import Pool, PoolInfo
|
|
5
|
+
from .sandbox import DirEntry, DriveAttachment, ExecResult, Sandbox, SandboxInfo, SnapshotInfo, StopResult
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Sandbox",
|
|
9
|
+
"SandboxInfo",
|
|
10
|
+
"SnapshotInfo",
|
|
11
|
+
"ExecResult",
|
|
12
|
+
"StopResult",
|
|
13
|
+
"DirEntry",
|
|
14
|
+
"DriveAttachment",
|
|
15
|
+
"Image",
|
|
16
|
+
"ImageInfo",
|
|
17
|
+
"Drive",
|
|
18
|
+
"DriveInfo",
|
|
19
|
+
"DriveHolder",
|
|
20
|
+
"Pool",
|
|
21
|
+
"PoolInfo",
|
|
22
|
+
"SandkilnApiError",
|
|
23
|
+
]
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
_DEFAULT_BASE_URL = "http://127.0.0.1:7777"
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def resolve_base_url(base_url: str | None = None) -> str:
|
|
9
|
+
chosen = base_url or os.environ.get("SANDKILN_DAEMON_URL") or _DEFAULT_BASE_URL
|
|
10
|
+
return chosen.rstrip("/")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def resolve_auth_token(auth_token: str | None = None) -> str | None:
|
|
14
|
+
return auth_token or os.environ.get("SANDKILN_AUTH_TOKEN")
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import urllib.error
|
|
5
|
+
import urllib.request
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .errors import SandkilnApiError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def request(
|
|
12
|
+
base_url: str,
|
|
13
|
+
method: str,
|
|
14
|
+
path: str,
|
|
15
|
+
auth_token: str | None = None,
|
|
16
|
+
body: Any = None,
|
|
17
|
+
) -> Any:
|
|
18
|
+
headers: dict[str, str] = {}
|
|
19
|
+
data: bytes | None = None
|
|
20
|
+
if body is not None:
|
|
21
|
+
data = json.dumps(body).encode("utf-8")
|
|
22
|
+
headers["Content-Type"] = "application/json"
|
|
23
|
+
if auth_token is not None:
|
|
24
|
+
headers["Authorization"] = f"Bearer {auth_token}"
|
|
25
|
+
|
|
26
|
+
req = urllib.request.Request(f"{base_url}{path}", data=data, headers=headers, method=method)
|
|
27
|
+
try:
|
|
28
|
+
with urllib.request.urlopen(req) as response:
|
|
29
|
+
return _parse_body(response)
|
|
30
|
+
except urllib.error.HTTPError as error:
|
|
31
|
+
raise SandkilnApiError(error.code, _extract_error_message(error)) from None
|
|
32
|
+
except urllib.error.URLError as error:
|
|
33
|
+
raise SandkilnApiError(0, f"could not reach {base_url}: {error.reason}") from None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _parse_body(response: Any) -> Any:
|
|
37
|
+
raw = response.read()
|
|
38
|
+
if not raw:
|
|
39
|
+
return None
|
|
40
|
+
return json.loads(raw)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _extract_error_message(error: urllib.error.HTTPError) -> str:
|
|
44
|
+
try:
|
|
45
|
+
body = json.loads(error.read())
|
|
46
|
+
if isinstance(body, dict) and isinstance(body.get("error"), str):
|
|
47
|
+
return body["error"]
|
|
48
|
+
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
49
|
+
pass
|
|
50
|
+
return error.reason or f"request failed with status {error.code}"
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
|
|
6
|
+
from ._config import resolve_auth_token, resolve_base_url
|
|
7
|
+
from ._http import request
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class DriveHolder:
|
|
12
|
+
"""Who currently holds a drive - `"sandbox <id>"` or
|
|
13
|
+
`"snapshot <id>"`. More than one holder means it's attached read-only
|
|
14
|
+
to several at once; a drive can't be deleted while any exist."""
|
|
15
|
+
|
|
16
|
+
holder: str
|
|
17
|
+
read_only: bool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class DriveInfo:
|
|
22
|
+
id: str
|
|
23
|
+
size_mib: int
|
|
24
|
+
created_at: datetime
|
|
25
|
+
attached_to: list[DriveHolder] = field(default_factory=list)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Drive:
|
|
29
|
+
"""Persistent drives: attachable filesystem storage that outlives any
|
|
30
|
+
single sandbox and can be reattached to a new one - for state that
|
|
31
|
+
should survive well past any one VM's lifetime. Attach one at create
|
|
32
|
+
time via `Sandbox.create`'s `drives` argument. Like `Image`, a
|
|
33
|
+
namespace of classmethods rather than a stateful handle - a drive has
|
|
34
|
+
no instance behavior besides delete.
|
|
35
|
+
|
|
36
|
+
A drive has no "detach" call of its own: detaching happens implicitly
|
|
37
|
+
when the sandbox holding it is stopped (`Sandbox.stop`), which drops
|
|
38
|
+
the attachment without touching the drive's backing file.
|
|
39
|
+
`Drive.delete` permanently destroys a drive and raises (409) while
|
|
40
|
+
anything still holds it.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def create(cls, size_mib: int, base_url: str | None = None, auth_token: str | None = None) -> DriveInfo:
|
|
45
|
+
"""Creates a new empty drive of `size_mib` MiB, ready to attach to
|
|
46
|
+
a sandbox at create time."""
|
|
47
|
+
resolved_base_url = resolve_base_url(base_url)
|
|
48
|
+
resolved_token = resolve_auth_token(auth_token)
|
|
49
|
+
response = request(resolved_base_url, "POST", "/drives", resolved_token, {"size_mib": size_mib})
|
|
50
|
+
return _to_drive_info(response)
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def list(cls, base_url: str | None = None, auth_token: str | None = None) -> list[DriveInfo]:
|
|
54
|
+
resolved_base_url = resolve_base_url(base_url)
|
|
55
|
+
resolved_token = resolve_auth_token(auth_token)
|
|
56
|
+
response = request(resolved_base_url, "GET", "/drives", resolved_token)
|
|
57
|
+
return [_to_drive_info(summary) for summary in response["drives"]]
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def delete(cls, id: str, base_url: str | None = None, auth_token: str | None = None) -> None:
|
|
61
|
+
"""Permanently removes a drive and its backing file. Raises
|
|
62
|
+
`SandkilnApiError` with status 409 while any sandbox or held
|
|
63
|
+
snapshot still attaches it - see `DriveInfo.attached_to`."""
|
|
64
|
+
resolved_base_url = resolve_base_url(base_url)
|
|
65
|
+
resolved_token = resolve_auth_token(auth_token)
|
|
66
|
+
request(resolved_base_url, "DELETE", f"/drives/{id}", resolved_token)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _to_drive_info(summary: dict) -> DriveInfo:
|
|
70
|
+
return DriveInfo(
|
|
71
|
+
id=summary["id"],
|
|
72
|
+
size_mib=summary["size_mib"],
|
|
73
|
+
created_at=datetime.fromtimestamp(summary["created_at_unix"], tz=timezone.utc),
|
|
74
|
+
attached_to=[DriveHolder(holder=h["holder"], read_only=h["read_only"]) for h in summary["attached_to"]],
|
|
75
|
+
)
|