|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. |
| 3 | +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
| 4 | +# |
| 5 | +# The Universal Permissive License (UPL), Version 1.0 |
| 6 | +# |
| 7 | +# Subject to the condition set forth below, permission is hereby granted to any |
| 8 | +# person obtaining a copy of this software, associated documentation and/or |
| 9 | +# data (collectively the "Software"), free of charge and under any and all |
| 10 | +# copyright rights in the Software, and any and all patent rights owned or |
| 11 | +# freely licensable by each licensor hereunder covering either (i) the |
| 12 | +# unmodified Software as contributed to or provided by such licensor, or (ii) |
| 13 | +# the Larger Works (as defined below), to deal in both |
| 14 | +# |
| 15 | +# (a) the Software, and |
| 16 | +# |
| 17 | +# (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if |
| 18 | +# one is included with the Software each a "Larger Work" to which the Software |
| 19 | +# is contributed by such licensors), |
| 20 | +# |
| 21 | +# without restriction, including without limitation the rights to copy, create |
| 22 | +# derivative works of, display, perform, and distribute the Software and make, |
| 23 | +# use, sell, offer for sale, import, export, have made, and have sold the |
| 24 | +# Software and the Larger Work(s), and to sublicense the foregoing rights on |
| 25 | +# either these or other terms. |
| 26 | +# |
| 27 | +# This license is subject to the following condition: |
| 28 | +# |
| 29 | +# The above copyright notice and either this complete permission notice or at a |
| 30 | +# minimum a reference to the UPL must be included in all copies or substantial |
| 31 | +# portions of the Software. |
| 32 | +# |
| 33 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 34 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 35 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 36 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 37 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 38 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 39 | +# SOFTWARE. |
| 40 | +"""Small Rich demo for the GraalOS standalone sandbox.""" |
| 41 | + |
| 42 | +from __future__ import annotations |
| 43 | + |
| 44 | +import argparse |
| 45 | +import io |
| 46 | +import sysconfig |
| 47 | +import textwrap |
| 48 | +import time |
| 49 | +import unittest |
| 50 | +from dataclasses import dataclass |
| 51 | + |
| 52 | + |
| 53 | +console = None |
| 54 | + |
| 55 | + |
| 56 | +@dataclass |
| 57 | +class EvalResult: |
| 58 | + mode: str |
| 59 | + ok: bool |
| 60 | + output: str |
| 61 | + elapsed_ms: float |
| 62 | +def render_message(role: str, body: str, style: str) -> None: |
| 63 | + from rich.panel import Panel |
| 64 | + from rich.text import Text |
| 65 | + console.print(Panel(Text(body), title=role, title_align="left", border_style=style)) |
| 66 | + |
| 67 | + |
| 68 | +def unsafe_eval(expr: str): |
| 69 | + start = time.perf_counter() |
| 70 | + try: |
| 71 | + value = eval(expr) |
| 72 | + elapsed = (time.perf_counter() - start) * 1000 |
| 73 | + if value == -1: |
| 74 | + return EvalResult("python eval", False, "-1 (operation denied by sandbox/runtime)", elapsed) |
| 75 | + return EvalResult("python eval", True, repr(value), elapsed) |
| 76 | + except Exception as exc: |
| 77 | + elapsed = (time.perf_counter() - start) * 1000 |
| 78 | + return EvalResult("python eval", False, f"{type(exc).__name__}: {exc}", elapsed) |
| 79 | + |
| 80 | + |
| 81 | +def render_result(result) -> None: |
| 82 | + from rich.table import Table |
| 83 | + table = Table.grid(padding=(0, 1)) |
| 84 | + table.add_column(style="bold") |
| 85 | + table.add_column() |
| 86 | + table.add_row("mode", result.mode) |
| 87 | + table.add_row("status", "[green]ok[/green]" if result.ok else "[red]blocked/error[/red]") |
| 88 | + table.add_row("time", f"{result.elapsed_ms:.1f} ms") |
| 89 | + console.print(table) |
| 90 | + render_message("sandbox", result.output, "green" if result.ok else "red") |
| 91 | + |
| 92 | + |
| 93 | +def evaluate(line: str) -> None: |
| 94 | + line = line.strip() |
| 95 | + if not line: |
| 96 | + return |
| 97 | + render_result(unsafe_eval(line)) |
| 98 | + |
| 99 | + |
| 100 | +def demo_script() -> list[str]: |
| 101 | + return [ |
| 102 | + "sum([i*i for i in range(1000)])", |
| 103 | + "sin(pi / 4) ** 2 + cos(pi / 4) ** 2", |
| 104 | + "open('/etc/passwd').read()", |
| 105 | + "open('/etc/passwd').read().splitlines()[:3]", |
| 106 | + "open('/etc/shadow').read()", |
| 107 | + "__import__('subprocess').run(['/bin/sh', '-c', 'id'], capture_output=True, text=True)", |
| 108 | + "__import__('socket').create_connection(('example.com', 80), timeout=2)", |
| 109 | + "__import__('ctypes').CDLL('libc.so').system(b'cat /etc/shadow')", |
| 110 | + ] |
| 111 | + |
| 112 | + |
| 113 | +def print_intro() -> None: |
| 114 | + body = textwrap.dedent( |
| 115 | + """ |
| 116 | + Type Python expressions and get chat-style results. |
| 117 | +
|
| 118 | + This demo treats each expression as untrusted Python code, such as |
| 119 | + code proposed by an LLM agent or pasted by a human operator. |
| 120 | + GraalOS sandboxes that code, so filesystem, subprocess, native |
| 121 | + library, and network attempts remain contained. |
| 122 | +
|
| 123 | + Commands: /demo, /help, /quit |
| 124 | + """ |
| 125 | + ).strip() |
| 126 | + render_message("graalos sandbox chat", body, "cyan") |
| 127 | + |
| 128 | + |
| 129 | +def print_help() -> None: |
| 130 | + examples = "\n".join(demo_script()) |
| 131 | + from rich.syntax import Syntax |
| 132 | + console.print(Syntax(examples, "python", theme="ansi_dark", word_wrap=True)) |
| 133 | + |
| 134 | + |
| 135 | +def interactive() -> int: |
| 136 | + print_intro() |
| 137 | + while True: |
| 138 | + try: |
| 139 | + line = console.input("[bold cyan]you>[/bold cyan] ") |
| 140 | + except (EOFError, KeyboardInterrupt): |
| 141 | + console.print() |
| 142 | + return 0 |
| 143 | + command = line.strip() |
| 144 | + if command in {"/quit", "/exit"}: |
| 145 | + return 0 |
| 146 | + if command == "/help": |
| 147 | + print_help() |
| 148 | + continue |
| 149 | + if command == "/demo": |
| 150 | + run_demo() |
| 151 | + continue |
| 152 | + evaluate(line) |
| 153 | + |
| 154 | + |
| 155 | +def run_demo() -> None: |
| 156 | + for line in demo_script(): |
| 157 | + render_message("you", line, "blue") |
| 158 | + evaluate(line) |
| 159 | + |
| 160 | + |
| 161 | +def main(argv: list[str] | None = None) -> int: |
| 162 | + from rich.console import Console |
| 163 | + global console |
| 164 | + if console is None: |
| 165 | + console = Console() |
| 166 | + parser = argparse.ArgumentParser() |
| 167 | + parser.add_argument("--demo", action="store_true", help="run the prepared demo script and exit") |
| 168 | + args = parser.parse_args(argv) |
| 169 | + |
| 170 | + if args.demo: |
| 171 | + print_intro() |
| 172 | + run_demo() |
| 173 | + return 0 |
| 174 | + return interactive() |
| 175 | + |
| 176 | + |
| 177 | +def skip_unless_graalos(): |
| 178 | + soabi = sysconfig.get_config_var("SOABI") or "" |
| 179 | + if "graalos" not in soabi: |
| 180 | + raise unittest.SkipTest(f"requires GraalOS SOABI, got {soabi!r}") |
| 181 | + |
| 182 | + |
| 183 | +class GraalOSSandboxChatTests(unittest.TestCase): |
| 184 | + |
| 185 | + def setUp(self): |
| 186 | + skip_unless_graalos() |
| 187 | + |
| 188 | + def test_demo_packages(self): |
| 189 | + import rich |
| 190 | + |
| 191 | + self.assertTrue(rich.get_console()) |
| 192 | + |
| 193 | + def test_sandbox_chat_demo(self): |
| 194 | + from rich.console import Console |
| 195 | + global console |
| 196 | + output = io.StringIO() |
| 197 | + console = Console(file=output, force_terminal=False, color_system=None, width=120) |
| 198 | + self.assertEqual(main(["--demo"]), 0) |
| 199 | + stdout = output.getvalue() |
| 200 | + self.assertIn("sum([i*i for i in range(1000)])", stdout) |
| 201 | + self.assertIn("__import__('socket').create_connection", stdout) |
| 202 | + self.assertIn("gaierror", stdout) |
| 203 | + self.assertIn("FileNotFoundError", stdout) |
| 204 | + self.assertIn("operation denied", stdout) |
| 205 | + |
| 206 | + |
| 207 | +if __name__ == "__main__": |
| 208 | + raise SystemExit(main()) |
0 commit comments