package httpapi
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/fstest"
)
const indexHTML = `
Sonda app`
// 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("")},
"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)
}
}
}
// ---- the app can be installed ----
func TestTheManifestAndTheServiceWorkerAreServedWithTheirTypeAndAskedAgain(t *testing.T) {
app := theApp()
app["manifest.webmanifest"] = &fstest.MapFile{Data: []byte(`{"name":"Sonda"}`)}
app["sw.js"] = &fstest.MapFile{Data: []byte("self.addEventListener('fetch', () => {})")}
for path, wantType := range map[string]string{
"/manifest.webmanifest": "application/manifest+json",
"/sw.js": "text/javascript",
} {
rec := serve(t, app, http.MethodGet, path)
if rec.Code != http.StatusOK {
t.Errorf("%s: status %d", path, rec.Code)
continue
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, wantType) {
t.Errorf("%s: Content-Type %q, want %s", path, ct, wantType)
}
// A new version of the worker or of the manifest must be seen at once: they are asked again every time.
if got := rec.Header().Get("Cache-Control"); got != "no-cache" {
t.Errorf("%s: Cache-Control %q, want no-cache", path, got)
}
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Errorf("%s: no nosniff", path)
}
}
}
func TestThePolicyOfTheAppLetsItRunItsOwnWorkerAndNothingElse(t *testing.T) {
rec := serve(t, theApp(), http.MethodGet, "/")
policy := rec.Header().Get("Content-Security-Policy")
// Workers and the manifest fall back to the sources of scripts and of everything else: the server itself.
for _, want := range []string{"default-src 'self'", "script-src 'self'", "connect-src 'self'"} {
if !strings.Contains(policy, want) {
t.Errorf("policy %q lacks %q", policy, want)
}
}
for _, never := range []string{"worker-src *", "worker-src http", "unsafe-eval", "script-src *"} {
if strings.Contains(policy, never) {
t.Errorf("policy %q has %q", policy, never)
}
}
if strings.Contains(policy, "worker-src") || strings.Contains(policy, "manifest-src") {
t.Errorf("policy %q names worker-src or manifest-src: they must follow default-src", policy)
}
}