refactor: clarify service boundaries and unify project tooling

This commit is contained in:
Meghdad committed 2026-10-16 18:46:23 +03:30
1 parent 1ca321e312
commit fda3ea9799
31 files changed
+832 -539

No files matched your search

+2
View File
@@ -16,3 +16,5 @@ Review upstream changes and security issues before updating. Reapply/review each
The initial 16-credit adaptation stalled the native macOS client before mkdir; 128 credits passed the local native smoke check. Credits bound the request window, while the synchronous parser and frame/I/O limits independently bound allocations. Preserve this native-client regression check when tuning credits.
RouterShelf also adds `guarded_root.go` and its tests for explicit disk-root views: protected relative subtrees are hidden/blocked, aliases refused, protected ancestors cannot be renamed/deleted, and parent descriptors are pinned with os.Root. Cross-directory rename and descriptor timestamp operations use BSD-licensed golang.org/x/sys/unix. Default subdirectory shares preserve the original os.Root behavior.
Source organization: RouterShelf-only share/lock helpers live in `access.go` (formerly `routershelf.go`); additional policy tests live in `policy_test.go` (formerly `routershelf_test.go`). Upstream file names and retained tests remain intact. These naming changes do not change the protocol.
File renamed without changes.
File renamed without changes.
+4
View File
@@ -0,0 +1,4 @@
// Package web serves RouterShelf's public, unauthenticated read-only HTTP
// content. Process startup, TLS certificates and deployment policy belong to
// the routershelf command and its optional platform supervisor.
package web
+143
View File
@@ -0,0 +1,143 @@
package web
import (
"bytes"
"io"
"log"
"net/http"
"os"
"path"
"sort"
"strings"
"time"
"routershelf/internal/theme"
)
// Handler serves public read-only content from rootPath, reopening the root
// for each request so removable storage does not retain a stale descriptor.
func Handler(rootPath string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'self'; script-src 'self'; img-src 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'")
w.Header().Set("Referrer-Policy", "no-referrer")
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "Read-only service", 405)
return
}
if strings.HasPrefix(r.URL.Path, "/_nais/") {
name := strings.TrimPrefix(r.URL.Path, "/_nais/")
types := map[string]string{"autoindex.css": "text/css; charset=utf-8", "autoindex.js": "text/javascript; charset=utf-8", "favicon.ico": "image/x-icon", "favicon.png": "image/png"}
contentType, ok := types[name]
if !ok {
http.NotFound(w, r)
return
}
data, err := theme.Files.ReadFile("nais/" + name)
if err != nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", contentType)
w.Header().Set("Cache-Control", "no-cache")
http.ServeContent(w, r, name, time.Time{}, bytes.NewReader(data))
return
}
p := r.URL.Path
if strings.ContainsAny(p, "\\\x00\r\n") {
http.Error(w, "Invalid path", 400)
return
}
for _, part := range strings.Split(p, "/") {
if strings.HasPrefix(part, ".") {
http.NotFound(w, r)
return
}
}
name := strings.TrimPrefix(p, "/")
if name == "" {
name = "."
}
root, err := os.OpenRoot(rootPath)
if err != nil {
http.Error(w, "Storage unavailable", 503)
return
}
defer root.Close()
f, err := root.Open(name)
if err != nil {
http.NotFound(w, r)
return
}
defer f.Close()
info, err := f.Stat()
if err != nil {
http.NotFound(w, r)
return
}
if info.IsDir() {
if !strings.HasSuffix(p, "/") {
http.Redirect(w, r, string(escapedPath(p+"/")), 301)
return
}
index, indexErr := root.Open(path.Join(name, "index.html"))
if indexErr == nil {
defer index.Close()
indexInfo, statErr := index.Stat()
if statErr == nil && indexInfo.Mode().IsRegular() {
serveFile(w, r, "index.html", indexInfo, index)
return
}
}
rows, err := f.ReadDir(5000)
if err != nil && err != io.EOF {
http.Error(w, "Cannot list folder", 500)
return
}
pg := page{Path: p, Truncated: len(rows) == 5000}
if p != "/" {
parent := path.Dir(strings.TrimSuffix(p, "/"))
if parent != "/" {
parent += "/"
}
pg.Parent = escapedPath(parent)
}
for _, row := range rows {
if strings.HasPrefix(row.Name(), ".") {
continue
}
st, err := root.Stat(path.Join(name, row.Name()))
if err != nil || (!st.IsDir() && !st.Mode().IsRegular()) {
continue
}
link := p + row.Name()
label := sizeLabel(st.Size())
if st.IsDir() {
link += "/"
label = "—"
}
pg.Entries = append(pg.Entries, entry{Name: row.Name(), Size: label, Modified: st.ModTime().UTC().Format("2006-01-02 15:04 UTC"), Link: escapedPath(link), Dir: st.IsDir(), Inline: inlineType(row.Name()) != ""})
}
sort.Slice(pg.Entries, func(i, j int) bool {
if pg.Entries[i].Dir != pg.Entries[j].Dir {
return pg.Entries[i].Dir
}
return pg.Entries[i].Name < pg.Entries[j].Name
})
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
if r.Method == http.MethodGet {
if err := listing.Execute(w, pg); err != nil {
log.Print("listing response interrupted")
}
}
return
}
if !info.Mode().IsRegular() {
http.NotFound(w, r)
return
}
serveFile(w, r, name, info, f)
})
}
+105
View File
@@ -0,0 +1,105 @@
package web
import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestFileScopeAndMethods(t *testing.T) {
root := t.TempDir()
os.WriteFile(filepath.Join(root, "test.txt"), []byte("test"), 0600)
os.WriteFile(filepath.Join(root, ".secret"), []byte("secret"), 0600)
outside := filepath.Join(t.TempDir(), "outside")
os.WriteFile(outside, []byte("private"), 0600)
os.Symlink(outside, filepath.Join(root, "escape.txt"))
os.Mkdir(filepath.Join(root, "sub"), 0700)
os.WriteFile(filepath.Join(root, "<&.txt"), []byte("safe"), 0600)
h := Handler(root)
for _, tc := range []struct {
method, url string
code int
body string
}{{"GET", "/", 200, "test.txt"}, {"GET", "/test.txt", 200, "test"}, {"HEAD", "/test.txt", 200, ""}, {"GET", "/.secret", 404, ""}, {"GET", "/../outside", 404, ""}, {"GET", "/%2e%2e/outside", 404, ""}, {"GET", "/escape.txt", 404, ""}, {"GET", "/sub/", 200, "This folder is empty"}, {"PUT", "/new.txt", 405, ""}, {"POST", "/", 405, ""}, {"DELETE", "/test.txt", 405, ""}} {
w := httptest.NewRecorder()
r := httptest.NewRequest(tc.method, tc.url, nil)
h.ServeHTTP(w, r)
if w.Code != tc.code {
t.Fatalf("%s %s: %d", tc.method, tc.url, w.Code)
}
if tc.body != "" && !strings.Contains(w.Body.String(), tc.body) {
t.Fatalf("unexpected response %s", tc.url)
}
if tc.method == "HEAD" && w.Body.Len() != 0 {
t.Fatal("HEAD body")
}
}
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if strings.Contains(w.Body.String(), ".secret") || strings.Contains(w.Body.String(), "escape.txt") {
t.Fatal("private entry listed")
}
if !strings.Contains(w.Body.String(), "&lt;&amp;.txt") {
t.Fatal("filename not escaped")
}
r := httptest.NewRequest("GET", "/test.txt", nil)
r.Header.Set("Range", "bytes=1-2")
w = httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 206 || w.Body.String() != "es" {
t.Fatal("range download failed")
}
}
func TestHTTPSRedirect(t *testing.T) {
h := RedirectHandler("files.example.com")
for _, tc := range []struct {
target, method string
status int
location string
}{
{"http://files.example.com/folder/a%20b.txt?q=1", "GET", 308, "https://files.example.com/folder/a%20b.txt?q=1"},
{"http://other.example/", "GET", 421, ""},
{"http://files.example.com/", "POST", 405, ""},
} {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(tc.method, tc.target, nil))
if w.Code != tc.status || w.Header().Get("Location") != tc.location {
t.Errorf("%s: status=%d location=%q", tc.target, w.Code, w.Header().Get("Location"))
}
}
}
// Exercise the embedding boundary after moving HTTP behavior out of the command.
func TestEmbeddedAssetsAndReservedNamespace(t *testing.T) {
h := Handler(filepath.Join(t.TempDir(), "unavailable-storage"))
for _, tc := range []struct{ name, contentType string }{
{"autoindex.css", "text/css; charset=utf-8"},
{"autoindex.js", "text/javascript; charset=utf-8"},
{"favicon.ico", "image/x-icon"},
{"favicon.png", "image/png"},
} {
for _, method := range []string{"GET", "HEAD"} {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest(method, "/_nais/"+tc.name, nil))
if w.Code != 200 || w.Header().Get("Content-Type") != tc.contentType {
t.Fatalf("%s %s: status=%d type=%q", method, tc.name, w.Code, w.Header().Get("Content-Type"))
}
if (method == "HEAD") != (w.Body.Len() == 0) {
t.Fatalf("%s %s: unexpected body length %d", method, tc.name, w.Body.Len())
}
if w.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatal("asset MIME protection missing")
}
}
}
for _, target := range []string{"/_nais/LICENSE", "/_nais/../secret", "/_nais/nested/autoindex.js"} {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", target, nil))
if w.Code != 404 {
t.Fatalf("reserved namespace exposed %s: %d", target, w.Code)
}
}
}
+49
View File
@@ -0,0 +1,49 @@
package web
import (
"fmt"
"html/template"
"net/url"
"strings"
)
type entry struct {
Name, Size, Modified string
Link template.URL
Dir bool
Inline bool
}
type page struct {
Path string
Parent template.URL
Entries []entry
Truncated bool
}
var listing = template.Must(template.New("listing").Parse(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Index of {{.Path}}</title><link rel="stylesheet" href="/_nais/autoindex.css"><link rel="icon" href="/_nais/favicon.ico"></head><body><h1><span>Index of {{.Path}}</span></h1><pre>{{if .Parent}}<a href="../">../</a>
{{end}}{{range .Entries}}<a href="{{.Link}}"{{if not .Dir}} data-file="true"{{if not .Inline}} download{{end}}{{end}}>{{.Name}}{{if .Dir}}/{{end}}</a> {{.Modified}} {{.Size}}
{{else}}This folder is empty.
{{end}}{{if .Truncated}}Only the first 5,000 entries are displayed.
{{end}}</pre><script src="/_nais/autoindex.js" defer></script></body></html>`))
func escapedPath(p string) template.URL {
parts := strings.Split(p, "/")
for i := range parts {
parts[i] = url.PathEscape(parts[i])
}
return template.URL(strings.Join(parts, "/"))
}
func sizeLabel(n int64) string {
if n < 1024 {
return fmt.Sprintf("%d B", n)
}
for _, u := range []struct {
n int64
s string
}{{1 << 30, "GiB"}, {1 << 20, "MiB"}, {1 << 10, "KiB"}} {
if n >= u.n {
return fmt.Sprintf("%.1f %s", float64(n)/float64(u.n), u.s)
}
}
return ""
}
+29
View File
@@ -0,0 +1,29 @@
package web
import (
"net"
"net/http"
"net/url"
"strings"
)
// RedirectHandler redirects allowed read requests to the configured HTTPS host.
func RedirectHandler(domain string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
host := r.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
if !strings.EqualFold(host, domain) {
http.Error(w, "Unknown host", http.StatusMisdirectedRequest)
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "Read-only service", 405)
return
}
target := url.URL{Scheme: "https", Host: domain, Path: r.URL.Path, RawPath: r.URL.RawPath, RawQuery: r.URL.RawQuery}
http.Redirect(w, r, target.String(), http.StatusPermanentRedirect)
})
}
+64
View File
@@ -0,0 +1,64 @@
package web
import (
"io"
"mime"
"net/http"
"os"
"path"
"strings"
)
// Static assets are identified explicitly; unrecognized files remain downloads.
func inlineType(name string) string {
switch strings.ToLower(path.Ext(name)) {
case ".html", ".htm":
return "text/html; charset=utf-8"
case ".css":
return "text/css; charset=utf-8"
case ".js", ".mjs":
return "text/javascript; charset=utf-8"
case ".json", ".map":
return "application/json"
case ".png":
return "image/png"
case ".jpg", ".jpeg":
return "image/jpeg"
case ".gif":
return "image/gif"
case ".webp":
return "image/webp"
case ".avif":
return "image/avif"
case ".svg":
return "image/svg+xml"
case ".ico":
return "image/x-icon"
case ".woff":
return "font/woff"
case ".woff2":
return "font/woff2"
case ".ttf":
return "font/ttf"
case ".otf":
return "font/otf"
case ".wasm":
return "application/wasm"
default:
return ""
}
}
func serveFile(w http.ResponseWriter, r *http.Request, name string, info os.FileInfo, f io.ReadSeeker) {
contentType := inlineType(name)
if contentType == "" {
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": info.Name()}))
} else {
w.Header().Set("Content-Type", contentType)
w.Header().Del("Content-Disposition")
// Published static pages may use inline scripts/styles and external assets.
// Directory listings retain their stricter policy; no server-side code runs.
w.Header().Set("Content-Security-Policy", "object-src 'none'; frame-ancestors 'none'; base-uri 'self'")
}
http.ServeContent(w, r, info.Name(), info.ModTime(), f)
}
+83
View File
@@ -0,0 +1,83 @@
package web
import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestStaticPagesAndAssets(t *testing.T) {
root := t.TempDir()
os.Mkdir(filepath.Join(root, "site"), 0700)
files := map[string]string{"site/index.html": "<h1>Home</h1>", "page.HTML": "<h1>Direct</h1>", "site/app.js": "console.log('ok')", "site/style.css": "h1{color:red}", "archive.zip": "archive", "script.php": "<?php echo 1;"}
for name, data := range files {
if err := os.WriteFile(filepath.Join(root, name), []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
h := Handler(root)
for _, tc := range []struct {
url, ctype, body string
code int
attachment bool
}{
{"/site/", "text/html; charset=utf-8", "<h1>Home</h1>", 200, false},
{"/site/index.html", "text/html; charset=utf-8", "<h1>Home</h1>", 200, false},
{"/page.HTML", "text/html; charset=utf-8", "<h1>Direct</h1>", 200, false},
{"/site/app.js", "text/javascript; charset=utf-8", "console.log('ok')", 200, false},
{"/site/style.css", "text/css; charset=utf-8", "h1{color:red}", 200, false},
{"/archive.zip", "application/octet-stream", "archive", 200, true},
{"/script.php", "application/octet-stream", "<?php echo 1;", 200, true},
} {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", tc.url, nil))
if w.Code != tc.code || w.Header().Get("Content-Type") != tc.ctype || w.Body.String() != tc.body {
t.Fatalf("%s: %d %s %q", tc.url, w.Code, w.Header().Get("Content-Type"), w.Body.String())
}
if strings.HasPrefix(w.Header().Get("Content-Disposition"), "attachment") != tc.attachment {
t.Fatalf("wrong disposition: %s", tc.url)
}
}
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/site?x=1", nil))
if w.Code != 301 || w.Header().Get("Location") != "/site/" {
t.Fatalf("bad directory redirect: %d", w.Code)
}
w = httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("HEAD", "/site/", nil))
if w.Code != 200 || w.Body.Len() != 0 {
t.Fatal("index HEAD failed")
}
w = httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
body := w.Body.String()
if strings.Contains(body, `href="/page.HTML" data-file="true" download`) || !strings.Contains(body, `href="/archive.zip" data-file="true" download`) {
t.Fatal("listing link download policy")
}
}
func TestEscapingIndexSymlinkAndRootIndex(t *testing.T) {
root := t.TempDir()
outside := filepath.Join(t.TempDir(), "secret.html")
os.WriteFile(outside, []byte("private page"), 0600)
os.Symlink(outside, filepath.Join(root, "index.html"))
h := Handler(root)
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if w.Code != 200 || strings.Contains(w.Body.String(), "private page") {
t.Fatal("outside index escaped root")
}
w = httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/index.html", nil))
if w.Code != 404 {
t.Fatal("direct escaping symlink allowed")
}
os.Remove(filepath.Join(root, "index.html"))
os.WriteFile(filepath.Join(root, "index.html"), []byte("<h1>Root index</h1>"), 0600)
w = httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
if w.Body.String() != "<h1>Root index</h1>" {
t.Fatal("root index not served")
}
}