Ask HN: How to let users run code on a website, for learning? Like educative?

2 points by akudha ↗ HN
Consider a site that teaches programming, say GoLang or Java. How to let users change the sample code and run it, like educative.io does? Do they have some kind of sandbox environment that runs in the background?

4 comments

[ 2.9 ms ] story [ 7.4 ms ] thread
Yes, there no magic. The code is compiled and run on a server. So the flow is HTML with a textarea, the text from that gets sent via HTTP POST to the server, the server then "shells out" and lets the os run `go build` or `javac` and captures stdout and stderr. It runs the compiled program, also capturing stdout and stderr and returns all that text to the user. It can do this as a result of the original HTTP POST or you could have a like a websocket open and the results come back via that.
Yes, it should set up a sandboxed environment, ideally a VM or a "system container" to avoid compiled program to break out and mess up the main system.

I remember playing with such systems for any of those international programming contests and their local brethren (they could compile a program and compare output for a number of test cases).

how do they make sure the user doesn't things like "rm -rf *" or something?
They don't care: you can use one of the systems with immutable root filesystems (eg. Ubuntu Core, Fedora CoreOS...), and you need to start a system from scratch for every "compilation" (you can optimize and keep the same image for one user: if they mess up the system, so be it).

Back in the day, one used chroot to achieve this, then we started doing VMs, and now it's possible to use "system containers" (eg. with lxd on Ubuntu: regular docker containers leak too much of the parent system into the container). Still, VMs are generally safer because it's harder to break out of the sandbox (eg. a system can be virtualized using different technologies, so finding an exploit in one will not make it vulnerable with another).

Eg. AWS Lambdas are implemented as quick-booting VMs using an optimized Linux image and optimized VM runtime (firecracker): not saying you need to go that far, but it should tell you what's possible.