Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/plan9/ns/v1"
gno = "0.9"

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 914348
  max_deposit = "14000000ugnot"

ns.gno

// Package ns is a Plan 9 namespace server for gno.land.
//
// Every account gets a private, persistent namespace: its own RAM root plus a
// mount table it alone controls. Realms publish file trees into /srv, accounts
// bind those trees wherever they like, and a read-only rc shell renders the
// whole thing in gnoweb.
//
// This is the part of Plan 9 that gno does not otherwise have. The chain has a
// single global tree of realm paths that looks the same to everybody; here a
// name means what YOU bound it to. Composing two realms that were never
// written to work together stops being a redeploy and becomes a transaction:
//
//	gnokey maketx call -pkgpath gno.land/r/moul/x/plan9/ns/v1 -func Exec \
//	  -args 'bind -ac /srv/dev /dev; echo hello > /tmp/greeting'
//
// SECURITY. Mounted trees are READ-ONLY by construction: ninep.File has no
// mutating method, so grafting a foreign realm's tree into your namespace
// cannot be turned into a write against that realm. Writes only ever reach a
// memfs tree this realm created for you. A crossing write method would mint
// THIS realm's frame for the callee, which is the confused-deputy shape that
// r/gov/dao's Executor relies on deliberately and p/nt/grc20's Teller refuses
// deliberately; it is out of scope for v0. See moul/gno-contracts#136.
//
// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research
// Center at Bell Labs; the name and the marks are theirs, and the copyright is
// held by the Plan 9 Foundation (https://p9f.org). This realm is not
// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9
// code: it borrows the vocabulary so that the design reads without a glossary,
// and it is an homage, asking what that ecosystem's spirit looks like on a
// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.
package ns

import (
	"chain/runtime"
	"errors"
	"strconv"
	"strings"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/kit/ui/v0"
	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/md/v0"
	"gno.land/p/nt/avl/v0"

	"gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/realmpath/v0"

	memfs "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/plan9/memfs/v0"
	ninep "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/plan9/ninep/v0"
	nspkg "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/plan9/ns/v0"
	rc "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/plan9/rc/v0"
)

// DemoKey names the namespace gnoweb browses when no ?u= is given. It is a
// plain string rather than an address so it can never collide with one.
const DemoKey = "demo"

// The bounds on what callers can create. Any realm may Post a service and any
// account gets a namespace on its first Exec; the home page lists both.
const (
	MaxServices   = 64
	MaxNamespaces = 1000
	HomeRecent    = 50 // namespaces the home page lists
)

type service struct {
	file  ninep.File
	owner string  // pkgpath of the realm that posted it
	addr  address // that realm's address
	since int64   // block height of the posting
}

type space struct {
	fs *memfs.FS
	ns *nspkg.Ns
}

var (
	services = avl.NewTree() // name -> *service
	spaces   = avl.NewTree() // address string (or DemoKey) -> *space
)

func init() {
	seedDemo()
}

// ---------------------------------------------------------------- /srv

// srvDir is the synthetic directory that makes posted services reachable by
// name. It is written out by hand rather than built with synfs because its
// contents change as realms post, and because implementing ninep.File
// directly is meant to look easy: four methods, no state of its own.
type srvDir struct{}

func (d *srvDir) Stat() ninep.Stat {
	return ninep.Stat{
		Qid:   ninep.Qid{Type: ninep.QTDIR, Path: 1},
		Mode:  ninep.DMDIR | 0555,
		Mtime: runtime.ChainHeight(),
		Name:  "srv",
		Uid:   "sys",
		Gid:   "sys",
		Muid:  "sys",
	}
}

func (d *srvDir) Walk(name string) (ninep.File, error) {
	if !ninep.ValidName(name) {
		return nil, ninep.ErrBadName
	}
	v := services.Get(name)
	if v == nil {
		return nil, ninep.ErrNotExist
	}
	return v.(*service).file, nil
}

func (d *srvDir) Read(off, count int64) (string, error) { return "", ninep.ErrIsDir }

func (d *srvDir) ReadDir() ([]ninep.Stat, error) {
	out := []ninep.Stat{}
	services.Iterate("", "", func(k string, v any) bool {
		st := v.(*service).file.Stat()
		st.Name = k // the posted name, not whatever the server calls its root
		out = append(out, st)
		return false
	})
	return out, nil
}

var srvRoot = &srvDir{}

// ---------------------------------------------------------------- posting

// Post publishes a file tree under name in /srv, where any account can bind
// it. The posting realm is recorded and is the only one that may Unpost.
//
// Names are first come, first served, which is fine for an experiment and
// would not be for anything else.
func Post(cur realm, name string, f ninep.File) {
	if !cur.IsCurrent() {
		panic("post: cur is not the caller's live realm")
	}
	if !ninep.ValidName(name) {
		panic("post: " + ninep.ErrBadName.Error())
	}
	if f == nil {
		panic("post: nil file server")
	}
	prev := cur.Previous()
	if services.Get(name) == nil && services.Size() >= MaxServices {
		panic("post: /srv is full at " + strconv.Itoa(MaxServices) + " services")
	}
	if existing := services.Get(name); existing != nil {
		if existing.(*service).owner != prev.PkgPath() {
			panic("post: " + name + " is already posted by " + existing.(*service).owner)
		}
	}
	services.Set(name, &service{
		file:  f,
		owner: prev.PkgPath(),
		addr:  prev.Address(),
		since: runtime.ChainHeight(),
	})
}

// Unpost withdraws a service. Only the realm that posted it may do so.
func Unpost(cur realm, name string) {
	if !cur.IsCurrent() {
		panic("unpost: cur is not the caller's live realm")
	}
	v := services.Get(name)
	if v == nil {
		panic("unpost: " + ninep.ErrNotExist.Error())
	}
	if v.(*service).owner != cur.Previous().PkgPath() {
		panic("unpost: " + name + " belongs to " + v.(*service).owner)
	}
	services.Remove(name)
}

// Services lists the posted service names, in order.
func Services() []string {
	out := []string{}
	services.Iterate("", "", func(k string, _ any) bool {
		out = append(out, k)
		return false
	})
	return out
}

// ---------------------------------------------------------------- namespaces

// newSpace builds the default namespace, which is this chain's /lib/namespace:
// a private ram root, the mount points that Plan 9 requires to exist before
// anything can be bound onto them, /srv mounted, and /dev bound from it when a
// device server has been posted.
func newSpace(owner string) *space {
	now := runtime.ChainHeight()
	fs := memfs.New(owner, now)
	fs.MkdirAll("/srv", now)
	fs.MkdirAll("/dev", now)
	fs.MkdirAll("/tmp", now)

	n := nspkg.New(fs.Root())
	n.Mount(srvRoot, "#s", "/srv", nspkg.MREPL)
	if services.Has("dev") {
		n.Bind("/srv/dev", "/dev", nspkg.MREPL)
	}
	return &space{fs: fs, ns: n}
}

func spaceFor(key string) *space {
	if v := spaces.Get(key); v != nil {
		return v.(*space)
	}
	if spaces.Size() >= MaxNamespaces {
		panic("ns: full at " + strconv.Itoa(MaxNamespaces) + " namespaces")
	}
	sp := newSpace(key)
	spaces.Set(key, sp)
	return sp
}

func peek(key string) *space {
	if v := spaces.Get(key); v != nil {
		return v.(*space)
	}
	return nil
}

// seedDemo builds the namespace gnoweb shows by default. It is deliberately
// reproducible: an example test resets it before rendering.
func seedDemo() {
	spaces.Remove(DemoKey)
	sp := spaceFor(DemoKey)
	now := runtime.ChainHeight()
	sp.fs.WriteFile("/tmp/greeting", "hello from a namespace\n", now)
	sp.fs.MkdirAll("/usr/glenda/bin", now)
	sp.fs.WriteFile("/usr/glenda/bin/rc", "#!/bin/rc\n", now)
	sp.fs.MkdirAll("/bin", now)
	sp.fs.WriteFile("/bin/ls", "system ls\n", now)
	sp.ns.Bind("/usr/glenda/bin", "/bin", nspkg.MAFTER|nspkg.MCREATE)
	sp.ns.Cd("/usr/glenda")
}

// ResetDemo rebuilds the demo namespace. Anyone may call it: it is a demo, and
// the alternative is a demo that the first visitor ruins for everybody.
func ResetDemo(cur realm) {
	if !cur.IsCurrent() {
		panic("resetdemo: cur is not the caller's live realm")
	}
	seedDemo()
}

// ---------------------------------------------------------------- shell

// Exec runs a command line against the CALLER's namespace and returns its
// output. The namespace belongs to cur.Previous().Address(), so a user gets
// theirs and a realm gets its own.
//
// An error panics, so a half-applied command line reverts with the
// transaction rather than leaving a namespace nobody asked for.
func Exec(cur realm, line string) string {
	if !cur.IsCurrent() {
		panic("exec: cur is not the caller's live realm")
	}
	key := cur.Previous().Address().String()
	sp := spaceFor(key)
	sh := rc.New(sp.ns, rc.ReadWrite, runtime.ChainHeight)
	out, err := sh.Run(line)
	if err != nil {
		panic(err.Error())
	}
	return out
}

// Reset discards the caller's namespace, so the next use rebuilds the default.
func Reset(cur realm) {
	if !cur.IsCurrent() {
		panic("reset: cur is not the caller's live realm")
	}
	spaces.Remove(cur.Previous().Address().String())
}

// Run executes a READ-ONLY command line against key's namespace. It is the
// query side of Exec: no transaction, no writes, safe from Render.
func Run(key, line string) (string, error) {
	sp := peek(key)
	if sp == nil {
		return "", errors.New("no namespace for " + key)
	}
	sh := rc.New(sp.ns, rc.ReadOnly, runtime.ChainHeight)
	return sh.Run(line)
}

// Namespace returns key's mount table, in ns(1) format.
func Namespace(key string) string {
	sp := peek(key)
	if sp == nil {
		return ""
	}
	return sp.ns.String()
}

// Keys lists the namespaces that exist, in order.
func Keys() []string {
	out := []string{}
	spaces.Iterate("", "", func(k string, _ any) bool {
		out = append(out, k)
		return false
	})
	return out
}

// ---------------------------------------------------------------- render

// Render browses a namespace.
//
//	Render("")                  overview, posted services, how to drive it
//	Render("ns?u=<key>")        the mount table
//	Render("ls/bin?u=<key>")    a directory listing (ls -l)
//	Render("cat/tmp/greeting")  a file
//	Render("stat/bin")          the 9P stat, with the union width
//	Render("walk/bin/rc")       how each element of a path resolves
//	Render("rc?c=<command>")    any read-only rc command line
//
// ?u= selects the namespace; it defaults to the demo one.
func Render(path string) string {
	req := realmpath.Parse(path)
	key := req.Query.Get("u")
	if key == "" {
		key = DemoKey
	}
	// A namespace is keyed by the address that created it, or is the demo one.
	// Anything else names no namespace, and refusing it here is also what keeps
	// a crafted ?u= out of the links and code spans every page builds from it.
	if key != DemoKey && !address(key).IsValid() {
		return "# 404\n\nno namespace by that name. `?u=` takes an address.\n"
	}
	parts := req.PathParts()
	if len(parts) == 0 || parts[0] == "" {
		return renderHome(key)
	}

	cmd := parts[0]
	rest := "/" + strings.Join(parts[1:], "/")
	var line string
	switch cmd {
	case "ns":
		return renderCmd(key, "ns", "ns")
	case "ls":
		line = "ls -l " + quote(rest)
	case "cat":
		line = "cat " + quote(rest)
	case "stat":
		line = "stat " + quote(rest)
	case "walk":
		line = "walk " + quote(rest)
	case "rc":
		line = req.Query.Get("c")
		if line == "" {
			line = "help"
		}
	default:
		return "# 404\n\nunknown command " + md.InlineCode(cmd) + ". Try `ls`, `cat`, `stat`, `walk`, `ns` or `rc?c=...`.\n"
	}
	return renderCmd(key, line, cmd+" "+rest)
}

func renderCmd(key, line, title string) string {
	var b strings.Builder
	b.WriteString("# " + ui.Inline(title) + "\n\n")
	//gnovet:ignore render-path-in-code-span key is checked against address(key).IsValid() at the top of Render
	b.WriteString("namespace: `" + key + "`\n\n")
	out, err := Run(key, line)
	if err != nil {
		b.WriteString(md.CodeBlock(err.Error()))
	} else if out == "" {
		b.WriteString("_(no output)_\n")
	} else {
		// The output is a user's file contents: a line of backticks in it
		// would close a hand-written fence, and md.CodeBlock picks one it cannot.
		b.WriteString(md.CodeBlock(strings.TrimSuffix(out, "\n")))
	}
	b.WriteString("\n[namespace](/r/moul/x/plan9/ns/v1:ns?u=" + key + ") · [root](/r/moul/x/plan9/ns/v1:ls?u=" + key +
		") · [home](/r/moul/x/plan9/ns/v1)\n")
	return b.String()
}

func renderHome(key string) string {
	var b strings.Builder
	b.WriteString("# plan9: namespaces for gno\n\n")
	b.WriteString("A Plan 9 namespace server. Every account owns a private mount table over ")
	b.WriteString("[9P-shaped](https://9p.io/sys/doc/9.html) file trees: realms post trees ")
	b.WriteString("into `/srv`, you `bind` them where you want them, and a name means what ")
	b.WriteString("*you* bound it to.\n\n")

	b.WriteString("## /srv\n\n")
	if services.Size() == 0 {
		b.WriteString("_No service is posted yet._\n\n")
	} else {
		b.WriteString("| name | posted by | since |\n|---|---|---|\n")
		services.Iterate("", "", func(k string, v any) bool {
			s := v.(*service)
			//gnovet:ignore render-path-in-code-span owner is the creating caller address, recorded by the realm, not a path
			b.WriteString("| " + ui.Cell(k) + " | [`" + s.owner + "`](" +
				strings.TrimPrefix(s.owner, "gno.land") + ") | " +
				strconv.FormatInt(s.since, 10) + " |\n")
			return false
		})
		b.WriteString("\n")
	}

	b.WriteString("## The demo namespace\n\n")
	b.WriteString(md.CodeBlock(strings.TrimSuffix(Namespace(DemoKey), "\n")) + "\n")
	b.WriteString("`/bin` is a union: the system `/bin` first, then `/usr/glenda/bin`, ")
	b.WriteString("with `-c` so new files land in the second. Listing it shows both members ")
	b.WriteString("because a Plan 9 union is a concatenation, so shadowing stays visible.\n\n")
	b.WriteString("- [ns](/r/moul/x/plan9/ns/v1:ns) · [ls /](/r/moul/x/plan9/ns/v1:ls) · [ls /bin](/r/moul/x/plan9/ns/v1:ls/bin) · ")
	b.WriteString("[cat /tmp/greeting](/r/moul/x/plan9/ns/v1:cat/tmp/greeting) · [walk /bin/rc](/r/moul/x/plan9/ns/v1:walk/bin/rc)\n")
	b.WriteString("- any read-only command: [`rc?c=ls -l /srv`](/r/moul/x/plan9/ns/v1:rc?c=ls%20-l%20/srv)\n\n")

	b.WriteString("## Your own namespace\n\n")
	b.WriteString("```\n")
	b.WriteString("gnokey maketx call -pkgpath gno.land/r/moul/x/plan9/ns/v1 \\\n")
	b.WriteString("  -func Exec -args 'bind -ac /srv/dev /dev; echo hi > /tmp/f'\n")
	b.WriteString("```\n\n")
	b.WriteString("Then browse it with `?u=<your address>`. `Reset` throws it away.\n\n")

	b.WriteString("## Namespaces\n\n")
	keys := Keys()
	if len(keys) > HomeRecent {
		b.WriteString(strconv.Itoa(len(keys)) + " namespaces, the first " + strconv.Itoa(HomeRecent) + " listed.\n\n")
		keys = keys[:HomeRecent]
	}
	for _, k := range keys {
		b.WriteString("- [`" + k + "`](/r/moul/x/plan9/ns/v1:ns?u=" + k + ")\n")
	}
	b.WriteString("\nDesign and analysis: ")
	b.WriteString("[moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).\n")
	b.WriteString("\n_Not affiliated with Plan 9. Plan 9 from Bell Labs is the ")
	b.WriteString("work of the Computing Science Research Center at Bell Labs; the name ")
	b.WriteString("and the marks are theirs, and the copyright is held by the ")
	b.WriteString("[Plan 9 Foundation](https://p9f.org). This realm borrows the ")
	b.WriteString("vocabulary and none of the code: it is an homage, asking what that ")
	b.WriteString("ecosystem's spirit looks like on a chain._\n")
	return b.String()
}

// quote wraps a path for rc if it needs it.
func quote(s string) string {
	// Always quoted: the path comes from the URL, and a route like
	// cat/tmp/f;echo must read one file, not run a second command. The shell
	// is read-only either way, but a path is data.
	return "'" + strings.ReplaceAll(s, "'", "''") + "'"
}

ns_test.gno

package ns

import (
	"strconv"
	"strings"
	"testing"

	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"

	ninep "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/plan9/ninep/v0"
	synfs "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/plan9/synfs/v0"
)

// probe is a tiny read-only server, standing in for another realm's tree.
func probe(name, contents string) ninep.File {
	t := synfs.New(name, "sys", func() int64 { return 1 })
	t.Root().Add("value", func() string { return contents })
	return t.Root()
}

func TestDemoNamespaceIsSeeded(t *testing.T) {
	seedDemo()
	out, err := Run(DemoKey, "ls -u /bin")
	if err != nil {
		t.Fatalf("ls: %v", err)
	}
	if out != "ls\nrc\n" {
		t.Errorf("the demo /bin should be a union of two directories: %q", out)
	}
	if got := Namespace(DemoKey); !strings.Contains(got, "bind -ac /usr/glenda/bin /bin") {
		t.Errorf("mount table: %q", got)
	}
	if got, _ := Run(DemoKey, "cat /tmp/greeting"); got != "hello from a namespace\n" {
		t.Errorf("greeting: %q", got)
	}
}

func TestRunIsReadOnly(t *testing.T) {
	seedDemo()
	if _, err := Run(DemoKey, "echo x > /tmp/f"); err == nil {
		t.Fatal("Render's shell must refuse a write")
	}
	if _, err := Run(DemoKey, "rm /tmp/greeting"); err == nil {
		t.Fatal("Render's shell must refuse a remove")
	}
	if _, err := Run("nobody", "ls /"); err == nil {
		t.Fatal("an unknown namespace should not be created by a read")
	}
}

func TestPostAndBind(cur realm, t *testing.T) {
	services.Remove("probe")
	Post(cross(cur), "probe", probe("probe", "42"))

	found := false
	for _, s := range Services() {
		if s == "probe" {
			found = true
		}
	}
	if !found {
		t.Fatalf("probe is not in /srv: %v", Services())
	}

	// A fresh namespace sees it through /srv without importing anything.
	spaces.Remove("tester")
	spaceFor("tester")
	defer spaces.Remove("tester")
	out, err := Run("tester", "cat /srv/probe/value")
	if err != nil {
		t.Fatalf("cat through /srv: %v", err)
	}
	if out != "42" {
		t.Errorf("got %q, want 42", out)
	}
	services.Remove("probe")
}

func TestExecWritesToTheCallersOwnNamespace(cur realm, t *testing.T) {
	alice := testutils.TestAddress("alice")
	bob := testutils.TestAddress("bob")
	spaces.Remove(alice.String())
	spaces.Remove(bob.String())

	testing.SetRealm(testing.NewUserRealm(alice))
	Exec(cross(cur), "echo 'alice was here' > /tmp/note")

	testing.SetRealm(testing.NewUserRealm(bob))
	Exec(cross(cur), "echo 'bob was here' > /tmp/note")

	got, err := Run(alice.String(), "cat /tmp/note")
	if err != nil {
		t.Fatalf("alice: %v", err)
	}
	if got != "alice was here\n" {
		t.Errorf("alice's namespace: %q", got)
	}
	if got, _ = Run(bob.String(), "cat /tmp/note"); got != "bob was here\n" {
		t.Errorf("bob's namespace: %q", got)
	}

	// Reset throws a namespace away; the next use rebuilds the default.
	testing.SetRealm(testing.NewUserRealm(alice))
	Reset(cross(cur))
	if _, err := Run(alice.String(), "cat /tmp/note"); err == nil {
		t.Error("the namespace should be gone after Reset")
	}
	spaces.Remove(alice.String())
	spaces.Remove(bob.String())
}

func TestExecBindsIntoTheCallersNamespace(cur realm, t *testing.T) {
	services.Remove("probe")
	Post(cross(cur), "probe", probe("probe", "42"))
	defer services.Remove("probe")

	erin := testutils.TestAddress("erin")
	spaces.Remove(erin.String())
	testing.SetRealm(testing.NewUserRealm(erin))
	Exec(cross(cur), "bind /srv/probe /dev")

	if got := mustRun(t, erin.String(), "cat /dev/value"); got != "42" {
		t.Errorf("read through the mount: %q", got)
	}
	if ns := Namespace(erin.String()); !strings.Contains(ns, "bind /srv/probe /dev") {
		t.Errorf("mount table: %q", ns)
	}
	spaces.Remove(erin.String())
}

func TestSrvListingUsesThePostedName(cur realm, t *testing.T) {
	services.Remove("aliased")
	// The server calls its own root "probe"; /srv must show it as "aliased".
	Post(cross(cur), "aliased", probe("probe", "x"))
	defer services.Remove("aliased")

	spaces.Remove("lister")
	spaceFor("lister")
	out := mustRun(t, "lister", "ls /srv")
	if !strings.Contains(out, "aliased") {
		t.Errorf("ls /srv: %q", out)
	}
	if strings.Contains(out, "probe") {
		t.Errorf("/srv leaked the server's own root name: %q", out)
	}
	spaces.Remove("lister")
}

func mustRun(t *testing.T, key, line string) string {
	t.Helper()
	out, err := Run(key, line)
	if err != nil {
		t.Fatalf("%s: %v", line, err)
	}
	return out
}

// --- the boundary. Three properties the suite would be unsafe without. -------

// A /srv name belongs to the realm that posted it: first come, first served,
// and then locked.
func TestPostRejectsASecondOwner(cur realm, t *testing.T) {
	services.Remove("taken")
	Post(cross(cur), "taken", probe("taken", "first"))
	defer services.Remove("taken")

	testing.SetRealm(testing.NewCodeRealm("gno.land/r/other/thing/v0"))
	uassert.AbortsWithMessage(t, cur,
		"post: taken is already posted by gno.land/r/moul/x/plan9/ns/v1",
		func() { Post(cross(cur), "taken", probe("taken", "second")) })
}

// Grafting another realm's tree into your namespace gives you reads and
// nothing else. ninep.File has no mutating method, so there is no route from a
// mount to a write against the realm that posted it.
func TestMountedTreesAreReadOnly(cur realm, t *testing.T) {
	services.Remove("probe")
	Post(cross(cur), "probe", probe("probe", "read me"))
	defer services.Remove("probe")

	frank := testutils.TestAddress("frank")
	spaces.Remove(frank.String())
	defer spaces.Remove(frank.String())

	testing.SetRealm(testing.NewUserRealm(frank))
	Exec(cross(cur), "bind /srv/probe /dev")
	uassert.Equal(t, "read me", mustRun(t, frank.String(), "cat /dev/value"))
	uassert.AbortsWithMessage(t, cur, "echo: read-only file server",
		func() { Exec(cross(cur), "echo nope > /dev/value") })
}

// A command line stops at the first error and the error leaves the realm as an
// abort, so a half-applied Exec reverts with its transaction instead of
// leaving a namespace nobody asked for.
func TestExecAbortsAtTheFirstError(cur realm, t *testing.T) {
	grace := testutils.TestAddress("grace")
	spaces.Remove(grace.String())
	defer spaces.Remove(grace.String())

	testing.SetRealm(testing.NewUserRealm(grace))
	uassert.AbortsWithMessage(t, cur, "cat: file does not exist",
		func() { Exec(cross(cur), "echo ok > /tmp/a; cat /absent; echo never > /tmp/b") })
}

func TestRenderUnknownCommand(t *testing.T) {
	if got := Render("nope/x"); !strings.Contains(got, "404") {
		t.Errorf("got %q", got)
	}
}

// ?u= is the only caller-controlled part of every link the pages build, so a
// value that is neither an address nor the demo key is refused outright.
func TestRenderRefusesANonAddressNamespace(t *testing.T) {
	out := Render("ns?u=x%29%20[evil](https://example)")
	uassert.True(t, strings.Contains(out, "# 404"), out)
	uassert.False(t, strings.Contains(out, "[evil](https://example)"), out)
}

// A file's contents are its owner's text. A line of backticks in one used to
// close the hand-written fence around `cat`'s output, and everything after it
// rendered as live markdown on the realm's own page.
func TestCatOutputCannotCloseItsFence(cur realm, t *testing.T) {
	who := testutils.TestAddress("fencer")
	testing.SetRealm(testing.NewUserRealm(who))
	Exec(cross(cur), "echo '```' > /tmp/f; echo '[claim](https://evil.example)' >> /tmp/f")
	out := Render("cat/tmp/f?u=" + who.String())
	// md.CodeBlock picks a fence longer than any run of backticks inside, so
	// the user's three backticks and the link after them stay inside the block.
	uassert.True(t, strings.Contains(out, "````\n```\n[claim](https://evil.example)\n````\n"), out)
}

// The command name and the rest of the path come from the URL: escaped in the
// heading and in the unknown-command page.
func TestPathDerivedTextIsEscaped(t *testing.T) {
	for _, path := range []string{"x` [claim](https://evil.example) `", "cat/x` [claim](https://evil.example) `"} {
		out := Render(path)
		uassert.False(t, strings.Contains(out, "[claim](https://evil.example)"), out)
	}
}

// A service name is chosen by whichever realm posts it, and ValidName refuses
// only "", ".", ".." and "/": the /srv table escapes it as a cell.
func TestServiceNameIsTableSafe(cur realm, t *testing.T) {
	name := "x` | [claim](https://evil.example) |"
	services.Set(name, &service{owner: "gno.land/r/someone/poster"})
	defer services.Remove(name)
	out := Render("")
	uassert.False(t, strings.Contains(out, "[claim](https://evil.example)"), out)
}

// A path route reads what it names: the rest of the path is one quoted
// argument, so a ";" in it is part of the file name and runs nothing.
func TestPathRouteIsOneArgument(t *testing.T) {
	// Unquoted, rc would cat /tmp/greeting and then run the second command;
	// quoted, it looks for one file with a ";" in its name and finds none.
	out := Render("cat/tmp/greeting;echo")
	uassert.True(t, strings.Contains(out, "cat: file does not exist"), out)
	uassert.Equal(t, "'/a;b'", quote("/a;b"))
}

// Namespaces and services are bounded, and the home page lists a fixed number.
func TestNamespacesAndServicesAreBounded(cur realm, t *testing.T) {
	var added []string
	for i := 0; spaces.Size() < MaxNamespaces; i++ {
		k := testutils.TestAddress("ns" + strconv.Itoa(i)).String()
		if spaces.Get(k) == nil {
			spaces.Set(k, newSpace(k))
			added = append(added, k)
		}
	}
	defer func() {
		for _, k := range added {
			spaces.Remove(k)
		}
	}()
	uassert.PanicsContains(t, cur, "full at", func() { spaceFor(testutils.TestAddress("one-more").String()) })
	uassert.Equal(t, HomeRecent, strings.Count(Render(""), "](/r/moul/x/plan9/ns/v1:ns?u="))
}

// /srv is bounded: once MaxServices names are posted, a new one is refused,
// and re-posting is not how a realm gets around it.
func TestServicesAreBounded(cur realm, t *testing.T) {
	var added []string
	for i := 0; services.Size() < MaxServices; i++ {
		name := "svc" + strconv.Itoa(i)
		if services.Get(name) == nil {
			services.Set(name, &service{owner: "gno.land/r/someone/poster"})
			added = append(added, name)
		}
	}
	defer func() {
		for _, n := range added {
			services.Remove(n)
		}
	}()
	testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/late"))
	uassert.AbortsContains(t, cur, "/srv is full", func() { Post(cross(cur), "late", probe("late", "x")) })
}

render_example_test.gno

package ns

import "gno.land/p/nt/avl/v0"

// resetForExample rebuilds the whole realm state. Realm globals persist for
// the entire test binary and examples run after every Test, so without this an
// example would pin whatever the last test happened to leave behind.
func resetForExample() {
	services = avl.NewTree()
	spaces = avl.NewTree()
	seedDemo()
}

// ExampleRender pins the realm's front page.
func ExampleRender() {
	resetForExample()
	print(Render(""))
	// Output:
	// # plan9: namespaces for gno
	//
	// A Plan 9 namespace server. Every account owns a private mount table over [9P-shaped](https://9p.io/sys/doc/9.html) file trees: realms post trees into `/srv`, you `bind` them where you want them, and a name means what *you* bound it to.
	//
	// ## /srv
	//
	// _No service is posted yet._
	//
	// ## The demo namespace
	//
	// ```
	// mount #s /srv
	// bind -ac /usr/glenda/bin /bin
	// cd /usr/glenda
	// ```
	//
	// `/bin` is a union: the system `/bin` first, then `/usr/glenda/bin`, with `-c` so new files land in the second. Listing it shows both members because a Plan 9 union is a concatenation, so shadowing stays visible.
	//
	// - [ns](/r/moul/x/plan9/ns/v1:ns) · [ls /](/r/moul/x/plan9/ns/v1:ls) · [ls /bin](/r/moul/x/plan9/ns/v1:ls/bin) · [cat /tmp/greeting](/r/moul/x/plan9/ns/v1:cat/tmp/greeting) · [walk /bin/rc](/r/moul/x/plan9/ns/v1:walk/bin/rc)
	// - any read-only command: [`rc?c=ls -l /srv`](/r/moul/x/plan9/ns/v1:rc?c=ls%20-l%20/srv)
	//
	// ## Your own namespace
	//
	// ```
	// gnokey maketx call -pkgpath gno.land/r/moul/x/plan9/ns/v1 \
	//   -func Exec -args 'bind -ac /srv/dev /dev; echo hi > /tmp/f'
	// ```
	//
	// Then browse it with `?u=<your address>`. `Reset` throws it away.
	//
	// ## Namespaces
	//
	// - [`demo`](/r/moul/x/plan9/ns/v1:ns?u=demo)
	//
	// Design and analysis: [moul/gno-contracts#136](https://github.com/moul/gno-contracts/issues/136).
	//
	// _Not affiliated with Plan 9. Plan 9 from Bell Labs is the work of the Computing Science Research Center at Bell Labs; the name and the marks are theirs, and the copyright is held by the [Plan 9 Foundation](https://p9f.org). This realm borrows the vocabulary and none of the code: it is an homage, asking what that ecosystem's spirit looks like on a chain._
}

// ExampleRender_ls pins a union directory listing.
func ExampleRender_ls() {
	resetForExample()
	print(Render("ls/bin"))
	// Output:
	// # ls /bin
	//
	// namespace: `demo`
	//
	// ```
	// -rw-r--r-- demo         demo          10 ls
	// -rw-r--r-- demo         demo          10 rc
	// ```
	//
	// [namespace](/r/moul/x/plan9/ns/v1:ns?u=demo) · [root](/r/moul/x/plan9/ns/v1:ls?u=demo) · [home](/r/moul/x/plan9/ns/v1)
}

// ExampleRender_walk pins a resolution trace, which is where a bind becomes
// visible: the union column widens exactly at the bound name.
func ExampleRender_walk() {
	resetForExample()
	print(Render("walk/bin/rc"))
	// Output:
	// # walk /bin/rc
	//
	// namespace: `demo`
	//
	// ```
	// /                        (1 5 d) drwxr-xr-x union=1
	// /bin                     (a 1 d) drwxr-xr-x union=2
	// /bin/rc                  (9 1 f) -rw-r--r-- union=1
	// ```
	//
	// [namespace](/r/moul/x/plan9/ns/v1:ns?u=demo) · [root](/r/moul/x/plan9/ns/v1:ls?u=demo) · [home](/r/moul/x/plan9/ns/v1)
}