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

-104
View File
@@ -1,126 +1,22 @@
// routershelf-smb is an independent private file service. It never changes
// firewall, routing, firmware settings, or the web service.
package main
import (
"bufio"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"runtime"
"runtime/debug"
"strings"
"syscall"
"time"
smb "routershelf/internal/smbwire"
)
func mounted(path string) bool {
if runtime.GOOS != "linux" {
return true
}
f, err := os.Open("/proc/mounts")
if err != nil {
return false
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
v := strings.Fields(sc.Text())
if len(v) > 1 {
p := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(v[1])
if p == path {
return true
}
}
}
return false
}
func drop(c config) error {
if os.Geteuid() != 0 {
if os.Geteuid() != c.UID || os.Getegid() != c.GID {
return errors.New("run as configured uid/gid or start as root to bind and drop privileges")
}
return nil
}
if err := syscall.Setgroups([]int{}); err != nil {
return err
}
if err := syscall.Setgid(c.GID); err != nil {
return err
}
return syscall.Setuid(c.UID)
}
func serve(ctx context.Context, c config) error {
if !mounted(c.Mount) {
return errors.New("expected USB mount is unavailable; refusing underlying mount directory")
}
initial, err := os.Stat(c.Root)
if err != nil {
return errors.New("share unavailable")
}
ln, err := net.Listen("tcp4", c.Listen)
if err != nil {
return errors.New("cannot bind SMB listener; check address, privileges and existing SMB services")
}
defer ln.Close()
if err := drop(c); err != nil {
return fmt.Errorf("cannot drop SMB privileges: %w", err)
}
// Confirm the dropped account can read this directory before announcing ready.
d, err := os.Open(c.Root)
if err != nil {
return errors.New("share is unreadable by configured account")
}
_, err = d.Readdirnames(1)
d.Close()
if err != nil && err != io.EOF {
return errors.New("share cannot be listed")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
lost := make(chan struct{})
go func() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
current, err := os.Stat(c.Root)
if err != nil || !os.SameFile(initial, current) || !mounted(c.Mount) {
close(lost)
cancel()
return
}
}
}
}()
var diagnostic func(string, ...any)
if c.Diagnostics {
diagnostic = log.Printf
}
err = smb.Serve(ctx, ln, smb.Config{ProtectedPaths: c.protectedRelative, ExpectedRoot: initial, Ready: func() {
log.Print("SMB ready; authenticated signing required; read_only=", c.ReadOnly)
if c.ready != nil {
c.ready()
}
}, Logf: diagnostic, Root: c.Root, Share: c.Share, User: c.User, NTHash: c.ntHash, Allow: c.prefixes, ReadOnly: c.ReadOnly, DiskMetadata: true, CaseInsensitive: c.CaseInsensitive})
select {
case <-lost:
return errors.New("USB storage disappeared or changed; sessions closed; reconnect after storage recovers")
default:
return err
}
}
func run() error {
if len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help" || os.Args[1] == "-help") {
fmt.Println("RouterShelf SMB (experimental)\nUsage: routershelf-smb -config /absolute/private/smb.json [-check-config]\n routershelf-smb -hash-password < password-from-hidden-prompt\nRS_SMB_CONFIG supplies the default config path. No web configuration is required.\nSee docs/smb.md for Finder setup, permissions, updates and recovery.")
+91
View File
@@ -0,0 +1,91 @@
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"time"
smb "routershelf/internal/smbwire"
)
func serve(ctx context.Context, c config) error {
if !mounted(c.Mount) {
return errors.New("expected USB mount is unavailable; refusing underlying mount directory")
}
initial, err := os.Stat(c.Root)
if err != nil {
return errors.New("share unavailable")
}
ln, err := net.Listen("tcp4", c.Listen)
if err != nil {
return errors.New("cannot bind SMB listener; check address, privileges and existing SMB services")
}
defer ln.Close()
if err := drop(c); err != nil {
return fmt.Errorf("cannot drop SMB privileges: %w", err)
}
// Confirm the dropped account can read this directory before announcing ready.
d, err := os.Open(c.Root)
if err != nil {
return errors.New("share is unreadable by configured account")
}
_, err = d.Readdirnames(1)
d.Close()
if err != nil && err != io.EOF {
return errors.New("share cannot be listed")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
lost := make(chan struct{})
go func() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
current, err := os.Stat(c.Root)
if err != nil || !os.SameFile(initial, current) || !mounted(c.Mount) {
close(lost)
cancel()
return
}
}
}
}()
var diagnostic func(string, ...any)
if c.Diagnostics {
diagnostic = log.Printf
}
err = smb.Serve(ctx, ln, smb.Config{
ProtectedPaths: c.protectedRelative,
ExpectedRoot: initial,
Ready: func() {
log.Print("SMB ready; authenticated signing required; read_only=", c.ReadOnly)
if c.ready != nil {
c.ready()
}
},
Logf: diagnostic,
Root: c.Root,
Share: c.Share,
User: c.User,
NTHash: c.ntHash,
Allow: c.prefixes,
ReadOnly: c.ReadOnly,
DiskMetadata: true,
CaseInsensitive: c.CaseInsensitive,
})
select {
case <-lost:
return errors.New("USB storage disappeared or changed; sessions closed; reconnect after storage recovers")
default:
return err
}
}
+47
View File
@@ -0,0 +1,47 @@
package main
import (
"bufio"
"errors"
"os"
"runtime"
"strings"
"syscall"
)
func mounted(path string) bool {
if runtime.GOOS != "linux" {
return true
}
f, err := os.Open("/proc/mounts")
if err != nil {
return false
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
v := strings.Fields(sc.Text())
if len(v) > 1 {
p := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(v[1])
if p == path {
return true
}
}
}
return false
}
func drop(c config) error {
if os.Geteuid() != 0 {
if os.Geteuid() != c.UID || os.Getegid() != c.GID {
return errors.New("run as configured uid/gid or start as root to bind and drop privileges")
}
return nil
}
if err := syscall.Setgroups([]int{}); err != nil {
return err
}
if err := syscall.Setgid(c.GID); err != nil {
return err
}
return syscall.Setuid(c.UID)
}
+27
View File
@@ -0,0 +1,27 @@
package main
import (
"net"
"sync"
)
type boundedListener struct {
net.Listener
slots chan struct{}
}
type boundedConn struct {
net.Conn
release func()
once sync.Once
}
func (c *boundedConn) Close() error { err := c.Conn.Close(); c.once.Do(c.release); return err }
func (l *boundedListener) Accept() (net.Conn, error) {
l.slots <- struct{}{}
c, e := l.Listener.Accept()
if e != nil {
<-l.slots
return nil, e
}
return &boundedConn{Conn: c, release: func() { <-l.slots }}, nil
}
+43 -300
View File
@@ -1,338 +1,81 @@
package main
import (
"bytes"
"crypto/tls"
"fmt"
"html/template"
"io"
"log"
"mime"
"net"
"net/http"
"net/url"
"os"
"path"
"sort"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/crypto/acme/autocert"
"routershelf/internal/theme"
"routershelf/internal/web"
)
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 ""
}
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)
})
}
type boundedListener struct {
net.Listener
slots chan struct{}
}
type boundedConn struct {
net.Conn
release func()
once sync.Once
}
func (c *boundedConn) Close() error { err := c.Conn.Close(); c.once.Do(c.release); return err }
func (l *boundedListener) Accept() (net.Conn, error) {
l.slots <- struct{}{}
c, e := l.Listener.Accept()
if e != nil {
<-l.slots
return nil, e
}
return &boundedConn{Conn: c, release: func() { <-l.slots }}, nil
}
func main() {
cfg, err := parseConfig(os.Args[1:])
if err != nil {
log.Fatal(err)
}
root, addr, domain, httpAddr, cache, drop := &cfg.root, &cfg.listen, &cfg.domain, &cfg.httpListen, &cfg.certCache, &cfg.drop
r, e := os.OpenRoot(*root)
if e != nil {
root, err := os.OpenRoot(cfg.root)
if err != nil {
log.Fatal("public directory unavailable")
}
r.Close()
if *drop {
if e = syscall.Setgroups([]int{}); e != nil {
log.Fatal(e)
root.Close()
if cfg.drop {
if err = syscall.Setgroups([]int{}); err != nil {
log.Fatal(err)
}
if e = syscall.Setgid(65534); e != nil {
log.Fatal(e)
if err = syscall.Setgid(65534); err != nil {
log.Fatal(err)
}
if e = syscall.Setuid(65534); e != nil {
log.Fatal(e)
if err = syscall.Setuid(65534); err != nil {
log.Fatal(err)
}
}
l, e := net.Listen("tcp4", *addr)
if e != nil {
log.Fatal(e)
listener, err := net.Listen("tcp4", cfg.listen)
if err != nil {
log.Fatal(err)
}
contentHandler := handler(*root)
contentHandler := web.Handler(cfg.root)
var manager *autocert.Manager
if *domain != "" {
if *cache == "" {
if cfg.domain != "" {
if cfg.certCache == "" {
log.Fatal("-cert-cache is required for HTTPS")
}
manager = &autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(*domain), Cache: autocert.DirCache(*cache)}
redirect := redirectHandler(*domain)
hl, err := net.Listen("tcp4", *httpAddr)
manager = &autocert.Manager{Prompt: autocert.AcceptTOS, HostPolicy: autocert.HostWhitelist(cfg.domain), Cache: autocert.DirCache(cfg.certCache)}
redirect := web.RedirectHandler(cfg.domain)
httpListener, err := net.Listen("tcp4", cfg.httpListen)
if err != nil {
log.Fatal(err)
}
hs := &http.Server{Handler: manager.HTTPHandler(redirect), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 15 * time.Second, MaxHeaderBytes: 16 * 1024}
go func() { log.Fatal(hs.Serve(&boundedListener{hl, make(chan struct{}, 16)})) }()
challengeServer := &http.Server{
Handler: manager.HTTPHandler(redirect),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 15 * time.Second,
MaxHeaderBytes: 16 * 1024,
}
go func() { log.Fatal(challengeServer.Serve(&boundedListener{httpListener, make(chan struct{}, 16)})) }()
}
s := &http.Server{Handler: contentHandler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Minute, IdleTimeout: 15 * time.Second, MaxHeaderBytes: 16 * 1024}
log.Printf("Read-only public directory listening on %s (domain=%s)", *addr, *domain)
server := &http.Server{
Handler: contentHandler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Minute,
IdleTimeout: 15 * time.Second,
MaxHeaderBytes: 16 * 1024,
}
log.Printf("Read-only public directory listening on %s (domain=%s)", cfg.listen, cfg.domain)
if manager != nil {
s.TLSConfig = manager.TLSConfig()
s.TLSConfig.MinVersion = tls.VersionTLS12
server.TLSConfig = manager.TLSConfig()
server.TLSConfig.MinVersion = tls.VersionTLS12
// HTTP/1.1 plus ACME ALPN; bound connections remain effective for all clients.
s.TLSConfig.NextProtos = []string{"http/1.1", "acme-tls/1"}
log.Fatal(s.ServeTLS(&boundedListener{l, make(chan struct{}, 32)}, "", ""))
server.TLSConfig.NextProtos = []string{"http/1.1", "acme-tls/1"}
log.Fatal(server.ServeTLS(&boundedListener{listener, make(chan struct{}, 32)}, "", ""))
}
log.Fatal(s.Serve(&boundedListener{l, make(chan struct{}, 32)}))
}
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)
})
}
// 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)
log.Fatal(server.Serve(&boundedListener{listener, make(chan struct{}, 32)}))
}
-73
View File
@@ -1,73 +0,0 @@
package main
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"))
}
}
}
-83
View File
@@ -1,83 +0,0 @@
package main
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")
}
}