init
This commit is contained in:
43 files changed
+2583
No files matched your search
@@ -0,0 +1,109 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type config struct {
|
||||
root, listen, domain, httpListen, certCache string
|
||||
drop bool
|
||||
}
|
||||
|
||||
func envDefault(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
// Flags override the environment. The launcher loads the private .env file;
|
||||
// the binary itself does not execute shell configuration files.
|
||||
func parseConfig(args []string) (config, error) {
|
||||
c := config{}
|
||||
mount := os.Getenv("RS_USB_MOUNT")
|
||||
root := os.Getenv("RS_ROOT")
|
||||
cache := os.Getenv("RS_CERT_CACHE")
|
||||
if mount != "" {
|
||||
if root == "" {
|
||||
root = filepath.Join(mount, envDefault("RS_PUBLIC_SUBDIR", "public-storage"))
|
||||
}
|
||||
if cache == "" {
|
||||
cache = filepath.Join(mount, envDefault("RS_SERVICE_SUBDIR", ".public-share-service"), "certificates")
|
||||
}
|
||||
}
|
||||
drop := false
|
||||
if raw := os.Getenv("RS_DROP_PRIVILEGES"); raw != "" {
|
||||
var err error
|
||||
drop, err = strconv.ParseBool(raw)
|
||||
if err != nil {
|
||||
return c, fmt.Errorf("RS_DROP_PRIVILEGES must be a boolean")
|
||||
}
|
||||
}
|
||||
ip := envDefault("RS_LAN_IP", "127.0.0.1")
|
||||
httpsPort := envDefault("RS_HTTPS_PORT", "8888")
|
||||
httpPort := envDefault("RS_HTTP_PORT", "10080")
|
||||
fs := flag.NewFlagSet("routershelf", flag.ContinueOnError)
|
||||
fs.SetOutput(io.Discard)
|
||||
fs.StringVar(&c.root, "root", root, "Shared directory (RS_ROOT or RS_USB_MOUNT)")
|
||||
fs.StringVar(&c.listen, "listen", net.JoinHostPort(ip, httpsPort), "Listener (RS_LAN_IP, RS_HTTPS_PORT)")
|
||||
fs.StringVar(&c.domain, "domain", os.Getenv("RS_DOMAIN"), "HTTPS domain (RS_DOMAIN)")
|
||||
fs.StringVar(&c.httpListen, "http-listen", net.JoinHostPort(ip, httpPort), "ACME HTTP listener (RS_HTTP_PORT)")
|
||||
fs.StringVar(&c.certCache, "cert-cache", cache, "Persistent private cache (RS_CERT_CACHE)")
|
||||
fs.BoolVar(&c.drop, "drop-privileges", drop, "Drop to uid/gid 65534 (RS_DROP_PRIVILEGES)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if len(fs.Args()) != 0 {
|
||||
return c, fmt.Errorf("unexpected positional arguments")
|
||||
}
|
||||
if c.root == "" {
|
||||
return c, fmt.Errorf("set RS_ROOT / RS_USB_MOUNT or -root")
|
||||
}
|
||||
for _, addr := range []string{c.listen, c.httpListen} {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil || net.ParseIP(host) == nil {
|
||||
return c, fmt.Errorf("listeners must use numeric IP:port")
|
||||
}
|
||||
n, err := strconv.Atoi(port)
|
||||
if err != nil || n < 1 || n > 65535 {
|
||||
return c, fmt.Errorf("invalid listener port")
|
||||
}
|
||||
if c.drop && n < 1024 {
|
||||
return c, fmt.Errorf("privilege drop requires internal ports >=1024")
|
||||
}
|
||||
}
|
||||
if c.domain != "" {
|
||||
if c.certCache == "" {
|
||||
return c, fmt.Errorf("HTTPS requires RS_CERT_CACHE / RS_USB_MOUNT or -cert-cache")
|
||||
}
|
||||
if c.listen == c.httpListen {
|
||||
return c, fmt.Errorf("HTTP and HTTPS listeners must differ")
|
||||
}
|
||||
if strings.ContainsAny(c.domain, "/: \t\r\n") {
|
||||
return c, fmt.Errorf("domain must be a hostname without scheme or port")
|
||||
}
|
||||
r, err := filepath.Abs(c.root)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
p, err := filepath.Abs(c.certCache)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
rel, err := filepath.Rel(r, p)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
if rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))) {
|
||||
return c, fmt.Errorf("certificate cache must be outside shared root")
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func clearConfigEnv(t *testing.T) {
|
||||
t.Helper()
|
||||
for _, key := range []string{"RS_USB_MOUNT", "RS_ROOT", "RS_CERT_CACHE", "RS_PUBLIC_SUBDIR", "RS_SERVICE_SUBDIR", "RS_DROP_PRIVILEGES", "RS_LAN_IP", "RS_HTTPS_PORT", "RS_HTTP_PORT", "RS_DOMAIN"} {
|
||||
t.Setenv(key, "")
|
||||
}
|
||||
}
|
||||
func TestEnvConfigurationAndOverrides(t *testing.T) {
|
||||
clearConfigEnv(t)
|
||||
t.Setenv("RS_USB_MOUNT", "/media/example")
|
||||
t.Setenv("RS_DOMAIN", "files.example.com")
|
||||
t.Setenv("RS_LAN_IP", "192.0.2.1")
|
||||
t.Setenv("RS_HTTPS_PORT", "10443")
|
||||
t.Setenv("RS_HTTP_PORT", "10080")
|
||||
t.Setenv("RS_DROP_PRIVILEGES", "true")
|
||||
c, err := parseConfig(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.root != "/media/example/public-storage" || c.certCache != "/media/example/.public-share-service/certificates" || c.listen != "192.0.2.1:10443" || !c.drop {
|
||||
t.Fatalf("incorrect derived configuration: %+v", c)
|
||||
}
|
||||
c, err = parseConfig([]string{"-listen", "127.0.0.1:9443", "-domain", "other.example.com"})
|
||||
if err != nil || c.listen != "127.0.0.1:9443" || c.domain != "other.example.com" {
|
||||
t.Fatalf("flags did not override env: %+v %v", c, err)
|
||||
}
|
||||
}
|
||||
func TestRejectUnsafeConfiguration(t *testing.T) {
|
||||
for _, tc := range []struct{ key, value string }{
|
||||
{"RS_HTTPS_PORT", "0"}, {"RS_DROP_PRIVILEGES", "perhaps"}, {"RS_DOMAIN", "https://files.example.com"}, {"RS_CERT_CACHE", "/media/example/public-storage/keys"},
|
||||
} {
|
||||
t.Run(tc.key, func(t *testing.T) {
|
||||
clearConfigEnv(t)
|
||||
t.Setenv("RS_USB_MOUNT", "/media/example")
|
||||
t.Setenv("RS_DOMAIN", "files.example.com")
|
||||
t.Setenv(tc.key, tc.value)
|
||||
if _, err := parseConfig(nil); err == nil {
|
||||
t.Fatal("unsafe config accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
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"
|
||||
)
|
||||
|
||||
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 {
|
||||
log.Fatal("public directory unavailable")
|
||||
}
|
||||
r.Close()
|
||||
if *drop {
|
||||
if e = syscall.Setgroups([]int{}); e != nil {
|
||||
log.Fatal(e)
|
||||
}
|
||||
if e = syscall.Setgid(65534); e != nil {
|
||||
log.Fatal(e)
|
||||
}
|
||||
if e = syscall.Setuid(65534); e != nil {
|
||||
log.Fatal(e)
|
||||
}
|
||||
}
|
||||
l, e := net.Listen("tcp4", *addr)
|
||||
if e != nil {
|
||||
log.Fatal(e)
|
||||
}
|
||||
contentHandler := handler(*root)
|
||||
var manager *autocert.Manager
|
||||
if *domain != "" {
|
||||
if *cache == "" {
|
||||
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)
|
||||
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)})) }()
|
||||
}
|
||||
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)
|
||||
if manager != nil {
|
||||
s.TLSConfig = manager.TLSConfig()
|
||||
s.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)}, "", ""))
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
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(), "<&.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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user