sonda/internal/api/http/web_test.go
tgiachi 7acac73dd0 feat(api): serve the web app on / and for its own links, with a strict policy
A GET or HEAD outside /api is a file of the app, or its page for a link inside it (/admin/users). A file that is missing (under assets/ or with an extension) answers 404, never the page, so a missing script is not run as HTML; hidden files and folders are never served; everything else, and any unknown /api address, keeps the JSON 404. The page gets a Content-Security-Policy that allows only its own server (no address, no wildcard, no inline script), nosniff, DENY and no referrer. Hashed assets are cached for good and the page is asked again. With no app in the binary, / says how to build it. The app is an optional dependency, so existing wiring is unchanged.
2026-11-12 15:56:33 +01:00

236 lines
9.1 KiB
Go

package httpapi
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
)
const indexHTML = `<!doctype html><title>Sonda app</title><script type="module" src="/assets/app-abc123.js"></script>`
// theApp is a small built web app: a page, hashed assets, a top-level file, and files that must never be served.
func theApp() fstest.MapFS {
return fstest.MapFS{
"index.html": {Data: []byte(indexHTML)},
"favicon.svg": {Data: []byte("<svg xmlns='http://www.w3.org/2000/svg'/>")},
"assets/app-abc123.js": {Data: []byte("console.log('app')")},
"assets/app-abc123.css": {Data: []byte("body{margin:0}")},
"assets/font-1.woff2": {Data: []byte("font")},
"assets/.hidden": {Data: []byte("secret")},
".gitkeep": {Data: []byte("")},
}
}
func serve(t *testing.T, app fstest.MapFS, method, path string) *httptest.ResponseRecorder {
t.Helper()
h, _ := newTestEnv(t, func(d *Deps) {
if app != nil {
d.Web = app
}
})
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(method, path, nil))
return rec
}
func TestRootServesTheAppWithItsHeaders(t *testing.T) {
rec := serve(t, theApp(), http.MethodGet, "/")
if rec.Code != http.StatusOK {
t.Fatalf("status %d, want 200", rec.Code)
}
if rec.Body.String() != indexHTML {
t.Errorf("body %q is not the page of the app", rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
t.Errorf("Content-Type %q, want text/html", ct)
}
if got := rec.Header().Get("Cache-Control"); got != "no-cache" {
t.Errorf("Cache-Control %q: the page must be asked again, so that an update shows at once", got)
}
for header, want := range map[string]string{
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
} {
if got := rec.Header().Get(header); got != want {
t.Errorf("%s = %q, want %q", header, got, want)
}
}
csp := rec.Header().Get("Content-Security-Policy")
for _, directive := range []string{
"default-src 'self'", "script-src 'self'", "connect-src 'self'", "img-src 'self' data: blob:",
"media-src 'self' blob:", "font-src 'self'", "object-src 'none'", "frame-ancestors 'none'",
"base-uri 'self'", "form-action 'self'", "style-src 'self'", "style-src-attr 'unsafe-inline'",
} {
if !strings.Contains(csp, directive) {
t.Errorf("the policy %q lacks %q", csp, directive)
}
}
// Nothing in the policy may let the page reach another server.
if strings.Contains(csp, "http:") || strings.Contains(csp, "https:") || strings.Contains(csp, "*") {
t.Errorf("the policy %q allows resources from outside", csp)
}
if strings.Contains(csp, "script-src 'self' 'unsafe") || strings.Contains(csp, "'unsafe-eval'") {
t.Errorf("the policy %q allows inline or eval scripts", csp)
}
}
func TestDirectLinksOfTheAppServeThePage(t *testing.T) {
for _, path := range []string{"/admin/users", "/artists/5", "/search?q=bjork", "/settings"} {
rec := serve(t, theApp(), http.MethodGet, path)
if rec.Code != http.StatusOK || rec.Body.String() != indexHTML {
t.Errorf("GET %s: status %d, body %q; want the page of the app", path, rec.Code, rec.Body.String())
}
if rec.Header().Get("Content-Security-Policy") == "" {
t.Errorf("GET %s: no policy", path)
}
}
}
func TestAssetsAreServedWithTheirTypeAndForever(t *testing.T) {
cases := map[string]string{
"/assets/app-abc123.js": "javascript",
"/assets/app-abc123.css": "text/css",
"/assets/font-1.woff2": "font/woff2",
}
for path, wantType := range cases {
rec := serve(t, theApp(), http.MethodGet, path)
if rec.Code != http.StatusOK {
t.Errorf("GET %s: status %d, want 200", path, rec.Code)
continue
}
if ct := rec.Header().Get("Content-Type"); !strings.Contains(ct, wantType) {
t.Errorf("GET %s: Content-Type %q, want %q", path, ct, wantType)
}
if got := rec.Header().Get("Cache-Control"); got != "public, max-age=31536000, immutable" {
t.Errorf("GET %s: Cache-Control %q: a file with a hash in its name never changes", path, got)
}
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Errorf("GET %s: no nosniff", path)
}
}
}
func TestATopLevelFileIsServedButAskedAgain(t *testing.T) {
rec := serve(t, theApp(), http.MethodGet, "/favicon.svg")
if rec.Code != http.StatusOK || !strings.Contains(rec.Header().Get("Content-Type"), "svg") {
t.Fatalf("status %d, type %q; want the icon", rec.Code, rec.Header().Get("Content-Type"))
}
if got := rec.Header().Get("Cache-Control"); got != "no-cache" {
t.Errorf("Cache-Control %q: a file with no hash in its name may change", got)
}
}
// A script that is missing must never come back as the HTML page: the browser would try to run it.
func TestAMissingFileIsA404NotThePage(t *testing.T) {
for _, path := range []string{"/assets/nope.js", "/assets/", "/assets", "/missing.js", "/some/deep/missing.css", "/robots.txt"} {
rec := serve(t, theApp(), http.MethodGet, path)
if rec.Code != http.StatusNotFound {
t.Errorf("GET %s: status %d, want 404", path, rec.Code)
}
if strings.Contains(rec.Body.String(), "Sonda app") {
t.Errorf("GET %s: answered with the page of the app", path)
}
}
}
func TestHiddenFilesAreNeverServed(t *testing.T) {
for _, path := range []string{"/.gitkeep", "/assets/.hidden", "/.env", "/assets/../.gitkeep"} {
rec := serve(t, theApp(), http.MethodGet, path)
if rec.Code == http.StatusOK && rec.Body.String() != indexHTML {
t.Errorf("GET %s: served %q", path, rec.Body.String())
}
if strings.Contains(rec.Body.String(), "secret") {
t.Errorf("GET %s: leaked a hidden file", path)
}
}
if rec := serve(t, theApp(), http.MethodGet, "/assets/.hidden"); rec.Code != http.StatusNotFound {
t.Errorf("a hidden file under assets: status %d, want 404", rec.Code)
}
}
func TestHeadWorksAndSendsNoBody(t *testing.T) {
rec := serve(t, theApp(), http.MethodHead, "/")
if rec.Code != http.StatusOK || rec.Body.Len() != 0 {
t.Errorf("HEAD /: status %d with %d bytes", rec.Code, rec.Body.Len())
}
if rec := serve(t, theApp(), http.MethodHead, "/assets/app-abc123.js"); rec.Code != http.StatusOK {
t.Errorf("HEAD of an asset: status %d", rec.Code)
}
}
func TestOtherMethodsOutsideTheAPIAreAJSON404(t *testing.T) {
for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodPatch} {
rec := serve(t, theApp(), method, "/admin/users")
if rec.Code != http.StatusNotFound {
t.Errorf("%s /admin/users: status %d, want 404", method, rec.Code)
}
if !strings.Contains(rec.Body.String(), `"code":"not_found"`) {
t.Errorf("%s /admin/users: body %q, want the JSON error", method, rec.Body.String())
}
}
}
// The API keeps answering as it did: an unknown address under /api is a JSON 404, never the page.
func TestUnknownAPIAddressesStayJSON404(t *testing.T) {
for _, path := range []string{"/api/v1/not-there", "/api/nothing", "/api"} {
rec := serve(t, theApp(), http.MethodGet, path)
if rec.Code != http.StatusNotFound {
t.Errorf("GET %s: status %d, want 404", path, rec.Code)
}
if !strings.Contains(rec.Body.String(), `"code":"not_found"`) || strings.Contains(rec.Body.String(), "Sonda app") {
t.Errorf("GET %s: body %q, want the JSON error", path, rec.Body.String())
}
}
}
func TestTheAPIAndItsDocsAreNotAffected(t *testing.T) {
if rec := serve(t, theApp(), http.MethodGet, "/api/v1/health"); rec.Code != http.StatusOK {
t.Errorf("health: status %d", rec.Code)
}
rec := serve(t, theApp(), http.MethodGet, "/api/docs/")
if rec.Code != http.StatusOK {
t.Fatalf("docs: status %d", rec.Code)
}
if strings.Contains(rec.Header().Get("Content-Security-Policy"), "default-src") {
t.Errorf("the docs page got the policy of the app: %q", rec.Header().Get("Content-Security-Policy"))
}
}
func TestPathsThatTryToLeaveTheAppDoNotBreakAnything(t *testing.T) {
for _, path := range []string{"/..%2f..%2fetc%2fpasswd", "/%2e%2e/%2e%2e/etc/passwd", "/assets/..%2f..%2fgo.mod", "/%00"} {
rec := serve(t, theApp(), http.MethodGet, path)
if rec.Code >= 500 {
t.Errorf("GET %s: status %d", path, rec.Code)
}
if strings.Contains(rec.Body.String(), "root:") || strings.Contains(rec.Body.String(), "module codeberg.org") {
t.Errorf("GET %s: left the app", path)
}
}
}
// With no app in the binary (a build without the webui tag) / says how to build it, and the API works.
func TestWithNoAppTheRootSaysHowToBuildIt(t *testing.T) {
for name, app := range map[string]fstest.MapFS{"nil": nil, "empty": {}} {
for _, path := range []string{"/", "/admin/users"} {
rec := serve(t, app, http.MethodGet, path)
if rec.Code != http.StatusOK {
t.Errorf("%s FS, GET %s: status %d, want 200", name, path, rec.Code)
}
body := rec.Body.String()
for _, want := range []string{"make build", "/api/docs/", "/api/v1"} {
if !strings.Contains(body, want) {
t.Errorf("%s FS, GET %s: the page does not mention %q", name, path, want)
}
}
if !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/html") {
t.Errorf("%s FS: Content-Type %q", name, rec.Header().Get("Content-Type"))
}
}
if rec := serve(t, app, http.MethodGet, "/api/v1/health"); rec.Code != http.StatusOK {
t.Errorf("%s FS: the API does not work, status %d", name, rec.Code)
}
}
}